blob: 44f2ba6ed7d91de234dc911e082c29249a17d705 [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
Sam Clegg5e3d33a2017-07-07 02:01:29 +000039#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000040
41namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000042
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
Sam Clegg9e15f352017-06-03 02:01:24 +000053// The signature of a wasm function, in a struct capable of being used as a
54// DenseMap key.
55struct WasmFunctionType {
56 // Support empty and tombstone instances, needed by DenseMap.
57 enum { Plain, Empty, Tombstone } State;
58
59 // The return types of the function.
60 SmallVector<wasm::ValType, 1> Returns;
61
62 // The parameter types of the function.
63 SmallVector<wasm::ValType, 4> Params;
64
65 WasmFunctionType() : State(Plain) {}
66
67 bool operator==(const WasmFunctionType &Other) const {
68 return State == Other.State && Returns == Other.Returns &&
69 Params == Other.Params;
70 }
71};
72
73// Traits for using WasmFunctionType in a DenseMap.
74struct WasmFunctionTypeDenseMapInfo {
75 static WasmFunctionType getEmptyKey() {
76 WasmFunctionType FuncTy;
77 FuncTy.State = WasmFunctionType::Empty;
78 return FuncTy;
79 }
80 static WasmFunctionType getTombstoneKey() {
81 WasmFunctionType FuncTy;
82 FuncTy.State = WasmFunctionType::Tombstone;
83 return FuncTy;
84 }
85 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
86 uintptr_t Value = FuncTy.State;
87 for (wasm::ValType Ret : FuncTy.Returns)
88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
89 for (wasm::ValType Param : FuncTy.Params)
90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
91 return Value;
92 }
93 static bool isEqual(const WasmFunctionType &LHS,
94 const WasmFunctionType &RHS) {
95 return LHS == RHS;
96 }
97};
98
Sam Clegg7c395942017-09-14 23:07:53 +000099// A wasm data segment. A wasm binary contains only a single data section
100// but that can contain many segments, each with their own virtual location
101// in memory. Each MCSection data created by llvm is modeled as its own
102// wasm data segment.
103struct WasmDataSegment {
104 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000105 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000106 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000107 uint32_t Alignment;
108 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000109 SmallVector<char, 4> Data;
110};
111
Sam Clegg9e15f352017-06-03 02:01:24 +0000112// A wasm import to be written into the import section.
113struct WasmImport {
114 StringRef ModuleName;
115 StringRef FieldName;
116 unsigned Kind;
117 int32_t Type;
118};
119
120// A wasm function to be written into the function section.
121struct WasmFunction {
122 int32_t Type;
123 const MCSymbolWasm *Sym;
124};
125
126// A wasm export to be written into the export section.
127struct WasmExport {
128 StringRef FieldName;
129 unsigned Kind;
130 uint32_t Index;
131};
132
133// A wasm global to be written into the global section.
134struct WasmGlobal {
135 wasm::ValType Type;
136 bool IsMutable;
137 bool HasImport;
138 uint64_t InitialValue;
139 uint32_t ImportIndex;
140};
141
Sam Clegg6dc65e92017-06-06 16:38:59 +0000142// Information about a single relocation.
143struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000144 uint64_t Offset; // Where is the relocation.
145 const MCSymbolWasm *Symbol; // The symbol to relocate with.
146 int64_t Addend; // A value to add to the symbol.
147 unsigned Type; // The type of the relocation.
148 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000149
150 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
151 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000152 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000153 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
154 FixupSection(FixupSection) {}
155
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000156 bool hasAddend() const {
157 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000158 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
159 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
160 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000161 return true;
162 default:
163 return false;
164 }
165 }
166
Sam Clegg6dc65e92017-06-06 16:38:59 +0000167 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000168 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000169 << ", Type=" << Type
170 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000171 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000172
Aaron Ballman615eb472017-10-15 14:32:27 +0000173#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000174 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
175#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000176};
177
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000178#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000179raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000180 Rel.print(OS);
181 return OS;
182}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000183#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000184
Dan Gohman18eafb62017-02-22 01:23:18 +0000185class WasmObjectWriter : public MCObjectWriter {
186 /// Helper struct for containing some precomputed information on symbols.
187 struct WasmSymbolData {
188 const MCSymbolWasm *Symbol;
189 StringRef Name;
190
191 // Support lexicographic sorting.
192 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
193 };
194
195 /// The target specific Wasm writer instance.
196 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
197
Dan Gohmand934cb82017-02-24 23:18:00 +0000198 // Relocations for fixing up references in the code section.
199 std::vector<WasmRelocationEntry> CodeRelocations;
200
201 // Relocations for fixing up references in the data section.
202 std::vector<WasmRelocationEntry> DataRelocations;
203
Dan Gohmand934cb82017-02-24 23:18:00 +0000204 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000205 // Maps function symbols to the index of the type of the function
206 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000207 // Maps function symbols to the table element index space. Used
208 // for TABLE_INDEX relocation types (i.e. address taken functions).
209 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
210 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000211 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
212
213 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
214 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000215 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000216 SmallVector<WasmGlobal, 4> Globals;
217 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000218
Dan Gohman18eafb62017-02-22 01:23:18 +0000219 // TargetObjectWriter wrappers.
220 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000221 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
222 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000223 }
224
Dan Gohmand934cb82017-02-24 23:18:00 +0000225 void startSection(SectionBookkeeping &Section, unsigned SectionId,
226 const char *Name = nullptr);
227 void endSection(SectionBookkeeping &Section);
228
Dan Gohman18eafb62017-02-22 01:23:18 +0000229public:
Lang Hames1301a872017-10-10 01:15:10 +0000230 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
231 raw_pwrite_stream &OS)
232 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
233 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000234
Dan Gohmand934cb82017-02-24 23:18:00 +0000235private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000236 ~WasmObjectWriter() override;
237
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000238 void reset() override {
239 CodeRelocations.clear();
240 DataRelocations.clear();
241 TypeIndices.clear();
242 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000243 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000244 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000245 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000246 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000247 MCObjectWriter::reset();
Sam Clegg7c395942017-09-14 23:07:53 +0000248 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000249 }
250
Dan Gohman18eafb62017-02-22 01:23:18 +0000251 void writeHeader(const MCAssembler &Asm);
252
253 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
254 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000255 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000256
257 void executePostLayoutBinding(MCAssembler &Asm,
258 const MCAsmLayout &Layout) override;
259
260 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000261
Sam Cleggb7787fd2017-06-20 04:04:59 +0000262 void writeString(const StringRef Str) {
263 encodeULEB128(Str.size(), getStream());
264 writeBytes(Str);
265 }
266
Sam Clegg9e15f352017-06-03 02:01:24 +0000267 void writeValueType(wasm::ValType Ty) {
268 encodeSLEB128(int32_t(Ty), getStream());
269 }
270
Sam Clegg457fb0b2017-09-15 19:50:44 +0000271 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
272 void writeImportSection(ArrayRef<WasmImport> Imports);
273 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +0000274 void writeTableSection(uint32_t NumElements);
Sam Clegg7c395942017-09-14 23:07:53 +0000275 void writeMemorySection(uint32_t DataSize);
276 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000277 void writeExportSection(ArrayRef<WasmExport> Exports);
278 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000279 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000280 ArrayRef<WasmFunction> Functions);
281 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
282 void writeNameSection(ArrayRef<WasmFunction> Functions,
283 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000284 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000285 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000286 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000287 void writeLinkingMetaDataSection(
288 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Clegg31a2c802017-09-20 21:17:04 +0000289 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags,
290 bool HasStackPointer, uint32_t StackPointerGlobal);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000291
Sam Clegg7c395942017-09-14 23:07:53 +0000292 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000293 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
294 uint64_t ContentsOffset);
295
Sam Clegg7c395942017-09-14 23:07:53 +0000296 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000297 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000298 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
299 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000300};
Sam Clegg9e15f352017-06-03 02:01:24 +0000301
Dan Gohman18eafb62017-02-22 01:23:18 +0000302} // end anonymous namespace
303
304WasmObjectWriter::~WasmObjectWriter() {}
305
Dan Gohmand934cb82017-02-24 23:18:00 +0000306// Write out a section header and a patchable section size field.
307void WasmObjectWriter::startSection(SectionBookkeeping &Section,
308 unsigned SectionId,
309 const char *Name) {
310 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
311 "Only custom sections can have names");
312
Sam Cleggb7787fd2017-06-20 04:04:59 +0000313 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000314 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000315
316 Section.SizeOffset = getStream().tell();
317
318 // The section size. We don't know the size yet, so reserve enough space
319 // for any 32-bit value; we'll patch it later.
320 encodeULEB128(UINT32_MAX, getStream());
321
322 // The position where the section starts, for measuring its size.
323 Section.ContentsOffset = getStream().tell();
324
325 // Custom sections in wasm also have a string identifier.
326 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000327 assert(Name);
328 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000329 }
330}
331
332// Now that the section is complete and we know how big it is, patch up the
333// section size field at the start of the section.
334void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
335 uint64_t Size = getStream().tell() - Section.ContentsOffset;
336 if (uint32_t(Size) != Size)
337 report_fatal_error("section size does not fit in a uint32_t");
338
Sam Cleggb7787fd2017-06-20 04:04:59 +0000339 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000340
341 // Write the final section size to the payload_len field, which follows
342 // the section id byte.
343 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000344 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000345 assert(SizeLen == 5);
346 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
347}
348
Dan Gohman18eafb62017-02-22 01:23:18 +0000349// Emit the Wasm header.
350void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000351 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
352 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000353}
354
355void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
356 const MCAsmLayout &Layout) {
357}
358
359void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
360 const MCAsmLayout &Layout,
361 const MCFragment *Fragment,
362 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000363 uint64_t &FixedValue) {
364 MCAsmBackend &Backend = Asm.getBackend();
365 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
366 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000367 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000368 uint64_t C = Target.getConstant();
369 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
370 MCContext &Ctx = Asm.getContext();
371
372 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
373 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
374 "Should not have constructed this");
375
376 // Let A, B and C being the components of Target and R be the location of
377 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
378 // If it is pcrel, we want to compute (A - B + C - R).
379
380 // In general, Wasm has no relocations for -B. It can only represent (A + C)
381 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
382 // replace B to implement it: (A - R - K + C)
383 if (IsPCRel) {
384 Ctx.reportError(
385 Fixup.getLoc(),
386 "No relocation available to represent this relative expression");
387 return;
388 }
389
390 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
391
392 if (SymB.isUndefined()) {
393 Ctx.reportError(Fixup.getLoc(),
394 Twine("symbol '") + SymB.getName() +
395 "' can not be undefined in a subtraction expression");
396 return;
397 }
398
399 assert(!SymB.isAbsolute() && "Should have been folded");
400 const MCSection &SecB = SymB.getSection();
401 if (&SecB != &FixupSection) {
402 Ctx.reportError(Fixup.getLoc(),
403 "Cannot represent a difference across sections");
404 return;
405 }
406
407 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
408 uint64_t K = SymBOffset - FixupOffset;
409 IsPCRel = true;
410 C -= K;
411 }
412
413 // We either rejected the fixup or folded B into C at this point.
414 const MCSymbolRefExpr *RefA = Target.getSymA();
415 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
416
Dan Gohmand934cb82017-02-24 23:18:00 +0000417 if (SymA && SymA->isVariable()) {
418 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000419 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
420 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
421 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000422 }
423
424 // Put any constant offset in an addend. Offsets can be negative, and
425 // LLVM expects wrapping, in contrast to wasm's immediates which can't
426 // be negative and don't wrap.
427 FixedValue = 0;
428
Sam Clegg6ad8f192017-07-11 02:21:57 +0000429 if (SymA)
430 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000431
Sam Cleggae03c1e72017-06-13 18:51:50 +0000432 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000433 assert(SymA);
434
Sam Cleggae03c1e72017-06-13 18:51:50 +0000435 unsigned Type = getRelocType(Target, Fixup);
436
Dan Gohmand934cb82017-02-24 23:18:00 +0000437 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000438 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000439
Sam Clegg12fd3da2017-10-20 21:28:38 +0000440 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000441 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000442 else if (FixupSection.getKind().isText())
443 CodeRelocations.push_back(Rec);
444 else if (!FixupSection.getKind().isMetadata())
445 // TODO(sbc): Add support for debug sections.
446 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000447}
448
Dan Gohmand934cb82017-02-24 23:18:00 +0000449// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
450// to allow patching.
451static void
452WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
453 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000454 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000455 assert(SizeLen == 5);
456 Stream.pwrite((char *)Buffer, SizeLen, Offset);
457}
458
459// Write X as an signed LEB value at offset Offset in Stream, padded
460// to allow patching.
461static void
462WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
463 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000464 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000465 assert(SizeLen == 5);
466 Stream.pwrite((char *)Buffer, SizeLen, Offset);
467}
468
469// Write X as a plain integer value at offset Offset in Stream.
470static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
471 uint8_t Buffer[4];
472 support::endian::write32le(Buffer, X);
473 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
474}
475
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000476static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
477 if (Symbol.isVariable()) {
478 const MCExpr *Expr = Symbol.getVariableValue();
479 auto *Inner = cast<MCSymbolRefExpr>(Expr);
480 return cast<MCSymbolWasm>(&Inner->getSymbol());
481 }
482 return &Symbol;
483}
484
Dan Gohmand934cb82017-02-24 23:18:00 +0000485// Compute a value to write into the code at the location covered
486// by RelEntry. This value isn't used by the static linker, since
487// we have addends; it just serves to make the code more readable
488// and to make standalone wasm modules directly usable.
Sam Clegg7c395942017-09-14 23:07:53 +0000489uint32_t
490WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000491 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +0000492
493 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000494 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000495 return UINT32_MAX;
496
Sam Clegg7c395942017-09-14 23:07:53 +0000497 uint32_t GlobalIndex = SymbolIndices[Sym];
498 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
499 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000500
501 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
502 uint32_t Value = Address;
503
504 return Value;
505}
506
Sam Clegg759631c2017-09-15 20:54:59 +0000507static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000508 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000509 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
510
Sam Clegg63ebb812017-09-29 16:50:08 +0000511 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
512
Sam Clegg759631c2017-09-15 20:54:59 +0000513 for (const MCFragment &Frag : DataSection) {
514 if (Frag.hasInstructions())
515 report_fatal_error("only data supported in data sections");
516
517 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
518 if (Align->getValueSize() != 1)
519 report_fatal_error("only byte values supported for alignment");
520 // If nops are requested, use zeros, as this is the data section.
521 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
522 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
523 Align->getAlignment()),
524 DataBytes.size() +
525 Align->getMaxBytesToEmit());
526 DataBytes.resize(Size, Value);
527 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
528 DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
529 } else {
530 const auto &DataFrag = cast<MCDataFragment>(Frag);
531 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
532
533 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
534 }
535 }
536
537 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
538}
539
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000540uint32_t WasmObjectWriter::getRelocationIndexValue(
541 const WasmRelocationEntry &RelEntry) {
542 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000543 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
544 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000545 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000546 report_fatal_error("symbol not found table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000547 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000548 return IndirectSymbolIndices[RelEntry.Symbol];
549 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000550 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000551 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
552 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
553 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000554 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000555 report_fatal_error("symbol not found function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000556 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000557 return SymbolIndices[RelEntry.Symbol];
558 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000559 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000560 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000561 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000562 return TypeIndices[RelEntry.Symbol];
563 default:
564 llvm_unreachable("invalid relocation type");
565 }
566}
567
Dan Gohmand934cb82017-02-24 23:18:00 +0000568// Apply the portions of the relocation records that we can handle ourselves
569// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000570void WasmObjectWriter::applyRelocations(
571 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
572 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000573 for (const WasmRelocationEntry &RelEntry : Relocations) {
574 uint64_t Offset = ContentsOffset +
575 RelEntry.FixupSection->getSectionOffset() +
576 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000577
Sam Cleggb7787fd2017-06-20 04:04:59 +0000578 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000579 switch (RelEntry.Type) {
580 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
581 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000582 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
583 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000584 uint32_t Index = getRelocationIndexValue(RelEntry);
585 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000586 break;
587 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000588 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
589 uint32_t Index = getRelocationIndexValue(RelEntry);
590 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000591 break;
592 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000593 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000594 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000595 WritePatchableSLEB(Stream, Value, Offset);
596 break;
597 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000598 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000599 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000600 WritePatchableLEB(Stream, Value, Offset);
601 break;
602 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000603 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
Sam Clegg7c395942017-09-14 23:07:53 +0000604 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000605 WriteI32(Stream, Value, Offset);
606 break;
607 }
608 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000609 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000610 }
611 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000612}
613
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000614// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000615// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000616void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000617 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000618 raw_pwrite_stream &Stream = getStream();
619 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000620
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000621 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000622 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000623 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000624
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000625 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000626 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000627 encodeULEB128(Index, Stream);
628 if (RelEntry.hasAddend())
629 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000630 }
631}
632
Sam Clegg9e15f352017-06-03 02:01:24 +0000633void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000634 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000635 if (FunctionTypes.empty())
636 return;
637
638 SectionBookkeeping Section;
639 startSection(Section, wasm::WASM_SEC_TYPE);
640
641 encodeULEB128(FunctionTypes.size(), getStream());
642
643 for (const WasmFunctionType &FuncTy : FunctionTypes) {
644 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
645 encodeULEB128(FuncTy.Params.size(), getStream());
646 for (wasm::ValType Ty : FuncTy.Params)
647 writeValueType(Ty);
648 encodeULEB128(FuncTy.Returns.size(), getStream());
649 for (wasm::ValType Ty : FuncTy.Returns)
650 writeValueType(Ty);
651 }
652
653 endSection(Section);
654}
655
Sam Clegg457fb0b2017-09-15 19:50:44 +0000656void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000657 if (Imports.empty())
658 return;
659
660 SectionBookkeeping Section;
661 startSection(Section, wasm::WASM_SEC_IMPORT);
662
663 encodeULEB128(Imports.size(), getStream());
664 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000665 writeString(Import.ModuleName);
666 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000667
668 encodeULEB128(Import.Kind, getStream());
669
670 switch (Import.Kind) {
671 case wasm::WASM_EXTERNAL_FUNCTION:
672 encodeULEB128(Import.Type, getStream());
673 break;
674 case wasm::WASM_EXTERNAL_GLOBAL:
675 encodeSLEB128(int32_t(Import.Type), getStream());
676 encodeULEB128(0, getStream()); // mutability
677 break;
678 default:
679 llvm_unreachable("unsupported import kind");
680 }
681 }
682
683 endSection(Section);
684}
685
Sam Clegg457fb0b2017-09-15 19:50:44 +0000686void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000687 if (Functions.empty())
688 return;
689
690 SectionBookkeeping Section;
691 startSection(Section, wasm::WASM_SEC_FUNCTION);
692
693 encodeULEB128(Functions.size(), getStream());
694 for (const WasmFunction &Func : Functions)
695 encodeULEB128(Func.Type, getStream());
696
697 endSection(Section);
698}
699
Sam Cleggd99f6072017-06-12 23:52:44 +0000700void WasmObjectWriter::writeTableSection(uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000701 // For now, always emit the table section, since indirect calls are not
702 // valid without it. In the future, we could perhaps be more clever and omit
703 // it if there are no indirect calls.
Sam Cleggd99f6072017-06-12 23:52:44 +0000704
Sam Clegg9e15f352017-06-03 02:01:24 +0000705 SectionBookkeeping Section;
706 startSection(Section, wasm::WASM_SEC_TABLE);
707
Sam Cleggd99f6072017-06-12 23:52:44 +0000708 encodeULEB128(1, getStream()); // The number of tables.
709 // Fixed to 1 for now.
710 encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); // Type of table
711 encodeULEB128(0, getStream()); // flags
712 encodeULEB128(NumElements, getStream()); // initial
Sam Clegg9e15f352017-06-03 02:01:24 +0000713
714 endSection(Section);
715}
716
Sam Clegg7c395942017-09-14 23:07:53 +0000717void WasmObjectWriter::writeMemorySection(uint32_t DataSize) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000718 // For now, always emit the memory section, since loads and stores are not
719 // valid without it. In the future, we could perhaps be more clever and omit
720 // it if there are no loads or stores.
721 SectionBookkeeping Section;
Sam Clegg7c395942017-09-14 23:07:53 +0000722 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
Sam Clegg9e15f352017-06-03 02:01:24 +0000723
724 startSection(Section, wasm::WASM_SEC_MEMORY);
725 encodeULEB128(1, getStream()); // number of memory spaces
726
727 encodeULEB128(0, getStream()); // flags
728 encodeULEB128(NumPages, getStream()); // initial
729
730 endSection(Section);
731}
732
Sam Clegg7c395942017-09-14 23:07:53 +0000733void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000734 if (Globals.empty())
735 return;
736
737 SectionBookkeeping Section;
738 startSection(Section, wasm::WASM_SEC_GLOBAL);
739
740 encodeULEB128(Globals.size(), getStream());
741 for (const WasmGlobal &Global : Globals) {
742 writeValueType(Global.Type);
743 write8(Global.IsMutable);
744
745 if (Global.HasImport) {
746 assert(Global.InitialValue == 0);
747 write8(wasm::WASM_OPCODE_GET_GLOBAL);
748 encodeULEB128(Global.ImportIndex, getStream());
749 } else {
750 assert(Global.ImportIndex == 0);
751 write8(wasm::WASM_OPCODE_I32_CONST);
752 encodeSLEB128(Global.InitialValue, getStream()); // offset
753 }
754 write8(wasm::WASM_OPCODE_END);
755 }
756
757 endSection(Section);
758}
759
Sam Clegg457fb0b2017-09-15 19:50:44 +0000760void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000761 if (Exports.empty())
762 return;
763
764 SectionBookkeeping Section;
765 startSection(Section, wasm::WASM_SEC_EXPORT);
766
767 encodeULEB128(Exports.size(), getStream());
768 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000769 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000770 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000771 encodeULEB128(Export.Index, getStream());
772 }
773
774 endSection(Section);
775}
776
Sam Clegg457fb0b2017-09-15 19:50:44 +0000777void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000778 if (TableElems.empty())
779 return;
780
781 SectionBookkeeping Section;
782 startSection(Section, wasm::WASM_SEC_ELEM);
783
784 encodeULEB128(1, getStream()); // number of "segments"
785 encodeULEB128(0, getStream()); // the table index
786
787 // init expr for starting offset
788 write8(wasm::WASM_OPCODE_I32_CONST);
789 encodeSLEB128(0, getStream());
790 write8(wasm::WASM_OPCODE_END);
791
792 encodeULEB128(TableElems.size(), getStream());
793 for (uint32_t Elem : TableElems)
794 encodeULEB128(Elem, getStream());
795
796 endSection(Section);
797}
798
Sam Clegg457fb0b2017-09-15 19:50:44 +0000799void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
800 const MCAsmLayout &Layout,
801 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000802 if (Functions.empty())
803 return;
804
805 SectionBookkeeping Section;
806 startSection(Section, wasm::WASM_SEC_CODE);
807
808 encodeULEB128(Functions.size(), getStream());
809
810 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000811 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000812
Sam Clegg9e15f352017-06-03 02:01:24 +0000813 int64_t Size = 0;
814 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
815 report_fatal_error(".size expression must be evaluatable");
816
817 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000818 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000819 Asm.writeSectionData(&FuncSection, Layout);
820 }
821
Sam Clegg9e15f352017-06-03 02:01:24 +0000822 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000823 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000824
825 endSection(Section);
826}
827
Sam Clegg457fb0b2017-09-15 19:50:44 +0000828void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000829 if (Segments.empty())
830 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000831
832 SectionBookkeeping Section;
833 startSection(Section, wasm::WASM_SEC_DATA);
834
Sam Clegg7c395942017-09-14 23:07:53 +0000835 encodeULEB128(Segments.size(), getStream()); // count
836
837 for (const WasmDataSegment & Segment : Segments) {
838 encodeULEB128(0, getStream()); // memory index
839 write8(wasm::WASM_OPCODE_I32_CONST);
840 encodeSLEB128(Segment.Offset, getStream()); // offset
841 write8(wasm::WASM_OPCODE_END);
842 encodeULEB128(Segment.Data.size(), getStream()); // size
843 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
844 writeBytes(Segment.Data); // data
845 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000846
847 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000848 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000849
850 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000851}
852
853void WasmObjectWriter::writeNameSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000854 ArrayRef<WasmFunction> Functions,
855 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000856 unsigned NumFuncImports) {
857 uint32_t TotalFunctions = NumFuncImports + Functions.size();
858 if (TotalFunctions == 0)
859 return;
860
861 SectionBookkeeping Section;
862 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
863 SectionBookkeeping SubSection;
864 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
865
866 encodeULEB128(TotalFunctions, getStream());
867 uint32_t Index = 0;
868 for (const WasmImport &Import : Imports) {
869 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
870 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000871 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000872 ++Index;
873 }
874 }
875 for (const WasmFunction &Func : Functions) {
876 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000877 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000878 ++Index;
879 }
880
881 endSection(SubSection);
882 endSection(Section);
883}
884
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000885void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000886 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
887 // for descriptions of the reloc sections.
888
889 if (CodeRelocations.empty())
890 return;
891
892 SectionBookkeeping Section;
893 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
894
895 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000896 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000897
Sam Clegg7c395942017-09-14 23:07:53 +0000898 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000899
900 endSection(Section);
901}
902
Sam Clegg7c395942017-09-14 23:07:53 +0000903void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000904 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
905 // for descriptions of the reloc sections.
906
907 if (DataRelocations.empty())
908 return;
909
910 SectionBookkeeping Section;
911 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
912
913 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
914 encodeULEB128(DataRelocations.size(), getStream());
915
Sam Clegg7c395942017-09-14 23:07:53 +0000916 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000917
918 endSection(Section);
919}
920
921void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000922 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Clegg31a2c802017-09-20 21:17:04 +0000923 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags,
Sam Clegg9e1ade92017-06-27 20:27:59 +0000924 bool HasStackPointer, uint32_t StackPointerGlobal) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000925 SectionBookkeeping Section;
926 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000927 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000928
Sam Cleggb7787fd2017-06-20 04:04:59 +0000929 if (HasStackPointer) {
930 startSection(SubSection, wasm::WASM_STACK_POINTER);
931 encodeULEB128(StackPointerGlobal, getStream()); // id
932 endSection(SubSection);
933 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000934
Sam Clegg31a2c802017-09-20 21:17:04 +0000935 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000936 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000937 encodeULEB128(SymbolFlags.size(), getStream());
938 for (auto Pair: SymbolFlags) {
939 writeString(Pair.first);
940 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000941 }
942 endSection(SubSection);
943 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000944
Sam Clegg9e1ade92017-06-27 20:27:59 +0000945 if (DataSize > 0) {
946 startSection(SubSection, wasm::WASM_DATA_SIZE);
947 encodeULEB128(DataSize, getStream());
948 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000949 }
950
Sam Cleggd95ed952017-09-20 19:03:35 +0000951 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000952 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000953 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000954 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000955 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000956 encodeULEB128(Segment.Alignment, getStream());
957 encodeULEB128(Segment.Flags, getStream());
958 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000959 endSection(SubSection);
960 }
961
Sam Clegg9e15f352017-06-03 02:01:24 +0000962 endSection(Section);
963}
964
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000965uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
966 assert(Symbol.isFunction());
967 assert(TypeIndices.count(&Symbol));
968 return TypeIndices[&Symbol];
969}
970
971uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
972 assert(Symbol.isFunction());
973
974 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000975 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
976 F.Returns = ResolvedSym->getReturns();
977 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000978
979 auto Pair =
980 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
981 if (Pair.second)
982 FunctionTypes.push_back(F);
983 TypeIndices[&Symbol] = Pair.first->second;
984
985 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
986 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
987 return Pair.first->second;
988}
989
Dan Gohman18eafb62017-02-22 01:23:18 +0000990void WasmObjectWriter::writeObject(MCAssembler &Asm,
991 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000992 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000993 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000994 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000995
996 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000997 SmallVector<WasmFunction, 4> Functions;
998 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000999 SmallVector<WasmImport, 4> Imports;
1000 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +00001001 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Dan Gohmand934cb82017-02-24 23:18:00 +00001002 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
1003 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +00001004 SmallVector<WasmDataSegment, 4> DataSegments;
Dan Gohman970d02c2017-03-30 23:58:19 +00001005 uint32_t StackPointerGlobal = 0;
Sam Clegg7c395942017-09-14 23:07:53 +00001006 uint32_t DataSize = 0;
Dan Gohman970d02c2017-03-30 23:58:19 +00001007 bool HasStackPointer = false;
Dan Gohmand934cb82017-02-24 23:18:00 +00001008
1009 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001010 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001011 switch (RelEntry.Type) {
1012 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg13a2e892017-09-01 17:32:01 +00001013 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
Dan Gohmand934cb82017-02-24 23:18:00 +00001014 IsAddressTaken.insert(RelEntry.Symbol);
1015 break;
1016 default:
1017 break;
1018 }
1019 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001020 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001021 switch (RelEntry.Type) {
1022 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Clegg13a2e892017-09-01 17:32:01 +00001023 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +00001024 IsAddressTaken.insert(RelEntry.Symbol);
1025 break;
1026 default:
1027 break;
1028 }
1029 }
1030
Sam Clegg7c395942017-09-14 23:07:53 +00001031 // Populate FunctionTypeIndices and Imports.
Dan Gohmand934cb82017-02-24 23:18:00 +00001032 for (const MCSymbol &S : Asm.symbols()) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001033 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1034
1035 if (WS.isTemporary())
Sam Clegg8c4baa002017-07-05 20:09:26 +00001036 continue;
1037
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001038 if (WS.isFunction())
1039 registerFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001040
1041 // If the symbol is not defined in this translation unit, import it.
Sam Cleggba9fa9f2017-09-26 21:10:09 +00001042 if (!WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001043 WasmImport Import;
1044 Import.ModuleName = WS.getModuleName();
1045 Import.FieldName = WS.getName();
1046
1047 if (WS.isFunction()) {
1048 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001049 Import.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001050 SymbolIndices[&WS] = NumFuncImports;
1051 ++NumFuncImports;
1052 } else {
1053 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001054 Import.Type = int32_t(PtrType);
Dan Gohmand934cb82017-02-24 23:18:00 +00001055 SymbolIndices[&WS] = NumGlobalImports;
1056 ++NumGlobalImports;
1057 }
1058
1059 Imports.push_back(Import);
1060 }
1061 }
1062
Dan Gohman82607f52017-02-24 23:46:05 +00001063 // In the special .global_variables section, we've encoded global
1064 // variables used by the function. Translate them into the Globals
1065 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +00001066 MCSectionWasm *GlobalVars =
1067 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +00001068 if (!GlobalVars->getFragmentList().empty()) {
1069 if (GlobalVars->getFragmentList().size() != 1)
1070 report_fatal_error("only one .global_variables fragment supported");
1071 const MCFragment &Frag = *GlobalVars->begin();
1072 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1073 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001074 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001075 if (!DataFrag.getFixups().empty())
1076 report_fatal_error("fixups not supported in .global_variables");
1077 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001078 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1079 *end = (const uint8_t *)Contents.data() + Contents.size();
1080 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001081 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001082 if (end - p < 3)
1083 report_fatal_error("truncated global variable encoding");
1084 G.Type = wasm::ValType(int8_t(*p++));
1085 G.IsMutable = bool(*p++);
1086 G.HasImport = bool(*p++);
1087 if (G.HasImport) {
1088 G.InitialValue = 0;
1089
1090 WasmImport Import;
1091 Import.ModuleName = (const char *)p;
1092 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1093 if (!nul)
1094 report_fatal_error("global module name must be nul-terminated");
1095 p = nul + 1;
1096 nul = (const uint8_t *)memchr(p, '\0', end - p);
1097 if (!nul)
1098 report_fatal_error("global base name must be nul-terminated");
1099 Import.FieldName = (const char *)p;
1100 p = nul + 1;
1101
1102 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1103 Import.Type = int32_t(G.Type);
1104
1105 G.ImportIndex = NumGlobalImports;
1106 ++NumGlobalImports;
1107
1108 Imports.push_back(Import);
1109 } else {
1110 unsigned n;
1111 G.InitialValue = decodeSLEB128(p, &n);
1112 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001113 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001114 report_fatal_error("global initial value must be valid SLEB128");
1115 p += n;
1116 }
Dan Gohman82607f52017-02-24 23:46:05 +00001117 Globals.push_back(G);
1118 }
1119 }
1120
Dan Gohman970d02c2017-03-30 23:58:19 +00001121 // In the special .stack_pointer section, we've encoded the stack pointer
1122 // index.
Sam Clegg12fd3da2017-10-20 21:28:38 +00001123 MCSectionWasm *StackPtr =
1124 Ctx.getWasmSection(".stack_pointer", SectionKind::getMetadata());
Dan Gohman970d02c2017-03-30 23:58:19 +00001125 if (!StackPtr->getFragmentList().empty()) {
1126 if (StackPtr->getFragmentList().size() != 1)
1127 report_fatal_error("only one .stack_pointer fragment supported");
1128 const MCFragment &Frag = *StackPtr->begin();
1129 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1130 report_fatal_error("only data supported in .stack_pointer");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001131 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman970d02c2017-03-30 23:58:19 +00001132 if (!DataFrag.getFixups().empty())
1133 report_fatal_error("fixups not supported in .stack_pointer");
1134 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1135 if (Contents.size() != 4)
1136 report_fatal_error("only one entry supported in .stack_pointer");
1137 HasStackPointer = true;
1138 StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data();
1139 }
1140
Sam Clegg759631c2017-09-15 20:54:59 +00001141 for (MCSection &Sec : Asm) {
1142 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001143 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001144 continue;
1145
1146 DataSize = alignTo(DataSize, Section.getAlignment());
1147 DataSegments.emplace_back();
1148 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001149 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001150 Segment.Offset = DataSize;
1151 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001152 addData(Segment.Data, Section);
1153 Segment.Alignment = Section.getAlignment();
1154 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001155 DataSize += Segment.Data.size();
1156 Section.setMemoryOffset(Segment.Offset);
1157 }
1158
Sam Cleggb7787fd2017-06-20 04:04:59 +00001159 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001160 for (const MCSymbol &S : Asm.symbols()) {
1161 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1162 // or used in relocations.
1163 if (S.isTemporary() && S.getName().empty())
1164 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001165
Dan Gohmand934cb82017-02-24 23:18:00 +00001166 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001167 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1168 << " isDefined=" << S.isDefined() << " isExternal="
1169 << S.isExternal() << " isTemporary=" << S.isTemporary()
1170 << " isFunction=" << WS.isFunction()
1171 << " isWeak=" << WS.isWeak()
1172 << " isVariable=" << WS.isVariable() << "\n");
1173
1174 if (WS.isWeak())
Sam Clegg31a2c802017-09-20 21:17:04 +00001175 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_WEAK);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001176
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001177 if (WS.isVariable())
1178 continue;
1179
Dan Gohmand934cb82017-02-24 23:18:00 +00001180 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001181
Dan Gohmand934cb82017-02-24 23:18:00 +00001182 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001183 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001184 if (WS.getOffset() != 0)
1185 report_fatal_error(
1186 "function sections must contain one function each");
1187
1188 if (WS.getSize() == 0)
1189 report_fatal_error(
1190 "function symbols must have a size set with .size");
1191
Dan Gohmand934cb82017-02-24 23:18:00 +00001192 // A definition. Take the next available index.
1193 Index = NumFuncImports + Functions.size();
1194
1195 // Prepare the function.
1196 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001197 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001198 Func.Sym = &WS;
1199 SymbolIndices[&WS] = Index;
1200 Functions.push_back(Func);
1201 } else {
1202 // An import; the index was assigned above.
1203 Index = SymbolIndices.find(&WS)->second;
1204 }
1205
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001206 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1207
Dan Gohmand934cb82017-02-24 23:18:00 +00001208 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001209 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001210 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001211 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001212 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001213 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001214 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001215 if (WS.isTemporary() && !WS.getSize())
1216 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001217
Sam Cleggfe6414b2017-06-21 23:46:41 +00001218 if (!WS.isDefined(/*SetUsed=*/false))
1219 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001220
Sam Cleggfe6414b2017-06-21 23:46:41 +00001221 if (!WS.getSize())
1222 report_fatal_error("data symbols must have a size set with .size: " +
1223 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001224
Sam Cleggfe6414b2017-06-21 23:46:41 +00001225 int64_t Size = 0;
1226 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1227 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001228
Sam Clegg7c395942017-09-14 23:07:53 +00001229 // For each global, prepare a corresponding wasm global holding its
1230 // address. For externals these will also be named exports.
1231 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001232 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Clegg7c395942017-09-14 23:07:53 +00001233
1234 WasmGlobal Global;
1235 Global.Type = PtrType;
1236 Global.IsMutable = false;
1237 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001238 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001239 Global.ImportIndex = 0;
1240 SymbolIndices[&WS] = Index;
1241 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1242 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 }
1244
1245 // If the symbol is visible outside this translation unit, export it.
Sam Clegg31a2c802017-09-20 21:17:04 +00001246 if (WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001247 WasmExport Export;
1248 Export.FieldName = WS.getName();
1249 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001250 if (WS.isFunction())
1251 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1252 else
1253 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001254 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001255 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001256 if (!WS.isExternal())
1257 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Dan Gohmand934cb82017-02-24 23:18:00 +00001258 }
1259 }
1260
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001261 // Handle weak aliases. We need to process these in a separate pass because
1262 // we need to have processed the target of the alias before the alias itself
1263 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001264 for (const MCSymbol &S : Asm.symbols()) {
1265 if (!S.isVariable())
1266 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001267
Sam Cleggb7787fd2017-06-20 04:04:59 +00001268 assert(S.isDefined(/*SetUsed=*/false));
1269
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001270 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001271 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1272 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001273 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1274 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001275 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001276 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001277
Sam Cleggba9fa9f2017-09-26 21:10:09 +00001278 SymbolIndices[&WS] = Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001279 WasmExport Export;
1280 Export.FieldName = WS.getName();
1281 Export.Index = Index;
1282 if (WS.isFunction())
1283 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1284 else
1285 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001286 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001287 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001288
1289 if (!WS.isExternal())
1290 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001291 }
1292
Dan Gohmand934cb82017-02-24 23:18:00 +00001293 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001294 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1295 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1296 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001297
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001298 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001299 }
1300
Dan Gohman18eafb62017-02-22 01:23:18 +00001301 // Write out the Wasm header.
1302 writeHeader(Asm);
1303
Sam Clegg9e15f352017-06-03 02:01:24 +00001304 writeTypeSection(FunctionTypes);
1305 writeImportSection(Imports);
1306 writeFunctionSection(Functions);
Sam Cleggd99f6072017-06-12 23:52:44 +00001307 writeTableSection(TableElems.size());
Sam Clegg7c395942017-09-14 23:07:53 +00001308 writeMemorySection(DataSize);
1309 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001310 writeExportSection(Exports);
1311 // TODO: Start Section
1312 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001313 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001314 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001315 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001316 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001317 writeDataRelocSection();
Sam Clegg63ebb812017-09-29 16:50:08 +00001318 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
1319 HasStackPointer, StackPointerGlobal);
Dan Gohman970d02c2017-03-30 23:58:19 +00001320
Dan Gohmand934cb82017-02-24 23:18:00 +00001321 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001322 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001323}
1324
Lang Hames60fbc7c2017-10-10 16:28:07 +00001325std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001326llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1327 raw_pwrite_stream &OS) {
Lang Hames60fbc7c2017-10-10 16:28:07 +00001328 // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's
1329 // destructor is private. Is that necessary?
1330 return std::unique_ptr<MCObjectWriter>(
1331 new WasmObjectWriter(std::move(MOTW), OS));
Dan Gohman18eafb62017-02-22 01:23:18 +00001332}