blob: cac4aa17a5d12019394ee91c37db48dbedbafdf5 [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).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000211 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000212 // 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 Cleggf9edbe92018-01-31 19:28:47 +0000246 TableIndices.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) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000496 switch (RelEntry.Type) {
497 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000498 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
499 // Provisional value is table address of the resolved symbol itself
500 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
501 assert(Sym->isFunction());
502 return TableIndices[Sym];
503 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000504 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
505 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
506 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000507 // Provisional value is function/type/global index itself
Sam Clegg60ec3032018-01-23 01:23:17 +0000508 return getRelocationIndexValue(RelEntry);
509 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
510 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
511 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000512 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000513 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
514 // For undefined symbols, use zero
515 if (!Sym->isDefined())
516 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000517
Sam Clegg60ec3032018-01-23 01:23:17 +0000518 uint32_t GlobalIndex = SymbolIndices[Sym];
519 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
520 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000521
Sam Clegg60ec3032018-01-23 01:23:17 +0000522 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
523 return Address;
524 }
525 default:
526 llvm_unreachable("invalid relocation type");
527 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000528}
529
Sam Clegg759631c2017-09-15 20:54:59 +0000530static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000531 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000532 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
533
Sam Clegg63ebb812017-09-29 16:50:08 +0000534 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
535
Sam Cleggc55d13f2017-10-27 00:08:55 +0000536 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000537 for (const MCFragment &Frag : DataSection) {
538 if (Frag.hasInstructions())
539 report_fatal_error("only data supported in data sections");
540
541 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
542 if (Align->getValueSize() != 1)
543 report_fatal_error("only byte values supported for alignment");
544 // If nops are requested, use zeros, as this is the data section.
545 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
546 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
547 Align->getAlignment()),
548 DataBytes.size() +
549 Align->getMaxBytesToEmit());
550 DataBytes.resize(Size, Value);
551 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000552 int64_t Size;
553 if (!Fill->getSize().evaluateAsAbsolute(Size))
554 llvm_unreachable("The fill should be an assembler constant");
555 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000556 } else {
557 const auto &DataFrag = cast<MCDataFragment>(Frag);
558 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
559
560 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000561 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000562 }
563 }
564
Sam Cleggc55d13f2017-10-27 00:08:55 +0000565 // Don't allow empty segments, or segments that end with zero-sized
566 // fragment, otherwise the linker cannot map symbols to a unique
567 // data segment. This can be triggered by zero-sized structs
568 // See: test/MC/WebAssembly/bss.ll
569 if (LastFragmentSize == 0)
570 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000571 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
572}
573
Sam Clegg60ec3032018-01-23 01:23:17 +0000574uint32_t
575WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
576 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000577 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000578 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000579 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000580 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000581 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000582
583 if (!SymbolIndices.count(RelEntry.Symbol))
584 report_fatal_error("symbol not found in function/global index space: " +
585 RelEntry.Symbol->getName());
586 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000587}
588
Dan Gohmand934cb82017-02-24 23:18:00 +0000589// Apply the portions of the relocation records that we can handle ourselves
590// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000591void WasmObjectWriter::applyRelocations(
592 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
593 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000594 for (const WasmRelocationEntry &RelEntry : Relocations) {
595 uint64_t Offset = ContentsOffset +
596 RelEntry.FixupSection->getSectionOffset() +
597 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000598
Sam Cleggb7787fd2017-06-20 04:04:59 +0000599 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000600 uint32_t Value = getProvisionalValue(RelEntry);
601
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000602 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000603 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000604 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000605 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
606 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000607 WritePatchableLEB(Stream, Value, Offset);
608 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
610 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000611 WriteI32(Stream, Value, Offset);
612 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000613 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
614 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
615 WritePatchableSLEB(Stream, Value, Offset);
616 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000617 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000618 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000619 }
620 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000621}
622
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000623// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000624// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000625void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000626 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000627 raw_pwrite_stream &Stream = getStream();
628 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000629
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000631 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000632 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000633
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000634 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000635 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000636 encodeULEB128(Index, Stream);
637 if (RelEntry.hasAddend())
638 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000639 }
640}
641
Sam Clegg9e15f352017-06-03 02:01:24 +0000642void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000643 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000644 if (FunctionTypes.empty())
645 return;
646
647 SectionBookkeeping Section;
648 startSection(Section, wasm::WASM_SEC_TYPE);
649
650 encodeULEB128(FunctionTypes.size(), getStream());
651
652 for (const WasmFunctionType &FuncTy : FunctionTypes) {
653 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
654 encodeULEB128(FuncTy.Params.size(), getStream());
655 for (wasm::ValType Ty : FuncTy.Params)
656 writeValueType(Ty);
657 encodeULEB128(FuncTy.Returns.size(), getStream());
658 for (wasm::ValType Ty : FuncTy.Returns)
659 writeValueType(Ty);
660 }
661
662 endSection(Section);
663}
664
Sam Cleggf950b242017-12-11 23:03:38 +0000665void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
666 uint32_t DataSize,
667 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000668 if (Imports.empty())
669 return;
670
Sam Cleggf950b242017-12-11 23:03:38 +0000671 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
672
Sam Clegg9e15f352017-06-03 02:01:24 +0000673 SectionBookkeeping Section;
674 startSection(Section, wasm::WASM_SEC_IMPORT);
675
676 encodeULEB128(Imports.size(), getStream());
677 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000678 writeString(Import.ModuleName);
679 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000680
681 encodeULEB128(Import.Kind, getStream());
682
683 switch (Import.Kind) {
684 case wasm::WASM_EXTERNAL_FUNCTION:
685 encodeULEB128(Import.Type, getStream());
686 break;
687 case wasm::WASM_EXTERNAL_GLOBAL:
688 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000689 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000690 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000691 case wasm::WASM_EXTERNAL_MEMORY:
692 encodeULEB128(0, getStream()); // flags
693 encodeULEB128(NumPages, getStream()); // initial
694 break;
695 case wasm::WASM_EXTERNAL_TABLE:
696 encodeSLEB128(int32_t(Import.Type), getStream());
697 encodeULEB128(0, getStream()); // flags
698 encodeULEB128(NumElements, getStream()); // initial
699 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000700 default:
701 llvm_unreachable("unsupported import kind");
702 }
703 }
704
705 endSection(Section);
706}
707
Sam Clegg457fb0b2017-09-15 19:50:44 +0000708void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000709 if (Functions.empty())
710 return;
711
712 SectionBookkeeping Section;
713 startSection(Section, wasm::WASM_SEC_FUNCTION);
714
715 encodeULEB128(Functions.size(), getStream());
716 for (const WasmFunction &Func : Functions)
717 encodeULEB128(Func.Type, getStream());
718
719 endSection(Section);
720}
721
Sam Clegg7c395942017-09-14 23:07:53 +0000722void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000723 if (Globals.empty())
724 return;
725
726 SectionBookkeeping Section;
727 startSection(Section, wasm::WASM_SEC_GLOBAL);
728
729 encodeULEB128(Globals.size(), getStream());
730 for (const WasmGlobal &Global : Globals) {
731 writeValueType(Global.Type);
732 write8(Global.IsMutable);
733
734 if (Global.HasImport) {
735 assert(Global.InitialValue == 0);
736 write8(wasm::WASM_OPCODE_GET_GLOBAL);
737 encodeULEB128(Global.ImportIndex, getStream());
738 } else {
739 assert(Global.ImportIndex == 0);
740 write8(wasm::WASM_OPCODE_I32_CONST);
741 encodeSLEB128(Global.InitialValue, getStream()); // offset
742 }
743 write8(wasm::WASM_OPCODE_END);
744 }
745
746 endSection(Section);
747}
748
Sam Clegg457fb0b2017-09-15 19:50:44 +0000749void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 if (Exports.empty())
751 return;
752
753 SectionBookkeeping Section;
754 startSection(Section, wasm::WASM_SEC_EXPORT);
755
756 encodeULEB128(Exports.size(), getStream());
757 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000758 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000759 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000760 encodeULEB128(Export.Index, getStream());
761 }
762
763 endSection(Section);
764}
765
Sam Clegg457fb0b2017-09-15 19:50:44 +0000766void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000767 if (TableElems.empty())
768 return;
769
770 SectionBookkeeping Section;
771 startSection(Section, wasm::WASM_SEC_ELEM);
772
773 encodeULEB128(1, getStream()); // number of "segments"
774 encodeULEB128(0, getStream()); // the table index
775
776 // init expr for starting offset
777 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000778 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 write8(wasm::WASM_OPCODE_END);
780
781 encodeULEB128(TableElems.size(), getStream());
782 for (uint32_t Elem : TableElems)
783 encodeULEB128(Elem, getStream());
784
785 endSection(Section);
786}
787
Sam Clegg457fb0b2017-09-15 19:50:44 +0000788void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
789 const MCAsmLayout &Layout,
790 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 if (Functions.empty())
792 return;
793
794 SectionBookkeeping Section;
795 startSection(Section, wasm::WASM_SEC_CODE);
796
797 encodeULEB128(Functions.size(), getStream());
798
799 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000800 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000801
Sam Clegg9e15f352017-06-03 02:01:24 +0000802 int64_t Size = 0;
803 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
804 report_fatal_error(".size expression must be evaluatable");
805
806 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000807 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000808 Asm.writeSectionData(&FuncSection, Layout);
809 }
810
Sam Clegg9e15f352017-06-03 02:01:24 +0000811 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000812 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000813
814 endSection(Section);
815}
816
Sam Clegg457fb0b2017-09-15 19:50:44 +0000817void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000818 if (Segments.empty())
819 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000820
821 SectionBookkeeping Section;
822 startSection(Section, wasm::WASM_SEC_DATA);
823
Sam Clegg7c395942017-09-14 23:07:53 +0000824 encodeULEB128(Segments.size(), getStream()); // count
825
826 for (const WasmDataSegment & Segment : Segments) {
827 encodeULEB128(0, getStream()); // memory index
828 write8(wasm::WASM_OPCODE_I32_CONST);
829 encodeSLEB128(Segment.Offset, getStream()); // offset
830 write8(wasm::WASM_OPCODE_END);
831 encodeULEB128(Segment.Data.size(), getStream()); // size
832 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
833 writeBytes(Segment.Data); // data
834 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000835
836 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000837 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000838
839 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000840}
841
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000842void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000843 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
844 // for descriptions of the reloc sections.
845
846 if (CodeRelocations.empty())
847 return;
848
849 SectionBookkeeping Section;
850 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
851
852 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000853 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000854
Sam Clegg7c395942017-09-14 23:07:53 +0000855 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000856
857 endSection(Section);
858}
859
Sam Clegg7c395942017-09-14 23:07:53 +0000860void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000861 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
862 // for descriptions of the reloc sections.
863
864 if (DataRelocations.empty())
865 return;
866
867 SectionBookkeeping Section;
868 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
869
870 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
871 encodeULEB128(DataRelocations.size(), getStream());
872
Sam Clegg7c395942017-09-14 23:07:53 +0000873 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
875 endSection(Section);
876}
877
878void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000879 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000880 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
881 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
882 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000883 SectionBookkeeping Section;
884 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000885 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
Sam Clegg31a2c802017-09-20 21:17:04 +0000887 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000888 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000889 encodeULEB128(SymbolFlags.size(), getStream());
890 for (auto Pair: SymbolFlags) {
891 writeString(Pair.first);
892 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000893 }
894 endSection(SubSection);
895 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000896
Sam Clegg9e1ade92017-06-27 20:27:59 +0000897 if (DataSize > 0) {
898 startSection(SubSection, wasm::WASM_DATA_SIZE);
899 encodeULEB128(DataSize, getStream());
900 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000901 }
902
Sam Cleggd95ed952017-09-20 19:03:35 +0000903 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000904 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000905 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000906 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000907 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000908 encodeULEB128(Segment.Alignment, getStream());
909 encodeULEB128(Segment.Flags, getStream());
910 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000911 endSection(SubSection);
912 }
913
Sam Cleggbafe6902017-12-15 00:17:10 +0000914 if (!InitFuncs.empty()) {
915 startSection(SubSection, wasm::WASM_INIT_FUNCS);
916 encodeULEB128(InitFuncs.size(), getStream());
917 for (auto &StartFunc : InitFuncs) {
918 encodeULEB128(StartFunc.first, getStream()); // priority
919 encodeULEB128(StartFunc.second, getStream()); // function index
920 }
921 endSection(SubSection);
922 }
923
Sam Cleggea7cace2018-01-09 23:43:14 +0000924 if (Comdats.size()) {
925 startSection(SubSection, wasm::WASM_COMDAT_INFO);
926 encodeULEB128(Comdats.size(), getStream());
927 for (const auto &C : Comdats) {
928 writeString(C.first);
929 encodeULEB128(0, getStream()); // flags for future use
930 encodeULEB128(C.second.size(), getStream());
931 for (const WasmComdatEntry &Entry : C.second) {
932 encodeULEB128(Entry.Kind, getStream());
933 encodeULEB128(Entry.Index, getStream());
934 }
935 }
936 endSection(SubSection);
937 }
938
Sam Clegg9e15f352017-06-03 02:01:24 +0000939 endSection(Section);
940}
941
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000942uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
943 assert(Symbol.isFunction());
944 assert(TypeIndices.count(&Symbol));
945 return TypeIndices[&Symbol];
946}
947
948uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
949 assert(Symbol.isFunction());
950
951 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000952 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
953 F.Returns = ResolvedSym->getReturns();
954 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000955
956 auto Pair =
957 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
958 if (Pair.second)
959 FunctionTypes.push_back(F);
960 TypeIndices[&Symbol] = Pair.first->second;
961
962 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
963 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
964 return Pair.first->second;
965}
966
Dan Gohman18eafb62017-02-22 01:23:18 +0000967void WasmObjectWriter::writeObject(MCAssembler &Asm,
968 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000969 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000970 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +0000971 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000972
973 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000974 SmallVector<WasmFunction, 4> Functions;
975 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000976 SmallVector<WasmImport, 4> Imports;
977 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +0000978 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Sam Cleggbafe6902017-12-15 00:17:10 +0000979 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000980 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +0000981 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +0000982 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000983
Dan Gohman82607f52017-02-24 23:46:05 +0000984 // In the special .global_variables section, we've encoded global
985 // variables used by the function. Translate them into the Globals
986 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +0000987 MCSectionWasm *GlobalVars =
988 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +0000989 if (!GlobalVars->getFragmentList().empty()) {
990 if (GlobalVars->getFragmentList().size() != 1)
991 report_fatal_error("only one .global_variables fragment supported");
992 const MCFragment &Frag = *GlobalVars->begin();
993 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
994 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +0000995 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +0000996 if (!DataFrag.getFixups().empty())
997 report_fatal_error("fixups not supported in .global_variables");
998 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +0000999 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1000 *end = (const uint8_t *)Contents.data() + Contents.size();
1001 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001002 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001003 if (end - p < 3)
1004 report_fatal_error("truncated global variable encoding");
1005 G.Type = wasm::ValType(int8_t(*p++));
1006 G.IsMutable = bool(*p++);
1007 G.HasImport = bool(*p++);
1008 if (G.HasImport) {
1009 G.InitialValue = 0;
1010
1011 WasmImport Import;
1012 Import.ModuleName = (const char *)p;
1013 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1014 if (!nul)
1015 report_fatal_error("global module name must be nul-terminated");
1016 p = nul + 1;
1017 nul = (const uint8_t *)memchr(p, '\0', end - p);
1018 if (!nul)
1019 report_fatal_error("global base name must be nul-terminated");
1020 Import.FieldName = (const char *)p;
1021 p = nul + 1;
1022
1023 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1024 Import.Type = int32_t(G.Type);
1025
1026 G.ImportIndex = NumGlobalImports;
1027 ++NumGlobalImports;
1028
1029 Imports.push_back(Import);
1030 } else {
1031 unsigned n;
1032 G.InitialValue = decodeSLEB128(p, &n);
1033 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001034 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001035 report_fatal_error("global initial value must be valid SLEB128");
1036 p += n;
1037 }
Dan Gohman82607f52017-02-24 23:46:05 +00001038 Globals.push_back(G);
1039 }
1040 }
1041
Sam Cleggf950b242017-12-11 23:03:38 +00001042 // For now, always emit the memory import, since loads and stores are not
1043 // valid without it. In the future, we could perhaps be more clever and omit
1044 // it if there are no loads or stores.
1045 MCSymbolWasm *MemorySym =
1046 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1047 WasmImport MemImport;
1048 MemImport.ModuleName = MemorySym->getModuleName();
1049 MemImport.FieldName = MemorySym->getName();
1050 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1051 Imports.push_back(MemImport);
1052
1053 // For now, always emit the table section, since indirect calls are not
1054 // valid without it. In the future, we could perhaps be more clever and omit
1055 // it if there are no indirect calls.
1056 MCSymbolWasm *TableSym =
1057 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1058 WasmImport TableImport;
1059 TableImport.ModuleName = TableSym->getModuleName();
1060 TableImport.FieldName = TableSym->getName();
1061 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1062 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1063 Imports.push_back(TableImport);
1064
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001065 // Populate FunctionTypeIndices and Imports.
1066 for (const MCSymbol &S : Asm.symbols()) {
1067 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1068
1069 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001070 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001071 if (WS.isFunction())
1072 registerFunctionType(WS);
1073
1074 if (WS.isTemporary())
1075 continue;
1076
1077 // If the symbol is not defined in this translation unit, import it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001078 if ((!WS.isDefined() && !WS.isComdat()) ||
Sam Cleggd423f0d2018-01-11 20:35:17 +00001079 WS.isVariable()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001080 WasmImport Import;
1081 Import.ModuleName = WS.getModuleName();
1082 Import.FieldName = WS.getName();
1083
1084 if (WS.isFunction()) {
1085 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1086 Import.Type = getFunctionType(WS);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001087 SymbolIndices[&WS] = NumFunctionImports;
1088 ++NumFunctionImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001089 } else {
1090 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1091 Import.Type = int32_t(PtrType);
1092 Import.IsMutable = false;
1093 SymbolIndices[&WS] = NumGlobalImports;
1094
Dan Gohman83b16222017-12-20 00:10:28 +00001095 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001096 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001097 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001098
1099 ++NumGlobalImports;
1100 }
1101
1102 Imports.push_back(Import);
1103 }
1104 }
1105
Sam Clegg759631c2017-09-15 20:54:59 +00001106 for (MCSection &Sec : Asm) {
1107 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001108 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001109 continue;
1110
Sam Cleggbafe6902017-12-15 00:17:10 +00001111 // .init_array sections are handled specially elsewhere.
1112 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1113 continue;
1114
Sam Clegg329e76d2018-01-31 04:21:44 +00001115 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001116 DataSize = alignTo(DataSize, Section.getAlignment());
1117 DataSegments.emplace_back();
1118 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001119 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001120 Segment.Offset = DataSize;
1121 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001122 addData(Segment.Data, Section);
1123 Segment.Alignment = Section.getAlignment();
1124 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001125 DataSize += Segment.Data.size();
1126 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001127
1128 if (const MCSymbolWasm *C = Section.getGroup()) {
1129 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001130 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001131 }
Sam Clegg759631c2017-09-15 20:54:59 +00001132 }
1133
Sam Cleggb7787fd2017-06-20 04:04:59 +00001134 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001135 for (const MCSymbol &S : Asm.symbols()) {
1136 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1137 // or used in relocations.
1138 if (S.isTemporary() && S.getName().empty())
1139 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001140
Dan Gohmand934cb82017-02-24 23:18:00 +00001141 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001142 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001143 << " isDefined=" << S.isDefined()
1144 << " isExternal=" << S.isExternal()
1145 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001146 << " isFunction=" << WS.isFunction()
1147 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001148 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001149 << " isVariable=" << WS.isVariable() << "\n");
1150
Sam Clegga2b35da2017-12-03 01:19:23 +00001151 if (WS.isWeak() || WS.isHidden()) {
1152 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1153 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1154 SymbolFlags.emplace_back(WS.getName(), Flags);
1155 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001156
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001157 if (WS.isVariable())
1158 continue;
1159
Dan Gohmand934cb82017-02-24 23:18:00 +00001160 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001161
Dan Gohmand934cb82017-02-24 23:18:00 +00001162 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001163 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001164 if (WS.getOffset() != 0)
1165 report_fatal_error(
1166 "function sections must contain one function each");
1167
1168 if (WS.getSize() == 0)
1169 report_fatal_error(
1170 "function symbols must have a size set with .size");
1171
Dan Gohmand934cb82017-02-24 23:18:00 +00001172 // A definition. Take the next available index.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001173 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001174
1175 // Prepare the function.
1176 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001177 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001178 Func.Sym = &WS;
1179 SymbolIndices[&WS] = Index;
1180 Functions.push_back(Func);
1181 } else {
1182 // An import; the index was assigned above.
1183 Index = SymbolIndices.find(&WS)->second;
1184 }
1185
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001186 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001187 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001188 if (WS.isTemporary() && !WS.getSize())
1189 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001190
Sam Cleggcd65f692018-01-11 23:59:16 +00001191 if (!WS.isDefined())
Sam Cleggfe6414b2017-06-21 23:46:41 +00001192 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001193
Sam Cleggfe6414b2017-06-21 23:46:41 +00001194 if (!WS.getSize())
1195 report_fatal_error("data symbols must have a size set with .size: " +
1196 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001197
Sam Cleggfe6414b2017-06-21 23:46:41 +00001198 int64_t Size = 0;
1199 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1200 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001201
Sam Clegg7c395942017-09-14 23:07:53 +00001202 // For each global, prepare a corresponding wasm global holding its
1203 // address. For externals these will also be named exports.
1204 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001205 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001206 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001207
1208 WasmGlobal Global;
1209 Global.Type = PtrType;
1210 Global.IsMutable = false;
1211 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001212 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001213 Global.ImportIndex = 0;
1214 SymbolIndices[&WS] = Index;
1215 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1216 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001217 }
1218
1219 // If the symbol is visible outside this translation unit, export it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001220 if (WS.isDefined()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001221 WasmExport Export;
1222 Export.FieldName = WS.getName();
1223 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001224 if (WS.isFunction())
1225 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1226 else
1227 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001228 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001229 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001230
Sam Clegg31a2c802017-09-20 21:17:04 +00001231 if (!WS.isExternal())
1232 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001233
1234 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001235 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001236 if (const MCSymbolWasm *C = Section.getGroup())
1237 Comdats[C->getName()].emplace_back(
1238 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1239 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001240 }
1241 }
1242
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001243 // Handle weak aliases. We need to process these in a separate pass because
1244 // we need to have processed the target of the alias before the alias itself
1245 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001246 for (const MCSymbol &S : Asm.symbols()) {
1247 if (!S.isVariable())
1248 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001249
Sam Cleggcd65f692018-01-11 23:59:16 +00001250 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001251
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001252 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001253 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1254 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001255 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1256 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001257 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001258 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001259
1260 WasmExport Export;
1261 Export.FieldName = WS.getName();
1262 Export.Index = Index;
1263 if (WS.isFunction())
1264 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1265 else
1266 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001267 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001268 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001269
1270 if (!WS.isExternal())
1271 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001272 }
1273
Sam Clegg6006e092017-12-22 20:31:39 +00001274 {
1275 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001276 // Functions referenced by a relocation need to put in the table. This is
1277 // purely to make the object file's provisional values readable, and is
1278 // ignored by the linker, which re-calculates the relocations itself.
1279 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1280 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1281 return;
1282 assert(Rel.Symbol->isFunction());
1283 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
1284 uint32_t SymbolIndex = SymbolIndices.find(&WS)->second;
1285 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1286 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1287 DEBUG(dbgs() << " -> adding " << WS.getName()
1288 << " to table: " << TableIndex << "\n");
1289 TableElems.push_back(SymbolIndex);
1290 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001291 }
1292 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001293
Sam Clegg6006e092017-12-22 20:31:39 +00001294 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1295 HandleReloc(RelEntry);
1296 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1297 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001298 }
1299
Sam Cleggbafe6902017-12-15 00:17:10 +00001300 // Translate .init_array section contents into start functions.
1301 for (const MCSection &S : Asm) {
1302 const auto &WS = static_cast<const MCSectionWasm &>(S);
1303 if (WS.getSectionName().startswith(".fini_array"))
1304 report_fatal_error(".fini_array sections are unsupported");
1305 if (!WS.getSectionName().startswith(".init_array"))
1306 continue;
1307 if (WS.getFragmentList().empty())
1308 continue;
1309 if (WS.getFragmentList().size() != 2)
1310 report_fatal_error("only one .init_array section fragment supported");
1311 const MCFragment &AlignFrag = *WS.begin();
1312 if (AlignFrag.getKind() != MCFragment::FT_Align)
1313 report_fatal_error(".init_array section should be aligned");
1314 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1315 report_fatal_error(".init_array section should be aligned for pointers");
1316 const MCFragment &Frag = *std::next(WS.begin());
1317 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1318 report_fatal_error("only data supported in .init_array section");
1319 uint16_t Priority = UINT16_MAX;
1320 if (WS.getSectionName().size() != 11) {
1321 if (WS.getSectionName()[11] != '.')
1322 report_fatal_error(".init_array section priority should start with '.'");
1323 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1324 report_fatal_error("invalid .init_array section priority");
1325 }
1326 const auto &DataFrag = cast<MCDataFragment>(Frag);
1327 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1328 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1329 *end = (const uint8_t *)Contents.data() + Contents.size();
1330 p != end; ++p) {
1331 if (*p != 0)
1332 report_fatal_error("non-symbolic data in .init_array section");
1333 }
1334 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1335 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1336 const MCExpr *Expr = Fixup.getValue();
1337 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1338 if (!Sym)
1339 report_fatal_error("fixups in .init_array should be symbol references");
1340 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1341 report_fatal_error("symbols in .init_array should be for functions");
1342 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1343 if (I == SymbolIndices.end())
1344 report_fatal_error("symbols in .init_array should be defined");
1345 uint32_t Index = I->second;
1346 InitFuncs.push_back(std::make_pair(Priority, Index));
1347 }
1348 }
1349
Dan Gohman18eafb62017-02-22 01:23:18 +00001350 // Write out the Wasm header.
1351 writeHeader(Asm);
1352
Sam Clegg9e15f352017-06-03 02:01:24 +00001353 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001354 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001355 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001356 // Skip the "table" section; we import the table instead.
1357 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001358 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001359 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001360 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001361 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001362 writeDataSection(DataSegments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001363 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001364 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001365 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001366 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001367
Dan Gohmand934cb82017-02-24 23:18:00 +00001368 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001369 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001370}
1371
Lang Hames60fbc7c2017-10-10 16:28:07 +00001372std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001373llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1374 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001375 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001376}