blob: 8b32cc4c7b5a516f463cf7f051ff520f8ab6786b [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 Clegg1fb8daa2017-06-20 05:05:10 +0000170#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000171raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000172 Rel.print(OS);
173 return OS;
174}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000175#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000176
Dan Gohman18eafb62017-02-22 01:23:18 +0000177class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000178 /// The target specific Wasm writer instance.
179 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
180
Dan Gohmand934cb82017-02-24 23:18:00 +0000181 // Relocations for fixing up references in the code section.
182 std::vector<WasmRelocationEntry> CodeRelocations;
183
184 // Relocations for fixing up references in the data section.
185 std::vector<WasmRelocationEntry> DataRelocations;
186
Dan Gohmand934cb82017-02-24 23:18:00 +0000187 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000188 // Maps function symbols to the index of the type of the function
189 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000190 // Maps function symbols to the table element index space. Used
191 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000192 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000193 // Maps function/global symbols to the (shared) Symbol index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000194 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000195 // Maps function/global symbols to the function/global Wasm index space.
196 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
197 // Maps data symbols to the Wasm segment and offset/size with the segment.
198 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000199
200 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
201 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000202 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000203 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000204 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000205 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000206 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000207
Dan Gohman18eafb62017-02-22 01:23:18 +0000208 // TargetObjectWriter wrappers.
209 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000210 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
211 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000212 }
213
Dan Gohmand934cb82017-02-24 23:18:00 +0000214 void startSection(SectionBookkeeping &Section, unsigned SectionId,
215 const char *Name = nullptr);
216 void endSection(SectionBookkeeping &Section);
217
Dan Gohman18eafb62017-02-22 01:23:18 +0000218public:
Lang Hames1301a872017-10-10 01:15:10 +0000219 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
220 raw_pwrite_stream &OS)
221 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
222 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000223
Dan Gohman18eafb62017-02-22 01:23:18 +0000224 ~WasmObjectWriter() override;
225
Dan Gohman0917c9e2018-01-15 17:06:23 +0000226private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000227 void reset() override {
228 CodeRelocations.clear();
229 DataRelocations.clear();
230 TypeIndices.clear();
231 SymbolIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000232 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000233 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000234 DataLocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000235 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000236 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000237 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000238 DataSegments.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000239 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000240 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000241 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000242 }
243
Dan Gohman18eafb62017-02-22 01:23:18 +0000244 void writeHeader(const MCAssembler &Asm);
245
246 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
247 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000248 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000249
250 void executePostLayoutBinding(MCAssembler &Asm,
251 const MCAsmLayout &Layout) override;
252
253 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000254
Sam Cleggb7787fd2017-06-20 04:04:59 +0000255 void writeString(const StringRef Str) {
256 encodeULEB128(Str.size(), getStream());
257 writeBytes(Str);
258 }
259
Sam Clegg9e15f352017-06-03 02:01:24 +0000260 void writeValueType(wasm::ValType Ty) {
261 encodeSLEB128(int32_t(Ty), getStream());
262 }
263
Sam Clegg457fb0b2017-09-15 19:50:44 +0000264 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000265 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000266 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000267 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000268 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000269 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000270 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000271 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000272 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000273 void writeDataSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000274 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000275 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000276 void writeLinkingMetaDataSection(
Sam Clegg6c899ba2018-02-23 05:08:34 +0000277 uint32_t DataSize, ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000278 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000279 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000280
Sam Clegg7c395942017-09-14 23:07:53 +0000281 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000282 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
283 uint64_t ContentsOffset);
284
Sam Clegg7c395942017-09-14 23:07:53 +0000285 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000286 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000287 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
288 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000289};
Sam Clegg9e15f352017-06-03 02:01:24 +0000290
Dan Gohman18eafb62017-02-22 01:23:18 +0000291} // end anonymous namespace
292
293WasmObjectWriter::~WasmObjectWriter() {}
294
Dan Gohmand934cb82017-02-24 23:18:00 +0000295// Write out a section header and a patchable section size field.
296void WasmObjectWriter::startSection(SectionBookkeeping &Section,
297 unsigned SectionId,
298 const char *Name) {
299 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
300 "Only custom sections can have names");
301
Sam Cleggb7787fd2017-06-20 04:04:59 +0000302 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000303 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000304
305 Section.SizeOffset = getStream().tell();
306
307 // The section size. We don't know the size yet, so reserve enough space
308 // for any 32-bit value; we'll patch it later.
309 encodeULEB128(UINT32_MAX, getStream());
310
311 // The position where the section starts, for measuring its size.
312 Section.ContentsOffset = getStream().tell();
313
314 // Custom sections in wasm also have a string identifier.
315 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000316 assert(Name);
317 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000318 }
319}
320
321// Now that the section is complete and we know how big it is, patch up the
322// section size field at the start of the section.
323void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
324 uint64_t Size = getStream().tell() - Section.ContentsOffset;
325 if (uint32_t(Size) != Size)
326 report_fatal_error("section size does not fit in a uint32_t");
327
Sam Cleggb7787fd2017-06-20 04:04:59 +0000328 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000329
330 // Write the final section size to the payload_len field, which follows
331 // the section id byte.
332 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000333 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000334 assert(SizeLen == 5);
335 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
336}
337
Dan Gohman18eafb62017-02-22 01:23:18 +0000338// Emit the Wasm header.
339void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000340 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
341 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000342}
343
344void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
345 const MCAsmLayout &Layout) {
346}
347
348void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
349 const MCAsmLayout &Layout,
350 const MCFragment *Fragment,
351 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000352 uint64_t &FixedValue) {
353 MCAsmBackend &Backend = Asm.getBackend();
354 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
355 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000356 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000357 uint64_t C = Target.getConstant();
358 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
359 MCContext &Ctx = Asm.getContext();
360
Sam Cleggbafe6902017-12-15 00:17:10 +0000361 // The .init_array isn't translated as data, so don't do relocations in it.
362 if (FixupSection.getSectionName().startswith(".init_array"))
363 return;
364
Sam Cleggb7a54692018-02-16 18:06:05 +0000365 // TODO(sbc): Add support for debug sections.
366 if (FixupSection.getKind().isMetadata())
367 return;
368
Dan Gohmand934cb82017-02-24 23:18:00 +0000369 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
370 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
371 "Should not have constructed this");
372
373 // Let A, B and C being the components of Target and R be the location of
374 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
375 // If it is pcrel, we want to compute (A - B + C - R).
376
377 // In general, Wasm has no relocations for -B. It can only represent (A + C)
378 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
379 // replace B to implement it: (A - R - K + C)
380 if (IsPCRel) {
381 Ctx.reportError(
382 Fixup.getLoc(),
383 "No relocation available to represent this relative expression");
384 return;
385 }
386
387 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
388
389 if (SymB.isUndefined()) {
390 Ctx.reportError(Fixup.getLoc(),
391 Twine("symbol '") + SymB.getName() +
392 "' can not be undefined in a subtraction expression");
393 return;
394 }
395
396 assert(!SymB.isAbsolute() && "Should have been folded");
397 const MCSection &SecB = SymB.getSection();
398 if (&SecB != &FixupSection) {
399 Ctx.reportError(Fixup.getLoc(),
400 "Cannot represent a difference across sections");
401 return;
402 }
403
404 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
405 uint64_t K = SymBOffset - FixupOffset;
406 IsPCRel = true;
407 C -= K;
408 }
409
410 // We either rejected the fixup or folded B into C at this point.
411 const MCSymbolRefExpr *RefA = Target.getSymA();
412 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
413
Dan Gohmand934cb82017-02-24 23:18:00 +0000414 if (SymA && SymA->isVariable()) {
415 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000416 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
417 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
418 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000419 }
420
421 // Put any constant offset in an addend. Offsets can be negative, and
422 // LLVM expects wrapping, in contrast to wasm's immediates which can't
423 // be negative and don't wrap.
424 FixedValue = 0;
425
Sam Clegg6ad8f192017-07-11 02:21:57 +0000426 if (SymA)
427 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000428
Sam Cleggae03c1e72017-06-13 18:51:50 +0000429 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000430 assert(SymA);
431
Sam Cleggae03c1e72017-06-13 18:51:50 +0000432 unsigned Type = getRelocType(Target, Fixup);
433
Dan Gohmand934cb82017-02-24 23:18:00 +0000434 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000435 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000436
Sam Cleggb7a54692018-02-16 18:06:05 +0000437 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required
438 // to be against a named symbol.
439 // TODO(sbc): Add support for relocations against unnamed temporaries such
440 // as those generated by llvm's `blockaddress`.
441 // See: test/MC/WebAssembly/blockaddress.ll
442 if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
443 report_fatal_error("relocations against un-named temporaries are not yet "
444 "supported by wasm");
445
Sam Clegg12fd3da2017-10-20 21:28:38 +0000446 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000447 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000448 else if (FixupSection.getKind().isText())
449 CodeRelocations.push_back(Rec);
Sam Cleggb7a54692018-02-16 18:06:05 +0000450 else
Sam Clegg12fd3da2017-10-20 21:28:38 +0000451 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000452}
453
Dan Gohmand934cb82017-02-24 23:18:00 +0000454// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
455// to allow patching.
456static void
457WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
458 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000459 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000460 assert(SizeLen == 5);
461 Stream.pwrite((char *)Buffer, SizeLen, Offset);
462}
463
464// Write X as an signed LEB value at offset Offset in Stream, padded
465// to allow patching.
466static void
467WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
468 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000469 unsigned SizeLen = encodeSLEB128(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 a plain integer value at offset Offset in Stream.
475static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
476 uint8_t Buffer[4];
477 support::endian::write32le(Buffer, X);
478 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
479}
480
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000481static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
482 if (Symbol.isVariable()) {
483 const MCExpr *Expr = Symbol.getVariableValue();
484 auto *Inner = cast<MCSymbolRefExpr>(Expr);
485 return cast<MCSymbolWasm>(&Inner->getSymbol());
486 }
487 return &Symbol;
488}
489
Dan Gohmand934cb82017-02-24 23:18:00 +0000490// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000491// by RelEntry. This value isn't used by the static linker; it just serves
492// to make the object format more readable and more likely to be directly
493// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000494uint32_t
495WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000496 switch (RelEntry.Type) {
497 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000498 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
499 // Provisional value is table address of the resolved symbol itself
500 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
501 assert(Sym->isFunction());
502 return TableIndices[Sym];
503 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000504 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000505 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000506 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000507 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
508 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
509 // Provisional value is function/global Wasm index
510 if (!WasmIndices.count(RelEntry.Symbol))
511 report_fatal_error("symbol not found in wasm index space: " +
512 RelEntry.Symbol->getName());
513 return WasmIndices[RelEntry.Symbol];
Sam Clegg60ec3032018-01-23 01:23:17 +0000514 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
515 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
516 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000517 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000518 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
519 // For undefined symbols, use zero
520 if (!Sym->isDefined())
521 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000522 const wasm::WasmDataReference &Ref = DataLocations[Sym];
523 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000524 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000525 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000526 }
527 default:
528 llvm_unreachable("invalid relocation type");
529 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000530}
531
Sam Clegg759631c2017-09-15 20:54:59 +0000532static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000533 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000534 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
535
Sam Clegg63ebb812017-09-29 16:50:08 +0000536 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
537
Sam Clegg759631c2017-09-15 20:54:59 +0000538 for (const MCFragment &Frag : DataSection) {
539 if (Frag.hasInstructions())
540 report_fatal_error("only data supported in data sections");
541
542 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
543 if (Align->getValueSize() != 1)
544 report_fatal_error("only byte values supported for alignment");
545 // If nops are requested, use zeros, as this is the data section.
546 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
547 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
548 Align->getAlignment()),
549 DataBytes.size() +
550 Align->getMaxBytesToEmit());
551 DataBytes.resize(Size, Value);
552 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000553 int64_t Size;
554 if (!Fill->getSize().evaluateAsAbsolute(Size))
555 llvm_unreachable("The fill should be an assembler constant");
556 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000557 } else {
558 const auto &DataFrag = cast<MCDataFragment>(Frag);
559 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
560
561 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
562 }
563 }
564
565 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
566}
567
Sam Clegg60ec3032018-01-23 01:23:17 +0000568uint32_t
569WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
570 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000571 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000572 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000573 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000574 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000575 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000576
577 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6c899ba2018-02-23 05:08:34 +0000578 report_fatal_error("symbol not found in symbol index space: " +
Sam Clegg60ec3032018-01-23 01:23:17 +0000579 RelEntry.Symbol->getName());
580 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000581}
582
Dan Gohmand934cb82017-02-24 23:18:00 +0000583// Apply the portions of the relocation records that we can handle ourselves
584// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000585void WasmObjectWriter::applyRelocations(
586 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
587 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000588 for (const WasmRelocationEntry &RelEntry : Relocations) {
589 uint64_t Offset = ContentsOffset +
590 RelEntry.FixupSection->getSectionOffset() +
591 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000592
Sam Cleggb7787fd2017-06-20 04:04:59 +0000593 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000594 uint32_t Value = getProvisionalValue(RelEntry);
595
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000596 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000597 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000598 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000599 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
600 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000601 WritePatchableLEB(Stream, Value, Offset);
602 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000603 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
604 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000605 WriteI32(Stream, Value, Offset);
606 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000607 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
608 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
609 WritePatchableSLEB(Stream, Value, Offset);
610 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000611 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000612 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000613 }
614 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000615}
616
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000617// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000618// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000619void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000620 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000621 raw_pwrite_stream &Stream = getStream();
622 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000623
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000624 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000625 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000626 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000627
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000628 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000629 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 encodeULEB128(Index, Stream);
631 if (RelEntry.hasAddend())
632 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000633 }
634}
635
Sam Clegg9e15f352017-06-03 02:01:24 +0000636void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000637 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000638 if (FunctionTypes.empty())
639 return;
640
641 SectionBookkeeping Section;
642 startSection(Section, wasm::WASM_SEC_TYPE);
643
644 encodeULEB128(FunctionTypes.size(), getStream());
645
646 for (const WasmFunctionType &FuncTy : FunctionTypes) {
647 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
648 encodeULEB128(FuncTy.Params.size(), getStream());
649 for (wasm::ValType Ty : FuncTy.Params)
650 writeValueType(Ty);
651 encodeULEB128(FuncTy.Returns.size(), getStream());
652 for (wasm::ValType Ty : FuncTy.Returns)
653 writeValueType(Ty);
654 }
655
656 endSection(Section);
657}
658
Sam Clegg8defa952018-02-12 22:41:29 +0000659void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000660 uint32_t DataSize,
661 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000662 if (Imports.empty())
663 return;
664
Sam Cleggf950b242017-12-11 23:03:38 +0000665 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
666
Sam Clegg9e15f352017-06-03 02:01:24 +0000667 SectionBookkeeping Section;
668 startSection(Section, wasm::WASM_SEC_IMPORT);
669
670 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000671 for (const wasm::WasmImport &Import : Imports) {
672 writeString(Import.Module);
673 writeString(Import.Field);
Sam Clegg9e15f352017-06-03 02:01:24 +0000674 encodeULEB128(Import.Kind, getStream());
675
676 switch (Import.Kind) {
677 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000678 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000679 break;
680 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg8defa952018-02-12 22:41:29 +0000681 encodeSLEB128(Import.Global.Type, getStream());
682 encodeULEB128(uint32_t(Import.Global.Mutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000683 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000684 case wasm::WASM_EXTERNAL_MEMORY:
685 encodeULEB128(0, getStream()); // flags
686 encodeULEB128(NumPages, getStream()); // initial
687 break;
688 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg8defa952018-02-12 22:41:29 +0000689 encodeSLEB128(Import.Table.ElemType, getStream());
Sam Cleggf950b242017-12-11 23:03:38 +0000690 encodeULEB128(0, getStream()); // flags
691 encodeULEB128(NumElements, getStream()); // initial
692 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000693 default:
694 llvm_unreachable("unsupported import kind");
695 }
696 }
697
698 endSection(Section);
699}
700
Sam Clegg457fb0b2017-09-15 19:50:44 +0000701void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000702 if (Functions.empty())
703 return;
704
705 SectionBookkeeping Section;
706 startSection(Section, wasm::WASM_SEC_FUNCTION);
707
708 encodeULEB128(Functions.size(), getStream());
709 for (const WasmFunction &Func : Functions)
710 encodeULEB128(Func.Type, getStream());
711
712 endSection(Section);
713}
714
Sam Clegg7c395942017-09-14 23:07:53 +0000715void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000716 if (Globals.empty())
717 return;
718
719 SectionBookkeeping Section;
720 startSection(Section, wasm::WASM_SEC_GLOBAL);
721
722 encodeULEB128(Globals.size(), getStream());
723 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000724 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
725 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000726
Sam Clegg6e7f1822018-01-31 19:50:14 +0000727 write8(wasm::WASM_OPCODE_I32_CONST);
728 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000729 write8(wasm::WASM_OPCODE_END);
730 }
731
732 endSection(Section);
733}
734
Sam Clegg8defa952018-02-12 22:41:29 +0000735void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000736 if (Exports.empty())
737 return;
738
739 SectionBookkeeping Section;
740 startSection(Section, wasm::WASM_SEC_EXPORT);
741
742 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000743 for (const wasm::WasmExport &Export : Exports) {
744 writeString(Export.Name);
Sam Clegg9e15f352017-06-03 02:01:24 +0000745 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 encodeULEB128(Export.Index, getStream());
747 }
748
749 endSection(Section);
750}
751
Sam Clegg457fb0b2017-09-15 19:50:44 +0000752void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000753 if (TableElems.empty())
754 return;
755
756 SectionBookkeeping Section;
757 startSection(Section, wasm::WASM_SEC_ELEM);
758
759 encodeULEB128(1, getStream()); // number of "segments"
760 encodeULEB128(0, getStream()); // the table index
761
762 // init expr for starting offset
763 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000764 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000765 write8(wasm::WASM_OPCODE_END);
766
767 encodeULEB128(TableElems.size(), getStream());
768 for (uint32_t Elem : TableElems)
769 encodeULEB128(Elem, getStream());
770
771 endSection(Section);
772}
773
Sam Clegg457fb0b2017-09-15 19:50:44 +0000774void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
775 const MCAsmLayout &Layout,
776 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000777 if (Functions.empty())
778 return;
779
780 SectionBookkeeping Section;
781 startSection(Section, wasm::WASM_SEC_CODE);
782
783 encodeULEB128(Functions.size(), getStream());
784
785 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000786 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000787
Sam Clegg9e15f352017-06-03 02:01:24 +0000788 int64_t Size = 0;
789 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
790 report_fatal_error(".size expression must be evaluatable");
791
792 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000793 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000794 Asm.writeSectionData(&FuncSection, Layout);
795 }
796
Sam Clegg9e15f352017-06-03 02:01:24 +0000797 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000798 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000799
800 endSection(Section);
801}
802
Sam Clegg6c899ba2018-02-23 05:08:34 +0000803void WasmObjectWriter::writeDataSection() {
804 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000805 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000806
807 SectionBookkeeping Section;
808 startSection(Section, wasm::WASM_SEC_DATA);
809
Sam Clegg6c899ba2018-02-23 05:08:34 +0000810 encodeULEB128(DataSegments.size(), getStream()); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000811
Sam Clegg6c899ba2018-02-23 05:08:34 +0000812 for (const WasmDataSegment &Segment : DataSegments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000813 encodeULEB128(0, getStream()); // memory index
814 write8(wasm::WASM_OPCODE_I32_CONST);
815 encodeSLEB128(Segment.Offset, getStream()); // offset
816 write8(wasm::WASM_OPCODE_END);
817 encodeULEB128(Segment.Data.size(), getStream()); // size
818 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
819 writeBytes(Segment.Data); // data
820 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000821
822 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000823 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000824
825 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000826}
827
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000828void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000829 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
830 // for descriptions of the reloc sections.
831
832 if (CodeRelocations.empty())
833 return;
834
835 SectionBookkeeping Section;
836 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
837
838 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000839 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000840
Sam Clegg7c395942017-09-14 23:07:53 +0000841 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000842
843 endSection(Section);
844}
845
Sam Clegg7c395942017-09-14 23:07:53 +0000846void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000847 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
848 // for descriptions of the reloc sections.
849
850 if (DataRelocations.empty())
851 return;
852
853 SectionBookkeeping Section;
854 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
855
856 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
857 encodeULEB128(DataRelocations.size(), getStream());
858
Sam Clegg7c395942017-09-14 23:07:53 +0000859 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000860
861 endSection(Section);
862}
863
864void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg6c899ba2018-02-23 05:08:34 +0000865 uint32_t DataSize, ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000866 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000867 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000868 SectionBookkeeping Section;
869 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000870 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
Sam Clegg6c899ba2018-02-23 05:08:34 +0000872 if (SymbolInfos.size() != 0) {
873 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
874 encodeULEB128(SymbolInfos.size(), getStream());
875 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
876 encodeULEB128(Sym.Kind, getStream());
877 encodeULEB128(Sym.Flags, getStream());
878 switch (Sym.Kind) {
879 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
880 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
881 encodeULEB128(Sym.ElementIndex, getStream());
882 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
883 writeString(Sym.Name);
884 break;
885 case wasm::WASM_SYMBOL_TYPE_DATA:
886 writeString(Sym.Name);
887 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
888 encodeULEB128(Sym.DataRef.Segment, getStream());
889 encodeULEB128(Sym.DataRef.Offset, getStream());
890 encodeULEB128(Sym.DataRef.Size, getStream());
891 }
892 break;
893 default:
894 llvm_unreachable("unexpected kind");
895 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000896 }
897 endSection(SubSection);
898 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000899
Sam Clegg9e1ade92017-06-27 20:27:59 +0000900 if (DataSize > 0) {
901 startSection(SubSection, wasm::WASM_DATA_SIZE);
902 encodeULEB128(DataSize, getStream());
903 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000904 }
905
Sam Clegg6c899ba2018-02-23 05:08:34 +0000906 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000907 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000908 encodeULEB128(DataSegments.size(), getStream());
909 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000910 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000911 encodeULEB128(Segment.Alignment, getStream());
912 encodeULEB128(Segment.Flags, getStream());
913 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000914 endSection(SubSection);
915 }
916
Sam Cleggbafe6902017-12-15 00:17:10 +0000917 if (!InitFuncs.empty()) {
918 startSection(SubSection, wasm::WASM_INIT_FUNCS);
919 encodeULEB128(InitFuncs.size(), getStream());
920 for (auto &StartFunc : InitFuncs) {
921 encodeULEB128(StartFunc.first, getStream()); // priority
922 encodeULEB128(StartFunc.second, getStream()); // function index
923 }
924 endSection(SubSection);
925 }
926
Sam Cleggea7cace2018-01-09 23:43:14 +0000927 if (Comdats.size()) {
928 startSection(SubSection, wasm::WASM_COMDAT_INFO);
929 encodeULEB128(Comdats.size(), getStream());
930 for (const auto &C : Comdats) {
931 writeString(C.first);
932 encodeULEB128(0, getStream()); // flags for future use
933 encodeULEB128(C.second.size(), getStream());
934 for (const WasmComdatEntry &Entry : C.second) {
935 encodeULEB128(Entry.Kind, getStream());
936 encodeULEB128(Entry.Index, getStream());
937 }
938 }
939 endSection(SubSection);
940 }
941
Sam Clegg9e15f352017-06-03 02:01:24 +0000942 endSection(Section);
943}
944
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000945uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
946 assert(Symbol.isFunction());
947 assert(TypeIndices.count(&Symbol));
948 return TypeIndices[&Symbol];
949}
950
951uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
952 assert(Symbol.isFunction());
953
954 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000955 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
956 F.Returns = ResolvedSym->getReturns();
957 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000958
959 auto Pair =
960 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
961 if (Pair.second)
962 FunctionTypes.push_back(F);
963 TypeIndices[&Symbol] = Pair.first->second;
964
965 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
966 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
967 return Pair.first->second;
968}
969
Dan Gohman18eafb62017-02-22 01:23:18 +0000970void WasmObjectWriter::writeObject(MCAssembler &Asm,
971 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000972 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000973 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +0000974
975 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000976 SmallVector<WasmFunction, 4> Functions;
977 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +0000978 SmallVector<wasm::WasmImport, 4> Imports;
979 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000980 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +0000981 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000982 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000983 unsigned NumSymbols = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000984 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000985
Sam Clegg6c899ba2018-02-23 05:08:34 +0000986 auto AddSymbol = [&](const MCSymbolWasm &WS) {
987 uint32_t Flags = 0;
988 if (WS.isWeak())
989 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
990 if (WS.isHidden())
991 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
992 if (!WS.isExternal() && WS.isDefined())
993 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
994 if (WS.isUndefined())
995 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
996
997 wasm::WasmSymbolInfo Info;
998 Info.Name = WS.getName();
999 Info.Kind = WS.getType();
1000 Info.Flags = Flags;
1001 if (!WS.isData())
1002 Info.ElementIndex = WasmIndices[&WS];
1003 else if (WS.isDefined())
1004 Info.DataRef = DataLocations[&WS];
1005 SymbolInfos.emplace_back(Info);
1006 SymbolIndices[&WS] = NumSymbols++;
1007 };
1008
Sam Cleggf950b242017-12-11 23:03:38 +00001009 // For now, always emit the memory import, since loads and stores are not
1010 // valid without it. In the future, we could perhaps be more clever and omit
1011 // it if there are no loads or stores.
1012 MCSymbolWasm *MemorySym =
1013 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001014 wasm::WasmImport MemImport;
1015 MemImport.Module = MemorySym->getModuleName();
1016 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001017 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1018 Imports.push_back(MemImport);
1019
1020 // For now, always emit the table section, since indirect calls are not
1021 // valid without it. In the future, we could perhaps be more clever and omit
1022 // it if there are no indirect calls.
1023 MCSymbolWasm *TableSym =
1024 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001025 wasm::WasmImport TableImport;
1026 TableImport.Module = TableSym->getModuleName();
1027 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001028 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001029 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001030 Imports.push_back(TableImport);
1031
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001032 // Populate FunctionTypeIndices and Imports.
1033 for (const MCSymbol &S : Asm.symbols()) {
1034 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1035
1036 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001037 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001038 if (WS.isFunction())
1039 registerFunctionType(WS);
1040
1041 if (WS.isTemporary())
1042 continue;
1043
1044 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001045 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001046 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001047 wasm::WasmImport Import;
1048 Import.Module = WS.getModuleName();
1049 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001050 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001051 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001052 Imports.push_back(Import);
1053 WasmIndices[&WS] = NumFunctionImports++;
1054 } else if (WS.isGlobal()) {
1055 wasm::WasmImport Import;
1056 Import.Module = WS.getModuleName();
1057 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001058 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001059 Import.Global = WS.getGlobalType();
1060 Imports.push_back(Import);
1061 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001062 }
1063
Sam Clegg6c899ba2018-02-23 05:08:34 +00001064 // TODO(ncw) We shouldn't be adding the symbol to the symbol table here!
1065 // Instead it should be done by removing the "if (WS.isDefined())" block
1066 // in the big loop below (line ~1284). However - that would reorder all
1067 // the symbols and thus require all the tests to be updated. I think it's
1068 // better to make that change therefore in a future commit, to isolate
1069 // each test update from the change that caused it.
1070 AddSymbol(WS);
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001071 }
1072 }
1073
Sam Clegg759631c2017-09-15 20:54:59 +00001074 for (MCSection &Sec : Asm) {
1075 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001076 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001077 continue;
1078
Sam Cleggbafe6902017-12-15 00:17:10 +00001079 // .init_array sections are handled specially elsewhere.
1080 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1081 continue;
1082
Sam Clegg329e76d2018-01-31 04:21:44 +00001083 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001084 DataSize = alignTo(DataSize, Section.getAlignment());
1085 DataSegments.emplace_back();
1086 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001087 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001088 Segment.Offset = DataSize;
1089 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001090 addData(Segment.Data, Section);
1091 Segment.Alignment = Section.getAlignment();
1092 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001093 DataSize += Segment.Data.size();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001094 Section.setSegmentIndex(SegmentIndex);
Sam Cleggea7cace2018-01-09 23:43:14 +00001095
1096 if (const MCSymbolWasm *C = Section.getGroup()) {
1097 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001098 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001099 }
Sam Clegg759631c2017-09-15 20:54:59 +00001100 }
1101
Sam Cleggb7787fd2017-06-20 04:04:59 +00001102 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001103 for (const MCSymbol &S : Asm.symbols()) {
1104 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1105 // or used in relocations.
1106 if (S.isTemporary() && S.getName().empty())
1107 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001108
Dan Gohmand934cb82017-02-24 23:18:00 +00001109 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001110 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001111 << " isDefined=" << S.isDefined()
1112 << " isExternal=" << S.isExternal()
1113 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001114 << " isFunction=" << WS.isFunction()
1115 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001116 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001117 << " isVariable=" << WS.isVariable() << "\n");
1118
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001119 if (WS.isVariable())
1120 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001121 if (WS.isComdat() && !WS.isDefined())
1122 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001123
Dan Gohmand934cb82017-02-24 23:18:00 +00001124 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001125 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001126 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001127 if (WS.getOffset() != 0)
1128 report_fatal_error(
1129 "function sections must contain one function each");
1130
1131 if (WS.getSize() == 0)
1132 report_fatal_error(
1133 "function symbols must have a size set with .size");
1134
Sam Clegg6c899ba2018-02-23 05:08:34 +00001135 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001136 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001137 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001138 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001139 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001140 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001141 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001142
1143 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1144 if (const MCSymbolWasm *C = Section.getGroup()) {
1145 Comdats[C->getName()].emplace_back(
1146 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1147 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001148 } else {
1149 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001150 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001151 }
1152
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001153 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001154 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001155 if (WS.isTemporary() && !WS.getSize())
1156 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001157
Sam Clegg6c899ba2018-02-23 05:08:34 +00001158 if (!WS.isDefined()) {
1159 DEBUG(dbgs() << " -> segment index: -1");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001160 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001161 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001162
Sam Cleggfe6414b2017-06-21 23:46:41 +00001163 if (!WS.getSize())
1164 report_fatal_error("data symbols must have a size set with .size: " +
1165 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001166
Sam Cleggfe6414b2017-06-21 23:46:41 +00001167 int64_t Size = 0;
1168 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1169 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001170
Sam Clegg759631c2017-09-15 20:54:59 +00001171 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001172 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001173
Sam Clegg6c899ba2018-02-23 05:08:34 +00001174 // For each data symbol, export it in the symtab as a reference to the
1175 // corresponding Wasm data segment.
1176 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1177 DataSection.getSegmentIndex(),
1178 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1179 static_cast<uint32_t>(Size)};
1180 DataLocations[&WS] = Ref;
1181 DEBUG(dbgs() << " -> segment index: " << Ref.Segment);
1182 } else {
1183 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001184 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001185 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001186
Eric Christopher545932b2018-02-23 21:14:47 +00001187 // An import; the index was assigned above
1188 DEBUG(dbgs() << " -> global index: " << WasmIndices.find(&WS)->second
1189 << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001190 }
Sam Clegg6c899ba2018-02-23 05:08:34 +00001191
1192 if (WS.isDefined())
1193 AddSymbol(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001194 }
1195
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001196 // Handle weak aliases. We need to process these in a separate pass because
1197 // we need to have processed the target of the alias before the alias itself
1198 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001199 for (const MCSymbol &S : Asm.symbols()) {
1200 if (!S.isVariable())
1201 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001202
Sam Cleggcd65f692018-01-11 23:59:16 +00001203 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001204
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001205 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001206 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1207 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001208 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001209
Sam Clegg6c899ba2018-02-23 05:08:34 +00001210 if (WS.isFunction()) {
1211 assert(WasmIndices.count(ResolvedSym) > 0);
1212 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1213 WasmIndices[&WS] = WasmIndex;
1214 DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
1215 } else if (WS.isData()) {
1216 assert(DataLocations.count(ResolvedSym) > 0);
1217 const wasm::WasmDataReference &Ref =
1218 DataLocations.find(ResolvedSym)->second;
1219 DataLocations[&WS] = Ref;
1220 DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
1221 } else {
1222 report_fatal_error("don't yet support global aliases");
1223 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001224
Sam Clegg6c899ba2018-02-23 05:08:34 +00001225 AddSymbol(WS);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001226 }
1227
Sam Clegg6006e092017-12-22 20:31:39 +00001228 {
1229 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001230 // Functions referenced by a relocation need to put in the table. This is
1231 // purely to make the object file's provisional values readable, and is
1232 // ignored by the linker, which re-calculates the relocations itself.
1233 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1234 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1235 return;
1236 assert(Rel.Symbol->isFunction());
1237 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001238 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001239 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1240 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1241 DEBUG(dbgs() << " -> adding " << WS.getName()
1242 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001243 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001244 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001245 }
1246 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001247
Sam Clegg6006e092017-12-22 20:31:39 +00001248 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1249 HandleReloc(RelEntry);
1250 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1251 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001252 }
1253
Sam Cleggbafe6902017-12-15 00:17:10 +00001254 // Translate .init_array section contents into start functions.
1255 for (const MCSection &S : Asm) {
1256 const auto &WS = static_cast<const MCSectionWasm &>(S);
1257 if (WS.getSectionName().startswith(".fini_array"))
1258 report_fatal_error(".fini_array sections are unsupported");
1259 if (!WS.getSectionName().startswith(".init_array"))
1260 continue;
1261 if (WS.getFragmentList().empty())
1262 continue;
1263 if (WS.getFragmentList().size() != 2)
1264 report_fatal_error("only one .init_array section fragment supported");
1265 const MCFragment &AlignFrag = *WS.begin();
1266 if (AlignFrag.getKind() != MCFragment::FT_Align)
1267 report_fatal_error(".init_array section should be aligned");
1268 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1269 report_fatal_error(".init_array section should be aligned for pointers");
1270 const MCFragment &Frag = *std::next(WS.begin());
1271 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1272 report_fatal_error("only data supported in .init_array section");
1273 uint16_t Priority = UINT16_MAX;
1274 if (WS.getSectionName().size() != 11) {
1275 if (WS.getSectionName()[11] != '.')
1276 report_fatal_error(".init_array section priority should start with '.'");
1277 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1278 report_fatal_error("invalid .init_array section priority");
1279 }
1280 const auto &DataFrag = cast<MCDataFragment>(Frag);
1281 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1282 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1283 *end = (const uint8_t *)Contents.data() + Contents.size();
1284 p != end; ++p) {
1285 if (*p != 0)
1286 report_fatal_error("non-symbolic data in .init_array section");
1287 }
1288 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1289 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1290 const MCExpr *Expr = Fixup.getValue();
1291 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1292 if (!Sym)
1293 report_fatal_error("fixups in .init_array should be symbol references");
1294 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1295 report_fatal_error("symbols in .init_array should be for functions");
1296 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1297 if (I == SymbolIndices.end())
1298 report_fatal_error("symbols in .init_array should be defined");
1299 uint32_t Index = I->second;
1300 InitFuncs.push_back(std::make_pair(Priority, Index));
1301 }
1302 }
1303
Dan Gohman18eafb62017-02-22 01:23:18 +00001304 // Write out the Wasm header.
1305 writeHeader(Asm);
1306
Sam Clegg9e15f352017-06-03 02:01:24 +00001307 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001308 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001309 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001310 // Skip the "table" section; we import the table instead.
1311 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001312 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001313 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001314 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001315 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001316 writeDataSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001317 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001318 writeDataRelocSection();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001319 writeLinkingMetaDataSection(DataSize, SymbolInfos, InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001320
Dan Gohmand934cb82017-02-24 23:18:00 +00001321 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001322 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001323}
1324
Lang Hames60fbc7c2017-10-10 16:28:07 +00001325std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001326llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1327 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001328 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001329}