blob: 6ef457055250c0db9332c1e4eb20468745a61254 [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.
61struct WasmFunctionType {
62 // Support empty and tombstone instances, needed by DenseMap.
63 enum { Plain, Empty, Tombstone } State;
64
65 // The return types of the function.
66 SmallVector<wasm::ValType, 1> Returns;
67
68 // The parameter types of the function.
69 SmallVector<wasm::ValType, 4> Params;
70
71 WasmFunctionType() : State(Plain) {}
72
73 bool operator==(const WasmFunctionType &Other) const {
74 return State == Other.State && Returns == Other.Returns &&
75 Params == Other.Params;
76 }
77};
78
79// Traits for using WasmFunctionType in a DenseMap.
80struct WasmFunctionTypeDenseMapInfo {
81 static WasmFunctionType getEmptyKey() {
82 WasmFunctionType FuncTy;
83 FuncTy.State = WasmFunctionType::Empty;
84 return FuncTy;
85 }
86 static WasmFunctionType getTombstoneKey() {
87 WasmFunctionType FuncTy;
88 FuncTy.State = WasmFunctionType::Tombstone;
89 return FuncTy;
90 }
91 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
92 uintptr_t Value = FuncTy.State;
93 for (wasm::ValType Ret : FuncTy.Returns)
94 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
95 for (wasm::ValType Param : FuncTy.Params)
96 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
97 return Value;
98 }
99 static bool isEqual(const WasmFunctionType &LHS,
100 const WasmFunctionType &RHS) {
101 return LHS == RHS;
102 }
103};
104
Sam Clegg7c395942017-09-14 23:07:53 +0000105// A wasm data segment. A wasm binary contains only a single data section
106// but that can contain many segments, each with their own virtual location
107// in memory. Each MCSection data created by llvm is modeled as its own
108// wasm data segment.
109struct WasmDataSegment {
110 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000111 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000112 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000113 uint32_t Alignment;
114 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000115 SmallVector<char, 4> Data;
116};
117
Sam Clegg9e15f352017-06-03 02:01:24 +0000118// A wasm function to be written into the function section.
119struct WasmFunction {
120 int32_t Type;
121 const MCSymbolWasm *Sym;
122};
123
Sam Clegg9e15f352017-06-03 02:01:24 +0000124// A wasm global to be written into the global section.
125struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000126 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000127 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000128};
129
Sam Cleggea7cace2018-01-09 23:43:14 +0000130// Information about a single item which is part of a COMDAT. For each data
131// segment or function which is in the COMDAT, there is a corresponding
132// WasmComdatEntry.
133struct WasmComdatEntry {
134 unsigned Kind;
135 uint32_t Index;
136};
137
Sam Clegg6dc65e92017-06-06 16:38:59 +0000138// Information about a single relocation.
139struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000140 uint64_t Offset; // Where is the relocation.
141 const MCSymbolWasm *Symbol; // The symbol to relocate with.
142 int64_t Addend; // A value to add to the symbol.
143 unsigned Type; // The type of the relocation.
144 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000145
146 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
147 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000148 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000149 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
150 FixupSection(FixupSection) {}
151
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000152 bool hasAddend() const {
153 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000154 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000157 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
158 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000159 return true;
160 default:
161 return false;
162 }
163 }
164
Sam Clegg6dc65e92017-06-06 16:38:59 +0000165 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000166 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000167 << ", Type=" << Type
168 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000169 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000170
Aaron Ballman615eb472017-10-15 14:32:27 +0000171#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000172 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000174};
175
Sam Cleggcfd44a22018-04-05 17:01:39 +0000176struct WasmCustomSection {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000177 const uint32_t INVALID_INDEX = -1;
Sam Cleggcfd44a22018-04-05 17:01:39 +0000178
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000179 StringRef Name;
180 MCSectionWasm *Section;
181
182 uint32_t OutputContentsOffset;
183 uint32_t OutputIndex;
184
185 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
186 : Name(Name), Section(Section), OutputContentsOffset(0),
187 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000188};
189
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000190#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000191raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000192 Rel.print(OS);
193 return OS;
194}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000195#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000196
Dan Gohman18eafb62017-02-22 01:23:18 +0000197class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000198 /// The target specific Wasm writer instance.
199 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
200
Dan Gohmand934cb82017-02-24 23:18:00 +0000201 // Relocations for fixing up references in the code section.
202 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000203 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000204
205 // Relocations for fixing up references in the data section.
206 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000207 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000208
Dan Gohmand934cb82017-02-24 23:18:00 +0000209 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000210 // Maps function symbols to the index of the type of the function
211 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000212 // Maps function symbols to the table element index space. Used
213 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000214 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000215 // Maps function/global symbols to the (shared) Symbol index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000216 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000217 // Maps function/global symbols to the function/global Wasm index space.
218 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
219 // Maps data symbols to the Wasm segment and offset/size with the segment.
220 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000221 // Maps section symbols to the section.
222 DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols;
223
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
231 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
232 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000233 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000234 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000235 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000236 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000237 unsigned NumGlobalImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000238 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000239
Dan Gohman18eafb62017-02-22 01:23:18 +0000240 // TargetObjectWriter wrappers.
241 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000242 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
243 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000244 }
245
Sam Clegg2322a932018-04-23 19:16:19 +0000246 void startSection(SectionBookkeeping &Section, unsigned SectionId);
247 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000248 void endSection(SectionBookkeeping &Section);
249
Dan Gohman18eafb62017-02-22 01:23:18 +0000250public:
Lang Hames1301a872017-10-10 01:15:10 +0000251 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
252 raw_pwrite_stream &OS)
253 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
254 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000255
Dan Gohman18eafb62017-02-22 01:23:18 +0000256 ~WasmObjectWriter() override;
257
Dan Gohman0917c9e2018-01-15 17:06:23 +0000258private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000259 void reset() override {
260 CodeRelocations.clear();
261 DataRelocations.clear();
262 TypeIndices.clear();
263 SymbolIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000264 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000265 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000266 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000267 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000268 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000269 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000270 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000271 DataSegments.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000272 CustomSectionSymbols.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000273 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000274 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000275 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000276 }
277
Dan Gohman18eafb62017-02-22 01:23:18 +0000278 void writeHeader(const MCAssembler &Asm);
279
280 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
281 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000282 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000283
284 void executePostLayoutBinding(MCAssembler &Asm,
285 const MCAsmLayout &Layout) override;
286
287 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000288
Sam Cleggb7787fd2017-06-20 04:04:59 +0000289 void writeString(const StringRef Str) {
290 encodeULEB128(Str.size(), getStream());
291 writeBytes(Str);
292 }
293
Sam Clegg9e15f352017-06-03 02:01:24 +0000294 void writeValueType(wasm::ValType Ty) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000295 write8(static_cast<uint8_t>(Ty));
Sam Clegg9e15f352017-06-03 02:01:24 +0000296 }
297
Sam Clegg457fb0b2017-09-15 19:50:44 +0000298 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000299 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000300 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000301 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000302 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000303 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000304 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000305 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000306 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000307 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000308 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
309 ArrayRef<WasmRelocationEntry> Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000310 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000311 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000312 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000313 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000314 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
315 void writeCustomRelocSections();
316 void
317 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
318 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000319
Sam Clegg7c395942017-09-14 23:07:53 +0000320 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000321 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
322 uint64_t ContentsOffset);
323
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000324 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000325 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
326 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000327};
Sam Clegg9e15f352017-06-03 02:01:24 +0000328
Dan Gohman18eafb62017-02-22 01:23:18 +0000329} // end anonymous namespace
330
331WasmObjectWriter::~WasmObjectWriter() {}
332
Dan Gohmand934cb82017-02-24 23:18:00 +0000333// Write out a section header and a patchable section size field.
334void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000335 unsigned SectionId) {
336 DEBUG(dbgs() << "startSection " << SectionId << "\n");
Sam Clegg03e101f2018-03-01 18:06:21 +0000337 write8(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000338
339 Section.SizeOffset = getStream().tell();
340
341 // The section size. We don't know the size yet, so reserve enough space
342 // for any 32-bit value; we'll patch it later.
343 encodeULEB128(UINT32_MAX, getStream());
344
345 // The position where the section starts, for measuring its size.
346 Section.ContentsOffset = getStream().tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000347 Section.PayloadOffset = getStream().tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000348 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000349}
Dan Gohmand934cb82017-02-24 23:18:00 +0000350
Sam Clegg2322a932018-04-23 19:16:19 +0000351void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
352 StringRef Name) {
353 DEBUG(dbgs() << "startCustomSection " << Name << "\n");
354 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000355
356 // The position where the section header ends, for measuring its size.
357 Section.PayloadOffset = getStream().tell();
358
Dan Gohmand934cb82017-02-24 23:18:00 +0000359 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000360 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000361
362 // The position where the custom section starts.
363 Section.ContentsOffset = getStream().tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000364}
365
366// Now that the section is complete and we know how big it is, patch up the
367// section size field at the start of the section.
368void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000369 uint64_t Size = getStream().tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000370 if (uint32_t(Size) != Size)
371 report_fatal_error("section size does not fit in a uint32_t");
372
Sam Cleggb7787fd2017-06-20 04:04:59 +0000373 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000374
375 // Write the final section size to the payload_len field, which follows
376 // the section id byte.
377 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000378 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000379 assert(SizeLen == 5);
380 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
381}
382
Dan Gohman18eafb62017-02-22 01:23:18 +0000383// Emit the Wasm header.
384void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000385 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
386 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000387}
388
389void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
390 const MCAsmLayout &Layout) {
391}
392
393void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
394 const MCAsmLayout &Layout,
395 const MCFragment *Fragment,
396 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000397 uint64_t &FixedValue) {
398 MCAsmBackend &Backend = Asm.getBackend();
399 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
400 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000401 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000402 uint64_t C = Target.getConstant();
403 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
404 MCContext &Ctx = Asm.getContext();
405
Sam Cleggbafe6902017-12-15 00:17:10 +0000406 // The .init_array isn't translated as data, so don't do relocations in it.
407 if (FixupSection.getSectionName().startswith(".init_array"))
408 return;
409
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000410 // TODO: Add support for non-debug metadata sections?
411 if (FixupSection.getKind().isMetadata() &&
412 !FixupSection.getSectionName().startswith(".debug_"))
Sam Cleggb7a54692018-02-16 18:06:05 +0000413 return;
414
Dan Gohmand934cb82017-02-24 23:18:00 +0000415 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
416 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
417 "Should not have constructed this");
418
419 // Let A, B and C being the components of Target and R be the location of
420 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
421 // If it is pcrel, we want to compute (A - B + C - R).
422
423 // In general, Wasm has no relocations for -B. It can only represent (A + C)
424 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
425 // replace B to implement it: (A - R - K + C)
426 if (IsPCRel) {
427 Ctx.reportError(
428 Fixup.getLoc(),
429 "No relocation available to represent this relative expression");
430 return;
431 }
432
433 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
434
435 if (SymB.isUndefined()) {
436 Ctx.reportError(Fixup.getLoc(),
437 Twine("symbol '") + SymB.getName() +
438 "' can not be undefined in a subtraction expression");
439 return;
440 }
441
442 assert(!SymB.isAbsolute() && "Should have been folded");
443 const MCSection &SecB = SymB.getSection();
444 if (&SecB != &FixupSection) {
445 Ctx.reportError(Fixup.getLoc(),
446 "Cannot represent a difference across sections");
447 return;
448 }
449
450 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
451 uint64_t K = SymBOffset - FixupOffset;
452 IsPCRel = true;
453 C -= K;
454 }
455
456 // We either rejected the fixup or folded B into C at this point.
457 const MCSymbolRefExpr *RefA = Target.getSymA();
458 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
459
Dan Gohmand934cb82017-02-24 23:18:00 +0000460 if (SymA && SymA->isVariable()) {
461 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000462 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
463 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
464 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000465 }
466
467 // Put any constant offset in an addend. Offsets can be negative, and
468 // LLVM expects wrapping, in contrast to wasm's immediates which can't
469 // be negative and don't wrap.
470 FixedValue = 0;
471
Sam Clegg6ad8f192017-07-11 02:21:57 +0000472 if (SymA)
473 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000474
Sam Cleggae03c1e72017-06-13 18:51:50 +0000475 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000476 assert(SymA);
477
Sam Cleggae03c1e72017-06-13 18:51:50 +0000478 unsigned Type = getRelocType(Target, Fixup);
479
Dan Gohmand934cb82017-02-24 23:18:00 +0000480 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000481 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000482
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000483 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB,
484 // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32
485 // are currently required to be against a named symbol.
Sam Cleggb7a54692018-02-16 18:06:05 +0000486 // TODO(sbc): Add support for relocations against unnamed temporaries such
487 // as those generated by llvm's `blockaddress`.
488 // See: test/MC/WebAssembly/blockaddress.ll
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000489 if (SymA->getName().empty() &&
490 !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB ||
491 Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
492 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32))
Sam Cleggb7a54692018-02-16 18:06:05 +0000493 report_fatal_error("relocations against un-named temporaries are not yet "
494 "supported by wasm");
495
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000496 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000497 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000498 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000499 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000500 } else if (FixupSection.getKind().isMetadata()) {
501 assert(FixupSection.getSectionName().startswith(".debug_"));
502 CustomSectionsRelocations[&FixupSection].push_back(Rec);
503 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000504 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000505 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000506}
507
Dan Gohmand934cb82017-02-24 23:18:00 +0000508// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
509// to allow patching.
510static void
511WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
512 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000513 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000514 assert(SizeLen == 5);
515 Stream.pwrite((char *)Buffer, SizeLen, Offset);
516}
517
518// Write X as an signed LEB value at offset Offset in Stream, padded
519// to allow patching.
520static void
521WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
522 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000523 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000524 assert(SizeLen == 5);
525 Stream.pwrite((char *)Buffer, SizeLen, Offset);
526}
527
528// Write X as a plain integer value at offset Offset in Stream.
529static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
530 uint8_t Buffer[4];
531 support::endian::write32le(Buffer, X);
532 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
533}
534
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000535static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
536 if (Symbol.isVariable()) {
537 const MCExpr *Expr = Symbol.getVariableValue();
538 auto *Inner = cast<MCSymbolRefExpr>(Expr);
539 return cast<MCSymbolWasm>(&Inner->getSymbol());
540 }
541 return &Symbol;
542}
543
Dan Gohmand934cb82017-02-24 23:18:00 +0000544// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000545// by RelEntry. This value isn't used by the static linker; it just serves
546// to make the object format more readable and more likely to be directly
547// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000548uint32_t
549WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000550 switch (RelEntry.Type) {
551 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000552 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
553 // Provisional value is table address of the resolved symbol itself
554 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
555 assert(Sym->isFunction());
556 return TableIndices[Sym];
557 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000558 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000559 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000560 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000561 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
562 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
563 // Provisional value is function/global Wasm index
564 if (!WasmIndices.count(RelEntry.Symbol))
565 report_fatal_error("symbol not found in wasm index space: " +
566 RelEntry.Symbol->getName());
567 return WasmIndices[RelEntry.Symbol];
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000568 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
569 const auto &Section =
570 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
571 return Section.getSectionOffset() + RelEntry.Addend;
572 }
573 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
574 const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second;
575 return Section.getSectionOffset() + RelEntry.Addend;
576 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000577 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
578 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
579 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000580 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000581 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
582 // For undefined symbols, use zero
583 if (!Sym->isDefined())
584 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000585 const wasm::WasmDataReference &Ref = DataLocations[Sym];
586 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000587 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000588 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000589 }
590 default:
591 llvm_unreachable("invalid relocation type");
592 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000593}
594
Sam Clegg759631c2017-09-15 20:54:59 +0000595static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000596 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000597 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
598
Sam Clegg63ebb812017-09-29 16:50:08 +0000599 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
600
Sam Clegg759631c2017-09-15 20:54:59 +0000601 for (const MCFragment &Frag : DataSection) {
602 if (Frag.hasInstructions())
603 report_fatal_error("only data supported in data sections");
604
605 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
606 if (Align->getValueSize() != 1)
607 report_fatal_error("only byte values supported for alignment");
608 // If nops are requested, use zeros, as this is the data section.
609 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
610 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
611 Align->getAlignment()),
612 DataBytes.size() +
613 Align->getMaxBytesToEmit());
614 DataBytes.resize(Size, Value);
615 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000616 int64_t Size;
617 if (!Fill->getSize().evaluateAsAbsolute(Size))
618 llvm_unreachable("The fill should be an assembler constant");
619 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000620 } else {
621 const auto &DataFrag = cast<MCDataFragment>(Frag);
622 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
623
624 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
625 }
626 }
627
628 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
629}
630
Sam Clegg60ec3032018-01-23 01:23:17 +0000631uint32_t
632WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
633 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000634 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000635 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000636 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000637 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000638 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000639
640 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6c899ba2018-02-23 05:08:34 +0000641 report_fatal_error("symbol not found in symbol index space: " +
Sam Clegg60ec3032018-01-23 01:23:17 +0000642 RelEntry.Symbol->getName());
643 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000644}
645
Dan Gohmand934cb82017-02-24 23:18:00 +0000646// Apply the portions of the relocation records that we can handle ourselves
647// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000648void WasmObjectWriter::applyRelocations(
649 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
650 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000651 for (const WasmRelocationEntry &RelEntry : Relocations) {
652 uint64_t Offset = ContentsOffset +
653 RelEntry.FixupSection->getSectionOffset() +
654 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000655
Sam Cleggb7787fd2017-06-20 04:04:59 +0000656 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000657 uint32_t Value = getProvisionalValue(RelEntry);
658
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000659 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000660 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000661 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000662 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
663 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000664 WritePatchableLEB(Stream, Value, Offset);
665 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000666 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
667 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000668 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
669 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000670 WriteI32(Stream, Value, Offset);
671 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000672 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
673 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
674 WritePatchableSLEB(Stream, Value, Offset);
675 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000676 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000677 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000678 }
679 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000680}
681
Sam Clegg9e15f352017-06-03 02:01:24 +0000682void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000683 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000684 if (FunctionTypes.empty())
685 return;
686
687 SectionBookkeeping Section;
688 startSection(Section, wasm::WASM_SEC_TYPE);
689
690 encodeULEB128(FunctionTypes.size(), getStream());
691
692 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000693 write8(wasm::WASM_TYPE_FUNC);
Sam Clegg9e15f352017-06-03 02:01:24 +0000694 encodeULEB128(FuncTy.Params.size(), getStream());
695 for (wasm::ValType Ty : FuncTy.Params)
696 writeValueType(Ty);
697 encodeULEB128(FuncTy.Returns.size(), getStream());
698 for (wasm::ValType Ty : FuncTy.Returns)
699 writeValueType(Ty);
700 }
701
702 endSection(Section);
703}
704
Sam Clegg8defa952018-02-12 22:41:29 +0000705void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000706 uint32_t DataSize,
707 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000708 if (Imports.empty())
709 return;
710
Sam Cleggf950b242017-12-11 23:03:38 +0000711 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
712
Sam Clegg9e15f352017-06-03 02:01:24 +0000713 SectionBookkeeping Section;
714 startSection(Section, wasm::WASM_SEC_IMPORT);
715
716 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000717 for (const wasm::WasmImport &Import : Imports) {
718 writeString(Import.Module);
719 writeString(Import.Field);
Sam Clegg03e101f2018-03-01 18:06:21 +0000720 write8(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000721
722 switch (Import.Kind) {
723 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000724 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000725 break;
726 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg03e101f2018-03-01 18:06:21 +0000727 write8(Import.Global.Type);
728 write8(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000729 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000730 case wasm::WASM_EXTERNAL_MEMORY:
731 encodeULEB128(0, getStream()); // flags
732 encodeULEB128(NumPages, getStream()); // initial
733 break;
734 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg03e101f2018-03-01 18:06:21 +0000735 write8(Import.Table.ElemType);
Sam Cleggf950b242017-12-11 23:03:38 +0000736 encodeULEB128(0, getStream()); // flags
737 encodeULEB128(NumElements, getStream()); // initial
738 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000739 default:
740 llvm_unreachable("unsupported import kind");
741 }
742 }
743
744 endSection(Section);
745}
746
Sam Clegg457fb0b2017-09-15 19:50:44 +0000747void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000748 if (Functions.empty())
749 return;
750
751 SectionBookkeeping Section;
752 startSection(Section, wasm::WASM_SEC_FUNCTION);
753
754 encodeULEB128(Functions.size(), getStream());
755 for (const WasmFunction &Func : Functions)
756 encodeULEB128(Func.Type, getStream());
757
758 endSection(Section);
759}
760
Sam Clegg7c395942017-09-14 23:07:53 +0000761void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000762 if (Globals.empty())
763 return;
764
765 SectionBookkeeping Section;
766 startSection(Section, wasm::WASM_SEC_GLOBAL);
767
768 encodeULEB128(Globals.size(), getStream());
769 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000770 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
771 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000772
Sam Clegg6e7f1822018-01-31 19:50:14 +0000773 write8(wasm::WASM_OPCODE_I32_CONST);
774 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000775 write8(wasm::WASM_OPCODE_END);
776 }
777
778 endSection(Section);
779}
780
Sam Clegg8defa952018-02-12 22:41:29 +0000781void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000782 if (Exports.empty())
783 return;
784
785 SectionBookkeeping Section;
786 startSection(Section, wasm::WASM_SEC_EXPORT);
787
788 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000789 for (const wasm::WasmExport &Export : Exports) {
790 writeString(Export.Name);
Sam Clegg03e101f2018-03-01 18:06:21 +0000791 write8(Export.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000792 encodeULEB128(Export.Index, getStream());
793 }
794
795 endSection(Section);
796}
797
Sam Clegg457fb0b2017-09-15 19:50:44 +0000798void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000799 if (TableElems.empty())
800 return;
801
802 SectionBookkeeping Section;
803 startSection(Section, wasm::WASM_SEC_ELEM);
804
805 encodeULEB128(1, getStream()); // number of "segments"
806 encodeULEB128(0, getStream()); // the table index
807
808 // init expr for starting offset
809 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000810 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000811 write8(wasm::WASM_OPCODE_END);
812
813 encodeULEB128(TableElems.size(), getStream());
814 for (uint32_t Elem : TableElems)
815 encodeULEB128(Elem, getStream());
816
817 endSection(Section);
818}
819
Sam Clegg457fb0b2017-09-15 19:50:44 +0000820void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
821 const MCAsmLayout &Layout,
822 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000823 if (Functions.empty())
824 return;
825
826 SectionBookkeeping Section;
827 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000828 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000829
830 encodeULEB128(Functions.size(), getStream());
831
832 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000833 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000834
Sam Clegg9e15f352017-06-03 02:01:24 +0000835 int64_t Size = 0;
836 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
837 report_fatal_error(".size expression must be evaluatable");
838
839 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000840 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000841 Asm.writeSectionData(&FuncSection, Layout);
842 }
843
Sam Clegg9e15f352017-06-03 02:01:24 +0000844 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000845 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000846
847 endSection(Section);
848}
849
Sam Clegg6c899ba2018-02-23 05:08:34 +0000850void WasmObjectWriter::writeDataSection() {
851 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000852 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000853
854 SectionBookkeeping Section;
855 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000856 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
Sam Clegg6c899ba2018-02-23 05:08:34 +0000858 encodeULEB128(DataSegments.size(), getStream()); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000859
Sam Clegg6c899ba2018-02-23 05:08:34 +0000860 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000861 encodeULEB128(0, getStream()); // memory index
862 write8(wasm::WASM_OPCODE_I32_CONST);
863 encodeSLEB128(Segment.Offset, getStream()); // offset
864 write8(wasm::WASM_OPCODE_END);
865 encodeULEB128(Segment.Data.size(), getStream()); // size
866 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
867 writeBytes(Segment.Data); // data
868 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000869
870 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000871 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000872
873 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000874}
875
Sam Clegg6f08c842018-04-24 18:11:36 +0000876void WasmObjectWriter::writeRelocSection(
877 uint32_t SectionIndex, StringRef Name,
878 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000879 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
880 // for descriptions of the reloc sections.
881
Sam Clegg6f08c842018-04-24 18:11:36 +0000882 if (Relocations.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000883 return;
884
885 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000886 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
Sam Clegg6f08c842018-04-24 18:11:36 +0000888 raw_pwrite_stream &Stream = getStream();
Sam Clegg9e15f352017-06-03 02:01:24 +0000889
Sam Clegg6f08c842018-04-24 18:11:36 +0000890 encodeULEB128(SectionIndex, Stream);
891 encodeULEB128(Relocations.size(), Stream);
892 for (const WasmRelocationEntry& RelEntry : Relocations) {
893 uint64_t Offset = RelEntry.Offset +
894 RelEntry.FixupSection->getSectionOffset();
895 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000896
Sam Clegg6f08c842018-04-24 18:11:36 +0000897 write8(RelEntry.Type);
898 encodeULEB128(Offset, Stream);
899 encodeULEB128(Index, Stream);
900 if (RelEntry.hasAddend())
901 encodeSLEB128(RelEntry.Addend, Stream);
902 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000903
904 endSection(Section);
905}
906
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000907void WasmObjectWriter::writeCustomRelocSections() {
908 for (const auto &Sec : CustomSections) {
909 auto &Relocations = CustomSectionsRelocations[Sec.Section];
910 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
911 }
912}
913
Sam Clegg9e15f352017-06-03 02:01:24 +0000914void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000915 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000916 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000917 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000918 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000919 startCustomSection(Section, "linking");
Sam Clegg6bb5a412018-04-26 18:15:32 +0000920 encodeULEB128(wasm::WasmMetadataVersion, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000921
Sam Clegg6bb5a412018-04-26 18:15:32 +0000922 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000923 if (SymbolInfos.size() != 0) {
924 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
925 encodeULEB128(SymbolInfos.size(), getStream());
926 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
927 encodeULEB128(Sym.Kind, getStream());
928 encodeULEB128(Sym.Flags, getStream());
929 switch (Sym.Kind) {
930 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
931 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
932 encodeULEB128(Sym.ElementIndex, getStream());
933 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
934 writeString(Sym.Name);
935 break;
936 case wasm::WASM_SYMBOL_TYPE_DATA:
937 writeString(Sym.Name);
938 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
939 encodeULEB128(Sym.DataRef.Segment, getStream());
940 encodeULEB128(Sym.DataRef.Offset, getStream());
941 encodeULEB128(Sym.DataRef.Size, getStream());
942 }
943 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000944 case wasm::WASM_SYMBOL_TYPE_SECTION: {
945 const uint32_t SectionIndex =
946 CustomSections[Sym.ElementIndex].OutputIndex;
947 encodeULEB128(SectionIndex, getStream());
948 break;
949 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000950 default:
951 llvm_unreachable("unexpected kind");
952 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000953 }
954 endSection(SubSection);
955 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000956
Sam Clegg6c899ba2018-02-23 05:08:34 +0000957 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000958 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000959 encodeULEB128(DataSegments.size(), getStream());
960 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000961 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000962 encodeULEB128(Segment.Alignment, getStream());
963 encodeULEB128(Segment.Flags, getStream());
964 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000965 endSection(SubSection);
966 }
967
Sam Cleggbafe6902017-12-15 00:17:10 +0000968 if (!InitFuncs.empty()) {
969 startSection(SubSection, wasm::WASM_INIT_FUNCS);
970 encodeULEB128(InitFuncs.size(), getStream());
971 for (auto &StartFunc : InitFuncs) {
972 encodeULEB128(StartFunc.first, getStream()); // priority
973 encodeULEB128(StartFunc.second, getStream()); // function index
974 }
975 endSection(SubSection);
976 }
977
Sam Cleggea7cace2018-01-09 23:43:14 +0000978 if (Comdats.size()) {
979 startSection(SubSection, wasm::WASM_COMDAT_INFO);
980 encodeULEB128(Comdats.size(), getStream());
981 for (const auto &C : Comdats) {
982 writeString(C.first);
983 encodeULEB128(0, getStream()); // flags for future use
984 encodeULEB128(C.second.size(), getStream());
985 for (const WasmComdatEntry &Entry : C.second) {
986 encodeULEB128(Entry.Kind, getStream());
987 encodeULEB128(Entry.Index, getStream());
988 }
989 }
990 endSection(SubSection);
991 }
992
Sam Clegg9e15f352017-06-03 02:01:24 +0000993 endSection(Section);
994}
995
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000996void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
997 const MCAsmLayout &Layout) {
998 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000999 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001000 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001001 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001002
1003 Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
1004 Asm.writeSectionData(Sec, Layout);
1005
1006 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1007 CustomSection.OutputIndex = Section.Index;
1008
Sam Cleggcfd44a22018-04-05 17:01:39 +00001009 endSection(Section);
1010 }
1011}
1012
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001013void WasmObjectWriter::updateCustomSectionRelocations(
1014 const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) {
1015 std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols;
1016 for (const auto &P : CustomSectionSymbols)
1017 SectionSymbols[P.second] = P.first;
1018 std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols;
1019 for (const auto &FuncInfo : Functions)
1020 FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym;
1021
1022 // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and
1023 // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from
1024 // the beginning of the function or custom section -- all such relocations
1025 // target the function or custom section starts.
1026 for (auto &Section : CustomSections) {
1027 auto &Relocations = CustomSectionsRelocations[Section.Section];
1028 for (WasmRelocationEntry &RelEntry : Relocations) {
1029 switch (RelEntry.Type) {
1030 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
1031 assert(RelEntry.hasAddend());
1032 auto &Section =
1033 static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
1034 RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
1035 RelEntry.Symbol = FuncSymbols[&Section];
1036 break;
1037 }
1038 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
1039 assert(RelEntry.hasAddend());
1040 auto &Section =
1041 static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
1042 RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
1043 RelEntry.Symbol = SectionSymbols[&Section];
1044 break;
1045 }
1046 default:
1047 break;
1048 }
1049 }
1050
1051 // Apply fixups.
1052 applyRelocations(Relocations, Section.OutputContentsOffset);
1053 }
1054}
1055
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001056uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
1057 assert(Symbol.isFunction());
1058 assert(TypeIndices.count(&Symbol));
1059 return TypeIndices[&Symbol];
1060}
1061
1062uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
1063 assert(Symbol.isFunction());
1064
1065 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001066 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
1067 F.Returns = ResolvedSym->getReturns();
1068 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001069
1070 auto Pair =
1071 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1072 if (Pair.second)
1073 FunctionTypes.push_back(F);
1074 TypeIndices[&Symbol] = Pair.first->second;
1075
1076 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
1077 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
1078 return Pair.first->second;
1079}
1080
Dan Gohman18eafb62017-02-22 01:23:18 +00001081void WasmObjectWriter::writeObject(MCAssembler &Asm,
1082 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001083 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001084 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001085
1086 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001087 SmallVector<WasmFunction, 4> Functions;
1088 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001089 SmallVector<wasm::WasmImport, 4> Imports;
1090 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001091 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001092 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001093 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001094 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001095
Sam Cleggf950b242017-12-11 23:03:38 +00001096 // For now, always emit the memory import, since loads and stores are not
1097 // valid without it. In the future, we could perhaps be more clever and omit
1098 // it if there are no loads or stores.
1099 MCSymbolWasm *MemorySym =
1100 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001101 wasm::WasmImport MemImport;
1102 MemImport.Module = MemorySym->getModuleName();
1103 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001104 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1105 Imports.push_back(MemImport);
1106
1107 // For now, always emit the table section, since indirect calls are not
1108 // valid without it. In the future, we could perhaps be more clever and omit
1109 // it if there are no indirect calls.
1110 MCSymbolWasm *TableSym =
1111 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001112 wasm::WasmImport TableImport;
1113 TableImport.Module = TableSym->getModuleName();
1114 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001115 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001116 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001117 Imports.push_back(TableImport);
1118
Nicholas Wilson586320c2018-02-28 17:19:48 +00001119 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1120 // symbols. This must be done before populating WasmIndices for defined
1121 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001122 for (const MCSymbol &S : Asm.symbols()) {
1123 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1124
1125 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001126 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001127 if (WS.isFunction())
1128 registerFunctionType(WS);
1129
1130 if (WS.isTemporary())
1131 continue;
1132
1133 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001134 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001135 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001136 wasm::WasmImport Import;
1137 Import.Module = WS.getModuleName();
1138 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001139 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001140 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001141 Imports.push_back(Import);
1142 WasmIndices[&WS] = NumFunctionImports++;
1143 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001144 if (WS.isWeak())
1145 report_fatal_error("undefined global symbol cannot be weak");
1146
Sam Clegg6c899ba2018-02-23 05:08:34 +00001147 wasm::WasmImport Import;
1148 Import.Module = WS.getModuleName();
1149 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001150 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001151 Import.Global = WS.getGlobalType();
1152 Imports.push_back(Import);
1153 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001154 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001155 }
1156 }
1157
Nicholas Wilson586320c2018-02-28 17:19:48 +00001158 // Populate DataSegments, which must be done before populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001159 for (MCSection &Sec : Asm) {
1160 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Cleggcfd44a22018-04-05 17:01:39 +00001161
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001162 if (Section.getSectionName().startswith(".custom_section.")) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001163 if (Section.getFragmentList().empty())
1164 continue;
1165 if (Section.getFragmentList().size() != 1)
1166 report_fatal_error(
1167 "only one .custom_section section fragment supported");
1168 const MCFragment &Frag = *Section.begin();
1169 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1170 report_fatal_error("only data supported in .custom_section section");
1171 const auto &DataFrag = cast<MCDataFragment>(Frag);
1172 if (!DataFrag.getFixups().empty())
1173 report_fatal_error("fixups not supported in .custom_section section");
1174 StringRef UserName = Section.getSectionName().substr(16);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001175 CustomSections.emplace_back(UserName, &Section);
Sam Cleggcfd44a22018-04-05 17:01:39 +00001176 continue;
1177 }
1178
Sam Clegg12fd3da2017-10-20 21:28:38 +00001179 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001180 continue;
1181
Sam Cleggbafe6902017-12-15 00:17:10 +00001182 // .init_array sections are handled specially elsewhere.
1183 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1184 continue;
1185
Sam Clegg329e76d2018-01-31 04:21:44 +00001186 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001187 DataSize = alignTo(DataSize, Section.getAlignment());
1188 DataSegments.emplace_back();
1189 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001190 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001191 Segment.Offset = DataSize;
1192 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001193 addData(Segment.Data, Section);
1194 Segment.Alignment = Section.getAlignment();
1195 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001196 DataSize += Segment.Data.size();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001197 Section.setSegmentIndex(SegmentIndex);
Sam Cleggea7cace2018-01-09 23:43:14 +00001198
1199 if (const MCSymbolWasm *C = Section.getGroup()) {
1200 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001201 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001202 }
Sam Clegg759631c2017-09-15 20:54:59 +00001203 }
1204
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001205 // Create symbols for debug/custom sections.
1206 for (MCSection &Sec : Asm) {
1207 auto &DebugSection = static_cast<MCSectionWasm &>(Sec);
1208 StringRef SectionName = DebugSection.getSectionName();
1209
1210 // TODO: Add support for non-debug metadata sections?
1211 if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_"))
1212 continue;
1213
1214 uint32_t ElementIndex = CustomSections.size();
1215 CustomSections.emplace_back(SectionName, &DebugSection);
1216
1217 MCSymbolWasm *SectionSym =
1218 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName));
1219 CustomSectionSymbols[SectionSym] = &DebugSection;
1220
1221 wasm::WasmSymbolInfo Info;
1222 Info.Name = SectionSym->getName();
1223 Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION;
Sam Cleggd5504a02018-04-27 00:17:21 +00001224 Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001225 Info.ElementIndex = ElementIndex;
1226 SymbolIndices[SectionSym] = SymbolInfos.size();
1227 SymbolInfos.emplace_back(Info);
1228 }
1229
Nicholas Wilson586320c2018-02-28 17:19:48 +00001230 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001231 for (const MCSymbol &S : Asm.symbols()) {
1232 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1233 // or used in relocations.
1234 if (S.isTemporary() && S.getName().empty())
1235 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001236
Dan Gohmand934cb82017-02-24 23:18:00 +00001237 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001238 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001239 << " isDefined=" << S.isDefined()
1240 << " isExternal=" << S.isExternal()
1241 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001242 << " isFunction=" << WS.isFunction()
1243 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001244 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001245 << " isVariable=" << WS.isVariable() << "\n");
1246
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001247 if (WS.isVariable())
1248 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001249 if (WS.isComdat() && !WS.isDefined())
1250 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001251
Dan Gohmand934cb82017-02-24 23:18:00 +00001252 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001253 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001254 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001255 if (WS.getOffset() != 0)
1256 report_fatal_error(
1257 "function sections must contain one function each");
1258
1259 if (WS.getSize() == 0)
1260 report_fatal_error(
1261 "function symbols must have a size set with .size");
1262
Sam Clegg6c899ba2018-02-23 05:08:34 +00001263 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001264 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001265 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001266 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001267 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001268 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001269 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001270
1271 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1272 if (const MCSymbolWasm *C = Section.getGroup()) {
1273 Comdats[C->getName()].emplace_back(
1274 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1275 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001276 } else {
1277 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001278 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001279 }
1280
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001281 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001282 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001283 if (WS.isTemporary() && !WS.getSize())
1284 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001285
Sam Clegg6c899ba2018-02-23 05:08:34 +00001286 if (!WS.isDefined()) {
1287 DEBUG(dbgs() << " -> segment index: -1");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001288 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001289 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001290
Sam Cleggfe6414b2017-06-21 23:46:41 +00001291 if (!WS.getSize())
1292 report_fatal_error("data symbols must have a size set with .size: " +
1293 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001294
Sam Cleggfe6414b2017-06-21 23:46:41 +00001295 int64_t Size = 0;
1296 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1297 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001298
Sam Clegg759631c2017-09-15 20:54:59 +00001299 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001300 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001301
Sam Clegg6c899ba2018-02-23 05:08:34 +00001302 // For each data symbol, export it in the symtab as a reference to the
1303 // corresponding Wasm data segment.
1304 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1305 DataSection.getSegmentIndex(),
1306 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1307 static_cast<uint32_t>(Size)};
1308 DataLocations[&WS] = Ref;
1309 DEBUG(dbgs() << " -> segment index: " << Ref.Segment);
1310 } else {
1311 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001312 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001313 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001314
Eric Christopher545932b2018-02-23 21:14:47 +00001315 // An import; the index was assigned above
1316 DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second
1317 << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001318 }
1319 }
1320
Nicholas Wilson586320c2018-02-28 17:19:48 +00001321 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1322 // process these in a separate pass because we need to have processed the
1323 // target of the alias before the alias itself and the symbols are not
1324 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001325 for (const MCSymbol &S : Asm.symbols()) {
1326 if (!S.isVariable())
1327 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001328
Sam Cleggcd65f692018-01-11 23:59:16 +00001329 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001330
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001331 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001332 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1333 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001334 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001335
Sam Clegg6c899ba2018-02-23 05:08:34 +00001336 if (WS.isFunction()) {
1337 assert(WasmIndices.count(ResolvedSym) > 0);
1338 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1339 WasmIndices[&WS] = WasmIndex;
1340 DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
1341 } else if (WS.isData()) {
1342 assert(DataLocations.count(ResolvedSym) > 0);
1343 const wasm::WasmDataReference &Ref =
1344 DataLocations.find(ResolvedSym)->second;
1345 DataLocations[&WS] = Ref;
1346 DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
1347 } else {
1348 report_fatal_error("don't yet support global aliases");
1349 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001350 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001351
Nicholas Wilson586320c2018-02-28 17:19:48 +00001352 // Finally, populate the symbol table itself, in its "natural" order.
1353 for (const MCSymbol &S : Asm.symbols()) {
1354 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1355 if (WS.isTemporary() && WS.getName().empty())
1356 continue;
1357 if (WS.isComdat() && !WS.isDefined())
1358 continue;
1359 if (WS.isTemporary() && WS.isData() && !WS.getSize())
1360 continue;
1361
1362 uint32_t Flags = 0;
1363 if (WS.isWeak())
1364 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1365 if (WS.isHidden())
1366 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1367 if (!WS.isExternal() && WS.isDefined())
1368 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1369 if (WS.isUndefined())
1370 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1371
1372 wasm::WasmSymbolInfo Info;
1373 Info.Name = WS.getName();
1374 Info.Kind = WS.getType();
1375 Info.Flags = Flags;
1376 if (!WS.isData())
1377 Info.ElementIndex = WasmIndices.find(&WS)->second;
1378 else if (WS.isDefined())
1379 Info.DataRef = DataLocations.find(&WS)->second;
1380 SymbolIndices[&WS] = SymbolInfos.size();
1381 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001382 }
1383
Sam Clegg6006e092017-12-22 20:31:39 +00001384 {
1385 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001386 // Functions referenced by a relocation need to put in the table. This is
1387 // purely to make the object file's provisional values readable, and is
1388 // ignored by the linker, which re-calculates the relocations itself.
1389 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1390 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1391 return;
1392 assert(Rel.Symbol->isFunction());
1393 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001394 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001395 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1396 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1397 DEBUG(dbgs() << " -> adding " << WS.getName()
1398 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001399 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001400 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001401 }
1402 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001403
Sam Clegg6006e092017-12-22 20:31:39 +00001404 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1405 HandleReloc(RelEntry);
1406 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1407 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001408 }
1409
Sam Cleggbafe6902017-12-15 00:17:10 +00001410 // Translate .init_array section contents into start functions.
1411 for (const MCSection &S : Asm) {
1412 const auto &WS = static_cast<const MCSectionWasm &>(S);
1413 if (WS.getSectionName().startswith(".fini_array"))
1414 report_fatal_error(".fini_array sections are unsupported");
1415 if (!WS.getSectionName().startswith(".init_array"))
1416 continue;
1417 if (WS.getFragmentList().empty())
1418 continue;
1419 if (WS.getFragmentList().size() != 2)
1420 report_fatal_error("only one .init_array section fragment supported");
1421 const MCFragment &AlignFrag = *WS.begin();
1422 if (AlignFrag.getKind() != MCFragment::FT_Align)
1423 report_fatal_error(".init_array section should be aligned");
1424 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1425 report_fatal_error(".init_array section should be aligned for pointers");
1426 const MCFragment &Frag = *std::next(WS.begin());
1427 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1428 report_fatal_error("only data supported in .init_array section");
1429 uint16_t Priority = UINT16_MAX;
1430 if (WS.getSectionName().size() != 11) {
1431 if (WS.getSectionName()[11] != '.')
1432 report_fatal_error(".init_array section priority should start with '.'");
1433 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1434 report_fatal_error("invalid .init_array section priority");
1435 }
1436 const auto &DataFrag = cast<MCDataFragment>(Frag);
1437 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1438 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1439 *end = (const uint8_t *)Contents.data() + Contents.size();
1440 p != end; ++p) {
1441 if (*p != 0)
1442 report_fatal_error("non-symbolic data in .init_array section");
1443 }
1444 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1445 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1446 const MCExpr *Expr = Fixup.getValue();
1447 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1448 if (!Sym)
1449 report_fatal_error("fixups in .init_array should be symbol references");
1450 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1451 report_fatal_error("symbols in .init_array should be for functions");
1452 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1453 if (I == SymbolIndices.end())
1454 report_fatal_error("symbols in .init_array should be defined");
1455 uint32_t Index = I->second;
1456 InitFuncs.push_back(std::make_pair(Priority, Index));
1457 }
1458 }
1459
Dan Gohman18eafb62017-02-22 01:23:18 +00001460 // Write out the Wasm header.
1461 writeHeader(Asm);
1462
Sam Clegg9e15f352017-06-03 02:01:24 +00001463 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001464 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001465 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001466 // Skip the "table" section; we import the table instead.
1467 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001468 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001469 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001470 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001471 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001472 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001473 writeCustomSections(Asm, Layout);
1474 updateCustomSectionRelocations(Functions, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001475 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001476 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1477 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001478 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001479
Dan Gohmand934cb82017-02-24 23:18:00 +00001480 // TODO: Translate the .comment section to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001481}
1482
Lang Hames60fbc7c2017-10-10 16:28:07 +00001483std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001484llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1485 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001486 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001487}