blob: ff000733999e6f4236b5b498e2da9c8fecd04d76 [file] [log] [blame]
Dan Gohman18eafb62017-02-22 01:23:18 +00001//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Wasm object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SmallPtrSet.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000016#include "llvm/BinaryFormat/Wasm.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000017#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmLayout.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000023#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionWasm.h"
25#include "llvm/MC/MCSymbolWasm.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000028#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000029#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000031#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/StringSaver.h"
33#include <vector>
34
35using namespace llvm;
36
Sam Clegg5e3d33a2017-07-07 02:01:29 +000037#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000038
39namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000040
Dan Gohmand934cb82017-02-24 23:18:00 +000041// For patching purposes, we need to remember where each section starts, both
42// for patching up the section size field, and for patching up references to
43// locations within the section.
44struct SectionBookkeeping {
45 // Where the size of the section is written.
46 uint64_t SizeOffset;
47 // Where the contents of the section starts (after the header).
48 uint64_t ContentsOffset;
49};
50
Sam Clegg9e15f352017-06-03 02:01:24 +000051// The signature of a wasm function, in a struct capable of being used as a
52// DenseMap key.
53struct WasmFunctionType {
54 // Support empty and tombstone instances, needed by DenseMap.
55 enum { Plain, Empty, Tombstone } State;
56
57 // The return types of the function.
58 SmallVector<wasm::ValType, 1> Returns;
59
60 // The parameter types of the function.
61 SmallVector<wasm::ValType, 4> Params;
62
63 WasmFunctionType() : State(Plain) {}
64
65 bool operator==(const WasmFunctionType &Other) const {
66 return State == Other.State && Returns == Other.Returns &&
67 Params == Other.Params;
68 }
69};
70
71// Traits for using WasmFunctionType in a DenseMap.
72struct WasmFunctionTypeDenseMapInfo {
73 static WasmFunctionType getEmptyKey() {
74 WasmFunctionType FuncTy;
75 FuncTy.State = WasmFunctionType::Empty;
76 return FuncTy;
77 }
78 static WasmFunctionType getTombstoneKey() {
79 WasmFunctionType FuncTy;
80 FuncTy.State = WasmFunctionType::Tombstone;
81 return FuncTy;
82 }
83 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
84 uintptr_t Value = FuncTy.State;
85 for (wasm::ValType Ret : FuncTy.Returns)
86 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
87 for (wasm::ValType Param : FuncTy.Params)
88 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
89 return Value;
90 }
91 static bool isEqual(const WasmFunctionType &LHS,
92 const WasmFunctionType &RHS) {
93 return LHS == RHS;
94 }
95};
96
Sam Clegg7c395942017-09-14 23:07:53 +000097// A wasm data segment. A wasm binary contains only a single data section
98// but that can contain many segments, each with their own virtual location
99// in memory. Each MCSection data created by llvm is modeled as its own
100// wasm data segment.
101struct WasmDataSegment {
102 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000103 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000104 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000105 uint32_t Alignment;
106 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000107 SmallVector<char, 4> Data;
108};
109
Sam Clegg9e15f352017-06-03 02:01:24 +0000110// A wasm import to be written into the import section.
111struct WasmImport {
112 StringRef ModuleName;
113 StringRef FieldName;
114 unsigned Kind;
115 int32_t Type;
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000116 bool IsMutable;
Sam Clegg9e15f352017-06-03 02:01:24 +0000117};
118
119// A wasm function to be written into the function section.
120struct WasmFunction {
121 int32_t Type;
122 const MCSymbolWasm *Sym;
123};
124
125// A wasm export to be written into the export section.
126struct WasmExport {
127 StringRef FieldName;
128 unsigned Kind;
129 uint32_t Index;
130};
131
132// A wasm global to be written into the global section.
133struct WasmGlobal {
134 wasm::ValType Type;
135 bool IsMutable;
136 bool HasImport;
137 uint64_t InitialValue;
138 uint32_t ImportIndex;
139};
140
Sam Cleggea7cace2018-01-09 23:43:14 +0000141// Information about a single item which is part of a COMDAT. For each data
142// segment or function which is in the COMDAT, there is a corresponding
143// WasmComdatEntry.
144struct WasmComdatEntry {
145 unsigned Kind;
146 uint32_t Index;
147};
148
Sam Clegg6dc65e92017-06-06 16:38:59 +0000149// Information about a single relocation.
150struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000151 uint64_t Offset; // Where is the relocation.
152 const MCSymbolWasm *Symbol; // The symbol to relocate with.
153 int64_t Addend; // A value to add to the symbol.
154 unsigned Type; // The type of the relocation.
155 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000156
157 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
158 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000159 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000160 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
161 FixupSection(FixupSection) {}
162
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000163 bool hasAddend() const {
164 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000165 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
166 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
167 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000168 return true;
169 default:
170 return false;
171 }
172 }
173
Sam Clegg6dc65e92017-06-06 16:38:59 +0000174 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000175 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000176 << ", Type=" << Type
177 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000178 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000179
Aaron Ballman615eb472017-10-15 14:32:27 +0000180#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000181 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
182#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000183};
184
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000185#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000186raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000187 Rel.print(OS);
188 return OS;
189}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000190#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000191
Dan Gohman18eafb62017-02-22 01:23:18 +0000192class WasmObjectWriter : public MCObjectWriter {
193 /// Helper struct for containing some precomputed information on symbols.
194 struct WasmSymbolData {
195 const MCSymbolWasm *Symbol;
196 StringRef Name;
197
198 // Support lexicographic sorting.
199 bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; }
200 };
201
202 /// The target specific Wasm writer instance.
203 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
204
Dan Gohmand934cb82017-02-24 23:18:00 +0000205 // Relocations for fixing up references in the code section.
206 std::vector<WasmRelocationEntry> CodeRelocations;
207
208 // Relocations for fixing up references in the data section.
209 std::vector<WasmRelocationEntry> DataRelocations;
210
Dan Gohmand934cb82017-02-24 23:18:00 +0000211 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000212 // Maps function symbols to the index of the type of the function
213 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000214 // Maps function symbols to the table element index space. Used
215 // for TABLE_INDEX relocation types (i.e. address taken functions).
216 DenseMap<const MCSymbolWasm *, uint32_t> IndirectSymbolIndices;
217 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000218 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
219
220 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
221 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000222 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000223 SmallVector<WasmGlobal, 4> Globals;
224 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000225
Dan Gohman18eafb62017-02-22 01:23:18 +0000226 // TargetObjectWriter wrappers.
227 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000228 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
229 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000230 }
231
Dan Gohmand934cb82017-02-24 23:18:00 +0000232 void startSection(SectionBookkeeping &Section, unsigned SectionId,
233 const char *Name = nullptr);
234 void endSection(SectionBookkeeping &Section);
235
Dan Gohman18eafb62017-02-22 01:23:18 +0000236public:
Lang Hames1301a872017-10-10 01:15:10 +0000237 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
238 raw_pwrite_stream &OS)
239 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
240 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000241
Dan Gohmand934cb82017-02-24 23:18:00 +0000242private:
Dan Gohman18eafb62017-02-22 01:23:18 +0000243 ~WasmObjectWriter() override;
244
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000245 void reset() override {
246 CodeRelocations.clear();
247 DataRelocations.clear();
248 TypeIndices.clear();
249 SymbolIndices.clear();
Sam Cleggd99f6072017-06-12 23:52:44 +0000250 IndirectSymbolIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000251 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000252 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000253 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000254 MCObjectWriter::reset();
Sam Clegg7c395942017-09-14 23:07:53 +0000255 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000256 }
257
Dan Gohman18eafb62017-02-22 01:23:18 +0000258 void writeHeader(const MCAssembler &Asm);
259
260 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
261 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000262 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000263
264 void executePostLayoutBinding(MCAssembler &Asm,
265 const MCAsmLayout &Layout) override;
266
267 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000268
Sam Cleggb7787fd2017-06-20 04:04:59 +0000269 void writeString(const StringRef Str) {
270 encodeULEB128(Str.size(), getStream());
271 writeBytes(Str);
272 }
273
Sam Clegg9e15f352017-06-03 02:01:24 +0000274 void writeValueType(wasm::ValType Ty) {
275 encodeSLEB128(int32_t(Ty), getStream());
276 }
277
Sam Clegg457fb0b2017-09-15 19:50:44 +0000278 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +0000279 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
280 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000281 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000282 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000283 void writeExportSection(ArrayRef<WasmExport> Exports);
284 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000285 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000286 ArrayRef<WasmFunction> Functions);
287 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
288 void writeNameSection(ArrayRef<WasmFunction> Functions,
289 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000290 uint32_t NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000291 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000292 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000293 void writeLinkingMetaDataSection(
294 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000295 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
296 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
297 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000298
Sam Clegg7c395942017-09-14 23:07:53 +0000299 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000300 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
301 uint64_t ContentsOffset);
302
Sam Clegg7c395942017-09-14 23:07:53 +0000303 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000304 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000305 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
306 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000307};
Sam Clegg9e15f352017-06-03 02:01:24 +0000308
Dan Gohman18eafb62017-02-22 01:23:18 +0000309} // end anonymous namespace
310
311WasmObjectWriter::~WasmObjectWriter() {}
312
Dan Gohmand934cb82017-02-24 23:18:00 +0000313// Write out a section header and a patchable section size field.
314void WasmObjectWriter::startSection(SectionBookkeeping &Section,
315 unsigned SectionId,
316 const char *Name) {
317 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
318 "Only custom sections can have names");
319
Sam Cleggb7787fd2017-06-20 04:04:59 +0000320 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000321 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000322
323 Section.SizeOffset = getStream().tell();
324
325 // The section size. We don't know the size yet, so reserve enough space
326 // for any 32-bit value; we'll patch it later.
327 encodeULEB128(UINT32_MAX, getStream());
328
329 // The position where the section starts, for measuring its size.
330 Section.ContentsOffset = getStream().tell();
331
332 // Custom sections in wasm also have a string identifier.
333 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000334 assert(Name);
335 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000336 }
337}
338
339// Now that the section is complete and we know how big it is, patch up the
340// section size field at the start of the section.
341void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
342 uint64_t Size = getStream().tell() - Section.ContentsOffset;
343 if (uint32_t(Size) != Size)
344 report_fatal_error("section size does not fit in a uint32_t");
345
Sam Cleggb7787fd2017-06-20 04:04:59 +0000346 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000347
348 // Write the final section size to the payload_len field, which follows
349 // the section id byte.
350 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000351 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000352 assert(SizeLen == 5);
353 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
354}
355
Dan Gohman18eafb62017-02-22 01:23:18 +0000356// Emit the Wasm header.
357void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000358 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
359 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000360}
361
362void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
363 const MCAsmLayout &Layout) {
364}
365
366void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
367 const MCAsmLayout &Layout,
368 const MCFragment *Fragment,
369 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000370 uint64_t &FixedValue) {
371 MCAsmBackend &Backend = Asm.getBackend();
372 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
373 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000374 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000375 uint64_t C = Target.getConstant();
376 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
377 MCContext &Ctx = Asm.getContext();
378
Sam Cleggbafe6902017-12-15 00:17:10 +0000379 // The .init_array isn't translated as data, so don't do relocations in it.
380 if (FixupSection.getSectionName().startswith(".init_array"))
381 return;
382
Dan Gohmand934cb82017-02-24 23:18:00 +0000383 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
384 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
385 "Should not have constructed this");
386
387 // Let A, B and C being the components of Target and R be the location of
388 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
389 // If it is pcrel, we want to compute (A - B + C - R).
390
391 // In general, Wasm has no relocations for -B. It can only represent (A + C)
392 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
393 // replace B to implement it: (A - R - K + C)
394 if (IsPCRel) {
395 Ctx.reportError(
396 Fixup.getLoc(),
397 "No relocation available to represent this relative expression");
398 return;
399 }
400
401 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
402
403 if (SymB.isUndefined()) {
404 Ctx.reportError(Fixup.getLoc(),
405 Twine("symbol '") + SymB.getName() +
406 "' can not be undefined in a subtraction expression");
407 return;
408 }
409
410 assert(!SymB.isAbsolute() && "Should have been folded");
411 const MCSection &SecB = SymB.getSection();
412 if (&SecB != &FixupSection) {
413 Ctx.reportError(Fixup.getLoc(),
414 "Cannot represent a difference across sections");
415 return;
416 }
417
418 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
419 uint64_t K = SymBOffset - FixupOffset;
420 IsPCRel = true;
421 C -= K;
422 }
423
424 // We either rejected the fixup or folded B into C at this point.
425 const MCSymbolRefExpr *RefA = Target.getSymA();
426 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
427
Dan Gohmand934cb82017-02-24 23:18:00 +0000428 if (SymA && SymA->isVariable()) {
429 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000430 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
431 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
432 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000433 }
434
435 // Put any constant offset in an addend. Offsets can be negative, and
436 // LLVM expects wrapping, in contrast to wasm's immediates which can't
437 // be negative and don't wrap.
438 FixedValue = 0;
439
Sam Clegg6ad8f192017-07-11 02:21:57 +0000440 if (SymA)
441 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000442
Sam Cleggae03c1e72017-06-13 18:51:50 +0000443 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000444 assert(SymA);
445
Sam Cleggae03c1e72017-06-13 18:51:50 +0000446 unsigned Type = getRelocType(Target, Fixup);
447
Dan Gohmand934cb82017-02-24 23:18:00 +0000448 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000449 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000450
Sam Clegg12fd3da2017-10-20 21:28:38 +0000451 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000452 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000453 else if (FixupSection.getKind().isText())
454 CodeRelocations.push_back(Rec);
455 else if (!FixupSection.getKind().isMetadata())
456 // TODO(sbc): Add support for debug sections.
457 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000458}
459
Dan Gohmand934cb82017-02-24 23:18:00 +0000460// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
461// to allow patching.
462static void
463WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
464 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000465 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000466 assert(SizeLen == 5);
467 Stream.pwrite((char *)Buffer, SizeLen, Offset);
468}
469
470// Write X as an signed LEB value at offset Offset in Stream, padded
471// to allow patching.
472static void
473WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
474 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000475 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000476 assert(SizeLen == 5);
477 Stream.pwrite((char *)Buffer, SizeLen, Offset);
478}
479
480// Write X as a plain integer value at offset Offset in Stream.
481static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
482 uint8_t Buffer[4];
483 support::endian::write32le(Buffer, X);
484 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
485}
486
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000487static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
488 if (Symbol.isVariable()) {
489 const MCExpr *Expr = Symbol.getVariableValue();
490 auto *Inner = cast<MCSymbolRefExpr>(Expr);
491 return cast<MCSymbolWasm>(&Inner->getSymbol());
492 }
493 return &Symbol;
494}
495
Dan Gohmand934cb82017-02-24 23:18:00 +0000496// Compute a value to write into the code at the location covered
497// by RelEntry. This value isn't used by the static linker, since
498// we have addends; it just serves to make the code more readable
499// and to make standalone wasm modules directly usable.
Sam Clegg7c395942017-09-14 23:07:53 +0000500uint32_t
501WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000502 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
Dan Gohmand934cb82017-02-24 23:18:00 +0000503
Sam Clegg270ed1b2018-01-09 22:44:02 +0000504 // For undefined symbols, use zero
Sam Cleggb7787fd2017-06-20 04:04:59 +0000505 if (!Sym->isDefined(/*SetUsed=*/false))
Sam Clegg270ed1b2018-01-09 22:44:02 +0000506 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000507
Sam Clegg7c395942017-09-14 23:07:53 +0000508 uint32_t GlobalIndex = SymbolIndices[Sym];
509 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
510 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000511
512 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
513 uint32_t Value = Address;
514
515 return Value;
516}
517
Sam Clegg759631c2017-09-15 20:54:59 +0000518static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000519 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000520 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
521
Sam Clegg63ebb812017-09-29 16:50:08 +0000522 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
523
Sam Cleggc55d13f2017-10-27 00:08:55 +0000524 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000525 for (const MCFragment &Frag : DataSection) {
526 if (Frag.hasInstructions())
527 report_fatal_error("only data supported in data sections");
528
529 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
530 if (Align->getValueSize() != 1)
531 report_fatal_error("only byte values supported for alignment");
532 // If nops are requested, use zeros, as this is the data section.
533 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
534 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
535 Align->getAlignment()),
536 DataBytes.size() +
537 Align->getMaxBytesToEmit());
538 DataBytes.resize(Size, Value);
539 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000540 int64_t Size;
541 if (!Fill->getSize().evaluateAsAbsolute(Size))
542 llvm_unreachable("The fill should be an assembler constant");
543 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000544 } else {
545 const auto &DataFrag = cast<MCDataFragment>(Frag);
546 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
547
548 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000549 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000550 }
551 }
552
Sam Cleggc55d13f2017-10-27 00:08:55 +0000553 // Don't allow empty segments, or segments that end with zero-sized
554 // fragment, otherwise the linker cannot map symbols to a unique
555 // data segment. This can be triggered by zero-sized structs
556 // See: test/MC/WebAssembly/bss.ll
557 if (LastFragmentSize == 0)
558 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000559 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
560}
561
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000562uint32_t WasmObjectWriter::getRelocationIndexValue(
563 const WasmRelocationEntry &RelEntry) {
564 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000565 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
566 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000567 if (!IndirectSymbolIndices.count(RelEntry.Symbol))
Sam Clegg6006e092017-12-22 20:31:39 +0000568 report_fatal_error("symbol not found in table index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000569 RelEntry.Symbol->getName());
Sam Cleggd99f6072017-06-12 23:52:44 +0000570 return IndirectSymbolIndices[RelEntry.Symbol];
571 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000572 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Clegg13a2e892017-09-01 17:32:01 +0000573 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
574 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
575 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000576 if (!SymbolIndices.count(RelEntry.Symbol))
Sam Clegg6006e092017-12-22 20:31:39 +0000577 report_fatal_error("symbol not found in function/global index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000578 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000579 return SymbolIndices[RelEntry.Symbol];
580 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Cleggb7787fd2017-06-20 04:04:59 +0000581 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000582 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000583 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000584 return TypeIndices[RelEntry.Symbol];
585 default:
586 llvm_unreachable("invalid relocation type");
587 }
588}
589
Dan Gohmand934cb82017-02-24 23:18:00 +0000590// Apply the portions of the relocation records that we can handle ourselves
591// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000592void WasmObjectWriter::applyRelocations(
593 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
594 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000595 for (const WasmRelocationEntry &RelEntry : Relocations) {
596 uint64_t Offset = ContentsOffset +
597 RelEntry.FixupSection->getSectionOffset() +
598 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000599
Sam Cleggb7787fd2017-06-20 04:04:59 +0000600 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000601 switch (RelEntry.Type) {
602 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
603 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000604 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
605 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB: {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000606 uint32_t Index = getRelocationIndexValue(RelEntry);
607 WritePatchableSLEB(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000608 break;
609 }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000610 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
611 uint32_t Index = getRelocationIndexValue(RelEntry);
612 WriteI32(Stream, Index, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000613 break;
614 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000615 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000616 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000617 WritePatchableSLEB(Stream, Value, Offset);
618 break;
619 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000620 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB: {
Sam Clegg7c395942017-09-14 23:07:53 +0000621 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000622 WritePatchableLEB(Stream, Value, Offset);
623 break;
624 }
Sam Clegg13a2e892017-09-01 17:32:01 +0000625 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32: {
Sam Clegg7c395942017-09-14 23:07:53 +0000626 uint32_t Value = getProvisionalValue(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +0000627 WriteI32(Stream, Value, Offset);
628 break;
629 }
630 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000631 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000632 }
633 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000634}
635
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000636// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000637// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000638void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000639 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000640 raw_pwrite_stream &Stream = getStream();
641 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000642
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000643 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000644 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000645 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000646
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000647 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000648 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000649 encodeULEB128(Index, Stream);
650 if (RelEntry.hasAddend())
651 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000652 }
653}
654
Sam Clegg9e15f352017-06-03 02:01:24 +0000655void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000656 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000657 if (FunctionTypes.empty())
658 return;
659
660 SectionBookkeeping Section;
661 startSection(Section, wasm::WASM_SEC_TYPE);
662
663 encodeULEB128(FunctionTypes.size(), getStream());
664
665 for (const WasmFunctionType &FuncTy : FunctionTypes) {
666 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
667 encodeULEB128(FuncTy.Params.size(), getStream());
668 for (wasm::ValType Ty : FuncTy.Params)
669 writeValueType(Ty);
670 encodeULEB128(FuncTy.Returns.size(), getStream());
671 for (wasm::ValType Ty : FuncTy.Returns)
672 writeValueType(Ty);
673 }
674
675 endSection(Section);
676}
677
Sam Cleggf950b242017-12-11 23:03:38 +0000678void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
679 uint32_t DataSize,
680 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000681 if (Imports.empty())
682 return;
683
Sam Cleggf950b242017-12-11 23:03:38 +0000684 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
685
Sam Clegg9e15f352017-06-03 02:01:24 +0000686 SectionBookkeeping Section;
687 startSection(Section, wasm::WASM_SEC_IMPORT);
688
689 encodeULEB128(Imports.size(), getStream());
690 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000691 writeString(Import.ModuleName);
692 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000693
694 encodeULEB128(Import.Kind, getStream());
695
696 switch (Import.Kind) {
697 case wasm::WASM_EXTERNAL_FUNCTION:
698 encodeULEB128(Import.Type, getStream());
699 break;
700 case wasm::WASM_EXTERNAL_GLOBAL:
701 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000702 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000703 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000704 case wasm::WASM_EXTERNAL_MEMORY:
705 encodeULEB128(0, getStream()); // flags
706 encodeULEB128(NumPages, getStream()); // initial
707 break;
708 case wasm::WASM_EXTERNAL_TABLE:
709 encodeSLEB128(int32_t(Import.Type), getStream());
710 encodeULEB128(0, getStream()); // flags
711 encodeULEB128(NumElements, getStream()); // initial
712 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000713 default:
714 llvm_unreachable("unsupported import kind");
715 }
716 }
717
718 endSection(Section);
719}
720
Sam Clegg457fb0b2017-09-15 19:50:44 +0000721void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000722 if (Functions.empty())
723 return;
724
725 SectionBookkeeping Section;
726 startSection(Section, wasm::WASM_SEC_FUNCTION);
727
728 encodeULEB128(Functions.size(), getStream());
729 for (const WasmFunction &Func : Functions)
730 encodeULEB128(Func.Type, getStream());
731
732 endSection(Section);
733}
734
Sam Clegg7c395942017-09-14 23:07:53 +0000735void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000736 if (Globals.empty())
737 return;
738
739 SectionBookkeeping Section;
740 startSection(Section, wasm::WASM_SEC_GLOBAL);
741
742 encodeULEB128(Globals.size(), getStream());
743 for (const WasmGlobal &Global : Globals) {
744 writeValueType(Global.Type);
745 write8(Global.IsMutable);
746
747 if (Global.HasImport) {
748 assert(Global.InitialValue == 0);
749 write8(wasm::WASM_OPCODE_GET_GLOBAL);
750 encodeULEB128(Global.ImportIndex, getStream());
751 } else {
752 assert(Global.ImportIndex == 0);
753 write8(wasm::WASM_OPCODE_I32_CONST);
754 encodeSLEB128(Global.InitialValue, getStream()); // offset
755 }
756 write8(wasm::WASM_OPCODE_END);
757 }
758
759 endSection(Section);
760}
761
Sam Clegg457fb0b2017-09-15 19:50:44 +0000762void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000763 if (Exports.empty())
764 return;
765
766 SectionBookkeeping Section;
767 startSection(Section, wasm::WASM_SEC_EXPORT);
768
769 encodeULEB128(Exports.size(), getStream());
770 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000771 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000772 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 encodeULEB128(Export.Index, getStream());
774 }
775
776 endSection(Section);
777}
778
Sam Clegg457fb0b2017-09-15 19:50:44 +0000779void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000780 if (TableElems.empty())
781 return;
782
783 SectionBookkeeping Section;
784 startSection(Section, wasm::WASM_SEC_ELEM);
785
786 encodeULEB128(1, getStream()); // number of "segments"
787 encodeULEB128(0, getStream()); // the table index
788
789 // init expr for starting offset
790 write8(wasm::WASM_OPCODE_I32_CONST);
791 encodeSLEB128(0, getStream());
792 write8(wasm::WASM_OPCODE_END);
793
794 encodeULEB128(TableElems.size(), getStream());
795 for (uint32_t Elem : TableElems)
796 encodeULEB128(Elem, getStream());
797
798 endSection(Section);
799}
800
Sam Clegg457fb0b2017-09-15 19:50:44 +0000801void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
802 const MCAsmLayout &Layout,
803 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000804 if (Functions.empty())
805 return;
806
807 SectionBookkeeping Section;
808 startSection(Section, wasm::WASM_SEC_CODE);
809
810 encodeULEB128(Functions.size(), getStream());
811
812 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000813 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000814
Sam Clegg9e15f352017-06-03 02:01:24 +0000815 int64_t Size = 0;
816 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
817 report_fatal_error(".size expression must be evaluatable");
818
819 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000820 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000821 Asm.writeSectionData(&FuncSection, Layout);
822 }
823
Sam Clegg9e15f352017-06-03 02:01:24 +0000824 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000825 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000826
827 endSection(Section);
828}
829
Sam Clegg457fb0b2017-09-15 19:50:44 +0000830void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000831 if (Segments.empty())
832 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
834 SectionBookkeeping Section;
835 startSection(Section, wasm::WASM_SEC_DATA);
836
Sam Clegg7c395942017-09-14 23:07:53 +0000837 encodeULEB128(Segments.size(), getStream()); // count
838
839 for (const WasmDataSegment & Segment : Segments) {
840 encodeULEB128(0, getStream()); // memory index
841 write8(wasm::WASM_OPCODE_I32_CONST);
842 encodeSLEB128(Segment.Offset, getStream()); // offset
843 write8(wasm::WASM_OPCODE_END);
844 encodeULEB128(Segment.Data.size(), getStream()); // size
845 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
846 writeBytes(Segment.Data); // data
847 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000850 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000851
852 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000853}
854
855void WasmObjectWriter::writeNameSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000856 ArrayRef<WasmFunction> Functions,
857 ArrayRef<WasmImport> Imports,
Sam Clegg9e15f352017-06-03 02:01:24 +0000858 unsigned NumFuncImports) {
859 uint32_t TotalFunctions = NumFuncImports + Functions.size();
860 if (TotalFunctions == 0)
861 return;
862
863 SectionBookkeeping Section;
864 startSection(Section, wasm::WASM_SEC_CUSTOM, "name");
865 SectionBookkeeping SubSection;
866 startSection(SubSection, wasm::WASM_NAMES_FUNCTION);
867
868 encodeULEB128(TotalFunctions, getStream());
869 uint32_t Index = 0;
870 for (const WasmImport &Import : Imports) {
871 if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) {
872 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000873 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000874 ++Index;
875 }
876 }
877 for (const WasmFunction &Func : Functions) {
878 encodeULEB128(Index, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000879 writeString(Func.Sym->getName());
Sam Clegg9e15f352017-06-03 02:01:24 +0000880 ++Index;
881 }
882
883 endSection(SubSection);
884 endSection(Section);
885}
886
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000887void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000888 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
889 // for descriptions of the reloc sections.
890
891 if (CodeRelocations.empty())
892 return;
893
894 SectionBookkeeping Section;
895 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
896
897 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000898 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000899
Sam Clegg7c395942017-09-14 23:07:53 +0000900 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000901
902 endSection(Section);
903}
904
Sam Clegg7c395942017-09-14 23:07:53 +0000905void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000906 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
907 // for descriptions of the reloc sections.
908
909 if (DataRelocations.empty())
910 return;
911
912 SectionBookkeeping Section;
913 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
914
915 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
916 encodeULEB128(DataRelocations.size(), getStream());
917
Sam Clegg7c395942017-09-14 23:07:53 +0000918 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000919
920 endSection(Section);
921}
922
923void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000924 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000925 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
926 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
927 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000928 SectionBookkeeping Section;
929 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000930 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000931
Sam Clegg31a2c802017-09-20 21:17:04 +0000932 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000933 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000934 encodeULEB128(SymbolFlags.size(), getStream());
935 for (auto Pair: SymbolFlags) {
936 writeString(Pair.first);
937 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000938 }
939 endSection(SubSection);
940 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000941
Sam Clegg9e1ade92017-06-27 20:27:59 +0000942 if (DataSize > 0) {
943 startSection(SubSection, wasm::WASM_DATA_SIZE);
944 encodeULEB128(DataSize, getStream());
945 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000946 }
947
Sam Cleggd95ed952017-09-20 19:03:35 +0000948 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000949 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000950 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000951 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000952 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000953 encodeULEB128(Segment.Alignment, getStream());
954 encodeULEB128(Segment.Flags, getStream());
955 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000956 endSection(SubSection);
957 }
958
Sam Cleggbafe6902017-12-15 00:17:10 +0000959 if (!InitFuncs.empty()) {
960 startSection(SubSection, wasm::WASM_INIT_FUNCS);
961 encodeULEB128(InitFuncs.size(), getStream());
962 for (auto &StartFunc : InitFuncs) {
963 encodeULEB128(StartFunc.first, getStream()); // priority
964 encodeULEB128(StartFunc.second, getStream()); // function index
965 }
966 endSection(SubSection);
967 }
968
Sam Cleggea7cace2018-01-09 23:43:14 +0000969 if (Comdats.size()) {
970 startSection(SubSection, wasm::WASM_COMDAT_INFO);
971 encodeULEB128(Comdats.size(), getStream());
972 for (const auto &C : Comdats) {
973 writeString(C.first);
974 encodeULEB128(0, getStream()); // flags for future use
975 encodeULEB128(C.second.size(), getStream());
976 for (const WasmComdatEntry &Entry : C.second) {
977 encodeULEB128(Entry.Kind, getStream());
978 encodeULEB128(Entry.Index, getStream());
979 }
980 }
981 endSection(SubSection);
982 }
983
Sam Clegg9e15f352017-06-03 02:01:24 +0000984 endSection(Section);
985}
986
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000987uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
988 assert(Symbol.isFunction());
989 assert(TypeIndices.count(&Symbol));
990 return TypeIndices[&Symbol];
991}
992
993uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
994 assert(Symbol.isFunction());
995
996 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000997 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
998 F.Returns = ResolvedSym->getReturns();
999 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001000
1001 auto Pair =
1002 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1003 if (Pair.second)
1004 FunctionTypes.push_back(F);
1005 TypeIndices[&Symbol] = Pair.first->second;
1006
1007 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
1008 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
1009 return Pair.first->second;
1010}
1011
Dan Gohman18eafb62017-02-22 01:23:18 +00001012void WasmObjectWriter::writeObject(MCAssembler &Asm,
1013 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001014 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001015 MCContext &Ctx = Asm.getContext();
Derek Schuffb8795392017-03-16 20:49:48 +00001016 wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32;
Dan Gohmand934cb82017-02-24 23:18:00 +00001017
1018 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001019 SmallVector<WasmFunction, 4> Functions;
1020 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +00001021 SmallVector<WasmImport, 4> Imports;
1022 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +00001023 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Sam Cleggbafe6902017-12-15 00:17:10 +00001024 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001025 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Dan Gohmand934cb82017-02-24 23:18:00 +00001026 unsigned NumFuncImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +00001027 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +00001028 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001029
Dan Gohman82607f52017-02-24 23:46:05 +00001030 // In the special .global_variables section, we've encoded global
1031 // variables used by the function. Translate them into the Globals
1032 // list.
Sam Clegg12fd3da2017-10-20 21:28:38 +00001033 MCSectionWasm *GlobalVars =
1034 Ctx.getWasmSection(".global_variables", SectionKind::getMetadata());
Dan Gohman82607f52017-02-24 23:46:05 +00001035 if (!GlobalVars->getFragmentList().empty()) {
1036 if (GlobalVars->getFragmentList().size() != 1)
1037 report_fatal_error("only one .global_variables fragment supported");
1038 const MCFragment &Frag = *GlobalVars->begin();
1039 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1040 report_fatal_error("only data supported in .global_variables");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001041 const auto &DataFrag = cast<MCDataFragment>(Frag);
Dan Gohman82607f52017-02-24 23:46:05 +00001042 if (!DataFrag.getFixups().empty())
1043 report_fatal_error("fixups not supported in .global_variables");
1044 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Dan Gohman970d02c2017-03-30 23:58:19 +00001045 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1046 *end = (const uint8_t *)Contents.data() + Contents.size();
1047 p != end; ) {
Dan Gohman82607f52017-02-24 23:46:05 +00001048 WasmGlobal G;
Dan Gohman970d02c2017-03-30 23:58:19 +00001049 if (end - p < 3)
1050 report_fatal_error("truncated global variable encoding");
1051 G.Type = wasm::ValType(int8_t(*p++));
1052 G.IsMutable = bool(*p++);
1053 G.HasImport = bool(*p++);
1054 if (G.HasImport) {
1055 G.InitialValue = 0;
1056
1057 WasmImport Import;
1058 Import.ModuleName = (const char *)p;
1059 const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p);
1060 if (!nul)
1061 report_fatal_error("global module name must be nul-terminated");
1062 p = nul + 1;
1063 nul = (const uint8_t *)memchr(p, '\0', end - p);
1064 if (!nul)
1065 report_fatal_error("global base name must be nul-terminated");
1066 Import.FieldName = (const char *)p;
1067 p = nul + 1;
1068
1069 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1070 Import.Type = int32_t(G.Type);
1071
1072 G.ImportIndex = NumGlobalImports;
1073 ++NumGlobalImports;
1074
1075 Imports.push_back(Import);
1076 } else {
1077 unsigned n;
1078 G.InitialValue = decodeSLEB128(p, &n);
1079 G.ImportIndex = 0;
Simon Pilgrimc8da0c02017-03-31 10:45:35 +00001080 if ((ptrdiff_t)n > end - p)
Dan Gohman970d02c2017-03-30 23:58:19 +00001081 report_fatal_error("global initial value must be valid SLEB128");
1082 p += n;
1083 }
Dan Gohman82607f52017-02-24 23:46:05 +00001084 Globals.push_back(G);
1085 }
1086 }
1087
Sam Cleggf950b242017-12-11 23:03:38 +00001088 // For now, always emit the memory import, since loads and stores are not
1089 // valid without it. In the future, we could perhaps be more clever and omit
1090 // it if there are no loads or stores.
1091 MCSymbolWasm *MemorySym =
1092 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
1093 WasmImport MemImport;
1094 MemImport.ModuleName = MemorySym->getModuleName();
1095 MemImport.FieldName = MemorySym->getName();
1096 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1097 Imports.push_back(MemImport);
1098
1099 // For now, always emit the table section, since indirect calls are not
1100 // valid without it. In the future, we could perhaps be more clever and omit
1101 // it if there are no indirect calls.
1102 MCSymbolWasm *TableSym =
1103 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
1104 WasmImport TableImport;
1105 TableImport.ModuleName = TableSym->getModuleName();
1106 TableImport.FieldName = TableSym->getName();
1107 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1108 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
1109 Imports.push_back(TableImport);
1110
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001111 // Populate FunctionTypeIndices and Imports.
1112 for (const MCSymbol &S : Asm.symbols()) {
1113 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1114
1115 // Register types for all functions, including those with private linkage
1116 // (making them
1117 // because wasm always needs a type signature.
1118 if (WS.isFunction())
1119 registerFunctionType(WS);
1120
1121 if (WS.isTemporary())
1122 continue;
1123
1124 // If the symbol is not defined in this translation unit, import it.
Sam Cleggd423f0d2018-01-11 20:35:17 +00001125 if ((!WS.isDefined(/*SetUsed=*/false) && !WS.isComdat()) ||
1126 WS.isVariable()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001127 WasmImport Import;
1128 Import.ModuleName = WS.getModuleName();
1129 Import.FieldName = WS.getName();
1130
1131 if (WS.isFunction()) {
1132 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1133 Import.Type = getFunctionType(WS);
1134 SymbolIndices[&WS] = NumFuncImports;
1135 ++NumFuncImports;
1136 } else {
1137 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1138 Import.Type = int32_t(PtrType);
1139 Import.IsMutable = false;
1140 SymbolIndices[&WS] = NumGlobalImports;
1141
Dan Gohman83b16222017-12-20 00:10:28 +00001142 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001143 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001144 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001145
1146 ++NumGlobalImports;
1147 }
1148
1149 Imports.push_back(Import);
1150 }
1151 }
1152
Sam Clegg759631c2017-09-15 20:54:59 +00001153 for (MCSection &Sec : Asm) {
1154 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001155 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001156 continue;
1157
Sam Cleggbafe6902017-12-15 00:17:10 +00001158 // .init_array sections are handled specially elsewhere.
1159 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1160 continue;
1161
Sam Clegg759631c2017-09-15 20:54:59 +00001162 DataSize = alignTo(DataSize, Section.getAlignment());
1163 DataSegments.emplace_back();
1164 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001165 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001166 Segment.Offset = DataSize;
1167 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001168 addData(Segment.Data, Section);
1169 Segment.Alignment = Section.getAlignment();
1170 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001171 DataSize += Segment.Data.size();
1172 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001173
1174 if (const MCSymbolWasm *C = Section.getGroup()) {
1175 Comdats[C->getName()].emplace_back(
1176 WasmComdatEntry{wasm::WASM_COMDAT_DATA,
1177 static_cast<uint32_t>(DataSegments.size()) - 1});
1178 }
Sam Clegg759631c2017-09-15 20:54:59 +00001179 }
1180
Sam Cleggb7787fd2017-06-20 04:04:59 +00001181 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001182 for (const MCSymbol &S : Asm.symbols()) {
1183 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1184 // or used in relocations.
1185 if (S.isTemporary() && S.getName().empty())
1186 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001187
Dan Gohmand934cb82017-02-24 23:18:00 +00001188 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001189 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
1190 << " isDefined=" << S.isDefined() << " isExternal="
1191 << S.isExternal() << " isTemporary=" << S.isTemporary()
1192 << " isFunction=" << WS.isFunction()
1193 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001194 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001195 << " isVariable=" << WS.isVariable() << "\n");
1196
Sam Clegga2b35da2017-12-03 01:19:23 +00001197 if (WS.isWeak() || WS.isHidden()) {
1198 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1199 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1200 SymbolFlags.emplace_back(WS.getName(), Flags);
1201 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001202
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001203 if (WS.isVariable())
1204 continue;
1205
Dan Gohmand934cb82017-02-24 23:18:00 +00001206 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001207
Dan Gohmand934cb82017-02-24 23:18:00 +00001208 if (WS.isFunction()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001209 if (WS.isDefined(/*SetUsed=*/false)) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001210 if (WS.getOffset() != 0)
1211 report_fatal_error(
1212 "function sections must contain one function each");
1213
1214 if (WS.getSize() == 0)
1215 report_fatal_error(
1216 "function symbols must have a size set with .size");
1217
Dan Gohmand934cb82017-02-24 23:18:00 +00001218 // A definition. Take the next available index.
1219 Index = NumFuncImports + Functions.size();
1220
1221 // Prepare the function.
1222 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001223 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001224 Func.Sym = &WS;
1225 SymbolIndices[&WS] = Index;
1226 Functions.push_back(Func);
1227 } else {
1228 // An import; the index was assigned above.
1229 Index = SymbolIndices.find(&WS)->second;
1230 }
1231
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001232 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001233 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001234 if (WS.isTemporary() && !WS.getSize())
1235 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001236
Sam Cleggfe6414b2017-06-21 23:46:41 +00001237 if (!WS.isDefined(/*SetUsed=*/false))
1238 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001239
Sam Cleggfe6414b2017-06-21 23:46:41 +00001240 if (!WS.getSize())
1241 report_fatal_error("data symbols must have a size set with .size: " +
1242 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001243
Sam Cleggfe6414b2017-06-21 23:46:41 +00001244 int64_t Size = 0;
1245 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1246 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001247
Sam Clegg7c395942017-09-14 23:07:53 +00001248 // For each global, prepare a corresponding wasm global holding its
1249 // address. For externals these will also be named exports.
1250 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001251 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001252 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001253
1254 WasmGlobal Global;
1255 Global.Type = PtrType;
1256 Global.IsMutable = false;
1257 Global.HasImport = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001258 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001259 Global.ImportIndex = 0;
1260 SymbolIndices[&WS] = Index;
1261 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1262 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001263 }
1264
1265 // If the symbol is visible outside this translation unit, export it.
Sam Clegg31a2c802017-09-20 21:17:04 +00001266 if (WS.isDefined(/*SetUsed=*/false)) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001267 WasmExport Export;
1268 Export.FieldName = WS.getName();
1269 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001270 if (WS.isFunction())
1271 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1272 else
1273 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001274 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001275 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001276
Sam Clegg31a2c802017-09-20 21:17:04 +00001277 if (!WS.isExternal())
1278 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001279
1280 if (WS.isFunction()) {
1281 auto &Section = static_cast<MCSectionWasm &>(WS.getSection(false));
1282 if (const MCSymbolWasm *C = Section.getGroup())
1283 Comdats[C->getName()].emplace_back(
1284 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1285 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001286 }
1287 }
1288
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001289 // Handle weak aliases. We need to process these in a separate pass because
1290 // we need to have processed the target of the alias before the alias itself
1291 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001292 for (const MCSymbol &S : Asm.symbols()) {
1293 if (!S.isVariable())
1294 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001295
Sam Cleggb7787fd2017-06-20 04:04:59 +00001296 assert(S.isDefined(/*SetUsed=*/false));
1297
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001298 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001299 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1300 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001301 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1302 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001303 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001304 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001305
1306 WasmExport Export;
1307 Export.FieldName = WS.getName();
1308 Export.Index = Index;
1309 if (WS.isFunction())
1310 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1311 else
1312 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001313 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001314 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001315
1316 if (!WS.isExternal())
1317 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001318 }
1319
Sam Clegg6006e092017-12-22 20:31:39 +00001320 {
1321 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1322 // Functions referenced by a relocation need to prepared to be called
1323 // indirectly.
1324 const MCSymbolWasm& WS = *Rel.Symbol;
1325 if (WS.isFunction() && IndirectSymbolIndices.count(&WS) == 0) {
1326 switch (Rel.Type) {
1327 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
1328 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
1329 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
1330 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
1331 uint32_t Index = SymbolIndices.find(&WS)->second;
1332 IndirectSymbolIndices[&WS] = TableElems.size();
1333 DEBUG(dbgs() << " -> adding to table: " << TableElems.size() << "\n");
1334 TableElems.push_back(Index);
1335 registerFunctionType(WS);
1336 break;
1337 }
1338 default:
1339 break;
1340 }
1341 }
1342 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001343
Sam Clegg6006e092017-12-22 20:31:39 +00001344 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1345 HandleReloc(RelEntry);
1346 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1347 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001348 }
1349
Sam Cleggbafe6902017-12-15 00:17:10 +00001350 // Translate .init_array section contents into start functions.
1351 for (const MCSection &S : Asm) {
1352 const auto &WS = static_cast<const MCSectionWasm &>(S);
1353 if (WS.getSectionName().startswith(".fini_array"))
1354 report_fatal_error(".fini_array sections are unsupported");
1355 if (!WS.getSectionName().startswith(".init_array"))
1356 continue;
1357 if (WS.getFragmentList().empty())
1358 continue;
1359 if (WS.getFragmentList().size() != 2)
1360 report_fatal_error("only one .init_array section fragment supported");
1361 const MCFragment &AlignFrag = *WS.begin();
1362 if (AlignFrag.getKind() != MCFragment::FT_Align)
1363 report_fatal_error(".init_array section should be aligned");
1364 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1365 report_fatal_error(".init_array section should be aligned for pointers");
1366 const MCFragment &Frag = *std::next(WS.begin());
1367 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1368 report_fatal_error("only data supported in .init_array section");
1369 uint16_t Priority = UINT16_MAX;
1370 if (WS.getSectionName().size() != 11) {
1371 if (WS.getSectionName()[11] != '.')
1372 report_fatal_error(".init_array section priority should start with '.'");
1373 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1374 report_fatal_error("invalid .init_array section priority");
1375 }
1376 const auto &DataFrag = cast<MCDataFragment>(Frag);
1377 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1378 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1379 *end = (const uint8_t *)Contents.data() + Contents.size();
1380 p != end; ++p) {
1381 if (*p != 0)
1382 report_fatal_error("non-symbolic data in .init_array section");
1383 }
1384 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1385 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1386 const MCExpr *Expr = Fixup.getValue();
1387 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1388 if (!Sym)
1389 report_fatal_error("fixups in .init_array should be symbol references");
1390 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1391 report_fatal_error("symbols in .init_array should be for functions");
1392 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1393 if (I == SymbolIndices.end())
1394 report_fatal_error("symbols in .init_array should be defined");
1395 uint32_t Index = I->second;
1396 InitFuncs.push_back(std::make_pair(Priority, Index));
1397 }
1398 }
1399
Dan Gohman18eafb62017-02-22 01:23:18 +00001400 // Write out the Wasm header.
1401 writeHeader(Asm);
1402
Sam Clegg9e15f352017-06-03 02:01:24 +00001403 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001404 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001405 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001406 // Skip the "table" section; we import the table instead.
1407 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001408 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001409 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001410 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001411 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001412 writeDataSection(DataSegments);
Sam Clegg9e15f352017-06-03 02:01:24 +00001413 writeNameSection(Functions, Imports, NumFuncImports);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001414 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001415 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001416 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001417 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001418
Dan Gohmand934cb82017-02-24 23:18:00 +00001419 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001420 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001421}
1422
Lang Hames60fbc7c2017-10-10 16:28:07 +00001423std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001424llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1425 raw_pwrite_stream &OS) {
Lang Hames60fbc7c2017-10-10 16:28:07 +00001426 // FIXME: Can't use make_unique<WasmObjectWriter>(...) as WasmObjectWriter's
1427 // destructor is private. Is that necessary?
1428 return std::unique_ptr<MCObjectWriter>(
1429 new WasmObjectWriter(std::move(MOTW), OS));
Dan Gohman18eafb62017-02-22 01:23:18 +00001430}