blob: 616fe0f2e629627d904c42881352562aa272e876 [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"
Dan Gohman18eafb62017-02-22 01:23:18 +000016#include "llvm/MC/MCAsmBackend.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCAsmLayout.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
23#include "llvm/MC/MCObjectFileInfo.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionWasm.h"
26#include "llvm/MC/MCSymbolWasm.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000029#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000031#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000032#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000033#include "llvm/Support/StringSaver.h"
Dan Gohman7ea5adf2017-02-22 18:50:20 +000034#include "llvm/Support/Wasm.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000035#include <vector>
36
37using namespace llvm;
38
39#undef DEBUG_TYPE
40#define DEBUG_TYPE "reloc-info"
41
42namespace {
Dan Gohmand934cb82017-02-24 23:18:00 +000043// For patching purposes, we need to remember where each section starts, both
44// for patching up the section size field, and for patching up references to
45// locations within the section.
46struct SectionBookkeeping {
47 // Where the size of the section is written.
48 uint64_t SizeOffset;
49 // Where the contents of the section starts (after the header).
50 uint64_t ContentsOffset;
51};
52
Dan Gohman18eafb62017-02-22 01:23:18 +000053class WasmObjectWriter : public MCObjectWriter {
54 /// Helper struct for containing some precomputed information on symbols.
55 struct WasmSymbolData {
56 const MCSymbolWasm *Symbol;
57 StringRef Name;
58
59 // Support lexicographic sorting.
60 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
61 };
62
63 /// The target specific Wasm writer instance.
64 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
65
Dan Gohmand934cb82017-02-24 23:18:00 +000066 // Relocations for fixing up references in the code section.
67 std::vector<WasmRelocationEntry> CodeRelocations;
68
69 // Relocations for fixing up references in the data section.
70 std::vector<WasmRelocationEntry> DataRelocations;
71
72 // Fixups for call_indirect type indices.
Dan Gohman970d02c2017-03-30 23:58:19 +000073 std::vector<WasmRelocationEntry> TypeIndexFixups;
Dan Gohmand934cb82017-02-24 23:18:00 +000074
75 // Index values to use for fixing up call_indirect type indices.
76 std::vector<uint32_t> TypeIndexFixupTypes;
77
Dan Gohman18eafb62017-02-22 01:23:18 +000078 // TargetObjectWriter wrappers.
79 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
80 unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
81 const MCFixup &Fixup, bool IsPCRel) const {
82 return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
83 }
84
Dan Gohmand934cb82017-02-24 23:18:00 +000085 void startSection(SectionBookkeeping &Section, unsigned SectionId,
86 const char *Name = nullptr);
87 void endSection(SectionBookkeeping &Section);
88
Dan Gohman18eafb62017-02-22 01:23:18 +000089public:
90 WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
91 : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {}
92
Dan Gohmand934cb82017-02-24 23:18:00 +000093private:
Dan Gohman18eafb62017-02-22 01:23:18 +000094 void reset() override {
95 MCObjectWriter::reset();
96 }
97
98 ~WasmObjectWriter() override;
99
100 void writeHeader(const MCAssembler &Asm);
101
Derek Schuffe2688c42017-03-14 20:23:22 +0000102 void writeValueType(wasm::ValType Ty) {
103 encodeSLEB128(int32_t(Ty), getStream());
104 }
105
Dan Gohman18eafb62017-02-22 01:23:18 +0000106 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
107 const MCFragment *Fragment, const MCFixup &Fixup,
108 MCValue Target, bool &IsPCRel,
109 uint64_t &FixedValue) override;
110
111 void executePostLayoutBinding(MCAssembler &Asm,
112 const MCAsmLayout &Layout) override;
113
114 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
115};
116} // end anonymous namespace
117
118WasmObjectWriter::~WasmObjectWriter() {}
119
Dan Gohmand934cb82017-02-24 23:18:00 +0000120// Return the padding size to write a 32-bit value into a 5-byte ULEB128.
121static unsigned PaddingFor5ByteULEB128(uint32_t X) {
122 return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u);
123}
124
125// Return the padding size to write a 32-bit value into a 5-byte SLEB128.
126static unsigned PaddingFor5ByteSLEB128(int32_t X) {
127 return 5 - getSLEB128Size(X);
128}
129
130// Write out a section header and a patchable section size field.
131void WasmObjectWriter::startSection(SectionBookkeeping &Section,
132 unsigned SectionId,
133 const char *Name) {
134 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
135 "Only custom sections can have names");
136
Derek Schuffe2688c42017-03-14 20:23:22 +0000137 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000138
139 Section.SizeOffset = getStream().tell();
140
141 // The section size. We don't know the size yet, so reserve enough space
142 // for any 32-bit value; we'll patch it later.
143 encodeULEB128(UINT32_MAX, getStream());
144
145 // The position where the section starts, for measuring its size.
146 Section.ContentsOffset = getStream().tell();
147
148 // Custom sections in wasm also have a string identifier.
149 if (SectionId == wasm::WASM_SEC_CUSTOM) {
150 encodeULEB128(strlen(Name), getStream());
151 writeBytes(Name);
152 }
153}
154
155// Now that the section is complete and we know how big it is, patch up the
156// section size field at the start of the section.
157void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
158 uint64_t Size = getStream().tell() - Section.ContentsOffset;
159 if (uint32_t(Size) != Size)
160 report_fatal_error("section size does not fit in a uint32_t");
161
162 unsigned Padding = PaddingFor5ByteULEB128(Size);
163
164 // Write the final section size to the payload_len field, which follows
165 // the section id byte.
166 uint8_t Buffer[16];
167 unsigned SizeLen = encodeULEB128(Size, Buffer, Padding);
168 assert(SizeLen == 5);
169 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
170}
171
Dan Gohman18eafb62017-02-22 01:23:18 +0000172// Emit the Wasm header.
173void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000174 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
175 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000176}
177
178void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
179 const MCAsmLayout &Layout) {
180}
181
182void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
183 const MCAsmLayout &Layout,
184 const MCFragment *Fragment,
185 const MCFixup &Fixup, MCValue Target,
186 bool &IsPCRel, uint64_t &FixedValue) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000187 MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
188 uint64_t C = Target.getConstant();
189 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
190 MCContext &Ctx = Asm.getContext();
191
192 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
193 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
194 "Should not have constructed this");
195
196 // Let A, B and C being the components of Target and R be the location of
197 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
198 // If it is pcrel, we want to compute (A - B + C - R).
199
200 // In general, Wasm has no relocations for -B. It can only represent (A + C)
201 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
202 // replace B to implement it: (A - R - K + C)
203 if (IsPCRel) {
204 Ctx.reportError(
205 Fixup.getLoc(),
206 "No relocation available to represent this relative expression");
207 return;
208 }
209
210 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
211
212 if (SymB.isUndefined()) {
213 Ctx.reportError(Fixup.getLoc(),
214 Twine("symbol '") + SymB.getName() +
215 "' can not be undefined in a subtraction expression");
216 return;
217 }
218
219 assert(!SymB.isAbsolute() && "Should have been folded");
220 const MCSection &SecB = SymB.getSection();
221 if (&SecB != &FixupSection) {
222 Ctx.reportError(Fixup.getLoc(),
223 "Cannot represent a difference across sections");
224 return;
225 }
226
227 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
228 uint64_t K = SymBOffset - FixupOffset;
229 IsPCRel = true;
230 C -= K;
231 }
232
233 // We either rejected the fixup or folded B into C at this point.
234 const MCSymbolRefExpr *RefA = Target.getSymA();
235 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
236
237 bool ViaWeakRef = false;
238 if (SymA && SymA->isVariable()) {
239 const MCExpr *Expr = SymA->getVariableValue();
240 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
241 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
242 SymA = cast<MCSymbolWasm>(&Inner->getSymbol());
243 ViaWeakRef = true;
244 }
245 }
246 }
247
248 // Put any constant offset in an addend. Offsets can be negative, and
249 // LLVM expects wrapping, in contrast to wasm's immediates which can't
250 // be negative and don't wrap.
251 FixedValue = 0;
252
253 if (SymA) {
254 if (ViaWeakRef)
255 llvm_unreachable("weakref used in reloc not yet implemented");
256 else
257 SymA->setUsedInReloc();
258 }
259
260 if (RefA) {
261 if (RefA->getKind() == MCSymbolRefExpr::VK_WebAssembly_TYPEINDEX) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000262 assert(C == 0);
263 WasmRelocationEntry Rec(FixupOffset, SymA, C,
264 wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB,
265 &FixupSection);
266 TypeIndexFixups.push_back(Rec);
Dan Gohmand934cb82017-02-24 23:18:00 +0000267 return;
268 }
269 }
270
271 unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel);
272
273 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
274
275 if (FixupSection.hasInstructions())
276 CodeRelocations.push_back(Rec);
277 else
278 DataRelocations.push_back(Rec);
279}
280
281namespace {
282
Dan Gohmand37dc2f2017-02-27 22:41:39 +0000283// The signature of a wasm function, in a struct capable of being used as a
284// DenseMap key.
Dan Gohmand934cb82017-02-24 23:18:00 +0000285struct WasmFunctionType {
286 // Support empty and tombstone instances, needed by DenseMap.
287 enum { Plain, Empty, Tombstone } State;
288
289 // The return types of the function.
Derek Schuffe2688c42017-03-14 20:23:22 +0000290 SmallVector<wasm::ValType, 1> Returns;
Dan Gohmand934cb82017-02-24 23:18:00 +0000291
292 // The parameter types of the function.
Derek Schuffe2688c42017-03-14 20:23:22 +0000293 SmallVector<wasm::ValType, 4> Params;
Dan Gohmand934cb82017-02-24 23:18:00 +0000294
295 WasmFunctionType() : State(Plain) {}
296
297 bool operator==(const WasmFunctionType &Other) const {
298 return State == Other.State && Returns == Other.Returns &&
299 Params == Other.Params;
300 }
301};
302
303// Traits for using WasmFunctionType in a DenseMap.
304struct WasmFunctionTypeDenseMapInfo {
305 static WasmFunctionType getEmptyKey() {
306 WasmFunctionType FuncTy;
307 FuncTy.State = WasmFunctionType::Empty;
308 return FuncTy;
309 }
310 static WasmFunctionType getTombstoneKey() {
311 WasmFunctionType FuncTy;
312 FuncTy.State = WasmFunctionType::Tombstone;
313 return FuncTy;
314 }
315 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
316 uintptr_t Value = FuncTy.State;
Derek Schuffe2688c42017-03-14 20:23:22 +0000317 for (wasm::ValType Ret : FuncTy.Returns)
318 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
319 for (wasm::ValType Param : FuncTy.Params)
320 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
Dan Gohmand934cb82017-02-24 23:18:00 +0000321 return Value;
322 }
323 static bool isEqual(const WasmFunctionType &LHS,
324 const WasmFunctionType &RHS) {
325 return LHS == RHS;
326 }
327};
328
329// A wasm import to be written into the import section.
330struct WasmImport {
331 StringRef ModuleName;
332 StringRef FieldName;
333 unsigned Kind;
Derek Schuff9a4e45a2017-03-23 15:46:47 +0000334 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000335};
336
337// A wasm function to be written into the function section.
338struct WasmFunction {
Derek Schuffb8795392017-03-16 20:49:48 +0000339 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000340 const MCSymbolWasm *Sym;
341};
342
343// A wasm export to be written into the export section.
344struct WasmExport {
345 StringRef FieldName;
346 unsigned Kind;
347 uint32_t Index;
348};
349
350// A wasm global to be written into the global section.
351struct WasmGlobal {
Derek Schuffb8795392017-03-16 20:49:48 +0000352 wasm::ValType Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000353 bool IsMutable;
Dan Gohman970d02c2017-03-30 23:58:19 +0000354 bool HasImport;
355 uint64_t InitialValue;
356 uint32_t ImportIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000357};
358
Dan Gohmand37dc2f2017-02-27 22:41:39 +0000359} // end anonymous namespace
Dan Gohmand934cb82017-02-24 23:18:00 +0000360
361// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
362// to allow patching.
363static void
364WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
365 uint8_t Buffer[5];
366 unsigned Padding = PaddingFor5ByteULEB128(X);
367 unsigned SizeLen = encodeULEB128(X, Buffer, Padding);
368 assert(SizeLen == 5);
369 Stream.pwrite((char *)Buffer, SizeLen, Offset);
370}
371
372// Write X as an signed LEB value at offset Offset in Stream, padded
373// to allow patching.
374static void
375WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
376 uint8_t Buffer[5];
377 unsigned Padding = PaddingFor5ByteSLEB128(X);
378 unsigned SizeLen = encodeSLEB128(X, Buffer, Padding);
379 assert(SizeLen == 5);
380 Stream.pwrite((char *)Buffer, SizeLen, Offset);
381}
382
383// Write X as a plain integer value at offset Offset in Stream.
384static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
385 uint8_t Buffer[4];
386 support::endian::write32le(Buffer, X);
387 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
388}
389
390// Compute a value to write into the code at the location covered
391// by RelEntry. This value isn't used by the static linker, since
392// we have addends; it just serves to make the code more readable
393// and to make standalone wasm modules directly usable.
394static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) {
395 const MCSymbolWasm *Sym = RelEntry.Symbol;
396
397 // For undefined symbols, use a hopefully invalid value.
398 if (!Sym->isDefined(false))
399 return UINT32_MAX;
400
401 MCSectionWasm &Section =
402 cast<MCSectionWasm>(RelEntry.Symbol->getSection(false));
403 uint64_t Address = Section.getSectionOffset() + RelEntry.Addend;
404
405 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
406 uint32_t Value = Address;
407
408 return Value;
409}
410
411// Apply the portions of the relocation records that we can handle ourselves
412// directly.
413static void ApplyRelocations(
414 ArrayRef<WasmRelocationEntry> Relocations,
415 raw_pwrite_stream &Stream,
416 DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices,
417 uint64_t ContentsOffset)
418{
419 for (const WasmRelocationEntry &RelEntry : Relocations) {
420 uint64_t Offset = ContentsOffset +
421 RelEntry.FixupSection->getSectionOffset() +
422 RelEntry.Offset;
423 switch (RelEntry.Type) {
424 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: {
Sam Clegg1c154a62017-05-25 21:08:07 +0000425 assert(SymbolIndices.count(RelEntry.Symbol));
Dan Gohmand934cb82017-02-24 23:18:00 +0000426 uint32_t Index = SymbolIndices[RelEntry.Symbol];
427 assert(RelEntry.Addend == 0);
428
429 WritePatchableLEB(Stream, Index, Offset);
430 break;
431 }
432 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: {
Sam Clegg1c154a62017-05-25 21:08:07 +0000433 assert(SymbolIndices.count(RelEntry.Symbol));
Dan Gohmand934cb82017-02-24 23:18:00 +0000434 uint32_t Index = SymbolIndices[RelEntry.Symbol];
435 assert(RelEntry.Addend == 0);
436
437 WritePatchableSLEB(Stream, Index, Offset);
438 break;
439 }
440 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: {
441 uint32_t Value = ProvisionalValue(RelEntry);
442
443 WritePatchableSLEB(Stream, Value, Offset);
444 break;
445 }
446 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: {
447 uint32_t Value = ProvisionalValue(RelEntry);
448
449 WritePatchableLEB(Stream, Value, Offset);
450 break;
451 }
452 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
Sam Clegg1c154a62017-05-25 21:08:07 +0000453 assert(SymbolIndices.count(RelEntry.Symbol));
Dan Gohmand934cb82017-02-24 23:18:00 +0000454 uint32_t Index = SymbolIndices[RelEntry.Symbol];
455 assert(RelEntry.Addend == 0);
456
457 WriteI32(Stream, Index, Offset);
458 break;
459 }
460 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: {
461 uint32_t Value = ProvisionalValue(RelEntry);
462
463 WriteI32(Stream, Value, Offset);
464 break;
465 }
466 default:
467 break;
468 }
469 }
470}
471
472// Write out the portions of the relocation records that the linker will
473// need to handle.
Sam Clegga06de022017-04-28 21:22:38 +0000474static void
475WriteRelocations(ArrayRef<WasmRelocationEntry> Relocations,
476 raw_pwrite_stream &Stream,
477 DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices,
478 uint64_t HeaderSize) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000479 for (const WasmRelocationEntry RelEntry : Relocations) {
480 encodeULEB128(RelEntry.Type, Stream);
481
482 uint64_t Offset = RelEntry.Offset +
Sam Clegga06de022017-04-28 21:22:38 +0000483 RelEntry.FixupSection->getSectionOffset() + HeaderSize;
Sam Clegg1c154a62017-05-25 21:08:07 +0000484 assert(SymbolIndices.count(RelEntry.Symbol));
Dan Gohmand934cb82017-02-24 23:18:00 +0000485 uint32_t Index = SymbolIndices[RelEntry.Symbol];
486 int64_t Addend = RelEntry.Addend;
487
488 switch (RelEntry.Type) {
489 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
490 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
491 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
492 encodeULEB128(Offset, Stream);
493 encodeULEB128(Index, Stream);
494 assert(Addend == 0 && "addends not supported for functions");
495 break;
496 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB:
497 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
498 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
499 encodeULEB128(Offset, Stream);
500 encodeULEB128(Index, Stream);
501 encodeSLEB128(Addend, Stream);
502 break;
503 default:
504 llvm_unreachable("unsupported relocation type");
505 }
506 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000507}
508
Dan Gohman970d02c2017-03-30 23:58:19 +0000509// Write out the the type relocation records that the linker will
510// need to handle.
511static void WriteTypeRelocations(
512 ArrayRef<WasmRelocationEntry> TypeIndexFixups,
513 ArrayRef<uint32_t> TypeIndexFixupTypes,
514 raw_pwrite_stream &Stream)
515{
516 for (size_t i = 0, e = TypeIndexFixups.size(); i < e; ++i) {
517 const WasmRelocationEntry &Fixup = TypeIndexFixups[i];
518 uint32_t Type = TypeIndexFixupTypes[i];
519
520 assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB);
521 assert(Fixup.Addend == 0);
522
523 uint64_t Offset = Fixup.Offset +
524 Fixup.FixupSection->getSectionOffset();
525
526 encodeULEB128(Fixup.Type, Stream);
527 encodeULEB128(Offset, Stream);
528 encodeULEB128(Type, Stream);
529 }
530}
531
Dan Gohman18eafb62017-02-22 01:23:18 +0000532void WasmObjectWriter::writeObject(MCAssembler &Asm,
533 const MCAsmLayout &Layout) {
Dan Gohman82607f52017-02-24 23:46:05 +0000534 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000535 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000536
537 // Collect information from the available symbols.
Derek Schuffb8795392017-03-16 20:49:48 +0000538 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
Dan Gohmand934cb82017-02-24 23:18:00 +0000539 FunctionTypeIndices;
540 SmallVector<WasmFunctionType, 4> FunctionTypes;
541 SmallVector<WasmFunction, 4> Functions;
542 SmallVector<uint32_t, 4> TableElems;
543 SmallVector<WasmGlobal, 4> Globals;
544 SmallVector<WasmImport, 4> Imports;
545 SmallVector<WasmExport, 4> Exports;
546 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
547 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
548 unsigned NumFuncImports = 0;
549 unsigned NumGlobalImports = 0;
550 SmallVector<char, 0> DataBytes;
Dan Gohman970d02c2017-03-30 23:58:19 +0000551 uint32_t StackPointerGlobal = 0;
552 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +0000553
554 // Populate the IsAddressTaken set.
555 for (WasmRelocationEntry RelEntry : CodeRelocations) {
556 switch (RelEntry.Type) {
557 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
558 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB:
559 IsAddressTaken.insert(RelEntry.Symbol);
560 break;
561 default:
562 break;
563 }
564 }
565 for (WasmRelocationEntry RelEntry : DataRelocations) {
566 switch (RelEntry.Type) {
567 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
568 case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32:
569 IsAddressTaken.insert(RelEntry.Symbol);
570 break;
571 default:
572 break;
573 }
574 }
575
576 // Populate the Imports set.
577 for (const MCSymbol &S : Asm.symbols()) {
578 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Derek Schuffb8795392017-03-16 20:49:48 +0000579 int32_t Type;
Dan Gohmand934cb82017-02-24 23:18:00 +0000580
581 if (WS.isFunction()) {
582 // Prepare the function's type, if we haven't seen it yet.
583 WasmFunctionType F;
584 F.Returns = WS.getReturns();
585 F.Params = WS.getParams();
586 auto Pair =
587 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
588 if (Pair.second)
589 FunctionTypes.push_back(F);
590
591 Type = Pair.first->second;
592 } else {
Derek Schuffb8795392017-03-16 20:49:48 +0000593 Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +0000594 }
595
596 // If the symbol is not defined in this translation unit, import it.
597 if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) {
598 WasmImport Import;
599 Import.ModuleName = WS.getModuleName();
600 Import.FieldName = WS.getName();
601
602 if (WS.isFunction()) {
603 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
604 Import.Type = Type;
605 SymbolIndices[&WS] = NumFuncImports;
606 ++NumFuncImports;
607 } else {
608 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
609 Import.Type = Type;
610 SymbolIndices[&WS] = NumGlobalImports;
611 ++NumGlobalImports;
612 }
613
614 Imports.push_back(Import);
615 }
616 }
617
Dan Gohman82607f52017-02-24 23:46:05 +0000618 // In the special .global_variables section, we've encoded global
619 // variables used by the function. Translate them into the Globals
620 // list.
621 MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0);
622 if (!GlobalVars->getFragmentList().empty()) {
623 if (GlobalVars->getFragmentList().size() != 1)
624 report_fatal_error("only one .global_variables fragment supported");
625 const MCFragment &Frag = *GlobalVars->begin();
626 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
627 report_fatal_error("only data supported in .global_variables");
628 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
629 if (!DataFrag.getFixups().empty())
630 report_fatal_error("fixups not supported in .global_variables");
631 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +0000632 for (const uint8_t *p = (const uint8_t *)Contents.data(),
633 *end = (const uint8_t *)Contents.data() + Contents.size();
634 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +0000635 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +0000636 if (end - p < 3)
637 report_fatal_error("truncated global variable encoding");
638 G.Type = wasm::ValType(int8_t(*p++));
639 G.IsMutable = bool(*p++);
640 G.HasImport = bool(*p++);
641 if (G.HasImport) {
642 G.InitialValue = 0;
643
644 WasmImport Import;
645 Import.ModuleName = (const char *)p;
646 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
647 if (!nul)
648 report_fatal_error("global module name must be nul-terminated");
649 p = nul + 1;
650 nul = (const uint8_t *)memchr(p, '\0', end - p);
651 if (!nul)
652 report_fatal_error("global base name must be nul-terminated");
653 Import.FieldName = (const char *)p;
654 p = nul + 1;
655
656 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
657 Import.Type = int32_t(G.Type);
658
659 G.ImportIndex = NumGlobalImports;
660 ++NumGlobalImports;
661
662 Imports.push_back(Import);
663 } else {
664 unsigned n;
665 G.InitialValue = decodeSLEB128(p, &n);
666 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +0000667 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +0000668 report_fatal_error("global initial value must be valid SLEB128");
669 p += n;
670 }
Dan Gohman82607f52017-02-24 23:46:05 +0000671 Globals.push_back(G);
672 }
673 }
674
Dan Gohman970d02c2017-03-30 23:58:19 +0000675 // In the special .stack_pointer section, we've encoded the stack pointer
676 // index.
677 MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0);
678 if (!StackPtr->getFragmentList().empty()) {
679 if (StackPtr->getFragmentList().size() != 1)
680 report_fatal_error("only one .stack_pointer fragment supported");
681 const MCFragment &Frag = *StackPtr->begin();
682 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
683 report_fatal_error("only data supported in .stack_pointer");
684 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
685 if (!DataFrag.getFixups().empty())
686 report_fatal_error("fixups not supported in .stack_pointer");
687 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
688 if (Contents.size() != 4)
689 report_fatal_error("only one entry supported in .stack_pointer");
690 HasStackPointer = true;
691 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
692 }
693
Dan Gohmand934cb82017-02-24 23:18:00 +0000694 // Handle defined symbols.
695 for (const MCSymbol &S : Asm.symbols()) {
696 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
697 // or used in relocations.
698 if (S.isTemporary() && S.getName().empty())
699 continue;
700 const auto &WS = static_cast<const MCSymbolWasm &>(S);
701 unsigned Index;
702 if (WS.isFunction()) {
703 // Prepare the function's type, if we haven't seen it yet.
704 WasmFunctionType F;
705 F.Returns = WS.getReturns();
706 F.Params = WS.getParams();
707 auto Pair =
708 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
709 if (Pair.second)
710 FunctionTypes.push_back(F);
711
Derek Schuffb8795392017-03-16 20:49:48 +0000712 int32_t Type = Pair.first->second;
Dan Gohmand934cb82017-02-24 23:18:00 +0000713
714 if (WS.isDefined(/*SetUsed=*/false)) {
715 // A definition. Take the next available index.
716 Index = NumFuncImports + Functions.size();
717
718 // Prepare the function.
719 WasmFunction Func;
720 Func.Type = Type;
721 Func.Sym = &WS;
722 SymbolIndices[&WS] = Index;
723 Functions.push_back(Func);
724 } else {
725 // An import; the index was assigned above.
726 Index = SymbolIndices.find(&WS)->second;
727 }
728
729 // If needed, prepare the function to be called indirectly.
730 if (IsAddressTaken.count(&WS))
731 TableElems.push_back(Index);
732 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +0000733 if (WS.isTemporary() && !WS.getSize())
734 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +0000735
736 if (WS.isDefined(false)) {
Sam Cleggc38e9472017-06-02 01:05:24 +0000737 if (WS.getOffset() != 0)
738 report_fatal_error("data sections must contain one variable each: " +
739 WS.getName());
740 if (!WS.getSize())
741 report_fatal_error("data symbols must have a size set with .size: " +
742 WS.getName());
743
744 int64_t Size = 0;
745 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
746 report_fatal_error(".size expression must be evaluatable");
747
Dan Gohmand934cb82017-02-24 23:18:00 +0000748 MCSectionWasm &DataSection =
749 static_cast<MCSectionWasm &>(WS.getSection());
750
751 if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection))
752 report_fatal_error("data sections must contain at most one variable");
753
754 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
755
756 DataSection.setSectionOffset(DataBytes.size());
757
758 for (MCSection::iterator I = DataSection.begin(), E = DataSection.end();
759 I != E; ++I) {
760 const MCFragment &Frag = *I;
761 if (Frag.hasInstructions())
762 report_fatal_error("only data supported in data sections");
763
764 if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) {
765 if (Align->getValueSize() != 1)
766 report_fatal_error("only byte values supported for alignment");
767 // If nops are requested, use zeros, as this is the data section.
768 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
769 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
770 Align->getAlignment()),
771 DataBytes.size() +
772 Align->getMaxBytesToEmit());
773 DataBytes.resize(Size, Value);
774 } else if (const MCFillFragment *Fill =
775 dyn_cast<MCFillFragment>(&Frag)) {
776 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
777 } else {
778 const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag);
779 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
780
781 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
782 }
783 }
784
Sam Clegg1c154a62017-05-25 21:08:07 +0000785 // For each global, prepare a corresponding wasm global holding its
786 // address. For externals these will also be named exports.
787 Index = NumGlobalImports + Globals.size();
Dan Gohmand934cb82017-02-24 23:18:00 +0000788
Sam Clegg1c154a62017-05-25 21:08:07 +0000789 WasmGlobal Global;
790 Global.Type = PtrType;
791 Global.IsMutable = false;
792 Global.HasImport = false;
793 Global.InitialValue = DataSection.getSectionOffset();
794 Global.ImportIndex = 0;
795 SymbolIndices[&WS] = Index;
796 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +0000797 }
798 }
799
800 // If the symbol is visible outside this translation unit, export it.
801 if (WS.isExternal()) {
802 assert(WS.isDefined(false));
803 WasmExport Export;
804 Export.FieldName = WS.getName();
805 Export.Index = Index;
806
807 if (WS.isFunction())
808 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
809 else
810 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
811
812 Exports.push_back(Export);
813 }
814 }
815
816 // Add types for indirect function calls.
Dan Gohman970d02c2017-03-30 23:58:19 +0000817 for (const WasmRelocationEntry &Fixup : TypeIndexFixups) {
818 assert(Fixup.Addend == 0);
819 assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB);
820
Dan Gohmand934cb82017-02-24 23:18:00 +0000821 WasmFunctionType F;
822 F.Returns = Fixup.Symbol->getReturns();
823 F.Params = Fixup.Symbol->getParams();
824 auto Pair =
825 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
826 if (Pair.second)
827 FunctionTypes.push_back(F);
828
829 TypeIndexFixupTypes.push_back(Pair.first->second);
830 }
831
Dan Gohman18eafb62017-02-22 01:23:18 +0000832 // Write out the Wasm header.
833 writeHeader(Asm);
834
Dan Gohmand934cb82017-02-24 23:18:00 +0000835 SectionBookkeeping Section;
836
837 // === Type Section =========================================================
838 if (!FunctionTypes.empty()) {
839 startSection(Section, wasm::WASM_SEC_TYPE);
840
841 encodeULEB128(FunctionTypes.size(), getStream());
842
843 for (WasmFunctionType &FuncTy : FunctionTypes) {
Derek Schuffe2688c42017-03-14 20:23:22 +0000844 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000845 encodeULEB128(FuncTy.Params.size(), getStream());
Derek Schuffe2688c42017-03-14 20:23:22 +0000846 for (wasm::ValType Ty : FuncTy.Params)
847 writeValueType(Ty);
Dan Gohmand934cb82017-02-24 23:18:00 +0000848 encodeULEB128(FuncTy.Returns.size(), getStream());
Derek Schuffe2688c42017-03-14 20:23:22 +0000849 for (wasm::ValType Ty : FuncTy.Returns)
850 writeValueType(Ty);
Dan Gohmand934cb82017-02-24 23:18:00 +0000851 }
852
853 endSection(Section);
854 }
855
856 // === Import Section ========================================================
857 if (!Imports.empty()) {
858 startSection(Section, wasm::WASM_SEC_IMPORT);
859
860 encodeULEB128(Imports.size(), getStream());
861 for (const WasmImport &Import : Imports) {
862 StringRef ModuleName = Import.ModuleName;
863 encodeULEB128(ModuleName.size(), getStream());
864 writeBytes(ModuleName);
865
866 StringRef FieldName = Import.FieldName;
867 encodeULEB128(FieldName.size(), getStream());
868 writeBytes(FieldName);
869
Derek Schuffe2688c42017-03-14 20:23:22 +0000870 encodeULEB128(Import.Kind, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000871
872 switch (Import.Kind) {
873 case wasm::WASM_EXTERNAL_FUNCTION:
874 encodeULEB128(Import.Type, getStream());
875 break;
876 case wasm::WASM_EXTERNAL_GLOBAL:
Dan Gohman970d02c2017-03-30 23:58:19 +0000877 encodeSLEB128(int32_t(Import.Type), getStream());
Derek Schuffe2688c42017-03-14 20:23:22 +0000878 encodeULEB128(0, getStream()); // mutability
Dan Gohmand934cb82017-02-24 23:18:00 +0000879 break;
880 default:
881 llvm_unreachable("unsupported import kind");
882 }
883 }
884
885 endSection(Section);
886 }
887
888 // === Function Section ======================================================
889 if (!Functions.empty()) {
890 startSection(Section, wasm::WASM_SEC_FUNCTION);
891
892 encodeULEB128(Functions.size(), getStream());
893 for (const WasmFunction &Func : Functions)
894 encodeULEB128(Func.Type, getStream());
895
896 endSection(Section);
897 }
898
899 // === Table Section =========================================================
900 // For now, always emit the table section, since indirect calls are not
901 // valid without it. In the future, we could perhaps be more clever and omit
902 // it if there are no indirect calls.
903 startSection(Section, wasm::WASM_SEC_TABLE);
904
905 // The number of tables, fixed to 1 for now.
906 encodeULEB128(1, getStream());
907
Derek Schuffe2688c42017-03-14 20:23:22 +0000908 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000909
910 encodeULEB128(0, getStream()); // flags
911 encodeULEB128(TableElems.size(), getStream()); // initial
912
913 endSection(Section);
914
915 // === Memory Section ========================================================
916 // For now, always emit the memory section, since loads and stores are not
917 // valid without it. In the future, we could perhaps be more clever and omit
918 // it if there are no loads or stores.
Sam Cleggff0730b2017-04-28 21:12:09 +0000919 uint32_t NumPages =
920 (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
Dan Gohmand934cb82017-02-24 23:18:00 +0000921
Sam Cleggff0730b2017-04-28 21:12:09 +0000922 startSection(Section, wasm::WASM_SEC_MEMORY);
Dan Gohmand934cb82017-02-24 23:18:00 +0000923 encodeULEB128(1, getStream()); // number of memory spaces
924
925 encodeULEB128(0, getStream()); // flags
Sam Cleggff0730b2017-04-28 21:12:09 +0000926 encodeULEB128(NumPages, getStream()); // initial
Dan Gohmand934cb82017-02-24 23:18:00 +0000927
928 endSection(Section);
929
930 // === Global Section ========================================================
931 if (!Globals.empty()) {
932 startSection(Section, wasm::WASM_SEC_GLOBAL);
933
934 encodeULEB128(Globals.size(), getStream());
935 for (const WasmGlobal &Global : Globals) {
Derek Schuffb8795392017-03-16 20:49:48 +0000936 writeValueType(Global.Type);
Dan Gohmand934cb82017-02-24 23:18:00 +0000937 write8(Global.IsMutable);
938
Dan Gohman970d02c2017-03-30 23:58:19 +0000939 if (Global.HasImport) {
940 assert(Global.InitialValue == 0);
941 write8(wasm::WASM_OPCODE_GET_GLOBAL);
942 encodeULEB128(Global.ImportIndex, getStream());
943 } else {
944 assert(Global.ImportIndex == 0);
945 write8(wasm::WASM_OPCODE_I32_CONST);
946 encodeSLEB128(Global.InitialValue, getStream()); // offset
947 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000948 write8(wasm::WASM_OPCODE_END);
949 }
950
951 endSection(Section);
952 }
953
954 // === Export Section ========================================================
955 if (!Exports.empty()) {
956 startSection(Section, wasm::WASM_SEC_EXPORT);
957
958 encodeULEB128(Exports.size(), getStream());
959 for (const WasmExport &Export : Exports) {
960 encodeULEB128(Export.FieldName.size(), getStream());
961 writeBytes(Export.FieldName);
962
Derek Schuffe2688c42017-03-14 20:23:22 +0000963 encodeSLEB128(Export.Kind, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000964
965 encodeULEB128(Export.Index, getStream());
966 }
967
968 endSection(Section);
969 }
970
971#if 0 // TODO: Start Section
972 if (HaveStartFunction) {
973 // === Start Section =========================================================
974 startSection(Section, wasm::WASM_SEC_START);
975
976 encodeSLEB128(StartFunction, getStream());
977
978 endSection(Section);
979 }
980#endif
981
982 // === Elem Section ==========================================================
983 if (!TableElems.empty()) {
984 startSection(Section, wasm::WASM_SEC_ELEM);
985
986 encodeULEB128(1, getStream()); // number of "segments"
987 encodeULEB128(0, getStream()); // the table index
988
989 // init expr for starting offset
990 write8(wasm::WASM_OPCODE_I32_CONST);
991 encodeSLEB128(0, getStream());
992 write8(wasm::WASM_OPCODE_END);
993
994 encodeULEB128(TableElems.size(), getStream());
995 for (uint32_t Elem : TableElems)
996 encodeULEB128(Elem, getStream());
997
998 endSection(Section);
999 }
1000
1001 // === Code Section ==========================================================
1002 if (!Functions.empty()) {
1003 startSection(Section, wasm::WASM_SEC_CODE);
1004
1005 encodeULEB128(Functions.size(), getStream());
1006
1007 for (const WasmFunction &Func : Functions) {
1008 MCSectionWasm &FuncSection =
1009 static_cast<MCSectionWasm &>(Func.Sym->getSection());
1010
1011 if (Func.Sym->isVariable())
1012 report_fatal_error("weak symbols not supported yet");
1013
1014 if (Func.Sym->getOffset() != 0)
1015 report_fatal_error("function sections must contain one function each");
1016
1017 if (!Func.Sym->getSize())
1018 report_fatal_error("function symbols must have a size set with .size");
1019
1020 int64_t Size = 0;
1021 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
1022 report_fatal_error(".size expression must be evaluatable");
1023
1024 encodeULEB128(Size, getStream());
1025
1026 FuncSection.setSectionOffset(getStream().tell() -
1027 Section.ContentsOffset);
1028
1029 Asm.writeSectionData(&FuncSection, Layout);
1030 }
1031
1032 // Apply the type index fixups for call_indirect etc. instructions.
1033 for (size_t i = 0, e = TypeIndexFixups.size(); i < e; ++i) {
1034 uint32_t Type = TypeIndexFixupTypes[i];
1035 unsigned Padding = PaddingFor5ByteULEB128(Type);
1036
Dan Gohman970d02c2017-03-30 23:58:19 +00001037 const WasmRelocationEntry &Fixup = TypeIndexFixups[i];
1038 assert(Fixup.Addend == 0);
1039 assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB);
Dan Gohmand934cb82017-02-24 23:18:00 +00001040 uint64_t Offset = Fixup.Offset +
1041 Fixup.FixupSection->getSectionOffset();
1042
1043 uint8_t Buffer[16];
1044 unsigned SizeLen = encodeULEB128(Type, Buffer, Padding);
1045 assert(SizeLen == 5);
1046 getStream().pwrite((char *)Buffer, SizeLen,
1047 Section.ContentsOffset + Offset);
1048 }
1049
1050 // Apply fixups.
1051 ApplyRelocations(CodeRelocations, getStream(), SymbolIndices,
1052 Section.ContentsOffset);
1053
1054 endSection(Section);
1055 }
1056
1057 // === Data Section ==========================================================
Sam Clegga06de022017-04-28 21:22:38 +00001058 uint32_t DataSectionHeaderSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001059 if (!DataBytes.empty()) {
1060 startSection(Section, wasm::WASM_SEC_DATA);
1061
1062 encodeULEB128(1, getStream()); // count
1063 encodeULEB128(0, getStream()); // memory index
1064 write8(wasm::WASM_OPCODE_I32_CONST);
1065 encodeSLEB128(0, getStream()); // offset
1066 write8(wasm::WASM_OPCODE_END);
1067 encodeULEB128(DataBytes.size(), getStream()); // size
Sam Clegga06de022017-04-28 21:22:38 +00001068 DataSectionHeaderSize = getStream().tell() - Section.ContentsOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +00001069 writeBytes(DataBytes); // data
1070
1071 // Apply fixups.
1072 ApplyRelocations(DataRelocations, getStream(), SymbolIndices,
Sam Clegga06de022017-04-28 21:22:38 +00001073 Section.ContentsOffset + DataSectionHeaderSize);
Dan Gohmand934cb82017-02-24 23:18:00 +00001074
1075 endSection(Section);
1076 }
1077
1078 // === Name Section ==========================================================
Derek Schuff13f080f2017-03-15 19:36:02 +00001079 uint32_t TotalFunctions = NumFuncImports + Functions.size();
1080 if (TotalFunctions != 0) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001081 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
Derek Schuff13f080f2017-03-15 19:36:02 +00001082 SectionBookkeeping SubSection;
1083 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
Dan Gohmand934cb82017-02-24 23:18:00 +00001084
Derek Schuff13f080f2017-03-15 19:36:02 +00001085 encodeULEB128(TotalFunctions, getStream());
1086 uint32_t Index = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001087 for (const WasmImport &Import : Imports) {
1088 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
Derek Schuff13f080f2017-03-15 19:36:02 +00001089 encodeULEB128(Index, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001090 encodeULEB128(Import.FieldName.size(), getStream());
1091 writeBytes(Import.FieldName);
Derek Schuff13f080f2017-03-15 19:36:02 +00001092 ++Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001093 }
1094 }
1095 for (const WasmFunction &Func : Functions) {
Derek Schuff13f080f2017-03-15 19:36:02 +00001096 encodeULEB128(Index, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001097 encodeULEB128(Func.Sym->getName().size(), getStream());
1098 writeBytes(Func.Sym->getName());
Derek Schuff13f080f2017-03-15 19:36:02 +00001099 ++Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001100 }
1101
Derek Schuff13f080f2017-03-15 19:36:02 +00001102 endSection(SubSection);
Dan Gohmand934cb82017-02-24 23:18:00 +00001103 endSection(Section);
1104 }
1105
1106 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
1107 // for descriptions of the reloc sections.
1108
1109 // === Code Reloc Section ====================================================
1110 if (!CodeRelocations.empty()) {
1111 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
1112
Derek Schuffe2688c42017-03-14 20:23:22 +00001113 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001114
Sam Clegg03b19232017-04-25 17:13:23 +00001115 encodeULEB128(CodeRelocations.size() + TypeIndexFixups.size(), getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001116
Sam Clegga06de022017-04-28 21:22:38 +00001117 WriteRelocations(CodeRelocations, getStream(), SymbolIndices, 0);
Dan Gohman970d02c2017-03-30 23:58:19 +00001118 WriteTypeRelocations(TypeIndexFixups, TypeIndexFixupTypes, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001119
1120 endSection(Section);
1121 }
1122
1123 // === Data Reloc Section ====================================================
1124 if (!DataRelocations.empty()) {
1125 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
1126
Derek Schuffe2688c42017-03-14 20:23:22 +00001127 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +00001128
1129 encodeULEB128(DataRelocations.size(), getStream());
1130
Sam Clegga06de022017-04-28 21:22:38 +00001131 WriteRelocations(DataRelocations, getStream(), SymbolIndices,
1132 DataSectionHeaderSize);
Dan Gohmand934cb82017-02-24 23:18:00 +00001133
1134 endSection(Section);
1135 }
1136
Dan Gohman970d02c2017-03-30 23:58:19 +00001137 // === Linking Metadata Section ==============================================
1138 if (HasStackPointer) {
1139 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
1140
1141 encodeULEB128(1, getStream()); // count
1142
1143 encodeULEB128(wasm::WASM_STACK_POINTER, getStream()); // type
1144 encodeULEB128(StackPointerGlobal, getStream()); // id
1145
1146 endSection(Section);
1147 }
1148
Dan Gohmand934cb82017-02-24 23:18:00 +00001149 // TODO: Translate the .comment section to the output.
1150
1151 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001152}
1153
1154MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW,
1155 raw_pwrite_stream &OS) {
1156 return new WasmObjectWriter(MOTW, OS);
1157}