blob: a4faaf0f6f6c587b1d76f457dda314c3935da256 [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 Cleggb7787fd2017-06-20 04:04:59 +0000165inline raw_ostream &operator<<(raw_ostream &OS,
166 const WasmRelocationEntry &Rel) {
167 Rel.print(OS);
168 return OS;
169}
170
Dan Gohman18eafb62017-02-22 01:23:18 +0000171class WasmObjectWriter : public MCObjectWriter {
172 /// Helper struct for containing some precomputed information on symbols.
173 struct WasmSymbolData {
174 const MCSymbolWasm *Symbol;
175 StringRef Name;
176
177 // Support lexicographic sorting.
178 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
179 };
180
181 /// The target specific Wasm writer instance.
182 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
183
Dan Gohmand934cb82017-02-24 23:18:00 +0000184 // Relocations for fixing up references in the code section.
185 std::vector<WasmRelocationEntry> CodeRelocations;
186
187 // Relocations for fixing up references in the data section.
188 std::vector<WasmRelocationEntry> DataRelocations;
189
Dan Gohmand934cb82017-02-24 23:18:00 +0000190 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000191 // Maps function symbols to the index of the type of the function
192 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000193 // Maps function symbols to the table element index space. Used
194 // for TABLE_INDEX relocation types (i.e. address taken functions).
195 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
196 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000197 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
198
199 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
200 FunctionTypeIndices;
Dan Gohmand934cb82017-02-24 23:18:00 +0000201
Dan Gohman18eafb62017-02-22 01:23:18 +0000202 // TargetObjectWriter wrappers.
203 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000204 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
205 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000206 }
207
Dan Gohmand934cb82017-02-24 23:18:00 +0000208 void startSection(SectionBookkeeping &Section, unsigned SectionId,
209 const char *Name = nullptr);
210 void endSection(SectionBookkeeping &Section);
211
Dan Gohman18eafb62017-02-22 01:23:18 +0000212public:
213 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
214 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
215
Dan Gohmand934cb82017-02-24 23:18:00 +0000216private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000217 ~WasmObjectWriter() override;
218
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000219 void reset() override {
220 CodeRelocations.clear();
221 DataRelocations.clear();
222 TypeIndices.clear();
223 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000224 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000225 FunctionTypeIndices.clear();
226 MCObjectWriter::reset();
227 }
228
Dan Gohman18eafb62017-02-22 01:23:18 +0000229 void writeHeader(const MCAssembler &Asm);
230
231 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
232 const MCFragment *Fragment, const MCFixup &Fixup,
233 MCValue Target, bool &IsPCRel,
234 uint64_t &FixedValue) override;
235
236 void executePostLayoutBinding(MCAssembler &Asm,
237 const MCAsmLayout &Layout) override;
238
239 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000240
Sam Cleggb7787fd2017-06-20 04:04:59 +0000241 void writeString(const StringRef Str) {
242 encodeULEB128(Str.size(), getStream());
243 writeBytes(Str);
244 }
245
Sam Clegg9e15f352017-06-03 02:01:24 +0000246 void writeValueType(wasm::ValType Ty) {
247 encodeSLEB128(int32_t(Ty), getStream());
248 }
249
250 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
251 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
252 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000253 void writeTableSection(uint32_t NumElements);
Sam Clegg9e15f352017-06-03 02:01:24 +0000254 void writeMemorySection(const SmallVector<char, 0> &DataBytes);
255 void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
256 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
257 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
258 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000259 const SmallVector<WasmFunction, 4> &Functions);
260 uint64_t
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000261 writeDataSection(const SmallVector<char, 0> &DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +0000262 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
263 const SmallVector<WasmImport, 4> &Imports,
264 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000265 void writeCodeRelocSection();
266 void writeDataRelocSection(uint64_t DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000267 void writeLinkingMetaDataSection(ArrayRef<StringRef> WeakSymbols,
268 bool HasStackPointer,
Sam Clegg9e15f352017-06-03 02:01:24 +0000269 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000270
271 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
272 uint64_t ContentsOffset);
273
274 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
275 uint64_t HeaderSize);
276 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Dan Gohman18eafb62017-02-22 01:23:18 +0000277};
Sam Clegg9e15f352017-06-03 02:01:24 +0000278
Dan Gohman18eafb62017-02-22 01:23:18 +0000279} // end anonymous namespace
280
281WasmObjectWriter::~WasmObjectWriter() {}
282
Dan Gohmand934cb82017-02-24 23:18:00 +0000283// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
284static unsigned PaddingFor5ByteULEB128(uint32_t X) {
285 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
286}
287
288// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
289static unsigned PaddingFor5ByteSLEB128(int32_t X) {
290 return 5 - getSLEB128Size(X);
291}
292
293// Write out a section header and a patchable section size field.
294void WasmObjectWriter::startSection(SectionBookkeeping &Section,
295 unsigned SectionId,
296 const char *Name) {
297 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
298 "Only custom sections can have names");
299
Sam Cleggb7787fd2017-06-20 04:04:59 +0000300 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000301 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000302
303 Section.SizeOffset = getStream().tell();
304
305 // The section size. We don't know the size yet, so reserve enough space
306 // for any 32-bit value; we'll patch it later.
307 encodeULEB128(UINT32_MAX, getStream());
308
309 // The position where the section starts, for measuring its size.
310 Section.ContentsOffset = getStream().tell();
311
312 // Custom sections in wasm also have a string identifier.
313 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000314 assert(Name);
315 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000316 }
317}
318
319// Now that the section is complete and we know how big it is, patch up the
320// section size field at the start of the section.
321void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
322 uint64_t Size = getStream().tell() - Section.ContentsOffset;
323 if (uint32_t(Size) != Size)
324 report_fatal_error("section size does not fit in a uint32_t");
325
Sam Cleggb7787fd2017-06-20 04:04:59 +0000326 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000327 unsigned Padding = PaddingFor5ByteULEB128(Size);
328
329 // Write the final section size to the payload_len field, which follows
330 // the section id byte.
331 uint8_t Buffer[16];
332 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
333 assert(SizeLen == 5);
334 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
335}
336
Dan Gohman18eafb62017-02-22 01:23:18 +0000337// Emit the Wasm header.
338void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000339 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
340 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000341}
342
343void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
344 const MCAsmLayout &Layout) {
345}
346
347void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
348 const MCAsmLayout &Layout,
349 const MCFragment *Fragment,
350 const MCFixup &Fixup, MCValue Target,
351 bool &IsPCRel, uint64_t &FixedValue) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000352 MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
353 uint64_t C = Target.getConstant();
354 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
355 MCContext &Ctx = Asm.getContext();
356
357 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
358 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
359 "Should not have constructed this");
360
361 // Let A, B and C being the components of Target and R be the location of
362 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
363 // If it is pcrel, we want to compute (A - B + C - R).
364
365 // In general, Wasm has no relocations for -B. It can only represent (A + C)
366 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
367 // replace B to implement it: (A - R - K + C)
368 if (IsPCRel) {
369 Ctx.reportError(
370 Fixup.getLoc(),
371 "No relocation available to represent this relative expression");
372 return;
373 }
374
375 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
376
377 if (SymB.isUndefined()) {
378 Ctx.reportError(Fixup.getLoc(),
379 Twine("symbol '") + SymB.getName() +
380 "' can not be undefined in a subtraction expression");
381 return;
382 }
383
384 assert(!SymB.isAbsolute() && "Should have been folded");
385 const MCSection &SecB = SymB.getSection();
386 if (&SecB != &FixupSection) {
387 Ctx.reportError(Fixup.getLoc(),
388 "Cannot represent a difference across sections");
389 return;
390 }
391
392 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
393 uint64_t K = SymBOffset - FixupOffset;
394 IsPCRel = true;
395 C -= K;
396 }
397
398 // We either rejected the fixup or folded B into C at this point.
399 const MCSymbolRefExpr *RefA = Target.getSymA();
400 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
401
402 bool ViaWeakRef = false;
403 if (SymA && SymA->isVariable()) {
404 const MCExpr *Expr = SymA->getVariableValue();
405 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
406 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
407 SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
408 ViaWeakRef = true;
409 }
410 }
411 }
412
413 // Put any constant offset in an addend. Offsets can be negative, and
414 // LLVM expects wrapping, in contrast to wasm's immediates which can't
415 // be negative and don't wrap.
416 FixedValue = 0;
417
418 if (SymA) {
419 if (ViaWeakRef)
420 llvm_unreachable("weakref used in reloc not yet implemented");
421 else
422 SymA->setUsedInReloc();
423 }
424
Sam Cleggae03c1e72017-06-13 18:51:50 +0000425 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000426 assert(SymA);
427
Sam Cleggae03c1e72017-06-13 18:51:50 +0000428 unsigned Type = getRelocType(Target, Fixup);
429
Dan Gohmand934cb82017-02-24 23:18:00 +0000430 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000431 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000432
433 if (FixupSection.hasInstructions())
434 CodeRelocations.push_back(Rec);
435 else
436 DataRelocations.push_back(Rec);
437}
438
Dan Gohmand934cb82017-02-24 23:18:00 +0000439// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
440// to allow patching.
441static void
442WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
443 uint8_t Buffer[5];
444 unsigned Padding = PaddingFor5ByteULEB128(X);
445 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
446 assert(SizeLen == 5);
447 Stream.pwrite((char *)Buffer, SizeLen, Offset);
448}
449
450// Write X as an signed LEB value at offset Offset in Stream, padded
451// to allow patching.
452static void
453WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
454 uint8_t Buffer[5];
455 unsigned Padding = PaddingFor5ByteSLEB128(X);
456 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
457 assert(SizeLen == 5);
458 Stream.pwrite((char *)Buffer, SizeLen, Offset);
459}
460
461// Write X as a plain integer value at offset Offset in Stream.
462static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
463 uint8_t Buffer[4];
464 support::endian::write32le(Buffer, X);
465 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
466}
467
468// Compute a value to write into the code at the location covered
469// by RelEntry. This value isn't used by the static linker, since
470// we have addends; it just serves to make the code more readable
471// and to make standalone wasm modules directly usable.
472static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
473 const MCSymbolWasm *Sym = RelEntry.Symbol;
474
475 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000476 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000477 return UINT32_MAX;
478
479 MCSectionWasm &Section =
480 cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
481 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
482
483 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
484 uint32_t Value = Address;
485
486 return Value;
487}
488
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000489uint32_t WasmObjectWriter::getRelocationIndexValue(
490 const WasmRelocationEntry &RelEntry) {
491 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000492 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
493 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000494 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
495 report_fatal_error("symbol not found table index space:" +
496 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000497 return IndirectSymbolIndices[RelEntry.Symbol];
498 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000499 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000500 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
501 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
502 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000503 if (!SymbolIndices.count(RelEntry.Symbol))
504 report_fatal_error("symbol not found function/global index space:" +
505 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000506 return SymbolIndices[RelEntry.Symbol];
507 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000508 if (!TypeIndices.count(RelEntry.Symbol))
509 report_fatal_error("symbol not found in type index space:" +
510 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000511 return TypeIndices[RelEntry.Symbol];
512 default:
513 llvm_unreachable("invalid relocation type");
514 }
515}
516
Dan Gohmand934cb82017-02-24 23:18:00 +0000517// Apply the portions of the relocation records that we can handle ourselves
518// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000519void WasmObjectWriter::applyRelocations(
520 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
521 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000522 for (const WasmRelocationEntry &RelEntry : Relocations) {
523 uint64_t Offset = ContentsOffset +
524 RelEntry.FixupSection->getSectionOffset() +
525 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000526
Sam Cleggb7787fd2017-06-20 04:04:59 +0000527 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000528 switch (RelEntry.Type) {
529 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
530 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000531 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
532 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000533 uint32_t Index = getRelocationIndexValue(RelEntry);
534 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000535 break;
536 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000537 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
538 uint32_t Index = getRelocationIndexValue(RelEntry);
539 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000540 break;
541 }
542 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
543 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000544 WritePatchableSLEB(Stream, Value, Offset);
545 break;
546 }
547 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
548 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000549 WritePatchableLEB(Stream, Value, Offset);
550 break;
551 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000552 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
553 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000554 WriteI32(Stream, Value, Offset);
555 break;
556 }
557 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000558 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000559 }
560 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000561}
562
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000563// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000564// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000565void WasmObjectWriter::writeRelocations(
566 ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
567 raw_pwrite_stream &Stream = getStream();
568 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000569
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000570 uint64_t Offset = RelEntry.Offset +
571 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
572 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000573
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000574 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000575 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000576 encodeULEB128(Index, Stream);
577 if (RelEntry.hasAddend())
578 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000579 }
580}
581
Sam Clegg9e15f352017-06-03 02:01:24 +0000582void WasmObjectWriter::writeTypeSection(
583 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
584 if (FunctionTypes.empty())
585 return;
586
587 SectionBookkeeping Section;
588 startSection(Section, wasm::WASM_SEC_TYPE);
589
590 encodeULEB128(FunctionTypes.size(), getStream());
591
592 for (const WasmFunctionType &FuncTy : FunctionTypes) {
593 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
594 encodeULEB128(FuncTy.Params.size(), getStream());
595 for (wasm::ValType Ty : FuncTy.Params)
596 writeValueType(Ty);
597 encodeULEB128(FuncTy.Returns.size(), getStream());
598 for (wasm::ValType Ty : FuncTy.Returns)
599 writeValueType(Ty);
600 }
601
602 endSection(Section);
603}
604
Sam Cleggb7787fd2017-06-20 04:04:59 +0000605
Sam Clegg9e15f352017-06-03 02:01:24 +0000606void WasmObjectWriter::writeImportSection(
607 const SmallVector<WasmImport, 4> &Imports) {
608 if (Imports.empty())
609 return;
610
611 SectionBookkeeping Section;
612 startSection(Section, wasm::WASM_SEC_IMPORT);
613
614 encodeULEB128(Imports.size(), getStream());
615 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000616 writeString(Import.ModuleName);
617 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000618
619 encodeULEB128(Import.Kind, getStream());
620
621 switch (Import.Kind) {
622 case wasm::WASM_EXTERNAL_FUNCTION:
623 encodeULEB128(Import.Type, getStream());
624 break;
625 case wasm::WASM_EXTERNAL_GLOBAL:
626 encodeSLEB128(int32_t(Import.Type), getStream());
627 encodeULEB128(0, getStream()); // mutability
628 break;
629 default:
630 llvm_unreachable("unsupported import kind");
631 }
632 }
633
634 endSection(Section);
635}
636
637void WasmObjectWriter::writeFunctionSection(
638 const SmallVector<WasmFunction, 4> &Functions) {
639 if (Functions.empty())
640 return;
641
642 SectionBookkeeping Section;
643 startSection(Section, wasm::WASM_SEC_FUNCTION);
644
645 encodeULEB128(Functions.size(), getStream());
646 for (const WasmFunction &Func : Functions)
647 encodeULEB128(Func.Type, getStream());
648
649 endSection(Section);
650}
651
Sam Cleggd99f6072017-06-12 23:52:44 +0000652void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000653 // For now, always emit the table section, since indirect calls are not
654 // valid without it. In the future, we could perhaps be more clever and omit
655 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000656
Sam Clegg9e15f352017-06-03 02:01:24 +0000657 SectionBookkeeping Section;
658 startSection(Section, wasm::WASM_SEC_TABLE);
659
Sam Cleggd99f6072017-06-12 23:52:44 +0000660 encodeULEB128(1, getStream()); // The number of tables.
661 // Fixed to 1 for now.
662 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
663 encodeULEB128(0, getStream()); // flags
664 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000665
666 endSection(Section);
667}
668
669void WasmObjectWriter::writeMemorySection(
670 const SmallVector<char, 0> &DataBytes) {
671 // For now, always emit the memory section, since loads and stores are not
672 // valid without it. In the future, we could perhaps be more clever and omit
673 // it if there are no loads or stores.
674 SectionBookkeeping Section;
675 uint32_t NumPages =
676 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
677
678 startSection(Section, wasm::WASM_SEC_MEMORY);
679 encodeULEB128(1, getStream()); // number of memory spaces
680
681 encodeULEB128(0, getStream()); // flags
682 encodeULEB128(NumPages, getStream()); // initial
683
684 endSection(Section);
685}
686
687void WasmObjectWriter::writeGlobalSection(
688 const SmallVector<WasmGlobal, 4> &Globals) {
689 if (Globals.empty())
690 return;
691
692 SectionBookkeeping Section;
693 startSection(Section, wasm::WASM_SEC_GLOBAL);
694
695 encodeULEB128(Globals.size(), getStream());
696 for (const WasmGlobal &Global : Globals) {
697 writeValueType(Global.Type);
698 write8(Global.IsMutable);
699
700 if (Global.HasImport) {
701 assert(Global.InitialValue == 0);
702 write8(wasm::WASM_OPCODE_GET_GLOBAL);
703 encodeULEB128(Global.ImportIndex, getStream());
704 } else {
705 assert(Global.ImportIndex == 0);
706 write8(wasm::WASM_OPCODE_I32_CONST);
707 encodeSLEB128(Global.InitialValue, getStream()); // offset
708 }
709 write8(wasm::WASM_OPCODE_END);
710 }
711
712 endSection(Section);
713}
714
715void WasmObjectWriter::writeExportSection(
716 const SmallVector<WasmExport, 4> &Exports) {
717 if (Exports.empty())
718 return;
719
720 SectionBookkeeping Section;
721 startSection(Section, wasm::WASM_SEC_EXPORT);
722
723 encodeULEB128(Exports.size(), getStream());
724 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000725 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000726 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000727 encodeULEB128(Export.Index, getStream());
728 }
729
730 endSection(Section);
731}
732
733void WasmObjectWriter::writeElemSection(
734 const SmallVector<uint32_t, 4> &TableElems) {
735 if (TableElems.empty())
736 return;
737
738 SectionBookkeeping Section;
739 startSection(Section, wasm::WASM_SEC_ELEM);
740
741 encodeULEB128(1, getStream()); // number of "segments"
742 encodeULEB128(0, getStream()); // the table index
743
744 // init expr for starting offset
745 write8(wasm::WASM_OPCODE_I32_CONST);
746 encodeSLEB128(0, getStream());
747 write8(wasm::WASM_OPCODE_END);
748
749 encodeULEB128(TableElems.size(), getStream());
750 for (uint32_t Elem : TableElems)
751 encodeULEB128(Elem, getStream());
752
753 endSection(Section);
754}
755
756void WasmObjectWriter::writeCodeSection(
757 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000758 const SmallVector<WasmFunction, 4> &Functions) {
759 if (Functions.empty())
760 return;
761
762 SectionBookkeeping Section;
763 startSection(Section, wasm::WASM_SEC_CODE);
764
765 encodeULEB128(Functions.size(), getStream());
766
767 for (const WasmFunction &Func : Functions) {
768 MCSectionWasm &FuncSection =
769 static_cast<MCSectionWasm &>(Func.Sym->getSection());
770
Sam Clegg9e15f352017-06-03 02:01:24 +0000771 int64_t Size = 0;
772 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
773 report_fatal_error(".size expression must be evaluatable");
774
775 encodeULEB128(Size, getStream());
776
777 FuncSection.setSectionOffset(getStream().tell() -
778 Section.ContentsOffset);
779
780 Asm.writeSectionData(&FuncSection, Layout);
781 }
782
Sam Clegg9e15f352017-06-03 02:01:24 +0000783 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000784 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000785
786 endSection(Section);
787}
788
789uint64_t WasmObjectWriter::writeDataSection(
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000790 const SmallVector<char, 0> &DataBytes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 if (DataBytes.empty())
792 return 0;
793
794 SectionBookkeeping Section;
795 startSection(Section, wasm::WASM_SEC_DATA);
796
797 encodeULEB128(1, getStream()); // count
798 encodeULEB128(0, getStream()); // memory index
799 write8(wasm::WASM_OPCODE_I32_CONST);
800 encodeSLEB128(0, getStream()); // offset
801 write8(wasm::WASM_OPCODE_END);
802 encodeULEB128(DataBytes.size(), getStream()); // size
803 uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
804 writeBytes(DataBytes); // data
805
806 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000807 applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000808
809 endSection(Section);
810 return HeaderSize;
811}
812
813void WasmObjectWriter::writeNameSection(
814 const SmallVector<WasmFunction, 4> &Functions,
815 const SmallVector<WasmImport, 4> &Imports,
816 unsigned NumFuncImports) {
817 uint32_t TotalFunctions = NumFuncImports + Functions.size();
818 if (TotalFunctions == 0)
819 return;
820
821 SectionBookkeeping Section;
822 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
823 SectionBookkeeping SubSection;
824 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
825
826 encodeULEB128(TotalFunctions, getStream());
827 uint32_t Index = 0;
828 for (const WasmImport &Import : Imports) {
829 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
830 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000831 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000832 ++Index;
833 }
834 }
835 for (const WasmFunction &Func : Functions) {
836 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000837 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000838 ++Index;
839 }
840
841 endSection(SubSection);
842 endSection(Section);
843}
844
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000845void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000846 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
847 // for descriptions of the reloc sections.
848
849 if (CodeRelocations.empty())
850 return;
851
852 SectionBookkeeping Section;
853 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
854
855 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000856 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000858 writeRelocations(CodeRelocations, 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859
860 endSection(Section);
861}
862
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000863void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000864 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
865 // for descriptions of the reloc sections.
866
867 if (DataRelocations.empty())
868 return;
869
870 SectionBookkeeping Section;
871 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
872
873 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
874 encodeULEB128(DataRelocations.size(), getStream());
875
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000876 writeRelocations(DataRelocations, DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000877
878 endSection(Section);
879}
880
881void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggb7787fd2017-06-20 04:04:59 +0000882 ArrayRef<StringRef> WeakSymbols, bool HasStackPointer,
883 uint32_t StackPointerGlobal) {
884 if (!HasStackPointer && WeakSymbols.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000885 return;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000886
Sam Clegg9e15f352017-06-03 02:01:24 +0000887 SectionBookkeeping Section;
888 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000889 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000890
Sam Cleggb7787fd2017-06-20 04:04:59 +0000891 if (HasStackPointer) {
892 startSection(SubSection, wasm::WASM_STACK_POINTER);
893 encodeULEB128(StackPointerGlobal, getStream()); // id
894 endSection(SubSection);
895 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000896
Sam Cleggb7787fd2017-06-20 04:04:59 +0000897 if (WeakSymbols.size() != 0) {
898 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
899 encodeULEB128(WeakSymbols.size(), getStream());
900 for (const StringRef Export: WeakSymbols) {
901 writeString(Export);
902 encodeULEB128(wasm::WASM_SYMBOL_FLAG_WEAK, getStream());
903 }
904 endSection(SubSection);
905 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000906
907 endSection(Section);
908}
909
Dan Gohman18eafb62017-02-22 01:23:18 +0000910void WasmObjectWriter::writeObject(MCAssembler &Asm,
911 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000912 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000913 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000914 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000915
916 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000917 SmallVector<WasmFunctionType, 4> FunctionTypes;
918 SmallVector<WasmFunction, 4> Functions;
919 SmallVector<uint32_t, 4> TableElems;
920 SmallVector<WasmGlobal, 4> Globals;
921 SmallVector<WasmImport, 4> Imports;
922 SmallVector<WasmExport, 4> Exports;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000923 SmallVector<StringRef, 4> WeakSymbols;
Dan Gohmand934cb82017-02-24 23:18:00 +0000924 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
925 unsigned NumFuncImports = 0;
926 unsigned NumGlobalImports = 0;
927 SmallVector<char, 0> DataBytes;
Dan Gohman970d02c2017-03-30 23:58:19 +0000928 uint32_t StackPointerGlobal = 0;
929 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000930
931 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000932 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000933 switch (RelEntry.Type) {
934 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
935 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
936 IsAddressTaken.insert(RelEntry.Symbol);
937 break;
938 default:
939 break;
940 }
941 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000942 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000943 switch (RelEntry.Type) {
944 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
945 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
946 IsAddressTaken.insert(RelEntry.Symbol);
947 break;
948 default:
949 break;
950 }
951 }
952
953 // Populate the Imports set.
954 for (const MCSymbol &S : Asm.symbols()) {
955 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Derek Schuffb8795392017-03-16 20:49:48 +0000956 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000957
958 if (WS.isFunction()) {
959 // Prepare the function's type, if we haven't seen it yet.
960 WasmFunctionType F;
961 F.Returns = WS.getReturns();
962 F.Params = WS.getParams();
963 auto Pair =
964 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
965 if (Pair.second)
966 FunctionTypes.push_back(F);
967
968 Type = Pair.first->second;
969 } else {
Derek Schuffb8795392017-03-16 20:49:48 +0000970 Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +0000971 }
972
973 // If the symbol is not defined in this translation unit, import it.
974 if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
975 WasmImport Import;
976 Import.ModuleName = WS.getModuleName();
977 Import.FieldName = WS.getName();
978
979 if (WS.isFunction()) {
980 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
981 Import.Type = Type;
982 SymbolIndices[&WS] = NumFuncImports;
983 ++NumFuncImports;
984 } else {
985 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
986 Import.Type = Type;
987 SymbolIndices[&WS] = NumGlobalImports;
988 ++NumGlobalImports;
989 }
990
991 Imports.push_back(Import);
992 }
993 }
994
Dan Gohman82607f52017-02-24 23:46:05 +0000995 // In the special .global_variables section, we've encoded global
996 // variables used by the function. Translate them into the Globals
997 // list.
998 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
999 if (!GlobalVars->getFragmentList().empty()) {
1000 if (GlobalVars->getFragmentList().size() != 1)
1001 report_fatal_error("only one .global_variables fragment supported");
1002 const MCFragment &Frag = *GlobalVars->begin();
1003 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1004 report_fatal_error("only data supported in .global_variables");
1005 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1006 if (!DataFrag.getFixups().empty())
1007 report_fatal_error("fixups not supported in .global_variables");
1008 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001009 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1010 *end = (const uint8_t *)Contents.data() + Contents.size();
1011 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001012 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001013 if (end - p < 3)
1014 report_fatal_error("truncated global variable encoding");
1015 G.Type = wasm::ValType(int8_t(*p++));
1016 G.IsMutable = bool(*p++);
1017 G.HasImport = bool(*p++);
1018 if (G.HasImport) {
1019 G.InitialValue = 0;
1020
1021 WasmImport Import;
1022 Import.ModuleName = (const char *)p;
1023 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1024 if (!nul)
1025 report_fatal_error("global module name must be nul-terminated");
1026 p = nul + 1;
1027 nul = (const uint8_t *)memchr(p, '\0', end - p);
1028 if (!nul)
1029 report_fatal_error("global base name must be nul-terminated");
1030 Import.FieldName = (const char *)p;
1031 p = nul + 1;
1032
1033 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1034 Import.Type = int32_t(G.Type);
1035
1036 G.ImportIndex = NumGlobalImports;
1037 ++NumGlobalImports;
1038
1039 Imports.push_back(Import);
1040 } else {
1041 unsigned n;
1042 G.InitialValue = decodeSLEB128(p, &n);
1043 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001044 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001045 report_fatal_error("global initial value must be valid SLEB128");
1046 p += n;
1047 }
Dan Gohman82607f52017-02-24 23:46:05 +00001048 Globals.push_back(G);
1049 }
1050 }
1051
Dan Gohman970d02c2017-03-30 23:58:19 +00001052 // In the special .stack_pointer section, we've encoded the stack pointer
1053 // index.
1054 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1055 if (!StackPtr->getFragmentList().empty()) {
1056 if (StackPtr->getFragmentList().size() != 1)
1057 report_fatal_error("only one .stack_pointer fragment supported");
1058 const MCFragment &Frag = *StackPtr->begin();
1059 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1060 report_fatal_error("only data supported in .stack_pointer");
1061 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1062 if (!DataFrag.getFixups().empty())
1063 report_fatal_error("fixups not supported in .stack_pointer");
1064 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1065 if (Contents.size() != 4)
1066 report_fatal_error("only one entry supported in .stack_pointer");
1067 HasStackPointer = true;
1068 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1069 }
1070
Sam Cleggb7787fd2017-06-20 04:04:59 +00001071 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001072 for (const MCSymbol &S : Asm.symbols()) {
1073 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1074 // or used in relocations.
1075 if (S.isTemporary() && S.getName().empty())
1076 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001077
1078 // Variable references (weak references) are handled in a second pass
1079 if (S.isVariable())
1080 continue;
1081
Dan Gohmand934cb82017-02-24 23:18:00 +00001082 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001083 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1084 << " isDefined=" << S.isDefined() << " isExternal="
1085 << S.isExternal() << " isTemporary=" << S.isTemporary()
1086 << " isFunction=" << WS.isFunction()
1087 << " isWeak=" << WS.isWeak()
1088 << " isVariable=" << WS.isVariable() << "\n");
1089
1090 if (WS.isWeak())
1091 WeakSymbols.push_back(WS.getName());
1092
Dan Gohmand934cb82017-02-24 23:18:00 +00001093 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001094
1095 //<< " function=" << S.isFunction()
1096
Dan Gohmand934cb82017-02-24 23:18:00 +00001097 if (WS.isFunction()) {
1098 // Prepare the function's type, if we haven't seen it yet.
1099 WasmFunctionType F;
1100 F.Returns = WS.getReturns();
1101 F.Params = WS.getParams();
1102 auto Pair =
1103 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1104 if (Pair.second)
1105 FunctionTypes.push_back(F);
1106
Derek Schuffb8795392017-03-16 20:49:48 +00001107 int32_t Type = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001108
1109 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001110 if (WS.getOffset() != 0)
1111 report_fatal_error(
1112 "function sections must contain one function each");
1113
1114 if (WS.getSize() == 0)
1115 report_fatal_error(
1116 "function symbols must have a size set with .size");
1117
Dan Gohmand934cb82017-02-24 23:18:00 +00001118 // A definition. Take the next available index.
1119 Index = NumFuncImports + Functions.size();
1120
1121 // Prepare the function.
1122 WasmFunction Func;
1123 Func.Type = Type;
1124 Func.Sym = &WS;
1125 SymbolIndices[&WS] = Index;
1126 Functions.push_back(Func);
1127 } else {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001128 // Should be no such thing as weak undefined symbol
1129 assert(!WS.isVariable());
1130
Dan Gohmand934cb82017-02-24 23:18:00 +00001131 // An import; the index was assigned above.
1132 Index = SymbolIndices.find(&WS)->second;
1133 }
1134
1135 // If needed, prepare the function to be called indirectly.
Sam Cleggd99f6072017-06-12 23:52:44 +00001136 if (IsAddressTaken.count(&WS)) {
1137 IndirectSymbolIndices[&WS] = TableElems.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001138 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001139 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001140 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001141 if (WS.isTemporary() && !WS.getSize())
1142 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001143
Sam Cleggb7787fd2017-06-20 04:04:59 +00001144 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001145 if (WS.getOffset() != 0)
1146 report_fatal_error("data sections must contain one variable each: " +
1147 WS.getName());
1148 if (!WS.getSize())
1149 report_fatal_error("data symbols must have a size set with .size: " +
1150 WS.getName());
1151
1152 int64_t Size = 0;
1153 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1154 report_fatal_error(".size expression must be evaluatable");
1155
Dan Gohmand934cb82017-02-24 23:18:00 +00001156 MCSectionWasm &DataSection =
1157 static_cast<MCSectionWasm &>(WS.getSection());
1158
1159 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1160 report_fatal_error("data sections must contain at most one variable");
1161
1162 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1163
1164 DataSection.setSectionOffset(DataBytes.size());
1165
1166 for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
1167 I != E; ++I) {
1168 const MCFragment &Frag = *I;
1169 if (Frag.hasInstructions())
1170 report_fatal_error("only data supported in data sections");
1171
1172 if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1173 if (Align->getValueSize() != 1)
1174 report_fatal_error("only byte values supported for alignment");
1175 // If nops are requested, use zeros, as this is the data section.
1176 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1177 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1178 Align->getAlignment()),
1179 DataBytes.size() +
1180 Align->getMaxBytesToEmit());
1181 DataBytes.resize(Size, Value);
1182 } else if (const MCFillFragment *Fill =
1183 dyn_cast<MCFillFragment>(&Frag)) {
1184 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1185 } else {
1186 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1187 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1188
1189 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1190 }
1191 }
1192
Sam Clegg1c154a62017-05-25 21:08:07 +00001193 // For each global, prepare a corresponding wasm global holding its
1194 // address. For externals these will also be named exports.
1195 Index = NumGlobalImports + Globals.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001196
Sam Clegg1c154a62017-05-25 21:08:07 +00001197 WasmGlobal Global;
1198 Global.Type = PtrType;
1199 Global.IsMutable = false;
1200 Global.HasImport = false;
1201 Global.InitialValue = DataSection.getSectionOffset();
1202 Global.ImportIndex = 0;
1203 SymbolIndices[&WS] = Index;
1204 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001205 }
1206 }
1207
1208 // If the symbol is visible outside this translation unit, export it.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001209 if (WS.isExternal() && WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001210 WasmExport Export;
1211 Export.FieldName = WS.getName();
1212 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001213 if (WS.isFunction())
1214 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1215 else
1216 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Dan Gohmand934cb82017-02-24 23:18:00 +00001217 Exports.push_back(Export);
1218 }
1219 }
1220
Sam Cleggb7787fd2017-06-20 04:04:59 +00001221 // Handle weak aliases
1222 for (const MCSymbol &S : Asm.symbols()) {
1223 if (!S.isVariable())
1224 continue;
1225 assert(S.isExternal());
1226 assert(S.isDefined(/*SetUsed=*/false));
1227
1228 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1229
1230 // Find the target symbol of this weak alias
1231 const MCExpr *Expr = WS.getVariableValue();
1232 auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
1233 const MCSymbolWasm *ResolvedSym = cast<MCSymbolWasm>(&Inner->getSymbol());
1234 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
1235 DEBUG(dbgs() << "Weak alias: '" << WS << "' -> '" << ResolvedSym << "' = " << Index << "\n");
1236 SymbolIndices[&WS] = Index;
1237
1238 WasmExport Export;
1239 Export.FieldName = WS.getName();
1240 Export.Index = Index;
1241 if (WS.isFunction())
1242 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1243 else
1244 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1245 WeakSymbols.push_back(Export.FieldName);
1246 Exports.push_back(Export);
1247 }
1248
Dan Gohmand934cb82017-02-24 23:18:00 +00001249 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001250 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1251 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1252 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001253
Dan Gohmand934cb82017-02-24 23:18:00 +00001254 WasmFunctionType F;
1255 F.Returns = Fixup.Symbol->getReturns();
1256 F.Params = Fixup.Symbol->getParams();
1257 auto Pair =
1258 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1259 if (Pair.second)
1260 FunctionTypes.push_back(F);
1261
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001262 TypeIndices[Fixup.Symbol] = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001263 }
1264
Dan Gohman18eafb62017-02-22 01:23:18 +00001265 // Write out the Wasm header.
1266 writeHeader(Asm);
1267
Sam Clegg9e15f352017-06-03 02:01:24 +00001268 writeTypeSection(FunctionTypes);
1269 writeImportSection(Imports);
1270 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001271 writeTableSection(TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001272 writeMemorySection(DataBytes);
1273 writeGlobalSection(Globals);
1274 writeExportSection(Exports);
1275 // TODO: Start Section
1276 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001277 writeCodeSection(Asm, Layout, Functions);
1278 uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +00001279 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001280 writeCodeRelocSection();
1281 writeDataRelocSection(DataSectionHeaderSize);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001282 writeLinkingMetaDataSection(WeakSymbols, HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001283
Dan Gohmand934cb82017-02-24 23:18:00 +00001284 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001285 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001286}
1287
1288MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1289 raw_pwrite_stream &OS) {
1290 return new WasmObjectWriter(MOTW, OS);
1291}