blob: 44f5335b658e135ca00476711572db311911bc6e [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;
51 // Where the contents of the section starts (after the header).
52 uint64_t ContentsOffset;
53};
54
Sam Clegg9e15f352017-06-03 02:01:24 +000055// The signature of a wasm function, in a struct capable of being used as a
56// DenseMap key.
57struct WasmFunctionType {
58 // Support empty and tombstone instances, needed by DenseMap.
59 enum { Plain, Empty, Tombstone } State;
60
61 // The return types of the function.
62 SmallVector<wasm::ValType, 1> Returns;
63
64 // The parameter types of the function.
65 SmallVector<wasm::ValType, 4> Params;
66
67 WasmFunctionType() : State(Plain) {}
68
69 bool operator==(const WasmFunctionType &Other) const {
70 return State == Other.State && Returns == Other.Returns &&
71 Params == Other.Params;
72 }
73};
74
75// Traits for using WasmFunctionType in a DenseMap.
76struct WasmFunctionTypeDenseMapInfo {
77 static WasmFunctionType getEmptyKey() {
78 WasmFunctionType FuncTy;
79 FuncTy.State = WasmFunctionType::Empty;
80 return FuncTy;
81 }
82 static WasmFunctionType getTombstoneKey() {
83 WasmFunctionType FuncTy;
84 FuncTy.State = WasmFunctionType::Tombstone;
85 return FuncTy;
86 }
87 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
88 uintptr_t Value = FuncTy.State;
89 for (wasm::ValType Ret : FuncTy.Returns)
90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
91 for (wasm::ValType Param : FuncTy.Params)
92 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
93 return Value;
94 }
95 static bool isEqual(const WasmFunctionType &LHS,
96 const WasmFunctionType &RHS) {
97 return LHS == RHS;
98 }
99};
100
Sam Clegg7c395942017-09-14 23:07:53 +0000101// A wasm data segment. A wasm binary contains only a single data section
102// but that can contain many segments, each with their own virtual location
103// in memory. Each MCSection data created by llvm is modeled as its own
104// wasm data segment.
105struct WasmDataSegment {
106 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000107 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000108 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000109 uint32_t Alignment;
110 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000111 SmallVector<char, 4> Data;
112};
113
Sam Clegg9e15f352017-06-03 02:01:24 +0000114// A wasm function to be written into the function section.
115struct WasmFunction {
116 int32_t Type;
117 const MCSymbolWasm *Sym;
118};
119
Sam Clegg9e15f352017-06-03 02:01:24 +0000120// A wasm global to be written into the global section.
121struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000122 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000123 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000124};
125
Sam Cleggea7cace2018-01-09 23:43:14 +0000126// Information about a single item which is part of a COMDAT. For each data
127// segment or function which is in the COMDAT, there is a corresponding
128// WasmComdatEntry.
129struct WasmComdatEntry {
130 unsigned Kind;
131 uint32_t Index;
132};
133
Sam Clegg6dc65e92017-06-06 16:38:59 +0000134// Information about a single relocation.
135struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000136 uint64_t Offset; // Where is the relocation.
137 const MCSymbolWasm *Symbol; // The symbol to relocate with.
138 int64_t Addend; // A value to add to the symbol.
139 unsigned Type; // The type of the relocation.
140 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000141
142 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
143 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000144 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000145 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
146 FixupSection(FixupSection) {}
147
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000148 bool hasAddend() const {
149 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000150 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
151 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
152 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000153 return true;
154 default:
155 return false;
156 }
157 }
158
Sam Clegg6dc65e92017-06-06 16:38:59 +0000159 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000160 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000161 << ", Type=" << Type
162 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000163 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000164
Aaron Ballman615eb472017-10-15 14:32:27 +0000165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000166 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
167#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000168};
169
Sam Cleggcfd44a22018-04-05 17:01:39 +0000170struct WasmCustomSection {
171 StringRef Name;
172 const SmallVectorImpl<char> &Contents;
173
174 WasmCustomSection(StringRef Name, const SmallVectorImpl<char> &Contents)
175 : Name(Name), Contents(Contents) {}
176};
177
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000178#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000179raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000180 Rel.print(OS);
181 return OS;
182}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000183#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000184
Dan Gohman18eafb62017-02-22 01:23:18 +0000185class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000186 /// The target specific Wasm writer instance.
187 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
188
Dan Gohmand934cb82017-02-24 23:18:00 +0000189 // Relocations for fixing up references in the code section.
190 std::vector<WasmRelocationEntry> CodeRelocations;
191
192 // Relocations for fixing up references in the data section.
193 std::vector<WasmRelocationEntry> DataRelocations;
194
Dan Gohmand934cb82017-02-24 23:18:00 +0000195 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000196 // Maps function symbols to the index of the type of the function
197 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000198 // Maps function symbols to the table element index space. Used
199 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000200 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000201 // Maps function/global symbols to the (shared) Symbol index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000202 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000203 // Maps function/global symbols to the function/global Wasm index space.
204 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
205 // Maps data symbols to the Wasm segment and offset/size with the segment.
206 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000207
208 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
209 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000210 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000211 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000212 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Cleggcfd44a22018-04-05 17:01:39 +0000213 std::vector<WasmCustomSection> CustomSections;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000214 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000215 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000216
Dan Gohman18eafb62017-02-22 01:23:18 +0000217 // TargetObjectWriter wrappers.
218 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000219 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
220 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000221 }
222
Dan Gohmand934cb82017-02-24 23:18:00 +0000223 void startSection(SectionBookkeeping &Section, unsigned SectionId,
224 const char *Name = nullptr);
225 void endSection(SectionBookkeeping &Section);
226
Dan Gohman18eafb62017-02-22 01:23:18 +0000227public:
Lang Hames1301a872017-10-10 01:15:10 +0000228 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
229 raw_pwrite_stream &OS)
230 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
231 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000232
Dan Gohman18eafb62017-02-22 01:23:18 +0000233 ~WasmObjectWriter() override;
234
Dan Gohman0917c9e2018-01-15 17:06:23 +0000235private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000236 void reset() override {
237 CodeRelocations.clear();
238 DataRelocations.clear();
239 TypeIndices.clear();
240 SymbolIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000241 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000242 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000243 DataLocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000244 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000245 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000246 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000247 DataSegments.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000248 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000249 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000250 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000251 }
252
Dan Gohman18eafb62017-02-22 01:23:18 +0000253 void writeHeader(const MCAssembler &Asm);
254
255 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
256 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000257 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000258
259 void executePostLayoutBinding(MCAssembler &Asm,
260 const MCAsmLayout &Layout) override;
261
262 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000263
Sam Cleggb7787fd2017-06-20 04:04:59 +0000264 void writeString(const StringRef Str) {
265 encodeULEB128(Str.size(), getStream());
266 writeBytes(Str);
267 }
268
Sam Clegg9e15f352017-06-03 02:01:24 +0000269 void writeValueType(wasm::ValType Ty) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000270 write8(static_cast<uint8_t>(Ty));
Sam Clegg9e15f352017-06-03 02:01:24 +0000271 }
272
Sam Clegg457fb0b2017-09-15 19:50:44 +0000273 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000274 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000275 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000276 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000277 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000278 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000279 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000280 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000281 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000282 void writeDataSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000283 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000284 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000285 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000286 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000287 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000288 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Cleggcfd44a22018-04-05 17:01:39 +0000289 void writeUserCustomSections(ArrayRef<WasmCustomSection> CustomSections);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000290
Sam Clegg7c395942017-09-14 23:07:53 +0000291 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000292 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
293 uint64_t ContentsOffset);
294
Sam Clegg7c395942017-09-14 23:07:53 +0000295 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000296 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000297 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
298 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000299};
Sam Clegg9e15f352017-06-03 02:01:24 +0000300
Dan Gohman18eafb62017-02-22 01:23:18 +0000301} // end anonymous namespace
302
303WasmObjectWriter::~WasmObjectWriter() {}
304
Dan Gohmand934cb82017-02-24 23:18:00 +0000305// Write out a section header and a patchable section size field.
306void WasmObjectWriter::startSection(SectionBookkeeping &Section,
307 unsigned SectionId,
308 const char *Name) {
309 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
310 "Only custom sections can have names");
311
Sam Cleggb7787fd2017-06-20 04:04:59 +0000312 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Sam Clegg03e101f2018-03-01 18:06:21 +0000313 write8(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000314
315 Section.SizeOffset = getStream().tell();
316
317 // The section size. We don't know the size yet, so reserve enough space
318 // for any 32-bit value; we'll patch it later.
319 encodeULEB128(UINT32_MAX, getStream());
320
321 // The position where the section starts, for measuring its size.
322 Section.ContentsOffset = getStream().tell();
323
324 // Custom sections in wasm also have a string identifier.
325 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000326 assert(Name);
Sam Cleggcfd44a22018-04-05 17:01:39 +0000327 writeString(Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000328 }
329}
330
331// Now that the section is complete and we know how big it is, patch up the
332// section size field at the start of the section.
333void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
334 uint64_t Size = getStream().tell() - Section.ContentsOffset;
335 if (uint32_t(Size) != Size)
336 report_fatal_error("section size does not fit in a uint32_t");
337
Sam Cleggb7787fd2017-06-20 04:04:59 +0000338 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000339
340 // Write the final section size to the payload_len field, which follows
341 // the section id byte.
342 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000343 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000344 assert(SizeLen == 5);
345 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
346}
347
Dan Gohman18eafb62017-02-22 01:23:18 +0000348// Emit the Wasm header.
349void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000350 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
351 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000352}
353
354void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
355 const MCAsmLayout &Layout) {
356}
357
358void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
359 const MCAsmLayout &Layout,
360 const MCFragment *Fragment,
361 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000362 uint64_t &FixedValue) {
363 MCAsmBackend &Backend = Asm.getBackend();
364 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
365 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000366 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000367 uint64_t C = Target.getConstant();
368 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
369 MCContext &Ctx = Asm.getContext();
370
Sam Cleggbafe6902017-12-15 00:17:10 +0000371 // The .init_array isn't translated as data, so don't do relocations in it.
372 if (FixupSection.getSectionName().startswith(".init_array"))
373 return;
374
Sam Cleggb7a54692018-02-16 18:06:05 +0000375 // TODO(sbc): Add support for debug sections.
376 if (FixupSection.getKind().isMetadata())
377 return;
378
Dan Gohmand934cb82017-02-24 23:18:00 +0000379 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
380 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
381 "Should not have constructed this");
382
383 // Let A, B and C being the components of Target and R be the location of
384 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
385 // If it is pcrel, we want to compute (A - B + C - R).
386
387 // In general, Wasm has no relocations for -B. It can only represent (A + C)
388 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
389 // replace B to implement it: (A - R - K + C)
390 if (IsPCRel) {
391 Ctx.reportError(
392 Fixup.getLoc(),
393 "No relocation available to represent this relative expression");
394 return;
395 }
396
397 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
398
399 if (SymB.isUndefined()) {
400 Ctx.reportError(Fixup.getLoc(),
401 Twine("symbol '") + SymB.getName() +
402 "' can not be undefined in a subtraction expression");
403 return;
404 }
405
406 assert(!SymB.isAbsolute() && "Should have been folded");
407 const MCSection &SecB = SymB.getSection();
408 if (&SecB != &FixupSection) {
409 Ctx.reportError(Fixup.getLoc(),
410 "Cannot represent a difference across sections");
411 return;
412 }
413
414 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
415 uint64_t K = SymBOffset - FixupOffset;
416 IsPCRel = true;
417 C -= K;
418 }
419
420 // We either rejected the fixup or folded B into C at this point.
421 const MCSymbolRefExpr *RefA = Target.getSymA();
422 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
423
Dan Gohmand934cb82017-02-24 23:18:00 +0000424 if (SymA && SymA->isVariable()) {
425 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000426 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
427 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
428 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000429 }
430
431 // Put any constant offset in an addend. Offsets can be negative, and
432 // LLVM expects wrapping, in contrast to wasm's immediates which can't
433 // be negative and don't wrap.
434 FixedValue = 0;
435
Sam Clegg6ad8f192017-07-11 02:21:57 +0000436 if (SymA)
437 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000438
Sam Cleggae03c1e72017-06-13 18:51:50 +0000439 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000440 assert(SymA);
441
Sam Cleggae03c1e72017-06-13 18:51:50 +0000442 unsigned Type = getRelocType(Target, Fixup);
443
Dan Gohmand934cb82017-02-24 23:18:00 +0000444 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000445 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000446
Sam Cleggb7a54692018-02-16 18:06:05 +0000447 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required
448 // to be against a named symbol.
449 // TODO(sbc): Add support for relocations against unnamed temporaries such
450 // as those generated by llvm's `blockaddress`.
451 // See: test/MC/WebAssembly/blockaddress.ll
452 if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
453 report_fatal_error("relocations against un-named temporaries are not yet "
454 "supported by wasm");
455
Sam Clegg12fd3da2017-10-20 21:28:38 +0000456 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000457 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000458 else if (FixupSection.getKind().isText())
459 CodeRelocations.push_back(Rec);
Sam Cleggb7a54692018-02-16 18:06:05 +0000460 else
Sam Clegg12fd3da2017-10-20 21:28:38 +0000461 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000462}
463
Dan Gohmand934cb82017-02-24 23:18:00 +0000464// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
465// to allow patching.
466static void
467WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
468 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000469 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000470 assert(SizeLen == 5);
471 Stream.pwrite((char *)Buffer, SizeLen, Offset);
472}
473
474// Write X as an signed LEB value at offset Offset in Stream, padded
475// to allow patching.
476static void
477WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
478 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000479 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000480 assert(SizeLen == 5);
481 Stream.pwrite((char *)Buffer, SizeLen, Offset);
482}
483
484// Write X as a plain integer value at offset Offset in Stream.
485static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
486 uint8_t Buffer[4];
487 support::endian::write32le(Buffer, X);
488 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
489}
490
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000491static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
492 if (Symbol.isVariable()) {
493 const MCExpr *Expr = Symbol.getVariableValue();
494 auto *Inner = cast<MCSymbolRefExpr>(Expr);
495 return cast<MCSymbolWasm>(&Inner->getSymbol());
496 }
497 return &Symbol;
498}
499
Dan Gohmand934cb82017-02-24 23:18:00 +0000500// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000501// by RelEntry. This value isn't used by the static linker; it just serves
502// to make the object format more readable and more likely to be directly
503// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000504uint32_t
505WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000506 switch (RelEntry.Type) {
507 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000508 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
509 // Provisional value is table address of the resolved symbol itself
510 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
511 assert(Sym->isFunction());
512 return TableIndices[Sym];
513 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000514 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000515 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000516 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000517 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
518 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
519 // Provisional value is function/global Wasm index
520 if (!WasmIndices.count(RelEntry.Symbol))
521 report_fatal_error("symbol not found in wasm index space: " +
522 RelEntry.Symbol->getName());
523 return WasmIndices[RelEntry.Symbol];
Sam Clegg60ec3032018-01-23 01:23:17 +0000524 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
525 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
526 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000527 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000528 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
529 // For undefined symbols, use zero
530 if (!Sym->isDefined())
531 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000532 const wasm::WasmDataReference &Ref = DataLocations[Sym];
533 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000534 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000535 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000536 }
537 default:
538 llvm_unreachable("invalid relocation type");
539 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000540}
541
Sam Clegg759631c2017-09-15 20:54:59 +0000542static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000543 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000544 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
545
Sam Clegg63ebb812017-09-29 16:50:08 +0000546 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
547
Sam Clegg759631c2017-09-15 20:54:59 +0000548 for (const MCFragment &Frag : DataSection) {
549 if (Frag.hasInstructions())
550 report_fatal_error("only data supported in data sections");
551
552 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
553 if (Align->getValueSize() != 1)
554 report_fatal_error("only byte values supported for alignment");
555 // If nops are requested, use zeros, as this is the data section.
556 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
557 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
558 Align->getAlignment()),
559 DataBytes.size() +
560 Align->getMaxBytesToEmit());
561 DataBytes.resize(Size, Value);
562 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000563 int64_t Size;
564 if (!Fill->getSize().evaluateAsAbsolute(Size))
565 llvm_unreachable("The fill should be an assembler constant");
566 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000567 } else {
568 const auto &DataFrag = cast<MCDataFragment>(Frag);
569 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
570
571 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
572 }
573 }
574
575 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
576}
577
Sam Clegg60ec3032018-01-23 01:23:17 +0000578uint32_t
579WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
580 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000581 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000582 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000583 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000584 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000585 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000586
587 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6c899ba2018-02-23 05:08:34 +0000588 report_fatal_error("symbol not found in symbol index space: " +
Sam Clegg60ec3032018-01-23 01:23:17 +0000589 RelEntry.Symbol->getName());
590 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000591}
592
Dan Gohmand934cb82017-02-24 23:18:00 +0000593// Apply the portions of the relocation records that we can handle ourselves
594// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000595void WasmObjectWriter::applyRelocations(
596 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
597 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000598 for (const WasmRelocationEntry &RelEntry : Relocations) {
599 uint64_t Offset = ContentsOffset +
600 RelEntry.FixupSection->getSectionOffset() +
601 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000602
Sam Cleggb7787fd2017-06-20 04:04:59 +0000603 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000604 uint32_t Value = getProvisionalValue(RelEntry);
605
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000606 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000607 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000608 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
610 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000611 WritePatchableLEB(Stream, Value, Offset);
612 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000613 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
614 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000615 WriteI32(Stream, Value, Offset);
616 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000617 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
618 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
619 WritePatchableSLEB(Stream, Value, Offset);
620 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000621 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000622 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000623 }
624 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000625}
626
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000627// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000628// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000629void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000630 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000631 raw_pwrite_stream &Stream = getStream();
632 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000633
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000634 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000635 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000636 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000637
Sam Clegg03e101f2018-03-01 18:06:21 +0000638 write8(RelEntry.Type);
Dan Gohman970d02c2017-03-30 23:58:19 +0000639 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000640 encodeULEB128(Index, Stream);
641 if (RelEntry.hasAddend())
642 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000643 }
644}
645
Sam Clegg9e15f352017-06-03 02:01:24 +0000646void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000647 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000648 if (FunctionTypes.empty())
649 return;
650
651 SectionBookkeeping Section;
652 startSection(Section, wasm::WASM_SEC_TYPE);
653
654 encodeULEB128(FunctionTypes.size(), getStream());
655
656 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Sam Clegg03e101f2018-03-01 18:06:21 +0000657 write8(wasm::WASM_TYPE_FUNC);
Sam Clegg9e15f352017-06-03 02:01:24 +0000658 encodeULEB128(FuncTy.Params.size(), getStream());
659 for (wasm::ValType Ty : FuncTy.Params)
660 writeValueType(Ty);
661 encodeULEB128(FuncTy.Returns.size(), getStream());
662 for (wasm::ValType Ty : FuncTy.Returns)
663 writeValueType(Ty);
664 }
665
666 endSection(Section);
667}
668
Sam Clegg8defa952018-02-12 22:41:29 +0000669void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000670 uint32_t DataSize,
671 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000672 if (Imports.empty())
673 return;
674
Sam Cleggf950b242017-12-11 23:03:38 +0000675 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
676
Sam Clegg9e15f352017-06-03 02:01:24 +0000677 SectionBookkeeping Section;
678 startSection(Section, wasm::WASM_SEC_IMPORT);
679
680 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000681 for (const wasm::WasmImport &Import : Imports) {
682 writeString(Import.Module);
683 writeString(Import.Field);
Sam Clegg03e101f2018-03-01 18:06:21 +0000684 write8(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000685
686 switch (Import.Kind) {
687 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000688 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000689 break;
690 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg03e101f2018-03-01 18:06:21 +0000691 write8(Import.Global.Type);
692 write8(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000693 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000694 case wasm::WASM_EXTERNAL_MEMORY:
695 encodeULEB128(0, getStream()); // flags
696 encodeULEB128(NumPages, getStream()); // initial
697 break;
698 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg03e101f2018-03-01 18:06:21 +0000699 write8(Import.Table.ElemType);
Sam Cleggf950b242017-12-11 23:03:38 +0000700 encodeULEB128(0, getStream()); // flags
701 encodeULEB128(NumElements, getStream()); // initial
702 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000703 default:
704 llvm_unreachable("unsupported import kind");
705 }
706 }
707
708 endSection(Section);
709}
710
Sam Clegg457fb0b2017-09-15 19:50:44 +0000711void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 if (Functions.empty())
713 return;
714
715 SectionBookkeeping Section;
716 startSection(Section, wasm::WASM_SEC_FUNCTION);
717
718 encodeULEB128(Functions.size(), getStream());
719 for (const WasmFunction &Func : Functions)
720 encodeULEB128(Func.Type, getStream());
721
722 endSection(Section);
723}
724
Sam Clegg7c395942017-09-14 23:07:53 +0000725void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000726 if (Globals.empty())
727 return;
728
729 SectionBookkeeping Section;
730 startSection(Section, wasm::WASM_SEC_GLOBAL);
731
732 encodeULEB128(Globals.size(), getStream());
733 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000734 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
735 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000736
Sam Clegg6e7f1822018-01-31 19:50:14 +0000737 write8(wasm::WASM_OPCODE_I32_CONST);
738 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000739 write8(wasm::WASM_OPCODE_END);
740 }
741
742 endSection(Section);
743}
744
Sam Clegg8defa952018-02-12 22:41:29 +0000745void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 if (Exports.empty())
747 return;
748
749 SectionBookkeeping Section;
750 startSection(Section, wasm::WASM_SEC_EXPORT);
751
752 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000753 for (const wasm::WasmExport &Export : Exports) {
754 writeString(Export.Name);
Sam Clegg03e101f2018-03-01 18:06:21 +0000755 write8(Export.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000756 encodeULEB128(Export.Index, getStream());
757 }
758
759 endSection(Section);
760}
761
Sam Clegg457fb0b2017-09-15 19:50:44 +0000762void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000763 if (TableElems.empty())
764 return;
765
766 SectionBookkeeping Section;
767 startSection(Section, wasm::WASM_SEC_ELEM);
768
769 encodeULEB128(1, getStream()); // number of "segments"
770 encodeULEB128(0, getStream()); // the table index
771
772 // init expr for starting offset
773 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000774 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000775 write8(wasm::WASM_OPCODE_END);
776
777 encodeULEB128(TableElems.size(), getStream());
778 for (uint32_t Elem : TableElems)
779 encodeULEB128(Elem, getStream());
780
781 endSection(Section);
782}
783
Sam Clegg457fb0b2017-09-15 19:50:44 +0000784void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
785 const MCAsmLayout &Layout,
786 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000787 if (Functions.empty())
788 return;
789
790 SectionBookkeeping Section;
791 startSection(Section, wasm::WASM_SEC_CODE);
792
793 encodeULEB128(Functions.size(), getStream());
794
795 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000796 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000797
Sam Clegg9e15f352017-06-03 02:01:24 +0000798 int64_t Size = 0;
799 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
800 report_fatal_error(".size expression must be evaluatable");
801
802 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000803 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000804 Asm.writeSectionData(&FuncSection, Layout);
805 }
806
Sam Clegg9e15f352017-06-03 02:01:24 +0000807 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000808 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000809
810 endSection(Section);
811}
812
Sam Clegg6c899ba2018-02-23 05:08:34 +0000813void WasmObjectWriter::writeDataSection() {
814 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000815 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000816
817 SectionBookkeeping Section;
818 startSection(Section, wasm::WASM_SEC_DATA);
819
Sam Clegg6c899ba2018-02-23 05:08:34 +0000820 encodeULEB128(DataSegments.size(), getStream()); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000821
Sam Clegg6c899ba2018-02-23 05:08:34 +0000822 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000823 encodeULEB128(0, getStream()); // memory index
824 write8(wasm::WASM_OPCODE_I32_CONST);
825 encodeSLEB128(Segment.Offset, getStream()); // offset
826 write8(wasm::WASM_OPCODE_END);
827 encodeULEB128(Segment.Data.size(), getStream()); // size
828 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
829 writeBytes(Segment.Data); // data
830 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000831
832 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000833 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000834
835 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000836}
837
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000838void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000839 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
840 // for descriptions of the reloc sections.
841
842 if (CodeRelocations.empty())
843 return;
844
845 SectionBookkeeping Section;
846 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
847
848 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000849 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000850
Sam Clegg7c395942017-09-14 23:07:53 +0000851 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000852
853 endSection(Section);
854}
855
Sam Clegg7c395942017-09-14 23:07:53 +0000856void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000857 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
858 // for descriptions of the reloc sections.
859
860 if (DataRelocations.empty())
861 return;
862
863 SectionBookkeeping Section;
864 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
865
866 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
867 encodeULEB128(DataRelocations.size(), getStream());
868
Sam Clegg7c395942017-09-14 23:07:53 +0000869 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000870
871 endSection(Section);
872}
873
874void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000875 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000876 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000877 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000878 SectionBookkeeping Section;
879 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000880 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000881
Sam Clegg6c899ba2018-02-23 05:08:34 +0000882 if (SymbolInfos.size() != 0) {
883 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
884 encodeULEB128(SymbolInfos.size(), getStream());
885 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
886 encodeULEB128(Sym.Kind, getStream());
887 encodeULEB128(Sym.Flags, getStream());
888 switch (Sym.Kind) {
889 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
890 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
891 encodeULEB128(Sym.ElementIndex, getStream());
892 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
893 writeString(Sym.Name);
894 break;
895 case wasm::WASM_SYMBOL_TYPE_DATA:
896 writeString(Sym.Name);
897 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
898 encodeULEB128(Sym.DataRef.Segment, getStream());
899 encodeULEB128(Sym.DataRef.Offset, getStream());
900 encodeULEB128(Sym.DataRef.Size, getStream());
901 }
902 break;
903 default:
904 llvm_unreachable("unexpected kind");
905 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000906 }
907 endSection(SubSection);
908 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000909
Sam Clegg6c899ba2018-02-23 05:08:34 +0000910 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000911 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000912 encodeULEB128(DataSegments.size(), getStream());
913 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000914 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000915 encodeULEB128(Segment.Alignment, getStream());
916 encodeULEB128(Segment.Flags, getStream());
917 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000918 endSection(SubSection);
919 }
920
Sam Cleggbafe6902017-12-15 00:17:10 +0000921 if (!InitFuncs.empty()) {
922 startSection(SubSection, wasm::WASM_INIT_FUNCS);
923 encodeULEB128(InitFuncs.size(), getStream());
924 for (auto &StartFunc : InitFuncs) {
925 encodeULEB128(StartFunc.first, getStream()); // priority
926 encodeULEB128(StartFunc.second, getStream()); // function index
927 }
928 endSection(SubSection);
929 }
930
Sam Cleggea7cace2018-01-09 23:43:14 +0000931 if (Comdats.size()) {
932 startSection(SubSection, wasm::WASM_COMDAT_INFO);
933 encodeULEB128(Comdats.size(), getStream());
934 for (const auto &C : Comdats) {
935 writeString(C.first);
936 encodeULEB128(0, getStream()); // flags for future use
937 encodeULEB128(C.second.size(), getStream());
938 for (const WasmComdatEntry &Entry : C.second) {
939 encodeULEB128(Entry.Kind, getStream());
940 encodeULEB128(Entry.Index, getStream());
941 }
942 }
943 endSection(SubSection);
944 }
945
Sam Clegg9e15f352017-06-03 02:01:24 +0000946 endSection(Section);
947}
948
Sam Cleggcfd44a22018-04-05 17:01:39 +0000949void WasmObjectWriter::writeUserCustomSections(
950 ArrayRef<WasmCustomSection> CustomSections) {
951 for (const auto &CustomSection : CustomSections) {
952 SectionBookkeeping Section;
953 startSection(Section, wasm::WASM_SEC_CUSTOM,
954 CustomSection.Name.str().c_str());
955 writeBytes(CustomSection.Contents);
956 endSection(Section);
957 }
958}
959
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000960uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
961 assert(Symbol.isFunction());
962 assert(TypeIndices.count(&Symbol));
963 return TypeIndices[&Symbol];
964}
965
966uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
967 assert(Symbol.isFunction());
968
969 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000970 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
971 F.Returns = ResolvedSym->getReturns();
972 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000973
974 auto Pair =
975 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
976 if (Pair.second)
977 FunctionTypes.push_back(F);
978 TypeIndices[&Symbol] = Pair.first->second;
979
980 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
981 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
982 return Pair.first->second;
983}
984
Dan Gohman18eafb62017-02-22 01:23:18 +0000985void WasmObjectWriter::writeObject(MCAssembler &Asm,
986 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000987 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000988 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +0000989
990 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000991 SmallVector<WasmFunction, 4> Functions;
992 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +0000993 SmallVector<wasm::WasmImport, 4> Imports;
994 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000995 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +0000996 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000997 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +0000998 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000999
Sam Cleggf950b242017-12-11 23:03:38 +00001000 // For now, always emit the memory import, since loads and stores are not
1001 // valid without it. In the future, we could perhaps be more clever and omit
1002 // it if there are no loads or stores.
1003 MCSymbolWasm *MemorySym =
1004 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001005 wasm::WasmImport MemImport;
1006 MemImport.Module = MemorySym->getModuleName();
1007 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001008 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1009 Imports.push_back(MemImport);
1010
1011 // For now, always emit the table section, since indirect calls are not
1012 // valid without it. In the future, we could perhaps be more clever and omit
1013 // it if there are no indirect calls.
1014 MCSymbolWasm *TableSym =
1015 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001016 wasm::WasmImport TableImport;
1017 TableImport.Module = TableSym->getModuleName();
1018 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001019 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001020 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001021 Imports.push_back(TableImport);
1022
Nicholas Wilson586320c2018-02-28 17:19:48 +00001023 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1024 // symbols. This must be done before populating WasmIndices for defined
1025 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001026 for (const MCSymbol &S : Asm.symbols()) {
1027 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1028
1029 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001030 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001031 if (WS.isFunction())
1032 registerFunctionType(WS);
1033
1034 if (WS.isTemporary())
1035 continue;
1036
1037 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001038 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001039 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001040 wasm::WasmImport Import;
1041 Import.Module = WS.getModuleName();
1042 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001043 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001044 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001045 Imports.push_back(Import);
1046 WasmIndices[&WS] = NumFunctionImports++;
1047 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001048 if (WS.isWeak())
1049 report_fatal_error("undefined global symbol cannot be weak");
1050
Sam Clegg6c899ba2018-02-23 05:08:34 +00001051 wasm::WasmImport Import;
1052 Import.Module = WS.getModuleName();
1053 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001054 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001055 Import.Global = WS.getGlobalType();
1056 Imports.push_back(Import);
1057 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001058 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001059 }
1060 }
1061
Nicholas Wilson586320c2018-02-28 17:19:48 +00001062 // Populate DataSegments, which must be done before populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001063 for (MCSection &Sec : Asm) {
1064 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Cleggcfd44a22018-04-05 17:01:39 +00001065
1066 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(
1067 ".custom_section.")) {
1068 if (Section.getFragmentList().empty())
1069 continue;
1070 if (Section.getFragmentList().size() != 1)
1071 report_fatal_error(
1072 "only one .custom_section section fragment supported");
1073 const MCFragment &Frag = *Section.begin();
1074 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1075 report_fatal_error("only data supported in .custom_section section");
1076 const auto &DataFrag = cast<MCDataFragment>(Frag);
1077 if (!DataFrag.getFixups().empty())
1078 report_fatal_error("fixups not supported in .custom_section section");
1079 StringRef UserName = Section.getSectionName().substr(16);
1080 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1081 CustomSections.push_back(WasmCustomSection(UserName, Contents));
1082 continue;
1083 }
1084
Sam Clegg12fd3da2017-10-20 21:28:38 +00001085 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001086 continue;
1087
Sam Cleggbafe6902017-12-15 00:17:10 +00001088 // .init_array sections are handled specially elsewhere.
1089 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1090 continue;
1091
Sam Clegg329e76d2018-01-31 04:21:44 +00001092 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001093 DataSize = alignTo(DataSize, Section.getAlignment());
1094 DataSegments.emplace_back();
1095 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001096 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001097 Segment.Offset = DataSize;
1098 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001099 addData(Segment.Data, Section);
1100 Segment.Alignment = Section.getAlignment();
1101 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001102 DataSize += Segment.Data.size();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001103 Section.setSegmentIndex(SegmentIndex);
Sam Cleggea7cace2018-01-09 23:43:14 +00001104
1105 if (const MCSymbolWasm *C = Section.getGroup()) {
1106 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001107 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001108 }
Sam Clegg759631c2017-09-15 20:54:59 +00001109 }
1110
Nicholas Wilson586320c2018-02-28 17:19:48 +00001111 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001112 for (const MCSymbol &S : Asm.symbols()) {
1113 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1114 // or used in relocations.
1115 if (S.isTemporary() && S.getName().empty())
1116 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001117
Dan Gohmand934cb82017-02-24 23:18:00 +00001118 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001119 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001120 << " isDefined=" << S.isDefined()
1121 << " isExternal=" << S.isExternal()
1122 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001123 << " isFunction=" << WS.isFunction()
1124 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001125 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001126 << " isVariable=" << WS.isVariable() << "\n");
1127
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001128 if (WS.isVariable())
1129 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001130 if (WS.isComdat() && !WS.isDefined())
1131 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001132
Dan Gohmand934cb82017-02-24 23:18:00 +00001133 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001134 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001135 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001136 if (WS.getOffset() != 0)
1137 report_fatal_error(
1138 "function sections must contain one function each");
1139
1140 if (WS.getSize() == 0)
1141 report_fatal_error(
1142 "function symbols must have a size set with .size");
1143
Sam Clegg6c899ba2018-02-23 05:08:34 +00001144 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001145 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001146 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001147 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001148 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001149 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001150 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001151
1152 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1153 if (const MCSymbolWasm *C = Section.getGroup()) {
1154 Comdats[C->getName()].emplace_back(
1155 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1156 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001157 } else {
1158 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001159 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001160 }
1161
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001162 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001163 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001164 if (WS.isTemporary() && !WS.getSize())
1165 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001166
Sam Clegg6c899ba2018-02-23 05:08:34 +00001167 if (!WS.isDefined()) {
1168 DEBUG(dbgs() << " -> segment index: -1");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001169 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001170 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001171
Sam Cleggfe6414b2017-06-21 23:46:41 +00001172 if (!WS.getSize())
1173 report_fatal_error("data symbols must have a size set with .size: " +
1174 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001175
Sam Cleggfe6414b2017-06-21 23:46:41 +00001176 int64_t Size = 0;
1177 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1178 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001179
Sam Clegg759631c2017-09-15 20:54:59 +00001180 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001181 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001182
Sam Clegg6c899ba2018-02-23 05:08:34 +00001183 // For each data symbol, export it in the symtab as a reference to the
1184 // corresponding Wasm data segment.
1185 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1186 DataSection.getSegmentIndex(),
1187 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1188 static_cast<uint32_t>(Size)};
1189 DataLocations[&WS] = Ref;
1190 DEBUG(dbgs() << " -> segment index: " << Ref.Segment);
1191 } else {
1192 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001193 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001194 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001195
Eric Christopher545932b2018-02-23 21:14:47 +00001196 // An import; the index was assigned above
1197 DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second
1198 << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001199 }
1200 }
1201
Nicholas Wilson586320c2018-02-28 17:19:48 +00001202 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1203 // process these in a separate pass because we need to have processed the
1204 // target of the alias before the alias itself and the symbols are not
1205 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001206 for (const MCSymbol &S : Asm.symbols()) {
1207 if (!S.isVariable())
1208 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001209
Sam Cleggcd65f692018-01-11 23:59:16 +00001210 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001211
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001212 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001213 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1214 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001215 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001216
Sam Clegg6c899ba2018-02-23 05:08:34 +00001217 if (WS.isFunction()) {
1218 assert(WasmIndices.count(ResolvedSym) > 0);
1219 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1220 WasmIndices[&WS] = WasmIndex;
1221 DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
1222 } else if (WS.isData()) {
1223 assert(DataLocations.count(ResolvedSym) > 0);
1224 const wasm::WasmDataReference &Ref =
1225 DataLocations.find(ResolvedSym)->second;
1226 DataLocations[&WS] = Ref;
1227 DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
1228 } else {
1229 report_fatal_error("don't yet support global aliases");
1230 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001231 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001232
Nicholas Wilson586320c2018-02-28 17:19:48 +00001233 // Finally, populate the symbol table itself, in its "natural" order.
1234 for (const MCSymbol &S : Asm.symbols()) {
1235 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1236 if (WS.isTemporary() && WS.getName().empty())
1237 continue;
1238 if (WS.isComdat() && !WS.isDefined())
1239 continue;
1240 if (WS.isTemporary() && WS.isData() && !WS.getSize())
1241 continue;
1242
1243 uint32_t Flags = 0;
1244 if (WS.isWeak())
1245 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1246 if (WS.isHidden())
1247 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1248 if (!WS.isExternal() && WS.isDefined())
1249 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1250 if (WS.isUndefined())
1251 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1252
1253 wasm::WasmSymbolInfo Info;
1254 Info.Name = WS.getName();
1255 Info.Kind = WS.getType();
1256 Info.Flags = Flags;
1257 if (!WS.isData())
1258 Info.ElementIndex = WasmIndices.find(&WS)->second;
1259 else if (WS.isDefined())
1260 Info.DataRef = DataLocations.find(&WS)->second;
1261 SymbolIndices[&WS] = SymbolInfos.size();
1262 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001263 }
1264
Sam Clegg6006e092017-12-22 20:31:39 +00001265 {
1266 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001267 // Functions referenced by a relocation need to put in the table. This is
1268 // purely to make the object file's provisional values readable, and is
1269 // ignored by the linker, which re-calculates the relocations itself.
1270 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1271 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1272 return;
1273 assert(Rel.Symbol->isFunction());
1274 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001275 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001276 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1277 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1278 DEBUG(dbgs() << " -> adding " << WS.getName()
1279 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001280 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001281 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001282 }
1283 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001284
Sam Clegg6006e092017-12-22 20:31:39 +00001285 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1286 HandleReloc(RelEntry);
1287 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1288 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001289 }
1290
Sam Cleggbafe6902017-12-15 00:17:10 +00001291 // Translate .init_array section contents into start functions.
1292 for (const MCSection &S : Asm) {
1293 const auto &WS = static_cast<const MCSectionWasm &>(S);
1294 if (WS.getSectionName().startswith(".fini_array"))
1295 report_fatal_error(".fini_array sections are unsupported");
1296 if (!WS.getSectionName().startswith(".init_array"))
1297 continue;
1298 if (WS.getFragmentList().empty())
1299 continue;
1300 if (WS.getFragmentList().size() != 2)
1301 report_fatal_error("only one .init_array section fragment supported");
1302 const MCFragment &AlignFrag = *WS.begin();
1303 if (AlignFrag.getKind() != MCFragment::FT_Align)
1304 report_fatal_error(".init_array section should be aligned");
1305 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1306 report_fatal_error(".init_array section should be aligned for pointers");
1307 const MCFragment &Frag = *std::next(WS.begin());
1308 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1309 report_fatal_error("only data supported in .init_array section");
1310 uint16_t Priority = UINT16_MAX;
1311 if (WS.getSectionName().size() != 11) {
1312 if (WS.getSectionName()[11] != '.')
1313 report_fatal_error(".init_array section priority should start with '.'");
1314 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1315 report_fatal_error("invalid .init_array section priority");
1316 }
1317 const auto &DataFrag = cast<MCDataFragment>(Frag);
1318 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1319 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1320 *end = (const uint8_t *)Contents.data() + Contents.size();
1321 p != end; ++p) {
1322 if (*p != 0)
1323 report_fatal_error("non-symbolic data in .init_array section");
1324 }
1325 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1326 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1327 const MCExpr *Expr = Fixup.getValue();
1328 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1329 if (!Sym)
1330 report_fatal_error("fixups in .init_array should be symbol references");
1331 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1332 report_fatal_error("symbols in .init_array should be for functions");
1333 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1334 if (I == SymbolIndices.end())
1335 report_fatal_error("symbols in .init_array should be defined");
1336 uint32_t Index = I->second;
1337 InitFuncs.push_back(std::make_pair(Priority, Index));
1338 }
1339 }
1340
Dan Gohman18eafb62017-02-22 01:23:18 +00001341 // Write out the Wasm header.
1342 writeHeader(Asm);
1343
Sam Clegg9e15f352017-06-03 02:01:24 +00001344 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001345 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001346 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001347 // Skip the "table" section; we import the table instead.
1348 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001349 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001350 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001351 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001352 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001353 writeDataSection();
Sam Cleggcfd44a22018-04-05 17:01:39 +00001354 writeUserCustomSections(CustomSections);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001355 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001356 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001357 writeDataRelocSection();
Dan Gohman970d02c2017-03-30 23:58:19 +00001358
Dan Gohmand934cb82017-02-24 23:18:00 +00001359 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001360 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001361}
1362
Lang Hames60fbc7c2017-10-10 16:28:07 +00001363std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001364llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1365 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001366 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001367}