blob: c47c014467a7ba4b2b63d636035a4e0e72e0ab7b [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 Cleggd99f6072017-06-12 23:52:44 +0000193 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000194 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
195
196 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
197 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000198 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000199 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000200 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000201 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000202
Dan Gohman18eafb62017-02-22 01:23:18 +0000203 // TargetObjectWriter wrappers.
204 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000205 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
206 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000207 }
208
Dan Gohmand934cb82017-02-24 23:18:00 +0000209 void startSection(SectionBookkeeping &Section, unsigned SectionId,
210 const char *Name = nullptr);
211 void endSection(SectionBookkeeping &Section);
212
Dan Gohman18eafb62017-02-22 01:23:18 +0000213public:
Lang Hames1301a872017-10-10 01:15:10 +0000214 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
215 raw_pwrite_stream &OS)
216 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
217 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000218
Dan Gohman18eafb62017-02-22 01:23:18 +0000219 ~WasmObjectWriter() override;
220
Dan Gohman0917c9e2018-01-15 17:06:23 +0000221private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000222 void reset() override {
223 CodeRelocations.clear();
224 DataRelocations.clear();
225 TypeIndices.clear();
226 SymbolIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000227 TableIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000228 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000229 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000230 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000231 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000232 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000233 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000234 }
235
Dan Gohman18eafb62017-02-22 01:23:18 +0000236 void writeHeader(const MCAssembler &Asm);
237
238 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
239 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000240 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000241
242 void executePostLayoutBinding(MCAssembler &Asm,
243 const MCAsmLayout &Layout) override;
244
245 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000246
Sam Cleggb7787fd2017-06-20 04:04:59 +0000247 void writeString(const StringRef Str) {
248 encodeULEB128(Str.size(), getStream());
249 writeBytes(Str);
250 }
251
Sam Clegg9e15f352017-06-03 02:01:24 +0000252 void writeValueType(wasm::ValType Ty) {
253 encodeSLEB128(int32_t(Ty), getStream());
254 }
255
Sam Clegg457fb0b2017-09-15 19:50:44 +0000256 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000257 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000258 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000259 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000260 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000261 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000262 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000263 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000264 ArrayRef<WasmFunction> Functions);
265 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000266 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000267 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000268 void writeLinkingMetaDataSection(
269 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000270 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
271 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
272 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000273
Sam Clegg7c395942017-09-14 23:07:53 +0000274 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000275 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
276 uint64_t ContentsOffset);
277
Sam Clegg7c395942017-09-14 23:07:53 +0000278 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000279 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000280 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
281 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000282};
Sam Clegg9e15f352017-06-03 02:01:24 +0000283
Dan Gohman18eafb62017-02-22 01:23:18 +0000284} // end anonymous namespace
285
286WasmObjectWriter::~WasmObjectWriter() {}
287
Dan Gohmand934cb82017-02-24 23:18:00 +0000288// Write out a section header and a patchable section size field.
289void WasmObjectWriter::startSection(SectionBookkeeping &Section,
290 unsigned SectionId,
291 const char *Name) {
292 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
293 "Only custom sections can have names");
294
Sam Cleggb7787fd2017-06-20 04:04:59 +0000295 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000296 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000297
298 Section.SizeOffset = getStream().tell();
299
300 // The section size. We don't know the size yet, so reserve enough space
301 // for any 32-bit value; we'll patch it later.
302 encodeULEB128(UINT32_MAX, getStream());
303
304 // The position where the section starts, for measuring its size.
305 Section.ContentsOffset = getStream().tell();
306
307 // Custom sections in wasm also have a string identifier.
308 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000309 assert(Name);
310 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000311 }
312}
313
314// Now that the section is complete and we know how big it is, patch up the
315// section size field at the start of the section.
316void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
317 uint64_t Size = getStream().tell() - Section.ContentsOffset;
318 if (uint32_t(Size) != Size)
319 report_fatal_error("section size does not fit in a uint32_t");
320
Sam Cleggb7787fd2017-06-20 04:04:59 +0000321 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000322
323 // Write the final section size to the payload_len field, which follows
324 // the section id byte.
325 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000326 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000327 assert(SizeLen == 5);
328 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
329}
330
Dan Gohman18eafb62017-02-22 01:23:18 +0000331// Emit the Wasm header.
332void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000333 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
334 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000335}
336
337void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
338 const MCAsmLayout &Layout) {
339}
340
341void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
342 const MCAsmLayout &Layout,
343 const MCFragment *Fragment,
344 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000345 uint64_t &FixedValue) {
346 MCAsmBackend &Backend = Asm.getBackend();
347 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
348 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000349 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000350 uint64_t C = Target.getConstant();
351 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
352 MCContext &Ctx = Asm.getContext();
353
Sam Cleggbafe6902017-12-15 00:17:10 +0000354 // The .init_array isn't translated as data, so don't do relocations in it.
355 if (FixupSection.getSectionName().startswith(".init_array"))
356 return;
357
Sam Cleggb7a54692018-02-16 18:06:05 +0000358 // TODO(sbc): Add support for debug sections.
359 if (FixupSection.getKind().isMetadata())
360 return;
361
Dan Gohmand934cb82017-02-24 23:18:00 +0000362 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
363 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
364 "Should not have constructed this");
365
366 // Let A, B and C being the components of Target and R be the location of
367 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
368 // If it is pcrel, we want to compute (A - B + C - R).
369
370 // In general, Wasm has no relocations for -B. It can only represent (A + C)
371 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
372 // replace B to implement it: (A - R - K + C)
373 if (IsPCRel) {
374 Ctx.reportError(
375 Fixup.getLoc(),
376 "No relocation available to represent this relative expression");
377 return;
378 }
379
380 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
381
382 if (SymB.isUndefined()) {
383 Ctx.reportError(Fixup.getLoc(),
384 Twine("symbol '") + SymB.getName() +
385 "' can not be undefined in a subtraction expression");
386 return;
387 }
388
389 assert(!SymB.isAbsolute() && "Should have been folded");
390 const MCSection &SecB = SymB.getSection();
391 if (&SecB != &FixupSection) {
392 Ctx.reportError(Fixup.getLoc(),
393 "Cannot represent a difference across sections");
394 return;
395 }
396
397 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
398 uint64_t K = SymBOffset - FixupOffset;
399 IsPCRel = true;
400 C -= K;
401 }
402
403 // We either rejected the fixup or folded B into C at this point.
404 const MCSymbolRefExpr *RefA = Target.getSymA();
405 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
406
Dan Gohmand934cb82017-02-24 23:18:00 +0000407 if (SymA && SymA->isVariable()) {
408 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000409 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
410 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
411 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000412 }
413
414 // Put any constant offset in an addend. Offsets can be negative, and
415 // LLVM expects wrapping, in contrast to wasm's immediates which can't
416 // be negative and don't wrap.
417 FixedValue = 0;
418
Sam Clegg6ad8f192017-07-11 02:21:57 +0000419 if (SymA)
420 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000421
Sam Cleggae03c1e72017-06-13 18:51:50 +0000422 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000423 assert(SymA);
424
Sam Cleggae03c1e72017-06-13 18:51:50 +0000425 unsigned Type = getRelocType(Target, Fixup);
426
Dan Gohmand934cb82017-02-24 23:18:00 +0000427 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000428 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000429
Sam Cleggb7a54692018-02-16 18:06:05 +0000430 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are currently required
431 // to be against a named symbol.
432 // TODO(sbc): Add support for relocations against unnamed temporaries such
433 // as those generated by llvm's `blockaddress`.
434 // See: test/MC/WebAssembly/blockaddress.ll
435 if (SymA->getName().empty() && Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
436 report_fatal_error("relocations against un-named temporaries are not yet "
437 "supported by wasm");
438
Sam Clegg12fd3da2017-10-20 21:28:38 +0000439 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000440 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000441 else if (FixupSection.getKind().isText())
442 CodeRelocations.push_back(Rec);
Sam Cleggb7a54692018-02-16 18:06:05 +0000443 else
Sam Clegg12fd3da2017-10-20 21:28:38 +0000444 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000445}
446
Dan Gohmand934cb82017-02-24 23:18:00 +0000447// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
448// to allow patching.
449static void
450WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
451 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000452 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000453 assert(SizeLen == 5);
454 Stream.pwrite((char *)Buffer, SizeLen, Offset);
455}
456
457// Write X as an signed LEB value at offset Offset in Stream, padded
458// to allow patching.
459static void
460WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
461 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000462 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000463 assert(SizeLen == 5);
464 Stream.pwrite((char *)Buffer, SizeLen, Offset);
465}
466
467// Write X as a plain integer value at offset Offset in Stream.
468static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
469 uint8_t Buffer[4];
470 support::endian::write32le(Buffer, X);
471 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
472}
473
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000474static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
475 if (Symbol.isVariable()) {
476 const MCExpr *Expr = Symbol.getVariableValue();
477 auto *Inner = cast<MCSymbolRefExpr>(Expr);
478 return cast<MCSymbolWasm>(&Inner->getSymbol());
479 }
480 return &Symbol;
481}
482
Dan Gohmand934cb82017-02-24 23:18:00 +0000483// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000484// by RelEntry. This value isn't used by the static linker; it just serves
485// to make the object format more readable and more likely to be directly
486// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000487uint32_t
488WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000489 switch (RelEntry.Type) {
490 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000491 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
492 // Provisional value is table address of the resolved symbol itself
493 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
494 assert(Sym->isFunction());
495 return TableIndices[Sym];
496 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000497 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
498 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
499 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000500 // Provisional value is function/type/global index itself
Sam Clegg60ec3032018-01-23 01:23:17 +0000501 return getRelocationIndexValue(RelEntry);
502 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
503 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
504 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000505 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000506 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
507 // For undefined symbols, use zero
508 if (!Sym->isDefined())
509 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000510
Sam Cleggb7a54692018-02-16 18:06:05 +0000511 if (!SymbolIndices.count(Sym))
512 report_fatal_error("symbol not found in function/global index space: " +
513 Sym->getName());
Sam Clegg60ec3032018-01-23 01:23:17 +0000514 uint32_t GlobalIndex = SymbolIndices[Sym];
515 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
516 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000517
Sam Clegg60ec3032018-01-23 01:23:17 +0000518 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
519 return Address;
520 }
521 default:
522 llvm_unreachable("invalid relocation type");
523 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000524}
525
Sam Clegg759631c2017-09-15 20:54:59 +0000526static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000527 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000528 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
529
Sam Clegg63ebb812017-09-29 16:50:08 +0000530 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
531
Sam Cleggc55d13f2017-10-27 00:08:55 +0000532 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000533 for (const MCFragment &Frag : DataSection) {
534 if (Frag.hasInstructions())
535 report_fatal_error("only data supported in data sections");
536
537 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
538 if (Align->getValueSize() != 1)
539 report_fatal_error("only byte values supported for alignment");
540 // If nops are requested, use zeros, as this is the data section.
541 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
542 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
543 Align->getAlignment()),
544 DataBytes.size() +
545 Align->getMaxBytesToEmit());
546 DataBytes.resize(Size, Value);
547 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000548 int64_t Size;
549 if (!Fill->getSize().evaluateAsAbsolute(Size))
550 llvm_unreachable("The fill should be an assembler constant");
551 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000552 } else {
553 const auto &DataFrag = cast<MCDataFragment>(Frag);
554 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
555
556 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000557 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000558 }
559 }
560
Sam Cleggc55d13f2017-10-27 00:08:55 +0000561 // Don't allow empty segments, or segments that end with zero-sized
562 // fragment, otherwise the linker cannot map symbols to a unique
563 // data segment. This can be triggered by zero-sized structs
564 // See: test/MC/WebAssembly/bss.ll
565 if (LastFragmentSize == 0)
566 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000567 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
568}
569
Sam Clegg60ec3032018-01-23 01:23:17 +0000570uint32_t
571WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
572 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000573 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000574 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000575 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000576 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000577 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000578
579 if (!SymbolIndices.count(RelEntry.Symbol))
580 report_fatal_error("symbol not found in function/global index space: " +
581 RelEntry.Symbol->getName());
582 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000583}
584
Dan Gohmand934cb82017-02-24 23:18:00 +0000585// Apply the portions of the relocation records that we can handle ourselves
586// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000587void WasmObjectWriter::applyRelocations(
588 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
589 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000590 for (const WasmRelocationEntry &RelEntry : Relocations) {
591 uint64_t Offset = ContentsOffset +
592 RelEntry.FixupSection->getSectionOffset() +
593 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000594
Sam Cleggb7787fd2017-06-20 04:04:59 +0000595 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000596 uint32_t Value = getProvisionalValue(RelEntry);
597
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000598 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000599 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000600 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000601 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
602 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000603 WritePatchableLEB(Stream, Value, Offset);
604 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000605 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
606 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000607 WriteI32(Stream, Value, Offset);
608 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
610 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
611 WritePatchableSLEB(Stream, Value, Offset);
612 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000613 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000614 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000615 }
616 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000617}
618
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000619// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000620// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000621void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000622 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000623 raw_pwrite_stream &Stream = getStream();
624 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000625
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000626 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000627 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000628 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000629
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000631 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000632 encodeULEB128(Index, Stream);
633 if (RelEntry.hasAddend())
634 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000635 }
636}
637
Sam Clegg9e15f352017-06-03 02:01:24 +0000638void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000639 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000640 if (FunctionTypes.empty())
641 return;
642
643 SectionBookkeeping Section;
644 startSection(Section, wasm::WASM_SEC_TYPE);
645
646 encodeULEB128(FunctionTypes.size(), getStream());
647
648 for (const WasmFunctionType &FuncTy : FunctionTypes) {
649 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
650 encodeULEB128(FuncTy.Params.size(), getStream());
651 for (wasm::ValType Ty : FuncTy.Params)
652 writeValueType(Ty);
653 encodeULEB128(FuncTy.Returns.size(), getStream());
654 for (wasm::ValType Ty : FuncTy.Returns)
655 writeValueType(Ty);
656 }
657
658 endSection(Section);
659}
660
Sam Clegg8defa952018-02-12 22:41:29 +0000661void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000662 uint32_t DataSize,
663 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000664 if (Imports.empty())
665 return;
666
Sam Cleggf950b242017-12-11 23:03:38 +0000667 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
668
Sam Clegg9e15f352017-06-03 02:01:24 +0000669 SectionBookkeeping Section;
670 startSection(Section, wasm::WASM_SEC_IMPORT);
671
672 encodeULEB128(Imports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000673 for (const wasm::WasmImport &Import : Imports) {
674 writeString(Import.Module);
675 writeString(Import.Field);
Sam Clegg9e15f352017-06-03 02:01:24 +0000676 encodeULEB128(Import.Kind, getStream());
677
678 switch (Import.Kind) {
679 case wasm::WASM_EXTERNAL_FUNCTION:
Sam Clegg8defa952018-02-12 22:41:29 +0000680 encodeULEB128(Import.SigIndex, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000681 break;
682 case wasm::WASM_EXTERNAL_GLOBAL:
Sam Clegg8defa952018-02-12 22:41:29 +0000683 encodeSLEB128(Import.Global.Type, getStream());
684 encodeULEB128(uint32_t(Import.Global.Mutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000685 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000686 case wasm::WASM_EXTERNAL_MEMORY:
687 encodeULEB128(0, getStream()); // flags
688 encodeULEB128(NumPages, getStream()); // initial
689 break;
690 case wasm::WASM_EXTERNAL_TABLE:
Sam Clegg8defa952018-02-12 22:41:29 +0000691 encodeSLEB128(Import.Table.ElemType, getStream());
Sam Cleggf950b242017-12-11 23:03:38 +0000692 encodeULEB128(0, getStream()); // flags
693 encodeULEB128(NumElements, getStream()); // initial
694 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000695 default:
696 llvm_unreachable("unsupported import kind");
697 }
698 }
699
700 endSection(Section);
701}
702
Sam Clegg457fb0b2017-09-15 19:50:44 +0000703void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000704 if (Functions.empty())
705 return;
706
707 SectionBookkeeping Section;
708 startSection(Section, wasm::WASM_SEC_FUNCTION);
709
710 encodeULEB128(Functions.size(), getStream());
711 for (const WasmFunction &Func : Functions)
712 encodeULEB128(Func.Type, getStream());
713
714 endSection(Section);
715}
716
Sam Clegg7c395942017-09-14 23:07:53 +0000717void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000718 if (Globals.empty())
719 return;
720
721 SectionBookkeeping Section;
722 startSection(Section, wasm::WASM_SEC_GLOBAL);
723
724 encodeULEB128(Globals.size(), getStream());
725 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000726 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
727 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000728
Sam Clegg6e7f1822018-01-31 19:50:14 +0000729 write8(wasm::WASM_OPCODE_I32_CONST);
730 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000731 write8(wasm::WASM_OPCODE_END);
732 }
733
734 endSection(Section);
735}
736
Sam Clegg8defa952018-02-12 22:41:29 +0000737void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000738 if (Exports.empty())
739 return;
740
741 SectionBookkeeping Section;
742 startSection(Section, wasm::WASM_SEC_EXPORT);
743
744 encodeULEB128(Exports.size(), getStream());
Sam Clegg8defa952018-02-12 22:41:29 +0000745 for (const wasm::WasmExport &Export : Exports) {
746 writeString(Export.Name);
Sam Clegg9e15f352017-06-03 02:01:24 +0000747 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000748 encodeULEB128(Export.Index, getStream());
749 }
750
751 endSection(Section);
752}
753
Sam Clegg457fb0b2017-09-15 19:50:44 +0000754void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000755 if (TableElems.empty())
756 return;
757
758 SectionBookkeeping Section;
759 startSection(Section, wasm::WASM_SEC_ELEM);
760
761 encodeULEB128(1, getStream()); // number of "segments"
762 encodeULEB128(0, getStream()); // the table index
763
764 // init expr for starting offset
765 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000766 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000767 write8(wasm::WASM_OPCODE_END);
768
769 encodeULEB128(TableElems.size(), getStream());
770 for (uint32_t Elem : TableElems)
771 encodeULEB128(Elem, getStream());
772
773 endSection(Section);
774}
775
Sam Clegg457fb0b2017-09-15 19:50:44 +0000776void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
777 const MCAsmLayout &Layout,
778 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 if (Functions.empty())
780 return;
781
782 SectionBookkeeping Section;
783 startSection(Section, wasm::WASM_SEC_CODE);
784
785 encodeULEB128(Functions.size(), getStream());
786
787 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000788 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000789
Sam Clegg9e15f352017-06-03 02:01:24 +0000790 int64_t Size = 0;
791 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
792 report_fatal_error(".size expression must be evaluatable");
793
794 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000795 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000796 Asm.writeSectionData(&FuncSection, Layout);
797 }
798
Sam Clegg9e15f352017-06-03 02:01:24 +0000799 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000800 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000801
802 endSection(Section);
803}
804
Sam Clegg457fb0b2017-09-15 19:50:44 +0000805void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000806 if (Segments.empty())
807 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000808
809 SectionBookkeeping Section;
810 startSection(Section, wasm::WASM_SEC_DATA);
811
Sam Clegg7c395942017-09-14 23:07:53 +0000812 encodeULEB128(Segments.size(), getStream()); // count
813
814 for (const WasmDataSegment & Segment : Segments) {
815 encodeULEB128(0, getStream()); // memory index
816 write8(wasm::WASM_OPCODE_I32_CONST);
817 encodeSLEB128(Segment.Offset, getStream()); // offset
818 write8(wasm::WASM_OPCODE_END);
819 encodeULEB128(Segment.Data.size(), getStream()); // size
820 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
821 writeBytes(Segment.Data); // data
822 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000823
824 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000825 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000826
827 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000828}
829
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000830void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000831 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
832 // for descriptions of the reloc sections.
833
834 if (CodeRelocations.empty())
835 return;
836
837 SectionBookkeeping Section;
838 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
839
840 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000841 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000842
Sam Clegg7c395942017-09-14 23:07:53 +0000843 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000844
845 endSection(Section);
846}
847
Sam Clegg7c395942017-09-14 23:07:53 +0000848void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000849 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
850 // for descriptions of the reloc sections.
851
852 if (DataRelocations.empty())
853 return;
854
855 SectionBookkeeping Section;
856 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
857
858 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
859 encodeULEB128(DataRelocations.size(), getStream());
860
Sam Clegg7c395942017-09-14 23:07:53 +0000861 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000862
863 endSection(Section);
864}
865
866void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000867 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000868 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
869 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
870 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000873 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
Sam Clegg31a2c802017-09-20 21:17:04 +0000875 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000876 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000877 encodeULEB128(SymbolFlags.size(), getStream());
878 for (auto Pair: SymbolFlags) {
879 writeString(Pair.first);
880 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000881 }
882 endSection(SubSection);
883 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000884
Sam Clegg9e1ade92017-06-27 20:27:59 +0000885 if (DataSize > 0) {
886 startSection(SubSection, wasm::WASM_DATA_SIZE);
887 encodeULEB128(DataSize, getStream());
888 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000889 }
890
Sam Cleggd95ed952017-09-20 19:03:35 +0000891 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000892 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000893 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000894 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000895 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000896 encodeULEB128(Segment.Alignment, getStream());
897 encodeULEB128(Segment.Flags, getStream());
898 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000899 endSection(SubSection);
900 }
901
Sam Cleggbafe6902017-12-15 00:17:10 +0000902 if (!InitFuncs.empty()) {
903 startSection(SubSection, wasm::WASM_INIT_FUNCS);
904 encodeULEB128(InitFuncs.size(), getStream());
905 for (auto &StartFunc : InitFuncs) {
906 encodeULEB128(StartFunc.first, getStream()); // priority
907 encodeULEB128(StartFunc.second, getStream()); // function index
908 }
909 endSection(SubSection);
910 }
911
Sam Cleggea7cace2018-01-09 23:43:14 +0000912 if (Comdats.size()) {
913 startSection(SubSection, wasm::WASM_COMDAT_INFO);
914 encodeULEB128(Comdats.size(), getStream());
915 for (const auto &C : Comdats) {
916 writeString(C.first);
917 encodeULEB128(0, getStream()); // flags for future use
918 encodeULEB128(C.second.size(), getStream());
919 for (const WasmComdatEntry &Entry : C.second) {
920 encodeULEB128(Entry.Kind, getStream());
921 encodeULEB128(Entry.Index, getStream());
922 }
923 }
924 endSection(SubSection);
925 }
926
Sam Clegg9e15f352017-06-03 02:01:24 +0000927 endSection(Section);
928}
929
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000930uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
931 assert(Symbol.isFunction());
932 assert(TypeIndices.count(&Symbol));
933 return TypeIndices[&Symbol];
934}
935
936uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
937 assert(Symbol.isFunction());
938
939 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000940 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
941 F.Returns = ResolvedSym->getReturns();
942 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000943
944 auto Pair =
945 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
946 if (Pair.second)
947 FunctionTypes.push_back(F);
948 TypeIndices[&Symbol] = Pair.first->second;
949
950 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
951 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
952 return Pair.first->second;
953}
954
Dan Gohman18eafb62017-02-22 01:23:18 +0000955void WasmObjectWriter::writeObject(MCAssembler &Asm,
956 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000957 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000958 MCContext &Ctx = Asm.getContext();
Sam Clegg6e7f1822018-01-31 19:50:14 +0000959 int32_t PtrType = is64Bit() ? wasm::WASM_TYPE_I64 : wasm::WASM_TYPE_I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000960
961 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000962 SmallVector<WasmFunction, 4> Functions;
963 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +0000964 SmallVector<wasm::WasmImport, 4> Imports;
965 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +0000966 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Sam Cleggbafe6902017-12-15 00:17:10 +0000967 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000968 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +0000969 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +0000970 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000971
Sam Cleggf950b242017-12-11 23:03:38 +0000972 // For now, always emit the memory import, since loads and stores are not
973 // valid without it. In the future, we could perhaps be more clever and omit
974 // it if there are no loads or stores.
975 MCSymbolWasm *MemorySym =
976 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +0000977 wasm::WasmImport MemImport;
978 MemImport.Module = MemorySym->getModuleName();
979 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +0000980 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
981 Imports.push_back(MemImport);
982
983 // For now, always emit the table section, since indirect calls are not
984 // valid without it. In the future, we could perhaps be more clever and omit
985 // it if there are no indirect calls.
986 MCSymbolWasm *TableSym =
987 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +0000988 wasm::WasmImport TableImport;
989 TableImport.Module = TableSym->getModuleName();
990 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +0000991 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +0000992 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +0000993 Imports.push_back(TableImport);
994
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000995 // Populate FunctionTypeIndices and Imports.
996 for (const MCSymbol &S : Asm.symbols()) {
997 const auto &WS = static_cast<const MCSymbolWasm &>(S);
998
999 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001000 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001001 if (WS.isFunction())
1002 registerFunctionType(WS);
1003
1004 if (WS.isTemporary())
1005 continue;
1006
1007 // If the symbol is not defined in this translation unit, import it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001008 if ((!WS.isDefined() && !WS.isComdat()) ||
Sam Cleggd423f0d2018-01-11 20:35:17 +00001009 WS.isVariable()) {
Sam Clegg8defa952018-02-12 22:41:29 +00001010 wasm::WasmImport Import;
1011 Import.Module = WS.getModuleName();
1012 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001013
1014 if (WS.isFunction()) {
1015 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001016 Import.SigIndex = getFunctionType(WS);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001017 SymbolIndices[&WS] = NumFunctionImports;
1018 ++NumFunctionImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001019 } else {
1020 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg8defa952018-02-12 22:41:29 +00001021 Import.Global.Type = PtrType;
Dan Gohman83b16222017-12-20 00:10:28 +00001022 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001023 if (WS.getName() == "__stack_pointer")
Sam Clegg8defa952018-02-12 22:41:29 +00001024 Import.Global.Mutable = true;
1025 else
1026 Import.Global.Mutable = false;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001027
Sam Clegg8defa952018-02-12 22:41:29 +00001028 SymbolIndices[&WS] = NumGlobalImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001029 ++NumGlobalImports;
1030 }
1031
1032 Imports.push_back(Import);
1033 }
1034 }
1035
Sam Clegg759631c2017-09-15 20:54:59 +00001036 for (MCSection &Sec : Asm) {
1037 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001038 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001039 continue;
1040
Sam Cleggbafe6902017-12-15 00:17:10 +00001041 // .init_array sections are handled specially elsewhere.
1042 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1043 continue;
1044
Sam Clegg329e76d2018-01-31 04:21:44 +00001045 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001046 DataSize = alignTo(DataSize, Section.getAlignment());
1047 DataSegments.emplace_back();
1048 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001049 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001050 Segment.Offset = DataSize;
1051 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001052 addData(Segment.Data, Section);
1053 Segment.Alignment = Section.getAlignment();
1054 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001055 DataSize += Segment.Data.size();
1056 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001057
1058 if (const MCSymbolWasm *C = Section.getGroup()) {
1059 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001060 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001061 }
Sam Clegg759631c2017-09-15 20:54:59 +00001062 }
1063
Sam Cleggb7787fd2017-06-20 04:04:59 +00001064 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001065 for (const MCSymbol &S : Asm.symbols()) {
1066 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1067 // or used in relocations.
1068 if (S.isTemporary() && S.getName().empty())
1069 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001070
Dan Gohmand934cb82017-02-24 23:18:00 +00001071 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001072 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001073 << " isDefined=" << S.isDefined()
1074 << " isExternal=" << S.isExternal()
1075 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001076 << " isFunction=" << WS.isFunction()
1077 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001078 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001079 << " isVariable=" << WS.isVariable() << "\n");
1080
Sam Clegga2b35da2017-12-03 01:19:23 +00001081 if (WS.isWeak() || WS.isHidden()) {
1082 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1083 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1084 SymbolFlags.emplace_back(WS.getName(), Flags);
1085 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001086
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001087 if (WS.isVariable())
1088 continue;
1089
Dan Gohmand934cb82017-02-24 23:18:00 +00001090 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001091
Dan Gohmand934cb82017-02-24 23:18:00 +00001092 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001093 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001094 if (WS.getOffset() != 0)
1095 report_fatal_error(
1096 "function sections must contain one function each");
1097
1098 if (WS.getSize() == 0)
1099 report_fatal_error(
1100 "function symbols must have a size set with .size");
1101
Dan Gohmand934cb82017-02-24 23:18:00 +00001102 // A definition. Take the next available index.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001103 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001104
1105 // Prepare the function.
1106 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001107 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001108 Func.Sym = &WS;
1109 SymbolIndices[&WS] = Index;
1110 Functions.push_back(Func);
1111 } else {
1112 // An import; the index was assigned above.
1113 Index = SymbolIndices.find(&WS)->second;
1114 }
1115
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001116 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001117 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001118 if (WS.isTemporary() && !WS.getSize())
1119 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001120
Sam Cleggcd65f692018-01-11 23:59:16 +00001121 if (!WS.isDefined())
Sam Cleggfe6414b2017-06-21 23:46:41 +00001122 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001123
Sam Cleggfe6414b2017-06-21 23:46:41 +00001124 if (!WS.getSize())
1125 report_fatal_error("data symbols must have a size set with .size: " +
1126 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001127
Sam Cleggfe6414b2017-06-21 23:46:41 +00001128 int64_t Size = 0;
1129 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1130 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001131
Sam Clegg7c395942017-09-14 23:07:53 +00001132 // For each global, prepare a corresponding wasm global holding its
1133 // address. For externals these will also be named exports.
1134 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001135 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001136 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001137
1138 WasmGlobal Global;
Sam Clegg6e7f1822018-01-31 19:50:14 +00001139 Global.Type.Type = PtrType;
1140 Global.Type.Mutable = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001141 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001142 SymbolIndices[&WS] = Index;
1143 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1144 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001145 }
1146
1147 // If the symbol is visible outside this translation unit, export it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001148 if (WS.isDefined()) {
Sam Clegg8defa952018-02-12 22:41:29 +00001149 wasm::WasmExport Export;
1150 Export.Name = WS.getName();
Dan Gohmand934cb82017-02-24 23:18:00 +00001151 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001152 if (WS.isFunction())
1153 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1154 else
1155 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001156 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001157 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001158
Sam Clegg31a2c802017-09-20 21:17:04 +00001159 if (!WS.isExternal())
1160 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001161
1162 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001163 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001164 if (const MCSymbolWasm *C = Section.getGroup())
1165 Comdats[C->getName()].emplace_back(
1166 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1167 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001168 }
1169 }
1170
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001171 // Handle weak aliases. We need to process these in a separate pass because
1172 // we need to have processed the target of the alias before the alias itself
1173 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001174 for (const MCSymbol &S : Asm.symbols()) {
1175 if (!S.isVariable())
1176 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001177
Sam Cleggcd65f692018-01-11 23:59:16 +00001178 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001179
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001180 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001181 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1182 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001183 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1184 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001185 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001186 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001187
Sam Clegg8defa952018-02-12 22:41:29 +00001188 wasm::WasmExport Export;
1189 Export.Name = WS.getName();
Sam Cleggb7787fd2017-06-20 04:04:59 +00001190 Export.Index = Index;
1191 if (WS.isFunction())
1192 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1193 else
1194 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001195 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001196 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001197
1198 if (!WS.isExternal())
1199 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001200 }
1201
Sam Clegg6006e092017-12-22 20:31:39 +00001202 {
1203 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001204 // Functions referenced by a relocation need to put in the table. This is
1205 // purely to make the object file's provisional values readable, and is
1206 // ignored by the linker, which re-calculates the relocations itself.
1207 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1208 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1209 return;
1210 assert(Rel.Symbol->isFunction());
1211 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
1212 uint32_t SymbolIndex = SymbolIndices.find(&WS)->second;
1213 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1214 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1215 DEBUG(dbgs() << " -> adding " << WS.getName()
1216 << " to table: " << TableIndex << "\n");
1217 TableElems.push_back(SymbolIndex);
1218 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001219 }
1220 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001221
Sam Clegg6006e092017-12-22 20:31:39 +00001222 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1223 HandleReloc(RelEntry);
1224 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1225 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001226 }
1227
Sam Cleggbafe6902017-12-15 00:17:10 +00001228 // Translate .init_array section contents into start functions.
1229 for (const MCSection &S : Asm) {
1230 const auto &WS = static_cast<const MCSectionWasm &>(S);
1231 if (WS.getSectionName().startswith(".fini_array"))
1232 report_fatal_error(".fini_array sections are unsupported");
1233 if (!WS.getSectionName().startswith(".init_array"))
1234 continue;
1235 if (WS.getFragmentList().empty())
1236 continue;
1237 if (WS.getFragmentList().size() != 2)
1238 report_fatal_error("only one .init_array section fragment supported");
1239 const MCFragment &AlignFrag = *WS.begin();
1240 if (AlignFrag.getKind() != MCFragment::FT_Align)
1241 report_fatal_error(".init_array section should be aligned");
1242 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1243 report_fatal_error(".init_array section should be aligned for pointers");
1244 const MCFragment &Frag = *std::next(WS.begin());
1245 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1246 report_fatal_error("only data supported in .init_array section");
1247 uint16_t Priority = UINT16_MAX;
1248 if (WS.getSectionName().size() != 11) {
1249 if (WS.getSectionName()[11] != '.')
1250 report_fatal_error(".init_array section priority should start with '.'");
1251 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1252 report_fatal_error("invalid .init_array section priority");
1253 }
1254 const auto &DataFrag = cast<MCDataFragment>(Frag);
1255 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1256 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1257 *end = (const uint8_t *)Contents.data() + Contents.size();
1258 p != end; ++p) {
1259 if (*p != 0)
1260 report_fatal_error("non-symbolic data in .init_array section");
1261 }
1262 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1263 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1264 const MCExpr *Expr = Fixup.getValue();
1265 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1266 if (!Sym)
1267 report_fatal_error("fixups in .init_array should be symbol references");
1268 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1269 report_fatal_error("symbols in .init_array should be for functions");
1270 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1271 if (I == SymbolIndices.end())
1272 report_fatal_error("symbols in .init_array should be defined");
1273 uint32_t Index = I->second;
1274 InitFuncs.push_back(std::make_pair(Priority, Index));
1275 }
1276 }
1277
Dan Gohman18eafb62017-02-22 01:23:18 +00001278 // Write out the Wasm header.
1279 writeHeader(Asm);
1280
Sam Clegg9e15f352017-06-03 02:01:24 +00001281 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001282 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001283 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001284 // Skip the "table" section; we import the table instead.
1285 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001286 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001287 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001288 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001289 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001290 writeDataSection(DataSegments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001291 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001292 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001293 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001294 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001295
Dan Gohmand934cb82017-02-24 23:18:00 +00001296 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001297 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001298}
1299
Lang Hames60fbc7c2017-10-10 16:28:07 +00001300std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001301llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1302 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001303 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001304}