blob: b2c5b14bca5defa4cf1cae5bae2930a17a5f12be [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"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#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"
Dan Gohman18eafb62017-02-22 01:23:18 +000023#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionWasm.h"
25#include "llvm/MC/MCSymbolWasm.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000028#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000029#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000031#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/StringSaver.h"
33#include <vector>
34
35using namespace llvm;
36
Sam Clegg5e3d33a2017-07-07 02:01:29 +000037#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000038
39namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000040
Dan Gohmand934cb82017-02-24 23:18:00 +000041// For patching purposes, we need to remember where each section starts, both
42// for patching up the section size field, and for patching up references to
43// locations within the section.
44struct SectionBookkeeping {
45 // Where the size of the section is written.
46 uint64_t SizeOffset;
47 // Where the contents of the section starts (after the header).
48 uint64_t ContentsOffset;
49};
50
Sam Clegg9e15f352017-06-03 02:01:24 +000051// The signature of a wasm function, in a struct capable of being used as a
52// DenseMap key.
53struct WasmFunctionType {
54 // Support empty and tombstone instances, needed by DenseMap.
55 enum { Plain, Empty, Tombstone } State;
56
57 // The return types of the function.
58 SmallVector<wasm::ValType, 1> Returns;
59
60 // The parameter types of the function.
61 SmallVector<wasm::ValType, 4> Params;
62
63 WasmFunctionType() : State(Plain) {}
64
65 bool operator==(const WasmFunctionType &Other) const {
66 return State == Other.State && Returns == Other.Returns &&
67 Params == Other.Params;
68 }
69};
70
71// Traits for using WasmFunctionType in a DenseMap.
72struct WasmFunctionTypeDenseMapInfo {
73 static WasmFunctionType getEmptyKey() {
74 WasmFunctionType FuncTy;
75 FuncTy.State = WasmFunctionType::Empty;
76 return FuncTy;
77 }
78 static WasmFunctionType getTombstoneKey() {
79 WasmFunctionType FuncTy;
80 FuncTy.State = WasmFunctionType::Tombstone;
81 return FuncTy;
82 }
83 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
84 uintptr_t Value = FuncTy.State;
85 for (wasm::ValType Ret : FuncTy.Returns)
86 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
87 for (wasm::ValType Param : FuncTy.Params)
88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
89 return Value;
90 }
91 static bool isEqual(const WasmFunctionType &LHS,
92 const WasmFunctionType &RHS) {
93 return LHS == RHS;
94 }
95};
96
Sam Clegg7c395942017-09-14 23:07:53 +000097// A wasm data segment. A wasm binary contains only a single data section
98// but that can contain many segments, each with their own virtual location
99// in memory. Each MCSection data created by llvm is modeled as its own
100// wasm data segment.
101struct WasmDataSegment {
102 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000103 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000104 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000105 uint32_t Alignment;
106 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000107 SmallVector<char, 4> Data;
108};
109
Sam Clegg9e15f352017-06-03 02:01:24 +0000110// A wasm import to be written into the import section.
111struct WasmImport {
112 StringRef ModuleName;
113 StringRef FieldName;
114 unsigned Kind;
115 int32_t Type;
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000116 bool IsMutable;
Sam Clegg9e15f352017-06-03 02:01:24 +0000117};
118
119// A wasm function to be written into the function section.
120struct WasmFunction {
121 int32_t Type;
122 const MCSymbolWasm *Sym;
123};
124
125// A wasm export to be written into the export section.
126struct WasmExport {
127 StringRef FieldName;
128 unsigned Kind;
129 uint32_t Index;
130};
131
132// A wasm global to be written into the global section.
133struct WasmGlobal {
134 wasm::ValType Type;
135 bool IsMutable;
136 bool HasImport;
137 uint64_t InitialValue;
138 uint32_t ImportIndex;
139};
140
Sam Clegg6dc65e92017-06-06 16:38:59 +0000141// Information about a single relocation.
142struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000143 uint64_t Offset; // Where is the relocation.
144 const MCSymbolWasm *Symbol; // The symbol to relocate with.
145 int64_t Addend; // A value to add to the symbol.
146 unsigned Type; // The type of the relocation.
147 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000148
149 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
150 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000151 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000152 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
153 FixupSection(FixupSection) {}
154
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000155 bool hasAddend() const {
156 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000157 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
158 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
159 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000160 return true;
161 default:
162 return false;
163 }
164 }
165
Sam Clegg6dc65e92017-06-06 16:38:59 +0000166 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000167 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000168 << ", Type=" << Type
169 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000170 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171
Aaron Ballman615eb472017-10-15 14:32:27 +0000172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000173 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
174#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000175};
176
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000177#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000178raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000179 Rel.print(OS);
180 return OS;
181}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000182#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000183
Dan Gohman18eafb62017-02-22 01:23:18 +0000184class WasmObjectWriter : public MCObjectWriter {
185 /// Helper struct for containing some precomputed information on symbols.
186 struct WasmSymbolData {
187 const MCSymbolWasm *Symbol;
188 StringRef Name;
189
190 // Support lexicographic sorting.
191 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
192 };
193
194 /// The target specific Wasm writer instance.
195 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
196
Dan Gohmand934cb82017-02-24 23:18:00 +0000197 // Relocations for fixing up references in the code section.
198 std::vector<WasmRelocationEntry> CodeRelocations;
199
200 // Relocations for fixing up references in the data section.
201 std::vector<WasmRelocationEntry> DataRelocations;
202
Dan Gohmand934cb82017-02-24 23:18:00 +0000203 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000204 // Maps function symbols to the index of the type of the function
205 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000206 // Maps function symbols to the table element index space. Used
207 // for TABLE_INDEX relocation types (i.e. address taken functions).
208 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
209 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000210 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
211
212 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
213 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000214 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000215 SmallVector<WasmGlobal, 4> Globals;
216 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000217
Dan Gohman18eafb62017-02-22 01:23:18 +0000218 // TargetObjectWriter wrappers.
219 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000220 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
221 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000222 }
223
Dan Gohmand934cb82017-02-24 23:18:00 +0000224 void startSection(SectionBookkeeping &Section, unsigned SectionId,
225 const char *Name = nullptr);
226 void endSection(SectionBookkeeping &Section);
227
Dan Gohman18eafb62017-02-22 01:23:18 +0000228public:
Lang Hames1301a872017-10-10 01:15:10 +0000229 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
230 raw_pwrite_stream &OS)
231 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
232 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000233
Dan Gohmand934cb82017-02-24 23:18:00 +0000234private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000235 ~WasmObjectWriter() override;
236
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000237 void reset() override {
238 CodeRelocations.clear();
239 DataRelocations.clear();
240 TypeIndices.clear();
241 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000242 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000243 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000244 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000245 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000246 MCObjectWriter::reset();
Sam Clegg7c395942017-09-14 23:07:53 +0000247 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000248 }
249
Dan Gohman18eafb62017-02-22 01:23:18 +0000250 void writeHeader(const MCAssembler &Asm);
251
252 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
253 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000254 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000255
256 void executePostLayoutBinding(MCAssembler &Asm,
257 const MCAsmLayout &Layout) override;
258
259 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000260
Sam Cleggb7787fd2017-06-20 04:04:59 +0000261 void writeString(const StringRef Str) {
262 encodeULEB128(Str.size(), getStream());
263 writeBytes(Str);
264 }
265
Sam Clegg9e15f352017-06-03 02:01:24 +0000266 void writeValueType(wasm::ValType Ty) {
267 encodeSLEB128(int32_t(Ty), getStream());
268 }
269
Sam Clegg457fb0b2017-09-15 19:50:44 +0000270 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +0000271 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
272 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000273 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000274 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000275 void writeExportSection(ArrayRef<WasmExport> Exports);
276 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000277 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000278 ArrayRef<WasmFunction> Functions);
279 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
280 void writeNameSection(ArrayRef<WasmFunction> Functions,
281 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000282 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000283 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000284 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000285 void writeLinkingMetaDataSection(
286 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Dan Gohmanad19047d2017-12-06 20:56:40 +0000287 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000288
Sam Clegg7c395942017-09-14 23:07:53 +0000289 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000290 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
291 uint64_t ContentsOffset);
292
Sam Clegg7c395942017-09-14 23:07:53 +0000293 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000294 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000295 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
296 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000297};
Sam Clegg9e15f352017-06-03 02:01:24 +0000298
Dan Gohman18eafb62017-02-22 01:23:18 +0000299} // end anonymous namespace
300
301WasmObjectWriter::~WasmObjectWriter() {}
302
Dan Gohmand934cb82017-02-24 23:18:00 +0000303// Write out a section header and a patchable section size field.
304void WasmObjectWriter::startSection(SectionBookkeeping &Section,
305 unsigned SectionId,
306 const char *Name) {
307 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
308 "Only custom sections can have names");
309
Sam Cleggb7787fd2017-06-20 04:04:59 +0000310 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000311 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000312
313 Section.SizeOffset = getStream().tell();
314
315 // The section size. We don't know the size yet, so reserve enough space
316 // for any 32-bit value; we'll patch it later.
317 encodeULEB128(UINT32_MAX, getStream());
318
319 // The position where the section starts, for measuring its size.
320 Section.ContentsOffset = getStream().tell();
321
322 // Custom sections in wasm also have a string identifier.
323 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000324 assert(Name);
325 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000326 }
327}
328
329// Now that the section is complete and we know how big it is, patch up the
330// section size field at the start of the section.
331void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
332 uint64_t Size = getStream().tell() - Section.ContentsOffset;
333 if (uint32_t(Size) != Size)
334 report_fatal_error("section size does not fit in a uint32_t");
335
Sam Cleggb7787fd2017-06-20 04:04:59 +0000336 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000337
338 // Write the final section size to the payload_len field, which follows
339 // the section id byte.
340 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000341 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000342 assert(SizeLen == 5);
343 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
344}
345
Dan Gohman18eafb62017-02-22 01:23:18 +0000346// Emit the Wasm header.
347void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000348 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
349 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000350}
351
352void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
353 const MCAsmLayout &Layout) {
354}
355
356void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
357 const MCAsmLayout &Layout,
358 const MCFragment *Fragment,
359 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000360 uint64_t &FixedValue) {
361 MCAsmBackend &Backend = Asm.getBackend();
362 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
363 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000364 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000365 uint64_t C = Target.getConstant();
366 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
367 MCContext &Ctx = Asm.getContext();
368
369 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
370 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
371 "Should not have constructed this");
372
373 // Let A, B and C being the components of Target and R be the location of
374 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
375 // If it is pcrel, we want to compute (A - B + C - R).
376
377 // In general, Wasm has no relocations for -B. It can only represent (A + C)
378 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
379 // replace B to implement it: (A - R - K + C)
380 if (IsPCRel) {
381 Ctx.reportError(
382 Fixup.getLoc(),
383 "No relocation available to represent this relative expression");
384 return;
385 }
386
387 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
388
389 if (SymB.isUndefined()) {
390 Ctx.reportError(Fixup.getLoc(),
391 Twine("symbol '") + SymB.getName() +
392 "' can not be undefined in a subtraction expression");
393 return;
394 }
395
396 assert(!SymB.isAbsolute() && "Should have been folded");
397 const MCSection &SecB = SymB.getSection();
398 if (&SecB != &FixupSection) {
399 Ctx.reportError(Fixup.getLoc(),
400 "Cannot represent a difference across sections");
401 return;
402 }
403
404 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
405 uint64_t K = SymBOffset - FixupOffset;
406 IsPCRel = true;
407 C -= K;
408 }
409
410 // We either rejected the fixup or folded B into C at this point.
411 const MCSymbolRefExpr *RefA = Target.getSymA();
412 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
413
Dan Gohmand934cb82017-02-24 23:18:00 +0000414 if (SymA && SymA->isVariable()) {
415 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000416 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
417 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
418 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000419 }
420
421 // Put any constant offset in an addend. Offsets can be negative, and
422 // LLVM expects wrapping, in contrast to wasm's immediates which can't
423 // be negative and don't wrap.
424 FixedValue = 0;
425
Sam Clegg6ad8f192017-07-11 02:21:57 +0000426 if (SymA)
427 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000428
Sam Cleggae03c1e72017-06-13 18:51:50 +0000429 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000430 assert(SymA);
431
Sam Cleggae03c1e72017-06-13 18:51:50 +0000432 unsigned Type = getRelocType(Target, Fixup);
433
Dan Gohmand934cb82017-02-24 23:18:00 +0000434 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000435 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000436
Sam Clegg12fd3da2017-10-20 21:28:38 +0000437 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000438 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000439 else if (FixupSection.getKind().isText())
440 CodeRelocations.push_back(Rec);
441 else if (!FixupSection.getKind().isMetadata())
442 // TODO(sbc): Add support for debug sections.
443 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000444}
445
Dan Gohmand934cb82017-02-24 23:18:00 +0000446// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
447// to allow patching.
448static void
449WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
450 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000451 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000452 assert(SizeLen == 5);
453 Stream.pwrite((char *)Buffer, SizeLen, Offset);
454}
455
456// Write X as an signed LEB value at offset Offset in Stream, padded
457// to allow patching.
458static void
459WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
460 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000461 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000462 assert(SizeLen == 5);
463 Stream.pwrite((char *)Buffer, SizeLen, Offset);
464}
465
466// Write X as a plain integer value at offset Offset in Stream.
467static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
468 uint8_t Buffer[4];
469 support::endian::write32le(Buffer, X);
470 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
471}
472
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000473static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
474 if (Symbol.isVariable()) {
475 const MCExpr *Expr = Symbol.getVariableValue();
476 auto *Inner = cast<MCSymbolRefExpr>(Expr);
477 return cast<MCSymbolWasm>(&Inner->getSymbol());
478 }
479 return &Symbol;
480}
481
Dan Gohmand934cb82017-02-24 23:18:00 +0000482// Compute a value to write into the code at the location covered
483// by RelEntry. This value isn't used by the static linker, since
484// we have addends; it just serves to make the code more readable
485// and to make standalone wasm modules directly usable.
Sam Clegg7c395942017-09-14 23:07:53 +0000486uint32_t
487WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000488 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +0000489
490 // For undefined symbols, use a hopefully invalid value.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000491 if (!Sym->isDefined(/*SetUsed=*/false))
Dan Gohmand934cb82017-02-24 23:18:00 +0000492 return UINT32_MAX;
493
Sam Clegg7c395942017-09-14 23:07:53 +0000494 uint32_t GlobalIndex = SymbolIndices[Sym];
495 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
496 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000497
498 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
499 uint32_t Value = Address;
500
501 return Value;
502}
503
Sam Clegg759631c2017-09-15 20:54:59 +0000504static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000505 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000506 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
507
Sam Clegg63ebb812017-09-29 16:50:08 +0000508 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
509
Sam Cleggc55d13f2017-10-27 00:08:55 +0000510 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000511 for (const MCFragment &Frag : DataSection) {
512 if (Frag.hasInstructions())
513 report_fatal_error("only data supported in data sections");
514
515 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
516 if (Align->getValueSize() != 1)
517 report_fatal_error("only byte values supported for alignment");
518 // If nops are requested, use zeros, as this is the data section.
519 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
520 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
521 Align->getAlignment()),
522 DataBytes.size() +
523 Align->getMaxBytesToEmit());
524 DataBytes.resize(Size, Value);
525 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
526 DataBytes.insert(DataBytes.end(), Fill->getSize(), Fill->getValue());
527 } else {
528 const auto &DataFrag = cast<MCDataFragment>(Frag);
529 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
530
531 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000532 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000533 }
534 }
535
Sam Cleggc55d13f2017-10-27 00:08:55 +0000536 // Don't allow empty segments, or segments that end with zero-sized
537 // fragment, otherwise the linker cannot map symbols to a unique
538 // data segment. This can be triggered by zero-sized structs
539 // See: test/MC/WebAssembly/bss.ll
540 if (LastFragmentSize == 0)
541 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000542 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
543}
544
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000545uint32_t WasmObjectWriter::getRelocationIndexValue(
546 const WasmRelocationEntry &RelEntry) {
547 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000548 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
549 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000550 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000551 report_fatal_error("symbol not found table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000552 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000553 return IndirectSymbolIndices[RelEntry.Symbol];
554 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000555 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000556 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
557 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
558 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000559 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000560 report_fatal_error("symbol not found function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000561 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000562 return SymbolIndices[RelEntry.Symbol];
563 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000564 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000565 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000566 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000567 return TypeIndices[RelEntry.Symbol];
568 default:
569 llvm_unreachable("invalid relocation type");
570 }
571}
572
Dan Gohmand934cb82017-02-24 23:18:00 +0000573// Apply the portions of the relocation records that we can handle ourselves
574// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000575void WasmObjectWriter::applyRelocations(
576 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
577 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000578 for (const WasmRelocationEntry &RelEntry : Relocations) {
579 uint64_t Offset = ContentsOffset +
580 RelEntry.FixupSection->getSectionOffset() +
581 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000582
Sam Cleggb7787fd2017-06-20 04:04:59 +0000583 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000584 switch (RelEntry.Type) {
585 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
586 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000587 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
588 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000589 uint32_t Index = getRelocationIndexValue(RelEntry);
590 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000591 break;
592 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000593 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
594 uint32_t Index = getRelocationIndexValue(RelEntry);
595 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000596 break;
597 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000598 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000599 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000600 WritePatchableSLEB(Stream, Value, Offset);
601 break;
602 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000603 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000604 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000605 WritePatchableLEB(Stream, Value, Offset);
606 break;
607 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000608 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
Sam Clegg7c395942017-09-14 23:07:53 +0000609 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000610 WriteI32(Stream, Value, Offset);
611 break;
612 }
613 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000614 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000615 }
616 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000617}
618
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000619// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000620// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000621void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000622 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000623 raw_pwrite_stream &Stream = getStream();
624 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000625
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000626 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000627 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000628 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000629
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000631 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000632 encodeULEB128(Index, Stream);
633 if (RelEntry.hasAddend())
634 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000635 }
636}
637
Sam Clegg9e15f352017-06-03 02:01:24 +0000638void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000639 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000640 if (FunctionTypes.empty())
641 return;
642
643 SectionBookkeeping Section;
644 startSection(Section, wasm::WASM_SEC_TYPE);
645
646 encodeULEB128(FunctionTypes.size(), getStream());
647
648 for (const WasmFunctionType &FuncTy : FunctionTypes) {
649 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
650 encodeULEB128(FuncTy.Params.size(), getStream());
651 for (wasm::ValType Ty : FuncTy.Params)
652 writeValueType(Ty);
653 encodeULEB128(FuncTy.Returns.size(), getStream());
654 for (wasm::ValType Ty : FuncTy.Returns)
655 writeValueType(Ty);
656 }
657
658 endSection(Section);
659}
660
Sam Cleggf950b242017-12-11 23:03:38 +0000661void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
662 uint32_t DataSize,
663 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000664 if (Imports.empty())
665 return;
666
Sam Cleggf950b242017-12-11 23:03:38 +0000667 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
668
Sam Clegg9e15f352017-06-03 02:01:24 +0000669 SectionBookkeeping Section;
670 startSection(Section, wasm::WASM_SEC_IMPORT);
671
672 encodeULEB128(Imports.size(), getStream());
673 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000674 writeString(Import.ModuleName);
675 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000676
677 encodeULEB128(Import.Kind, getStream());
678
679 switch (Import.Kind) {
680 case wasm::WASM_EXTERNAL_FUNCTION:
681 encodeULEB128(Import.Type, getStream());
682 break;
683 case wasm::WASM_EXTERNAL_GLOBAL:
684 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000685 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000686 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000687 case wasm::WASM_EXTERNAL_MEMORY:
688 encodeULEB128(0, getStream()); // flags
689 encodeULEB128(NumPages, getStream()); // initial
690 break;
691 case wasm::WASM_EXTERNAL_TABLE:
692 encodeSLEB128(int32_t(Import.Type), getStream());
693 encodeULEB128(0, getStream()); // flags
694 encodeULEB128(NumElements, getStream()); // initial
695 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000696 default:
697 llvm_unreachable("unsupported import kind");
698 }
699 }
700
701 endSection(Section);
702}
703
Sam Clegg457fb0b2017-09-15 19:50:44 +0000704void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000705 if (Functions.empty())
706 return;
707
708 SectionBookkeeping Section;
709 startSection(Section, wasm::WASM_SEC_FUNCTION);
710
711 encodeULEB128(Functions.size(), getStream());
712 for (const WasmFunction &Func : Functions)
713 encodeULEB128(Func.Type, getStream());
714
715 endSection(Section);
716}
717
Sam Clegg7c395942017-09-14 23:07:53 +0000718void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000719 if (Globals.empty())
720 return;
721
722 SectionBookkeeping Section;
723 startSection(Section, wasm::WASM_SEC_GLOBAL);
724
725 encodeULEB128(Globals.size(), getStream());
726 for (const WasmGlobal &Global : Globals) {
727 writeValueType(Global.Type);
728 write8(Global.IsMutable);
729
730 if (Global.HasImport) {
731 assert(Global.InitialValue == 0);
732 write8(wasm::WASM_OPCODE_GET_GLOBAL);
733 encodeULEB128(Global.ImportIndex, getStream());
734 } else {
735 assert(Global.ImportIndex == 0);
736 write8(wasm::WASM_OPCODE_I32_CONST);
737 encodeSLEB128(Global.InitialValue, getStream()); // offset
738 }
739 write8(wasm::WASM_OPCODE_END);
740 }
741
742 endSection(Section);
743}
744
Sam Clegg457fb0b2017-09-15 19:50:44 +0000745void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 if (Exports.empty())
747 return;
748
749 SectionBookkeeping Section;
750 startSection(Section, wasm::WASM_SEC_EXPORT);
751
752 encodeULEB128(Exports.size(), getStream());
753 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000754 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000755 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000756 encodeULEB128(Export.Index, getStream());
757 }
758
759 endSection(Section);
760}
761
Sam Clegg457fb0b2017-09-15 19:50:44 +0000762void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000763 if (TableElems.empty())
764 return;
765
766 SectionBookkeeping Section;
767 startSection(Section, wasm::WASM_SEC_ELEM);
768
769 encodeULEB128(1, getStream()); // number of "segments"
770 encodeULEB128(0, getStream()); // the table index
771
772 // init expr for starting offset
773 write8(wasm::WASM_OPCODE_I32_CONST);
774 encodeSLEB128(0, getStream());
775 write8(wasm::WASM_OPCODE_END);
776
777 encodeULEB128(TableElems.size(), getStream());
778 for (uint32_t Elem : TableElems)
779 encodeULEB128(Elem, getStream());
780
781 endSection(Section);
782}
783
Sam Clegg457fb0b2017-09-15 19:50:44 +0000784void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
785 const MCAsmLayout &Layout,
786 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000787 if (Functions.empty())
788 return;
789
790 SectionBookkeeping Section;
791 startSection(Section, wasm::WASM_SEC_CODE);
792
793 encodeULEB128(Functions.size(), getStream());
794
795 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000796 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000797
Sam Clegg9e15f352017-06-03 02:01:24 +0000798 int64_t Size = 0;
799 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
800 report_fatal_error(".size expression must be evaluatable");
801
802 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000803 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000804 Asm.writeSectionData(&FuncSection, Layout);
805 }
806
Sam Clegg9e15f352017-06-03 02:01:24 +0000807 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000808 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000809
810 endSection(Section);
811}
812
Sam Clegg457fb0b2017-09-15 19:50:44 +0000813void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000814 if (Segments.empty())
815 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000816
817 SectionBookkeeping Section;
818 startSection(Section, wasm::WASM_SEC_DATA);
819
Sam Clegg7c395942017-09-14 23:07:53 +0000820 encodeULEB128(Segments.size(), getStream()); // count
821
822 for (const WasmDataSegment & Segment : Segments) {
823 encodeULEB128(0, getStream()); // memory index
824 write8(wasm::WASM_OPCODE_I32_CONST);
825 encodeSLEB128(Segment.Offset, getStream()); // offset
826 write8(wasm::WASM_OPCODE_END);
827 encodeULEB128(Segment.Data.size(), getStream()); // size
828 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
829 writeBytes(Segment.Data); // data
830 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000831
832 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000833 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000834
835 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000836}
837
838void WasmObjectWriter::writeNameSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000839 ArrayRef<WasmFunction> Functions,
840 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000841 unsigned NumFuncImports) {
842 uint32_t TotalFunctions = NumFuncImports + Functions.size();
843 if (TotalFunctions == 0)
844 return;
845
846 SectionBookkeeping Section;
847 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
848 SectionBookkeeping SubSection;
849 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
850
851 encodeULEB128(TotalFunctions, getStream());
852 uint32_t Index = 0;
853 for (const WasmImport &Import : Imports) {
854 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
855 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000856 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000857 ++Index;
858 }
859 }
860 for (const WasmFunction &Func : Functions) {
861 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000862 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000863 ++Index;
864 }
865
866 endSection(SubSection);
867 endSection(Section);
868}
869
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000870void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000871 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
872 // for descriptions of the reloc sections.
873
874 if (CodeRelocations.empty())
875 return;
876
877 SectionBookkeeping Section;
878 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
879
880 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000881 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000882
Sam Clegg7c395942017-09-14 23:07:53 +0000883 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000884
885 endSection(Section);
886}
887
Sam Clegg7c395942017-09-14 23:07:53 +0000888void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000889 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
890 // for descriptions of the reloc sections.
891
892 if (DataRelocations.empty())
893 return;
894
895 SectionBookkeeping Section;
896 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
897
898 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
899 encodeULEB128(DataRelocations.size(), getStream());
900
Sam Clegg7c395942017-09-14 23:07:53 +0000901 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000902
903 endSection(Section);
904}
905
906void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000907 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Dan Gohmanad19047d2017-12-06 20:56:40 +0000908 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000909 SectionBookkeeping Section;
910 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000911 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000912
Sam Clegg31a2c802017-09-20 21:17:04 +0000913 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000914 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000915 encodeULEB128(SymbolFlags.size(), getStream());
916 for (auto Pair: SymbolFlags) {
917 writeString(Pair.first);
918 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000919 }
920 endSection(SubSection);
921 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000922
Sam Clegg9e1ade92017-06-27 20:27:59 +0000923 if (DataSize > 0) {
924 startSection(SubSection, wasm::WASM_DATA_SIZE);
925 encodeULEB128(DataSize, getStream());
926 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000927 }
928
Sam Cleggd95ed952017-09-20 19:03:35 +0000929 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000930 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000931 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000932 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000933 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000934 encodeULEB128(Segment.Alignment, getStream());
935 encodeULEB128(Segment.Flags, getStream());
936 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000937 endSection(SubSection);
938 }
939
Sam Clegg9e15f352017-06-03 02:01:24 +0000940 endSection(Section);
941}
942
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000943uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
944 assert(Symbol.isFunction());
945 assert(TypeIndices.count(&Symbol));
946 return TypeIndices[&Symbol];
947}
948
949uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
950 assert(Symbol.isFunction());
951
952 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000953 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
954 F.Returns = ResolvedSym->getReturns();
955 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000956
957 auto Pair =
958 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
959 if (Pair.second)
960 FunctionTypes.push_back(F);
961 TypeIndices[&Symbol] = Pair.first->second;
962
963 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
964 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
965 return Pair.first->second;
966}
967
Dan Gohman18eafb62017-02-22 01:23:18 +0000968void WasmObjectWriter::writeObject(MCAssembler &Asm,
969 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000970 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000971 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000972 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000973
974 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000975 SmallVector<WasmFunction, 4> Functions;
976 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000977 SmallVector<WasmImport, 4> Imports;
978 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +0000979 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Dan Gohmand934cb82017-02-24 23:18:00 +0000980 SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken;
981 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000982 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +0000983 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000984
985 // Populate the IsAddressTaken set.
Sam Cleggb7787fd2017-06-20 04:04:59 +0000986 for (const WasmRelocationEntry &RelEntry : CodeRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000987 switch (RelEntry.Type) {
988 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000989 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000990 IsAddressTaken.insert(RelEntry.Symbol);
991 break;
992 default:
993 break;
994 }
995 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000996 for (const WasmRelocationEntry &RelEntry : DataRelocations) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000997 switch (RelEntry.Type) {
998 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Clegg13a2e892017-09-01 17:32:01 +0000999 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +00001000 IsAddressTaken.insert(RelEntry.Symbol);
1001 break;
1002 default:
1003 break;
1004 }
1005 }
1006
Dan Gohman82607f52017-02-24 23:46:05 +00001007 // In the special .global_variables section, we've encoded global
1008 // variables used by the function. Translate them into the Globals
1009 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +00001010 MCSectionWasm *GlobalVars =
1011 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +00001012 if (!GlobalVars->getFragmentList().empty()) {
1013 if (GlobalVars->getFragmentList().size() != 1)
1014 report_fatal_error("only one .global_variables fragment supported");
1015 const MCFragment &Frag = *GlobalVars->begin();
1016 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1017 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001018 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001019 if (!DataFrag.getFixups().empty())
1020 report_fatal_error("fixups not supported in .global_variables");
1021 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001022 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1023 *end = (const uint8_t *)Contents.data() + Contents.size();
1024 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001025 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001026 if (end - p < 3)
1027 report_fatal_error("truncated global variable encoding");
1028 G.Type = wasm::ValType(int8_t(*p++));
1029 G.IsMutable = bool(*p++);
1030 G.HasImport = bool(*p++);
1031 if (G.HasImport) {
1032 G.InitialValue = 0;
1033
1034 WasmImport Import;
1035 Import.ModuleName = (const char *)p;
1036 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1037 if (!nul)
1038 report_fatal_error("global module name must be nul-terminated");
1039 p = nul + 1;
1040 nul = (const uint8_t *)memchr(p, '\0', end - p);
1041 if (!nul)
1042 report_fatal_error("global base name must be nul-terminated");
1043 Import.FieldName = (const char *)p;
1044 p = nul + 1;
1045
1046 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1047 Import.Type = int32_t(G.Type);
1048
1049 G.ImportIndex = NumGlobalImports;
1050 ++NumGlobalImports;
1051
1052 Imports.push_back(Import);
1053 } else {
1054 unsigned n;
1055 G.InitialValue = decodeSLEB128(p, &n);
1056 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001057 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001058 report_fatal_error("global initial value must be valid SLEB128");
1059 p += n;
1060 }
Dan Gohman82607f52017-02-24 23:46:05 +00001061 Globals.push_back(G);
1062 }
1063 }
1064
Sam Cleggf950b242017-12-11 23:03:38 +00001065 // For now, always emit the memory import, since loads and stores are not
1066 // valid without it. In the future, we could perhaps be more clever and omit
1067 // it if there are no loads or stores.
1068 MCSymbolWasm *MemorySym =
1069 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1070 WasmImport MemImport;
1071 MemImport.ModuleName = MemorySym->getModuleName();
1072 MemImport.FieldName = MemorySym->getName();
1073 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1074 Imports.push_back(MemImport);
1075
1076 // For now, always emit the table section, since indirect calls are not
1077 // valid without it. In the future, we could perhaps be more clever and omit
1078 // it if there are no indirect calls.
1079 MCSymbolWasm *TableSym =
1080 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1081 WasmImport TableImport;
1082 TableImport.ModuleName = TableSym->getModuleName();
1083 TableImport.FieldName = TableSym->getName();
1084 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1085 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1086 Imports.push_back(TableImport);
1087
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001088 // Populate FunctionTypeIndices and Imports.
1089 for (const MCSymbol &S : Asm.symbols()) {
1090 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1091
1092 // Register types for all functions, including those with private linkage
1093 // (making them
1094 // because wasm always needs a type signature.
1095 if (WS.isFunction())
1096 registerFunctionType(WS);
1097
1098 if (WS.isTemporary())
1099 continue;
1100
1101 // If the symbol is not defined in this translation unit, import it.
1102 if (!WS.isDefined(/*SetUsed=*/false)) {
1103 WasmImport Import;
1104 Import.ModuleName = WS.getModuleName();
1105 Import.FieldName = WS.getName();
1106
1107 if (WS.isFunction()) {
1108 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1109 Import.Type = getFunctionType(WS);
1110 SymbolIndices[&WS] = NumFuncImports;
1111 ++NumFuncImports;
1112 } else {
1113 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1114 Import.Type = int32_t(PtrType);
1115 Import.IsMutable = false;
1116 SymbolIndices[&WS] = NumGlobalImports;
1117
1118 // If this global is the stack pointer, make it mutable and remember it
1119 // so that we can emit metadata for it.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001120 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001121 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001122
1123 ++NumGlobalImports;
1124 }
1125
1126 Imports.push_back(Import);
1127 }
1128 }
1129
Sam Clegg759631c2017-09-15 20:54:59 +00001130 for (MCSection &Sec : Asm) {
1131 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001132 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001133 continue;
1134
1135 DataSize = alignTo(DataSize, Section.getAlignment());
1136 DataSegments.emplace_back();
1137 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001138 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001139 Segment.Offset = DataSize;
1140 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001141 addData(Segment.Data, Section);
1142 Segment.Alignment = Section.getAlignment();
1143 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001144 DataSize += Segment.Data.size();
1145 Section.setMemoryOffset(Segment.Offset);
1146 }
1147
Sam Cleggb7787fd2017-06-20 04:04:59 +00001148 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001149 for (const MCSymbol &S : Asm.symbols()) {
1150 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1151 // or used in relocations.
1152 if (S.isTemporary() && S.getName().empty())
1153 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001154
Dan Gohmand934cb82017-02-24 23:18:00 +00001155 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001156 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1157 << " isDefined=" << S.isDefined() << " isExternal="
1158 << S.isExternal() << " isTemporary=" << S.isTemporary()
1159 << " isFunction=" << WS.isFunction()
1160 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001161 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001162 << " isVariable=" << WS.isVariable() << "\n");
1163
Sam Clegga2b35da2017-12-03 01:19:23 +00001164 if (WS.isWeak() || WS.isHidden()) {
1165 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1166 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1167 SymbolFlags.emplace_back(WS.getName(), Flags);
1168 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001169
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001170 if (WS.isVariable())
1171 continue;
1172
Dan Gohmand934cb82017-02-24 23:18:00 +00001173 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001174
Dan Gohmand934cb82017-02-24 23:18:00 +00001175 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001176 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001177 if (WS.getOffset() != 0)
1178 report_fatal_error(
1179 "function sections must contain one function each");
1180
1181 if (WS.getSize() == 0)
1182 report_fatal_error(
1183 "function symbols must have a size set with .size");
1184
Dan Gohmand934cb82017-02-24 23:18:00 +00001185 // A definition. Take the next available index.
1186 Index = NumFuncImports + Functions.size();
1187
1188 // Prepare the function.
1189 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001190 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001191 Func.Sym = &WS;
1192 SymbolIndices[&WS] = Index;
1193 Functions.push_back(Func);
1194 } else {
1195 // An import; the index was assigned above.
1196 Index = SymbolIndices.find(&WS)->second;
1197 }
1198
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001199 DEBUG(dbgs() << " -> function index: " << Index << "\n");
1200
Dan Gohmand934cb82017-02-24 23:18:00 +00001201 // If needed, prepare the function to be called indirectly.
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001202 if (IsAddressTaken.count(&WS) != 0) {
Sam Cleggd99f6072017-06-12 23:52:44 +00001203 IndirectSymbolIndices[&WS] = TableElems.size();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001204 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001205 TableElems.push_back(Index);
Sam Cleggd99f6072017-06-12 23:52:44 +00001206 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001207 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001208 if (WS.isTemporary() && !WS.getSize())
1209 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001210
Sam Cleggfe6414b2017-06-21 23:46:41 +00001211 if (!WS.isDefined(/*SetUsed=*/false))
1212 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001213
Sam Cleggfe6414b2017-06-21 23:46:41 +00001214 if (!WS.getSize())
1215 report_fatal_error("data symbols must have a size set with .size: " +
1216 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001217
Sam Cleggfe6414b2017-06-21 23:46:41 +00001218 int64_t Size = 0;
1219 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1220 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001221
Sam Clegg7c395942017-09-14 23:07:53 +00001222 // For each global, prepare a corresponding wasm global holding its
1223 // address. For externals these will also be named exports.
1224 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001225 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Clegg7c395942017-09-14 23:07:53 +00001226
1227 WasmGlobal Global;
1228 Global.Type = PtrType;
1229 Global.IsMutable = false;
1230 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001231 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001232 Global.ImportIndex = 0;
1233 SymbolIndices[&WS] = Index;
1234 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1235 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001236 }
1237
1238 // If the symbol is visible outside this translation unit, export it.
Sam Clegg31a2c802017-09-20 21:17:04 +00001239 if (WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001240 WasmExport Export;
1241 Export.FieldName = WS.getName();
1242 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 if (WS.isFunction())
1244 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1245 else
1246 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001247 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001248 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001249 if (!WS.isExternal())
1250 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Dan Gohmand934cb82017-02-24 23:18:00 +00001251 }
1252 }
1253
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001254 // Handle weak aliases. We need to process these in a separate pass because
1255 // we need to have processed the target of the alias before the alias itself
1256 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001257 for (const MCSymbol &S : Asm.symbols()) {
1258 if (!S.isVariable())
1259 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001260
Sam Cleggb7787fd2017-06-20 04:04:59 +00001261 assert(S.isDefined(/*SetUsed=*/false));
1262
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001263 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001264 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1265 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001266 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1267 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001268 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001269 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001270
Sam Cleggba9fa9f2017-09-26 21:10:09 +00001271 SymbolIndices[&WS] = Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001272 WasmExport Export;
1273 Export.FieldName = WS.getName();
1274 Export.Index = Index;
1275 if (WS.isFunction())
1276 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1277 else
1278 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001279 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001280 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001281
1282 if (!WS.isExternal())
1283 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001284 }
1285
Dan Gohmand934cb82017-02-24 23:18:00 +00001286 // Add types for indirect function calls.
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001287 for (const WasmRelocationEntry &Fixup : CodeRelocations) {
1288 if (Fixup.Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB)
1289 continue;
Dan Gohman970d02c2017-03-30 23:58:19 +00001290
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001291 registerFunctionType(*Fixup.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +00001292 }
1293
Dan Gohman18eafb62017-02-22 01:23:18 +00001294 // Write out the Wasm header.
1295 writeHeader(Asm);
1296
Sam Clegg9e15f352017-06-03 02:01:24 +00001297 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001298 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001299 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001300 // Skip the "table" section; we import the table instead.
1301 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001302 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001303 writeExportSection(Exports);
1304 // TODO: Start Section
1305 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001306 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001307 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001308 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001309 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001310 writeDataRelocSection();
Dan Gohmanad19047d2017-12-06 20:56:40 +00001311 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags);
Dan Gohman970d02c2017-03-30 23:58:19 +00001312
Dan Gohmand934cb82017-02-24 23:18:00 +00001313 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001314 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001315}
1316
Lang Hames60fbc7c2017-10-10 16:28:07 +00001317std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001318llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1319 raw_pwrite_stream &OS) {
Lang Hames60fbc7c2017-10-10 16:28:07 +00001320 // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's
1321 // destructor is private. Is that necessary?
1322 return std::unique_ptr<MCObjectWriter>(
1323 new WasmObjectWriter(std::move(MOTW), OS));
Dan Gohman18eafb62017-02-22 01:23:18 +00001324}