blob: 4b3dc6e0c211fccb13cf2675b63848bba505f237 [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 }
159 void dump() const { print(errs()); }
160};
161
Dan Gohman18eafb62017-02-22 01:23:18 +0000162class WasmObjectWriter : public MCObjectWriter {
163 /// Helper struct for containing some precomputed information on symbols.
164 struct WasmSymbolData {
165 const MCSymbolWasm *Symbol;
166 StringRef Name;
167
168 // Support lexicographic sorting.
169 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
170 };
171
172 /// The target specific Wasm writer instance.
173 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
174
Dan Gohmand934cb82017-02-24 23:18:00 +0000175 // Relocations for fixing up references in the code section.
176 std::vector<WasmRelocationEntry> CodeRelocations;
177
178 // Relocations for fixing up references in the data section.
179 std::vector<WasmRelocationEntry> DataRelocations;
180
Dan Gohmand934cb82017-02-24 23:18:00 +0000181 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000182 // Maps function symbols to the index of the type of the function
183 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
184
185 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
186
187 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
188 FunctionTypeIndices;
Dan Gohmand934cb82017-02-24 23:18:00 +0000189
Dan Gohman18eafb62017-02-22 01:23:18 +0000190 // TargetObjectWriter wrappers.
191 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
192 unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
193 const MCFixup &Fixup, bool IsPCRel) const {
194 return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
195 }
196
Dan Gohmand934cb82017-02-24 23:18:00 +0000197 void startSection(SectionBookkeeping &Section, unsigned SectionId,
198 const char *Name = nullptr);
199 void endSection(SectionBookkeeping &Section);
200
Dan Gohman18eafb62017-02-22 01:23:18 +0000201public:
202 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
203 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
204
Dan Gohmand934cb82017-02-24 23:18:00 +0000205private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000206 ~WasmObjectWriter() override;
207
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000208 void reset() override {
209 CodeRelocations.clear();
210 DataRelocations.clear();
211 TypeIndices.clear();
212 SymbolIndices.clear();
213 FunctionTypeIndices.clear();
214 MCObjectWriter::reset();
215 }
216
Dan Gohman18eafb62017-02-22 01:23:18 +0000217 void writeHeader(const MCAssembler &Asm);
218
219 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
220 const MCFragment *Fragment, const MCFixup &Fixup,
221 MCValue Target, bool &IsPCRel,
222 uint64_t &FixedValue) override;
223
224 void executePostLayoutBinding(MCAssembler &Asm,
225 const MCAsmLayout &Layout) override;
226
227 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000228
229 void writeValueType(wasm::ValType Ty) {
230 encodeSLEB128(int32_t(Ty), getStream());
231 }
232
233 void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes);
234 void writeImportSection(const SmallVector<WasmImport, 4> &Imports);
235 void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions);
236 void writeTableSection(const SmallVector<uint32_t, 4> &TableElems);
237 void writeMemorySection(const SmallVector<char, 0> &DataBytes);
238 void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals);
239 void writeExportSection(const SmallVector<WasmExport, 4> &Exports);
240 void writeElemSection(const SmallVector<uint32_t, 4> &TableElems);
241 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000242 const SmallVector<WasmFunction, 4> &Functions);
243 uint64_t
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000244 writeDataSection(const SmallVector<char, 0> &DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +0000245 void writeNameSection(const SmallVector<WasmFunction, 4> &Functions,
246 const SmallVector<WasmImport, 4> &Imports,
247 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000248 void writeCodeRelocSection();
249 void writeDataRelocSection(uint64_t DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000250 void writeLinkingMetaDataSection(bool HasStackPointer,
251 uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000252
253 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
254 uint64_t ContentsOffset);
255
256 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations,
257 uint64_t HeaderSize);
258 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Dan Gohman18eafb62017-02-22 01:23:18 +0000259};
Sam Clegg9e15f352017-06-03 02:01:24 +0000260
Dan Gohman18eafb62017-02-22 01:23:18 +0000261} // end anonymous namespace
262
263WasmObjectWriter::~WasmObjectWriter() {}
264
Dan Gohmand934cb82017-02-24 23:18:00 +0000265// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
266static unsigned PaddingFor5ByteULEB128(uint32_t X) {
267 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
268}
269
270// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
271static unsigned PaddingFor5ByteSLEB128(int32_t X) {
272 return 5 - getSLEB128Size(X);
273}
274
275// Write out a section header and a patchable section size field.
276void WasmObjectWriter::startSection(SectionBookkeeping &Section,
277 unsigned SectionId,
278 const char *Name) {
279 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
280 "Only custom sections can have names");
281
Derek Schuffe2688c42017-03-14 20:23:22 +0000282 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000283
284 Section.SizeOffset = getStream().tell();
285
286 // The section size. We don't know the size yet, so reserve enough space
287 // for any 32-bit value; we'll patch it later.
288 encodeULEB128(UINT32_MAX, getStream());
289
290 // The position where the section starts, for measuring its size.
291 Section.ContentsOffset = getStream().tell();
292
293 // Custom sections in wasm also have a string identifier.
294 if (SectionId == wasm::WASM_SEC_CUSTOM) {
295 encodeULEB128(strlen(Name), getStream());
296 writeBytes(Name);
297 }
298}
299
300// Now that the section is complete and we know how big it is, patch up the
301// section size field at the start of the section.
302void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
303 uint64_t Size = getStream().tell() - Section.ContentsOffset;
304 if (uint32_t(Size) != Size)
305 report_fatal_error("section size does not fit in a uint32_t");
306
307 unsigned Padding = PaddingFor5ByteULEB128(Size);
308
309 // Write the final section size to the payload_len field, which follows
310 // the section id byte.
311 uint8_t Buffer[16];
312 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
313 assert(SizeLen == 5);
314 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
315}
316
Dan Gohman18eafb62017-02-22 01:23:18 +0000317// Emit the Wasm header.
318void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000319 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
320 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000321}
322
323void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
324 const MCAsmLayout &Layout) {
325}
326
327void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
328 const MCAsmLayout &Layout,
329 const MCFragment *Fragment,
330 const MCFixup &Fixup, MCValue Target,
331 bool &IsPCRel, uint64_t &FixedValue) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000332 MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
333 uint64_t C = Target.getConstant();
334 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
335 MCContext &Ctx = Asm.getContext();
336
337 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
338 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
339 "Should not have constructed this");
340
341 // Let A, B and C being the components of Target and R be the location of
342 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
343 // If it is pcrel, we want to compute (A - B + C - R).
344
345 // In general, Wasm has no relocations for -B. It can only represent (A + C)
346 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
347 // replace B to implement it: (A - R - K + C)
348 if (IsPCRel) {
349 Ctx.reportError(
350 Fixup.getLoc(),
351 "No relocation available to represent this relative expression");
352 return;
353 }
354
355 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
356
357 if (SymB.isUndefined()) {
358 Ctx.reportError(Fixup.getLoc(),
359 Twine("symbol '") + SymB.getName() +
360 "' can not be undefined in a subtraction expression");
361 return;
362 }
363
364 assert(!SymB.isAbsolute() && "Should have been folded");
365 const MCSection &SecB = SymB.getSection();
366 if (&SecB != &FixupSection) {
367 Ctx.reportError(Fixup.getLoc(),
368 "Cannot represent a difference across sections");
369 return;
370 }
371
372 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
373 uint64_t K = SymBOffset - FixupOffset;
374 IsPCRel = true;
375 C -= K;
376 }
377
378 // We either rejected the fixup or folded B into C at this point.
379 const MCSymbolRefExpr *RefA = Target.getSymA();
380 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
381
382 bool ViaWeakRef = false;
383 if (SymA && SymA->isVariable()) {
384 const MCExpr *Expr = SymA->getVariableValue();
385 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
386 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
387 SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
388 ViaWeakRef = true;
389 }
390 }
391 }
392
393 // Put any constant offset in an addend. Offsets can be negative, and
394 // LLVM expects wrapping, in contrast to wasm's immediates which can't
395 // be negative and don't wrap.
396 FixedValue = 0;
397
398 if (SymA) {
399 if (ViaWeakRef)
400 llvm_unreachable("weakref used in reloc not yet implemented");
401 else
402 SymA->setUsedInReloc();
403 }
404
Dan Gohmand934cb82017-02-24 23:18:00 +0000405 unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel);
Dan Gohmand934cb82017-02-24 23:18:00 +0000406 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
407
408 if (FixupSection.hasInstructions())
409 CodeRelocations.push_back(Rec);
410 else
411 DataRelocations.push_back(Rec);
412}
413
Dan Gohmand934cb82017-02-24 23:18:00 +0000414// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
415// to allow patching.
416static void
417WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
418 uint8_t Buffer[5];
419 unsigned Padding = PaddingFor5ByteULEB128(X);
420 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
421 assert(SizeLen == 5);
422 Stream.pwrite((char *)Buffer, SizeLen, Offset);
423}
424
425// Write X as an signed LEB value at offset Offset in Stream, padded
426// to allow patching.
427static void
428WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
429 uint8_t Buffer[5];
430 unsigned Padding = PaddingFor5ByteSLEB128(X);
431 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
432 assert(SizeLen == 5);
433 Stream.pwrite((char *)Buffer, SizeLen, Offset);
434}
435
436// Write X as a plain integer value at offset Offset in Stream.
437static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
438 uint8_t Buffer[4];
439 support::endian::write32le(Buffer, X);
440 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
441}
442
443// Compute a value to write into the code at the location covered
444// by RelEntry. This value isn't used by the static linker, since
445// we have addends; it just serves to make the code more readable
446// and to make standalone wasm modules directly usable.
447static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
448 const MCSymbolWasm *Sym = RelEntry.Symbol;
449
450 // For undefined symbols, use a hopefully invalid value.
451 if (!Sym->isDefined(false))
452 return UINT32_MAX;
453
454 MCSectionWasm &Section =
455 cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
456 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
457
458 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
459 uint32_t Value = Address;
460
461 return Value;
462}
463
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000464uint32_t WasmObjectWriter::getRelocationIndexValue(
465 const WasmRelocationEntry &RelEntry) {
466 switch (RelEntry.Type) {
467 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
468 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
469 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
470 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
471 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
472 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
473 assert(SymbolIndices.count(RelEntry.Symbol));
474 return SymbolIndices[RelEntry.Symbol];
475 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
476 assert(TypeIndices.count(RelEntry.Symbol));
477 return TypeIndices[RelEntry.Symbol];
478 default:
479 llvm_unreachable("invalid relocation type");
480 }
481}
482
Dan Gohmand934cb82017-02-24 23:18:00 +0000483// Apply the portions of the relocation records that we can handle ourselves
484// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000485void WasmObjectWriter::applyRelocations(
486 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
487 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000488 for (const WasmRelocationEntry &RelEntry : Relocations) {
489 uint64_t Offset = ContentsOffset +
490 RelEntry.FixupSection->getSectionOffset() +
491 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000492
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000493 switch (RelEntry.Type) {
494 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
495 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
496 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB: {
497 uint32_t Index = getRelocationIndexValue(RelEntry);
498 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000499 break;
500 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000501 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
502 uint32_t Index = getRelocationIndexValue(RelEntry);
503 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000504 break;
505 }
506 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
507 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000508 WritePatchableSLEB(Stream, Value, Offset);
509 break;
510 }
511 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
512 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000513 WritePatchableLEB(Stream, Value, Offset);
514 break;
515 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000516 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
517 uint32_t Value = ProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000518 WriteI32(Stream, Value, Offset);
519 break;
520 }
521 default:
Dan Gohmand934cb82017-02-24 23:18:00 +0000522 llvm_unreachable("unsupported relocation type");
523 }
524 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000525}
526
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000527// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000528// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000529void WasmObjectWriter::writeRelocations(
530 ArrayRef<WasmRelocationEntry> Relocations, uint64_t HeaderSize) {
531 raw_pwrite_stream &Stream = getStream();
532 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000533
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000534 uint64_t Offset = RelEntry.Offset +
535 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
536 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000537
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000538 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000539 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000540 encodeULEB128(Index, Stream);
541 if (RelEntry.hasAddend())
542 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000543 }
544}
545
Sam Clegg9e15f352017-06-03 02:01:24 +0000546void WasmObjectWriter::writeTypeSection(
547 const SmallVector<WasmFunctionType, 4> &FunctionTypes) {
548 if (FunctionTypes.empty())
549 return;
550
551 SectionBookkeeping Section;
552 startSection(Section, wasm::WASM_SEC_TYPE);
553
554 encodeULEB128(FunctionTypes.size(), getStream());
555
556 for (const WasmFunctionType &FuncTy : FunctionTypes) {
557 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
558 encodeULEB128(FuncTy.Params.size(), getStream());
559 for (wasm::ValType Ty : FuncTy.Params)
560 writeValueType(Ty);
561 encodeULEB128(FuncTy.Returns.size(), getStream());
562 for (wasm::ValType Ty : FuncTy.Returns)
563 writeValueType(Ty);
564 }
565
566 endSection(Section);
567}
568
569void WasmObjectWriter::writeImportSection(
570 const SmallVector<WasmImport, 4> &Imports) {
571 if (Imports.empty())
572 return;
573
574 SectionBookkeeping Section;
575 startSection(Section, wasm::WASM_SEC_IMPORT);
576
577 encodeULEB128(Imports.size(), getStream());
578 for (const WasmImport &Import : Imports) {
579 StringRef ModuleName = Import.ModuleName;
580 encodeULEB128(ModuleName.size(), getStream());
581 writeBytes(ModuleName);
582
583 StringRef FieldName = Import.FieldName;
584 encodeULEB128(FieldName.size(), getStream());
585 writeBytes(FieldName);
586
587 encodeULEB128(Import.Kind, getStream());
588
589 switch (Import.Kind) {
590 case wasm::WASM_EXTERNAL_FUNCTION:
591 encodeULEB128(Import.Type, getStream());
592 break;
593 case wasm::WASM_EXTERNAL_GLOBAL:
594 encodeSLEB128(int32_t(Import.Type), getStream());
595 encodeULEB128(0, getStream()); // mutability
596 break;
597 default:
598 llvm_unreachable("unsupported import kind");
599 }
600 }
601
602 endSection(Section);
603}
604
605void WasmObjectWriter::writeFunctionSection(
606 const SmallVector<WasmFunction, 4> &Functions) {
607 if (Functions.empty())
608 return;
609
610 SectionBookkeeping Section;
611 startSection(Section, wasm::WASM_SEC_FUNCTION);
612
613 encodeULEB128(Functions.size(), getStream());
614 for (const WasmFunction &Func : Functions)
615 encodeULEB128(Func.Type, getStream());
616
617 endSection(Section);
618}
619
620void WasmObjectWriter::writeTableSection(
621 const SmallVector<uint32_t, 4> &TableElems) {
622 // For now, always emit the table section, since indirect calls are not
623 // valid without it. In the future, we could perhaps be more clever and omit
624 // it if there are no indirect calls.
625 SectionBookkeeping Section;
626 startSection(Section, wasm::WASM_SEC_TABLE);
627
628 // The number of tables, fixed to 1 for now.
629 encodeULEB128(1, getStream());
630
631 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream());
632
633 encodeULEB128(0, getStream()); // flags
634 encodeULEB128(TableElems.size(), getStream()); // initial
635
636 endSection(Section);
637}
638
639void WasmObjectWriter::writeMemorySection(
640 const SmallVector<char, 0> &DataBytes) {
641 // For now, always emit the memory section, since loads and stores are not
642 // valid without it. In the future, we could perhaps be more clever and omit
643 // it if there are no loads or stores.
644 SectionBookkeeping Section;
645 uint32_t NumPages =
646 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
647
648 startSection(Section, wasm::WASM_SEC_MEMORY);
649 encodeULEB128(1, getStream()); // number of memory spaces
650
651 encodeULEB128(0, getStream()); // flags
652 encodeULEB128(NumPages, getStream()); // initial
653
654 endSection(Section);
655}
656
657void WasmObjectWriter::writeGlobalSection(
658 const SmallVector<WasmGlobal, 4> &Globals) {
659 if (Globals.empty())
660 return;
661
662 SectionBookkeeping Section;
663 startSection(Section, wasm::WASM_SEC_GLOBAL);
664
665 encodeULEB128(Globals.size(), getStream());
666 for (const WasmGlobal &Global : Globals) {
667 writeValueType(Global.Type);
668 write8(Global.IsMutable);
669
670 if (Global.HasImport) {
671 assert(Global.InitialValue == 0);
672 write8(wasm::WASM_OPCODE_GET_GLOBAL);
673 encodeULEB128(Global.ImportIndex, getStream());
674 } else {
675 assert(Global.ImportIndex == 0);
676 write8(wasm::WASM_OPCODE_I32_CONST);
677 encodeSLEB128(Global.InitialValue, getStream()); // offset
678 }
679 write8(wasm::WASM_OPCODE_END);
680 }
681
682 endSection(Section);
683}
684
685void WasmObjectWriter::writeExportSection(
686 const SmallVector<WasmExport, 4> &Exports) {
687 if (Exports.empty())
688 return;
689
690 SectionBookkeeping Section;
691 startSection(Section, wasm::WASM_SEC_EXPORT);
692
693 encodeULEB128(Exports.size(), getStream());
694 for (const WasmExport &Export : Exports) {
695 encodeULEB128(Export.FieldName.size(), getStream());
696 writeBytes(Export.FieldName);
697
698 encodeSLEB128(Export.Kind, getStream());
699
700 encodeULEB128(Export.Index, getStream());
701 }
702
703 endSection(Section);
704}
705
706void WasmObjectWriter::writeElemSection(
707 const SmallVector<uint32_t, 4> &TableElems) {
708 if (TableElems.empty())
709 return;
710
711 SectionBookkeeping Section;
712 startSection(Section, wasm::WASM_SEC_ELEM);
713
714 encodeULEB128(1, getStream()); // number of "segments"
715 encodeULEB128(0, getStream()); // the table index
716
717 // init expr for starting offset
718 write8(wasm::WASM_OPCODE_I32_CONST);
719 encodeSLEB128(0, getStream());
720 write8(wasm::WASM_OPCODE_END);
721
722 encodeULEB128(TableElems.size(), getStream());
723 for (uint32_t Elem : TableElems)
724 encodeULEB128(Elem, getStream());
725
726 endSection(Section);
727}
728
729void WasmObjectWriter::writeCodeSection(
730 const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg9e15f352017-06-03 02:01:24 +0000731 const SmallVector<WasmFunction, 4> &Functions) {
732 if (Functions.empty())
733 return;
734
735 SectionBookkeeping Section;
736 startSection(Section, wasm::WASM_SEC_CODE);
737
738 encodeULEB128(Functions.size(), getStream());
739
740 for (const WasmFunction &Func : Functions) {
741 MCSectionWasm &FuncSection =
742 static_cast<MCSectionWasm &>(Func.Sym->getSection());
743
744 if (Func.Sym->isVariable())
745 report_fatal_error("weak symbols not supported yet");
746
747 if (Func.Sym->getOffset() != 0)
748 report_fatal_error("function sections must contain one function each");
749
750 if (!Func.Sym->getSize())
751 report_fatal_error("function symbols must have a size set with .size");
752
753 int64_t Size = 0;
754 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
755 report_fatal_error(".size expression must be evaluatable");
756
757 encodeULEB128(Size, getStream());
758
759 FuncSection.setSectionOffset(getStream().tell() -
760 Section.ContentsOffset);
761
762 Asm.writeSectionData(&FuncSection, Layout);
763 }
764
Sam Clegg9e15f352017-06-03 02:01:24 +0000765 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000766 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000767
768 endSection(Section);
769}
770
771uint64_t WasmObjectWriter::writeDataSection(
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000772 const SmallVector<char, 0> &DataBytes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 if (DataBytes.empty())
774 return 0;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_DATA);
778
779 encodeULEB128(1, getStream()); // count
780 encodeULEB128(0, getStream()); // memory index
781 write8(wasm::WASM_OPCODE_I32_CONST);
782 encodeSLEB128(0, getStream()); // offset
783 write8(wasm::WASM_OPCODE_END);
784 encodeULEB128(DataBytes.size(), getStream()); // size
785 uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset;
786 writeBytes(DataBytes); // data
787
788 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000789 applyRelocations(DataRelocations, Section.ContentsOffset + HeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000790
791 endSection(Section);
792 return HeaderSize;
793}
794
795void WasmObjectWriter::writeNameSection(
796 const SmallVector<WasmFunction, 4> &Functions,
797 const SmallVector<WasmImport, 4> &Imports,
798 unsigned NumFuncImports) {
799 uint32_t TotalFunctions = NumFuncImports + Functions.size();
800 if (TotalFunctions == 0)
801 return;
802
803 SectionBookkeeping Section;
804 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
805 SectionBookkeeping SubSection;
806 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
807
808 encodeULEB128(TotalFunctions, getStream());
809 uint32_t Index = 0;
810 for (const WasmImport &Import : Imports) {
811 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
812 encodeULEB128(Index, getStream());
813 encodeULEB128(Import.FieldName.size(), getStream());
814 writeBytes(Import.FieldName);
815 ++Index;
816 }
817 }
818 for (const WasmFunction &Func : Functions) {
819 encodeULEB128(Index, getStream());
820 encodeULEB128(Func.Sym->getName().size(), getStream());
821 writeBytes(Func.Sym->getName());
822 ++Index;
823 }
824
825 endSection(SubSection);
826 endSection(Section);
827}
828
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000829void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000830 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
831 // for descriptions of the reloc sections.
832
833 if (CodeRelocations.empty())
834 return;
835
836 SectionBookkeeping Section;
837 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
838
839 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000840 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000841
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000842 writeRelocations(CodeRelocations, 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000843
844 endSection(Section);
845}
846
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000847void WasmObjectWriter::writeDataRelocSection(uint64_t DataSectionHeaderSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000848 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
849 // for descriptions of the reloc sections.
850
851 if (DataRelocations.empty())
852 return;
853
854 SectionBookkeeping Section;
855 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
856
857 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
858 encodeULEB128(DataRelocations.size(), getStream());
859
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000860 writeRelocations(DataRelocations, DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +0000861
862 endSection(Section);
863}
864
865void WasmObjectWriter::writeLinkingMetaDataSection(
866 bool HasStackPointer, uint32_t StackPointerGlobal) {
867 if (!HasStackPointer)
868 return;
869 SectionBookkeeping Section;
870 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
871
872 encodeULEB128(1, getStream()); // count
873
874 encodeULEB128(wasm::WASM_STACK_POINTER, getStream()); // type
875 encodeULEB128(StackPointerGlobal, getStream()); // id
876
877 endSection(Section);
878}
879
Dan Gohman18eafb62017-02-22 01:23:18 +0000880void WasmObjectWriter::writeObject(MCAssembler &Asm,
881 const MCAsmLayout &Layout) {
Dan Gohman82607f52017-02-24 23:46:05 +0000882 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000883 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000884
885 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000886 SmallVector<WasmFunctionType, 4> FunctionTypes;
887 SmallVector<WasmFunction, 4> Functions;
888 SmallVector<uint32_t, 4> TableElems;
889 SmallVector<WasmGlobal, 4> Globals;
890 SmallVector<WasmImport, 4> Imports;
891 SmallVector<WasmExport, 4> Exports;
Dan Gohmand934cb82017-02-24 23:18:00 +0000892 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
893 unsigned NumFuncImports = 0;
894 unsigned NumGlobalImports = 0;
895 SmallVector<char, 0> DataBytes;
Dan Gohman970d02c2017-03-30 23:58:19 +0000896 uint32_t StackPointerGlobal = 0;
897 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000898
899 // Populate the IsAddressTaken set.
900 for (WasmRelocationEntry RelEntry : CodeRelocations) {
901 switch (RelEntry.Type) {
902 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
903 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
904 IsAddressTaken.insert(RelEntry.Symbol);
905 break;
906 default:
907 break;
908 }
909 }
910 for (WasmRelocationEntry RelEntry : DataRelocations) {
911 switch (RelEntry.Type) {
912 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
913 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
914 IsAddressTaken.insert(RelEntry.Symbol);
915 break;
916 default:
917 break;
918 }
919 }
920
921 // Populate the Imports set.
922 for (const MCSymbol &S : Asm.symbols()) {
923 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Derek Schuffb8795392017-03-16 20:49:48 +0000924 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000925
926 if (WS.isFunction()) {
927 // Prepare the function's type, if we haven't seen it yet.
928 WasmFunctionType F;
929 F.Returns = WS.getReturns();
930 F.Params = WS.getParams();
931 auto Pair =
932 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
933 if (Pair.second)
934 FunctionTypes.push_back(F);
935
936 Type = Pair.first->second;
937 } else {
Derek Schuffb8795392017-03-16 20:49:48 +0000938 Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +0000939 }
940
941 // If the symbol is not defined in this translation unit, import it.
942 if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
943 WasmImport Import;
944 Import.ModuleName = WS.getModuleName();
945 Import.FieldName = WS.getName();
946
947 if (WS.isFunction()) {
948 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
949 Import.Type = Type;
950 SymbolIndices[&WS] = NumFuncImports;
951 ++NumFuncImports;
952 } else {
953 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
954 Import.Type = Type;
955 SymbolIndices[&WS] = NumGlobalImports;
956 ++NumGlobalImports;
957 }
958
959 Imports.push_back(Import);
960 }
961 }
962
Dan Gohman82607f52017-02-24 23:46:05 +0000963 // In the special .global_variables section, we've encoded global
964 // variables used by the function. Translate them into the Globals
965 // list.
966 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
967 if (!GlobalVars->getFragmentList().empty()) {
968 if (GlobalVars->getFragmentList().size() != 1)
969 report_fatal_error("only one .global_variables fragment supported");
970 const MCFragment &Frag = *GlobalVars->begin();
971 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
972 report_fatal_error("only data supported in .global_variables");
973 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
974 if (!DataFrag.getFixups().empty())
975 report_fatal_error("fixups not supported in .global_variables");
976 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +0000977 for (const uint8_t *p = (const uint8_t *)Contents.data(),
978 *end = (const uint8_t *)Contents.data() + Contents.size();
979 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +0000980 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +0000981 if (end - p < 3)
982 report_fatal_error("truncated global variable encoding");
983 G.Type = wasm::ValType(int8_t(*p++));
984 G.IsMutable = bool(*p++);
985 G.HasImport = bool(*p++);
986 if (G.HasImport) {
987 G.InitialValue = 0;
988
989 WasmImport Import;
990 Import.ModuleName = (const char *)p;
991 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
992 if (!nul)
993 report_fatal_error("global module name must be nul-terminated");
994 p = nul + 1;
995 nul = (const uint8_t *)memchr(p, '\0', end - p);
996 if (!nul)
997 report_fatal_error("global base name must be nul-terminated");
998 Import.FieldName = (const char *)p;
999 p = nul + 1;
1000
1001 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1002 Import.Type = int32_t(G.Type);
1003
1004 G.ImportIndex = NumGlobalImports;
1005 ++NumGlobalImports;
1006
1007 Imports.push_back(Import);
1008 } else {
1009 unsigned n;
1010 G.InitialValue = decodeSLEB128(p, &n);
1011 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001012 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001013 report_fatal_error("global initial value must be valid SLEB128");
1014 p += n;
1015 }
Dan Gohman82607f52017-02-24 23:46:05 +00001016 Globals.push_back(G);
1017 }
1018 }
1019
Dan Gohman970d02c2017-03-30 23:58:19 +00001020 // In the special .stack_pointer section, we've encoded the stack pointer
1021 // index.
1022 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
1023 if (!StackPtr->getFragmentList().empty()) {
1024 if (StackPtr->getFragmentList().size() != 1)
1025 report_fatal_error("only one .stack_pointer fragment supported");
1026 const MCFragment &Frag = *StackPtr->begin();
1027 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1028 report_fatal_error("only data supported in .stack_pointer");
1029 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1030 if (!DataFrag.getFixups().empty())
1031 report_fatal_error("fixups not supported in .stack_pointer");
1032 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1033 if (Contents.size() != 4)
1034 report_fatal_error("only one entry supported in .stack_pointer");
1035 HasStackPointer = true;
1036 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1037 }
1038
Dan Gohmand934cb82017-02-24 23:18:00 +00001039 // Handle defined symbols.
1040 for (const MCSymbol &S : Asm.symbols()) {
1041 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1042 // or used in relocations.
1043 if (S.isTemporary() && S.getName().empty())
1044 continue;
1045 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1046 unsigned Index;
1047 if (WS.isFunction()) {
1048 // Prepare the function's type, if we haven't seen it yet.
1049 WasmFunctionType F;
1050 F.Returns = WS.getReturns();
1051 F.Params = WS.getParams();
1052 auto Pair =
1053 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1054 if (Pair.second)
1055 FunctionTypes.push_back(F);
1056
Derek Schuffb8795392017-03-16 20:49:48 +00001057 int32_t Type = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001058
1059 if (WS.isDefined(/*SetUsed=*/false)) {
1060 // A definition. Take the next available index.
1061 Index = NumFuncImports + Functions.size();
1062
1063 // Prepare the function.
1064 WasmFunction Func;
1065 Func.Type = Type;
1066 Func.Sym = &WS;
1067 SymbolIndices[&WS] = Index;
1068 Functions.push_back(Func);
1069 } else {
1070 // An import; the index was assigned above.
1071 Index = SymbolIndices.find(&WS)->second;
1072 }
1073
1074 // If needed, prepare the function to be called indirectly.
1075 if (IsAddressTaken.count(&WS))
1076 TableElems.push_back(Index);
1077 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001078 if (WS.isTemporary() && !WS.getSize())
1079 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001080
1081 if (WS.isDefined(false)) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001082 if (WS.getOffset() != 0)
1083 report_fatal_error("data sections must contain one variable each: " +
1084 WS.getName());
1085 if (!WS.getSize())
1086 report_fatal_error("data symbols must have a size set with .size: " +
1087 WS.getName());
1088
1089 int64_t Size = 0;
1090 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1091 report_fatal_error(".size expression must be evaluatable");
1092
Dan Gohmand934cb82017-02-24 23:18:00 +00001093 MCSectionWasm &DataSection =
1094 static_cast<MCSectionWasm &>(WS.getSection());
1095
1096 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
1097 report_fatal_error("data sections must contain at most one variable");
1098
1099 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
1100
1101 DataSection.setSectionOffset(DataBytes.size());
1102
1103 for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
1104 I != E; ++I) {
1105 const MCFragment &Frag = *I;
1106 if (Frag.hasInstructions())
1107 report_fatal_error("only data supported in data sections");
1108
1109 if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
1110 if (Align->getValueSize() != 1)
1111 report_fatal_error("only byte values supported for alignment");
1112 // If nops are requested, use zeros, as this is the data section.
1113 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
1114 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
1115 Align->getAlignment()),
1116 DataBytes.size() +
1117 Align->getMaxBytesToEmit());
1118 DataBytes.resize(Size, Value);
1119 } else if (const MCFillFragment *Fill =
1120 dyn_cast<MCFillFragment>(&Frag)) {
1121 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
1122 } else {
1123 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
1124 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1125
1126 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
1127 }
1128 }
1129
Sam Clegg1c154a62017-05-25 21:08:07 +00001130 // For each global, prepare a corresponding wasm global holding its
1131 // address. For externals these will also be named exports.
1132 Index = NumGlobalImports + Globals.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001133
Sam Clegg1c154a62017-05-25 21:08:07 +00001134 WasmGlobal Global;
1135 Global.Type = PtrType;
1136 Global.IsMutable = false;
1137 Global.HasImport = false;
1138 Global.InitialValue = DataSection.getSectionOffset();
1139 Global.ImportIndex = 0;
1140 SymbolIndices[&WS] = Index;
1141 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001142 }
1143 }
1144
1145 // If the symbol is visible outside this translation unit, export it.
1146 if (WS.isExternal()) {
1147 assert(WS.isDefined(false));
1148 WasmExport Export;
1149 Export.FieldName = WS.getName();
1150 Export.Index = Index;
1151
1152 if (WS.isFunction())
1153 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1154 else
1155 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1156
1157 Exports.push_back(Export);
1158 }
1159 }
1160
1161 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001162 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1163 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1164 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001165
Dan Gohmand934cb82017-02-24 23:18:00 +00001166 WasmFunctionType F;
1167 F.Returns = Fixup.Symbol->getReturns();
1168 F.Params = Fixup.Symbol->getParams();
1169 auto Pair =
1170 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1171 if (Pair.second)
1172 FunctionTypes.push_back(F);
1173
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001174 TypeIndices[Fixup.Symbol] = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001175 }
1176
Dan Gohman18eafb62017-02-22 01:23:18 +00001177 // Write out the Wasm header.
1178 writeHeader(Asm);
1179
Sam Clegg9e15f352017-06-03 02:01:24 +00001180 writeTypeSection(FunctionTypes);
1181 writeImportSection(Imports);
1182 writeFunctionSection(Functions);
1183 writeTableSection(TableElems);
1184 writeMemorySection(DataBytes);
1185 writeGlobalSection(Globals);
1186 writeExportSection(Exports);
1187 // TODO: Start Section
1188 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001189 writeCodeSection(Asm, Layout, Functions);
1190 uint64_t DataSectionHeaderSize = writeDataSection(DataBytes);
Sam Clegg9e15f352017-06-03 02:01:24 +00001191 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001192 writeCodeRelocSection();
1193 writeDataRelocSection(DataSectionHeaderSize);
Sam Clegg9e15f352017-06-03 02:01:24 +00001194 writeLinkingMetaDataSection(HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001195
Dan Gohmand934cb82017-02-24 23:18:00 +00001196 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001197 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001198}
1199
1200MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1201 raw_pwrite_stream &OS) {
1202 return new WasmObjectWriter(MOTW, OS);
1203}