blob: f601c144c30a3668047f992a52d4fd8db68e1dd8 [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// Write out a section header and a patchable section size field.
301void WasmObjectWriter::startSection(SectionBookkeeping &Section,
302 unsigned SectionId,
303 const char *Name) {
304 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
305 "Only custom sections can have names");
306
Sam Cleggb7787fd2017-06-20 04:04:59 +0000307 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000308 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000309
310 Section.SizeOffset = getStream().tell();
311
312 // The section size. We don't know the size yet, so reserve enough space
313 // for any 32-bit value; we'll patch it later.
314 encodeULEB128(UINT32_MAX, getStream());
315
316 // The position where the section starts, for measuring its size.
317 Section.ContentsOffset = getStream().tell();
318
319 // Custom sections in wasm also have a string identifier.
320 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000321 assert(Name);
322 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000323 }
324}
325
326// Now that the section is complete and we know how big it is, patch up the
327// section size field at the start of the section.
328void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
329 uint64_t Size = getStream().tell() - Section.ContentsOffset;
330 if (uint32_t(Size) != Size)
331 report_fatal_error("section size does not fit in a uint32_t");
332
Sam Cleggb7787fd2017-06-20 04:04:59 +0000333 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000334
335 // Write the final section size to the payload_len field, which follows
336 // the section id byte.
337 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000338 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000339 assert(SizeLen == 5);
340 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
341}
342
Dan Gohman18eafb62017-02-22 01:23:18 +0000343// Emit the Wasm header.
344void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000345 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
346 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000347}
348
349void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
350 const MCAsmLayout &Layout) {
351}
352
353void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
354 const MCAsmLayout &Layout,
355 const MCFragment *Fragment,
356 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000357 uint64_t &FixedValue) {
358 MCAsmBackend &Backend = Asm.getBackend();
359 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
360 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000361 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000362 uint64_t C = Target.getConstant();
363 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
364 MCContext &Ctx = Asm.getContext();
365
366 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
367 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
368 "Should not have constructed this");
369
370 // Let A, B and C being the components of Target and R be the location of
371 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
372 // If it is pcrel, we want to compute (A - B + C - R).
373
374 // In general, Wasm has no relocations for -B. It can only represent (A + C)
375 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
376 // replace B to implement it: (A - R - K + C)
377 if (IsPCRel) {
378 Ctx.reportError(
379 Fixup.getLoc(),
380 "No relocation available to represent this relative expression");
381 return;
382 }
383
384 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
385
386 if (SymB.isUndefined()) {
387 Ctx.reportError(Fixup.getLoc(),
388 Twine("symbol '") + SymB.getName() +
389 "' can not be undefined in a subtraction expression");
390 return;
391 }
392
393 assert(!SymB.isAbsolute() && "Should have been folded");
394 const MCSection &SecB = SymB.getSection();
395 if (&SecB != &FixupSection) {
396 Ctx.reportError(Fixup.getLoc(),
397 "Cannot represent a difference across sections");
398 return;
399 }
400
401 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
402 uint64_t K = SymBOffset - FixupOffset;
403 IsPCRel = true;
404 C -= K;
405 }
406
407 // We either rejected the fixup or folded B into C at this point.
408 const MCSymbolRefExpr *RefA = Target.getSymA();
409 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
410
Dan Gohmand934cb82017-02-24 23:18:00 +0000411 if (SymA && SymA->isVariable()) {
412 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000413 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
414 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
415 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000416 }
417
418 // Put any constant offset in an addend. Offsets can be negative, and
419 // LLVM expects wrapping, in contrast to wasm's immediates which can't
420 // be negative and don't wrap.
421 FixedValue = 0;
422
Sam Clegg6ad8f192017-07-11 02:21:57 +0000423 if (SymA)
424 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000425
Sam Cleggae03c1e72017-06-13 18:51:50 +0000426 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000427 assert(SymA);
428
Sam Cleggae03c1e72017-06-13 18:51:50 +0000429 unsigned Type = getRelocType(Target, Fixup);
430
Dan Gohmand934cb82017-02-24 23:18:00 +0000431 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000432 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000433
434 if (FixupSection.hasInstructions())
435 CodeRelocations.push_back(Rec);
436 else
437 DataRelocations.push_back(Rec);
438}
439
Dan Gohmand934cb82017-02-24 23:18:00 +0000440// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
441// to allow patching.
442static void
443WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
444 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000445 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000446 assert(SizeLen == 5);
447 Stream.pwrite((char *)Buffer, SizeLen, Offset);
448}
449
450// Write X as an signed LEB value at offset Offset in Stream, padded
451// to allow patching.
452static void
453WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
454 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000455 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000456 assert(SizeLen == 5);
457 Stream.pwrite((char *)Buffer, SizeLen, Offset);
458}
459
460// Write X as a plain integer value at offset Offset in Stream.
461static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
462 uint8_t Buffer[4];
463 support::endian::write32le(Buffer, X);
464 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
465}
466
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000467static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
468 if (Symbol.isVariable()) {
469 const MCExpr *Expr = Symbol.getVariableValue();
470 auto *Inner = cast<MCSymbolRefExpr>(Expr);
471 return cast<MCSymbolWasm>(&Inner->getSymbol());
472 }
473 return &Symbol;
474}
475
Dan Gohmand934cb82017-02-24 23:18:00 +0000476// Compute a value to write into the code at the location covered
477// by RelEntry. This value isn't used by the static linker, since
478// we have addends; it just serves to make the code more readable
479// and to make standalone wasm modules directly usable.
Sam Clegg7c395942017-09-14 23:07:53 +0000480uint32_t
481WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000482 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +0000483
484 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000485 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000486 return UINT32_MAX;
487
Sam Clegg7c395942017-09-14 23:07:53 +0000488 uint32_t GlobalIndex = SymbolIndices[Sym];
489 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
490 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000491
492 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
493 uint32_t Value = Address;
494
495 return Value;
496}
497
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000498uint32_t WasmObjectWriter::getRelocationIndexValue(
499 const WasmRelocationEntry &RelEntry) {
500 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000501 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
502 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000503 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000504 report_fatal_error("symbol not found table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000505 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000506 return IndirectSymbolIndices[RelEntry.Symbol];
507 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000508 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000509 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
510 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
511 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000512 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000513 report_fatal_error("symbol not found function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000514 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000515 return SymbolIndices[RelEntry.Symbol];
516 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000517 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000518 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000519 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000520 return TypeIndices[RelEntry.Symbol];
521 default:
522 llvm_unreachable("invalid relocation type");
523 }
524}
525
Dan Gohmand934cb82017-02-24 23:18:00 +0000526// Apply the portions of the relocation records that we can handle ourselves
527// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000528void WasmObjectWriter::applyRelocations(
529 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
530 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000531 for (const WasmRelocationEntry &RelEntry : Relocations) {
532 uint64_t Offset = ContentsOffset +
533 RelEntry.FixupSection->getSectionOffset() +
534 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000535
Sam Cleggb7787fd2017-06-20 04:04:59 +0000536 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000537 switch (RelEntry.Type) {
538 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
539 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000540 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
541 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000542 uint32_t Index = getRelocationIndexValue(RelEntry);
543 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000544 break;
545 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000546 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
547 uint32_t Index = getRelocationIndexValue(RelEntry);
548 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000549 break;
550 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000551 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000552 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000553 WritePatchableSLEB(Stream, Value, Offset);
554 break;
555 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000556 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000557 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000558 WritePatchableLEB(Stream, Value, Offset);
559 break;
560 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000561 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
Sam Clegg7c395942017-09-14 23:07:53 +0000562 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000563 WriteI32(Stream, Value, Offset);
564 break;
565 }
566 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000567 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000568 }
569 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000570}
571
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000572// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000573// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000574void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000575 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000576 raw_pwrite_stream &Stream = getStream();
577 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000578
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000579 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000580 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000581 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000582
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000583 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000584 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000585 encodeULEB128(Index, Stream);
586 if (RelEntry.hasAddend())
587 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000588 }
589}
590
Sam Clegg9e15f352017-06-03 02:01:24 +0000591void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000592 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000593 if (FunctionTypes.empty())
594 return;
595
596 SectionBookkeeping Section;
597 startSection(Section, wasm::WASM_SEC_TYPE);
598
599 encodeULEB128(FunctionTypes.size(), getStream());
600
601 for (const WasmFunctionType &FuncTy : FunctionTypes) {
602 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
603 encodeULEB128(FuncTy.Params.size(), getStream());
604 for (wasm::ValType Ty : FuncTy.Params)
605 writeValueType(Ty);
606 encodeULEB128(FuncTy.Returns.size(), getStream());
607 for (wasm::ValType Ty : FuncTy.Returns)
608 writeValueType(Ty);
609 }
610
611 endSection(Section);
612}
613
Sam Clegg457fb0b2017-09-15 19:50:44 +0000614void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000615 if (Imports.empty())
616 return;
617
618 SectionBookkeeping Section;
619 startSection(Section, wasm::WASM_SEC_IMPORT);
620
621 encodeULEB128(Imports.size(), getStream());
622 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000623 writeString(Import.ModuleName);
624 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000625
626 encodeULEB128(Import.Kind, getStream());
627
628 switch (Import.Kind) {
629 case wasm::WASM_EXTERNAL_FUNCTION:
630 encodeULEB128(Import.Type, getStream());
631 break;
632 case wasm::WASM_EXTERNAL_GLOBAL:
633 encodeSLEB128(int32_t(Import.Type), getStream());
634 encodeULEB128(0, getStream()); // mutability
635 break;
636 default:
637 llvm_unreachable("unsupported import kind");
638 }
639 }
640
641 endSection(Section);
642}
643
Sam Clegg457fb0b2017-09-15 19:50:44 +0000644void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000645 if (Functions.empty())
646 return;
647
648 SectionBookkeeping Section;
649 startSection(Section, wasm::WASM_SEC_FUNCTION);
650
651 encodeULEB128(Functions.size(), getStream());
652 for (const WasmFunction &Func : Functions)
653 encodeULEB128(Func.Type, getStream());
654
655 endSection(Section);
656}
657
Sam Cleggd99f6072017-06-12 23:52:44 +0000658void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000659 // For now, always emit the table section, since indirect calls are not
660 // valid without it. In the future, we could perhaps be more clever and omit
661 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000662
Sam Clegg9e15f352017-06-03 02:01:24 +0000663 SectionBookkeeping Section;
664 startSection(Section, wasm::WASM_SEC_TABLE);
665
Sam Cleggd99f6072017-06-12 23:52:44 +0000666 encodeULEB128(1, getStream()); // The number of tables.
667 // Fixed to 1 for now.
668 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
669 encodeULEB128(0, getStream()); // flags
670 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000671
672 endSection(Section);
673}
674
Sam Clegg7c395942017-09-14 23:07:53 +0000675void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000676 // For now, always emit the memory section, since loads and stores are not
677 // valid without it. In the future, we could perhaps be more clever and omit
678 // it if there are no loads or stores.
679 SectionBookkeeping Section;
Sam Clegg7c395942017-09-14 23:07:53 +0000680 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
Sam Clegg9e15f352017-06-03 02:01:24 +0000681
682 startSection(Section, wasm::WASM_SEC_MEMORY);
683 encodeULEB128(1, getStream()); // number of memory spaces
684
685 encodeULEB128(0, getStream()); // flags
686 encodeULEB128(NumPages, getStream()); // initial
687
688 endSection(Section);
689}
690
Sam Clegg7c395942017-09-14 23:07:53 +0000691void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000692 if (Globals.empty())
693 return;
694
695 SectionBookkeeping Section;
696 startSection(Section, wasm::WASM_SEC_GLOBAL);
697
698 encodeULEB128(Globals.size(), getStream());
699 for (const WasmGlobal &Global : Globals) {
700 writeValueType(Global.Type);
701 write8(Global.IsMutable);
702
703 if (Global.HasImport) {
704 assert(Global.InitialValue == 0);
705 write8(wasm::WASM_OPCODE_GET_GLOBAL);
706 encodeULEB128(Global.ImportIndex, getStream());
707 } else {
708 assert(Global.ImportIndex == 0);
709 write8(wasm::WASM_OPCODE_I32_CONST);
710 encodeSLEB128(Global.InitialValue, getStream()); // offset
711 }
712 write8(wasm::WASM_OPCODE_END);
713 }
714
715 endSection(Section);
716}
717
Sam Clegg457fb0b2017-09-15 19:50:44 +0000718void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000719 if (Exports.empty())
720 return;
721
722 SectionBookkeeping Section;
723 startSection(Section, wasm::WASM_SEC_EXPORT);
724
725 encodeULEB128(Exports.size(), getStream());
726 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000727 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000728 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000729 encodeULEB128(Export.Index, getStream());
730 }
731
732 endSection(Section);
733}
734
Sam Clegg457fb0b2017-09-15 19:50:44 +0000735void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000736 if (TableElems.empty())
737 return;
738
739 SectionBookkeeping Section;
740 startSection(Section, wasm::WASM_SEC_ELEM);
741
742 encodeULEB128(1, getStream()); // number of "segments"
743 encodeULEB128(0, getStream()); // the table index
744
745 // init expr for starting offset
746 write8(wasm::WASM_OPCODE_I32_CONST);
747 encodeSLEB128(0, getStream());
748 write8(wasm::WASM_OPCODE_END);
749
750 encodeULEB128(TableElems.size(), getStream());
751 for (uint32_t Elem : TableElems)
752 encodeULEB128(Elem, getStream());
753
754 endSection(Section);
755}
756
Sam Clegg457fb0b2017-09-15 19:50:44 +0000757void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
758 const MCAsmLayout &Layout,
759 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000760 if (Functions.empty())
761 return;
762
763 SectionBookkeeping Section;
764 startSection(Section, wasm::WASM_SEC_CODE);
765
766 encodeULEB128(Functions.size(), getStream());
767
768 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000769 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000770
Sam Clegg9e15f352017-06-03 02:01:24 +0000771 int64_t Size = 0;
772 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
773 report_fatal_error(".size expression must be evaluatable");
774
775 encodeULEB128(Size, getStream());
776
Sam Cleggfe6414b2017-06-21 23:46:41 +0000777 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000778
779 Asm.writeSectionData(&FuncSection, Layout);
780 }
781
Sam Clegg9e15f352017-06-03 02:01:24 +0000782 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000783 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000784
785 endSection(Section);
786}
787
Sam Clegg457fb0b2017-09-15 19:50:44 +0000788void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000789 if (Segments.empty())
790 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000791
792 SectionBookkeeping Section;
793 startSection(Section, wasm::WASM_SEC_DATA);
794
Sam Clegg7c395942017-09-14 23:07:53 +0000795 encodeULEB128(Segments.size(), getStream()); // count
796
797 for (const WasmDataSegment & Segment : Segments) {
798 encodeULEB128(0, getStream()); // memory index
799 write8(wasm::WASM_OPCODE_I32_CONST);
800 encodeSLEB128(Segment.Offset, getStream()); // offset
801 write8(wasm::WASM_OPCODE_END);
802 encodeULEB128(Segment.Data.size(), getStream()); // size
803 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
804 writeBytes(Segment.Data); // data
805 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000806
807 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000808 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000809
810 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000811}
812
813void WasmObjectWriter::writeNameSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000814 ArrayRef<WasmFunction> Functions,
815 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000816 unsigned NumFuncImports) {
817 uint32_t TotalFunctions = NumFuncImports + Functions.size();
818 if (TotalFunctions == 0)
819 return;
820
821 SectionBookkeeping Section;
822 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
823 SectionBookkeeping SubSection;
824 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
825
826 encodeULEB128(TotalFunctions, getStream());
827 uint32_t Index = 0;
828 for (const WasmImport &Import : Imports) {
829 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
830 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000831 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000832 ++Index;
833 }
834 }
835 for (const WasmFunction &Func : Functions) {
836 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000837 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000838 ++Index;
839 }
840
841 endSection(SubSection);
842 endSection(Section);
843}
844
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000845void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000846 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
847 // for descriptions of the reloc sections.
848
849 if (CodeRelocations.empty())
850 return;
851
852 SectionBookkeeping Section;
853 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
854
855 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000856 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
Sam Clegg7c395942017-09-14 23:07:53 +0000858 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859
860 endSection(Section);
861}
862
Sam Clegg7c395942017-09-14 23:07:53 +0000863void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000864 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
865 // for descriptions of the reloc sections.
866
867 if (DataRelocations.empty())
868 return;
869
870 SectionBookkeeping Section;
871 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
872
873 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
874 encodeULEB128(DataRelocations.size(), getStream());
875
Sam Clegg7c395942017-09-14 23:07:53 +0000876 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000877
878 endSection(Section);
879}
880
881void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg9e1ade92017-06-27 20:27:59 +0000882 uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
883 bool HasStackPointer, uint32_t StackPointerGlobal) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000884 SectionBookkeeping Section;
885 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000886 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
Sam Cleggb7787fd2017-06-20 04:04:59 +0000888 if (HasStackPointer) {
889 startSection(SubSection, wasm::WASM_STACK_POINTER);
890 encodeULEB128(StackPointerGlobal, getStream()); // id
891 endSection(SubSection);
892 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000893
Sam Cleggb7787fd2017-06-20 04:04:59 +0000894 if (WeakSymbols.size() != 0) {
895 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
896 encodeULEB128(WeakSymbols.size(), getStream());
897 for (const StringRef Export: WeakSymbols) {
898 writeString(Export);
899 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
900 }
901 endSection(SubSection);
902 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000903
Sam Clegg9e1ade92017-06-27 20:27:59 +0000904 if (DataSize > 0) {
905 startSection(SubSection, wasm::WASM_DATA_SIZE);
906 encodeULEB128(DataSize, getStream());
907 endSection(SubSection);
908
909 startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
910 encodeULEB128(DataAlignment, getStream());
911 endSection(SubSection);
912 }
913
Sam Clegg9e15f352017-06-03 02:01:24 +0000914 endSection(Section);
915}
916
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000917uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
918 assert(Symbol.isFunction());
919 assert(TypeIndices.count(&Symbol));
920 return TypeIndices[&Symbol];
921}
922
923uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
924 assert(Symbol.isFunction());
925
926 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000927 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
928 F.Returns = ResolvedSym->getReturns();
929 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000930
931 auto Pair =
932 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
933 if (Pair.second)
934 FunctionTypes.push_back(F);
935 TypeIndices[&Symbol] = Pair.first->second;
936
937 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
938 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
939 return Pair.first->second;
940}
941
Dan Gohman18eafb62017-02-22 01:23:18 +0000942void WasmObjectWriter::writeObject(MCAssembler &Asm,
943 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000944 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000945 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000946 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000947
948 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000949 SmallVector<WasmFunction, 4> Functions;
950 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000951 SmallVector<WasmImport, 4> Imports;
952 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000953 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000954 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
955 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000956 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9e1ade92017-06-27 20:27:59 +0000957 uint32_t DataAlignment = 1;
Dan Gohman970d02c2017-03-30 23:58:19 +0000958 uint32_t StackPointerGlobal = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000959 uint32_t DataSize = 0;
Dan Gohman970d02c2017-03-30 23:58:19 +0000960 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000961
962 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000963 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000964 switch (RelEntry.Type) {
965 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000966 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000967 IsAddressTaken.insert(RelEntry.Symbol);
968 break;
969 default:
970 break;
971 }
972 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000973 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000974 switch (RelEntry.Type) {
975 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Clegg13a2e892017-09-01 17:32:01 +0000976 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000977 IsAddressTaken.insert(RelEntry.Symbol);
978 break;
979 default:
980 break;
981 }
982 }
983
Sam Clegg7c395942017-09-14 23:07:53 +0000984 // Populate FunctionTypeIndices and Imports.
Dan Gohmand934cb82017-02-24 23:18:00 +0000985 for (const MCSymbol &S : Asm.symbols()) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000986 const auto &WS = static_cast<const MCSymbolWasm &>(S);
987
988 if (WS.isTemporary())
Sam Clegg8c4baa002017-07-05 20:09:26 +0000989 continue;
990
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000991 if (WS.isFunction())
992 registerFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000993
994 // If the symbol is not defined in this translation unit, import it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000995 if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000996 WasmImport Import;
997 Import.ModuleName = WS.getModuleName();
998 Import.FieldName = WS.getName();
999
1000 if (WS.isFunction()) {
1001 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001002 Import.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001003 SymbolIndices[&WS] = NumFuncImports;
1004 ++NumFuncImports;
1005 } else {
1006 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001007 Import.Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +00001008 SymbolIndices[&WS] = NumGlobalImports;
1009 ++NumGlobalImports;
1010 }
1011
1012 Imports.push_back(Import);
1013 }
1014 }
1015
Dan Gohman82607f52017-02-24 23:46:05 +00001016 // In the special .global_variables section, we've encoded global
1017 // variables used by the function. Translate them into the Globals
1018 // list.
1019 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
1020 if (!GlobalVars->getFragmentList().empty()) {
1021 if (GlobalVars->getFragmentList().size() != 1)
1022 report_fatal_error("only one .global_variables fragment supported");
1023 const MCFragment &Frag = *GlobalVars->begin();
1024 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1025 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001026 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001027 if (!DataFrag.getFixups().empty())
1028 report_fatal_error("fixups not supported in .global_variables");
1029 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001030 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1031 *end = (const uint8_t *)Contents.data() + Contents.size();
1032 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001033 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001034 if (end - p < 3)
1035 report_fatal_error("truncated global variable encoding");
1036 G.Type = wasm::ValType(int8_t(*p++));
1037 G.IsMutable = bool(*p++);
1038 G.HasImport = bool(*p++);
1039 if (G.HasImport) {
1040 G.InitialValue = 0;
1041
1042 WasmImport Import;
1043 Import.ModuleName = (const char *)p;
1044 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1045 if (!nul)
1046 report_fatal_error("global module name must be nul-terminated");
1047 p = nul + 1;
1048 nul = (const uint8_t *)memchr(p, '\0', end - p);
1049 if (!nul)
1050 report_fatal_error("global base name must be nul-terminated");
1051 Import.FieldName = (const char *)p;
1052 p = nul + 1;
1053
1054 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1055 Import.Type = int32_t(G.Type);
1056
1057 G.ImportIndex = NumGlobalImports;
1058 ++NumGlobalImports;
1059
1060 Imports.push_back(Import);
1061 } else {
1062 unsigned n;
1063 G.InitialValue = decodeSLEB128(p, &n);
1064 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001065 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001066 report_fatal_error("global initial value must be valid SLEB128");
1067 p += n;
1068 }
Dan Gohman82607f52017-02-24 23:46:05 +00001069 Globals.push_back(G);
1070 }
1071 }
1072
Dan Gohman970d02c2017-03-30 23:58:19 +00001073 // In the special .stack_pointer section, we've encoded the stack pointer
1074 // index.
1075 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1076 if (!StackPtr->getFragmentList().empty()) {
1077 if (StackPtr->getFragmentList().size() != 1)
1078 report_fatal_error("only one .stack_pointer fragment supported");
1079 const MCFragment &Frag = *StackPtr->begin();
1080 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1081 report_fatal_error("only data supported in .stack_pointer");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001082 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman970d02c2017-03-30 23:58:19 +00001083 if (!DataFrag.getFixups().empty())
1084 report_fatal_error("fixups not supported in .stack_pointer");
1085 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1086 if (Contents.size() != 4)
1087 report_fatal_error("only one entry supported in .stack_pointer");
1088 HasStackPointer = true;
1089 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1090 }
1091
Sam Cleggb7787fd2017-06-20 04:04:59 +00001092 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001093 for (const MCSymbol &S : Asm.symbols()) {
1094 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1095 // or used in relocations.
1096 if (S.isTemporary() && S.getName().empty())
1097 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001098
Dan Gohmand934cb82017-02-24 23:18:00 +00001099 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001100 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1101 << " isDefined=" << S.isDefined() << " isExternal="
1102 << S.isExternal() << " isTemporary=" << S.isTemporary()
1103 << " isFunction=" << WS.isFunction()
1104 << " isWeak=" << WS.isWeak()
1105 << " isVariable=" << WS.isVariable() << "\n");
1106
1107 if (WS.isWeak())
1108 WeakSymbols.push_back(WS.getName());
1109
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001110 if (WS.isVariable())
1111 continue;
1112
Dan Gohmand934cb82017-02-24 23:18:00 +00001113 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001114
Dan Gohmand934cb82017-02-24 23:18:00 +00001115 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001116 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001117 if (WS.getOffset() != 0)
1118 report_fatal_error(
1119 "function sections must contain one function each");
1120
1121 if (WS.getSize() == 0)
1122 report_fatal_error(
1123 "function symbols must have a size set with .size");
1124
Dan Gohmand934cb82017-02-24 23:18:00 +00001125 // A definition. Take the next available index.
1126 Index = NumFuncImports + Functions.size();
1127
1128 // Prepare the function.
1129 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001130 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001131 Func.Sym = &WS;
1132 SymbolIndices[&WS] = Index;
1133 Functions.push_back(Func);
1134 } else {
1135 // An import; the index was assigned above.
1136 Index = SymbolIndices.find(&WS)->second;
1137 }
1138
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001139 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1140
Dan Gohmand934cb82017-02-24 23:18:00 +00001141 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001142 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001143 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001144 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001145 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001146 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001147 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001148 if (WS.isTemporary() && !WS.getSize())
1149 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001150
Sam Cleggfe6414b2017-06-21 23:46:41 +00001151 if (!WS.isDefined(/*SetUsed=*/false))
1152 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001153
Sam Cleggfe6414b2017-06-21 23:46:41 +00001154 if (WS.getOffset() != 0)
1155 report_fatal_error("data sections must contain one variable each: " +
1156 WS.getName());
1157 if (!WS.getSize())
1158 report_fatal_error("data symbols must have a size set with .size: " +
1159 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001160
Sam Cleggfe6414b2017-06-21 23:46:41 +00001161 int64_t Size = 0;
1162 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1163 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001164
Sam Cleggfe6414b2017-06-21 23:46:41 +00001165 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001166
Sam Cleggfe6414b2017-06-21 23:46:41 +00001167 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1168 report_fatal_error("data sections must contain at most one variable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001169
Sam Clegg9e1ade92017-06-27 20:27:59 +00001170 DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
Dan Gohmand934cb82017-02-24 23:18:00 +00001171
Sam Clegg7c395942017-09-14 23:07:53 +00001172 DataSegments.emplace_back();
1173 WasmDataSegment &Segment = DataSegments.back();
1174
1175 DataSize = alignTo(DataSize, DataSection.getAlignment());
1176 Segment.Offset = DataSize;
1177 Segment.Section = &DataSection;
1178
1179 // For each global, prepare a corresponding wasm global holding its
1180 // address. For externals these will also be named exports.
1181 Index = NumGlobalImports + Globals.size();
1182
1183 WasmGlobal Global;
1184 Global.Type = PtrType;
1185 Global.IsMutable = false;
1186 Global.HasImport = false;
1187 Global.InitialValue = DataSize;
1188 Global.ImportIndex = 0;
1189 SymbolIndices[&WS] = Index;
1190 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1191 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001192
Sam Cleggfe6414b2017-06-21 23:46:41 +00001193 for (const MCFragment &Frag : DataSection) {
1194 if (Frag.hasInstructions())
1195 report_fatal_error("only data supported in data sections");
Dan Gohmand934cb82017-02-24 23:18:00 +00001196
Sam Cleggfe6414b2017-06-21 23:46:41 +00001197 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1198 if (Align->getValueSize() != 1)
1199 report_fatal_error("only byte values supported for alignment");
1200 // If nops are requested, use zeros, as this is the data section.
1201 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Sam Clegg7c395942017-09-14 23:07:53 +00001202 uint64_t Size = std::min<uint64_t>(
1203 alignTo(Segment.Data.size(), Align->getAlignment()),
1204 Segment.Data.size() + Align->getMaxBytesToEmit());
1205 Segment.Data.resize(Size, Value);
Sam Cleggfe6414b2017-06-21 23:46:41 +00001206 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Sam Clegg7c395942017-09-14 23:07:53 +00001207 Segment.Data.insert(Segment.Data.end(), Fill->getSize(), Fill->getValue());
Sam Cleggfe6414b2017-06-21 23:46:41 +00001208 } else {
1209 const auto &DataFrag = cast<MCDataFragment>(Frag);
1210 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1211
Sam Clegg7c395942017-09-14 23:07:53 +00001212 Segment.Data.insert(Segment.Data.end(), Contents.begin(),
1213 Contents.end());
Dan Gohmand934cb82017-02-24 23:18:00 +00001214 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001215 }
Sam Clegg7c395942017-09-14 23:07:53 +00001216 DataSize += Segment.Data.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001217 }
1218
1219 // If the symbol is visible outside this translation unit, export it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001220 if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001221 WasmExport Export;
1222 Export.FieldName = WS.getName();
1223 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001224 if (WS.isFunction())
1225 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1226 else
1227 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001228 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001229 Exports.push_back(Export);
1230 }
1231 }
1232
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001233 // Handle weak aliases. We need to process these in a separate pass because
1234 // we need to have processed the target of the alias before the alias itself
1235 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001236 for (const MCSymbol &S : Asm.symbols()) {
1237 if (!S.isVariable())
1238 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001239 assert(S.isDefined(/*SetUsed=*/false));
1240
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001241 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001242 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1243 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001244 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1245 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001246 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001247 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001248
1249 WasmExport Export;
1250 Export.FieldName = WS.getName();
1251 Export.Index = Index;
1252 if (WS.isFunction())
1253 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1254 else
1255 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001256 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001257 Exports.push_back(Export);
1258 }
1259
Dan Gohmand934cb82017-02-24 23:18:00 +00001260 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001261 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1262 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1263 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001264
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001265 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001266 }
1267
Dan Gohman18eafb62017-02-22 01:23:18 +00001268 // Write out the Wasm header.
1269 writeHeader(Asm);
1270
Sam Clegg9e15f352017-06-03 02:01:24 +00001271 writeTypeSection(FunctionTypes);
1272 writeImportSection(Imports);
1273 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001274 writeTableSection(TableElems.size());
Sam Clegg7c395942017-09-14 23:07:53 +00001275 writeMemorySection(DataSize);
1276 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001277 writeExportSection(Exports);
1278 // TODO: Start Section
1279 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001280 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001281 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001282 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001283 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001284 writeDataRelocSection();
1285 writeLinkingMetaDataSection(DataSize, DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001286
Dan Gohmand934cb82017-02-24 23:18:00 +00001287 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001288 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001289}
1290
1291MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1292 raw_pwrite_stream &OS) {
1293 return new WasmObjectWriter(MOTW, OS);
1294}