blob: 1ae292e51356022632f439cf13d8af551ac02a0d [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"
18#include "llvm/MC/MCAsmInfo.h"
19#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCAssembler.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCFixupKindInfo.h"
24#include "llvm/MC/MCObjectFileInfo.h"
25#include "llvm/MC/MCObjectWriter.h"
26#include "llvm/MC/MCSectionWasm.h"
27#include "llvm/MC/MCSymbolWasm.h"
28#include "llvm/MC/MCValue.h"
29#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000030#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000031#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000033#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000034#include "llvm/Support/StringSaver.h"
35#include <vector>
36
37using namespace llvm;
38
Sam Clegg5e3d33a2017-07-07 02:01:29 +000039#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000040
41namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000042
Dan Gohmand934cb82017-02-24 23:18:00 +000043// For patching purposes, we need to remember where each section starts, both
44// for patching up the section size field, and for patching up references to
45// locations within the section.
46struct SectionBookkeeping {
47 // Where the size of the section is written.
48 uint64_t SizeOffset;
49 // Where the contents of the section starts (after the header).
50 uint64_t ContentsOffset;
51};
52
Sam Clegg9e15f352017-06-03 02:01:24 +000053// The signature of a wasm function, in a struct capable of being used as a
54// DenseMap key.
55struct WasmFunctionType {
56 // Support empty and tombstone instances, needed by DenseMap.
57 enum { Plain, Empty, Tombstone } State;
58
59 // The return types of the function.
60 SmallVector<wasm::ValType, 1> Returns;
61
62 // The parameter types of the function.
63 SmallVector<wasm::ValType, 4> Params;
64
65 WasmFunctionType() : State(Plain) {}
66
67 bool operator==(const WasmFunctionType &Other) const {
68 return State == Other.State && Returns == Other.Returns &&
69 Params == Other.Params;
70 }
71};
72
73// Traits for using WasmFunctionType in a DenseMap.
74struct WasmFunctionTypeDenseMapInfo {
75 static WasmFunctionType getEmptyKey() {
76 WasmFunctionType FuncTy;
77 FuncTy.State = WasmFunctionType::Empty;
78 return FuncTy;
79 }
80 static WasmFunctionType getTombstoneKey() {
81 WasmFunctionType FuncTy;
82 FuncTy.State = WasmFunctionType::Tombstone;
83 return FuncTy;
84 }
85 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
86 uintptr_t Value = FuncTy.State;
87 for (wasm::ValType Ret : FuncTy.Returns)
88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
89 for (wasm::ValType Param : FuncTy.Params)
90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
91 return Value;
92 }
93 static bool isEqual(const WasmFunctionType &LHS,
94 const WasmFunctionType &RHS) {
95 return LHS == RHS;
96 }
97};
98
Sam Clegg7c395942017-09-14 23:07:53 +000099// A wasm data segment. A wasm binary contains only a single data section
100// but that can contain many segments, each with their own virtual location
101// in memory. Each MCSection data created by llvm is modeled as its own
102// wasm data segment.
103struct WasmDataSegment {
104 MCSectionWasm *Section;
105 uint32_t Offset;
106 SmallVector<char, 4> Data;
107};
108
Sam Clegg9e15f352017-06-03 02:01:24 +0000109// A wasm import to be written into the import section.
110struct WasmImport {
111 StringRef ModuleName;
112 StringRef FieldName;
113 unsigned Kind;
114 int32_t Type;
115};
116
117// A wasm function to be written into the function section.
118struct WasmFunction {
119 int32_t Type;
120 const MCSymbolWasm *Sym;
121};
122
123// A wasm export to be written into the export section.
124struct WasmExport {
125 StringRef FieldName;
126 unsigned Kind;
127 uint32_t Index;
128};
129
130// A wasm global to be written into the global section.
131struct WasmGlobal {
132 wasm::ValType Type;
133 bool IsMutable;
134 bool HasImport;
135 uint64_t InitialValue;
136 uint32_t ImportIndex;
137};
138
Sam Clegg6dc65e92017-06-06 16:38:59 +0000139// Information about a single relocation.
140struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000141 uint64_t Offset; // Where is the relocation.
142 const MCSymbolWasm *Symbol; // The symbol to relocate with.
143 int64_t Addend; // A value to add to the symbol.
144 unsigned Type; // The type of the relocation.
145 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000146
147 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
148 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000149 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000150 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
151 FixupSection(FixupSection) {}
152
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000153 bool hasAddend() const {
154 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
157 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000158 return true;
159 default:
160 return false;
161 }
162 }
163
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000165 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg6dc65e92017-06-06 16:38:59 +0000166 << ", Type=" << Type << ", FixupSection=" << FixupSection;
167 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000168
169#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
170 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
171#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000172};
173
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000174#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000175raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000176 Rel.print(OS);
177 return OS;
178}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000179#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000180
Dan Gohman18eafb62017-02-22 01:23:18 +0000181class WasmObjectWriter : public MCObjectWriter {
182 /// Helper struct for containing some precomputed information on symbols.
183 struct WasmSymbolData {
184 const MCSymbolWasm *Symbol;
185 StringRef Name;
186
187 // Support lexicographic sorting.
188 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
189 };
190
191 /// The target specific Wasm writer instance.
192 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
193
Dan Gohmand934cb82017-02-24 23:18:00 +0000194 // Relocations for fixing up references in the code section.
195 std::vector<WasmRelocationEntry> CodeRelocations;
196
197 // Relocations for fixing up references in the data section.
198 std::vector<WasmRelocationEntry> DataRelocations;
199
Dan Gohmand934cb82017-02-24 23:18:00 +0000200 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000201 // Maps function symbols to the index of the type of the function
202 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000203 // Maps function symbols to the table element index space. Used
204 // for TABLE_INDEX relocation types (i.e. address taken functions).
205 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
206 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000207 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
208
209 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
210 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000211 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000212 SmallVector<WasmGlobal, 4> Globals;
213 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000214
Dan Gohman18eafb62017-02-22 01:23:18 +0000215 // TargetObjectWriter wrappers.
216 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000217 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
218 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000219 }
220
Dan Gohmand934cb82017-02-24 23:18:00 +0000221 void startSection(SectionBookkeeping &Section, unsigned SectionId,
222 const char *Name = nullptr);
223 void endSection(SectionBookkeeping &Section);
224
Dan Gohman18eafb62017-02-22 01:23:18 +0000225public:
226 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
227 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
228
Dan Gohmand934cb82017-02-24 23:18:00 +0000229private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000230 ~WasmObjectWriter() override;
231
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000232 void reset() override {
233 CodeRelocations.clear();
234 DataRelocations.clear();
235 TypeIndices.clear();
236 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000237 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000238 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000239 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000240 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000241 MCObjectWriter::reset();
Sam Clegg7c395942017-09-14 23:07:53 +0000242 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000243 }
244
Dan Gohman18eafb62017-02-22 01:23:18 +0000245 void writeHeader(const MCAssembler &Asm);
246
247 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
248 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000249 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000250
251 void executePostLayoutBinding(MCAssembler &Asm,
252 const MCAsmLayout &Layout) override;
253
254 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000255
Sam Cleggb7787fd2017-06-20 04:04:59 +0000256 void writeString(const StringRef Str) {
257 encodeULEB128(Str.size(), getStream());
258 writeBytes(Str);
259 }
260
Sam Clegg9e15f352017-06-03 02:01:24 +0000261 void writeValueType(wasm::ValType Ty) {
262 encodeSLEB128(int32_t(Ty), getStream());
263 }
264
265 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
266 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
267 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000268 void writeTableSection(uint32_t NumElements);
Sam Clegg7c395942017-09-14 23:07:53 +0000269 void writeMemorySection(uint32_t DataSize);
270 void writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +0000271 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
272 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
273 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000274 const SmallVector<WasmFunction, 4> &Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000275 void writeDataSection(const SmallVector<WasmDataSegment, 4> &Segments);
Sam Clegg9e15f352017-06-03 02:01:24 +0000276 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
277 const SmallVector<WasmImport, 4> &Imports,
278 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000279 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000280 void writeDataRelocSection();
Sam Clegg9e1ade92017-06-27 20:27:59 +0000281 void writeLinkingMetaDataSection(uint32_t DataSize, uint32_t DataAlignment,
282 ArrayRef<StringRef> WeakSymbols,
Sam Cleggb7787fd2017-06-20 04:04:59 +0000283 bool HasStackPointer,
Sam Clegg9e15f352017-06-03 02:01:24 +0000284 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000285
Sam Clegg7c395942017-09-14 23:07:53 +0000286 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000287 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
288 uint64_t ContentsOffset);
289
Sam Clegg7c395942017-09-14 23:07:53 +0000290 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000291 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000292 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
293 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000294};
Sam Clegg9e15f352017-06-03 02:01:24 +0000295
Dan Gohman18eafb62017-02-22 01:23:18 +0000296} // end anonymous namespace
297
298WasmObjectWriter::~WasmObjectWriter() {}
299
Dan Gohmand934cb82017-02-24 23:18:00 +0000300// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
301static unsigned PaddingFor5ByteULEB128(uint32_t X) {
302 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
303}
304
305// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
306static unsigned PaddingFor5ByteSLEB128(int32_t X) {
307 return 5 - getSLEB128Size(X);
308}
309
310// Write out a section header and a patchable section size field.
311void WasmObjectWriter::startSection(SectionBookkeeping &Section,
312 unsigned SectionId,
313 const char *Name) {
314 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
315 "Only custom sections can have names");
316
Sam Cleggb7787fd2017-06-20 04:04:59 +0000317 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000318 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000319
320 Section.SizeOffset = getStream().tell();
321
322 // The section size. We don't know the size yet, so reserve enough space
323 // for any 32-bit value; we'll patch it later.
324 encodeULEB128(UINT32_MAX, getStream());
325
326 // The position where the section starts, for measuring its size.
327 Section.ContentsOffset = getStream().tell();
328
329 // Custom sections in wasm also have a string identifier.
330 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000331 assert(Name);
332 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000333 }
334}
335
336// Now that the section is complete and we know how big it is, patch up the
337// section size field at the start of the section.
338void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
339 uint64_t Size = getStream().tell() - Section.ContentsOffset;
340 if (uint32_t(Size) != Size)
341 report_fatal_error("section size does not fit in a uint32_t");
342
Sam Cleggb7787fd2017-06-20 04:04:59 +0000343 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000344 unsigned Padding = PaddingFor5ByteULEB128(Size);
345
346 // Write the final section size to the payload_len field, which follows
347 // the section id byte.
348 uint8_t Buffer[16];
349 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
350 assert(SizeLen == 5);
351 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
352}
353
Dan Gohman18eafb62017-02-22 01:23:18 +0000354// Emit the Wasm header.
355void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000356 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
357 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000358}
359
360void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
361 const MCAsmLayout &Layout) {
362}
363
364void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
365 const MCAsmLayout &Layout,
366 const MCFragment *Fragment,
367 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000368 uint64_t &FixedValue) {
369 MCAsmBackend &Backend = Asm.getBackend();
370 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
371 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000372 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000373 uint64_t C = Target.getConstant();
374 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
375 MCContext &Ctx = Asm.getContext();
376
377 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
378 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
379 "Should not have constructed this");
380
381 // Let A, B and C being the components of Target and R be the location of
382 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
383 // If it is pcrel, we want to compute (A - B + C - R).
384
385 // In general, Wasm has no relocations for -B. It can only represent (A + C)
386 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
387 // replace B to implement it: (A - R - K + C)
388 if (IsPCRel) {
389 Ctx.reportError(
390 Fixup.getLoc(),
391 "No relocation available to represent this relative expression");
392 return;
393 }
394
395 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
396
397 if (SymB.isUndefined()) {
398 Ctx.reportError(Fixup.getLoc(),
399 Twine("symbol '") + SymB.getName() +
400 "' can not be undefined in a subtraction expression");
401 return;
402 }
403
404 assert(!SymB.isAbsolute() && "Should have been folded");
405 const MCSection &SecB = SymB.getSection();
406 if (&SecB != &FixupSection) {
407 Ctx.reportError(Fixup.getLoc(),
408 "Cannot represent a difference across sections");
409 return;
410 }
411
412 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
413 uint64_t K = SymBOffset - FixupOffset;
414 IsPCRel = true;
415 C -= K;
416 }
417
418 // We either rejected the fixup or folded B into C at this point.
419 const MCSymbolRefExpr *RefA = Target.getSymA();
420 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
421
Dan Gohmand934cb82017-02-24 23:18:00 +0000422 if (SymA && SymA->isVariable()) {
423 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000424 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
425 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
426 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000427 }
428
429 // Put any constant offset in an addend. Offsets can be negative, and
430 // LLVM expects wrapping, in contrast to wasm's immediates which can't
431 // be negative and don't wrap.
432 FixedValue = 0;
433
Sam Clegg6ad8f192017-07-11 02:21:57 +0000434 if (SymA)
435 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000436
Sam Cleggae03c1e72017-06-13 18:51:50 +0000437 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000438 assert(SymA);
439
Sam Cleggae03c1e72017-06-13 18:51:50 +0000440 unsigned Type = getRelocType(Target, Fixup);
441
Dan Gohmand934cb82017-02-24 23:18:00 +0000442 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000443 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000444
445 if (FixupSection.hasInstructions())
446 CodeRelocations.push_back(Rec);
447 else
448 DataRelocations.push_back(Rec);
449}
450
Dan Gohmand934cb82017-02-24 23:18:00 +0000451// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
452// to allow patching.
453static void
454WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
455 uint8_t Buffer[5];
456 unsigned Padding = PaddingFor5ByteULEB128(X);
457 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
458 assert(SizeLen == 5);
459 Stream.pwrite((char *)Buffer, SizeLen, Offset);
460}
461
462// Write X as an signed LEB value at offset Offset in Stream, padded
463// to allow patching.
464static void
465WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
466 uint8_t Buffer[5];
467 unsigned Padding = PaddingFor5ByteSLEB128(X);
468 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
469 assert(SizeLen == 5);
470 Stream.pwrite((char *)Buffer, SizeLen, Offset);
471}
472
473// Write X as a plain integer value at offset Offset in Stream.
474static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
475 uint8_t Buffer[4];
476 support::endian::write32le(Buffer, X);
477 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
478}
479
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000480static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
481 if (Symbol.isVariable()) {
482 const MCExpr *Expr = Symbol.getVariableValue();
483 auto *Inner = cast<MCSymbolRefExpr>(Expr);
484 return cast<MCSymbolWasm>(&Inner->getSymbol());
485 }
486 return &Symbol;
487}
488
Dan Gohmand934cb82017-02-24 23:18:00 +0000489// Compute a value to write into the code at the location covered
490// by RelEntry. This value isn't used by the static linker, since
491// we have addends; it just serves to make the code more readable
492// and to make standalone wasm modules directly usable.
Sam Clegg7c395942017-09-14 23:07:53 +0000493uint32_t
494WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000495 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +0000496
497 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000498 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000499 return UINT32_MAX;
500
Sam Clegg7c395942017-09-14 23:07:53 +0000501 uint32_t GlobalIndex = SymbolIndices[Sym];
502 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
503 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000504
505 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
506 uint32_t Value = Address;
507
508 return Value;
509}
510
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000511uint32_t WasmObjectWriter::getRelocationIndexValue(
512 const WasmRelocationEntry &RelEntry) {
513 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000514 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
515 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000516 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000517 report_fatal_error("symbol not found table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000518 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000519 return IndirectSymbolIndices[RelEntry.Symbol];
520 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000521 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000522 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
523 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
524 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000525 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000526 report_fatal_error("symbol not found function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000527 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000528 return SymbolIndices[RelEntry.Symbol];
529 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000530 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000531 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000532 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000533 return TypeIndices[RelEntry.Symbol];
534 default:
535 llvm_unreachable("invalid relocation type");
536 }
537}
538
Dan Gohmand934cb82017-02-24 23:18:00 +0000539// Apply the portions of the relocation records that we can handle ourselves
540// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000541void WasmObjectWriter::applyRelocations(
542 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
543 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000544 for (const WasmRelocationEntry &RelEntry : Relocations) {
545 uint64_t Offset = ContentsOffset +
546 RelEntry.FixupSection->getSectionOffset() +
547 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000548
Sam Cleggb7787fd2017-06-20 04:04:59 +0000549 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000550 switch (RelEntry.Type) {
551 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
552 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000553 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
554 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000555 uint32_t Index = getRelocationIndexValue(RelEntry);
556 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000557 break;
558 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000559 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
560 uint32_t Index = getRelocationIndexValue(RelEntry);
561 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000562 break;
563 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000564 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000565 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000566 WritePatchableSLEB(Stream, Value, Offset);
567 break;
568 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000569 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000570 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000571 WritePatchableLEB(Stream, Value, Offset);
572 break;
573 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000574 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
Sam Clegg7c395942017-09-14 23:07:53 +0000575 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000576 WriteI32(Stream, Value, Offset);
577 break;
578 }
579 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000580 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000581 }
582 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000583}
584
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000585// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000586// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000587void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000588 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000589 raw_pwrite_stream &Stream = getStream();
590 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000591
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000592 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000593 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000594 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000595
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000596 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000597 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000598 encodeULEB128(Index, Stream);
599 if (RelEntry.hasAddend())
600 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000601 }
602}
603
Sam Clegg9e15f352017-06-03 02:01:24 +0000604void WasmObjectWriter::writeTypeSection(
605 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
606 if (FunctionTypes.empty())
607 return;
608
609 SectionBookkeeping Section;
610 startSection(Section, wasm::WASM_SEC_TYPE);
611
612 encodeULEB128(FunctionTypes.size(), getStream());
613
614 for (const WasmFunctionType &FuncTy : FunctionTypes) {
615 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
616 encodeULEB128(FuncTy.Params.size(), getStream());
617 for (wasm::ValType Ty : FuncTy.Params)
618 writeValueType(Ty);
619 encodeULEB128(FuncTy.Returns.size(), getStream());
620 for (wasm::ValType Ty : FuncTy.Returns)
621 writeValueType(Ty);
622 }
623
624 endSection(Section);
625}
626
Sam Cleggb7787fd2017-06-20 04:04:59 +0000627
Sam Clegg9e15f352017-06-03 02:01:24 +0000628void WasmObjectWriter::writeImportSection(
629 const SmallVector<WasmImport, 4> &Imports) {
630 if (Imports.empty())
631 return;
632
633 SectionBookkeeping Section;
634 startSection(Section, wasm::WASM_SEC_IMPORT);
635
636 encodeULEB128(Imports.size(), getStream());
637 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000638 writeString(Import.ModuleName);
639 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000640
641 encodeULEB128(Import.Kind, getStream());
642
643 switch (Import.Kind) {
644 case wasm::WASM_EXTERNAL_FUNCTION:
645 encodeULEB128(Import.Type, getStream());
646 break;
647 case wasm::WASM_EXTERNAL_GLOBAL:
648 encodeSLEB128(int32_t(Import.Type), getStream());
649 encodeULEB128(0, getStream()); // mutability
650 break;
651 default:
652 llvm_unreachable("unsupported import kind");
653 }
654 }
655
656 endSection(Section);
657}
658
659void WasmObjectWriter::writeFunctionSection(
660 const SmallVector<WasmFunction, 4> &Functions) {
661 if (Functions.empty())
662 return;
663
664 SectionBookkeeping Section;
665 startSection(Section, wasm::WASM_SEC_FUNCTION);
666
667 encodeULEB128(Functions.size(), getStream());
668 for (const WasmFunction &Func : Functions)
669 encodeULEB128(Func.Type, getStream());
670
671 endSection(Section);
672}
673
Sam Cleggd99f6072017-06-12 23:52:44 +0000674void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000675 // For now, always emit the table section, since indirect calls are not
676 // valid without it. In the future, we could perhaps be more clever and omit
677 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000678
Sam Clegg9e15f352017-06-03 02:01:24 +0000679 SectionBookkeeping Section;
680 startSection(Section, wasm::WASM_SEC_TABLE);
681
Sam Cleggd99f6072017-06-12 23:52:44 +0000682 encodeULEB128(1, getStream()); // The number of tables.
683 // Fixed to 1 for now.
684 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
685 encodeULEB128(0, getStream()); // flags
686 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000687
688 endSection(Section);
689}
690
Sam Clegg7c395942017-09-14 23:07:53 +0000691void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000692 // For now, always emit the memory section, since loads and stores are not
693 // valid without it. In the future, we could perhaps be more clever and omit
694 // it if there are no loads or stores.
695 SectionBookkeeping Section;
Sam Clegg7c395942017-09-14 23:07:53 +0000696 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
Sam Clegg9e15f352017-06-03 02:01:24 +0000697
698 startSection(Section, wasm::WASM_SEC_MEMORY);
699 encodeULEB128(1, getStream()); // number of memory spaces
700
701 encodeULEB128(0, getStream()); // flags
702 encodeULEB128(NumPages, getStream()); // initial
703
704 endSection(Section);
705}
706
Sam Clegg7c395942017-09-14 23:07:53 +0000707void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000708 if (Globals.empty())
709 return;
710
711 SectionBookkeeping Section;
712 startSection(Section, wasm::WASM_SEC_GLOBAL);
713
714 encodeULEB128(Globals.size(), getStream());
715 for (const WasmGlobal &Global : Globals) {
716 writeValueType(Global.Type);
717 write8(Global.IsMutable);
718
719 if (Global.HasImport) {
720 assert(Global.InitialValue == 0);
721 write8(wasm::WASM_OPCODE_GET_GLOBAL);
722 encodeULEB128(Global.ImportIndex, getStream());
723 } else {
724 assert(Global.ImportIndex == 0);
725 write8(wasm::WASM_OPCODE_I32_CONST);
726 encodeSLEB128(Global.InitialValue, getStream()); // offset
727 }
728 write8(wasm::WASM_OPCODE_END);
729 }
730
731 endSection(Section);
732}
733
734void WasmObjectWriter::writeExportSection(
735 const SmallVector<WasmExport, 4> &Exports) {
736 if (Exports.empty())
737 return;
738
739 SectionBookkeeping Section;
740 startSection(Section, wasm::WASM_SEC_EXPORT);
741
742 encodeULEB128(Exports.size(), getStream());
743 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000744 writeString(Export.FieldName);
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
752void WasmObjectWriter::writeElemSection(
753 const SmallVector<uint32_t, 4> &TableElems) {
754 if (TableElems.empty())
755 return;
756
757 SectionBookkeeping Section;
758 startSection(Section, wasm::WASM_SEC_ELEM);
759
760 encodeULEB128(1, getStream()); // number of "segments"
761 encodeULEB128(0, getStream()); // the table index
762
763 // init expr for starting offset
764 write8(wasm::WASM_OPCODE_I32_CONST);
765 encodeSLEB128(0, getStream());
766 write8(wasm::WASM_OPCODE_END);
767
768 encodeULEB128(TableElems.size(), getStream());
769 for (uint32_t Elem : TableElems)
770 encodeULEB128(Elem, getStream());
771
772 endSection(Section);
773}
774
775void WasmObjectWriter::writeCodeSection(
776 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000777 const SmallVector<WasmFunction, 4> &Functions) {
778 if (Functions.empty())
779 return;
780
781 SectionBookkeeping Section;
782 startSection(Section, wasm::WASM_SEC_CODE);
783
784 encodeULEB128(Functions.size(), getStream());
785
786 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000787 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000788
Sam Clegg9e15f352017-06-03 02:01:24 +0000789 int64_t Size = 0;
790 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
791 report_fatal_error(".size expression must be evaluatable");
792
793 encodeULEB128(Size, getStream());
794
Sam Cleggfe6414b2017-06-21 23:46:41 +0000795 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000796
797 Asm.writeSectionData(&FuncSection, Layout);
798 }
799
Sam Clegg9e15f352017-06-03 02:01:24 +0000800 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000801 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000802
803 endSection(Section);
804}
805
Sam Clegg7c395942017-09-14 23:07:53 +0000806void WasmObjectWriter::writeDataSection(
807 const SmallVector<WasmDataSegment, 4> &Segments) {
808 if (Segments.empty())
809 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000810
811 SectionBookkeeping Section;
812 startSection(Section, wasm::WASM_SEC_DATA);
813
Sam Clegg7c395942017-09-14 23:07:53 +0000814 encodeULEB128(Segments.size(), getStream()); // count
815
816 for (const WasmDataSegment & Segment : Segments) {
817 encodeULEB128(0, getStream()); // memory index
818 write8(wasm::WASM_OPCODE_I32_CONST);
819 encodeSLEB128(Segment.Offset, getStream()); // offset
820 write8(wasm::WASM_OPCODE_END);
821 encodeULEB128(Segment.Data.size(), getStream()); // size
822 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
823 writeBytes(Segment.Data); // data
824 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000825
826 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000827 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000828
829 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000830}
831
832void WasmObjectWriter::writeNameSection(
833 const SmallVector<WasmFunction, 4> &Functions,
834 const SmallVector<WasmImport, 4> &Imports,
835 unsigned NumFuncImports) {
836 uint32_t TotalFunctions = NumFuncImports + Functions.size();
837 if (TotalFunctions == 0)
838 return;
839
840 SectionBookkeeping Section;
841 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
842 SectionBookkeeping SubSection;
843 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
844
845 encodeULEB128(TotalFunctions, getStream());
846 uint32_t Index = 0;
847 for (const WasmImport &Import : Imports) {
848 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
849 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000850 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000851 ++Index;
852 }
853 }
854 for (const WasmFunction &Func : Functions) {
855 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000856 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000857 ++Index;
858 }
859
860 endSection(SubSection);
861 endSection(Section);
862}
863
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000864void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000865 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
866 // for descriptions of the reloc sections.
867
868 if (CodeRelocations.empty())
869 return;
870
871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
873
874 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000875 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
Sam Clegg7c395942017-09-14 23:07:53 +0000877 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000878
879 endSection(Section);
880}
881
Sam Clegg7c395942017-09-14 23:07:53 +0000882void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000883 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
884 // for descriptions of the reloc sections.
885
886 if (DataRelocations.empty())
887 return;
888
889 SectionBookkeeping Section;
890 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
891
892 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
893 encodeULEB128(DataRelocations.size(), getStream());
894
Sam Clegg7c395942017-09-14 23:07:53 +0000895 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000896
897 endSection(Section);
898}
899
900void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg9e1ade92017-06-27 20:27:59 +0000901 uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
902 bool HasStackPointer, uint32_t StackPointerGlobal) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000903 SectionBookkeeping Section;
904 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000905 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000906
Sam Cleggb7787fd2017-06-20 04:04:59 +0000907 if (HasStackPointer) {
908 startSection(SubSection, wasm::WASM_STACK_POINTER);
909 encodeULEB128(StackPointerGlobal, getStream()); // id
910 endSection(SubSection);
911 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000912
Sam Cleggb7787fd2017-06-20 04:04:59 +0000913 if (WeakSymbols.size() != 0) {
914 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
915 encodeULEB128(WeakSymbols.size(), getStream());
916 for (const StringRef Export: WeakSymbols) {
917 writeString(Export);
918 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
919 }
920 endSection(SubSection);
921 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000922
Sam Clegg9e1ade92017-06-27 20:27:59 +0000923 if (DataSize > 0) {
924 startSection(SubSection, wasm::WASM_DATA_SIZE);
925 encodeULEB128(DataSize, getStream());
926 endSection(SubSection);
927
928 startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
929 encodeULEB128(DataAlignment, getStream());
930 endSection(SubSection);
931 }
932
Sam Clegg9e15f352017-06-03 02:01:24 +0000933 endSection(Section);
934}
935
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000936uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
937 assert(Symbol.isFunction());
938 assert(TypeIndices.count(&Symbol));
939 return TypeIndices[&Symbol];
940}
941
942uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
943 assert(Symbol.isFunction());
944
945 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000946 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
947 F.Returns = ResolvedSym->getReturns();
948 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000949
950 auto Pair =
951 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
952 if (Pair.second)
953 FunctionTypes.push_back(F);
954 TypeIndices[&Symbol] = Pair.first->second;
955
956 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
957 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
958 return Pair.first->second;
959}
960
Dan Gohman18eafb62017-02-22 01:23:18 +0000961void WasmObjectWriter::writeObject(MCAssembler &Asm,
962 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000963 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000964 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000965 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000966
967 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000968 SmallVector<WasmFunction, 4> Functions;
969 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000970 SmallVector<WasmImport, 4> Imports;
971 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000972 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000973 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
974 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000975 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9e1ade92017-06-27 20:27:59 +0000976 uint32_t DataAlignment = 1;
Dan Gohman970d02c2017-03-30 23:58:19 +0000977 uint32_t StackPointerGlobal = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000978 uint32_t DataSize = 0;
Dan Gohman970d02c2017-03-30 23:58:19 +0000979 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000980
981 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000982 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000983 switch (RelEntry.Type) {
984 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000985 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000986 IsAddressTaken.insert(RelEntry.Symbol);
987 break;
988 default:
989 break;
990 }
991 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000992 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000993 switch (RelEntry.Type) {
994 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Clegg13a2e892017-09-01 17:32:01 +0000995 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000996 IsAddressTaken.insert(RelEntry.Symbol);
997 break;
998 default:
999 break;
1000 }
1001 }
1002
Sam Clegg7c395942017-09-14 23:07:53 +00001003 // Populate FunctionTypeIndices and Imports.
Dan Gohmand934cb82017-02-24 23:18:00 +00001004 for (const MCSymbol &S : Asm.symbols()) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001005 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1006
1007 if (WS.isTemporary())
Sam Clegg8c4baa002017-07-05 20:09:26 +00001008 continue;
1009
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001010 if (WS.isFunction())
1011 registerFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001012
1013 // If the symbol is not defined in this translation unit, import it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001014 if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001015 WasmImport Import;
1016 Import.ModuleName = WS.getModuleName();
1017 Import.FieldName = WS.getName();
1018
1019 if (WS.isFunction()) {
1020 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001021 Import.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001022 SymbolIndices[&WS] = NumFuncImports;
1023 ++NumFuncImports;
1024 } else {
1025 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001026 Import.Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +00001027 SymbolIndices[&WS] = NumGlobalImports;
1028 ++NumGlobalImports;
1029 }
1030
1031 Imports.push_back(Import);
1032 }
1033 }
1034
Dan Gohman82607f52017-02-24 23:46:05 +00001035 // In the special .global_variables section, we've encoded global
1036 // variables used by the function. Translate them into the Globals
1037 // list.
1038 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
1039 if (!GlobalVars->getFragmentList().empty()) {
1040 if (GlobalVars->getFragmentList().size() != 1)
1041 report_fatal_error("only one .global_variables fragment supported");
1042 const MCFragment &Frag = *GlobalVars->begin();
1043 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1044 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001045 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001046 if (!DataFrag.getFixups().empty())
1047 report_fatal_error("fixups not supported in .global_variables");
1048 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001049 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1050 *end = (const uint8_t *)Contents.data() + Contents.size();
1051 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001052 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001053 if (end - p < 3)
1054 report_fatal_error("truncated global variable encoding");
1055 G.Type = wasm::ValType(int8_t(*p++));
1056 G.IsMutable = bool(*p++);
1057 G.HasImport = bool(*p++);
1058 if (G.HasImport) {
1059 G.InitialValue = 0;
1060
1061 WasmImport Import;
1062 Import.ModuleName = (const char *)p;
1063 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1064 if (!nul)
1065 report_fatal_error("global module name must be nul-terminated");
1066 p = nul + 1;
1067 nul = (const uint8_t *)memchr(p, '\0', end - p);
1068 if (!nul)
1069 report_fatal_error("global base name must be nul-terminated");
1070 Import.FieldName = (const char *)p;
1071 p = nul + 1;
1072
1073 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1074 Import.Type = int32_t(G.Type);
1075
1076 G.ImportIndex = NumGlobalImports;
1077 ++NumGlobalImports;
1078
1079 Imports.push_back(Import);
1080 } else {
1081 unsigned n;
1082 G.InitialValue = decodeSLEB128(p, &n);
1083 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001084 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001085 report_fatal_error("global initial value must be valid SLEB128");
1086 p += n;
1087 }
Dan Gohman82607f52017-02-24 23:46:05 +00001088 Globals.push_back(G);
1089 }
1090 }
1091
Dan Gohman970d02c2017-03-30 23:58:19 +00001092 // In the special .stack_pointer section, we've encoded the stack pointer
1093 // index.
1094 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1095 if (!StackPtr->getFragmentList().empty()) {
1096 if (StackPtr->getFragmentList().size() != 1)
1097 report_fatal_error("only one .stack_pointer fragment supported");
1098 const MCFragment &Frag = *StackPtr->begin();
1099 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1100 report_fatal_error("only data supported in .stack_pointer");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001101 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman970d02c2017-03-30 23:58:19 +00001102 if (!DataFrag.getFixups().empty())
1103 report_fatal_error("fixups not supported in .stack_pointer");
1104 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1105 if (Contents.size() != 4)
1106 report_fatal_error("only one entry supported in .stack_pointer");
1107 HasStackPointer = true;
1108 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1109 }
1110
Sam Cleggb7787fd2017-06-20 04:04:59 +00001111 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001112 for (const MCSymbol &S : Asm.symbols()) {
1113 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1114 // or used in relocations.
1115 if (S.isTemporary() && S.getName().empty())
1116 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001117
Dan Gohmand934cb82017-02-24 23:18:00 +00001118 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001119 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1120 << " isDefined=" << S.isDefined() << " isExternal="
1121 << S.isExternal() << " isTemporary=" << S.isTemporary()
1122 << " isFunction=" << WS.isFunction()
1123 << " isWeak=" << WS.isWeak()
1124 << " isVariable=" << WS.isVariable() << "\n");
1125
1126 if (WS.isWeak())
1127 WeakSymbols.push_back(WS.getName());
1128
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001129 if (WS.isVariable())
1130 continue;
1131
Dan Gohmand934cb82017-02-24 23:18:00 +00001132 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001133
Dan Gohmand934cb82017-02-24 23:18:00 +00001134 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001135 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001136 if (WS.getOffset() != 0)
1137 report_fatal_error(
1138 "function sections must contain one function each");
1139
1140 if (WS.getSize() == 0)
1141 report_fatal_error(
1142 "function symbols must have a size set with .size");
1143
Dan Gohmand934cb82017-02-24 23:18:00 +00001144 // A definition. Take the next available index.
1145 Index = NumFuncImports + Functions.size();
1146
1147 // Prepare the function.
1148 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001149 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001150 Func.Sym = &WS;
1151 SymbolIndices[&WS] = Index;
1152 Functions.push_back(Func);
1153 } else {
1154 // An import; the index was assigned above.
1155 Index = SymbolIndices.find(&WS)->second;
1156 }
1157
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001158 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1159
Dan Gohmand934cb82017-02-24 23:18:00 +00001160 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001161 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001162 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001163 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001164 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001165 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001166 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001167 if (WS.isTemporary() && !WS.getSize())
1168 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001169
Sam Cleggfe6414b2017-06-21 23:46:41 +00001170 if (!WS.isDefined(/*SetUsed=*/false))
1171 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001172
Sam Cleggfe6414b2017-06-21 23:46:41 +00001173 if (WS.getOffset() != 0)
1174 report_fatal_error("data sections must contain one variable each: " +
1175 WS.getName());
1176 if (!WS.getSize())
1177 report_fatal_error("data symbols must have a size set with .size: " +
1178 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001179
Sam Cleggfe6414b2017-06-21 23:46:41 +00001180 int64_t Size = 0;
1181 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1182 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001183
Sam Cleggfe6414b2017-06-21 23:46:41 +00001184 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001185
Sam Cleggfe6414b2017-06-21 23:46:41 +00001186 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1187 report_fatal_error("data sections must contain at most one variable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001188
Sam Clegg9e1ade92017-06-27 20:27:59 +00001189 DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
Dan Gohmand934cb82017-02-24 23:18:00 +00001190
Sam Clegg7c395942017-09-14 23:07:53 +00001191 DataSegments.emplace_back();
1192 WasmDataSegment &Segment = DataSegments.back();
1193
1194 DataSize = alignTo(DataSize, DataSection.getAlignment());
1195 Segment.Offset = DataSize;
1196 Segment.Section = &DataSection;
1197
1198 // For each global, prepare a corresponding wasm global holding its
1199 // address. For externals these will also be named exports.
1200 Index = NumGlobalImports + Globals.size();
1201
1202 WasmGlobal Global;
1203 Global.Type = PtrType;
1204 Global.IsMutable = false;
1205 Global.HasImport = false;
1206 Global.InitialValue = DataSize;
1207 Global.ImportIndex = 0;
1208 SymbolIndices[&WS] = Index;
1209 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1210 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001211
Sam Cleggfe6414b2017-06-21 23:46:41 +00001212 for (const MCFragment &Frag : DataSection) {
1213 if (Frag.hasInstructions())
1214 report_fatal_error("only data supported in data sections");
Dan Gohmand934cb82017-02-24 23:18:00 +00001215
Sam Cleggfe6414b2017-06-21 23:46:41 +00001216 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1217 if (Align->getValueSize() != 1)
1218 report_fatal_error("only byte values supported for alignment");
1219 // If nops are requested, use zeros, as this is the data section.
1220 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Sam Clegg7c395942017-09-14 23:07:53 +00001221 uint64_t Size = std::min<uint64_t>(
1222 alignTo(Segment.Data.size(), Align->getAlignment()),
1223 Segment.Data.size() + Align->getMaxBytesToEmit());
1224 Segment.Data.resize(Size, Value);
Sam Cleggfe6414b2017-06-21 23:46:41 +00001225 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Sam Clegg7c395942017-09-14 23:07:53 +00001226 Segment.Data.insert(Segment.Data.end(), Fill->getSize(), Fill->getValue());
Sam Cleggfe6414b2017-06-21 23:46:41 +00001227 } else {
1228 const auto &DataFrag = cast<MCDataFragment>(Frag);
1229 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1230
Sam Clegg7c395942017-09-14 23:07:53 +00001231 Segment.Data.insert(Segment.Data.end(), Contents.begin(),
1232 Contents.end());
Dan Gohmand934cb82017-02-24 23:18:00 +00001233 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001234 }
Sam Clegg7c395942017-09-14 23:07:53 +00001235 DataSize += Segment.Data.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001236 }
1237
1238 // If the symbol is visible outside this translation unit, export it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001239 if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001240 WasmExport Export;
1241 Export.FieldName = WS.getName();
1242 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 if (WS.isFunction())
1244 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1245 else
1246 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001247 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001248 Exports.push_back(Export);
1249 }
1250 }
1251
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001252 // Handle weak aliases. We need to process these in a separate pass because
1253 // we need to have processed the target of the alias before the alias itself
1254 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001255 for (const MCSymbol &S : Asm.symbols()) {
1256 if (!S.isVariable())
1257 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001258 assert(S.isDefined(/*SetUsed=*/false));
1259
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001260 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001261 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1262 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001263 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1264 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001265 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001266 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001267
1268 WasmExport Export;
1269 Export.FieldName = WS.getName();
1270 Export.Index = Index;
1271 if (WS.isFunction())
1272 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1273 else
1274 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001275 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001276 Exports.push_back(Export);
1277 }
1278
Dan Gohmand934cb82017-02-24 23:18:00 +00001279 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001280 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1281 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1282 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001283
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001284 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001285 }
1286
Dan Gohman18eafb62017-02-22 01:23:18 +00001287 // Write out the Wasm header.
1288 writeHeader(Asm);
1289
Sam Clegg9e15f352017-06-03 02:01:24 +00001290 writeTypeSection(FunctionTypes);
1291 writeImportSection(Imports);
1292 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001293 writeTableSection(TableElems.size());
Sam Clegg7c395942017-09-14 23:07:53 +00001294 writeMemorySection(DataSize);
1295 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001296 writeExportSection(Exports);
1297 // TODO: Start Section
1298 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001299 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001300 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001301 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001302 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001303 writeDataRelocSection();
1304 writeLinkingMetaDataSection(DataSize, DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001305
Dan Gohmand934cb82017-02-24 23:18:00 +00001306 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001307 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001308}
1309
1310MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1311 raw_pwrite_stream &OS) {
1312 return new WasmObjectWriter(MOTW, OS);
1313}