blob: f70d57f5d26b15588165dcb65babcacc801c88d3 [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 {
197 /// Helper struct for containing some precomputed information on symbols.
198 struct WasmSymbolData {
199 const MCSymbolWasm *Symbol;
200 StringRef Name;
201
202 // Support lexicographic sorting.
203 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
204 };
205
206 /// The target specific Wasm writer instance.
207 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
208
Dan Gohmand934cb82017-02-24 23:18:00 +0000209 // Relocations for fixing up references in the code section.
210 std::vector<WasmRelocationEntry> CodeRelocations;
211
212 // Relocations for fixing up references in the data section.
213 std::vector<WasmRelocationEntry> DataRelocations;
214
Dan Gohmand934cb82017-02-24 23:18:00 +0000215 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000216 // Maps function symbols to the index of the type of the function
217 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000218 // Maps function symbols to the table element index space. Used
219 // for TABLE_INDEX relocation types (i.e. address taken functions).
220 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
221 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000222 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
223
224 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
225 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000226 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000227 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000228 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000229 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000230
Dan Gohman18eafb62017-02-22 01:23:18 +0000231 // TargetObjectWriter wrappers.
232 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000233 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
234 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000235 }
236
Dan Gohmand934cb82017-02-24 23:18:00 +0000237 void startSection(SectionBookkeeping &Section, unsigned SectionId,
238 const char *Name = nullptr);
239 void endSection(SectionBookkeeping &Section);
240
Dan Gohman18eafb62017-02-22 01:23:18 +0000241public:
Lang Hames1301a872017-10-10 01:15:10 +0000242 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
243 raw_pwrite_stream &OS)
244 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
245 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000246
Dan Gohman18eafb62017-02-22 01:23:18 +0000247 ~WasmObjectWriter() override;
248
Dan Gohman0917c9e2018-01-15 17:06:23 +0000249private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000250 void reset() override {
251 CodeRelocations.clear();
252 DataRelocations.clear();
253 TypeIndices.clear();
254 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000255 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000256 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000257 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000258 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000259 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000260 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000261 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000262 }
263
Dan Gohman18eafb62017-02-22 01:23:18 +0000264 void writeHeader(const MCAssembler &Asm);
265
266 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
267 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000268 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000269
270 void executePostLayoutBinding(MCAssembler &Asm,
271 const MCAsmLayout &Layout) override;
272
273 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000274
Sam Cleggb7787fd2017-06-20 04:04:59 +0000275 void writeString(const StringRef Str) {
276 encodeULEB128(Str.size(), getStream());
277 writeBytes(Str);
278 }
279
Sam Clegg9e15f352017-06-03 02:01:24 +0000280 void writeValueType(wasm::ValType Ty) {
281 encodeSLEB128(int32_t(Ty), getStream());
282 }
283
Sam Clegg457fb0b2017-09-15 19:50:44 +0000284 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +0000285 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
286 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000287 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000288 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000289 void writeExportSection(ArrayRef<WasmExport> Exports);
290 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000291 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000292 ArrayRef<WasmFunction> Functions);
293 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
294 void writeNameSection(ArrayRef<WasmFunction> Functions,
Sam Clegg9f3fe422018-01-17 19:28:43 +0000295 ArrayRef<WasmImport> Imports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000296 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000297 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000298 void writeLinkingMetaDataSection(
299 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000300 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
301 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
302 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000303
Sam Clegg7c395942017-09-14 23:07:53 +0000304 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000305 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
306 uint64_t ContentsOffset);
307
Sam Clegg7c395942017-09-14 23:07:53 +0000308 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000309 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000310 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
311 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000312};
Sam Clegg9e15f352017-06-03 02:01:24 +0000313
Dan Gohman18eafb62017-02-22 01:23:18 +0000314} // end anonymous namespace
315
316WasmObjectWriter::~WasmObjectWriter() {}
317
Dan Gohmand934cb82017-02-24 23:18:00 +0000318// Write out a section header and a patchable section size field.
319void WasmObjectWriter::startSection(SectionBookkeeping &Section,
320 unsigned SectionId,
321 const char *Name) {
322 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
323 "Only custom sections can have names");
324
Sam Cleggb7787fd2017-06-20 04:04:59 +0000325 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000326 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000327
328 Section.SizeOffset = getStream().tell();
329
330 // The section size. We don't know the size yet, so reserve enough space
331 // for any 32-bit value; we'll patch it later.
332 encodeULEB128(UINT32_MAX, getStream());
333
334 // The position where the section starts, for measuring its size.
335 Section.ContentsOffset = getStream().tell();
336
337 // Custom sections in wasm also have a string identifier.
338 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000339 assert(Name);
340 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000341 }
342}
343
344// Now that the section is complete and we know how big it is, patch up the
345// section size field at the start of the section.
346void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
347 uint64_t Size = getStream().tell() - Section.ContentsOffset;
348 if (uint32_t(Size) != Size)
349 report_fatal_error("section size does not fit in a uint32_t");
350
Sam Cleggb7787fd2017-06-20 04:04:59 +0000351 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000352
353 // Write the final section size to the payload_len field, which follows
354 // the section id byte.
355 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000356 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000357 assert(SizeLen == 5);
358 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
359}
360
Dan Gohman18eafb62017-02-22 01:23:18 +0000361// Emit the Wasm header.
362void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000363 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
364 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000365}
366
367void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
368 const MCAsmLayout &Layout) {
369}
370
371void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
372 const MCAsmLayout &Layout,
373 const MCFragment *Fragment,
374 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000375 uint64_t &FixedValue) {
376 MCAsmBackend &Backend = Asm.getBackend();
377 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
378 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000379 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000380 uint64_t C = Target.getConstant();
381 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
382 MCContext &Ctx = Asm.getContext();
383
Sam Cleggbafe6902017-12-15 00:17:10 +0000384 // The .init_array isn't translated as data, so don't do relocations in it.
385 if (FixupSection.getSectionName().startswith(".init_array"))
386 return;
387
Dan Gohmand934cb82017-02-24 23:18:00 +0000388 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
389 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
390 "Should not have constructed this");
391
392 // Let A, B and C being the components of Target and R be the location of
393 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
394 // If it is pcrel, we want to compute (A - B + C - R).
395
396 // In general, Wasm has no relocations for -B. It can only represent (A + C)
397 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
398 // replace B to implement it: (A - R - K + C)
399 if (IsPCRel) {
400 Ctx.reportError(
401 Fixup.getLoc(),
402 "No relocation available to represent this relative expression");
403 return;
404 }
405
406 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
407
408 if (SymB.isUndefined()) {
409 Ctx.reportError(Fixup.getLoc(),
410 Twine("symbol '") + SymB.getName() +
411 "' can not be undefined in a subtraction expression");
412 return;
413 }
414
415 assert(!SymB.isAbsolute() && "Should have been folded");
416 const MCSection &SecB = SymB.getSection();
417 if (&SecB != &FixupSection) {
418 Ctx.reportError(Fixup.getLoc(),
419 "Cannot represent a difference across sections");
420 return;
421 }
422
423 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
424 uint64_t K = SymBOffset - FixupOffset;
425 IsPCRel = true;
426 C -= K;
427 }
428
429 // We either rejected the fixup or folded B into C at this point.
430 const MCSymbolRefExpr *RefA = Target.getSymA();
431 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
432
Dan Gohmand934cb82017-02-24 23:18:00 +0000433 if (SymA && SymA->isVariable()) {
434 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000435 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
436 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
437 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000438 }
439
440 // Put any constant offset in an addend. Offsets can be negative, and
441 // LLVM expects wrapping, in contrast to wasm's immediates which can't
442 // be negative and don't wrap.
443 FixedValue = 0;
444
Sam Clegg6ad8f192017-07-11 02:21:57 +0000445 if (SymA)
446 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000447
Sam Cleggae03c1e72017-06-13 18:51:50 +0000448 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000449 assert(SymA);
450
Sam Cleggae03c1e72017-06-13 18:51:50 +0000451 unsigned Type = getRelocType(Target, Fixup);
452
Dan Gohmand934cb82017-02-24 23:18:00 +0000453 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000454 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000455
Sam Clegg12fd3da2017-10-20 21:28:38 +0000456 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000457 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000458 else if (FixupSection.getKind().isText())
459 CodeRelocations.push_back(Rec);
460 else if (!FixupSection.getKind().isMetadata())
461 // TODO(sbc): Add support for debug sections.
462 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000463}
464
Dan Gohmand934cb82017-02-24 23:18:00 +0000465// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
466// to allow patching.
467static void
468WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
469 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000470 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000471 assert(SizeLen == 5);
472 Stream.pwrite((char *)Buffer, SizeLen, Offset);
473}
474
475// Write X as an signed LEB value at offset Offset in Stream, padded
476// to allow patching.
477static void
478WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
479 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000480 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000481 assert(SizeLen == 5);
482 Stream.pwrite((char *)Buffer, SizeLen, Offset);
483}
484
485// Write X as a plain integer value at offset Offset in Stream.
486static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
487 uint8_t Buffer[4];
488 support::endian::write32le(Buffer, X);
489 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
490}
491
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000492static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
493 if (Symbol.isVariable()) {
494 const MCExpr *Expr = Symbol.getVariableValue();
495 auto *Inner = cast<MCSymbolRefExpr>(Expr);
496 return cast<MCSymbolWasm>(&Inner->getSymbol());
497 }
498 return &Symbol;
499}
500
Dan Gohmand934cb82017-02-24 23:18:00 +0000501// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000502// by RelEntry. This value isn't used by the static linker; it just serves
503// to make the object format more readable and more likely to be directly
504// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000505uint32_t
506WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000507
Sam Clegg60ec3032018-01-23 01:23:17 +0000508 switch (RelEntry.Type) {
509 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
510 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
511 // Provitional value is the indirect symbol index
512 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
513 report_fatal_error("symbol not found in table index space: " +
514 RelEntry.Symbol->getName());
515 return IndirectSymbolIndices[RelEntry.Symbol];
516 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
517 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
518 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
519 // Provitional value is function/type/global index itself
520 return getRelocationIndexValue(RelEntry);
521 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
522 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
523 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
524 // Provitional value is address of the global
525 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
526 // For undefined symbols, use zero
527 if (!Sym->isDefined())
528 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000529
Sam Clegg60ec3032018-01-23 01:23:17 +0000530 uint32_t GlobalIndex = SymbolIndices[Sym];
531 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
532 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000533
Sam Clegg60ec3032018-01-23 01:23:17 +0000534 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
535 return Address;
536 }
537 default:
538 llvm_unreachable("invalid relocation type");
539 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000540}
541
Sam Clegg759631c2017-09-15 20:54:59 +0000542static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000543 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000544 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
545
Sam Clegg63ebb812017-09-29 16:50:08 +0000546 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
547
Sam Cleggc55d13f2017-10-27 00:08:55 +0000548 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000549 for (const MCFragment &Frag : DataSection) {
550 if (Frag.hasInstructions())
551 report_fatal_error("only data supported in data sections");
552
553 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
554 if (Align->getValueSize() != 1)
555 report_fatal_error("only byte values supported for alignment");
556 // If nops are requested, use zeros, as this is the data section.
557 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
558 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
559 Align->getAlignment()),
560 DataBytes.size() +
561 Align->getMaxBytesToEmit());
562 DataBytes.resize(Size, Value);
563 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000564 int64_t Size;
565 if (!Fill->getSize().evaluateAsAbsolute(Size))
566 llvm_unreachable("The fill should be an assembler constant");
567 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000568 } else {
569 const auto &DataFrag = cast<MCDataFragment>(Frag);
570 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
571
572 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000573 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000574 }
575 }
576
Sam Cleggc55d13f2017-10-27 00:08:55 +0000577 // Don't allow empty segments, or segments that end with zero-sized
578 // fragment, otherwise the linker cannot map symbols to a unique
579 // data segment. This can be triggered by zero-sized structs
580 // See: test/MC/WebAssembly/bss.ll
581 if (LastFragmentSize == 0)
582 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000583 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
584}
585
Sam Clegg60ec3032018-01-23 01:23:17 +0000586uint32_t
587WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
588 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000589 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000590 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000591 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000592 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000593 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000594
595 if (!SymbolIndices.count(RelEntry.Symbol))
596 report_fatal_error("symbol not found in function/global index space: " +
597 RelEntry.Symbol->getName());
598 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000599}
600
Dan Gohmand934cb82017-02-24 23:18:00 +0000601// Apply the portions of the relocation records that we can handle ourselves
602// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000603void WasmObjectWriter::applyRelocations(
604 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
605 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000606 for (const WasmRelocationEntry &RelEntry : Relocations) {
607 uint64_t Offset = ContentsOffset +
608 RelEntry.FixupSection->getSectionOffset() +
609 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000610
Sam Cleggb7787fd2017-06-20 04:04:59 +0000611 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000612 uint32_t Value = getProvisionalValue(RelEntry);
613
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000614 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000615 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000616 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000617 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
618 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000619 WritePatchableLEB(Stream, Value, Offset);
620 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000621 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
622 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000623 WriteI32(Stream, Value, Offset);
624 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000625 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
626 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
627 WritePatchableSLEB(Stream, Value, Offset);
628 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000629 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000630 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000631 }
632 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000633}
634
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000635// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000636// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000637void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000638 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000639 raw_pwrite_stream &Stream = getStream();
640 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000641
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000642 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000643 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000644 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000645
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000646 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000647 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000648 encodeULEB128(Index, Stream);
649 if (RelEntry.hasAddend())
650 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000651 }
652}
653
Sam Clegg9e15f352017-06-03 02:01:24 +0000654void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000655 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000656 if (FunctionTypes.empty())
657 return;
658
659 SectionBookkeeping Section;
660 startSection(Section, wasm::WASM_SEC_TYPE);
661
662 encodeULEB128(FunctionTypes.size(), getStream());
663
664 for (const WasmFunctionType &FuncTy : FunctionTypes) {
665 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
666 encodeULEB128(FuncTy.Params.size(), getStream());
667 for (wasm::ValType Ty : FuncTy.Params)
668 writeValueType(Ty);
669 encodeULEB128(FuncTy.Returns.size(), getStream());
670 for (wasm::ValType Ty : FuncTy.Returns)
671 writeValueType(Ty);
672 }
673
674 endSection(Section);
675}
676
Sam Cleggf950b242017-12-11 23:03:38 +0000677void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
678 uint32_t DataSize,
679 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000680 if (Imports.empty())
681 return;
682
Sam Cleggf950b242017-12-11 23:03:38 +0000683 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
684
Sam Clegg9e15f352017-06-03 02:01:24 +0000685 SectionBookkeeping Section;
686 startSection(Section, wasm::WASM_SEC_IMPORT);
687
688 encodeULEB128(Imports.size(), getStream());
689 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000690 writeString(Import.ModuleName);
691 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000692
693 encodeULEB128(Import.Kind, getStream());
694
695 switch (Import.Kind) {
696 case wasm::WASM_EXTERNAL_FUNCTION:
697 encodeULEB128(Import.Type, getStream());
698 break;
699 case wasm::WASM_EXTERNAL_GLOBAL:
700 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000701 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000702 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000703 case wasm::WASM_EXTERNAL_MEMORY:
704 encodeULEB128(0, getStream()); // flags
705 encodeULEB128(NumPages, getStream()); // initial
706 break;
707 case wasm::WASM_EXTERNAL_TABLE:
708 encodeSLEB128(int32_t(Import.Type), getStream());
709 encodeULEB128(0, getStream()); // flags
710 encodeULEB128(NumElements, getStream()); // initial
711 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 default:
713 llvm_unreachable("unsupported import kind");
714 }
715 }
716
717 endSection(Section);
718}
719
Sam Clegg457fb0b2017-09-15 19:50:44 +0000720void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000721 if (Functions.empty())
722 return;
723
724 SectionBookkeeping Section;
725 startSection(Section, wasm::WASM_SEC_FUNCTION);
726
727 encodeULEB128(Functions.size(), getStream());
728 for (const WasmFunction &Func : Functions)
729 encodeULEB128(Func.Type, getStream());
730
731 endSection(Section);
732}
733
Sam Clegg7c395942017-09-14 23:07:53 +0000734void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000735 if (Globals.empty())
736 return;
737
738 SectionBookkeeping Section;
739 startSection(Section, wasm::WASM_SEC_GLOBAL);
740
741 encodeULEB128(Globals.size(), getStream());
742 for (const WasmGlobal &Global : Globals) {
743 writeValueType(Global.Type);
744 write8(Global.IsMutable);
745
746 if (Global.HasImport) {
747 assert(Global.InitialValue == 0);
748 write8(wasm::WASM_OPCODE_GET_GLOBAL);
749 encodeULEB128(Global.ImportIndex, getStream());
750 } else {
751 assert(Global.ImportIndex == 0);
752 write8(wasm::WASM_OPCODE_I32_CONST);
753 encodeSLEB128(Global.InitialValue, getStream()); // offset
754 }
755 write8(wasm::WASM_OPCODE_END);
756 }
757
758 endSection(Section);
759}
760
Sam Clegg457fb0b2017-09-15 19:50:44 +0000761void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000762 if (Exports.empty())
763 return;
764
765 SectionBookkeeping Section;
766 startSection(Section, wasm::WASM_SEC_EXPORT);
767
768 encodeULEB128(Exports.size(), getStream());
769 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000770 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000771 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000772 encodeULEB128(Export.Index, getStream());
773 }
774
775 endSection(Section);
776}
777
Sam Clegg457fb0b2017-09-15 19:50:44 +0000778void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 if (TableElems.empty())
780 return;
781
782 SectionBookkeeping Section;
783 startSection(Section, wasm::WASM_SEC_ELEM);
784
785 encodeULEB128(1, getStream()); // number of "segments"
786 encodeULEB128(0, getStream()); // the table index
787
788 // init expr for starting offset
789 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000790 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 write8(wasm::WASM_OPCODE_END);
792
793 encodeULEB128(TableElems.size(), getStream());
794 for (uint32_t Elem : TableElems)
795 encodeULEB128(Elem, getStream());
796
797 endSection(Section);
798}
799
Sam Clegg457fb0b2017-09-15 19:50:44 +0000800void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
801 const MCAsmLayout &Layout,
802 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000803 if (Functions.empty())
804 return;
805
806 SectionBookkeeping Section;
807 startSection(Section, wasm::WASM_SEC_CODE);
808
809 encodeULEB128(Functions.size(), getStream());
810
811 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000812 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000813
Sam Clegg9e15f352017-06-03 02:01:24 +0000814 int64_t Size = 0;
815 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
816 report_fatal_error(".size expression must be evaluatable");
817
818 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000819 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000820 Asm.writeSectionData(&FuncSection, Layout);
821 }
822
Sam Clegg9e15f352017-06-03 02:01:24 +0000823 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000824 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000825
826 endSection(Section);
827}
828
Sam Clegg457fb0b2017-09-15 19:50:44 +0000829void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000830 if (Segments.empty())
831 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000832
833 SectionBookkeeping Section;
834 startSection(Section, wasm::WASM_SEC_DATA);
835
Sam Clegg7c395942017-09-14 23:07:53 +0000836 encodeULEB128(Segments.size(), getStream()); // count
837
838 for (const WasmDataSegment & Segment : Segments) {
839 encodeULEB128(0, getStream()); // memory index
840 write8(wasm::WASM_OPCODE_I32_CONST);
841 encodeSLEB128(Segment.Offset, getStream()); // offset
842 write8(wasm::WASM_OPCODE_END);
843 encodeULEB128(Segment.Data.size(), getStream()); // size
844 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
845 writeBytes(Segment.Data); // data
846 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000847
848 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000849 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000850
851 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000852}
853
Sam Clegg9f3fe422018-01-17 19:28:43 +0000854void WasmObjectWriter::writeNameSection(ArrayRef<WasmFunction> Functions,
855 ArrayRef<WasmImport> Imports) {
856 uint32_t TotalFunctions = NumFunctionImports + Functions.size();
Sam Clegg9e15f352017-06-03 02:01:24 +0000857 if (TotalFunctions == 0)
858 return;
859
860 SectionBookkeeping Section;
861 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
862 SectionBookkeeping SubSection;
863 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
864
865 encodeULEB128(TotalFunctions, getStream());
866 uint32_t Index = 0;
867 for (const WasmImport &Import : Imports) {
868 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
869 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000870 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000871 ++Index;
872 }
873 }
874 for (const WasmFunction &Func : Functions) {
875 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000876 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000877 ++Index;
878 }
879
880 endSection(SubSection);
881 endSection(Section);
882}
883
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000884void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000885 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
886 // for descriptions of the reloc sections.
887
888 if (CodeRelocations.empty())
889 return;
890
891 SectionBookkeeping Section;
892 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
893
894 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000895 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000896
Sam Clegg7c395942017-09-14 23:07:53 +0000897 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000898
899 endSection(Section);
900}
901
Sam Clegg7c395942017-09-14 23:07:53 +0000902void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000903 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
904 // for descriptions of the reloc sections.
905
906 if (DataRelocations.empty())
907 return;
908
909 SectionBookkeeping Section;
910 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
911
912 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
913 encodeULEB128(DataRelocations.size(), getStream());
914
Sam Clegg7c395942017-09-14 23:07:53 +0000915 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000916
917 endSection(Section);
918}
919
920void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000921 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000922 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
923 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
924 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000925 SectionBookkeeping Section;
926 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000927 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000928
Sam Clegg31a2c802017-09-20 21:17:04 +0000929 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000930 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000931 encodeULEB128(SymbolFlags.size(), getStream());
932 for (auto Pair: SymbolFlags) {
933 writeString(Pair.first);
934 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000935 }
936 endSection(SubSection);
937 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000938
Sam Clegg9e1ade92017-06-27 20:27:59 +0000939 if (DataSize > 0) {
940 startSection(SubSection, wasm::WASM_DATA_SIZE);
941 encodeULEB128(DataSize, getStream());
942 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000943 }
944
Sam Cleggd95ed952017-09-20 19:03:35 +0000945 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000946 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000947 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000948 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000949 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000950 encodeULEB128(Segment.Alignment, getStream());
951 encodeULEB128(Segment.Flags, getStream());
952 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000953 endSection(SubSection);
954 }
955
Sam Cleggbafe6902017-12-15 00:17:10 +0000956 if (!InitFuncs.empty()) {
957 startSection(SubSection, wasm::WASM_INIT_FUNCS);
958 encodeULEB128(InitFuncs.size(), getStream());
959 for (auto &StartFunc : InitFuncs) {
960 encodeULEB128(StartFunc.first, getStream()); // priority
961 encodeULEB128(StartFunc.second, getStream()); // function index
962 }
963 endSection(SubSection);
964 }
965
Sam Cleggea7cace2018-01-09 23:43:14 +0000966 if (Comdats.size()) {
967 startSection(SubSection, wasm::WASM_COMDAT_INFO);
968 encodeULEB128(Comdats.size(), getStream());
969 for (const auto &C : Comdats) {
970 writeString(C.first);
971 encodeULEB128(0, getStream()); // flags for future use
972 encodeULEB128(C.second.size(), getStream());
973 for (const WasmComdatEntry &Entry : C.second) {
974 encodeULEB128(Entry.Kind, getStream());
975 encodeULEB128(Entry.Index, getStream());
976 }
977 }
978 endSection(SubSection);
979 }
980
Sam Clegg9e15f352017-06-03 02:01:24 +0000981 endSection(Section);
982}
983
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000984uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
985 assert(Symbol.isFunction());
986 assert(TypeIndices.count(&Symbol));
987 return TypeIndices[&Symbol];
988}
989
990uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
991 assert(Symbol.isFunction());
992
993 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000994 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
995 F.Returns = ResolvedSym->getReturns();
996 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000997
998 auto Pair =
999 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1000 if (Pair.second)
1001 FunctionTypes.push_back(F);
1002 TypeIndices[&Symbol] = Pair.first->second;
1003
1004 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
1005 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
1006 return Pair.first->second;
1007}
1008
Dan Gohman18eafb62017-02-22 01:23:18 +00001009void WasmObjectWriter::writeObject(MCAssembler &Asm,
1010 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001011 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001012 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +00001013 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +00001014
1015 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001016 SmallVector<WasmFunction, 4> Functions;
1017 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +00001018 SmallVector<WasmImport, 4> Imports;
1019 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +00001020 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Sam Cleggbafe6902017-12-15 00:17:10 +00001021 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001022 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001023 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +00001024 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001025
Dan Gohman82607f52017-02-24 23:46:05 +00001026 // In the special .global_variables section, we've encoded global
1027 // variables used by the function. Translate them into the Globals
1028 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +00001029 MCSectionWasm *GlobalVars =
1030 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +00001031 if (!GlobalVars->getFragmentList().empty()) {
1032 if (GlobalVars->getFragmentList().size() != 1)
1033 report_fatal_error("only one .global_variables fragment supported");
1034 const MCFragment &Frag = *GlobalVars->begin();
1035 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1036 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001037 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001038 if (!DataFrag.getFixups().empty())
1039 report_fatal_error("fixups not supported in .global_variables");
1040 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001041 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1042 *end = (const uint8_t *)Contents.data() + Contents.size();
1043 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001044 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001045 if (end - p < 3)
1046 report_fatal_error("truncated global variable encoding");
1047 G.Type = wasm::ValType(int8_t(*p++));
1048 G.IsMutable = bool(*p++);
1049 G.HasImport = bool(*p++);
1050 if (G.HasImport) {
1051 G.InitialValue = 0;
1052
1053 WasmImport Import;
1054 Import.ModuleName = (const char *)p;
1055 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1056 if (!nul)
1057 report_fatal_error("global module name must be nul-terminated");
1058 p = nul + 1;
1059 nul = (const uint8_t *)memchr(p, '\0', end - p);
1060 if (!nul)
1061 report_fatal_error("global base name must be nul-terminated");
1062 Import.FieldName = (const char *)p;
1063 p = nul + 1;
1064
1065 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1066 Import.Type = int32_t(G.Type);
1067
1068 G.ImportIndex = NumGlobalImports;
1069 ++NumGlobalImports;
1070
1071 Imports.push_back(Import);
1072 } else {
1073 unsigned n;
1074 G.InitialValue = decodeSLEB128(p, &n);
1075 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001076 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001077 report_fatal_error("global initial value must be valid SLEB128");
1078 p += n;
1079 }
Dan Gohman82607f52017-02-24 23:46:05 +00001080 Globals.push_back(G);
1081 }
1082 }
1083
Sam Cleggf950b242017-12-11 23:03:38 +00001084 // For now, always emit the memory import, since loads and stores are not
1085 // valid without it. In the future, we could perhaps be more clever and omit
1086 // it if there are no loads or stores.
1087 MCSymbolWasm *MemorySym =
1088 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1089 WasmImport MemImport;
1090 MemImport.ModuleName = MemorySym->getModuleName();
1091 MemImport.FieldName = MemorySym->getName();
1092 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1093 Imports.push_back(MemImport);
1094
1095 // For now, always emit the table section, since indirect calls are not
1096 // valid without it. In the future, we could perhaps be more clever and omit
1097 // it if there are no indirect calls.
1098 MCSymbolWasm *TableSym =
1099 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1100 WasmImport TableImport;
1101 TableImport.ModuleName = TableSym->getModuleName();
1102 TableImport.FieldName = TableSym->getName();
1103 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1104 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1105 Imports.push_back(TableImport);
1106
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001107 // Populate FunctionTypeIndices and Imports.
1108 for (const MCSymbol &S : Asm.symbols()) {
1109 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1110
1111 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001112 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001113 if (WS.isFunction())
1114 registerFunctionType(WS);
1115
1116 if (WS.isTemporary())
1117 continue;
1118
1119 // If the symbol is not defined in this translation unit, import it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001120 if ((!WS.isDefined() && !WS.isComdat()) ||
Sam Cleggd423f0d2018-01-11 20:35:17 +00001121 WS.isVariable()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001122 WasmImport Import;
1123 Import.ModuleName = WS.getModuleName();
1124 Import.FieldName = WS.getName();
1125
1126 if (WS.isFunction()) {
1127 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1128 Import.Type = getFunctionType(WS);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001129 SymbolIndices[&WS] = NumFunctionImports;
1130 ++NumFunctionImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001131 } else {
1132 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1133 Import.Type = int32_t(PtrType);
1134 Import.IsMutable = false;
1135 SymbolIndices[&WS] = NumGlobalImports;
1136
Dan Gohman83b16222017-12-20 00:10:28 +00001137 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001138 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001139 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001140
1141 ++NumGlobalImports;
1142 }
1143
1144 Imports.push_back(Import);
1145 }
1146 }
1147
Sam Clegg759631c2017-09-15 20:54:59 +00001148 for (MCSection &Sec : Asm) {
1149 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001150 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001151 continue;
1152
Sam Cleggbafe6902017-12-15 00:17:10 +00001153 // .init_array sections are handled specially elsewhere.
1154 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1155 continue;
1156
Sam Clegg759631c2017-09-15 20:54:59 +00001157 DataSize = alignTo(DataSize, Section.getAlignment());
1158 DataSegments.emplace_back();
1159 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001160 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001161 Segment.Offset = DataSize;
1162 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001163 addData(Segment.Data, Section);
1164 Segment.Alignment = Section.getAlignment();
1165 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001166 DataSize += Segment.Data.size();
1167 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001168
1169 if (const MCSymbolWasm *C = Section.getGroup()) {
1170 Comdats[C->getName()].emplace_back(
1171 WasmComdatEntry{wasm::WASM_COMDAT_DATA,
1172 static_cast<uint32_t>(DataSegments.size()) - 1});
1173 }
Sam Clegg759631c2017-09-15 20:54:59 +00001174 }
1175
Sam Cleggb7787fd2017-06-20 04:04:59 +00001176 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001177 for (const MCSymbol &S : Asm.symbols()) {
1178 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1179 // or used in relocations.
1180 if (S.isTemporary() && S.getName().empty())
1181 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001182
Dan Gohmand934cb82017-02-24 23:18:00 +00001183 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001184 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1185 << " isDefined=" << S.isDefined() << " isExternal="
1186 << S.isExternal() << " isTemporary=" << S.isTemporary()
1187 << " isFunction=" << WS.isFunction()
1188 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001189 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001190 << " isVariable=" << WS.isVariable() << "\n");
1191
Sam Clegga2b35da2017-12-03 01:19:23 +00001192 if (WS.isWeak() || WS.isHidden()) {
1193 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1194 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1195 SymbolFlags.emplace_back(WS.getName(), Flags);
1196 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001197
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001198 if (WS.isVariable())
1199 continue;
1200
Dan Gohmand934cb82017-02-24 23:18:00 +00001201 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001202
Dan Gohmand934cb82017-02-24 23:18:00 +00001203 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001204 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001205 if (WS.getOffset() != 0)
1206 report_fatal_error(
1207 "function sections must contain one function each");
1208
1209 if (WS.getSize() == 0)
1210 report_fatal_error(
1211 "function symbols must have a size set with .size");
1212
Dan Gohmand934cb82017-02-24 23:18:00 +00001213 // A definition. Take the next available index.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001214 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001215
1216 // Prepare the function.
1217 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001218 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001219 Func.Sym = &WS;
1220 SymbolIndices[&WS] = Index;
1221 Functions.push_back(Func);
1222 } else {
1223 // An import; the index was assigned above.
1224 Index = SymbolIndices.find(&WS)->second;
1225 }
1226
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001227 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001228 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001229 if (WS.isTemporary() && !WS.getSize())
1230 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001231
Sam Cleggcd65f692018-01-11 23:59:16 +00001232 if (!WS.isDefined())
Sam Cleggfe6414b2017-06-21 23:46:41 +00001233 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001234
Sam Cleggfe6414b2017-06-21 23:46:41 +00001235 if (!WS.getSize())
1236 report_fatal_error("data symbols must have a size set with .size: " +
1237 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001238
Sam Cleggfe6414b2017-06-21 23:46:41 +00001239 int64_t Size = 0;
1240 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1241 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001242
Sam Clegg7c395942017-09-14 23:07:53 +00001243 // For each global, prepare a corresponding wasm global holding its
1244 // address. For externals these will also be named exports.
1245 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001246 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001247 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001248
1249 WasmGlobal Global;
1250 Global.Type = PtrType;
1251 Global.IsMutable = false;
1252 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001253 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001254 Global.ImportIndex = 0;
1255 SymbolIndices[&WS] = Index;
1256 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1257 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001258 }
1259
1260 // If the symbol is visible outside this translation unit, export it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001261 if (WS.isDefined()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001262 WasmExport Export;
1263 Export.FieldName = WS.getName();
1264 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001265 if (WS.isFunction())
1266 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1267 else
1268 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001269 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001270 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001271
Sam Clegg31a2c802017-09-20 21:17:04 +00001272 if (!WS.isExternal())
1273 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001274
1275 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001276 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001277 if (const MCSymbolWasm *C = Section.getGroup())
1278 Comdats[C->getName()].emplace_back(
1279 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1280 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001281 }
1282 }
1283
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001284 // Handle weak aliases. We need to process these in a separate pass because
1285 // we need to have processed the target of the alias before the alias itself
1286 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001287 for (const MCSymbol &S : Asm.symbols()) {
1288 if (!S.isVariable())
1289 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001290
Sam Cleggcd65f692018-01-11 23:59:16 +00001291 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001292
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001293 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001294 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1295 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001296 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1297 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001298 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001299 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001300
1301 WasmExport Export;
1302 Export.FieldName = WS.getName();
1303 Export.Index = Index;
1304 if (WS.isFunction())
1305 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1306 else
1307 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001308 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001309 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001310
1311 if (!WS.isExternal())
1312 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001313 }
1314
Sam Clegg6006e092017-12-22 20:31:39 +00001315 {
1316 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1317 // Functions referenced by a relocation need to prepared to be called
1318 // indirectly.
1319 const MCSymbolWasm& WS = *Rel.Symbol;
1320 if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
1321 switch (Rel.Type) {
1322 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1323 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1324 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1325 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
1326 uint32_t Index = SymbolIndices.find(&WS)->second;
Sam Clegg30e1bbc2018-01-19 18:57:01 +00001327 IndirectSymbolIndices[&WS] = TableElems.size() + kInitialTableOffset;
Sam Clegg6006e092017-12-22 20:31:39 +00001328 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
1329 TableElems.push_back(Index);
1330 registerFunctionType(WS);
1331 break;
1332 }
1333 default:
1334 break;
1335 }
1336 }
1337 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001338
Sam Clegg6006e092017-12-22 20:31:39 +00001339 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1340 HandleReloc(RelEntry);
1341 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1342 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001343 }
1344
Sam Cleggbafe6902017-12-15 00:17:10 +00001345 // Translate .init_array section contents into start functions.
1346 for (const MCSection &S : Asm) {
1347 const auto &WS = static_cast<const MCSectionWasm &>(S);
1348 if (WS.getSectionName().startswith(".fini_array"))
1349 report_fatal_error(".fini_array sections are unsupported");
1350 if (!WS.getSectionName().startswith(".init_array"))
1351 continue;
1352 if (WS.getFragmentList().empty())
1353 continue;
1354 if (WS.getFragmentList().size() != 2)
1355 report_fatal_error("only one .init_array section fragment supported");
1356 const MCFragment &AlignFrag = *WS.begin();
1357 if (AlignFrag.getKind() != MCFragment::FT_Align)
1358 report_fatal_error(".init_array section should be aligned");
1359 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1360 report_fatal_error(".init_array section should be aligned for pointers");
1361 const MCFragment &Frag = *std::next(WS.begin());
1362 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1363 report_fatal_error("only data supported in .init_array section");
1364 uint16_t Priority = UINT16_MAX;
1365 if (WS.getSectionName().size() != 11) {
1366 if (WS.getSectionName()[11] != '.')
1367 report_fatal_error(".init_array section priority should start with '.'");
1368 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1369 report_fatal_error("invalid .init_array section priority");
1370 }
1371 const auto &DataFrag = cast<MCDataFragment>(Frag);
1372 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1373 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1374 *end = (const uint8_t *)Contents.data() + Contents.size();
1375 p != end; ++p) {
1376 if (*p != 0)
1377 report_fatal_error("non-symbolic data in .init_array section");
1378 }
1379 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1380 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1381 const MCExpr *Expr = Fixup.getValue();
1382 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1383 if (!Sym)
1384 report_fatal_error("fixups in .init_array should be symbol references");
1385 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1386 report_fatal_error("symbols in .init_array should be for functions");
1387 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1388 if (I == SymbolIndices.end())
1389 report_fatal_error("symbols in .init_array should be defined");
1390 uint32_t Index = I->second;
1391 InitFuncs.push_back(std::make_pair(Priority, Index));
1392 }
1393 }
1394
Dan Gohman18eafb62017-02-22 01:23:18 +00001395 // Write out the Wasm header.
1396 writeHeader(Asm);
1397
Sam Clegg9e15f352017-06-03 02:01:24 +00001398 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001399 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001400 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001401 // Skip the "table" section; we import the table instead.
1402 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001403 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001404 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001405 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001406 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001407 writeDataSection(DataSegments);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001408 writeNameSection(Functions, Imports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001409 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001410 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001411 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001412 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001413
Dan Gohmand934cb82017-02-24 23:18:00 +00001414 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001415 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001416}
1417
Lang Hames60fbc7c2017-10-10 16:28:07 +00001418std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001419llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1420 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001421 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001422}