blob: a71a3d414e77713d6d2c246145e80ed3e7fc6e46 [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
Sam Clegg457fb0b2017-09-15 19:50:44 +0000265 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
266 void writeImportSection(ArrayRef<WasmImport> Imports);
267 void writeFunctionSection(ArrayRef<WasmFunction> 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 Clegg457fb0b2017-09-15 19:50:44 +0000271 void writeExportSection(ArrayRef<WasmExport> Exports);
272 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000273 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000274 ArrayRef<WasmFunction> Functions);
275 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
276 void writeNameSection(ArrayRef<WasmFunction> Functions,
277 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000278 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(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000605 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000606 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 Clegg457fb0b2017-09-15 19:50:44 +0000627void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000628 if (Imports.empty())
629 return;
630
631 SectionBookkeeping Section;
632 startSection(Section, wasm::WASM_SEC_IMPORT);
633
634 encodeULEB128(Imports.size(), getStream());
635 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000636 writeString(Import.ModuleName);
637 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000638
639 encodeULEB128(Import.Kind, getStream());
640
641 switch (Import.Kind) {
642 case wasm::WASM_EXTERNAL_FUNCTION:
643 encodeULEB128(Import.Type, getStream());
644 break;
645 case wasm::WASM_EXTERNAL_GLOBAL:
646 encodeSLEB128(int32_t(Import.Type), getStream());
647 encodeULEB128(0, getStream()); // mutability
648 break;
649 default:
650 llvm_unreachable("unsupported import kind");
651 }
652 }
653
654 endSection(Section);
655}
656
Sam Clegg457fb0b2017-09-15 19:50:44 +0000657void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000658 if (Functions.empty())
659 return;
660
661 SectionBookkeeping Section;
662 startSection(Section, wasm::WASM_SEC_FUNCTION);
663
664 encodeULEB128(Functions.size(), getStream());
665 for (const WasmFunction &Func : Functions)
666 encodeULEB128(Func.Type, getStream());
667
668 endSection(Section);
669}
670
Sam Cleggd99f6072017-06-12 23:52:44 +0000671void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000672 // For now, always emit the table section, since indirect calls are not
673 // valid without it. In the future, we could perhaps be more clever and omit
674 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000675
Sam Clegg9e15f352017-06-03 02:01:24 +0000676 SectionBookkeeping Section;
677 startSection(Section, wasm::WASM_SEC_TABLE);
678
Sam Cleggd99f6072017-06-12 23:52:44 +0000679 encodeULEB128(1, getStream()); // The number of tables.
680 // Fixed to 1 for now.
681 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
682 encodeULEB128(0, getStream()); // flags
683 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000684
685 endSection(Section);
686}
687
Sam Clegg7c395942017-09-14 23:07:53 +0000688void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000689 // For now, always emit the memory section, since loads and stores are not
690 // valid without it. In the future, we could perhaps be more clever and omit
691 // it if there are no loads or stores.
692 SectionBookkeeping Section;
Sam Clegg7c395942017-09-14 23:07:53 +0000693 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
Sam Clegg9e15f352017-06-03 02:01:24 +0000694
695 startSection(Section, wasm::WASM_SEC_MEMORY);
696 encodeULEB128(1, getStream()); // number of memory spaces
697
698 encodeULEB128(0, getStream()); // flags
699 encodeULEB128(NumPages, getStream()); // initial
700
701 endSection(Section);
702}
703
Sam Clegg7c395942017-09-14 23:07:53 +0000704void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000705 if (Globals.empty())
706 return;
707
708 SectionBookkeeping Section;
709 startSection(Section, wasm::WASM_SEC_GLOBAL);
710
711 encodeULEB128(Globals.size(), getStream());
712 for (const WasmGlobal &Global : Globals) {
713 writeValueType(Global.Type);
714 write8(Global.IsMutable);
715
716 if (Global.HasImport) {
717 assert(Global.InitialValue == 0);
718 write8(wasm::WASM_OPCODE_GET_GLOBAL);
719 encodeULEB128(Global.ImportIndex, getStream());
720 } else {
721 assert(Global.ImportIndex == 0);
722 write8(wasm::WASM_OPCODE_I32_CONST);
723 encodeSLEB128(Global.InitialValue, getStream()); // offset
724 }
725 write8(wasm::WASM_OPCODE_END);
726 }
727
728 endSection(Section);
729}
730
Sam Clegg457fb0b2017-09-15 19:50:44 +0000731void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000732 if (Exports.empty())
733 return;
734
735 SectionBookkeeping Section;
736 startSection(Section, wasm::WASM_SEC_EXPORT);
737
738 encodeULEB128(Exports.size(), getStream());
739 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000740 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000741 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000742 encodeULEB128(Export.Index, getStream());
743 }
744
745 endSection(Section);
746}
747
Sam Clegg457fb0b2017-09-15 19:50:44 +0000748void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000749 if (TableElems.empty())
750 return;
751
752 SectionBookkeeping Section;
753 startSection(Section, wasm::WASM_SEC_ELEM);
754
755 encodeULEB128(1, getStream()); // number of "segments"
756 encodeULEB128(0, getStream()); // the table index
757
758 // init expr for starting offset
759 write8(wasm::WASM_OPCODE_I32_CONST);
760 encodeSLEB128(0, getStream());
761 write8(wasm::WASM_OPCODE_END);
762
763 encodeULEB128(TableElems.size(), getStream());
764 for (uint32_t Elem : TableElems)
765 encodeULEB128(Elem, getStream());
766
767 endSection(Section);
768}
769
Sam Clegg457fb0b2017-09-15 19:50:44 +0000770void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
771 const MCAsmLayout &Layout,
772 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 if (Functions.empty())
774 return;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_CODE);
778
779 encodeULEB128(Functions.size(), getStream());
780
781 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000782 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000783
Sam Clegg9e15f352017-06-03 02:01:24 +0000784 int64_t Size = 0;
785 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
786 report_fatal_error(".size expression must be evaluatable");
787
788 encodeULEB128(Size, getStream());
789
Sam Cleggfe6414b2017-06-21 23:46:41 +0000790 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000791
792 Asm.writeSectionData(&FuncSection, Layout);
793 }
794
Sam Clegg9e15f352017-06-03 02:01:24 +0000795 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000796 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000797
798 endSection(Section);
799}
800
Sam Clegg457fb0b2017-09-15 19:50:44 +0000801void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000802 if (Segments.empty())
803 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000804
805 SectionBookkeeping Section;
806 startSection(Section, wasm::WASM_SEC_DATA);
807
Sam Clegg7c395942017-09-14 23:07:53 +0000808 encodeULEB128(Segments.size(), getStream()); // count
809
810 for (const WasmDataSegment & Segment : Segments) {
811 encodeULEB128(0, getStream()); // memory index
812 write8(wasm::WASM_OPCODE_I32_CONST);
813 encodeSLEB128(Segment.Offset, getStream()); // offset
814 write8(wasm::WASM_OPCODE_END);
815 encodeULEB128(Segment.Data.size(), getStream()); // size
816 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
817 writeBytes(Segment.Data); // data
818 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000819
820 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000821 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000822
823 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000824}
825
826void WasmObjectWriter::writeNameSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000827 ArrayRef<WasmFunction> Functions,
828 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000829 unsigned NumFuncImports) {
830 uint32_t TotalFunctions = NumFuncImports + Functions.size();
831 if (TotalFunctions == 0)
832 return;
833
834 SectionBookkeeping Section;
835 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
836 SectionBookkeeping SubSection;
837 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
838
839 encodeULEB128(TotalFunctions, getStream());
840 uint32_t Index = 0;
841 for (const WasmImport &Import : Imports) {
842 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
843 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000844 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000845 ++Index;
846 }
847 }
848 for (const WasmFunction &Func : Functions) {
849 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000850 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000851 ++Index;
852 }
853
854 endSection(SubSection);
855 endSection(Section);
856}
857
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000858void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000859 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
860 // for descriptions of the reloc sections.
861
862 if (CodeRelocations.empty())
863 return;
864
865 SectionBookkeeping Section;
866 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
867
868 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000869 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000870
Sam Clegg7c395942017-09-14 23:07:53 +0000871 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000872
873 endSection(Section);
874}
875
Sam Clegg7c395942017-09-14 23:07:53 +0000876void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000877 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
878 // for descriptions of the reloc sections.
879
880 if (DataRelocations.empty())
881 return;
882
883 SectionBookkeeping Section;
884 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
885
886 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
887 encodeULEB128(DataRelocations.size(), getStream());
888
Sam Clegg7c395942017-09-14 23:07:53 +0000889 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000890
891 endSection(Section);
892}
893
894void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg9e1ade92017-06-27 20:27:59 +0000895 uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
896 bool HasStackPointer, uint32_t StackPointerGlobal) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000897 SectionBookkeeping Section;
898 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000899 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000900
Sam Cleggb7787fd2017-06-20 04:04:59 +0000901 if (HasStackPointer) {
902 startSection(SubSection, wasm::WASM_STACK_POINTER);
903 encodeULEB128(StackPointerGlobal, getStream()); // id
904 endSection(SubSection);
905 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000906
Sam Cleggb7787fd2017-06-20 04:04:59 +0000907 if (WeakSymbols.size() != 0) {
908 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
909 encodeULEB128(WeakSymbols.size(), getStream());
910 for (const StringRef Export: WeakSymbols) {
911 writeString(Export);
912 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
913 }
914 endSection(SubSection);
915 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000916
Sam Clegg9e1ade92017-06-27 20:27:59 +0000917 if (DataSize > 0) {
918 startSection(SubSection, wasm::WASM_DATA_SIZE);
919 encodeULEB128(DataSize, getStream());
920 endSection(SubSection);
921
922 startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
923 encodeULEB128(DataAlignment, getStream());
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();
Derek Schuffb8795392017-03-16 20:49:48 +0000959 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::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;
Dan Gohmand934cb82017-02-24 23:18:00 +0000964 SmallVector<WasmImport, 4> Imports;
965 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000966 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000967 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
968 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000969 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9e1ade92017-06-27 20:27:59 +0000970 uint32_t DataAlignment = 1;
Dan Gohman970d02c2017-03-30 23:58:19 +0000971 uint32_t StackPointerGlobal = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000972 uint32_t DataSize = 0;
Dan Gohman970d02c2017-03-30 23:58:19 +0000973 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000974
975 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000976 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000977 switch (RelEntry.Type) {
978 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000979 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000980 IsAddressTaken.insert(RelEntry.Symbol);
981 break;
982 default:
983 break;
984 }
985 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000986 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000987 switch (RelEntry.Type) {
988 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Clegg13a2e892017-09-01 17:32:01 +0000989 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000990 IsAddressTaken.insert(RelEntry.Symbol);
991 break;
992 default:
993 break;
994 }
995 }
996
Sam Clegg7c395942017-09-14 23:07:53 +0000997 // Populate FunctionTypeIndices and Imports.
Dan Gohmand934cb82017-02-24 23:18:00 +0000998 for (const MCSymbol &S : Asm.symbols()) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000999 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1000
1001 if (WS.isTemporary())
Sam Clegg8c4baa002017-07-05 20:09:26 +00001002 continue;
1003
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001004 if (WS.isFunction())
1005 registerFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001006
1007 // If the symbol is not defined in this translation unit, import it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001008 if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001009 WasmImport Import;
1010 Import.ModuleName = WS.getModuleName();
1011 Import.FieldName = WS.getName();
1012
1013 if (WS.isFunction()) {
1014 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001015 Import.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001016 SymbolIndices[&WS] = NumFuncImports;
1017 ++NumFuncImports;
1018 } else {
1019 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001020 Import.Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +00001021 SymbolIndices[&WS] = NumGlobalImports;
1022 ++NumGlobalImports;
1023 }
1024
1025 Imports.push_back(Import);
1026 }
1027 }
1028
Dan Gohman82607f52017-02-24 23:46:05 +00001029 // In the special .global_variables section, we've encoded global
1030 // variables used by the function. Translate them into the Globals
1031 // list.
1032 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
1033 if (!GlobalVars->getFragmentList().empty()) {
1034 if (GlobalVars->getFragmentList().size() != 1)
1035 report_fatal_error("only one .global_variables fragment supported");
1036 const MCFragment &Frag = *GlobalVars->begin();
1037 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1038 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001039 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001040 if (!DataFrag.getFixups().empty())
1041 report_fatal_error("fixups not supported in .global_variables");
1042 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001043 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1044 *end = (const uint8_t *)Contents.data() + Contents.size();
1045 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001046 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001047 if (end - p < 3)
1048 report_fatal_error("truncated global variable encoding");
1049 G.Type = wasm::ValType(int8_t(*p++));
1050 G.IsMutable = bool(*p++);
1051 G.HasImport = bool(*p++);
1052 if (G.HasImport) {
1053 G.InitialValue = 0;
1054
1055 WasmImport Import;
1056 Import.ModuleName = (const char *)p;
1057 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1058 if (!nul)
1059 report_fatal_error("global module name must be nul-terminated");
1060 p = nul + 1;
1061 nul = (const uint8_t *)memchr(p, '\0', end - p);
1062 if (!nul)
1063 report_fatal_error("global base name must be nul-terminated");
1064 Import.FieldName = (const char *)p;
1065 p = nul + 1;
1066
1067 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1068 Import.Type = int32_t(G.Type);
1069
1070 G.ImportIndex = NumGlobalImports;
1071 ++NumGlobalImports;
1072
1073 Imports.push_back(Import);
1074 } else {
1075 unsigned n;
1076 G.InitialValue = decodeSLEB128(p, &n);
1077 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001078 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001079 report_fatal_error("global initial value must be valid SLEB128");
1080 p += n;
1081 }
Dan Gohman82607f52017-02-24 23:46:05 +00001082 Globals.push_back(G);
1083 }
1084 }
1085
Dan Gohman970d02c2017-03-30 23:58:19 +00001086 // In the special .stack_pointer section, we've encoded the stack pointer
1087 // index.
1088 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1089 if (!StackPtr->getFragmentList().empty()) {
1090 if (StackPtr->getFragmentList().size() != 1)
1091 report_fatal_error("only one .stack_pointer fragment supported");
1092 const MCFragment &Frag = *StackPtr->begin();
1093 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1094 report_fatal_error("only data supported in .stack_pointer");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001095 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman970d02c2017-03-30 23:58:19 +00001096 if (!DataFrag.getFixups().empty())
1097 report_fatal_error("fixups not supported in .stack_pointer");
1098 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1099 if (Contents.size() != 4)
1100 report_fatal_error("only one entry supported in .stack_pointer");
1101 HasStackPointer = true;
1102 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1103 }
1104
Sam Cleggb7787fd2017-06-20 04:04:59 +00001105 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001106 for (const MCSymbol &S : Asm.symbols()) {
1107 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1108 // or used in relocations.
1109 if (S.isTemporary() && S.getName().empty())
1110 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001111
Dan Gohmand934cb82017-02-24 23:18:00 +00001112 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001113 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1114 << " isDefined=" << S.isDefined() << " isExternal="
1115 << S.isExternal() << " isTemporary=" << S.isTemporary()
1116 << " isFunction=" << WS.isFunction()
1117 << " isWeak=" << WS.isWeak()
1118 << " isVariable=" << WS.isVariable() << "\n");
1119
1120 if (WS.isWeak())
1121 WeakSymbols.push_back(WS.getName());
1122
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001123 if (WS.isVariable())
1124 continue;
1125
Dan Gohmand934cb82017-02-24 23:18:00 +00001126 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001127
Dan Gohmand934cb82017-02-24 23:18:00 +00001128 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001129 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001130 if (WS.getOffset() != 0)
1131 report_fatal_error(
1132 "function sections must contain one function each");
1133
1134 if (WS.getSize() == 0)
1135 report_fatal_error(
1136 "function symbols must have a size set with .size");
1137
Dan Gohmand934cb82017-02-24 23:18:00 +00001138 // A definition. Take the next available index.
1139 Index = NumFuncImports + Functions.size();
1140
1141 // Prepare the function.
1142 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001143 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001144 Func.Sym = &WS;
1145 SymbolIndices[&WS] = Index;
1146 Functions.push_back(Func);
1147 } else {
1148 // An import; the index was assigned above.
1149 Index = SymbolIndices.find(&WS)->second;
1150 }
1151
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001152 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1153
Dan Gohmand934cb82017-02-24 23:18:00 +00001154 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001155 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001156 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001157 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001158 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001159 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001160 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001161 if (WS.isTemporary() && !WS.getSize())
1162 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001163
Sam Cleggfe6414b2017-06-21 23:46:41 +00001164 if (!WS.isDefined(/*SetUsed=*/false))
1165 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001166
Sam Cleggfe6414b2017-06-21 23:46:41 +00001167 if (WS.getOffset() != 0)
1168 report_fatal_error("data sections must contain one variable each: " +
1169 WS.getName());
1170 if (!WS.getSize())
1171 report_fatal_error("data symbols must have a size set with .size: " +
1172 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001173
Sam Cleggfe6414b2017-06-21 23:46:41 +00001174 int64_t Size = 0;
1175 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1176 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001177
Sam Cleggfe6414b2017-06-21 23:46:41 +00001178 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001179
Sam Cleggfe6414b2017-06-21 23:46:41 +00001180 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1181 report_fatal_error("data sections must contain at most one variable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001182
Sam Clegg9e1ade92017-06-27 20:27:59 +00001183 DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
Dan Gohmand934cb82017-02-24 23:18:00 +00001184
Sam Clegg7c395942017-09-14 23:07:53 +00001185 DataSegments.emplace_back();
1186 WasmDataSegment &Segment = DataSegments.back();
1187
1188 DataSize = alignTo(DataSize, DataSection.getAlignment());
1189 Segment.Offset = DataSize;
1190 Segment.Section = &DataSection;
1191
1192 // For each global, prepare a corresponding wasm global holding its
1193 // address. For externals these will also be named exports.
1194 Index = NumGlobalImports + Globals.size();
1195
1196 WasmGlobal Global;
1197 Global.Type = PtrType;
1198 Global.IsMutable = false;
1199 Global.HasImport = false;
1200 Global.InitialValue = DataSize;
1201 Global.ImportIndex = 0;
1202 SymbolIndices[&WS] = Index;
1203 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1204 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001205
Sam Cleggfe6414b2017-06-21 23:46:41 +00001206 for (const MCFragment &Frag : DataSection) {
1207 if (Frag.hasInstructions())
1208 report_fatal_error("only data supported in data sections");
Dan Gohmand934cb82017-02-24 23:18:00 +00001209
Sam Cleggfe6414b2017-06-21 23:46:41 +00001210 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1211 if (Align->getValueSize() != 1)
1212 report_fatal_error("only byte values supported for alignment");
1213 // If nops are requested, use zeros, as this is the data section.
1214 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Sam Clegg7c395942017-09-14 23:07:53 +00001215 uint64_t Size = std::min<uint64_t>(
1216 alignTo(Segment.Data.size(), Align->getAlignment()),
1217 Segment.Data.size() + Align->getMaxBytesToEmit());
1218 Segment.Data.resize(Size, Value);
Sam Cleggfe6414b2017-06-21 23:46:41 +00001219 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Sam Clegg7c395942017-09-14 23:07:53 +00001220 Segment.Data.insert(Segment.Data.end(), Fill->getSize(), Fill->getValue());
Sam Cleggfe6414b2017-06-21 23:46:41 +00001221 } else {
1222 const auto &DataFrag = cast<MCDataFragment>(Frag);
1223 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1224
Sam Clegg7c395942017-09-14 23:07:53 +00001225 Segment.Data.insert(Segment.Data.end(), Contents.begin(),
1226 Contents.end());
Dan Gohmand934cb82017-02-24 23:18:00 +00001227 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001228 }
Sam Clegg7c395942017-09-14 23:07:53 +00001229 DataSize += Segment.Data.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001230 }
1231
1232 // If the symbol is visible outside this translation unit, export it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001233 if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001234 WasmExport Export;
1235 Export.FieldName = WS.getName();
1236 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001237 if (WS.isFunction())
1238 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1239 else
1240 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001241 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001242 Exports.push_back(Export);
1243 }
1244 }
1245
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001246 // Handle weak aliases. We need to process these in a separate pass because
1247 // we need to have processed the target of the alias before the alias itself
1248 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001249 for (const MCSymbol &S : Asm.symbols()) {
1250 if (!S.isVariable())
1251 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001252 assert(S.isDefined(/*SetUsed=*/false));
1253
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001254 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001255 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1256 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001257 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1258 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001259 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001260 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001261
1262 WasmExport Export;
1263 Export.FieldName = WS.getName();
1264 Export.Index = Index;
1265 if (WS.isFunction())
1266 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1267 else
1268 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001269 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001270 Exports.push_back(Export);
1271 }
1272
Dan Gohmand934cb82017-02-24 23:18:00 +00001273 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001274 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1275 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1276 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001277
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001278 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001279 }
1280
Dan Gohman18eafb62017-02-22 01:23:18 +00001281 // Write out the Wasm header.
1282 writeHeader(Asm);
1283
Sam Clegg9e15f352017-06-03 02:01:24 +00001284 writeTypeSection(FunctionTypes);
1285 writeImportSection(Imports);
1286 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001287 writeTableSection(TableElems.size());
Sam Clegg7c395942017-09-14 23:07:53 +00001288 writeMemorySection(DataSize);
1289 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001290 writeExportSection(Exports);
1291 // TODO: Start Section
1292 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001293 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001294 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001295 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001296 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001297 writeDataRelocSection();
1298 writeLinkingMetaDataSection(DataSize, DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001299
Dan Gohmand934cb82017-02-24 23:18:00 +00001300 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001301 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001302}
1303
1304MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1305 raw_pwrite_stream &OS) {
1306 return new WasmObjectWriter(MOTW, OS);
1307}