blob: 54c8d00ebc2ece02035ba6568aa7f6957e9b37f2 [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
99// A wasm import to be written into the import section.
100struct WasmImport {
101 StringRef ModuleName;
102 StringRef FieldName;
103 unsigned Kind;
104 int32_t Type;
105};
106
107// A wasm function to be written into the function section.
108struct WasmFunction {
109 int32_t Type;
110 const MCSymbolWasm *Sym;
111};
112
113// A wasm export to be written into the export section.
114struct WasmExport {
115 StringRef FieldName;
116 unsigned Kind;
117 uint32_t Index;
118};
119
120// A wasm global to be written into the global section.
121struct WasmGlobal {
122 wasm::ValType Type;
123 bool IsMutable;
124 bool HasImport;
125 uint64_t InitialValue;
126 uint32_t ImportIndex;
127};
128
Sam Clegg6dc65e92017-06-06 16:38:59 +0000129// Information about a single relocation.
130struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000131 uint64_t Offset; // Where is the relocation.
132 const MCSymbolWasm *Symbol; // The symbol to relocate with.
133 int64_t Addend; // A value to add to the symbol.
134 unsigned Type; // The type of the relocation.
135 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000136
137 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
138 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000139 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000140 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
141 FixupSection(FixupSection) {}
142
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000143 bool hasAddend() const {
144 switch (Type) {
145 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
146 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
147 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
148 return true;
149 default:
150 return false;
151 }
152 }
153
Sam Clegg6dc65e92017-06-06 16:38:59 +0000154 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000155 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg6dc65e92017-06-06 16:38:59 +0000156 << ", Type=" << Type << ", FixupSection=" << FixupSection;
157 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000158
159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
161#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000162};
163
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000164#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000165raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000166 Rel.print(OS);
167 return OS;
168}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000169#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000170
Dan Gohman18eafb62017-02-22 01:23:18 +0000171class WasmObjectWriter : public MCObjectWriter {
172 /// Helper struct for containing some precomputed information on symbols.
173 struct WasmSymbolData {
174 const MCSymbolWasm *Symbol;
175 StringRef Name;
176
177 // Support lexicographic sorting.
178 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
179 };
180
181 /// The target specific Wasm writer instance.
182 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
183
Dan Gohmand934cb82017-02-24 23:18:00 +0000184 // Relocations for fixing up references in the code section.
185 std::vector<WasmRelocationEntry> CodeRelocations;
186
187 // Relocations for fixing up references in the data section.
188 std::vector<WasmRelocationEntry> DataRelocations;
189
Dan Gohmand934cb82017-02-24 23:18:00 +0000190 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000191 // Maps function symbols to the index of the type of the function
192 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000193 // Maps function symbols to the table element index space. Used
194 // for TABLE_INDEX relocation types (i.e. address taken functions).
195 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
196 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000197 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
198
199 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
200 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000201 SmallVector<WasmFunctionType, 4> FunctionTypes;
Dan Gohmand934cb82017-02-24 23:18:00 +0000202
Dan Gohman18eafb62017-02-22 01:23:18 +0000203 // TargetObjectWriter wrappers.
204 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000205 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
206 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000207 }
208
Dan Gohmand934cb82017-02-24 23:18:00 +0000209 void startSection(SectionBookkeeping &Section, unsigned SectionId,
210 const char *Name = nullptr);
211 void endSection(SectionBookkeeping &Section);
212
Dan Gohman18eafb62017-02-22 01:23:18 +0000213public:
214 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
215 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
216
Dan Gohmand934cb82017-02-24 23:18:00 +0000217private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000218 ~WasmObjectWriter() override;
219
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000220 void reset() override {
221 CodeRelocations.clear();
222 DataRelocations.clear();
223 TypeIndices.clear();
224 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000225 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000226 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000227 FunctionTypes.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000228 MCObjectWriter::reset();
229 }
230
Dan Gohman18eafb62017-02-22 01:23:18 +0000231 void writeHeader(const MCAssembler &Asm);
232
233 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
234 const MCFragment *Fragment, const MCFixup &Fixup,
235 MCValue Target, bool &IsPCRel,
236 uint64_t &FixedValue) override;
237
238 void executePostLayoutBinding(MCAssembler &Asm,
239 const MCAsmLayout &Layout) override;
240
241 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000242
Sam Cleggb7787fd2017-06-20 04:04:59 +0000243 void writeString(const StringRef Str) {
244 encodeULEB128(Str.size(), getStream());
245 writeBytes(Str);
246 }
247
Sam Clegg9e15f352017-06-03 02:01:24 +0000248 void writeValueType(wasm::ValType Ty) {
249 encodeSLEB128(int32_t(Ty), getStream());
250 }
251
252 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
253 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
254 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000255 void writeTableSection(uint32_t NumElements);
Sam Clegg9e15f352017-06-03 02:01:24 +0000256 void writeMemorySection(const SmallVector<char, 0> &DataBytes);
257 void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
258 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
259 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
260 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000261 const SmallVector<WasmFunction, 4> &Functions);
262 uint64_t
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000263 writeDataSection(const SmallVector<char, 0> &DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +0000264 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
265 const SmallVector<WasmImport, 4> &Imports,
266 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000267 void writeCodeRelocSection();
268 void writeDataRelocSection(uint64_t DataSectionHeaderSize);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000269 void writeLinkingMetaDataSection(uint32_t DataSize, uint32_t DataAlignment,
270 ArrayRef<StringRef> WeakSymbols,
Sam Cleggb7787fd2017-06-20 04:04:59 +0000271 bool HasStackPointer,
Sam Clegg9e15f352017-06-03 02:01:24 +0000272 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000273
274 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
275 uint64_t ContentsOffset);
276
277 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
278 uint64_t HeaderSize);
279 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000280 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
281 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000282};
Sam Clegg9e15f352017-06-03 02:01:24 +0000283
Dan Gohman18eafb62017-02-22 01:23:18 +0000284} // end anonymous namespace
285
286WasmObjectWriter::~WasmObjectWriter() {}
287
Dan Gohmand934cb82017-02-24 23:18:00 +0000288// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
289static unsigned PaddingFor5ByteULEB128(uint32_t X) {
290 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
291}
292
293// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
294static unsigned PaddingFor5ByteSLEB128(int32_t X) {
295 return 5 - getSLEB128Size(X);
296}
297
298// Write out a section header and a patchable section size field.
299void WasmObjectWriter::startSection(SectionBookkeeping &Section,
300 unsigned SectionId,
301 const char *Name) {
302 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
303 "Only custom sections can have names");
304
Sam Cleggb7787fd2017-06-20 04:04:59 +0000305 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000306 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000307
308 Section.SizeOffset = getStream().tell();
309
310 // The section size. We don't know the size yet, so reserve enough space
311 // for any 32-bit value; we'll patch it later.
312 encodeULEB128(UINT32_MAX, getStream());
313
314 // The position where the section starts, for measuring its size.
315 Section.ContentsOffset = getStream().tell();
316
317 // Custom sections in wasm also have a string identifier.
318 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000319 assert(Name);
320 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000321 }
322}
323
324// Now that the section is complete and we know how big it is, patch up the
325// section size field at the start of the section.
326void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
327 uint64_t Size = getStream().tell() - Section.ContentsOffset;
328 if (uint32_t(Size) != Size)
329 report_fatal_error("section size does not fit in a uint32_t");
330
Sam Cleggb7787fd2017-06-20 04:04:59 +0000331 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000332 unsigned Padding = PaddingFor5ByteULEB128(Size);
333
334 // Write the final section size to the payload_len field, which follows
335 // the section id byte.
336 uint8_t Buffer[16];
337 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
338 assert(SizeLen == 5);
339 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
340}
341
Dan Gohman18eafb62017-02-22 01:23:18 +0000342// Emit the Wasm header.
343void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000344 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
345 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000346}
347
348void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
349 const MCAsmLayout &Layout) {
350}
351
352void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
353 const MCAsmLayout &Layout,
354 const MCFragment *Fragment,
355 const MCFixup &Fixup, MCValue Target,
356 bool &IsPCRel, uint64_t &FixedValue) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000357 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000358 uint64_t C = Target.getConstant();
359 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
360 MCContext &Ctx = Asm.getContext();
361
362 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
363 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
364 "Should not have constructed this");
365
366 // Let A, B and C being the components of Target and R be the location of
367 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
368 // If it is pcrel, we want to compute (A - B + C - R).
369
370 // In general, Wasm has no relocations for -B. It can only represent (A + C)
371 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
372 // replace B to implement it: (A - R - K + C)
373 if (IsPCRel) {
374 Ctx.reportError(
375 Fixup.getLoc(),
376 "No relocation available to represent this relative expression");
377 return;
378 }
379
380 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
381
382 if (SymB.isUndefined()) {
383 Ctx.reportError(Fixup.getLoc(),
384 Twine("symbol '") + SymB.getName() +
385 "' can not be undefined in a subtraction expression");
386 return;
387 }
388
389 assert(!SymB.isAbsolute() && "Should have been folded");
390 const MCSection &SecB = SymB.getSection();
391 if (&SecB != &FixupSection) {
392 Ctx.reportError(Fixup.getLoc(),
393 "Cannot represent a difference across sections");
394 return;
395 }
396
397 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
398 uint64_t K = SymBOffset - FixupOffset;
399 IsPCRel = true;
400 C -= K;
401 }
402
403 // We either rejected the fixup or folded B into C at this point.
404 const MCSymbolRefExpr *RefA = Target.getSymA();
405 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
406
Dan Gohmand934cb82017-02-24 23:18:00 +0000407 if (SymA && SymA->isVariable()) {
408 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000409 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
410 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
411 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000412 }
413
414 // Put any constant offset in an addend. Offsets can be negative, and
415 // LLVM expects wrapping, in contrast to wasm's immediates which can't
416 // be negative and don't wrap.
417 FixedValue = 0;
418
Sam Clegg6ad8f192017-07-11 02:21:57 +0000419 if (SymA)
420 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000421
Sam Cleggae03c1e72017-06-13 18:51:50 +0000422 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000423 assert(SymA);
424
Sam Cleggae03c1e72017-06-13 18:51:50 +0000425 unsigned Type = getRelocType(Target, Fixup);
426
Dan Gohmand934cb82017-02-24 23:18:00 +0000427 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000428 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000429
430 if (FixupSection.hasInstructions())
431 CodeRelocations.push_back(Rec);
432 else
433 DataRelocations.push_back(Rec);
434}
435
Dan Gohmand934cb82017-02-24 23:18:00 +0000436// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
437// to allow patching.
438static void
439WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
440 uint8_t Buffer[5];
441 unsigned Padding = PaddingFor5ByteULEB128(X);
442 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
443 assert(SizeLen == 5);
444 Stream.pwrite((char *)Buffer, SizeLen, Offset);
445}
446
447// Write X as an signed LEB value at offset Offset in Stream, padded
448// to allow patching.
449static void
450WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
451 uint8_t Buffer[5];
452 unsigned Padding = PaddingFor5ByteSLEB128(X);
453 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
454 assert(SizeLen == 5);
455 Stream.pwrite((char *)Buffer, SizeLen, Offset);
456}
457
458// Write X as a plain integer value at offset Offset in Stream.
459static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
460 uint8_t Buffer[4];
461 support::endian::write32le(Buffer, X);
462 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
463}
464
465// Compute a value to write into the code at the location covered
466// by RelEntry. This value isn't used by the static linker, since
467// we have addends; it just serves to make the code more readable
468// and to make standalone wasm modules directly usable.
469static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
470 const MCSymbolWasm *Sym = RelEntry.Symbol;
471
472 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000473 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000474 return UINT32_MAX;
475
Sam Cleggfe6414b2017-06-21 23:46:41 +0000476 const auto &Section = cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
Dan Gohmand934cb82017-02-24 23:18:00 +0000477 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
478
479 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
480 uint32_t Value = Address;
481
482 return Value;
483}
484
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000485uint32_t WasmObjectWriter::getRelocationIndexValue(
486 const WasmRelocationEntry &RelEntry) {
487 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000488 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
489 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000490 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000491 report_fatal_error("symbol not found table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000492 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000493 return IndirectSymbolIndices[RelEntry.Symbol];
494 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000495 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000496 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
497 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
498 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000499 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000500 report_fatal_error("symbol not found function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000501 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000502 return SymbolIndices[RelEntry.Symbol];
503 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000504 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000505 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000506 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000507 return TypeIndices[RelEntry.Symbol];
508 default:
509 llvm_unreachable("invalid relocation type");
510 }
511}
512
Dan Gohmand934cb82017-02-24 23:18:00 +0000513// Apply the portions of the relocation records that we can handle ourselves
514// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000515void WasmObjectWriter::applyRelocations(
516 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
517 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000518 for (const WasmRelocationEntry &RelEntry : Relocations) {
519 uint64_t Offset = ContentsOffset +
520 RelEntry.FixupSection->getSectionOffset() +
521 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000522
Sam Cleggb7787fd2017-06-20 04:04:59 +0000523 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000524 switch (RelEntry.Type) {
525 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
526 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000527 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
528 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000529 uint32_t Index = getRelocationIndexValue(RelEntry);
530 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000531 break;
532 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000533 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
534 uint32_t Index = getRelocationIndexValue(RelEntry);
535 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000536 break;
537 }
538 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
539 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000540 WritePatchableSLEB(Stream, Value, Offset);
541 break;
542 }
543 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
544 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000545 WritePatchableLEB(Stream, Value, Offset);
546 break;
547 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000548 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
549 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000550 WriteI32(Stream, Value, Offset);
551 break;
552 }
553 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000554 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000555 }
556 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000557}
558
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000559// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000560// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000561void WasmObjectWriter::writeRelocations(
562 ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
563 raw_pwrite_stream &Stream = getStream();
564 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000565
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000566 uint64_t Offset = RelEntry.Offset +
567 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
568 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000569
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000570 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000571 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000572 encodeULEB128(Index, Stream);
573 if (RelEntry.hasAddend())
574 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000575 }
576}
577
Sam Clegg9e15f352017-06-03 02:01:24 +0000578void WasmObjectWriter::writeTypeSection(
579 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
580 if (FunctionTypes.empty())
581 return;
582
583 SectionBookkeeping Section;
584 startSection(Section, wasm::WASM_SEC_TYPE);
585
586 encodeULEB128(FunctionTypes.size(), getStream());
587
588 for (const WasmFunctionType &FuncTy : FunctionTypes) {
589 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
590 encodeULEB128(FuncTy.Params.size(), getStream());
591 for (wasm::ValType Ty : FuncTy.Params)
592 writeValueType(Ty);
593 encodeULEB128(FuncTy.Returns.size(), getStream());
594 for (wasm::ValType Ty : FuncTy.Returns)
595 writeValueType(Ty);
596 }
597
598 endSection(Section);
599}
600
Sam Cleggb7787fd2017-06-20 04:04:59 +0000601
Sam Clegg9e15f352017-06-03 02:01:24 +0000602void WasmObjectWriter::writeImportSection(
603 const SmallVector<WasmImport, 4> &Imports) {
604 if (Imports.empty())
605 return;
606
607 SectionBookkeeping Section;
608 startSection(Section, wasm::WASM_SEC_IMPORT);
609
610 encodeULEB128(Imports.size(), getStream());
611 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000612 writeString(Import.ModuleName);
613 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000614
615 encodeULEB128(Import.Kind, getStream());
616
617 switch (Import.Kind) {
618 case wasm::WASM_EXTERNAL_FUNCTION:
619 encodeULEB128(Import.Type, getStream());
620 break;
621 case wasm::WASM_EXTERNAL_GLOBAL:
622 encodeSLEB128(int32_t(Import.Type), getStream());
623 encodeULEB128(0, getStream()); // mutability
624 break;
625 default:
626 llvm_unreachable("unsupported import kind");
627 }
628 }
629
630 endSection(Section);
631}
632
633void WasmObjectWriter::writeFunctionSection(
634 const SmallVector<WasmFunction, 4> &Functions) {
635 if (Functions.empty())
636 return;
637
638 SectionBookkeeping Section;
639 startSection(Section, wasm::WASM_SEC_FUNCTION);
640
641 encodeULEB128(Functions.size(), getStream());
642 for (const WasmFunction &Func : Functions)
643 encodeULEB128(Func.Type, getStream());
644
645 endSection(Section);
646}
647
Sam Cleggd99f6072017-06-12 23:52:44 +0000648void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000649 // For now, always emit the table section, since indirect calls are not
650 // valid without it. In the future, we could perhaps be more clever and omit
651 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000652
Sam Clegg9e15f352017-06-03 02:01:24 +0000653 SectionBookkeeping Section;
654 startSection(Section, wasm::WASM_SEC_TABLE);
655
Sam Cleggd99f6072017-06-12 23:52:44 +0000656 encodeULEB128(1, getStream()); // The number of tables.
657 // Fixed to 1 for now.
658 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
659 encodeULEB128(0, getStream()); // flags
660 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000661
662 endSection(Section);
663}
664
665void WasmObjectWriter::writeMemorySection(
666 const SmallVector<char, 0> &DataBytes) {
667 // For now, always emit the memory section, since loads and stores are not
668 // valid without it. In the future, we could perhaps be more clever and omit
669 // it if there are no loads or stores.
670 SectionBookkeeping Section;
671 uint32_t NumPages =
672 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
673
674 startSection(Section, wasm::WASM_SEC_MEMORY);
675 encodeULEB128(1, getStream()); // number of memory spaces
676
677 encodeULEB128(0, getStream()); // flags
678 encodeULEB128(NumPages, getStream()); // initial
679
680 endSection(Section);
681}
682
683void WasmObjectWriter::writeGlobalSection(
684 const SmallVector<WasmGlobal, 4> &Globals) {
685 if (Globals.empty())
686 return;
687
688 SectionBookkeeping Section;
689 startSection(Section, wasm::WASM_SEC_GLOBAL);
690
691 encodeULEB128(Globals.size(), getStream());
692 for (const WasmGlobal &Global : Globals) {
693 writeValueType(Global.Type);
694 write8(Global.IsMutable);
695
696 if (Global.HasImport) {
697 assert(Global.InitialValue == 0);
698 write8(wasm::WASM_OPCODE_GET_GLOBAL);
699 encodeULEB128(Global.ImportIndex, getStream());
700 } else {
701 assert(Global.ImportIndex == 0);
702 write8(wasm::WASM_OPCODE_I32_CONST);
703 encodeSLEB128(Global.InitialValue, getStream()); // offset
704 }
705 write8(wasm::WASM_OPCODE_END);
706 }
707
708 endSection(Section);
709}
710
711void WasmObjectWriter::writeExportSection(
712 const SmallVector<WasmExport, 4> &Exports) {
713 if (Exports.empty())
714 return;
715
716 SectionBookkeeping Section;
717 startSection(Section, wasm::WASM_SEC_EXPORT);
718
719 encodeULEB128(Exports.size(), getStream());
720 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000721 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000722 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000723 encodeULEB128(Export.Index, getStream());
724 }
725
726 endSection(Section);
727}
728
729void WasmObjectWriter::writeElemSection(
730 const SmallVector<uint32_t, 4> &TableElems) {
731 if (TableElems.empty())
732 return;
733
734 SectionBookkeeping Section;
735 startSection(Section, wasm::WASM_SEC_ELEM);
736
737 encodeULEB128(1, getStream()); // number of "segments"
738 encodeULEB128(0, getStream()); // the table index
739
740 // init expr for starting offset
741 write8(wasm::WASM_OPCODE_I32_CONST);
742 encodeSLEB128(0, getStream());
743 write8(wasm::WASM_OPCODE_END);
744
745 encodeULEB128(TableElems.size(), getStream());
746 for (uint32_t Elem : TableElems)
747 encodeULEB128(Elem, getStream());
748
749 endSection(Section);
750}
751
752void WasmObjectWriter::writeCodeSection(
753 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000754 const SmallVector<WasmFunction, 4> &Functions) {
755 if (Functions.empty())
756 return;
757
758 SectionBookkeeping Section;
759 startSection(Section, wasm::WASM_SEC_CODE);
760
761 encodeULEB128(Functions.size(), getStream());
762
763 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000764 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000765
Sam Clegg9e15f352017-06-03 02:01:24 +0000766 int64_t Size = 0;
767 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
768 report_fatal_error(".size expression must be evaluatable");
769
770 encodeULEB128(Size, getStream());
771
Sam Cleggfe6414b2017-06-21 23:46:41 +0000772 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000773
774 Asm.writeSectionData(&FuncSection, Layout);
775 }
776
Sam Clegg9e15f352017-06-03 02:01:24 +0000777 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000778 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000779
780 endSection(Section);
781}
782
783uint64_t WasmObjectWriter::writeDataSection(
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000784 const SmallVector<char, 0> &DataBytes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000785 if (DataBytes.empty())
786 return 0;
787
788 SectionBookkeeping Section;
789 startSection(Section, wasm::WASM_SEC_DATA);
790
791 encodeULEB128(1, getStream()); // count
792 encodeULEB128(0, getStream()); // memory index
793 write8(wasm::WASM_OPCODE_I32_CONST);
794 encodeSLEB128(0, getStream()); // offset
795 write8(wasm::WASM_OPCODE_END);
796 encodeULEB128(DataBytes.size(), getStream()); // size
797 uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
798 writeBytes(DataBytes); // data
799
800 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000801 applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000802
803 endSection(Section);
804 return HeaderSize;
805}
806
807void WasmObjectWriter::writeNameSection(
808 const SmallVector<WasmFunction, 4> &Functions,
809 const SmallVector<WasmImport, 4> &Imports,
810 unsigned NumFuncImports) {
811 uint32_t TotalFunctions = NumFuncImports + Functions.size();
812 if (TotalFunctions == 0)
813 return;
814
815 SectionBookkeeping Section;
816 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
817 SectionBookkeeping SubSection;
818 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
819
820 encodeULEB128(TotalFunctions, getStream());
821 uint32_t Index = 0;
822 for (const WasmImport &Import : Imports) {
823 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
824 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000825 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000826 ++Index;
827 }
828 }
829 for (const WasmFunction &Func : Functions) {
830 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000831 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000832 ++Index;
833 }
834
835 endSection(SubSection);
836 endSection(Section);
837}
838
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000839void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
841 // for descriptions of the reloc sections.
842
843 if (CodeRelocations.empty())
844 return;
845
846 SectionBookkeeping Section;
847 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
848
849 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000850 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000851
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000852 writeRelocations(CodeRelocations, 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000853
854 endSection(Section);
855}
856
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000857void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000858 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
859 // for descriptions of the reloc sections.
860
861 if (DataRelocations.empty())
862 return;
863
864 SectionBookkeeping Section;
865 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
866
867 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
868 encodeULEB128(DataRelocations.size(), getStream());
869
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000870 writeRelocations(DataRelocations, DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
872 endSection(Section);
873}
874
875void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg9e1ade92017-06-27 20:27:59 +0000876 uint32_t DataSize, uint32_t DataAlignment, ArrayRef<StringRef> WeakSymbols,
877 bool HasStackPointer, uint32_t StackPointerGlobal) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000878 SectionBookkeeping Section;
879 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000880 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000881
Sam Cleggb7787fd2017-06-20 04:04:59 +0000882 if (HasStackPointer) {
883 startSection(SubSection, wasm::WASM_STACK_POINTER);
884 encodeULEB128(StackPointerGlobal, getStream()); // id
885 endSection(SubSection);
886 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
Sam Cleggb7787fd2017-06-20 04:04:59 +0000888 if (WeakSymbols.size() != 0) {
889 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
890 encodeULEB128(WeakSymbols.size(), getStream());
891 for (const StringRef Export: WeakSymbols) {
892 writeString(Export);
893 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
894 }
895 endSection(SubSection);
896 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000897
Sam Clegg9e1ade92017-06-27 20:27:59 +0000898 if (DataSize > 0) {
899 startSection(SubSection, wasm::WASM_DATA_SIZE);
900 encodeULEB128(DataSize, getStream());
901 endSection(SubSection);
902
903 startSection(SubSection, wasm::WASM_DATA_ALIGNMENT);
904 encodeULEB128(DataAlignment, getStream());
905 endSection(SubSection);
906 }
907
Sam Clegg9e15f352017-06-03 02:01:24 +0000908 endSection(Section);
909}
910
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000911uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
912 assert(Symbol.isFunction());
913 assert(TypeIndices.count(&Symbol));
914 return TypeIndices[&Symbol];
915}
916
917uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
918 assert(Symbol.isFunction());
919
920 WasmFunctionType F;
921 if (Symbol.isVariable()) {
922 const MCExpr *Expr = Symbol.getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000923 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000924 const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
925 F.Returns = ResolvedSym->getReturns();
926 F.Params = ResolvedSym->getParams();
927 } else {
928 F.Returns = Symbol.getReturns();
929 F.Params = Symbol.getParams();
930 }
931
932 auto Pair =
933 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
934 if (Pair.second)
935 FunctionTypes.push_back(F);
936 TypeIndices[&Symbol] = Pair.first->second;
937
938 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
939 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
940 return Pair.first->second;
941}
942
Dan Gohman18eafb62017-02-22 01:23:18 +0000943void WasmObjectWriter::writeObject(MCAssembler &Asm,
944 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000945 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000946 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000947 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000948
949 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000950 SmallVector<WasmFunction, 4> Functions;
951 SmallVector<uint32_t, 4> TableElems;
952 SmallVector<WasmGlobal, 4> Globals;
953 SmallVector<WasmImport, 4> Imports;
954 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000955 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000956 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
957 unsigned NumFuncImports = 0;
958 unsigned NumGlobalImports = 0;
959 SmallVector<char, 0> DataBytes;
Sam Clegg9e1ade92017-06-27 20:27:59 +0000960 uint32_t DataAlignment = 1;
Dan Gohman970d02c2017-03-30 23:58:19 +0000961 uint32_t StackPointerGlobal = 0;
962 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000963
964 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000965 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000966 switch (RelEntry.Type) {
967 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
968 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
969 IsAddressTaken.insert(RelEntry.Symbol);
970 break;
971 default:
972 break;
973 }
974 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000975 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000976 switch (RelEntry.Type) {
977 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
978 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
979 IsAddressTaken.insert(RelEntry.Symbol);
980 break;
981 default:
982 break;
983 }
984 }
985
986 // Populate the Imports set.
987 for (const MCSymbol &S : Asm.symbols()) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000988 const auto &WS = static_cast<const MCSymbolWasm &>(S);
989
990 if (WS.isTemporary())
Sam Clegg8c4baa002017-07-05 20:09:26 +0000991 continue;
992
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000993 if (WS.isFunction())
994 registerFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000995
996 // If the symbol is not defined in this translation unit, import it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000997 if (!WS.isDefined(/*SetUsed=*/false) || WS.isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000998 WasmImport Import;
999 Import.ModuleName = WS.getModuleName();
1000 Import.FieldName = WS.getName();
1001
1002 if (WS.isFunction()) {
1003 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001004 Import.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001005 SymbolIndices[&WS] = NumFuncImports;
1006 ++NumFuncImports;
1007 } else {
1008 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001009 Import.Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +00001010 SymbolIndices[&WS] = NumGlobalImports;
1011 ++NumGlobalImports;
1012 }
1013
1014 Imports.push_back(Import);
1015 }
1016 }
1017
Dan Gohman82607f52017-02-24 23:46:05 +00001018 // In the special .global_variables section, we've encoded global
1019 // variables used by the function. Translate them into the Globals
1020 // list.
1021 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
1022 if (!GlobalVars->getFragmentList().empty()) {
1023 if (GlobalVars->getFragmentList().size() != 1)
1024 report_fatal_error("only one .global_variables fragment supported");
1025 const MCFragment &Frag = *GlobalVars->begin();
1026 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1027 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001028 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001029 if (!DataFrag.getFixups().empty())
1030 report_fatal_error("fixups not supported in .global_variables");
1031 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001032 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1033 *end = (const uint8_t *)Contents.data() + Contents.size();
1034 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001035 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001036 if (end - p < 3)
1037 report_fatal_error("truncated global variable encoding");
1038 G.Type = wasm::ValType(int8_t(*p++));
1039 G.IsMutable = bool(*p++);
1040 G.HasImport = bool(*p++);
1041 if (G.HasImport) {
1042 G.InitialValue = 0;
1043
1044 WasmImport Import;
1045 Import.ModuleName = (const char *)p;
1046 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1047 if (!nul)
1048 report_fatal_error("global module name must be nul-terminated");
1049 p = nul + 1;
1050 nul = (const uint8_t *)memchr(p, '\0', end - p);
1051 if (!nul)
1052 report_fatal_error("global base name must be nul-terminated");
1053 Import.FieldName = (const char *)p;
1054 p = nul + 1;
1055
1056 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1057 Import.Type = int32_t(G.Type);
1058
1059 G.ImportIndex = NumGlobalImports;
1060 ++NumGlobalImports;
1061
1062 Imports.push_back(Import);
1063 } else {
1064 unsigned n;
1065 G.InitialValue = decodeSLEB128(p, &n);
1066 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001067 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001068 report_fatal_error("global initial value must be valid SLEB128");
1069 p += n;
1070 }
Dan Gohman82607f52017-02-24 23:46:05 +00001071 Globals.push_back(G);
1072 }
1073 }
1074
Dan Gohman970d02c2017-03-30 23:58:19 +00001075 // In the special .stack_pointer section, we've encoded the stack pointer
1076 // index.
1077 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1078 if (!StackPtr->getFragmentList().empty()) {
1079 if (StackPtr->getFragmentList().size() != 1)
1080 report_fatal_error("only one .stack_pointer fragment supported");
1081 const MCFragment &Frag = *StackPtr->begin();
1082 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1083 report_fatal_error("only data supported in .stack_pointer");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001084 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman970d02c2017-03-30 23:58:19 +00001085 if (!DataFrag.getFixups().empty())
1086 report_fatal_error("fixups not supported in .stack_pointer");
1087 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1088 if (Contents.size() != 4)
1089 report_fatal_error("only one entry supported in .stack_pointer");
1090 HasStackPointer = true;
1091 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1092 }
1093
Sam Cleggb7787fd2017-06-20 04:04:59 +00001094 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001095 for (const MCSymbol &S : Asm.symbols()) {
1096 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1097 // or used in relocations.
1098 if (S.isTemporary() && S.getName().empty())
1099 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001100
Dan Gohmand934cb82017-02-24 23:18:00 +00001101 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001102 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1103 << " isDefined=" << S.isDefined() << " isExternal="
1104 << S.isExternal() << " isTemporary=" << S.isTemporary()
1105 << " isFunction=" << WS.isFunction()
1106 << " isWeak=" << WS.isWeak()
1107 << " isVariable=" << WS.isVariable() << "\n");
1108
1109 if (WS.isWeak())
1110 WeakSymbols.push_back(WS.getName());
1111
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001112 if (WS.isVariable())
1113 continue;
1114
Dan Gohmand934cb82017-02-24 23:18:00 +00001115 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001116
Dan Gohmand934cb82017-02-24 23:18:00 +00001117 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001118 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001119 if (WS.getOffset() != 0)
1120 report_fatal_error(
1121 "function sections must contain one function each");
1122
1123 if (WS.getSize() == 0)
1124 report_fatal_error(
1125 "function symbols must have a size set with .size");
1126
Dan Gohmand934cb82017-02-24 23:18:00 +00001127 // A definition. Take the next available index.
1128 Index = NumFuncImports + Functions.size();
1129
1130 // Prepare the function.
1131 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001132 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001133 Func.Sym = &WS;
1134 SymbolIndices[&WS] = Index;
1135 Functions.push_back(Func);
1136 } else {
1137 // An import; the index was assigned above.
1138 Index = SymbolIndices.find(&WS)->second;
1139 }
1140
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001141 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1142
Dan Gohmand934cb82017-02-24 23:18:00 +00001143 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001144 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001145 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001146 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001147 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001148 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001149 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001150 if (WS.isTemporary() && !WS.getSize())
1151 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001152
Sam Cleggfe6414b2017-06-21 23:46:41 +00001153 if (!WS.isDefined(/*SetUsed=*/false))
1154 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001155
Sam Cleggfe6414b2017-06-21 23:46:41 +00001156 if (WS.getOffset() != 0)
1157 report_fatal_error("data sections must contain one variable each: " +
1158 WS.getName());
1159 if (!WS.getSize())
1160 report_fatal_error("data symbols must have a size set with .size: " +
1161 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001162
Sam Cleggfe6414b2017-06-21 23:46:41 +00001163 int64_t Size = 0;
1164 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1165 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001166
Sam Cleggfe6414b2017-06-21 23:46:41 +00001167 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001168
Sam Cleggfe6414b2017-06-21 23:46:41 +00001169 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1170 report_fatal_error("data sections must contain at most one variable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001171
Sam Cleggfe6414b2017-06-21 23:46:41 +00001172 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
Sam Clegg9e1ade92017-06-27 20:27:59 +00001173 DataAlignment = std::max(DataAlignment, DataSection.getAlignment());
Dan Gohmand934cb82017-02-24 23:18:00 +00001174
Sam Cleggfe6414b2017-06-21 23:46:41 +00001175 DataSection.setSectionOffset(DataBytes.size());
Dan Gohmand934cb82017-02-24 23:18:00 +00001176
Sam Cleggfe6414b2017-06-21 23:46:41 +00001177 for (const MCFragment &Frag : DataSection) {
1178 if (Frag.hasInstructions())
1179 report_fatal_error("only data supported in data sections");
Dan Gohmand934cb82017-02-24 23:18:00 +00001180
Sam Cleggfe6414b2017-06-21 23:46:41 +00001181 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1182 if (Align->getValueSize() != 1)
1183 report_fatal_error("only byte values supported for alignment");
1184 // If nops are requested, use zeros, as this is the data section.
1185 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1186 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1187 Align->getAlignment()),
1188 DataBytes.size() +
1189 Align->getMaxBytesToEmit());
1190 DataBytes.resize(Size, Value);
1191 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Sam Cleggb03c2b42017-07-10 18:36:34 +00001192 DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
Sam Cleggfe6414b2017-06-21 23:46:41 +00001193 } else {
1194 const auto &DataFrag = cast<MCDataFragment>(Frag);
1195 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1196
1197 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Dan Gohmand934cb82017-02-24 23:18:00 +00001198 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001199 }
Sam Cleggfe6414b2017-06-21 23:46:41 +00001200
1201 // For each global, prepare a corresponding wasm global holding its
1202 // address. For externals these will also be named exports.
1203 Index = NumGlobalImports + Globals.size();
1204
1205 WasmGlobal Global;
1206 Global.Type = PtrType;
1207 Global.IsMutable = false;
1208 Global.HasImport = false;
1209 Global.InitialValue = DataSection.getSectionOffset();
1210 Global.ImportIndex = 0;
1211 SymbolIndices[&WS] = Index;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001212 DEBUG(dbgs() << " -> global index: " << Index << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001213 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001214 }
1215
1216 // If the symbol is visible outside this translation unit, export it.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001217 if ((WS.isExternal() && WS.isDefined(/*SetUsed=*/false))) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001218 WasmExport Export;
1219 Export.FieldName = WS.getName();
1220 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001221 if (WS.isFunction())
1222 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1223 else
1224 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001225 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001226 Exports.push_back(Export);
1227 }
1228 }
1229
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001230 // Handle weak aliases. We need to process these in a separate pass because
1231 // we need to have processed the target of the alias before the alias itself
1232 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001233 for (const MCSymbol &S : Asm.symbols()) {
1234 if (!S.isVariable())
1235 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001236 assert(S.isDefined(/*SetUsed=*/false));
1237
1238 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001239 // Find the target symbol of this weak alias and export that index
Sam Cleggb7787fd2017-06-20 04:04:59 +00001240 const MCExpr *Expr = WS.getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +00001241 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Cleggfe6414b2017-06-21 23:46:41 +00001242 const auto *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001243 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1244 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001245 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001246 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001247
1248 WasmExport Export;
1249 Export.FieldName = WS.getName();
1250 Export.Index = Index;
1251 if (WS.isFunction())
1252 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1253 else
1254 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001255 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001256 Exports.push_back(Export);
1257 }
1258
Dan Gohmand934cb82017-02-24 23:18:00 +00001259 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001260 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1261 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1262 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001263
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001264 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001265 }
1266
Dan Gohman18eafb62017-02-22 01:23:18 +00001267 // Write out the Wasm header.
1268 writeHeader(Asm);
1269
Sam Clegg9e15f352017-06-03 02:01:24 +00001270 writeTypeSection(FunctionTypes);
1271 writeImportSection(Imports);
1272 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001273 writeTableSection(TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001274 writeMemorySection(DataBytes);
1275 writeGlobalSection(Globals);
1276 writeExportSection(Exports);
1277 // TODO: Start Section
1278 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001279 writeCodeSection(Asm, Layout, Functions);
1280 uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +00001281 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001282 writeCodeRelocSection();
1283 writeDataRelocSection(DataSectionHeaderSize);
Sam Clegg9e1ade92017-06-27 20:27:59 +00001284 writeLinkingMetaDataSection(DataBytes.size(), DataAlignment, WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001285
Dan Gohmand934cb82017-02-24 23:18:00 +00001286 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001287 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001288}
1289
1290MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1291 raw_pwrite_stream &OS) {
1292 return new WasmObjectWriter(MOTW, OS);
1293}