blob: dd2e371c114059f2763ce44b5229ea5a8a056dd0 [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
39#undef DEBUG_TYPE
40#define DEBUG_TYPE "reloc-info"
41
42namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000043
Dan Gohmand934cb82017-02-24 23:18:00 +000044// For patching purposes, we need to remember where each section starts, both
45// for patching up the section size field, and for patching up references to
46// locations within the section.
47struct SectionBookkeeping {
48 // Where the size of the section is written.
49 uint64_t SizeOffset;
50 // Where the contents of the section starts (after the header).
51 uint64_t ContentsOffset;
52};
53
Sam Clegg9e15f352017-06-03 02:01:24 +000054// The signature of a wasm function, in a struct capable of being used as a
55// DenseMap key.
56struct WasmFunctionType {
57 // Support empty and tombstone instances, needed by DenseMap.
58 enum { Plain, Empty, Tombstone } State;
59
60 // The return types of the function.
61 SmallVector<wasm::ValType, 1> Returns;
62
63 // The parameter types of the function.
64 SmallVector<wasm::ValType, 4> Params;
65
66 WasmFunctionType() : State(Plain) {}
67
68 bool operator==(const WasmFunctionType &Other) const {
69 return State == Other.State && Returns == Other.Returns &&
70 Params == Other.Params;
71 }
72};
73
74// Traits for using WasmFunctionType in a DenseMap.
75struct WasmFunctionTypeDenseMapInfo {
76 static WasmFunctionType getEmptyKey() {
77 WasmFunctionType FuncTy;
78 FuncTy.State = WasmFunctionType::Empty;
79 return FuncTy;
80 }
81 static WasmFunctionType getTombstoneKey() {
82 WasmFunctionType FuncTy;
83 FuncTy.State = WasmFunctionType::Tombstone;
84 return FuncTy;
85 }
86 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
87 uintptr_t Value = FuncTy.State;
88 for (wasm::ValType Ret : FuncTy.Returns)
89 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
90 for (wasm::ValType Param : FuncTy.Params)
91 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
92 return Value;
93 }
94 static bool isEqual(const WasmFunctionType &LHS,
95 const WasmFunctionType &RHS) {
96 return LHS == RHS;
97 }
98};
99
100// A wasm import to be written into the import section.
101struct WasmImport {
102 StringRef ModuleName;
103 StringRef FieldName;
104 unsigned Kind;
105 int32_t Type;
106};
107
108// A wasm function to be written into the function section.
109struct WasmFunction {
110 int32_t Type;
111 const MCSymbolWasm *Sym;
112};
113
114// A wasm export to be written into the export section.
115struct WasmExport {
116 StringRef FieldName;
117 unsigned Kind;
118 uint32_t Index;
119};
120
121// A wasm global to be written into the global section.
122struct WasmGlobal {
123 wasm::ValType Type;
124 bool IsMutable;
125 bool HasImport;
126 uint64_t InitialValue;
127 uint32_t ImportIndex;
128};
129
Sam Clegg6dc65e92017-06-06 16:38:59 +0000130// Information about a single relocation.
131struct WasmRelocationEntry {
132 uint64_t Offset; // Where is the relocation.
133 const MCSymbolWasm *Symbol; // The symbol to relocate with.
134 int64_t Addend; // A value to add to the symbol.
135 unsigned Type; // The type of the relocation.
136 MCSectionWasm *FixupSection;// The section the relocation is targeting.
137
138 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
139 int64_t Addend, unsigned Type,
140 MCSectionWasm *FixupSection)
141 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
142 FixupSection(FixupSection) {}
143
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000144 bool hasAddend() const {
145 switch (Type) {
146 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
147 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
148 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
149 return true;
150 default:
151 return false;
152 }
153 }
154
Sam Clegg6dc65e92017-06-06 16:38:59 +0000155 void print(raw_ostream &Out) const {
156 Out << "Off=" << Offset << ", Sym=" << Symbol << ", Addend=" << Addend
157 << ", Type=" << Type << ", FixupSection=" << FixupSection;
158 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000159
160#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
161 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
162#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000163};
164
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}
169
Dan Gohman18eafb62017-02-22 01:23:18 +0000170class WasmObjectWriter : public MCObjectWriter {
171 /// Helper struct for containing some precomputed information on symbols.
172 struct WasmSymbolData {
173 const MCSymbolWasm *Symbol;
174 StringRef Name;
175
176 // Support lexicographic sorting.
177 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
178 };
179
180 /// The target specific Wasm writer instance.
181 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
182
Dan Gohmand934cb82017-02-24 23:18:00 +0000183 // Relocations for fixing up references in the code section.
184 std::vector<WasmRelocationEntry> CodeRelocations;
185
186 // Relocations for fixing up references in the data section.
187 std::vector<WasmRelocationEntry> DataRelocations;
188
Dan Gohmand934cb82017-02-24 23:18:00 +0000189 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000190 // Maps function symbols to the index of the type of the function
191 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000192 // Maps function symbols to the table element index space. Used
193 // for TABLE_INDEX relocation types (i.e. address taken functions).
194 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
195 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000196 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
197
198 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
199 FunctionTypeIndices;
Dan Gohmand934cb82017-02-24 23:18:00 +0000200
Dan Gohman18eafb62017-02-22 01:23:18 +0000201 // TargetObjectWriter wrappers.
202 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000203 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
204 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000205 }
206
Dan Gohmand934cb82017-02-24 23:18:00 +0000207 void startSection(SectionBookkeeping &Section, unsigned SectionId,
208 const char *Name = nullptr);
209 void endSection(SectionBookkeeping &Section);
210
Dan Gohman18eafb62017-02-22 01:23:18 +0000211public:
212 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
213 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
214
Dan Gohmand934cb82017-02-24 23:18:00 +0000215private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000216 ~WasmObjectWriter() override;
217
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000218 void reset() override {
219 CodeRelocations.clear();
220 DataRelocations.clear();
221 TypeIndices.clear();
222 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000223 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000224 FunctionTypeIndices.clear();
225 MCObjectWriter::reset();
226 }
227
Dan Gohman18eafb62017-02-22 01:23:18 +0000228 void writeHeader(const MCAssembler &Asm);
229
230 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
231 const MCFragment *Fragment, const MCFixup &Fixup,
232 MCValue Target, bool &IsPCRel,
233 uint64_t &FixedValue) override;
234
235 void executePostLayoutBinding(MCAssembler &Asm,
236 const MCAsmLayout &Layout) override;
237
238 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000239
Sam Cleggb7787fd2017-06-20 04:04:59 +0000240 void writeString(const StringRef Str) {
241 encodeULEB128(Str.size(), getStream());
242 writeBytes(Str);
243 }
244
Sam Clegg9e15f352017-06-03 02:01:24 +0000245 void writeValueType(wasm::ValType Ty) {
246 encodeSLEB128(int32_t(Ty), getStream());
247 }
248
249 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
250 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
251 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000252 void writeTableSection(uint32_t NumElements);
Sam Clegg9e15f352017-06-03 02:01:24 +0000253 void writeMemorySection(const SmallVector<char, 0> &DataBytes);
254 void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
255 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
256 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
257 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000258 const SmallVector<WasmFunction, 4> &Functions);
259 uint64_t
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000260 writeDataSection(const SmallVector<char, 0> &DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +0000261 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
262 const SmallVector<WasmImport, 4> &Imports,
263 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000264 void writeCodeRelocSection();
265 void writeDataRelocSection(uint64_t DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000266 void writeLinkingMetaDataSection(ArrayRef<StringRef> WeakSymbols,
267 bool HasStackPointer,
Sam Clegg9e15f352017-06-03 02:01:24 +0000268 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000269
270 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
271 uint64_t ContentsOffset);
272
273 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
274 uint64_t HeaderSize);
275 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Dan Gohman18eafb62017-02-22 01:23:18 +0000276};
Sam Clegg9e15f352017-06-03 02:01:24 +0000277
Dan Gohman18eafb62017-02-22 01:23:18 +0000278} // end anonymous namespace
279
280WasmObjectWriter::~WasmObjectWriter() {}
281
Dan Gohmand934cb82017-02-24 23:18:00 +0000282// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
283static unsigned PaddingFor5ByteULEB128(uint32_t X) {
284 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
285}
286
287// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
288static unsigned PaddingFor5ByteSLEB128(int32_t X) {
289 return 5 - getSLEB128Size(X);
290}
291
292// Write out a section header and a patchable section size field.
293void WasmObjectWriter::startSection(SectionBookkeeping &Section,
294 unsigned SectionId,
295 const char *Name) {
296 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
297 "Only custom sections can have names");
298
Sam Cleggb7787fd2017-06-20 04:04:59 +0000299 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000300 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000301
302 Section.SizeOffset = getStream().tell();
303
304 // The section size. We don't know the size yet, so reserve enough space
305 // for any 32-bit value; we'll patch it later.
306 encodeULEB128(UINT32_MAX, getStream());
307
308 // The position where the section starts, for measuring its size.
309 Section.ContentsOffset = getStream().tell();
310
311 // Custom sections in wasm also have a string identifier.
312 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000313 assert(Name);
314 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000315 }
316}
317
318// Now that the section is complete and we know how big it is, patch up the
319// section size field at the start of the section.
320void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
321 uint64_t Size = getStream().tell() - Section.ContentsOffset;
322 if (uint32_t(Size) != Size)
323 report_fatal_error("section size does not fit in a uint32_t");
324
Sam Cleggb7787fd2017-06-20 04:04:59 +0000325 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000326 unsigned Padding = PaddingFor5ByteULEB128(Size);
327
328 // Write the final section size to the payload_len field, which follows
329 // the section id byte.
330 uint8_t Buffer[16];
331 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
332 assert(SizeLen == 5);
333 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
334}
335
Dan Gohman18eafb62017-02-22 01:23:18 +0000336// Emit the Wasm header.
337void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000338 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
339 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000340}
341
342void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
343 const MCAsmLayout &Layout) {
344}
345
346void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
347 const MCAsmLayout &Layout,
348 const MCFragment *Fragment,
349 const MCFixup &Fixup, MCValue Target,
350 bool &IsPCRel, uint64_t &FixedValue) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000351 MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
352 uint64_t C = Target.getConstant();
353 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
354 MCContext &Ctx = Asm.getContext();
355
356 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
357 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
358 "Should not have constructed this");
359
360 // Let A, B and C being the components of Target and R be the location of
361 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
362 // If it is pcrel, we want to compute (A - B + C - R).
363
364 // In general, Wasm has no relocations for -B. It can only represent (A + C)
365 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
366 // replace B to implement it: (A - R - K + C)
367 if (IsPCRel) {
368 Ctx.reportError(
369 Fixup.getLoc(),
370 "No relocation available to represent this relative expression");
371 return;
372 }
373
374 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
375
376 if (SymB.isUndefined()) {
377 Ctx.reportError(Fixup.getLoc(),
378 Twine("symbol '") + SymB.getName() +
379 "' can not be undefined in a subtraction expression");
380 return;
381 }
382
383 assert(!SymB.isAbsolute() && "Should have been folded");
384 const MCSection &SecB = SymB.getSection();
385 if (&SecB != &FixupSection) {
386 Ctx.reportError(Fixup.getLoc(),
387 "Cannot represent a difference across sections");
388 return;
389 }
390
391 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
392 uint64_t K = SymBOffset - FixupOffset;
393 IsPCRel = true;
394 C -= K;
395 }
396
397 // We either rejected the fixup or folded B into C at this point.
398 const MCSymbolRefExpr *RefA = Target.getSymA();
399 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
400
401 bool ViaWeakRef = false;
402 if (SymA && SymA->isVariable()) {
403 const MCExpr *Expr = SymA->getVariableValue();
404 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
405 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
406 SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
407 ViaWeakRef = true;
408 }
409 }
410 }
411
412 // Put any constant offset in an addend. Offsets can be negative, and
413 // LLVM expects wrapping, in contrast to wasm's immediates which can't
414 // be negative and don't wrap.
415 FixedValue = 0;
416
417 if (SymA) {
418 if (ViaWeakRef)
419 llvm_unreachable("weakref used in reloc not yet implemented");
420 else
421 SymA->setUsedInReloc();
422 }
423
Sam Cleggae03c1e72017-06-13 18:51:50 +0000424 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000425 assert(SymA);
426
Sam Cleggae03c1e72017-06-13 18:51:50 +0000427 unsigned Type = getRelocType(Target, Fixup);
428
Dan Gohmand934cb82017-02-24 23:18:00 +0000429 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000430 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000431
432 if (FixupSection.hasInstructions())
433 CodeRelocations.push_back(Rec);
434 else
435 DataRelocations.push_back(Rec);
436}
437
Dan Gohmand934cb82017-02-24 23:18:00 +0000438// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
439// to allow patching.
440static void
441WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
442 uint8_t Buffer[5];
443 unsigned Padding = PaddingFor5ByteULEB128(X);
444 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
445 assert(SizeLen == 5);
446 Stream.pwrite((char *)Buffer, SizeLen, Offset);
447}
448
449// Write X as an signed LEB value at offset Offset in Stream, padded
450// to allow patching.
451static void
452WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
453 uint8_t Buffer[5];
454 unsigned Padding = PaddingFor5ByteSLEB128(X);
455 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
456 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
467// Compute a value to write into the code at the location covered
468// by RelEntry. This value isn't used by the static linker, since
469// we have addends; it just serves to make the code more readable
470// and to make standalone wasm modules directly usable.
471static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
472 const MCSymbolWasm *Sym = RelEntry.Symbol;
473
474 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000475 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000476 return UINT32_MAX;
477
478 MCSectionWasm &Section =
479 cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
480 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
481
482 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
483 uint32_t Value = Address;
484
485 return Value;
486}
487
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000488uint32_t WasmObjectWriter::getRelocationIndexValue(
489 const WasmRelocationEntry &RelEntry) {
490 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000491 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
492 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000493 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
494 report_fatal_error("symbol not found table index space:" +
495 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000496 return IndirectSymbolIndices[RelEntry.Symbol];
497 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000498 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000499 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
500 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
501 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000502 if (!SymbolIndices.count(RelEntry.Symbol))
503 report_fatal_error("symbol not found function/global index space:" +
504 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000505 return SymbolIndices[RelEntry.Symbol];
506 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000507 if (!TypeIndices.count(RelEntry.Symbol))
508 report_fatal_error("symbol not found in type index space:" +
509 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000510 return TypeIndices[RelEntry.Symbol];
511 default:
512 llvm_unreachable("invalid relocation type");
513 }
514}
515
Dan Gohmand934cb82017-02-24 23:18:00 +0000516// Apply the portions of the relocation records that we can handle ourselves
517// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000518void WasmObjectWriter::applyRelocations(
519 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
520 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000521 for (const WasmRelocationEntry &RelEntry : Relocations) {
522 uint64_t Offset = ContentsOffset +
523 RelEntry.FixupSection->getSectionOffset() +
524 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000525
Sam Cleggb7787fd2017-06-20 04:04:59 +0000526 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000527 switch (RelEntry.Type) {
528 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
529 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000530 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
531 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000532 uint32_t Index = getRelocationIndexValue(RelEntry);
533 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000534 break;
535 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000536 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
537 uint32_t Index = getRelocationIndexValue(RelEntry);
538 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000539 break;
540 }
541 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
542 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000543 WritePatchableSLEB(Stream, Value, Offset);
544 break;
545 }
546 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
547 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000548 WritePatchableLEB(Stream, Value, Offset);
549 break;
550 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000551 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
552 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000553 WriteI32(Stream, Value, Offset);
554 break;
555 }
556 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000557 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000558 }
559 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000560}
561
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000562// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000563// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000564void WasmObjectWriter::writeRelocations(
565 ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
566 raw_pwrite_stream &Stream = getStream();
567 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000568
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000569 uint64_t Offset = RelEntry.Offset +
570 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
571 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000572
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000573 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000574 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000575 encodeULEB128(Index, Stream);
576 if (RelEntry.hasAddend())
577 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000578 }
579}
580
Sam Clegg9e15f352017-06-03 02:01:24 +0000581void WasmObjectWriter::writeTypeSection(
582 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
583 if (FunctionTypes.empty())
584 return;
585
586 SectionBookkeeping Section;
587 startSection(Section, wasm::WASM_SEC_TYPE);
588
589 encodeULEB128(FunctionTypes.size(), getStream());
590
591 for (const WasmFunctionType &FuncTy : FunctionTypes) {
592 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
593 encodeULEB128(FuncTy.Params.size(), getStream());
594 for (wasm::ValType Ty : FuncTy.Params)
595 writeValueType(Ty);
596 encodeULEB128(FuncTy.Returns.size(), getStream());
597 for (wasm::ValType Ty : FuncTy.Returns)
598 writeValueType(Ty);
599 }
600
601 endSection(Section);
602}
603
Sam Cleggb7787fd2017-06-20 04:04:59 +0000604
Sam Clegg9e15f352017-06-03 02:01:24 +0000605void WasmObjectWriter::writeImportSection(
606 const SmallVector<WasmImport, 4> &Imports) {
607 if (Imports.empty())
608 return;
609
610 SectionBookkeeping Section;
611 startSection(Section, wasm::WASM_SEC_IMPORT);
612
613 encodeULEB128(Imports.size(), getStream());
614 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000615 writeString(Import.ModuleName);
616 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000617
618 encodeULEB128(Import.Kind, getStream());
619
620 switch (Import.Kind) {
621 case wasm::WASM_EXTERNAL_FUNCTION:
622 encodeULEB128(Import.Type, getStream());
623 break;
624 case wasm::WASM_EXTERNAL_GLOBAL:
625 encodeSLEB128(int32_t(Import.Type), getStream());
626 encodeULEB128(0, getStream()); // mutability
627 break;
628 default:
629 llvm_unreachable("unsupported import kind");
630 }
631 }
632
633 endSection(Section);
634}
635
636void WasmObjectWriter::writeFunctionSection(
637 const SmallVector<WasmFunction, 4> &Functions) {
638 if (Functions.empty())
639 return;
640
641 SectionBookkeeping Section;
642 startSection(Section, wasm::WASM_SEC_FUNCTION);
643
644 encodeULEB128(Functions.size(), getStream());
645 for (const WasmFunction &Func : Functions)
646 encodeULEB128(Func.Type, getStream());
647
648 endSection(Section);
649}
650
Sam Cleggd99f6072017-06-12 23:52:44 +0000651void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000652 // For now, always emit the table section, since indirect calls are not
653 // valid without it. In the future, we could perhaps be more clever and omit
654 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000655
Sam Clegg9e15f352017-06-03 02:01:24 +0000656 SectionBookkeeping Section;
657 startSection(Section, wasm::WASM_SEC_TABLE);
658
Sam Cleggd99f6072017-06-12 23:52:44 +0000659 encodeULEB128(1, getStream()); // The number of tables.
660 // Fixed to 1 for now.
661 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
662 encodeULEB128(0, getStream()); // flags
663 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000664
665 endSection(Section);
666}
667
668void WasmObjectWriter::writeMemorySection(
669 const SmallVector<char, 0> &DataBytes) {
670 // For now, always emit the memory section, since loads and stores are not
671 // valid without it. In the future, we could perhaps be more clever and omit
672 // it if there are no loads or stores.
673 SectionBookkeeping Section;
674 uint32_t NumPages =
675 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
676
677 startSection(Section, wasm::WASM_SEC_MEMORY);
678 encodeULEB128(1, getStream()); // number of memory spaces
679
680 encodeULEB128(0, getStream()); // flags
681 encodeULEB128(NumPages, getStream()); // initial
682
683 endSection(Section);
684}
685
686void WasmObjectWriter::writeGlobalSection(
687 const SmallVector<WasmGlobal, 4> &Globals) {
688 if (Globals.empty())
689 return;
690
691 SectionBookkeeping Section;
692 startSection(Section, wasm::WASM_SEC_GLOBAL);
693
694 encodeULEB128(Globals.size(), getStream());
695 for (const WasmGlobal &Global : Globals) {
696 writeValueType(Global.Type);
697 write8(Global.IsMutable);
698
699 if (Global.HasImport) {
700 assert(Global.InitialValue == 0);
701 write8(wasm::WASM_OPCODE_GET_GLOBAL);
702 encodeULEB128(Global.ImportIndex, getStream());
703 } else {
704 assert(Global.ImportIndex == 0);
705 write8(wasm::WASM_OPCODE_I32_CONST);
706 encodeSLEB128(Global.InitialValue, getStream()); // offset
707 }
708 write8(wasm::WASM_OPCODE_END);
709 }
710
711 endSection(Section);
712}
713
714void WasmObjectWriter::writeExportSection(
715 const SmallVector<WasmExport, 4> &Exports) {
716 if (Exports.empty())
717 return;
718
719 SectionBookkeeping Section;
720 startSection(Section, wasm::WASM_SEC_EXPORT);
721
722 encodeULEB128(Exports.size(), getStream());
723 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000724 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000725 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000726 encodeULEB128(Export.Index, getStream());
727 }
728
729 endSection(Section);
730}
731
732void WasmObjectWriter::writeElemSection(
733 const SmallVector<uint32_t, 4> &TableElems) {
734 if (TableElems.empty())
735 return;
736
737 SectionBookkeeping Section;
738 startSection(Section, wasm::WASM_SEC_ELEM);
739
740 encodeULEB128(1, getStream()); // number of "segments"
741 encodeULEB128(0, getStream()); // the table index
742
743 // init expr for starting offset
744 write8(wasm::WASM_OPCODE_I32_CONST);
745 encodeSLEB128(0, getStream());
746 write8(wasm::WASM_OPCODE_END);
747
748 encodeULEB128(TableElems.size(), getStream());
749 for (uint32_t Elem : TableElems)
750 encodeULEB128(Elem, getStream());
751
752 endSection(Section);
753}
754
755void WasmObjectWriter::writeCodeSection(
756 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000757 const SmallVector<WasmFunction, 4> &Functions) {
758 if (Functions.empty())
759 return;
760
761 SectionBookkeeping Section;
762 startSection(Section, wasm::WASM_SEC_CODE);
763
764 encodeULEB128(Functions.size(), getStream());
765
766 for (const WasmFunction &Func : Functions) {
767 MCSectionWasm &FuncSection =
768 static_cast<MCSectionWasm &>(Func.Sym->getSection());
769
Sam Clegg9e15f352017-06-03 02:01:24 +0000770 int64_t Size = 0;
771 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
772 report_fatal_error(".size expression must be evaluatable");
773
774 encodeULEB128(Size, getStream());
775
776 FuncSection.setSectionOffset(getStream().tell() -
777 Section.ContentsOffset);
778
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
788uint64_t WasmObjectWriter::writeDataSection(
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000789 const SmallVector<char, 0> &DataBytes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000790 if (DataBytes.empty())
791 return 0;
792
793 SectionBookkeeping Section;
794 startSection(Section, wasm::WASM_SEC_DATA);
795
796 encodeULEB128(1, getStream()); // count
797 encodeULEB128(0, getStream()); // memory index
798 write8(wasm::WASM_OPCODE_I32_CONST);
799 encodeSLEB128(0, getStream()); // offset
800 write8(wasm::WASM_OPCODE_END);
801 encodeULEB128(DataBytes.size(), getStream()); // size
802 uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
803 writeBytes(DataBytes); // data
804
805 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000806 applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000807
808 endSection(Section);
809 return HeaderSize;
810}
811
812void WasmObjectWriter::writeNameSection(
813 const SmallVector<WasmFunction, 4> &Functions,
814 const SmallVector<WasmImport, 4> &Imports,
815 unsigned NumFuncImports) {
816 uint32_t TotalFunctions = NumFuncImports + Functions.size();
817 if (TotalFunctions == 0)
818 return;
819
820 SectionBookkeeping Section;
821 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
822 SectionBookkeeping SubSection;
823 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
824
825 encodeULEB128(TotalFunctions, getStream());
826 uint32_t Index = 0;
827 for (const WasmImport &Import : Imports) {
828 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
829 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000830 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000831 ++Index;
832 }
833 }
834 for (const WasmFunction &Func : Functions) {
835 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000836 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000837 ++Index;
838 }
839
840 endSection(SubSection);
841 endSection(Section);
842}
843
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000844void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000845 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
846 // for descriptions of the reloc sections.
847
848 if (CodeRelocations.empty())
849 return;
850
851 SectionBookkeeping Section;
852 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
853
854 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000855 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000856
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000857 writeRelocations(CodeRelocations, 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000858
859 endSection(Section);
860}
861
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000862void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000863 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
864 // for descriptions of the reloc sections.
865
866 if (DataRelocations.empty())
867 return;
868
869 SectionBookkeeping Section;
870 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
871
872 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
873 encodeULEB128(DataRelocations.size(), getStream());
874
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000875 writeRelocations(DataRelocations, DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
877 endSection(Section);
878}
879
880void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggb7787fd2017-06-20 04:04:59 +0000881 ArrayRef<StringRef> WeakSymbols, bool HasStackPointer,
882 uint32_t StackPointerGlobal) {
883 if (!HasStackPointer && WeakSymbols.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000884 return;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000885
Sam Clegg9e15f352017-06-03 02:01:24 +0000886 SectionBookkeeping Section;
887 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000888 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000889
Sam Cleggb7787fd2017-06-20 04:04:59 +0000890 if (HasStackPointer) {
891 startSection(SubSection, wasm::WASM_STACK_POINTER);
892 encodeULEB128(StackPointerGlobal, getStream()); // id
893 endSection(SubSection);
894 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000895
Sam Cleggb7787fd2017-06-20 04:04:59 +0000896 if (WeakSymbols.size() != 0) {
897 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
898 encodeULEB128(WeakSymbols.size(), getStream());
899 for (const StringRef Export: WeakSymbols) {
900 writeString(Export);
901 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
902 }
903 endSection(SubSection);
904 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000905
906 endSection(Section);
907}
908
Dan Gohman18eafb62017-02-22 01:23:18 +0000909void WasmObjectWriter::writeObject(MCAssembler &Asm,
910 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000911 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000912 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000913 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000914
915 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000916 SmallVector<WasmFunctionType, 4> FunctionTypes;
917 SmallVector<WasmFunction, 4> Functions;
918 SmallVector<uint32_t, 4> TableElems;
919 SmallVector<WasmGlobal, 4> Globals;
920 SmallVector<WasmImport, 4> Imports;
921 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000922 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000923 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
924 unsigned NumFuncImports = 0;
925 unsigned NumGlobalImports = 0;
926 SmallVector<char, 0> DataBytes;
Dan Gohman970d02c2017-03-30 23:58:19 +0000927 uint32_t StackPointerGlobal = 0;
928 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000929
930 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000931 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000932 switch (RelEntry.Type) {
933 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
934 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
935 IsAddressTaken.insert(RelEntry.Symbol);
936 break;
937 default:
938 break;
939 }
940 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000941 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000942 switch (RelEntry.Type) {
943 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
944 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
945 IsAddressTaken.insert(RelEntry.Symbol);
946 break;
947 default:
948 break;
949 }
950 }
951
952 // Populate the Imports set.
953 for (const MCSymbol &S : Asm.symbols()) {
954 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Derek Schuffb8795392017-03-16 20:49:48 +0000955 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000956
957 if (WS.isFunction()) {
958 // Prepare the function's type, if we haven't seen it yet.
959 WasmFunctionType F;
960 F.Returns = WS.getReturns();
961 F.Params = WS.getParams();
962 auto Pair =
963 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
964 if (Pair.second)
965 FunctionTypes.push_back(F);
966
967 Type = Pair.first->second;
968 } else {
Derek Schuffb8795392017-03-16 20:49:48 +0000969 Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +0000970 }
971
972 // If the symbol is not defined in this translation unit, import it.
973 if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
974 WasmImport Import;
975 Import.ModuleName = WS.getModuleName();
976 Import.FieldName = WS.getName();
977
978 if (WS.isFunction()) {
979 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
980 Import.Type = Type;
981 SymbolIndices[&WS] = NumFuncImports;
982 ++NumFuncImports;
983 } else {
984 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
985 Import.Type = Type;
986 SymbolIndices[&WS] = NumGlobalImports;
987 ++NumGlobalImports;
988 }
989
990 Imports.push_back(Import);
991 }
992 }
993
Dan Gohman82607f52017-02-24 23:46:05 +0000994 // In the special .global_variables section, we've encoded global
995 // variables used by the function. Translate them into the Globals
996 // list.
997 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
998 if (!GlobalVars->getFragmentList().empty()) {
999 if (GlobalVars->getFragmentList().size() != 1)
1000 report_fatal_error("only one .global_variables fragment supported");
1001 const MCFragment &Frag = *GlobalVars->begin();
1002 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1003 report_fatal_error("only data supported in .global_variables");
1004 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1005 if (!DataFrag.getFixups().empty())
1006 report_fatal_error("fixups not supported in .global_variables");
1007 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001008 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1009 *end = (const uint8_t *)Contents.data() + Contents.size();
1010 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001011 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001012 if (end - p < 3)
1013 report_fatal_error("truncated global variable encoding");
1014 G.Type = wasm::ValType(int8_t(*p++));
1015 G.IsMutable = bool(*p++);
1016 G.HasImport = bool(*p++);
1017 if (G.HasImport) {
1018 G.InitialValue = 0;
1019
1020 WasmImport Import;
1021 Import.ModuleName = (const char *)p;
1022 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1023 if (!nul)
1024 report_fatal_error("global module name must be nul-terminated");
1025 p = nul + 1;
1026 nul = (const uint8_t *)memchr(p, '\0', end - p);
1027 if (!nul)
1028 report_fatal_error("global base name must be nul-terminated");
1029 Import.FieldName = (const char *)p;
1030 p = nul + 1;
1031
1032 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1033 Import.Type = int32_t(G.Type);
1034
1035 G.ImportIndex = NumGlobalImports;
1036 ++NumGlobalImports;
1037
1038 Imports.push_back(Import);
1039 } else {
1040 unsigned n;
1041 G.InitialValue = decodeSLEB128(p, &n);
1042 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001043 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001044 report_fatal_error("global initial value must be valid SLEB128");
1045 p += n;
1046 }
Dan Gohman82607f52017-02-24 23:46:05 +00001047 Globals.push_back(G);
1048 }
1049 }
1050
Dan Gohman970d02c2017-03-30 23:58:19 +00001051 // In the special .stack_pointer section, we've encoded the stack pointer
1052 // index.
1053 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1054 if (!StackPtr->getFragmentList().empty()) {
1055 if (StackPtr->getFragmentList().size() != 1)
1056 report_fatal_error("only one .stack_pointer fragment supported");
1057 const MCFragment &Frag = *StackPtr->begin();
1058 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1059 report_fatal_error("only data supported in .stack_pointer");
1060 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1061 if (!DataFrag.getFixups().empty())
1062 report_fatal_error("fixups not supported in .stack_pointer");
1063 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1064 if (Contents.size() != 4)
1065 report_fatal_error("only one entry supported in .stack_pointer");
1066 HasStackPointer = true;
1067 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1068 }
1069
Sam Cleggb7787fd2017-06-20 04:04:59 +00001070 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001071 for (const MCSymbol &S : Asm.symbols()) {
1072 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1073 // or used in relocations.
1074 if (S.isTemporary() && S.getName().empty())
1075 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001076
1077 // Variable references (weak references) are handled in a second pass
1078 if (S.isVariable())
1079 continue;
1080
Dan Gohmand934cb82017-02-24 23:18:00 +00001081 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001082 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1083 << " isDefined=" << S.isDefined() << " isExternal="
1084 << S.isExternal() << " isTemporary=" << S.isTemporary()
1085 << " isFunction=" << WS.isFunction()
1086 << " isWeak=" << WS.isWeak()
1087 << " isVariable=" << WS.isVariable() << "\n");
1088
1089 if (WS.isWeak())
1090 WeakSymbols.push_back(WS.getName());
1091
Dan Gohmand934cb82017-02-24 23:18:00 +00001092 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001093
1094 //<< " function=" << S.isFunction()
1095
Dan Gohmand934cb82017-02-24 23:18:00 +00001096 if (WS.isFunction()) {
1097 // Prepare the function's type, if we haven't seen it yet.
1098 WasmFunctionType F;
1099 F.Returns = WS.getReturns();
1100 F.Params = WS.getParams();
1101 auto Pair =
1102 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1103 if (Pair.second)
1104 FunctionTypes.push_back(F);
1105
Derek Schuffb8795392017-03-16 20:49:48 +00001106 int32_t Type = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001107
1108 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001109 if (WS.getOffset() != 0)
1110 report_fatal_error(
1111 "function sections must contain one function each");
1112
1113 if (WS.getSize() == 0)
1114 report_fatal_error(
1115 "function symbols must have a size set with .size");
1116
Dan Gohmand934cb82017-02-24 23:18:00 +00001117 // A definition. Take the next available index.
1118 Index = NumFuncImports + Functions.size();
1119
1120 // Prepare the function.
1121 WasmFunction Func;
1122 Func.Type = Type;
1123 Func.Sym = &WS;
1124 SymbolIndices[&WS] = Index;
1125 Functions.push_back(Func);
1126 } else {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001127 // Should be no such thing as weak undefined symbol
1128 assert(!WS.isVariable());
1129
Dan Gohmand934cb82017-02-24 23:18:00 +00001130 // An import; the index was assigned above.
1131 Index = SymbolIndices.find(&WS)->second;
1132 }
1133
1134 // If needed, prepare the function to be called indirectly.
Sam Cleggd99f6072017-06-12 23:52:44 +00001135 if (IsAddressTaken.count(&WS)) {
1136 IndirectSymbolIndices[&WS] = TableElems.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001137 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001138 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001139 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001140 if (WS.isTemporary() && !WS.getSize())
1141 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001142
Sam Cleggb7787fd2017-06-20 04:04:59 +00001143 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001144 if (WS.getOffset() != 0)
1145 report_fatal_error("data sections must contain one variable each: " +
1146 WS.getName());
1147 if (!WS.getSize())
1148 report_fatal_error("data symbols must have a size set with .size: " +
1149 WS.getName());
1150
1151 int64_t Size = 0;
1152 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1153 report_fatal_error(".size expression must be evaluatable");
1154
Dan Gohmand934cb82017-02-24 23:18:00 +00001155 MCSectionWasm &DataSection =
1156 static_cast<MCSectionWasm &>(WS.getSection());
1157
1158 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1159 report_fatal_error("data sections must contain at most one variable");
1160
1161 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1162
1163 DataSection.setSectionOffset(DataBytes.size());
1164
1165 for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
1166 I != E; ++I) {
1167 const MCFragment &Frag = *I;
1168 if (Frag.hasInstructions())
1169 report_fatal_error("only data supported in data sections");
1170
1171 if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1172 if (Align->getValueSize() != 1)
1173 report_fatal_error("only byte values supported for alignment");
1174 // If nops are requested, use zeros, as this is the data section.
1175 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1176 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1177 Align->getAlignment()),
1178 DataBytes.size() +
1179 Align->getMaxBytesToEmit());
1180 DataBytes.resize(Size, Value);
1181 } else if (const MCFillFragment *Fill =
1182 dyn_cast<MCFillFragment>(&Frag)) {
1183 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1184 } else {
1185 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1186 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1187
1188 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1189 }
1190 }
1191
Sam Clegg1c154a62017-05-25 21:08:07 +00001192 // For each global, prepare a corresponding wasm global holding its
1193 // address. For externals these will also be named exports.
1194 Index = NumGlobalImports + Globals.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001195
Sam Clegg1c154a62017-05-25 21:08:07 +00001196 WasmGlobal Global;
1197 Global.Type = PtrType;
1198 Global.IsMutable = false;
1199 Global.HasImport = false;
1200 Global.InitialValue = DataSection.getSectionOffset();
1201 Global.ImportIndex = 0;
1202 SymbolIndices[&WS] = Index;
1203 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001204 }
1205 }
1206
1207 // If the symbol is visible outside this translation unit, export it.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001208 if (WS.isExternal() && WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001209 WasmExport Export;
1210 Export.FieldName = WS.getName();
1211 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001212 if (WS.isFunction())
1213 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1214 else
1215 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Dan Gohmand934cb82017-02-24 23:18:00 +00001216 Exports.push_back(Export);
1217 }
1218 }
1219
Sam Cleggb7787fd2017-06-20 04:04:59 +00001220 // Handle weak aliases
1221 for (const MCSymbol &S : Asm.symbols()) {
1222 if (!S.isVariable())
1223 continue;
1224 assert(S.isExternal());
1225 assert(S.isDefined(/*SetUsed=*/false));
1226
1227 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1228
1229 // Find the target symbol of this weak alias
1230 const MCExpr *Expr = WS.getVariableValue();
1231 auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
1232 const MCSymbolWasm *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
1233 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1234 DEBUG(dbgs() << "Weak alias: '" << WS << "' -> '" << ResolvedSym << "' = " << Index << "\n");
1235 SymbolIndices[&WS] = Index;
1236
1237 WasmExport Export;
1238 Export.FieldName = WS.getName();
1239 Export.Index = Index;
1240 if (WS.isFunction())
1241 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1242 else
1243 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1244 WeakSymbols.push_back(Export.FieldName);
1245 Exports.push_back(Export);
1246 }
1247
Dan Gohmand934cb82017-02-24 23:18:00 +00001248 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001249 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1250 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1251 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001252
Dan Gohmand934cb82017-02-24 23:18:00 +00001253 WasmFunctionType F;
1254 F.Returns = Fixup.Symbol->getReturns();
1255 F.Params = Fixup.Symbol->getParams();
1256 auto Pair =
1257 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1258 if (Pair.second)
1259 FunctionTypes.push_back(F);
1260
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001261 TypeIndices[Fixup.Symbol] = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001262 }
1263
Dan Gohman18eafb62017-02-22 01:23:18 +00001264 // Write out the Wasm header.
1265 writeHeader(Asm);
1266
Sam Clegg9e15f352017-06-03 02:01:24 +00001267 writeTypeSection(FunctionTypes);
1268 writeImportSection(Imports);
1269 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001270 writeTableSection(TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001271 writeMemorySection(DataBytes);
1272 writeGlobalSection(Globals);
1273 writeExportSection(Exports);
1274 // TODO: Start Section
1275 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001276 writeCodeSection(Asm, Layout, Functions);
1277 uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +00001278 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001279 writeCodeRelocSection();
1280 writeDataRelocSection(DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001281 writeLinkingMetaDataSection(WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001282
Dan Gohmand934cb82017-02-24 23:18:00 +00001283 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001284 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001285}
1286
1287MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1288 raw_pwrite_stream &OS) {
1289 return new WasmObjectWriter(MOTW, OS);
1290}