blob: 05fc3362745a2e631823bcde9e5fc95155d9db64 [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"
Dan Gohman18eafb62017-02-22 01:23:18 +000017#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmLayout.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000023#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionWasm.h"
25#include "llvm/MC/MCSymbolWasm.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000028#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000029#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000031#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/StringSaver.h"
33#include <vector>
34
35using namespace llvm;
36
Sam Clegg5e3d33a2017-07-07 02:01:29 +000037#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000038
39namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000040
Sam Clegg30e1bbc2018-01-19 18:57:01 +000041// Went we ceate the indirect function table we start at 1, so that there is
42// and emtpy slot at 0 and therefore calling a null function pointer will trap.
43static const uint32_t kInitialTableOffset = 1;
44
Dan Gohmand934cb82017-02-24 23:18:00 +000045// For patching purposes, we need to remember where each section starts, both
46// for patching up the section size field, and for patching up references to
47// locations within the section.
48struct SectionBookkeeping {
49 // Where the size of the section is written.
50 uint64_t SizeOffset;
Sam Clegg6a31a0d2018-04-26 19:27:28 +000051 // Where the section header ends (without custom section name).
52 uint64_t PayloadOffset;
53 // Where the contents of the section starts.
Dan Gohmand934cb82017-02-24 23:18:00 +000054 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000055 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000056};
57
Sam Clegg9e15f352017-06-03 02:01:24 +000058// The signature of a wasm function, in a struct capable of being used as a
59// DenseMap key.
60struct WasmFunctionType {
61 // Support empty and tombstone instances, needed by DenseMap.
62 enum { Plain, Empty, Tombstone } State;
63
64 // The return types of the function.
65 SmallVector<wasm::ValType, 1> Returns;
66
67 // The parameter types of the function.
68 SmallVector<wasm::ValType, 4> Params;
69
70 WasmFunctionType() : State(Plain) {}
71
72 bool operator==(const WasmFunctionType &Other) const {
73 return State == Other.State && Returns == Other.Returns &&
74 Params == Other.Params;
75 }
76};
77
78// Traits for using WasmFunctionType in a DenseMap.
79struct WasmFunctionTypeDenseMapInfo {
80 static WasmFunctionType getEmptyKey() {
81 WasmFunctionType FuncTy;
82 FuncTy.State = WasmFunctionType::Empty;
83 return FuncTy;
84 }
85 static WasmFunctionType getTombstoneKey() {
86 WasmFunctionType FuncTy;
87 FuncTy.State = WasmFunctionType::Tombstone;
88 return FuncTy;
89 }
90 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
91 uintptr_t Value = FuncTy.State;
92 for (wasm::ValType Ret : FuncTy.Returns)
93 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
94 for (wasm::ValType Param : FuncTy.Params)
95 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
96 return Value;
97 }
98 static bool isEqual(const WasmFunctionType &LHS,
99 const WasmFunctionType &RHS) {
100 return LHS == RHS;
101 }
102};
103
Sam Clegg7c395942017-09-14 23:07:53 +0000104// A wasm data segment. A wasm binary contains only a single data section
105// but that can contain many segments, each with their own virtual location
106// in memory. Each MCSection data created by llvm is modeled as its own
107// wasm data segment.
108struct WasmDataSegment {
109 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000110 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000111 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000112 uint32_t Alignment;
113 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000114 SmallVector<char, 4> Data;
115};
116
Sam Clegg9e15f352017-06-03 02:01:24 +0000117// A wasm function to be written into the function section.
118struct WasmFunction {
119 int32_t Type;
120 const MCSymbolWasm *Sym;
121};
122
Sam Clegg9e15f352017-06-03 02:01:24 +0000123// A wasm global to be written into the global section.
124struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000125 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000126 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000127};
128
Sam Cleggea7cace2018-01-09 23:43:14 +0000129// Information about a single item which is part of a COMDAT. For each data
130// segment or function which is in the COMDAT, there is a corresponding
131// WasmComdatEntry.
132struct WasmComdatEntry {
133 unsigned Kind;
134 uint32_t Index;
135};
136
Sam Clegg6dc65e92017-06-06 16:38:59 +0000137// Information about a single relocation.
138struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000139 uint64_t Offset; // Where is the relocation.
140 const MCSymbolWasm *Symbol; // The symbol to relocate with.
141 int64_t Addend; // A value to add to the symbol.
142 unsigned Type; // The type of the relocation.
143 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000144
145 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
146 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000147 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000148 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
149 FixupSection(FixupSection) {}
150
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000151 bool hasAddend() const {
152 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000153 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
154 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000156 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
157 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000158 return true;
159 default:
160 return false;
161 }
162 }
163
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000165 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000166 << ", Type=" << Type
167 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000168 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000169
Aaron Ballman615eb472017-10-15 14:32:27 +0000170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
172#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000173};
174
Sam Cleggcfd44a22018-04-05 17:01:39 +0000175struct WasmCustomSection {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000176 const uint32_t INVALID_INDEX = -1;
Sam Cleggcfd44a22018-04-05 17:01:39 +0000177
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000178 StringRef Name;
179 MCSectionWasm *Section;
180
181 uint32_t OutputContentsOffset;
182 uint32_t OutputIndex;
183
184 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
185 : Name(Name), Section(Section), OutputContentsOffset(0),
186 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000187};
188
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000189#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000190raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000191 Rel.print(OS);
192 return OS;
193}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000194#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000195
Dan Gohman18eafb62017-02-22 01:23:18 +0000196class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000197 /// The target specific Wasm writer instance.
198 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
199
Dan Gohmand934cb82017-02-24 23:18:00 +0000200 // Relocations for fixing up references in the code section.
201 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000202 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000203
204 // Relocations for fixing up references in the data section.
205 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000206 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000207
Dan Gohmand934cb82017-02-24 23:18:00 +0000208 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000209 // Maps function symbols to the index of the type of the function
210 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000211 // Maps function symbols to the table element index space. Used
212 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000213 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000214 // Maps function/global symbols to the (shared) Symbol index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000215 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000216 // Maps function/global symbols to the function/global Wasm index space.
217 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
218 // Maps data symbols to the Wasm segment and offset/size with the segment.
219 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000220 // Maps section symbols to the section.
221 DenseMap<const MCSymbolWasm *, const MCSectionWasm *> CustomSectionSymbols;
222
223 // Stores output data (index, relocations, content offset) for custom
224 // section.
225 std::vector<WasmCustomSection> CustomSections;
226 // Relocations for fixing up references in the custom sections.
227 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
228 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000229
230 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
231 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000232 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000233 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000234 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000235 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000236 unsigned NumGlobalImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000237 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000238
Dan Gohman18eafb62017-02-22 01:23:18 +0000239 // TargetObjectWriter wrappers.
240 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000241 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
242 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000243 }
244
Sam Clegg2322a932018-04-23 19:16:19 +0000245 void startSection(SectionBookkeeping &Section, unsigned SectionId);
246 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000247 void endSection(SectionBookkeeping &Section);
248
Dan Gohman18eafb62017-02-22 01:23:18 +0000249public:
Lang Hames1301a872017-10-10 01:15:10 +0000250 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
251 raw_pwrite_stream &OS)
252 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
253 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000254
Dan Gohman18eafb62017-02-22 01:23:18 +0000255 ~WasmObjectWriter() override;
256
Dan Gohman0917c9e2018-01-15 17:06:23 +0000257private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000258 void reset() override {
259 CodeRelocations.clear();
260 DataRelocations.clear();
261 TypeIndices.clear();
262 SymbolIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000263 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000264 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000265 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000266 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000267 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000268 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000269 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000270 DataSegments.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000271 CustomSectionSymbols.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000272 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000273 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000274 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000275 }
276
Dan Gohman18eafb62017-02-22 01:23:18 +0000277 void writeHeader(const MCAssembler &Asm);
278
279 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
280 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000281 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000282
283 void executePostLayoutBinding(MCAssembler &Asm,
284 const MCAsmLayout &Layout) override;
285
286 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000287
Sam Cleggb7787fd2017-06-20 04:04:59 +0000288 void writeString(const StringRef Str) {
289 encodeULEB128(Str.size(), getStream());
290 writeBytes(Str);
291 }
292
Sam Clegg9e15f352017-06-03 02:01:24 +0000293 void writeValueType(wasm::ValType Ty) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000294 write8(static_cast<uint8_t>(Ty));
Sam Clegg9e15f352017-06-03 02:01:24 +0000295 }
296
Sam Clegg457fb0b2017-09-15 19:50:44 +0000297 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000298 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000299 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000300 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000301 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000302 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000303 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000304 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000305 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000306 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000307 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
308 ArrayRef<WasmRelocationEntry> Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000309 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000310 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000311 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000312 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000313 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
314 void writeCustomRelocSections();
315 void
316 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
317 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000318
Sam Clegg7c395942017-09-14 23:07:53 +0000319 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000320 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
321 uint64_t ContentsOffset);
322
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000323 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000324 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
325 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000326};
Sam Clegg9e15f352017-06-03 02:01:24 +0000327
Dan Gohman18eafb62017-02-22 01:23:18 +0000328} // end anonymous namespace
329
330WasmObjectWriter::~WasmObjectWriter() {}
331
Dan Gohmand934cb82017-02-24 23:18:00 +0000332// Write out a section header and a patchable section size field.
333void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000334 unsigned SectionId) {
335 DEBUG(dbgs() << "startSection " << SectionId << "\n");
Sam Clegg03e101f2018-03-01 18:06:21 +0000336 write8(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000337
338 Section.SizeOffset = getStream().tell();
339
340 // The section size. We don't know the size yet, so reserve enough space
341 // for any 32-bit value; we'll patch it later.
342 encodeULEB128(UINT32_MAX, getStream());
343
344 // The position where the section starts, for measuring its size.
345 Section.ContentsOffset = getStream().tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000346 Section.PayloadOffset = getStream().tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000347 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000348}
Dan Gohmand934cb82017-02-24 23:18:00 +0000349
Sam Clegg2322a932018-04-23 19:16:19 +0000350void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
351 StringRef Name) {
352 DEBUG(dbgs() << "startCustomSection " << Name << "\n");
353 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000354
355 // The position where the section header ends, for measuring its size.
356 Section.PayloadOffset = getStream().tell();
357
Dan Gohmand934cb82017-02-24 23:18:00 +0000358 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000359 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000360
361 // The position where the custom section starts.
362 Section.ContentsOffset = getStream().tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000363}
364
365// Now that the section is complete and we know how big it is, patch up the
366// section size field at the start of the section.
367void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000368 uint64_t Size = getStream().tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000369 if (uint32_t(Size) != Size)
370 report_fatal_error("section size does not fit in a uint32_t");
371
Sam Cleggb7787fd2017-06-20 04:04:59 +0000372 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000373
374 // Write the final section size to the payload_len field, which follows
375 // the section id byte.
376 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000377 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000378 assert(SizeLen == 5);
379 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
380}
381
Dan Gohman18eafb62017-02-22 01:23:18 +0000382// Emit the Wasm header.
383void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000384 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
385 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000386}
387
388void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
389 const MCAsmLayout &Layout) {
390}
391
392void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
393 const MCAsmLayout &Layout,
394 const MCFragment *Fragment,
395 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000396 uint64_t &FixedValue) {
397 MCAsmBackend &Backend = Asm.getBackend();
398 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
399 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000400 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000401 uint64_t C = Target.getConstant();
402 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
403 MCContext &Ctx = Asm.getContext();
404
Sam Cleggbafe6902017-12-15 00:17:10 +0000405 // The .init_array isn't translated as data, so don't do relocations in it.
406 if (FixupSection.getSectionName().startswith(".init_array"))
407 return;
408
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000409 // TODO: Add support for non-debug metadata sections?
410 if (FixupSection.getKind().isMetadata() &&
411 !FixupSection.getSectionName().startswith(".debug_"))
Sam Cleggb7a54692018-02-16 18:06:05 +0000412 return;
413
Dan Gohmand934cb82017-02-24 23:18:00 +0000414 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
415 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
416 "Should not have constructed this");
417
418 // Let A, B and C being the components of Target and R be the location of
419 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
420 // If it is pcrel, we want to compute (A - B + C - R).
421
422 // In general, Wasm has no relocations for -B. It can only represent (A + C)
423 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
424 // replace B to implement it: (A - R - K + C)
425 if (IsPCRel) {
426 Ctx.reportError(
427 Fixup.getLoc(),
428 "No relocation available to represent this relative expression");
429 return;
430 }
431
432 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
433
434 if (SymB.isUndefined()) {
435 Ctx.reportError(Fixup.getLoc(),
436 Twine("symbol '") + SymB.getName() +
437 "' can not be undefined in a subtraction expression");
438 return;
439 }
440
441 assert(!SymB.isAbsolute() && "Should have been folded");
442 const MCSection &SecB = SymB.getSection();
443 if (&SecB != &FixupSection) {
444 Ctx.reportError(Fixup.getLoc(),
445 "Cannot represent a difference across sections");
446 return;
447 }
448
449 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
450 uint64_t K = SymBOffset - FixupOffset;
451 IsPCRel = true;
452 C -= K;
453 }
454
455 // We either rejected the fixup or folded B into C at this point.
456 const MCSymbolRefExpr *RefA = Target.getSymA();
457 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
458
Dan Gohmand934cb82017-02-24 23:18:00 +0000459 if (SymA && SymA->isVariable()) {
460 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000461 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
462 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
463 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000464 }
465
466 // Put any constant offset in an addend. Offsets can be negative, and
467 // LLVM expects wrapping, in contrast to wasm's immediates which can't
468 // be negative and don't wrap.
469 FixedValue = 0;
470
Sam Clegg6ad8f192017-07-11 02:21:57 +0000471 if (SymA)
472 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000473
Sam Cleggae03c1e72017-06-13 18:51:50 +0000474 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000475 assert(SymA);
476
Sam Cleggae03c1e72017-06-13 18:51:50 +0000477 unsigned Type = getRelocType(Target, Fixup);
478
Dan Gohmand934cb82017-02-24 23:18:00 +0000479 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000480 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000481
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000482 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB,
483 // R_WEBASSEMBLY_SECTION_OFFSET_I32 or R_WEBASSEMBLY_FUNCTION_OFFSET_I32
484 // are currently required to be against a named symbol.
Sam Cleggb7a54692018-02-16 18:06:05 +0000485 // TODO(sbc): Add support for relocations against unnamed temporaries such
486 // as those generated by llvm's `blockaddress`.
487 // See: test/MC/WebAssembly/blockaddress.ll
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000488 if (SymA->getName().empty() &&
489 !(Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB ||
490 Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
491 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32))
Sam Cleggb7a54692018-02-16 18:06:05 +0000492 report_fatal_error("relocations against un-named temporaries are not yet "
493 "supported by wasm");
494
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000495 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000496 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000497 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000498 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000499 } else if (FixupSection.getKind().isMetadata()) {
500 assert(FixupSection.getSectionName().startswith(".debug_"));
501 CustomSectionsRelocations[&FixupSection].push_back(Rec);
502 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000503 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000504 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000505}
506
Dan Gohmand934cb82017-02-24 23:18:00 +0000507// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
508// to allow patching.
509static void
510WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
511 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000512 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000513 assert(SizeLen == 5);
514 Stream.pwrite((char *)Buffer, SizeLen, Offset);
515}
516
517// Write X as an signed LEB value at offset Offset in Stream, padded
518// to allow patching.
519static void
520WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
521 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000522 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000523 assert(SizeLen == 5);
524 Stream.pwrite((char *)Buffer, SizeLen, Offset);
525}
526
527// Write X as a plain integer value at offset Offset in Stream.
528static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
529 uint8_t Buffer[4];
530 support::endian::write32le(Buffer, X);
531 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
532}
533
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000534static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
535 if (Symbol.isVariable()) {
536 const MCExpr *Expr = Symbol.getVariableValue();
537 auto *Inner = cast<MCSymbolRefExpr>(Expr);
538 return cast<MCSymbolWasm>(&Inner->getSymbol());
539 }
540 return &Symbol;
541}
542
Dan Gohmand934cb82017-02-24 23:18:00 +0000543// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000544// by RelEntry. This value isn't used by the static linker; it just serves
545// to make the object format more readable and more likely to be directly
546// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000547uint32_t
548WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000549 switch (RelEntry.Type) {
550 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000551 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
552 // Provisional value is table address of the resolved symbol itself
553 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
554 assert(Sym->isFunction());
555 return TableIndices[Sym];
556 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000557 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000558 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000559 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000560 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
561 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
562 // Provisional value is function/global Wasm index
563 if (!WasmIndices.count(RelEntry.Symbol))
564 report_fatal_error("symbol not found in wasm index space: " +
565 RelEntry.Symbol->getName());
566 return WasmIndices[RelEntry.Symbol];
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000567 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
568 const auto &Section =
569 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
570 return Section.getSectionOffset() + RelEntry.Addend;
571 }
572 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
573 const auto &Section = *CustomSectionSymbols.find(RelEntry.Symbol)->second;
574 return Section.getSectionOffset() + RelEntry.Addend;
575 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000576 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
577 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
578 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000579 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000580 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
581 // For undefined symbols, use zero
582 if (!Sym->isDefined())
583 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000584 const wasm::WasmDataReference &Ref = DataLocations[Sym];
585 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000586 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000587 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000588 }
589 default:
590 llvm_unreachable("invalid relocation type");
591 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000592}
593
Sam Clegg759631c2017-09-15 20:54:59 +0000594static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000595 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000596 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
597
Sam Clegg63ebb812017-09-29 16:50:08 +0000598 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
599
Sam Clegg759631c2017-09-15 20:54:59 +0000600 for (const MCFragment &Frag : DataSection) {
601 if (Frag.hasInstructions())
602 report_fatal_error("only data supported in data sections");
603
604 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
605 if (Align->getValueSize() != 1)
606 report_fatal_error("only byte values supported for alignment");
607 // If nops are requested, use zeros, as this is the data section.
608 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
609 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
610 Align->getAlignment()),
611 DataBytes.size() +
612 Align->getMaxBytesToEmit());
613 DataBytes.resize(Size, Value);
614 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000615 int64_t Size;
616 if (!Fill->getSize().evaluateAsAbsolute(Size))
617 llvm_unreachable("The fill should be an assembler constant");
618 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000619 } else {
620 const auto &DataFrag = cast<MCDataFragment>(Frag);
621 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
622
623 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
624 }
625 }
626
627 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
628}
629
Sam Clegg60ec3032018-01-23 01:23:17 +0000630uint32_t
631WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
632 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000633 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000634 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000635 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000636 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000637 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000638
639 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6c899ba2018-02-23 05:08:34 +0000640 report_fatal_error("symbol not found in symbol index space: " +
Sam Clegg60ec3032018-01-23 01:23:17 +0000641 RelEntry.Symbol->getName());
642 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000643}
644
Dan Gohmand934cb82017-02-24 23:18:00 +0000645// Apply the portions of the relocation records that we can handle ourselves
646// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000647void WasmObjectWriter::applyRelocations(
648 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
649 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000650 for (const WasmRelocationEntry &RelEntry : Relocations) {
651 uint64_t Offset = ContentsOffset +
652 RelEntry.FixupSection->getSectionOffset() +
653 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000654
Sam Cleggb7787fd2017-06-20 04:04:59 +0000655 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000656 uint32_t Value = getProvisionalValue(RelEntry);
657
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000658 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000659 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000660 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000661 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
662 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000663 WritePatchableLEB(Stream, Value, Offset);
664 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000665 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
666 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000667 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
668 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000669 WriteI32(Stream, Value, Offset);
670 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000671 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
672 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
673 WritePatchableSLEB(Stream, Value, Offset);
674 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000675 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000676 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000677 }
678 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000679}
680
Sam Clegg9e15f352017-06-03 02:01:24 +0000681void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000682 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000683 if (FunctionTypes.empty())
684 return;
685
686 SectionBookkeeping Section;
687 startSection(Section, wasm::WASM_SEC_TYPE);
688
689 encodeULEB128(FunctionTypes.size(), getStream());
690
691 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000692 write8(wasm::WASM_TYPE_FUNC);
Sam Clegg9e15f352017-06-03 02:01:24 +0000693 encodeULEB128(FuncTy.Params.size(), getStream());
694 for (wasm::ValType Ty : FuncTy.Params)
695 writeValueType(Ty);
696 encodeULEB128(FuncTy.Returns.size(), getStream());
697 for (wasm::ValType Ty : FuncTy.Returns)
698 writeValueType(Ty);
699 }
700
701 endSection(Section);
702}
703
Sam Clegg8defa952018-02-12 22:41:29 +0000704void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000705 uint32_t DataSize,
706 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000707 if (Imports.empty())
708 return;
709
Sam Cleggf950b242017-12-11 23:03:38 +0000710 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
711
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 SectionBookkeeping Section;
713 startSection(Section, wasm::WASM_SEC_IMPORT);
714
715 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000716 for (const wasm::WasmImport &Import : Imports) {
717 writeString(Import.Module);
718 writeString(Import.Field);
Sam Clegg03e101f2018-03-01 18:06:21 +0000719 write8(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000720
721 switch (Import.Kind) {
722 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000723 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000724 break;
725 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg03e101f2018-03-01 18:06:21 +0000726 write8(Import.Global.Type);
727 write8(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000728 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000729 case wasm::WASM_EXTERNAL_MEMORY:
730 encodeULEB128(0, getStream()); // flags
731 encodeULEB128(NumPages, getStream()); // initial
732 break;
733 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg03e101f2018-03-01 18:06:21 +0000734 write8(Import.Table.ElemType);
Sam Cleggf950b242017-12-11 23:03:38 +0000735 encodeULEB128(0, getStream()); // flags
736 encodeULEB128(NumElements, getStream()); // initial
737 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000738 default:
739 llvm_unreachable("unsupported import kind");
740 }
741 }
742
743 endSection(Section);
744}
745
Sam Clegg457fb0b2017-09-15 19:50:44 +0000746void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000747 if (Functions.empty())
748 return;
749
750 SectionBookkeeping Section;
751 startSection(Section, wasm::WASM_SEC_FUNCTION);
752
753 encodeULEB128(Functions.size(), getStream());
754 for (const WasmFunction &Func : Functions)
755 encodeULEB128(Func.Type, getStream());
756
757 endSection(Section);
758}
759
Sam Clegg7c395942017-09-14 23:07:53 +0000760void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000761 if (Globals.empty())
762 return;
763
764 SectionBookkeeping Section;
765 startSection(Section, wasm::WASM_SEC_GLOBAL);
766
767 encodeULEB128(Globals.size(), getStream());
768 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000769 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
770 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000771
Sam Clegg6e7f1822018-01-31 19:50:14 +0000772 write8(wasm::WASM_OPCODE_I32_CONST);
773 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000774 write8(wasm::WASM_OPCODE_END);
775 }
776
777 endSection(Section);
778}
779
Sam Clegg8defa952018-02-12 22:41:29 +0000780void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000781 if (Exports.empty())
782 return;
783
784 SectionBookkeeping Section;
785 startSection(Section, wasm::WASM_SEC_EXPORT);
786
787 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000788 for (const wasm::WasmExport &Export : Exports) {
789 writeString(Export.Name);
Sam Clegg03e101f2018-03-01 18:06:21 +0000790 write8(Export.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 encodeULEB128(Export.Index, getStream());
792 }
793
794 endSection(Section);
795}
796
Sam Clegg457fb0b2017-09-15 19:50:44 +0000797void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000798 if (TableElems.empty())
799 return;
800
801 SectionBookkeeping Section;
802 startSection(Section, wasm::WASM_SEC_ELEM);
803
804 encodeULEB128(1, getStream()); // number of "segments"
805 encodeULEB128(0, getStream()); // the table index
806
807 // init expr for starting offset
808 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000809 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000810 write8(wasm::WASM_OPCODE_END);
811
812 encodeULEB128(TableElems.size(), getStream());
813 for (uint32_t Elem : TableElems)
814 encodeULEB128(Elem, getStream());
815
816 endSection(Section);
817}
818
Sam Clegg457fb0b2017-09-15 19:50:44 +0000819void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
820 const MCAsmLayout &Layout,
821 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000822 if (Functions.empty())
823 return;
824
825 SectionBookkeeping Section;
826 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000827 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000828
829 encodeULEB128(Functions.size(), getStream());
830
831 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000832 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
Sam Clegg9e15f352017-06-03 02:01:24 +0000834 int64_t Size = 0;
835 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
836 report_fatal_error(".size expression must be evaluatable");
837
838 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000839 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 Asm.writeSectionData(&FuncSection, Layout);
841 }
842
Sam Clegg9e15f352017-06-03 02:01:24 +0000843 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000844 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000845
846 endSection(Section);
847}
848
Sam Clegg6c899ba2018-02-23 05:08:34 +0000849void WasmObjectWriter::writeDataSection() {
850 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000851 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000852
853 SectionBookkeeping Section;
854 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000855 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000856
Sam Clegg6c899ba2018-02-23 05:08:34 +0000857 encodeULEB128(DataSegments.size(), getStream()); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000858
Sam Clegg6c899ba2018-02-23 05:08:34 +0000859 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000860 encodeULEB128(0, getStream()); // memory index
861 write8(wasm::WASM_OPCODE_I32_CONST);
862 encodeSLEB128(Segment.Offset, getStream()); // offset
863 write8(wasm::WASM_OPCODE_END);
864 encodeULEB128(Segment.Data.size(), getStream()); // size
865 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
866 writeBytes(Segment.Data); // data
867 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000868
869 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000870 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
872 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000873}
874
Sam Clegg6f08c842018-04-24 18:11:36 +0000875void WasmObjectWriter::writeRelocSection(
876 uint32_t SectionIndex, StringRef Name,
877 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000878 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
879 // for descriptions of the reloc sections.
880
Sam Clegg6f08c842018-04-24 18:11:36 +0000881 if (Relocations.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000882 return;
883
884 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000885 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
Sam Clegg6f08c842018-04-24 18:11:36 +0000887 raw_pwrite_stream &Stream = getStream();
Sam Clegg9e15f352017-06-03 02:01:24 +0000888
Sam Clegg6f08c842018-04-24 18:11:36 +0000889 encodeULEB128(SectionIndex, Stream);
890 encodeULEB128(Relocations.size(), Stream);
891 for (const WasmRelocationEntry& RelEntry : Relocations) {
892 uint64_t Offset = RelEntry.Offset +
893 RelEntry.FixupSection->getSectionOffset();
894 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000895
Sam Clegg6f08c842018-04-24 18:11:36 +0000896 write8(RelEntry.Type);
897 encodeULEB128(Offset, Stream);
898 encodeULEB128(Index, Stream);
899 if (RelEntry.hasAddend())
900 encodeSLEB128(RelEntry.Addend, Stream);
901 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000902
903 endSection(Section);
904}
905
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000906void WasmObjectWriter::writeCustomRelocSections() {
907 for (const auto &Sec : CustomSections) {
908 auto &Relocations = CustomSectionsRelocations[Sec.Section];
909 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
910 }
911}
912
Sam Clegg9e15f352017-06-03 02:01:24 +0000913void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000914 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000915 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000916 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000917 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000918 startCustomSection(Section, "linking");
Sam Clegg6bb5a412018-04-26 18:15:32 +0000919 encodeULEB128(wasm::WasmMetadataVersion, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000920
Sam Clegg6bb5a412018-04-26 18:15:32 +0000921 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000922 if (SymbolInfos.size() != 0) {
923 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
924 encodeULEB128(SymbolInfos.size(), getStream());
925 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
926 encodeULEB128(Sym.Kind, getStream());
927 encodeULEB128(Sym.Flags, getStream());
928 switch (Sym.Kind) {
929 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
930 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
931 encodeULEB128(Sym.ElementIndex, getStream());
932 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
933 writeString(Sym.Name);
934 break;
935 case wasm::WASM_SYMBOL_TYPE_DATA:
936 writeString(Sym.Name);
937 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
938 encodeULEB128(Sym.DataRef.Segment, getStream());
939 encodeULEB128(Sym.DataRef.Offset, getStream());
940 encodeULEB128(Sym.DataRef.Size, getStream());
941 }
942 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000943 case wasm::WASM_SYMBOL_TYPE_SECTION: {
944 const uint32_t SectionIndex =
945 CustomSections[Sym.ElementIndex].OutputIndex;
946 encodeULEB128(SectionIndex, getStream());
947 break;
948 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000949 default:
950 llvm_unreachable("unexpected kind");
951 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000952 }
953 endSection(SubSection);
954 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000955
Sam Clegg6c899ba2018-02-23 05:08:34 +0000956 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000957 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000958 encodeULEB128(DataSegments.size(), getStream());
959 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000960 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000961 encodeULEB128(Segment.Alignment, getStream());
962 encodeULEB128(Segment.Flags, getStream());
963 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000964 endSection(SubSection);
965 }
966
Sam Cleggbafe6902017-12-15 00:17:10 +0000967 if (!InitFuncs.empty()) {
968 startSection(SubSection, wasm::WASM_INIT_FUNCS);
969 encodeULEB128(InitFuncs.size(), getStream());
970 for (auto &StartFunc : InitFuncs) {
971 encodeULEB128(StartFunc.first, getStream()); // priority
972 encodeULEB128(StartFunc.second, getStream()); // function index
973 }
974 endSection(SubSection);
975 }
976
Sam Cleggea7cace2018-01-09 23:43:14 +0000977 if (Comdats.size()) {
978 startSection(SubSection, wasm::WASM_COMDAT_INFO);
979 encodeULEB128(Comdats.size(), getStream());
980 for (const auto &C : Comdats) {
981 writeString(C.first);
982 encodeULEB128(0, getStream()); // flags for future use
983 encodeULEB128(C.second.size(), getStream());
984 for (const WasmComdatEntry &Entry : C.second) {
985 encodeULEB128(Entry.Kind, getStream());
986 encodeULEB128(Entry.Index, getStream());
987 }
988 }
989 endSection(SubSection);
990 }
991
Sam Clegg9e15f352017-06-03 02:01:24 +0000992 endSection(Section);
993}
994
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000995void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
996 const MCAsmLayout &Layout) {
997 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000998 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000999 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001000 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001001
1002 Sec->setSectionOffset(getStream().tell() - Section.ContentsOffset);
1003 Asm.writeSectionData(Sec, Layout);
1004
1005 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1006 CustomSection.OutputIndex = Section.Index;
1007
Sam Cleggcfd44a22018-04-05 17:01:39 +00001008 endSection(Section);
1009 }
1010}
1011
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001012void WasmObjectWriter::updateCustomSectionRelocations(
1013 const SmallVector<WasmFunction, 4> &Functions, const MCAsmLayout &Layout) {
1014 std::map<const MCSection *, const MCSymbolWasm *> SectionSymbols;
1015 for (const auto &P : CustomSectionSymbols)
1016 SectionSymbols[P.second] = P.first;
1017 std::map<const MCSection *, const MCSymbolWasm *> FuncSymbols;
1018 for (const auto &FuncInfo : Functions)
1019 FuncSymbols[&FuncInfo.Sym->getSection()] = FuncInfo.Sym;
1020
1021 // Patch relocation records for R_WEBASSEMBLY_FUNCTION_OFFSET_I32 and
1022 // R_WEBASSEMBLY_SECTION_OFFSET_I32. The Addend is stuffed the offset from
1023 // the beginning of the function or custom section -- all such relocations
1024 // target the function or custom section starts.
1025 for (auto &Section : CustomSections) {
1026 auto &Relocations = CustomSectionsRelocations[Section.Section];
1027 for (WasmRelocationEntry &RelEntry : Relocations) {
1028 switch (RelEntry.Type) {
1029 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32: {
1030 assert(RelEntry.hasAddend());
1031 auto &Section =
1032 static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
1033 RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
1034 RelEntry.Symbol = FuncSymbols[&Section];
1035 break;
1036 }
1037 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
1038 assert(RelEntry.hasAddend());
1039 auto &Section =
1040 static_cast<MCSectionWasm &>(RelEntry.Symbol->getSection());
1041 RelEntry.Addend += Layout.getSymbolOffset(*RelEntry.Symbol);
1042 RelEntry.Symbol = SectionSymbols[&Section];
1043 break;
1044 }
1045 default:
1046 break;
1047 }
1048 }
1049
1050 // Apply fixups.
1051 applyRelocations(Relocations, Section.OutputContentsOffset);
1052 }
1053}
1054
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001055uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
1056 assert(Symbol.isFunction());
1057 assert(TypeIndices.count(&Symbol));
1058 return TypeIndices[&Symbol];
1059}
1060
1061uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
1062 assert(Symbol.isFunction());
1063
1064 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001065 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
1066 F.Returns = ResolvedSym->getReturns();
1067 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001068
1069 auto Pair =
1070 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1071 if (Pair.second)
1072 FunctionTypes.push_back(F);
1073 TypeIndices[&Symbol] = Pair.first->second;
1074
1075 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
1076 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
1077 return Pair.first->second;
1078}
1079
Dan Gohman18eafb62017-02-22 01:23:18 +00001080void WasmObjectWriter::writeObject(MCAssembler &Asm,
1081 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001082 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001083 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001084
1085 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001086 SmallVector<WasmFunction, 4> Functions;
1087 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001088 SmallVector<wasm::WasmImport, 4> Imports;
1089 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001090 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001091 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001092 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001093 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001094
Sam Cleggf950b242017-12-11 23:03:38 +00001095 // For now, always emit the memory import, since loads and stores are not
1096 // valid without it. In the future, we could perhaps be more clever and omit
1097 // it if there are no loads or stores.
1098 MCSymbolWasm *MemorySym =
1099 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001100 wasm::WasmImport MemImport;
1101 MemImport.Module = MemorySym->getModuleName();
1102 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001103 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1104 Imports.push_back(MemImport);
1105
1106 // For now, always emit the table section, since indirect calls are not
1107 // valid without it. In the future, we could perhaps be more clever and omit
1108 // it if there are no indirect calls.
1109 MCSymbolWasm *TableSym =
1110 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001111 wasm::WasmImport TableImport;
1112 TableImport.Module = TableSym->getModuleName();
1113 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001114 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001115 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001116 Imports.push_back(TableImport);
1117
Nicholas Wilson586320c2018-02-28 17:19:48 +00001118 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1119 // symbols. This must be done before populating WasmIndices for defined
1120 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001121 for (const MCSymbol &S : Asm.symbols()) {
1122 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1123
1124 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001125 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001126 if (WS.isFunction())
1127 registerFunctionType(WS);
1128
1129 if (WS.isTemporary())
1130 continue;
1131
1132 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001133 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001134 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001135 wasm::WasmImport Import;
1136 Import.Module = WS.getModuleName();
1137 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001138 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001139 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001140 Imports.push_back(Import);
1141 WasmIndices[&WS] = NumFunctionImports++;
1142 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001143 if (WS.isWeak())
1144 report_fatal_error("undefined global symbol cannot be weak");
1145
Sam Clegg6c899ba2018-02-23 05:08:34 +00001146 wasm::WasmImport Import;
1147 Import.Module = WS.getModuleName();
1148 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001149 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001150 Import.Global = WS.getGlobalType();
1151 Imports.push_back(Import);
1152 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001153 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001154 }
1155 }
1156
Nicholas Wilson586320c2018-02-28 17:19:48 +00001157 // Populate DataSegments, which must be done before populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001158 for (MCSection &Sec : Asm) {
1159 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Cleggcfd44a22018-04-05 17:01:39 +00001160
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001161 if (Section.getSectionName().startswith(".custom_section.")) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001162 if (Section.getFragmentList().empty())
1163 continue;
1164 if (Section.getFragmentList().size() != 1)
1165 report_fatal_error(
1166 "only one .custom_section section fragment supported");
1167 const MCFragment &Frag = *Section.begin();
1168 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1169 report_fatal_error("only data supported in .custom_section section");
1170 const auto &DataFrag = cast<MCDataFragment>(Frag);
1171 if (!DataFrag.getFixups().empty())
1172 report_fatal_error("fixups not supported in .custom_section section");
1173 StringRef UserName = Section.getSectionName().substr(16);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001174 CustomSections.emplace_back(UserName, &Section);
Sam Cleggcfd44a22018-04-05 17:01:39 +00001175 continue;
1176 }
1177
Sam Clegg12fd3da2017-10-20 21:28:38 +00001178 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001179 continue;
1180
Sam Cleggbafe6902017-12-15 00:17:10 +00001181 // .init_array sections are handled specially elsewhere.
1182 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1183 continue;
1184
Sam Clegg329e76d2018-01-31 04:21:44 +00001185 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001186 DataSize = alignTo(DataSize, Section.getAlignment());
1187 DataSegments.emplace_back();
1188 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001189 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001190 Segment.Offset = DataSize;
1191 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001192 addData(Segment.Data, Section);
1193 Segment.Alignment = Section.getAlignment();
1194 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001195 DataSize += Segment.Data.size();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001196 Section.setSegmentIndex(SegmentIndex);
Sam Cleggea7cace2018-01-09 23:43:14 +00001197
1198 if (const MCSymbolWasm *C = Section.getGroup()) {
1199 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001200 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001201 }
Sam Clegg759631c2017-09-15 20:54:59 +00001202 }
1203
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001204 // Create symbols for debug/custom sections.
1205 for (MCSection &Sec : Asm) {
1206 auto &DebugSection = static_cast<MCSectionWasm &>(Sec);
1207 StringRef SectionName = DebugSection.getSectionName();
1208
1209 // TODO: Add support for non-debug metadata sections?
1210 if (!Sec.getKind().isMetadata() || !SectionName.startswith(".debug_"))
1211 continue;
1212
1213 uint32_t ElementIndex = CustomSections.size();
1214 CustomSections.emplace_back(SectionName, &DebugSection);
1215
1216 MCSymbolWasm *SectionSym =
1217 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol(SectionName));
1218 CustomSectionSymbols[SectionSym] = &DebugSection;
1219
1220 wasm::WasmSymbolInfo Info;
1221 Info.Name = SectionSym->getName();
1222 Info.Kind = wasm::WASM_SYMBOL_TYPE_SECTION;
Sam Cleggd5504a02018-04-27 00:17:21 +00001223 Info.Flags = wasm::WASM_SYMBOL_BINDING_LOCAL;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001224 Info.ElementIndex = ElementIndex;
1225 SymbolIndices[SectionSym] = SymbolInfos.size();
1226 SymbolInfos.emplace_back(Info);
1227 }
1228
Nicholas Wilson586320c2018-02-28 17:19:48 +00001229 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001230 for (const MCSymbol &S : Asm.symbols()) {
1231 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1232 // or used in relocations.
1233 if (S.isTemporary() && S.getName().empty())
1234 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001235
Dan Gohmand934cb82017-02-24 23:18:00 +00001236 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001237 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001238 << " isDefined=" << S.isDefined()
1239 << " isExternal=" << S.isExternal()
1240 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001241 << " isFunction=" << WS.isFunction()
1242 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001243 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001244 << " isVariable=" << WS.isVariable() << "\n");
1245
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001246 if (WS.isVariable())
1247 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001248 if (WS.isComdat() && !WS.isDefined())
1249 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001250
Dan Gohmand934cb82017-02-24 23:18:00 +00001251 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001252 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001253 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001254 if (WS.getOffset() != 0)
1255 report_fatal_error(
1256 "function sections must contain one function each");
1257
1258 if (WS.getSize() == 0)
1259 report_fatal_error(
1260 "function symbols must have a size set with .size");
1261
Sam Clegg6c899ba2018-02-23 05:08:34 +00001262 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001263 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001264 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001265 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001266 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001267 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001268 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001269
1270 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1271 if (const MCSymbolWasm *C = Section.getGroup()) {
1272 Comdats[C->getName()].emplace_back(
1273 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1274 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001275 } else {
1276 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001277 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001278 }
1279
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001280 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001281 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001282 if (WS.isTemporary() && !WS.getSize())
1283 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001284
Sam Clegg6c899ba2018-02-23 05:08:34 +00001285 if (!WS.isDefined()) {
1286 DEBUG(dbgs() << " -> segment index: -1");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001287 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001288 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001289
Sam Cleggfe6414b2017-06-21 23:46:41 +00001290 if (!WS.getSize())
1291 report_fatal_error("data symbols must have a size set with .size: " +
1292 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001293
Sam Cleggfe6414b2017-06-21 23:46:41 +00001294 int64_t Size = 0;
1295 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1296 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001297
Sam Clegg759631c2017-09-15 20:54:59 +00001298 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001299 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001300
Sam Clegg6c899ba2018-02-23 05:08:34 +00001301 // For each data symbol, export it in the symtab as a reference to the
1302 // corresponding Wasm data segment.
1303 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1304 DataSection.getSegmentIndex(),
1305 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1306 static_cast<uint32_t>(Size)};
1307 DataLocations[&WS] = Ref;
1308 DEBUG(dbgs() << " -> segment index: " << Ref.Segment);
1309 } else {
1310 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001311 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001312 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001313
Eric Christopher545932b2018-02-23 21:14:47 +00001314 // An import; the index was assigned above
1315 DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second
1316 << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001317 }
1318 }
1319
Nicholas Wilson586320c2018-02-28 17:19:48 +00001320 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1321 // process these in a separate pass because we need to have processed the
1322 // target of the alias before the alias itself and the symbols are not
1323 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001324 for (const MCSymbol &S : Asm.symbols()) {
1325 if (!S.isVariable())
1326 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001327
Sam Cleggcd65f692018-01-11 23:59:16 +00001328 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001329
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001330 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001331 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1332 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001333 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001334
Sam Clegg6c899ba2018-02-23 05:08:34 +00001335 if (WS.isFunction()) {
1336 assert(WasmIndices.count(ResolvedSym) > 0);
1337 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1338 WasmIndices[&WS] = WasmIndex;
1339 DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
1340 } else if (WS.isData()) {
1341 assert(DataLocations.count(ResolvedSym) > 0);
1342 const wasm::WasmDataReference &Ref =
1343 DataLocations.find(ResolvedSym)->second;
1344 DataLocations[&WS] = Ref;
1345 DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
1346 } else {
1347 report_fatal_error("don't yet support global aliases");
1348 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001349 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001350
Nicholas Wilson586320c2018-02-28 17:19:48 +00001351 // Finally, populate the symbol table itself, in its "natural" order.
1352 for (const MCSymbol &S : Asm.symbols()) {
1353 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1354 if (WS.isTemporary() && WS.getName().empty())
1355 continue;
1356 if (WS.isComdat() && !WS.isDefined())
1357 continue;
1358 if (WS.isTemporary() && WS.isData() && !WS.getSize())
1359 continue;
1360
1361 uint32_t Flags = 0;
1362 if (WS.isWeak())
1363 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1364 if (WS.isHidden())
1365 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1366 if (!WS.isExternal() && WS.isDefined())
1367 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1368 if (WS.isUndefined())
1369 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1370
1371 wasm::WasmSymbolInfo Info;
1372 Info.Name = WS.getName();
1373 Info.Kind = WS.getType();
1374 Info.Flags = Flags;
1375 if (!WS.isData())
1376 Info.ElementIndex = WasmIndices.find(&WS)->second;
1377 else if (WS.isDefined())
1378 Info.DataRef = DataLocations.find(&WS)->second;
1379 SymbolIndices[&WS] = SymbolInfos.size();
1380 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001381 }
1382
Sam Clegg6006e092017-12-22 20:31:39 +00001383 {
1384 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001385 // Functions referenced by a relocation need to put in the table. This is
1386 // purely to make the object file's provisional values readable, and is
1387 // ignored by the linker, which re-calculates the relocations itself.
1388 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1389 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1390 return;
1391 assert(Rel.Symbol->isFunction());
1392 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001393 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001394 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1395 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1396 DEBUG(dbgs() << " -> adding " << WS.getName()
1397 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001398 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001399 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001400 }
1401 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001402
Sam Clegg6006e092017-12-22 20:31:39 +00001403 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1404 HandleReloc(RelEntry);
1405 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1406 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001407 }
1408
Sam Cleggbafe6902017-12-15 00:17:10 +00001409 // Translate .init_array section contents into start functions.
1410 for (const MCSection &S : Asm) {
1411 const auto &WS = static_cast<const MCSectionWasm &>(S);
1412 if (WS.getSectionName().startswith(".fini_array"))
1413 report_fatal_error(".fini_array sections are unsupported");
1414 if (!WS.getSectionName().startswith(".init_array"))
1415 continue;
1416 if (WS.getFragmentList().empty())
1417 continue;
1418 if (WS.getFragmentList().size() != 2)
1419 report_fatal_error("only one .init_array section fragment supported");
1420 const MCFragment &AlignFrag = *WS.begin();
1421 if (AlignFrag.getKind() != MCFragment::FT_Align)
1422 report_fatal_error(".init_array section should be aligned");
1423 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1424 report_fatal_error(".init_array section should be aligned for pointers");
1425 const MCFragment &Frag = *std::next(WS.begin());
1426 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1427 report_fatal_error("only data supported in .init_array section");
1428 uint16_t Priority = UINT16_MAX;
1429 if (WS.getSectionName().size() != 11) {
1430 if (WS.getSectionName()[11] != '.')
1431 report_fatal_error(".init_array section priority should start with '.'");
1432 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1433 report_fatal_error("invalid .init_array section priority");
1434 }
1435 const auto &DataFrag = cast<MCDataFragment>(Frag);
1436 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1437 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1438 *end = (const uint8_t *)Contents.data() + Contents.size();
1439 p != end; ++p) {
1440 if (*p != 0)
1441 report_fatal_error("non-symbolic data in .init_array section");
1442 }
1443 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1444 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1445 const MCExpr *Expr = Fixup.getValue();
1446 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1447 if (!Sym)
1448 report_fatal_error("fixups in .init_array should be symbol references");
1449 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1450 report_fatal_error("symbols in .init_array should be for functions");
1451 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1452 if (I == SymbolIndices.end())
1453 report_fatal_error("symbols in .init_array should be defined");
1454 uint32_t Index = I->second;
1455 InitFuncs.push_back(std::make_pair(Priority, Index));
1456 }
1457 }
1458
Dan Gohman18eafb62017-02-22 01:23:18 +00001459 // Write out the Wasm header.
1460 writeHeader(Asm);
1461
Sam Clegg9e15f352017-06-03 02:01:24 +00001462 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001463 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001464 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001465 // Skip the "table" section; we import the table instead.
1466 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001467 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001468 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001469 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001470 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001471 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001472 writeCustomSections(Asm, Layout);
1473 updateCustomSectionRelocations(Functions, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001474 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001475 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1476 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001477 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001478
Dan Gohmand934cb82017-02-24 23:18:00 +00001479 // TODO: Translate the .comment section to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001480}
1481
Lang Hames60fbc7c2017-10-10 16:28:07 +00001482std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001483llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1484 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001485 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001486}