blob: 4a824b2cae0bebac1dc5ff5f8cd0b8a57c7ed448 [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
Sam Clegg30e1bbc2018-01-19 18:57:01 +000041// Went we ceate the indirect function table we start at 1, so that there is
42// and emtpy slot at 0 and therefore calling a null function pointer will trap.
43static const uint32_t kInitialTableOffset = 1;
44
Dan Gohmand934cb82017-02-24 23:18:00 +000045// For patching purposes, we need to remember where each section starts, both
46// for patching up the section size field, and for patching up references to
47// locations within the section.
48struct SectionBookkeeping {
49 // Where the size of the section is written.
50 uint64_t SizeOffset;
51 // Where the contents of the section starts (after the header).
52 uint64_t ContentsOffset;
53};
54
Sam Clegg9e15f352017-06-03 02:01:24 +000055// The signature of a wasm function, in a struct capable of being used as a
56// DenseMap key.
57struct WasmFunctionType {
58 // Support empty and tombstone instances, needed by DenseMap.
59 enum { Plain, Empty, Tombstone } State;
60
61 // The return types of the function.
62 SmallVector<wasm::ValType, 1> Returns;
63
64 // The parameter types of the function.
65 SmallVector<wasm::ValType, 4> Params;
66
67 WasmFunctionType() : State(Plain) {}
68
69 bool operator==(const WasmFunctionType &Other) const {
70 return State == Other.State && Returns == Other.Returns &&
71 Params == Other.Params;
72 }
73};
74
75// Traits for using WasmFunctionType in a DenseMap.
76struct WasmFunctionTypeDenseMapInfo {
77 static WasmFunctionType getEmptyKey() {
78 WasmFunctionType FuncTy;
79 FuncTy.State = WasmFunctionType::Empty;
80 return FuncTy;
81 }
82 static WasmFunctionType getTombstoneKey() {
83 WasmFunctionType FuncTy;
84 FuncTy.State = WasmFunctionType::Tombstone;
85 return FuncTy;
86 }
87 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
88 uintptr_t Value = FuncTy.State;
89 for (wasm::ValType Ret : FuncTy.Returns)
90 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
91 for (wasm::ValType Param : FuncTy.Params)
92 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
93 return Value;
94 }
95 static bool isEqual(const WasmFunctionType &LHS,
96 const WasmFunctionType &RHS) {
97 return LHS == RHS;
98 }
99};
100
Sam Clegg7c395942017-09-14 23:07:53 +0000101// A wasm data segment. A wasm binary contains only a single data section
102// but that can contain many segments, each with their own virtual location
103// in memory. Each MCSection data created by llvm is modeled as its own
104// wasm data segment.
105struct WasmDataSegment {
106 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000107 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000108 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000109 uint32_t Alignment;
110 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000111 SmallVector<char, 4> Data;
112};
113
Sam Clegg9e15f352017-06-03 02:01:24 +0000114// A wasm import to be written into the import section.
115struct WasmImport {
116 StringRef ModuleName;
117 StringRef FieldName;
118 unsigned Kind;
119 int32_t Type;
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000120 bool IsMutable;
Sam Clegg9e15f352017-06-03 02:01:24 +0000121};
122
123// A wasm function to be written into the function section.
124struct WasmFunction {
125 int32_t Type;
126 const MCSymbolWasm *Sym;
127};
128
129// A wasm export to be written into the export section.
130struct WasmExport {
131 StringRef FieldName;
132 unsigned Kind;
133 uint32_t Index;
134};
135
136// A wasm global to be written into the global section.
137struct WasmGlobal {
138 wasm::ValType Type;
139 bool IsMutable;
140 bool HasImport;
141 uint64_t InitialValue;
142 uint32_t ImportIndex;
143};
144
Sam Cleggea7cace2018-01-09 23:43:14 +0000145// Information about a single item which is part of a COMDAT. For each data
146// segment or function which is in the COMDAT, there is a corresponding
147// WasmComdatEntry.
148struct WasmComdatEntry {
149 unsigned Kind;
150 uint32_t Index;
151};
152
Sam Clegg6dc65e92017-06-06 16:38:59 +0000153// Information about a single relocation.
154struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000155 uint64_t Offset; // Where is the relocation.
156 const MCSymbolWasm *Symbol; // The symbol to relocate with.
157 int64_t Addend; // A value to add to the symbol.
158 unsigned Type; // The type of the relocation.
159 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000160
161 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
162 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000163 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
165 FixupSection(FixupSection) {}
166
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000167 bool hasAddend() const {
168 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000169 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
170 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
171 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000172 return true;
173 default:
174 return false;
175 }
176 }
177
Sam Clegg6dc65e92017-06-06 16:38:59 +0000178 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000179 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000180 << ", Type=" << Type
181 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000182 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000183
Aaron Ballman615eb472017-10-15 14:32:27 +0000184#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000185 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
186#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000187};
188
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000189#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000190raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000191 Rel.print(OS);
192 return OS;
193}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000194#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000195
Dan Gohman18eafb62017-02-22 01:23:18 +0000196class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000197 /// The target specific Wasm writer instance.
198 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
199
Dan Gohmand934cb82017-02-24 23:18:00 +0000200 // Relocations for fixing up references in the code section.
201 std::vector<WasmRelocationEntry> CodeRelocations;
202
203 // Relocations for fixing up references in the data section.
204 std::vector<WasmRelocationEntry> DataRelocations;
205
Dan Gohmand934cb82017-02-24 23:18:00 +0000206 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000207 // Maps function symbols to the index of the type of the function
208 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000209 // Maps function symbols to the table element index space. Used
210 // for TABLE_INDEX relocation types (i.e. address taken functions).
211 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
212 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000213 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
214
215 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
216 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000217 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000218 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000219 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000220 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000221
Dan Gohman18eafb62017-02-22 01:23:18 +0000222 // TargetObjectWriter wrappers.
223 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000224 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
225 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000226 }
227
Dan Gohmand934cb82017-02-24 23:18:00 +0000228 void startSection(SectionBookkeeping &Section, unsigned SectionId,
229 const char *Name = nullptr);
230 void endSection(SectionBookkeeping &Section);
231
Dan Gohman18eafb62017-02-22 01:23:18 +0000232public:
Lang Hames1301a872017-10-10 01:15:10 +0000233 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
234 raw_pwrite_stream &OS)
235 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
236 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000237
Dan Gohman18eafb62017-02-22 01:23:18 +0000238 ~WasmObjectWriter() override;
239
Dan Gohman0917c9e2018-01-15 17:06:23 +0000240private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000241 void reset() override {
242 CodeRelocations.clear();
243 DataRelocations.clear();
244 TypeIndices.clear();
245 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000246 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000247 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000248 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000249 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000250 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000251 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000252 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000253 }
254
Dan Gohman18eafb62017-02-22 01:23:18 +0000255 void writeHeader(const MCAssembler &Asm);
256
257 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
258 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000259 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000260
261 void executePostLayoutBinding(MCAssembler &Asm,
262 const MCAsmLayout &Layout) override;
263
264 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000265
Sam Cleggb7787fd2017-06-20 04:04:59 +0000266 void writeString(const StringRef Str) {
267 encodeULEB128(Str.size(), getStream());
268 writeBytes(Str);
269 }
270
Sam Clegg9e15f352017-06-03 02:01:24 +0000271 void writeValueType(wasm::ValType Ty) {
272 encodeSLEB128(int32_t(Ty), getStream());
273 }
274
Sam Clegg457fb0b2017-09-15 19:50:44 +0000275 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +0000276 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
277 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000278 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000279 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000280 void writeExportSection(ArrayRef<WasmExport> Exports);
281 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000282 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000283 ArrayRef<WasmFunction> Functions);
284 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
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 Cleggea7cace2018-01-09 23:43:14 +0000289 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
290 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
291 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000292
Sam Clegg7c395942017-09-14 23:07:53 +0000293 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000294 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
295 uint64_t ContentsOffset);
296
Sam Clegg7c395942017-09-14 23:07:53 +0000297 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000298 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000299 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
300 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000301};
Sam Clegg9e15f352017-06-03 02:01:24 +0000302
Dan Gohman18eafb62017-02-22 01:23:18 +0000303} // end anonymous namespace
304
305WasmObjectWriter::~WasmObjectWriter() {}
306
Dan Gohmand934cb82017-02-24 23:18:00 +0000307// Write out a section header and a patchable section size field.
308void WasmObjectWriter::startSection(SectionBookkeeping &Section,
309 unsigned SectionId,
310 const char *Name) {
311 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
312 "Only custom sections can have names");
313
Sam Cleggb7787fd2017-06-20 04:04:59 +0000314 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000315 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000316
317 Section.SizeOffset = getStream().tell();
318
319 // The section size. We don't know the size yet, so reserve enough space
320 // for any 32-bit value; we'll patch it later.
321 encodeULEB128(UINT32_MAX, getStream());
322
323 // The position where the section starts, for measuring its size.
324 Section.ContentsOffset = getStream().tell();
325
326 // Custom sections in wasm also have a string identifier.
327 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000328 assert(Name);
329 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000330 }
331}
332
333// Now that the section is complete and we know how big it is, patch up the
334// section size field at the start of the section.
335void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
336 uint64_t Size = getStream().tell() - Section.ContentsOffset;
337 if (uint32_t(Size) != Size)
338 report_fatal_error("section size does not fit in a uint32_t");
339
Sam Cleggb7787fd2017-06-20 04:04:59 +0000340 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000341
342 // Write the final section size to the payload_len field, which follows
343 // the section id byte.
344 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000345 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000346 assert(SizeLen == 5);
347 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
348}
349
Dan Gohman18eafb62017-02-22 01:23:18 +0000350// Emit the Wasm header.
351void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000352 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
353 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000354}
355
356void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
357 const MCAsmLayout &Layout) {
358}
359
360void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
361 const MCAsmLayout &Layout,
362 const MCFragment *Fragment,
363 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000364 uint64_t &FixedValue) {
365 MCAsmBackend &Backend = Asm.getBackend();
366 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
367 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000368 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000369 uint64_t C = Target.getConstant();
370 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
371 MCContext &Ctx = Asm.getContext();
372
Sam Cleggbafe6902017-12-15 00:17:10 +0000373 // The .init_array isn't translated as data, so don't do relocations in it.
374 if (FixupSection.getSectionName().startswith(".init_array"))
375 return;
376
Dan Gohmand934cb82017-02-24 23:18:00 +0000377 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
378 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
379 "Should not have constructed this");
380
381 // Let A, B and C being the components of Target and R be the location of
382 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
383 // If it is pcrel, we want to compute (A - B + C - R).
384
385 // In general, Wasm has no relocations for -B. It can only represent (A + C)
386 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
387 // replace B to implement it: (A - R - K + C)
388 if (IsPCRel) {
389 Ctx.reportError(
390 Fixup.getLoc(),
391 "No relocation available to represent this relative expression");
392 return;
393 }
394
395 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
396
397 if (SymB.isUndefined()) {
398 Ctx.reportError(Fixup.getLoc(),
399 Twine("symbol '") + SymB.getName() +
400 "' can not be undefined in a subtraction expression");
401 return;
402 }
403
404 assert(!SymB.isAbsolute() && "Should have been folded");
405 const MCSection &SecB = SymB.getSection();
406 if (&SecB != &FixupSection) {
407 Ctx.reportError(Fixup.getLoc(),
408 "Cannot represent a difference across sections");
409 return;
410 }
411
412 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
413 uint64_t K = SymBOffset - FixupOffset;
414 IsPCRel = true;
415 C -= K;
416 }
417
418 // We either rejected the fixup or folded B into C at this point.
419 const MCSymbolRefExpr *RefA = Target.getSymA();
420 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
421
Dan Gohmand934cb82017-02-24 23:18:00 +0000422 if (SymA && SymA->isVariable()) {
423 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000424 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
425 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
426 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000427 }
428
429 // Put any constant offset in an addend. Offsets can be negative, and
430 // LLVM expects wrapping, in contrast to wasm's immediates which can't
431 // be negative and don't wrap.
432 FixedValue = 0;
433
Sam Clegg6ad8f192017-07-11 02:21:57 +0000434 if (SymA)
435 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000436
Sam Cleggae03c1e72017-06-13 18:51:50 +0000437 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000438 assert(SymA);
439
Sam Cleggae03c1e72017-06-13 18:51:50 +0000440 unsigned Type = getRelocType(Target, Fixup);
441
Dan Gohmand934cb82017-02-24 23:18:00 +0000442 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000443 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000444
Sam Clegg12fd3da2017-10-20 21:28:38 +0000445 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000446 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000447 else if (FixupSection.getKind().isText())
448 CodeRelocations.push_back(Rec);
449 else if (!FixupSection.getKind().isMetadata())
450 // TODO(sbc): Add support for debug sections.
451 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000452}
453
Dan Gohmand934cb82017-02-24 23:18:00 +0000454// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
455// to allow patching.
456static void
457WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
458 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000459 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000460 assert(SizeLen == 5);
461 Stream.pwrite((char *)Buffer, SizeLen, Offset);
462}
463
464// Write X as an signed LEB value at offset Offset in Stream, padded
465// to allow patching.
466static void
467WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
468 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000469 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000470 assert(SizeLen == 5);
471 Stream.pwrite((char *)Buffer, SizeLen, Offset);
472}
473
474// Write X as a plain integer value at offset Offset in Stream.
475static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
476 uint8_t Buffer[4];
477 support::endian::write32le(Buffer, X);
478 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
479}
480
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000481static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
482 if (Symbol.isVariable()) {
483 const MCExpr *Expr = Symbol.getVariableValue();
484 auto *Inner = cast<MCSymbolRefExpr>(Expr);
485 return cast<MCSymbolWasm>(&Inner->getSymbol());
486 }
487 return &Symbol;
488}
489
Dan Gohmand934cb82017-02-24 23:18:00 +0000490// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000491// by RelEntry. This value isn't used by the static linker; it just serves
492// to make the object format more readable and more likely to be directly
493// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000494uint32_t
495WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000496
Sam Clegg60ec3032018-01-23 01:23:17 +0000497 switch (RelEntry.Type) {
498 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
499 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
500 // Provitional value is the indirect symbol index
501 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
502 report_fatal_error("symbol not found in table index space: " +
503 RelEntry.Symbol->getName());
504 return IndirectSymbolIndices[RelEntry.Symbol];
505 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
506 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
507 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
508 // Provitional value is function/type/global index itself
509 return getRelocationIndexValue(RelEntry);
510 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
511 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
512 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
513 // Provitional value is address of the global
514 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
515 // For undefined symbols, use zero
516 if (!Sym->isDefined())
517 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000518
Sam Clegg60ec3032018-01-23 01:23:17 +0000519 uint32_t GlobalIndex = SymbolIndices[Sym];
520 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
521 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000522
Sam Clegg60ec3032018-01-23 01:23:17 +0000523 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
524 return Address;
525 }
526 default:
527 llvm_unreachable("invalid relocation type");
528 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000529}
530
Sam Clegg759631c2017-09-15 20:54:59 +0000531static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000532 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000533 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
534
Sam Clegg63ebb812017-09-29 16:50:08 +0000535 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
536
Sam Cleggc55d13f2017-10-27 00:08:55 +0000537 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000538 for (const MCFragment &Frag : DataSection) {
539 if (Frag.hasInstructions())
540 report_fatal_error("only data supported in data sections");
541
542 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
543 if (Align->getValueSize() != 1)
544 report_fatal_error("only byte values supported for alignment");
545 // If nops are requested, use zeros, as this is the data section.
546 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
547 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
548 Align->getAlignment()),
549 DataBytes.size() +
550 Align->getMaxBytesToEmit());
551 DataBytes.resize(Size, Value);
552 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000553 int64_t Size;
554 if (!Fill->getSize().evaluateAsAbsolute(Size))
555 llvm_unreachable("The fill should be an assembler constant");
556 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000557 } else {
558 const auto &DataFrag = cast<MCDataFragment>(Frag);
559 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
560
561 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000562 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000563 }
564 }
565
Sam Cleggc55d13f2017-10-27 00:08:55 +0000566 // Don't allow empty segments, or segments that end with zero-sized
567 // fragment, otherwise the linker cannot map symbols to a unique
568 // data segment. This can be triggered by zero-sized structs
569 // See: test/MC/WebAssembly/bss.ll
570 if (LastFragmentSize == 0)
571 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000572 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
573}
574
Sam Clegg60ec3032018-01-23 01:23:17 +0000575uint32_t
576WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
577 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000578 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000579 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000580 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000581 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000582 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000583
584 if (!SymbolIndices.count(RelEntry.Symbol))
585 report_fatal_error("symbol not found in function/global index space: " +
586 RelEntry.Symbol->getName());
587 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000588}
589
Dan Gohmand934cb82017-02-24 23:18:00 +0000590// Apply the portions of the relocation records that we can handle ourselves
591// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000592void WasmObjectWriter::applyRelocations(
593 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
594 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000595 for (const WasmRelocationEntry &RelEntry : Relocations) {
596 uint64_t Offset = ContentsOffset +
597 RelEntry.FixupSection->getSectionOffset() +
598 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000599
Sam Cleggb7787fd2017-06-20 04:04:59 +0000600 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000601 uint32_t Value = getProvisionalValue(RelEntry);
602
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000603 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000604 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000605 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000606 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
607 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000608 WritePatchableLEB(Stream, Value, Offset);
609 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000610 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
611 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000612 WriteI32(Stream, Value, Offset);
613 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000614 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
615 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
616 WritePatchableSLEB(Stream, Value, Offset);
617 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000618 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000619 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000620 }
621 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000622}
623
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000624// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000625// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000626void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000627 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000628 raw_pwrite_stream &Stream = getStream();
629 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000630
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000631 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000632 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000633 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000634
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000635 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000636 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000637 encodeULEB128(Index, Stream);
638 if (RelEntry.hasAddend())
639 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000640 }
641}
642
Sam Clegg9e15f352017-06-03 02:01:24 +0000643void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000644 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000645 if (FunctionTypes.empty())
646 return;
647
648 SectionBookkeeping Section;
649 startSection(Section, wasm::WASM_SEC_TYPE);
650
651 encodeULEB128(FunctionTypes.size(), getStream());
652
653 for (const WasmFunctionType &FuncTy : FunctionTypes) {
654 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
655 encodeULEB128(FuncTy.Params.size(), getStream());
656 for (wasm::ValType Ty : FuncTy.Params)
657 writeValueType(Ty);
658 encodeULEB128(FuncTy.Returns.size(), getStream());
659 for (wasm::ValType Ty : FuncTy.Returns)
660 writeValueType(Ty);
661 }
662
663 endSection(Section);
664}
665
Sam Cleggf950b242017-12-11 23:03:38 +0000666void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
667 uint32_t DataSize,
668 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000669 if (Imports.empty())
670 return;
671
Sam Cleggf950b242017-12-11 23:03:38 +0000672 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
673
Sam Clegg9e15f352017-06-03 02:01:24 +0000674 SectionBookkeeping Section;
675 startSection(Section, wasm::WASM_SEC_IMPORT);
676
677 encodeULEB128(Imports.size(), getStream());
678 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000679 writeString(Import.ModuleName);
680 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000681
682 encodeULEB128(Import.Kind, getStream());
683
684 switch (Import.Kind) {
685 case wasm::WASM_EXTERNAL_FUNCTION:
686 encodeULEB128(Import.Type, getStream());
687 break;
688 case wasm::WASM_EXTERNAL_GLOBAL:
689 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000690 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000691 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000692 case wasm::WASM_EXTERNAL_MEMORY:
693 encodeULEB128(0, getStream()); // flags
694 encodeULEB128(NumPages, getStream()); // initial
695 break;
696 case wasm::WASM_EXTERNAL_TABLE:
697 encodeSLEB128(int32_t(Import.Type), getStream());
698 encodeULEB128(0, getStream()); // flags
699 encodeULEB128(NumElements, getStream()); // initial
700 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000701 default:
702 llvm_unreachable("unsupported import kind");
703 }
704 }
705
706 endSection(Section);
707}
708
Sam Clegg457fb0b2017-09-15 19:50:44 +0000709void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000710 if (Functions.empty())
711 return;
712
713 SectionBookkeeping Section;
714 startSection(Section, wasm::WASM_SEC_FUNCTION);
715
716 encodeULEB128(Functions.size(), getStream());
717 for (const WasmFunction &Func : Functions)
718 encodeULEB128(Func.Type, getStream());
719
720 endSection(Section);
721}
722
Sam Clegg7c395942017-09-14 23:07:53 +0000723void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000724 if (Globals.empty())
725 return;
726
727 SectionBookkeeping Section;
728 startSection(Section, wasm::WASM_SEC_GLOBAL);
729
730 encodeULEB128(Globals.size(), getStream());
731 for (const WasmGlobal &Global : Globals) {
732 writeValueType(Global.Type);
733 write8(Global.IsMutable);
734
735 if (Global.HasImport) {
736 assert(Global.InitialValue == 0);
737 write8(wasm::WASM_OPCODE_GET_GLOBAL);
738 encodeULEB128(Global.ImportIndex, getStream());
739 } else {
740 assert(Global.ImportIndex == 0);
741 write8(wasm::WASM_OPCODE_I32_CONST);
742 encodeSLEB128(Global.InitialValue, getStream()); // offset
743 }
744 write8(wasm::WASM_OPCODE_END);
745 }
746
747 endSection(Section);
748}
749
Sam Clegg457fb0b2017-09-15 19:50:44 +0000750void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000751 if (Exports.empty())
752 return;
753
754 SectionBookkeeping Section;
755 startSection(Section, wasm::WASM_SEC_EXPORT);
756
757 encodeULEB128(Exports.size(), getStream());
758 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000759 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000760 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000761 encodeULEB128(Export.Index, getStream());
762 }
763
764 endSection(Section);
765}
766
Sam Clegg457fb0b2017-09-15 19:50:44 +0000767void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000768 if (TableElems.empty())
769 return;
770
771 SectionBookkeeping Section;
772 startSection(Section, wasm::WASM_SEC_ELEM);
773
774 encodeULEB128(1, getStream()); // number of "segments"
775 encodeULEB128(0, getStream()); // the table index
776
777 // init expr for starting offset
778 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000779 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000780 write8(wasm::WASM_OPCODE_END);
781
782 encodeULEB128(TableElems.size(), getStream());
783 for (uint32_t Elem : TableElems)
784 encodeULEB128(Elem, getStream());
785
786 endSection(Section);
787}
788
Sam Clegg457fb0b2017-09-15 19:50:44 +0000789void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
790 const MCAsmLayout &Layout,
791 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000792 if (Functions.empty())
793 return;
794
795 SectionBookkeeping Section;
796 startSection(Section, wasm::WASM_SEC_CODE);
797
798 encodeULEB128(Functions.size(), getStream());
799
800 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000801 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000802
Sam Clegg9e15f352017-06-03 02:01:24 +0000803 int64_t Size = 0;
804 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
805 report_fatal_error(".size expression must be evaluatable");
806
807 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000808 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000809 Asm.writeSectionData(&FuncSection, Layout);
810 }
811
Sam Clegg9e15f352017-06-03 02:01:24 +0000812 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000813 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000814
815 endSection(Section);
816}
817
Sam Clegg457fb0b2017-09-15 19:50:44 +0000818void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000819 if (Segments.empty())
820 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000821
822 SectionBookkeeping Section;
823 startSection(Section, wasm::WASM_SEC_DATA);
824
Sam Clegg7c395942017-09-14 23:07:53 +0000825 encodeULEB128(Segments.size(), getStream()); // count
826
827 for (const WasmDataSegment & Segment : Segments) {
828 encodeULEB128(0, getStream()); // memory index
829 write8(wasm::WASM_OPCODE_I32_CONST);
830 encodeSLEB128(Segment.Offset, getStream()); // offset
831 write8(wasm::WASM_OPCODE_END);
832 encodeULEB128(Segment.Data.size(), getStream()); // size
833 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
834 writeBytes(Segment.Data); // data
835 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000836
837 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000838 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000839
840 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000841}
842
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000843void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000844 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
845 // for descriptions of the reloc sections.
846
847 if (CodeRelocations.empty())
848 return;
849
850 SectionBookkeeping Section;
851 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
852
853 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000854 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000855
Sam Clegg7c395942017-09-14 23:07:53 +0000856 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
858 endSection(Section);
859}
860
Sam Clegg7c395942017-09-14 23:07:53 +0000861void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000862 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
863 // for descriptions of the reloc sections.
864
865 if (DataRelocations.empty())
866 return;
867
868 SectionBookkeeping Section;
869 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
870
871 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
872 encodeULEB128(DataRelocations.size(), getStream());
873
Sam Clegg7c395942017-09-14 23:07:53 +0000874 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000875
876 endSection(Section);
877}
878
879void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000880 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000881 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
882 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
883 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000884 SectionBookkeeping Section;
885 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000886 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
Sam Clegg31a2c802017-09-20 21:17:04 +0000888 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000889 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000890 encodeULEB128(SymbolFlags.size(), getStream());
891 for (auto Pair: SymbolFlags) {
892 writeString(Pair.first);
893 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000894 }
895 endSection(SubSection);
896 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000897
Sam Clegg9e1ade92017-06-27 20:27:59 +0000898 if (DataSize > 0) {
899 startSection(SubSection, wasm::WASM_DATA_SIZE);
900 encodeULEB128(DataSize, getStream());
901 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000902 }
903
Sam Cleggd95ed952017-09-20 19:03:35 +0000904 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000905 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000906 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000907 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000908 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000909 encodeULEB128(Segment.Alignment, getStream());
910 encodeULEB128(Segment.Flags, getStream());
911 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000912 endSection(SubSection);
913 }
914
Sam Cleggbafe6902017-12-15 00:17:10 +0000915 if (!InitFuncs.empty()) {
916 startSection(SubSection, wasm::WASM_INIT_FUNCS);
917 encodeULEB128(InitFuncs.size(), getStream());
918 for (auto &StartFunc : InitFuncs) {
919 encodeULEB128(StartFunc.first, getStream()); // priority
920 encodeULEB128(StartFunc.second, getStream()); // function index
921 }
922 endSection(SubSection);
923 }
924
Sam Cleggea7cace2018-01-09 23:43:14 +0000925 if (Comdats.size()) {
926 startSection(SubSection, wasm::WASM_COMDAT_INFO);
927 encodeULEB128(Comdats.size(), getStream());
928 for (const auto &C : Comdats) {
929 writeString(C.first);
930 encodeULEB128(0, getStream()); // flags for future use
931 encodeULEB128(C.second.size(), getStream());
932 for (const WasmComdatEntry &Entry : C.second) {
933 encodeULEB128(Entry.Kind, getStream());
934 encodeULEB128(Entry.Index, getStream());
935 }
936 }
937 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;
Sam Cleggbafe6902017-12-15 00:17:10 +0000980 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000981 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
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
Dan Gohman82607f52017-02-24 23:46:05 +0000985 // In the special .global_variables section, we've encoded global
986 // variables used by the function. Translate them into the Globals
987 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +0000988 MCSectionWasm *GlobalVars =
989 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +0000990 if (!GlobalVars->getFragmentList().empty()) {
991 if (GlobalVars->getFragmentList().size() != 1)
992 report_fatal_error("only one .global_variables fragment supported");
993 const MCFragment &Frag = *GlobalVars->begin();
994 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
995 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +0000996 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +0000997 if (!DataFrag.getFixups().empty())
998 report_fatal_error("fixups not supported in .global_variables");
999 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001000 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1001 *end = (const uint8_t *)Contents.data() + Contents.size();
1002 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001003 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001004 if (end - p < 3)
1005 report_fatal_error("truncated global variable encoding");
1006 G.Type = wasm::ValType(int8_t(*p++));
1007 G.IsMutable = bool(*p++);
1008 G.HasImport = bool(*p++);
1009 if (G.HasImport) {
1010 G.InitialValue = 0;
1011
1012 WasmImport Import;
1013 Import.ModuleName = (const char *)p;
1014 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1015 if (!nul)
1016 report_fatal_error("global module name must be nul-terminated");
1017 p = nul + 1;
1018 nul = (const uint8_t *)memchr(p, '\0', end - p);
1019 if (!nul)
1020 report_fatal_error("global base name must be nul-terminated");
1021 Import.FieldName = (const char *)p;
1022 p = nul + 1;
1023
1024 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1025 Import.Type = int32_t(G.Type);
1026
1027 G.ImportIndex = NumGlobalImports;
1028 ++NumGlobalImports;
1029
1030 Imports.push_back(Import);
1031 } else {
1032 unsigned n;
1033 G.InitialValue = decodeSLEB128(p, &n);
1034 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001035 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001036 report_fatal_error("global initial value must be valid SLEB128");
1037 p += n;
1038 }
Dan Gohman82607f52017-02-24 23:46:05 +00001039 Globals.push_back(G);
1040 }
1041 }
1042
Sam Cleggf950b242017-12-11 23:03:38 +00001043 // For now, always emit the memory import, since loads and stores are not
1044 // valid without it. In the future, we could perhaps be more clever and omit
1045 // it if there are no loads or stores.
1046 MCSymbolWasm *MemorySym =
1047 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1048 WasmImport MemImport;
1049 MemImport.ModuleName = MemorySym->getModuleName();
1050 MemImport.FieldName = MemorySym->getName();
1051 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1052 Imports.push_back(MemImport);
1053
1054 // For now, always emit the table section, since indirect calls are not
1055 // valid without it. In the future, we could perhaps be more clever and omit
1056 // it if there are no indirect calls.
1057 MCSymbolWasm *TableSym =
1058 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1059 WasmImport TableImport;
1060 TableImport.ModuleName = TableSym->getModuleName();
1061 TableImport.FieldName = TableSym->getName();
1062 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1063 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1064 Imports.push_back(TableImport);
1065
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001066 // Populate FunctionTypeIndices and Imports.
1067 for (const MCSymbol &S : Asm.symbols()) {
1068 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1069
1070 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001071 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001072 if (WS.isFunction())
1073 registerFunctionType(WS);
1074
1075 if (WS.isTemporary())
1076 continue;
1077
1078 // If the symbol is not defined in this translation unit, import it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001079 if ((!WS.isDefined() && !WS.isComdat()) ||
Sam Cleggd423f0d2018-01-11 20:35:17 +00001080 WS.isVariable()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001081 WasmImport Import;
1082 Import.ModuleName = WS.getModuleName();
1083 Import.FieldName = WS.getName();
1084
1085 if (WS.isFunction()) {
1086 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1087 Import.Type = getFunctionType(WS);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001088 SymbolIndices[&WS] = NumFunctionImports;
1089 ++NumFunctionImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001090 } else {
1091 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1092 Import.Type = int32_t(PtrType);
1093 Import.IsMutable = false;
1094 SymbolIndices[&WS] = NumGlobalImports;
1095
Dan Gohman83b16222017-12-20 00:10:28 +00001096 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001097 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001098 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001099
1100 ++NumGlobalImports;
1101 }
1102
1103 Imports.push_back(Import);
1104 }
1105 }
1106
Sam Clegg759631c2017-09-15 20:54:59 +00001107 for (MCSection &Sec : Asm) {
1108 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001109 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001110 continue;
1111
Sam Cleggbafe6902017-12-15 00:17:10 +00001112 // .init_array sections are handled specially elsewhere.
1113 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1114 continue;
1115
Sam Clegg329e76d2018-01-31 04:21:44 +00001116 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001117 DataSize = alignTo(DataSize, Section.getAlignment());
1118 DataSegments.emplace_back();
1119 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001120 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001121 Segment.Offset = DataSize;
1122 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001123 addData(Segment.Data, Section);
1124 Segment.Alignment = Section.getAlignment();
1125 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001126 DataSize += Segment.Data.size();
1127 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001128
1129 if (const MCSymbolWasm *C = Section.getGroup()) {
1130 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001131 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001132 }
Sam Clegg759631c2017-09-15 20:54:59 +00001133 }
1134
Sam Cleggb7787fd2017-06-20 04:04:59 +00001135 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001136 for (const MCSymbol &S : Asm.symbols()) {
1137 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1138 // or used in relocations.
1139 if (S.isTemporary() && S.getName().empty())
1140 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001141
Dan Gohmand934cb82017-02-24 23:18:00 +00001142 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001143 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001144 << " isDefined=" << S.isDefined()
1145 << " isExternal=" << S.isExternal()
1146 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001147 << " isFunction=" << WS.isFunction()
1148 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001149 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001150 << " isVariable=" << WS.isVariable() << "\n");
1151
Sam Clegga2b35da2017-12-03 01:19:23 +00001152 if (WS.isWeak() || WS.isHidden()) {
1153 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1154 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1155 SymbolFlags.emplace_back(WS.getName(), Flags);
1156 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001157
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001158 if (WS.isVariable())
1159 continue;
1160
Dan Gohmand934cb82017-02-24 23:18:00 +00001161 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001162
Dan Gohmand934cb82017-02-24 23:18:00 +00001163 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001164 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001165 if (WS.getOffset() != 0)
1166 report_fatal_error(
1167 "function sections must contain one function each");
1168
1169 if (WS.getSize() == 0)
1170 report_fatal_error(
1171 "function symbols must have a size set with .size");
1172
Dan Gohmand934cb82017-02-24 23:18:00 +00001173 // A definition. Take the next available index.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001174 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001175
1176 // Prepare the function.
1177 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001178 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001179 Func.Sym = &WS;
1180 SymbolIndices[&WS] = Index;
1181 Functions.push_back(Func);
1182 } else {
1183 // An import; the index was assigned above.
1184 Index = SymbolIndices.find(&WS)->second;
1185 }
1186
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001187 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001188 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001189 if (WS.isTemporary() && !WS.getSize())
1190 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001191
Sam Cleggcd65f692018-01-11 23:59:16 +00001192 if (!WS.isDefined())
Sam Cleggfe6414b2017-06-21 23:46:41 +00001193 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001194
Sam Cleggfe6414b2017-06-21 23:46:41 +00001195 if (!WS.getSize())
1196 report_fatal_error("data symbols must have a size set with .size: " +
1197 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001198
Sam Cleggfe6414b2017-06-21 23:46:41 +00001199 int64_t Size = 0;
1200 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1201 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001202
Sam Clegg7c395942017-09-14 23:07:53 +00001203 // For each global, prepare a corresponding wasm global holding its
1204 // address. For externals these will also be named exports.
1205 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001206 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001207 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001208
1209 WasmGlobal Global;
1210 Global.Type = PtrType;
1211 Global.IsMutable = false;
1212 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001213 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001214 Global.ImportIndex = 0;
1215 SymbolIndices[&WS] = Index;
1216 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1217 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001218 }
1219
1220 // If the symbol is visible outside this translation unit, export it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001221 if (WS.isDefined()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001222 WasmExport Export;
1223 Export.FieldName = WS.getName();
1224 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001225 if (WS.isFunction())
1226 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1227 else
1228 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001229 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001230 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001231
Sam Clegg31a2c802017-09-20 21:17:04 +00001232 if (!WS.isExternal())
1233 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001234
1235 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001236 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001237 if (const MCSymbolWasm *C = Section.getGroup())
1238 Comdats[C->getName()].emplace_back(
1239 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1240 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001241 }
1242 }
1243
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001244 // Handle weak aliases. We need to process these in a separate pass because
1245 // we need to have processed the target of the alias before the alias itself
1246 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001247 for (const MCSymbol &S : Asm.symbols()) {
1248 if (!S.isVariable())
1249 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001250
Sam Cleggcd65f692018-01-11 23:59:16 +00001251 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001252
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001253 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001254 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1255 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001256 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1257 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001258 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001259 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001260
1261 WasmExport Export;
1262 Export.FieldName = WS.getName();
1263 Export.Index = Index;
1264 if (WS.isFunction())
1265 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1266 else
1267 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001268 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001269 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001270
1271 if (!WS.isExternal())
1272 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001273 }
1274
Sam Clegg6006e092017-12-22 20:31:39 +00001275 {
1276 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1277 // Functions referenced by a relocation need to prepared to be called
1278 // indirectly.
1279 const MCSymbolWasm& WS = *Rel.Symbol;
1280 if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
1281 switch (Rel.Type) {
1282 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1283 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1284 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1285 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
1286 uint32_t Index = SymbolIndices.find(&WS)->second;
Sam Clegg30e1bbc2018-01-19 18:57:01 +00001287 IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset;
Sam Clegg329e76d2018-01-31 04:21:44 +00001288 DEBUG(dbgs() << " -> adding " << WS.getName()
1289 << " to table: " << TableElems.size() << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001290 TableElems.push_back(Index);
1291 registerFunctionType(WS);
1292 break;
1293 }
1294 default:
1295 break;
1296 }
1297 }
1298 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001299
Sam Clegg6006e092017-12-22 20:31:39 +00001300 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1301 HandleReloc(RelEntry);
1302 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1303 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001304 }
1305
Sam Cleggbafe6902017-12-15 00:17:10 +00001306 // Translate .init_array section contents into start functions.
1307 for (const MCSection &S : Asm) {
1308 const auto &WS = static_cast<const MCSectionWasm &>(S);
1309 if (WS.getSectionName().startswith(".fini_array"))
1310 report_fatal_error(".fini_array sections are unsupported");
1311 if (!WS.getSectionName().startswith(".init_array"))
1312 continue;
1313 if (WS.getFragmentList().empty())
1314 continue;
1315 if (WS.getFragmentList().size() != 2)
1316 report_fatal_error("only one .init_array section fragment supported");
1317 const MCFragment &AlignFrag = *WS.begin();
1318 if (AlignFrag.getKind() != MCFragment::FT_Align)
1319 report_fatal_error(".init_array section should be aligned");
1320 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1321 report_fatal_error(".init_array section should be aligned for pointers");
1322 const MCFragment &Frag = *std::next(WS.begin());
1323 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1324 report_fatal_error("only data supported in .init_array section");
1325 uint16_t Priority = UINT16_MAX;
1326 if (WS.getSectionName().size() != 11) {
1327 if (WS.getSectionName()[11] != '.')
1328 report_fatal_error(".init_array section priority should start with '.'");
1329 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1330 report_fatal_error("invalid .init_array section priority");
1331 }
1332 const auto &DataFrag = cast<MCDataFragment>(Frag);
1333 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1334 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1335 *end = (const uint8_t *)Contents.data() + Contents.size();
1336 p != end; ++p) {
1337 if (*p != 0)
1338 report_fatal_error("non-symbolic data in .init_array section");
1339 }
1340 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1341 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1342 const MCExpr *Expr = Fixup.getValue();
1343 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1344 if (!Sym)
1345 report_fatal_error("fixups in .init_array should be symbol references");
1346 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1347 report_fatal_error("symbols in .init_array should be for functions");
1348 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1349 if (I == SymbolIndices.end())
1350 report_fatal_error("symbols in .init_array should be defined");
1351 uint32_t Index = I->second;
1352 InitFuncs.push_back(std::make_pair(Priority, Index));
1353 }
1354 }
1355
Dan Gohman18eafb62017-02-22 01:23:18 +00001356 // Write out the Wasm header.
1357 writeHeader(Asm);
1358
Sam Clegg9e15f352017-06-03 02:01:24 +00001359 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001360 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001361 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001362 // Skip the "table" section; we import the table instead.
1363 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001364 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001365 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001366 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001367 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001368 writeDataSection(DataSegments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001369 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001370 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001371 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001372 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001373
Dan Gohmand934cb82017-02-24 23:18:00 +00001374 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001375 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001376}
1377
Lang Hames60fbc7c2017-10-10 16:28:07 +00001378std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001379llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1380 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001381 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001382}