blob: 292c5bac1c607d0663951e2494cbb4116009f6d5 [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 Clegg1fb8daa2017-06-20 05:05:10 +0000165#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000166raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000167 Rel.print(OS);
168 return OS;
169}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000170#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171
Dan Gohman18eafb62017-02-22 01:23:18 +0000172class WasmObjectWriter : public MCObjectWriter {
173 /// Helper struct for containing some precomputed information on symbols.
174 struct WasmSymbolData {
175 const MCSymbolWasm *Symbol;
176 StringRef Name;
177
178 // Support lexicographic sorting.
179 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
180 };
181
182 /// The target specific Wasm writer instance.
183 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
184
Dan Gohmand934cb82017-02-24 23:18:00 +0000185 // Relocations for fixing up references in the code section.
186 std::vector<WasmRelocationEntry> CodeRelocations;
187
188 // Relocations for fixing up references in the data section.
189 std::vector<WasmRelocationEntry> DataRelocations;
190
Dan Gohmand934cb82017-02-24 23:18:00 +0000191 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000192 // Maps function symbols to the index of the type of the function
193 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000194 // Maps function symbols to the table element index space. Used
195 // for TABLE_INDEX relocation types (i.e. address taken functions).
196 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
197 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000198 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
199
200 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
201 FunctionTypeIndices;
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();
227 MCObjectWriter::reset();
228 }
229
Dan Gohman18eafb62017-02-22 01:23:18 +0000230 void writeHeader(const MCAssembler &Asm);
231
232 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
233 const MCFragment *Fragment, const MCFixup &Fixup,
234 MCValue Target, bool &IsPCRel,
235 uint64_t &FixedValue) override;
236
237 void executePostLayoutBinding(MCAssembler &Asm,
238 const MCAsmLayout &Layout) override;
239
240 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000241
Sam Cleggb7787fd2017-06-20 04:04:59 +0000242 void writeString(const StringRef Str) {
243 encodeULEB128(Str.size(), getStream());
244 writeBytes(Str);
245 }
246
Sam Clegg9e15f352017-06-03 02:01:24 +0000247 void writeValueType(wasm::ValType Ty) {
248 encodeSLEB128(int32_t(Ty), getStream());
249 }
250
251 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
252 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
253 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000254 void writeTableSection(uint32_t NumElements);
Sam Clegg9e15f352017-06-03 02:01:24 +0000255 void writeMemorySection(const SmallVector<char, 0> &DataBytes);
256 void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
257 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
258 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
259 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000260 const SmallVector<WasmFunction, 4> &Functions);
261 uint64_t
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000262 writeDataSection(const SmallVector<char, 0> &DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +0000263 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
264 const SmallVector<WasmImport, 4> &Imports,
265 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000266 void writeCodeRelocSection();
267 void writeDataRelocSection(uint64_t DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000268 void writeLinkingMetaDataSection(ArrayRef<StringRef> WeakSymbols,
269 bool HasStackPointer,
Sam Clegg9e15f352017-06-03 02:01:24 +0000270 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000271
272 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
273 uint64_t ContentsOffset);
274
275 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
276 uint64_t HeaderSize);
277 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Dan Gohman18eafb62017-02-22 01:23:18 +0000278};
Sam Clegg9e15f352017-06-03 02:01:24 +0000279
Dan Gohman18eafb62017-02-22 01:23:18 +0000280} // end anonymous namespace
281
282WasmObjectWriter::~WasmObjectWriter() {}
283
Dan Gohmand934cb82017-02-24 23:18:00 +0000284// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
285static unsigned PaddingFor5ByteULEB128(uint32_t X) {
286 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
287}
288
289// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
290static unsigned PaddingFor5ByteSLEB128(int32_t X) {
291 return 5 - getSLEB128Size(X);
292}
293
294// Write out a section header and a patchable section size field.
295void WasmObjectWriter::startSection(SectionBookkeeping &Section,
296 unsigned SectionId,
297 const char *Name) {
298 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
299 "Only custom sections can have names");
300
Sam Cleggb7787fd2017-06-20 04:04:59 +0000301 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000302 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000303
304 Section.SizeOffset = getStream().tell();
305
306 // The section size. We don't know the size yet, so reserve enough space
307 // for any 32-bit value; we'll patch it later.
308 encodeULEB128(UINT32_MAX, getStream());
309
310 // The position where the section starts, for measuring its size.
311 Section.ContentsOffset = getStream().tell();
312
313 // Custom sections in wasm also have a string identifier.
314 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000315 assert(Name);
316 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000317 }
318}
319
320// Now that the section is complete and we know how big it is, patch up the
321// section size field at the start of the section.
322void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
323 uint64_t Size = getStream().tell() - Section.ContentsOffset;
324 if (uint32_t(Size) != Size)
325 report_fatal_error("section size does not fit in a uint32_t");
326
Sam Cleggb7787fd2017-06-20 04:04:59 +0000327 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000328 unsigned Padding = PaddingFor5ByteULEB128(Size);
329
330 // Write the final section size to the payload_len field, which follows
331 // the section id byte.
332 uint8_t Buffer[16];
333 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
334 assert(SizeLen == 5);
335 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
336}
337
Dan Gohman18eafb62017-02-22 01:23:18 +0000338// Emit the Wasm header.
339void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000340 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
341 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000342}
343
344void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
345 const MCAsmLayout &Layout) {
346}
347
348void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
349 const MCAsmLayout &Layout,
350 const MCFragment *Fragment,
351 const MCFixup &Fixup, MCValue Target,
352 bool &IsPCRel, uint64_t &FixedValue) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000353 MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
354 uint64_t C = Target.getConstant();
355 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
356 MCContext &Ctx = Asm.getContext();
357
358 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
359 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
360 "Should not have constructed this");
361
362 // Let A, B and C being the components of Target and R be the location of
363 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
364 // If it is pcrel, we want to compute (A - B + C - R).
365
366 // In general, Wasm has no relocations for -B. It can only represent (A + C)
367 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
368 // replace B to implement it: (A - R - K + C)
369 if (IsPCRel) {
370 Ctx.reportError(
371 Fixup.getLoc(),
372 "No relocation available to represent this relative expression");
373 return;
374 }
375
376 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
377
378 if (SymB.isUndefined()) {
379 Ctx.reportError(Fixup.getLoc(),
380 Twine("symbol '") + SymB.getName() +
381 "' can not be undefined in a subtraction expression");
382 return;
383 }
384
385 assert(!SymB.isAbsolute() && "Should have been folded");
386 const MCSection &SecB = SymB.getSection();
387 if (&SecB != &FixupSection) {
388 Ctx.reportError(Fixup.getLoc(),
389 "Cannot represent a difference across sections");
390 return;
391 }
392
393 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
394 uint64_t K = SymBOffset - FixupOffset;
395 IsPCRel = true;
396 C -= K;
397 }
398
399 // We either rejected the fixup or folded B into C at this point.
400 const MCSymbolRefExpr *RefA = Target.getSymA();
401 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
402
403 bool ViaWeakRef = false;
404 if (SymA && SymA->isVariable()) {
405 const MCExpr *Expr = SymA->getVariableValue();
406 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
407 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
408 SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
409 ViaWeakRef = true;
410 }
411 }
412 }
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
419 if (SymA) {
420 if (ViaWeakRef)
421 llvm_unreachable("weakref used in reloc not yet implemented");
422 else
423 SymA->setUsedInReloc();
424 }
425
Sam Cleggae03c1e72017-06-13 18:51:50 +0000426 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000427 assert(SymA);
428
Sam Cleggae03c1e72017-06-13 18:51:50 +0000429 unsigned Type = getRelocType(Target, Fixup);
430
Dan Gohmand934cb82017-02-24 23:18:00 +0000431 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000432 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000433
434 if (FixupSection.hasInstructions())
435 CodeRelocations.push_back(Rec);
436 else
437 DataRelocations.push_back(Rec);
438}
439
Dan Gohmand934cb82017-02-24 23:18:00 +0000440// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
441// to allow patching.
442static void
443WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
444 uint8_t Buffer[5];
445 unsigned Padding = PaddingFor5ByteULEB128(X);
446 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
447 assert(SizeLen == 5);
448 Stream.pwrite((char *)Buffer, SizeLen, Offset);
449}
450
451// Write X as an signed LEB value at offset Offset in Stream, padded
452// to allow patching.
453static void
454WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
455 uint8_t Buffer[5];
456 unsigned Padding = PaddingFor5ByteSLEB128(X);
457 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
458 assert(SizeLen == 5);
459 Stream.pwrite((char *)Buffer, SizeLen, Offset);
460}
461
462// Write X as a plain integer value at offset Offset in Stream.
463static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
464 uint8_t Buffer[4];
465 support::endian::write32le(Buffer, X);
466 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
467}
468
469// Compute a value to write into the code at the location covered
470// by RelEntry. This value isn't used by the static linker, since
471// we have addends; it just serves to make the code more readable
472// and to make standalone wasm modules directly usable.
473static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
474 const MCSymbolWasm *Sym = RelEntry.Symbol;
475
476 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000477 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000478 return UINT32_MAX;
479
480 MCSectionWasm &Section =
481 cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
482 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
483
484 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
485 uint32_t Value = Address;
486
487 return Value;
488}
489
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000490uint32_t WasmObjectWriter::getRelocationIndexValue(
491 const WasmRelocationEntry &RelEntry) {
492 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000493 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
494 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000495 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
496 report_fatal_error("symbol not found table index space:" +
497 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000498 return IndirectSymbolIndices[RelEntry.Symbol];
499 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000500 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000501 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
502 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
503 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000504 if (!SymbolIndices.count(RelEntry.Symbol))
505 report_fatal_error("symbol not found function/global index space:" +
506 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000507 return SymbolIndices[RelEntry.Symbol];
508 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000509 if (!TypeIndices.count(RelEntry.Symbol))
510 report_fatal_error("symbol not found in type index space:" +
511 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000512 return TypeIndices[RelEntry.Symbol];
513 default:
514 llvm_unreachable("invalid relocation type");
515 }
516}
517
Dan Gohmand934cb82017-02-24 23:18:00 +0000518// Apply the portions of the relocation records that we can handle ourselves
519// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000520void WasmObjectWriter::applyRelocations(
521 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
522 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000523 for (const WasmRelocationEntry &RelEntry : Relocations) {
524 uint64_t Offset = ContentsOffset +
525 RelEntry.FixupSection->getSectionOffset() +
526 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000527
Sam Cleggb7787fd2017-06-20 04:04:59 +0000528 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000529 switch (RelEntry.Type) {
530 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
531 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000532 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
533 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000534 uint32_t Index = getRelocationIndexValue(RelEntry);
535 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000536 break;
537 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000538 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
539 uint32_t Index = getRelocationIndexValue(RelEntry);
540 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000541 break;
542 }
543 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
544 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000545 WritePatchableSLEB(Stream, Value, Offset);
546 break;
547 }
548 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
549 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000550 WritePatchableLEB(Stream, Value, Offset);
551 break;
552 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000553 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
554 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000555 WriteI32(Stream, Value, Offset);
556 break;
557 }
558 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000559 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000560 }
561 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000562}
563
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000564// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000565// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000566void WasmObjectWriter::writeRelocations(
567 ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
568 raw_pwrite_stream &Stream = getStream();
569 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000570
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000571 uint64_t Offset = RelEntry.Offset +
572 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
573 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000574
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000575 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000576 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000577 encodeULEB128(Index, Stream);
578 if (RelEntry.hasAddend())
579 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000580 }
581}
582
Sam Clegg9e15f352017-06-03 02:01:24 +0000583void WasmObjectWriter::writeTypeSection(
584 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
585 if (FunctionTypes.empty())
586 return;
587
588 SectionBookkeeping Section;
589 startSection(Section, wasm::WASM_SEC_TYPE);
590
591 encodeULEB128(FunctionTypes.size(), getStream());
592
593 for (const WasmFunctionType &FuncTy : FunctionTypes) {
594 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
595 encodeULEB128(FuncTy.Params.size(), getStream());
596 for (wasm::ValType Ty : FuncTy.Params)
597 writeValueType(Ty);
598 encodeULEB128(FuncTy.Returns.size(), getStream());
599 for (wasm::ValType Ty : FuncTy.Returns)
600 writeValueType(Ty);
601 }
602
603 endSection(Section);
604}
605
Sam Cleggb7787fd2017-06-20 04:04:59 +0000606
Sam Clegg9e15f352017-06-03 02:01:24 +0000607void WasmObjectWriter::writeImportSection(
608 const SmallVector<WasmImport, 4> &Imports) {
609 if (Imports.empty())
610 return;
611
612 SectionBookkeeping Section;
613 startSection(Section, wasm::WASM_SEC_IMPORT);
614
615 encodeULEB128(Imports.size(), getStream());
616 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000617 writeString(Import.ModuleName);
618 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000619
620 encodeULEB128(Import.Kind, getStream());
621
622 switch (Import.Kind) {
623 case wasm::WASM_EXTERNAL_FUNCTION:
624 encodeULEB128(Import.Type, getStream());
625 break;
626 case wasm::WASM_EXTERNAL_GLOBAL:
627 encodeSLEB128(int32_t(Import.Type), getStream());
628 encodeULEB128(0, getStream()); // mutability
629 break;
630 default:
631 llvm_unreachable("unsupported import kind");
632 }
633 }
634
635 endSection(Section);
636}
637
638void WasmObjectWriter::writeFunctionSection(
639 const SmallVector<WasmFunction, 4> &Functions) {
640 if (Functions.empty())
641 return;
642
643 SectionBookkeeping Section;
644 startSection(Section, wasm::WASM_SEC_FUNCTION);
645
646 encodeULEB128(Functions.size(), getStream());
647 for (const WasmFunction &Func : Functions)
648 encodeULEB128(Func.Type, getStream());
649
650 endSection(Section);
651}
652
Sam Cleggd99f6072017-06-12 23:52:44 +0000653void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000654 // For now, always emit the table section, since indirect calls are not
655 // valid without it. In the future, we could perhaps be more clever and omit
656 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000657
Sam Clegg9e15f352017-06-03 02:01:24 +0000658 SectionBookkeeping Section;
659 startSection(Section, wasm::WASM_SEC_TABLE);
660
Sam Cleggd99f6072017-06-12 23:52:44 +0000661 encodeULEB128(1, getStream()); // The number of tables.
662 // Fixed to 1 for now.
663 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
664 encodeULEB128(0, getStream()); // flags
665 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000666
667 endSection(Section);
668}
669
670void WasmObjectWriter::writeMemorySection(
671 const SmallVector<char, 0> &DataBytes) {
672 // For now, always emit the memory section, since loads and stores are not
673 // valid without it. In the future, we could perhaps be more clever and omit
674 // it if there are no loads or stores.
675 SectionBookkeeping Section;
676 uint32_t NumPages =
677 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
678
679 startSection(Section, wasm::WASM_SEC_MEMORY);
680 encodeULEB128(1, getStream()); // number of memory spaces
681
682 encodeULEB128(0, getStream()); // flags
683 encodeULEB128(NumPages, getStream()); // initial
684
685 endSection(Section);
686}
687
688void WasmObjectWriter::writeGlobalSection(
689 const SmallVector<WasmGlobal, 4> &Globals) {
690 if (Globals.empty())
691 return;
692
693 SectionBookkeeping Section;
694 startSection(Section, wasm::WASM_SEC_GLOBAL);
695
696 encodeULEB128(Globals.size(), getStream());
697 for (const WasmGlobal &Global : Globals) {
698 writeValueType(Global.Type);
699 write8(Global.IsMutable);
700
701 if (Global.HasImport) {
702 assert(Global.InitialValue == 0);
703 write8(wasm::WASM_OPCODE_GET_GLOBAL);
704 encodeULEB128(Global.ImportIndex, getStream());
705 } else {
706 assert(Global.ImportIndex == 0);
707 write8(wasm::WASM_OPCODE_I32_CONST);
708 encodeSLEB128(Global.InitialValue, getStream()); // offset
709 }
710 write8(wasm::WASM_OPCODE_END);
711 }
712
713 endSection(Section);
714}
715
716void WasmObjectWriter::writeExportSection(
717 const SmallVector<WasmExport, 4> &Exports) {
718 if (Exports.empty())
719 return;
720
721 SectionBookkeeping Section;
722 startSection(Section, wasm::WASM_SEC_EXPORT);
723
724 encodeULEB128(Exports.size(), getStream());
725 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000726 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000727 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000728 encodeULEB128(Export.Index, getStream());
729 }
730
731 endSection(Section);
732}
733
734void WasmObjectWriter::writeElemSection(
735 const SmallVector<uint32_t, 4> &TableElems) {
736 if (TableElems.empty())
737 return;
738
739 SectionBookkeeping Section;
740 startSection(Section, wasm::WASM_SEC_ELEM);
741
742 encodeULEB128(1, getStream()); // number of "segments"
743 encodeULEB128(0, getStream()); // the table index
744
745 // init expr for starting offset
746 write8(wasm::WASM_OPCODE_I32_CONST);
747 encodeSLEB128(0, getStream());
748 write8(wasm::WASM_OPCODE_END);
749
750 encodeULEB128(TableElems.size(), getStream());
751 for (uint32_t Elem : TableElems)
752 encodeULEB128(Elem, getStream());
753
754 endSection(Section);
755}
756
757void WasmObjectWriter::writeCodeSection(
758 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000759 const SmallVector<WasmFunction, 4> &Functions) {
760 if (Functions.empty())
761 return;
762
763 SectionBookkeeping Section;
764 startSection(Section, wasm::WASM_SEC_CODE);
765
766 encodeULEB128(Functions.size(), getStream());
767
768 for (const WasmFunction &Func : Functions) {
769 MCSectionWasm &FuncSection =
770 static_cast<MCSectionWasm &>(Func.Sym->getSection());
771
Sam Clegg9e15f352017-06-03 02:01:24 +0000772 int64_t Size = 0;
773 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
774 report_fatal_error(".size expression must be evaluatable");
775
776 encodeULEB128(Size, getStream());
777
778 FuncSection.setSectionOffset(getStream().tell() -
779 Section.ContentsOffset);
780
781 Asm.writeSectionData(&FuncSection, Layout);
782 }
783
Sam Clegg9e15f352017-06-03 02:01:24 +0000784 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000785 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786
787 endSection(Section);
788}
789
790uint64_t WasmObjectWriter::writeDataSection(
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000791 const SmallVector<char, 0> &DataBytes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000792 if (DataBytes.empty())
793 return 0;
794
795 SectionBookkeeping Section;
796 startSection(Section, wasm::WASM_SEC_DATA);
797
798 encodeULEB128(1, getStream()); // count
799 encodeULEB128(0, getStream()); // memory index
800 write8(wasm::WASM_OPCODE_I32_CONST);
801 encodeSLEB128(0, getStream()); // offset
802 write8(wasm::WASM_OPCODE_END);
803 encodeULEB128(DataBytes.size(), getStream()); // size
804 uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
805 writeBytes(DataBytes); // data
806
807 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000808 applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000809
810 endSection(Section);
811 return HeaderSize;
812}
813
814void WasmObjectWriter::writeNameSection(
815 const SmallVector<WasmFunction, 4> &Functions,
816 const SmallVector<WasmImport, 4> &Imports,
817 unsigned NumFuncImports) {
818 uint32_t TotalFunctions = NumFuncImports + Functions.size();
819 if (TotalFunctions == 0)
820 return;
821
822 SectionBookkeeping Section;
823 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
824 SectionBookkeeping SubSection;
825 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
826
827 encodeULEB128(TotalFunctions, getStream());
828 uint32_t Index = 0;
829 for (const WasmImport &Import : Imports) {
830 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
831 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000832 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000833 ++Index;
834 }
835 }
836 for (const WasmFunction &Func : Functions) {
837 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000838 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000839 ++Index;
840 }
841
842 endSection(SubSection);
843 endSection(Section);
844}
845
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000846void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000847 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
848 // for descriptions of the reloc sections.
849
850 if (CodeRelocations.empty())
851 return;
852
853 SectionBookkeeping Section;
854 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
855
856 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000857 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000858
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000859 writeRelocations(CodeRelocations, 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000860
861 endSection(Section);
862}
863
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000864void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000865 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
866 // for descriptions of the reloc sections.
867
868 if (DataRelocations.empty())
869 return;
870
871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
873
874 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
875 encodeULEB128(DataRelocations.size(), getStream());
876
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000877 writeRelocations(DataRelocations, DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000878
879 endSection(Section);
880}
881
882void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggb7787fd2017-06-20 04:04:59 +0000883 ArrayRef<StringRef> WeakSymbols, bool HasStackPointer,
884 uint32_t StackPointerGlobal) {
885 if (!HasStackPointer && WeakSymbols.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000886 return;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000887
Sam Clegg9e15f352017-06-03 02:01:24 +0000888 SectionBookkeeping Section;
889 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000890 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000891
Sam Cleggb7787fd2017-06-20 04:04:59 +0000892 if (HasStackPointer) {
893 startSection(SubSection, wasm::WASM_STACK_POINTER);
894 encodeULEB128(StackPointerGlobal, getStream()); // id
895 endSection(SubSection);
896 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000897
Sam Cleggb7787fd2017-06-20 04:04:59 +0000898 if (WeakSymbols.size() != 0) {
899 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
900 encodeULEB128(WeakSymbols.size(), getStream());
901 for (const StringRef Export: WeakSymbols) {
902 writeString(Export);
903 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
904 }
905 endSection(SubSection);
906 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000907
908 endSection(Section);
909}
910
Dan Gohman18eafb62017-02-22 01:23:18 +0000911void WasmObjectWriter::writeObject(MCAssembler &Asm,
912 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000913 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000914 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000915 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000916
917 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000918 SmallVector<WasmFunctionType, 4> FunctionTypes;
919 SmallVector<WasmFunction, 4> Functions;
920 SmallVector<uint32_t, 4> TableElems;
921 SmallVector<WasmGlobal, 4> Globals;
922 SmallVector<WasmImport, 4> Imports;
923 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000924 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000925 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
926 unsigned NumFuncImports = 0;
927 unsigned NumGlobalImports = 0;
928 SmallVector<char, 0> DataBytes;
Dan Gohman970d02c2017-03-30 23:58:19 +0000929 uint32_t StackPointerGlobal = 0;
930 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000931
932 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000933 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000934 switch (RelEntry.Type) {
935 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
936 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
937 IsAddressTaken.insert(RelEntry.Symbol);
938 break;
939 default:
940 break;
941 }
942 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000943 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000944 switch (RelEntry.Type) {
945 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
946 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
947 IsAddressTaken.insert(RelEntry.Symbol);
948 break;
949 default:
950 break;
951 }
952 }
953
954 // Populate the Imports set.
955 for (const MCSymbol &S : Asm.symbols()) {
956 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Derek Schuffb8795392017-03-16 20:49:48 +0000957 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000958
959 if (WS.isFunction()) {
960 // Prepare the function's type, if we haven't seen it yet.
961 WasmFunctionType F;
962 F.Returns = WS.getReturns();
963 F.Params = WS.getParams();
964 auto Pair =
965 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
966 if (Pair.second)
967 FunctionTypes.push_back(F);
968
969 Type = Pair.first->second;
970 } else {
Derek Schuffb8795392017-03-16 20:49:48 +0000971 Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +0000972 }
973
974 // If the symbol is not defined in this translation unit, import it.
975 if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
976 WasmImport Import;
977 Import.ModuleName = WS.getModuleName();
978 Import.FieldName = WS.getName();
979
980 if (WS.isFunction()) {
981 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
982 Import.Type = Type;
983 SymbolIndices[&WS] = NumFuncImports;
984 ++NumFuncImports;
985 } else {
986 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
987 Import.Type = Type;
988 SymbolIndices[&WS] = NumGlobalImports;
989 ++NumGlobalImports;
990 }
991
992 Imports.push_back(Import);
993 }
994 }
995
Dan Gohman82607f52017-02-24 23:46:05 +0000996 // In the special .global_variables section, we've encoded global
997 // variables used by the function. Translate them into the Globals
998 // list.
999 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
1000 if (!GlobalVars->getFragmentList().empty()) {
1001 if (GlobalVars->getFragmentList().size() != 1)
1002 report_fatal_error("only one .global_variables fragment supported");
1003 const MCFragment &Frag = *GlobalVars->begin();
1004 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1005 report_fatal_error("only data supported in .global_variables");
1006 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1007 if (!DataFrag.getFixups().empty())
1008 report_fatal_error("fixups not supported in .global_variables");
1009 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001010 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1011 *end = (const uint8_t *)Contents.data() + Contents.size();
1012 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001013 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001014 if (end - p < 3)
1015 report_fatal_error("truncated global variable encoding");
1016 G.Type = wasm::ValType(int8_t(*p++));
1017 G.IsMutable = bool(*p++);
1018 G.HasImport = bool(*p++);
1019 if (G.HasImport) {
1020 G.InitialValue = 0;
1021
1022 WasmImport Import;
1023 Import.ModuleName = (const char *)p;
1024 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1025 if (!nul)
1026 report_fatal_error("global module name must be nul-terminated");
1027 p = nul + 1;
1028 nul = (const uint8_t *)memchr(p, '\0', end - p);
1029 if (!nul)
1030 report_fatal_error("global base name must be nul-terminated");
1031 Import.FieldName = (const char *)p;
1032 p = nul + 1;
1033
1034 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1035 Import.Type = int32_t(G.Type);
1036
1037 G.ImportIndex = NumGlobalImports;
1038 ++NumGlobalImports;
1039
1040 Imports.push_back(Import);
1041 } else {
1042 unsigned n;
1043 G.InitialValue = decodeSLEB128(p, &n);
1044 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001045 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001046 report_fatal_error("global initial value must be valid SLEB128");
1047 p += n;
1048 }
Dan Gohman82607f52017-02-24 23:46:05 +00001049 Globals.push_back(G);
1050 }
1051 }
1052
Dan Gohman970d02c2017-03-30 23:58:19 +00001053 // In the special .stack_pointer section, we've encoded the stack pointer
1054 // index.
1055 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1056 if (!StackPtr->getFragmentList().empty()) {
1057 if (StackPtr->getFragmentList().size() != 1)
1058 report_fatal_error("only one .stack_pointer fragment supported");
1059 const MCFragment &Frag = *StackPtr->begin();
1060 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1061 report_fatal_error("only data supported in .stack_pointer");
1062 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1063 if (!DataFrag.getFixups().empty())
1064 report_fatal_error("fixups not supported in .stack_pointer");
1065 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1066 if (Contents.size() != 4)
1067 report_fatal_error("only one entry supported in .stack_pointer");
1068 HasStackPointer = true;
1069 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1070 }
1071
Sam Cleggb7787fd2017-06-20 04:04:59 +00001072 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001073 for (const MCSymbol &S : Asm.symbols()) {
1074 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1075 // or used in relocations.
1076 if (S.isTemporary() && S.getName().empty())
1077 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001078
1079 // Variable references (weak references) are handled in a second pass
1080 if (S.isVariable())
1081 continue;
1082
Dan Gohmand934cb82017-02-24 23:18:00 +00001083 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001084 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1085 << " isDefined=" << S.isDefined() << " isExternal="
1086 << S.isExternal() << " isTemporary=" << S.isTemporary()
1087 << " isFunction=" << WS.isFunction()
1088 << " isWeak=" << WS.isWeak()
1089 << " isVariable=" << WS.isVariable() << "\n");
1090
1091 if (WS.isWeak())
1092 WeakSymbols.push_back(WS.getName());
1093
Dan Gohmand934cb82017-02-24 23:18:00 +00001094 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001095
1096 //<< " function=" << S.isFunction()
1097
Dan Gohmand934cb82017-02-24 23:18:00 +00001098 if (WS.isFunction()) {
1099 // Prepare the function's type, if we haven't seen it yet.
1100 WasmFunctionType F;
1101 F.Returns = WS.getReturns();
1102 F.Params = WS.getParams();
1103 auto Pair =
1104 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1105 if (Pair.second)
1106 FunctionTypes.push_back(F);
1107
Derek Schuffb8795392017-03-16 20:49:48 +00001108 int32_t Type = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001109
1110 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001111 if (WS.getOffset() != 0)
1112 report_fatal_error(
1113 "function sections must contain one function each");
1114
1115 if (WS.getSize() == 0)
1116 report_fatal_error(
1117 "function symbols must have a size set with .size");
1118
Dan Gohmand934cb82017-02-24 23:18:00 +00001119 // A definition. Take the next available index.
1120 Index = NumFuncImports + Functions.size();
1121
1122 // Prepare the function.
1123 WasmFunction Func;
1124 Func.Type = Type;
1125 Func.Sym = &WS;
1126 SymbolIndices[&WS] = Index;
1127 Functions.push_back(Func);
1128 } else {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001129 // Should be no such thing as weak undefined symbol
1130 assert(!WS.isVariable());
1131
Dan Gohmand934cb82017-02-24 23:18:00 +00001132 // An import; the index was assigned above.
1133 Index = SymbolIndices.find(&WS)->second;
1134 }
1135
1136 // If needed, prepare the function to be called indirectly.
Sam Cleggd99f6072017-06-12 23:52:44 +00001137 if (IsAddressTaken.count(&WS)) {
1138 IndirectSymbolIndices[&WS] = TableElems.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001139 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001140 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001141 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001142 if (WS.isTemporary() && !WS.getSize())
1143 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001144
Sam Cleggb7787fd2017-06-20 04:04:59 +00001145 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001146 if (WS.getOffset() != 0)
1147 report_fatal_error("data sections must contain one variable each: " +
1148 WS.getName());
1149 if (!WS.getSize())
1150 report_fatal_error("data symbols must have a size set with .size: " +
1151 WS.getName());
1152
1153 int64_t Size = 0;
1154 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1155 report_fatal_error(".size expression must be evaluatable");
1156
Dan Gohmand934cb82017-02-24 23:18:00 +00001157 MCSectionWasm &DataSection =
1158 static_cast<MCSectionWasm &>(WS.getSection());
1159
1160 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1161 report_fatal_error("data sections must contain at most one variable");
1162
1163 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1164
1165 DataSection.setSectionOffset(DataBytes.size());
1166
1167 for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
1168 I != E; ++I) {
1169 const MCFragment &Frag = *I;
1170 if (Frag.hasInstructions())
1171 report_fatal_error("only data supported in data sections");
1172
1173 if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1174 if (Align->getValueSize() != 1)
1175 report_fatal_error("only byte values supported for alignment");
1176 // If nops are requested, use zeros, as this is the data section.
1177 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1178 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1179 Align->getAlignment()),
1180 DataBytes.size() +
1181 Align->getMaxBytesToEmit());
1182 DataBytes.resize(Size, Value);
1183 } else if (const MCFillFragment *Fill =
1184 dyn_cast<MCFillFragment>(&Frag)) {
1185 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1186 } else {
1187 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1188 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1189
1190 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1191 }
1192 }
1193
Sam Clegg1c154a62017-05-25 21:08:07 +00001194 // For each global, prepare a corresponding wasm global holding its
1195 // address. For externals these will also be named exports.
1196 Index = NumGlobalImports + Globals.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001197
Sam Clegg1c154a62017-05-25 21:08:07 +00001198 WasmGlobal Global;
1199 Global.Type = PtrType;
1200 Global.IsMutable = false;
1201 Global.HasImport = false;
1202 Global.InitialValue = DataSection.getSectionOffset();
1203 Global.ImportIndex = 0;
1204 SymbolIndices[&WS] = Index;
1205 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001206 }
1207 }
1208
1209 // If the symbol is visible outside this translation unit, export it.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001210 if (WS.isExternal() && WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001211 WasmExport Export;
1212 Export.FieldName = WS.getName();
1213 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001214 if (WS.isFunction())
1215 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1216 else
1217 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Dan Gohmand934cb82017-02-24 23:18:00 +00001218 Exports.push_back(Export);
1219 }
1220 }
1221
Sam Cleggb7787fd2017-06-20 04:04:59 +00001222 // Handle weak aliases
1223 for (const MCSymbol &S : Asm.symbols()) {
1224 if (!S.isVariable())
1225 continue;
1226 assert(S.isExternal());
1227 assert(S.isDefined(/*SetUsed=*/false));
1228
1229 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1230
1231 // Find the target symbol of this weak alias
1232 const MCExpr *Expr = WS.getVariableValue();
1233 auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
1234 const MCSymbolWasm *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
1235 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1236 DEBUG(dbgs() << "Weak alias: '" << WS << "' -> '" << ResolvedSym << "' = " << Index << "\n");
1237 SymbolIndices[&WS] = Index;
1238
1239 WasmExport Export;
1240 Export.FieldName = WS.getName();
1241 Export.Index = Index;
1242 if (WS.isFunction())
1243 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1244 else
1245 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1246 WeakSymbols.push_back(Export.FieldName);
1247 Exports.push_back(Export);
1248 }
1249
Dan Gohmand934cb82017-02-24 23:18:00 +00001250 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001251 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1252 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1253 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001254
Dan Gohmand934cb82017-02-24 23:18:00 +00001255 WasmFunctionType F;
1256 F.Returns = Fixup.Symbol->getReturns();
1257 F.Params = Fixup.Symbol->getParams();
1258 auto Pair =
1259 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1260 if (Pair.second)
1261 FunctionTypes.push_back(F);
1262
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001263 TypeIndices[Fixup.Symbol] = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001264 }
1265
Dan Gohman18eafb62017-02-22 01:23:18 +00001266 // Write out the Wasm header.
1267 writeHeader(Asm);
1268
Sam Clegg9e15f352017-06-03 02:01:24 +00001269 writeTypeSection(FunctionTypes);
1270 writeImportSection(Imports);
1271 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001272 writeTableSection(TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001273 writeMemorySection(DataBytes);
1274 writeGlobalSection(Globals);
1275 writeExportSection(Exports);
1276 // TODO: Start Section
1277 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001278 writeCodeSection(Asm, Layout, Functions);
1279 uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +00001280 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001281 writeCodeRelocSection();
1282 writeDataRelocSection(DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001283 writeLinkingMetaDataSection(WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001284
Dan Gohmand934cb82017-02-24 23:18:00 +00001285 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001286 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001287}
1288
1289MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1290 raw_pwrite_stream &OS) {
1291 return new WasmObjectWriter(MOTW, OS);
1292}