blob: 28d339409f8ce7a28548e7d72db7d15f102bb114 [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 {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000138 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000139 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000140};
141
Sam Cleggea7cace2018-01-09 23:43:14 +0000142// Information about a single item which is part of a COMDAT. For each data
143// segment or function which is in the COMDAT, there is a corresponding
144// WasmComdatEntry.
145struct WasmComdatEntry {
146 unsigned Kind;
147 uint32_t Index;
148};
149
Sam Clegg6dc65e92017-06-06 16:38:59 +0000150// Information about a single relocation.
151struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000152 uint64_t Offset; // Where is the relocation.
153 const MCSymbolWasm *Symbol; // The symbol to relocate with.
154 int64_t Addend; // A value to add to the symbol.
155 unsigned Type; // The type of the relocation.
156 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000157
158 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
159 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000160 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000161 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
162 FixupSection(FixupSection) {}
163
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000164 bool hasAddend() const {
165 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000166 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
167 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
168 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000169 return true;
170 default:
171 return false;
172 }
173 }
174
Sam Clegg6dc65e92017-06-06 16:38:59 +0000175 void print(raw_ostream &Out) const {
Sam Clegg9bf73c02017-07-05 20:25:08 +0000176 Out << "Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000177 << ", Type=" << Type
178 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000179 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000180
Aaron Ballman615eb472017-10-15 14:32:27 +0000181#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000182 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
183#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000184};
185
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000186#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000187raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000188 Rel.print(OS);
189 return OS;
190}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000191#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000192
Dan Gohman18eafb62017-02-22 01:23:18 +0000193class WasmObjectWriter : public MCObjectWriter {
Dan Gohman18eafb62017-02-22 01:23:18 +0000194 /// The target specific Wasm writer instance.
195 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
196
Dan Gohmand934cb82017-02-24 23:18:00 +0000197 // Relocations for fixing up references in the code section.
198 std::vector<WasmRelocationEntry> CodeRelocations;
199
200 // Relocations for fixing up references in the data section.
201 std::vector<WasmRelocationEntry> DataRelocations;
202
Dan Gohmand934cb82017-02-24 23:18:00 +0000203 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000204 // Maps function symbols to the index of the type of the function
205 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000206 // Maps function symbols to the table element index space. Used
207 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000208 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000209 // Maps function/global symbols to the function/global index space.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000210 DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices;
211
212 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
213 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000214 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000215 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000216 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000217 unsigned NumGlobalImports = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000218
Dan Gohman18eafb62017-02-22 01:23:18 +0000219 // TargetObjectWriter wrappers.
220 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000221 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
222 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000223 }
224
Dan Gohmand934cb82017-02-24 23:18:00 +0000225 void startSection(SectionBookkeeping &Section, unsigned SectionId,
226 const char *Name = nullptr);
227 void endSection(SectionBookkeeping &Section);
228
Dan Gohman18eafb62017-02-22 01:23:18 +0000229public:
Lang Hames1301a872017-10-10 01:15:10 +0000230 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
231 raw_pwrite_stream &OS)
232 : MCObjectWriter(OS, /*IsLittleEndian=*/true),
233 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000234
Dan Gohman18eafb62017-02-22 01:23:18 +0000235 ~WasmObjectWriter() override;
236
Dan Gohman0917c9e2018-01-15 17:06:23 +0000237private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000238 void reset() override {
239 CodeRelocations.clear();
240 DataRelocations.clear();
241 TypeIndices.clear();
242 SymbolIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000243 TableIndices.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000244 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000245 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000246 Globals.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000247 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000248 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000249 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000250 }
251
Dan Gohman18eafb62017-02-22 01:23:18 +0000252 void writeHeader(const MCAssembler &Asm);
253
254 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
255 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000256 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000257
258 void executePostLayoutBinding(MCAssembler &Asm,
259 const MCAsmLayout &Layout) override;
260
261 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000262
Sam Cleggb7787fd2017-06-20 04:04:59 +0000263 void writeString(const StringRef Str) {
264 encodeULEB128(Str.size(), getStream());
265 writeBytes(Str);
266 }
267
Sam Clegg9e15f352017-06-03 02:01:24 +0000268 void writeValueType(wasm::ValType Ty) {
269 encodeSLEB128(int32_t(Ty), getStream());
270 }
271
Sam Clegg457fb0b2017-09-15 19:50:44 +0000272 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +0000273 void writeImportSection(ArrayRef<WasmImport> Imports, uint32_t DataSize,
274 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000275 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000276 void writeGlobalSection();
Sam Clegg457fb0b2017-09-15 19:50:44 +0000277 void writeExportSection(ArrayRef<WasmExport> Exports);
278 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000279 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000280 ArrayRef<WasmFunction> Functions);
281 void writeDataSection(ArrayRef<WasmDataSegment> Segments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000282 void writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +0000283 void writeDataRelocSection();
Sam Clegg31a2c802017-09-20 21:17:04 +0000284 void writeLinkingMetaDataSection(
285 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000286 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
287 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
288 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000289
Sam Clegg7c395942017-09-14 23:07:53 +0000290 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000291 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
292 uint64_t ContentsOffset);
293
Sam Clegg7c395942017-09-14 23:07:53 +0000294 void writeRelocations(ArrayRef<WasmRelocationEntry> Relocations);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000295 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000296 uint32_t getFunctionType(const MCSymbolWasm& Symbol);
297 uint32_t registerFunctionType(const MCSymbolWasm& Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000298};
Sam Clegg9e15f352017-06-03 02:01:24 +0000299
Dan Gohman18eafb62017-02-22 01:23:18 +0000300} // end anonymous namespace
301
302WasmObjectWriter::~WasmObjectWriter() {}
303
Dan Gohmand934cb82017-02-24 23:18:00 +0000304// Write out a section header and a patchable section size field.
305void WasmObjectWriter::startSection(SectionBookkeeping &Section,
306 unsigned SectionId,
307 const char *Name) {
308 assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) &&
309 "Only custom sections can have names");
310
Sam Cleggb7787fd2017-06-20 04:04:59 +0000311 DEBUG(dbgs() << "startSection " << SectionId << ": " << Name << "\n");
Derek Schuffe2688c42017-03-14 20:23:22 +0000312 encodeULEB128(SectionId, getStream());
Dan Gohmand934cb82017-02-24 23:18:00 +0000313
314 Section.SizeOffset = getStream().tell();
315
316 // The section size. We don't know the size yet, so reserve enough space
317 // for any 32-bit value; we'll patch it later.
318 encodeULEB128(UINT32_MAX, getStream());
319
320 // The position where the section starts, for measuring its size.
321 Section.ContentsOffset = getStream().tell();
322
323 // Custom sections in wasm also have a string identifier.
324 if (SectionId == wasm::WASM_SEC_CUSTOM) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000325 assert(Name);
326 writeString(StringRef(Name));
Dan Gohmand934cb82017-02-24 23:18:00 +0000327 }
328}
329
330// Now that the section is complete and we know how big it is, patch up the
331// section size field at the start of the section.
332void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
333 uint64_t Size = getStream().tell() - Section.ContentsOffset;
334 if (uint32_t(Size) != Size)
335 report_fatal_error("section size does not fit in a uint32_t");
336
Sam Cleggb7787fd2017-06-20 04:04:59 +0000337 DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000338
339 // Write the final section size to the payload_len field, which follows
340 // the section id byte.
341 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000342 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000343 assert(SizeLen == 5);
344 getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset);
345}
346
Dan Gohman18eafb62017-02-22 01:23:18 +0000347// Emit the Wasm header.
348void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Dan Gohman7ea5adf2017-02-22 18:50:20 +0000349 writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic)));
350 writeLE32(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000351}
352
353void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
354 const MCAsmLayout &Layout) {
355}
356
357void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
358 const MCAsmLayout &Layout,
359 const MCFragment *Fragment,
360 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000361 uint64_t &FixedValue) {
362 MCAsmBackend &Backend = Asm.getBackend();
363 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
364 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000365 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000366 uint64_t C = Target.getConstant();
367 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
368 MCContext &Ctx = Asm.getContext();
369
Sam Cleggbafe6902017-12-15 00:17:10 +0000370 // The .init_array isn't translated as data, so don't do relocations in it.
371 if (FixupSection.getSectionName().startswith(".init_array"))
372 return;
373
Dan Gohmand934cb82017-02-24 23:18:00 +0000374 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
375 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
376 "Should not have constructed this");
377
378 // Let A, B and C being the components of Target and R be the location of
379 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
380 // If it is pcrel, we want to compute (A - B + C - R).
381
382 // In general, Wasm has no relocations for -B. It can only represent (A + C)
383 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
384 // replace B to implement it: (A - R - K + C)
385 if (IsPCRel) {
386 Ctx.reportError(
387 Fixup.getLoc(),
388 "No relocation available to represent this relative expression");
389 return;
390 }
391
392 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
393
394 if (SymB.isUndefined()) {
395 Ctx.reportError(Fixup.getLoc(),
396 Twine("symbol '") + SymB.getName() +
397 "' can not be undefined in a subtraction expression");
398 return;
399 }
400
401 assert(!SymB.isAbsolute() && "Should have been folded");
402 const MCSection &SecB = SymB.getSection();
403 if (&SecB != &FixupSection) {
404 Ctx.reportError(Fixup.getLoc(),
405 "Cannot represent a difference across sections");
406 return;
407 }
408
409 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
410 uint64_t K = SymBOffset - FixupOffset;
411 IsPCRel = true;
412 C -= K;
413 }
414
415 // We either rejected the fixup or folded B into C at this point.
416 const MCSymbolRefExpr *RefA = Target.getSymA();
417 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
418
Dan Gohmand934cb82017-02-24 23:18:00 +0000419 if (SymA && SymA->isVariable()) {
420 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000421 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
422 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
423 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000424 }
425
426 // Put any constant offset in an addend. Offsets can be negative, and
427 // LLVM expects wrapping, in contrast to wasm's immediates which can't
428 // be negative and don't wrap.
429 FixedValue = 0;
430
Sam Clegg6ad8f192017-07-11 02:21:57 +0000431 if (SymA)
432 SymA->setUsedInReloc();
Dan Gohmand934cb82017-02-24 23:18:00 +0000433
Sam Cleggae03c1e72017-06-13 18:51:50 +0000434 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000435 assert(SymA);
436
Sam Cleggae03c1e72017-06-13 18:51:50 +0000437 unsigned Type = getRelocType(Target, Fixup);
438
Dan Gohmand934cb82017-02-24 23:18:00 +0000439 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Sam Cleggb7787fd2017-06-20 04:04:59 +0000440 DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000441
Sam Clegg12fd3da2017-10-20 21:28:38 +0000442 if (FixupSection.isWasmData())
Dan Gohmand934cb82017-02-24 23:18:00 +0000443 DataRelocations.push_back(Rec);
Sam Clegg12fd3da2017-10-20 21:28:38 +0000444 else if (FixupSection.getKind().isText())
445 CodeRelocations.push_back(Rec);
446 else if (!FixupSection.getKind().isMetadata())
447 // TODO(sbc): Add support for debug sections.
448 llvm_unreachable("unexpected section type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000449}
450
Dan Gohmand934cb82017-02-24 23:18:00 +0000451// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
452// to allow patching.
453static void
454WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
455 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000456 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000457 assert(SizeLen == 5);
458 Stream.pwrite((char *)Buffer, SizeLen, Offset);
459}
460
461// Write X as an signed LEB value at offset Offset in Stream, padded
462// to allow patching.
463static void
464WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
465 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000466 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000467 assert(SizeLen == 5);
468 Stream.pwrite((char *)Buffer, SizeLen, Offset);
469}
470
471// Write X as a plain integer value at offset Offset in Stream.
472static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
473 uint8_t Buffer[4];
474 support::endian::write32le(Buffer, X);
475 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
476}
477
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000478static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
479 if (Symbol.isVariable()) {
480 const MCExpr *Expr = Symbol.getVariableValue();
481 auto *Inner = cast<MCSymbolRefExpr>(Expr);
482 return cast<MCSymbolWasm>(&Inner->getSymbol());
483 }
484 return &Symbol;
485}
486
Dan Gohmand934cb82017-02-24 23:18:00 +0000487// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000488// by RelEntry. This value isn't used by the static linker; it just serves
489// to make the object format more readable and more likely to be directly
490// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000491uint32_t
492WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000493 switch (RelEntry.Type) {
494 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000495 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
496 // Provisional value is table address of the resolved symbol itself
497 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
498 assert(Sym->isFunction());
499 return TableIndices[Sym];
500 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000501 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
502 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
503 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000504 // Provisional value is function/type/global index itself
Sam Clegg60ec3032018-01-23 01:23:17 +0000505 return getRelocationIndexValue(RelEntry);
506 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
507 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
508 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000509 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000510 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
511 // For undefined symbols, use zero
512 if (!Sym->isDefined())
513 return 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000514
Sam Clegg60ec3032018-01-23 01:23:17 +0000515 uint32_t GlobalIndex = SymbolIndices[Sym];
516 const WasmGlobal& Global = Globals[GlobalIndex - NumGlobalImports];
517 uint64_t Address = Global.InitialValue + RelEntry.Addend;
Dan Gohmand934cb82017-02-24 23:18:00 +0000518
Sam Clegg60ec3032018-01-23 01:23:17 +0000519 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
520 return Address;
521 }
522 default:
523 llvm_unreachable("invalid relocation type");
524 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000525}
526
Sam Clegg759631c2017-09-15 20:54:59 +0000527static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000528 MCSectionWasm &DataSection) {
Sam Clegg759631c2017-09-15 20:54:59 +0000529 DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
530
Sam Clegg63ebb812017-09-29 16:50:08 +0000531 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
532
Sam Cleggc55d13f2017-10-27 00:08:55 +0000533 size_t LastFragmentSize = 0;
Sam Clegg759631c2017-09-15 20:54:59 +0000534 for (const MCFragment &Frag : DataSection) {
535 if (Frag.hasInstructions())
536 report_fatal_error("only data supported in data sections");
537
538 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
539 if (Align->getValueSize() != 1)
540 report_fatal_error("only byte values supported for alignment");
541 // If nops are requested, use zeros, as this is the data section.
542 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
543 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
544 Align->getAlignment()),
545 DataBytes.size() +
546 Align->getMaxBytesToEmit());
547 DataBytes.resize(Size, Value);
548 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Rafael Espindolad707c372018-01-09 22:48:37 +0000549 int64_t Size;
550 if (!Fill->getSize().evaluateAsAbsolute(Size))
551 llvm_unreachable("The fill should be an assembler constant");
552 DataBytes.insert(DataBytes.end(), Size, Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000553 } else {
554 const auto &DataFrag = cast<MCDataFragment>(Frag);
555 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
556
557 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Cleggc55d13f2017-10-27 00:08:55 +0000558 LastFragmentSize = Contents.size();
Sam Clegg759631c2017-09-15 20:54:59 +0000559 }
560 }
561
Sam Cleggc55d13f2017-10-27 00:08:55 +0000562 // Don't allow empty segments, or segments that end with zero-sized
563 // fragment, otherwise the linker cannot map symbols to a unique
564 // data segment. This can be triggered by zero-sized structs
565 // See: test/MC/WebAssembly/bss.ll
566 if (LastFragmentSize == 0)
567 DataBytes.resize(DataBytes.size() + 1);
Sam Clegg759631c2017-09-15 20:54:59 +0000568 DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
569}
570
Sam Clegg60ec3032018-01-23 01:23:17 +0000571uint32_t
572WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
573 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000574 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000575 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000576 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000577 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000578 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000579
580 if (!SymbolIndices.count(RelEntry.Symbol))
581 report_fatal_error("symbol not found in function/global index space: " +
582 RelEntry.Symbol->getName());
583 return SymbolIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000584}
585
Dan Gohmand934cb82017-02-24 23:18:00 +0000586// Apply the portions of the relocation records that we can handle ourselves
587// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000588void WasmObjectWriter::applyRelocations(
589 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
590 raw_pwrite_stream &Stream = getStream();
Dan Gohmand934cb82017-02-24 23:18:00 +0000591 for (const WasmRelocationEntry &RelEntry : Relocations) {
592 uint64_t Offset = ContentsOffset +
593 RelEntry.FixupSection->getSectionOffset() +
594 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000595
Sam Cleggb7787fd2017-06-20 04:04:59 +0000596 DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000597 uint32_t Value = getProvisionalValue(RelEntry);
598
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000599 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000600 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000601 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000602 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
603 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000604 WritePatchableLEB(Stream, Value, Offset);
605 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000606 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
607 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000608 WriteI32(Stream, Value, Offset);
609 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000610 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
611 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
612 WritePatchableSLEB(Stream, Value, Offset);
613 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000614 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000615 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000616 }
617 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000618}
619
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000620// Write out the portions of the relocation records that the linker will
Dan Gohman970d02c2017-03-30 23:58:19 +0000621// need to handle.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000622void WasmObjectWriter::writeRelocations(
Sam Clegg7c395942017-09-14 23:07:53 +0000623 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000624 raw_pwrite_stream &Stream = getStream();
625 for (const WasmRelocationEntry& RelEntry : Relocations) {
Dan Gohman970d02c2017-03-30 23:58:19 +0000626
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000627 uint64_t Offset = RelEntry.Offset +
Sam Clegg7c395942017-09-14 23:07:53 +0000628 RelEntry.FixupSection->getSectionOffset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000629 uint32_t Index = getRelocationIndexValue(RelEntry);
Dan Gohman970d02c2017-03-30 23:58:19 +0000630
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000631 encodeULEB128(RelEntry.Type, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000632 encodeULEB128(Offset, Stream);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000633 encodeULEB128(Index, Stream);
634 if (RelEntry.hasAddend())
635 encodeSLEB128(RelEntry.Addend, Stream);
Dan Gohman970d02c2017-03-30 23:58:19 +0000636 }
637}
638
Sam Clegg9e15f352017-06-03 02:01:24 +0000639void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000640 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000641 if (FunctionTypes.empty())
642 return;
643
644 SectionBookkeeping Section;
645 startSection(Section, wasm::WASM_SEC_TYPE);
646
647 encodeULEB128(FunctionTypes.size(), getStream());
648
649 for (const WasmFunctionType &FuncTy : FunctionTypes) {
650 encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream());
651 encodeULEB128(FuncTy.Params.size(), getStream());
652 for (wasm::ValType Ty : FuncTy.Params)
653 writeValueType(Ty);
654 encodeULEB128(FuncTy.Returns.size(), getStream());
655 for (wasm::ValType Ty : FuncTy.Returns)
656 writeValueType(Ty);
657 }
658
659 endSection(Section);
660}
661
Sam Cleggf950b242017-12-11 23:03:38 +0000662void WasmObjectWriter::writeImportSection(ArrayRef<WasmImport> Imports,
663 uint32_t DataSize,
664 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000665 if (Imports.empty())
666 return;
667
Sam Cleggf950b242017-12-11 23:03:38 +0000668 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
669
Sam Clegg9e15f352017-06-03 02:01:24 +0000670 SectionBookkeeping Section;
671 startSection(Section, wasm::WASM_SEC_IMPORT);
672
673 encodeULEB128(Imports.size(), getStream());
674 for (const WasmImport &Import : Imports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000675 writeString(Import.ModuleName);
676 writeString(Import.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000677
678 encodeULEB128(Import.Kind, getStream());
679
680 switch (Import.Kind) {
681 case wasm::WASM_EXTERNAL_FUNCTION:
682 encodeULEB128(Import.Type, getStream());
683 break;
684 case wasm::WASM_EXTERNAL_GLOBAL:
685 encodeSLEB128(int32_t(Import.Type), getStream());
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000686 encodeULEB128(int32_t(Import.IsMutable), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000687 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000688 case wasm::WASM_EXTERNAL_MEMORY:
689 encodeULEB128(0, getStream()); // flags
690 encodeULEB128(NumPages, getStream()); // initial
691 break;
692 case wasm::WASM_EXTERNAL_TABLE:
693 encodeSLEB128(int32_t(Import.Type), getStream());
694 encodeULEB128(0, getStream()); // flags
695 encodeULEB128(NumElements, getStream()); // initial
696 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000697 default:
698 llvm_unreachable("unsupported import kind");
699 }
700 }
701
702 endSection(Section);
703}
704
Sam Clegg457fb0b2017-09-15 19:50:44 +0000705void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000706 if (Functions.empty())
707 return;
708
709 SectionBookkeeping Section;
710 startSection(Section, wasm::WASM_SEC_FUNCTION);
711
712 encodeULEB128(Functions.size(), getStream());
713 for (const WasmFunction &Func : Functions)
714 encodeULEB128(Func.Type, getStream());
715
716 endSection(Section);
717}
718
Sam Clegg7c395942017-09-14 23:07:53 +0000719void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000720 if (Globals.empty())
721 return;
722
723 SectionBookkeeping Section;
724 startSection(Section, wasm::WASM_SEC_GLOBAL);
725
726 encodeULEB128(Globals.size(), getStream());
727 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000728 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
729 write8(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000730
Sam Clegg6e7f1822018-01-31 19:50:14 +0000731 write8(wasm::WASM_OPCODE_I32_CONST);
732 encodeSLEB128(Global.InitialValue, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000733 write8(wasm::WASM_OPCODE_END);
734 }
735
736 endSection(Section);
737}
738
Sam Clegg457fb0b2017-09-15 19:50:44 +0000739void WasmObjectWriter::writeExportSection(ArrayRef<WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000740 if (Exports.empty())
741 return;
742
743 SectionBookkeeping Section;
744 startSection(Section, wasm::WASM_SEC_EXPORT);
745
746 encodeULEB128(Exports.size(), getStream());
747 for (const WasmExport &Export : Exports) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000748 writeString(Export.FieldName);
Sam Clegg9e15f352017-06-03 02:01:24 +0000749 encodeSLEB128(Export.Kind, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 encodeULEB128(Export.Index, getStream());
751 }
752
753 endSection(Section);
754}
755
Sam Clegg457fb0b2017-09-15 19:50:44 +0000756void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000757 if (TableElems.empty())
758 return;
759
760 SectionBookkeeping Section;
761 startSection(Section, wasm::WASM_SEC_ELEM);
762
763 encodeULEB128(1, getStream()); // number of "segments"
764 encodeULEB128(0, getStream()); // the table index
765
766 // init expr for starting offset
767 write8(wasm::WASM_OPCODE_I32_CONST);
Sam Clegg30e1bbc2018-01-19 18:57:01 +0000768 encodeSLEB128(kInitialTableOffset, getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000769 write8(wasm::WASM_OPCODE_END);
770
771 encodeULEB128(TableElems.size(), getStream());
772 for (uint32_t Elem : TableElems)
773 encodeULEB128(Elem, getStream());
774
775 endSection(Section);
776}
777
Sam Clegg457fb0b2017-09-15 19:50:44 +0000778void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
779 const MCAsmLayout &Layout,
780 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000781 if (Functions.empty())
782 return;
783
784 SectionBookkeeping Section;
785 startSection(Section, wasm::WASM_SEC_CODE);
786
787 encodeULEB128(Functions.size(), getStream());
788
789 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000790 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000791
Sam Clegg9e15f352017-06-03 02:01:24 +0000792 int64_t Size = 0;
793 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
794 report_fatal_error(".size expression must be evaluatable");
795
796 encodeULEB128(Size, getStream());
Sam Cleggfe6414b2017-06-21 23:46:41 +0000797 FuncSection.setSectionOffset(getStream().tell() - Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000798 Asm.writeSectionData(&FuncSection, Layout);
799 }
800
Sam Clegg9e15f352017-06-03 02:01:24 +0000801 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000802 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000803
804 endSection(Section);
805}
806
Sam Clegg457fb0b2017-09-15 19:50:44 +0000807void WasmObjectWriter::writeDataSection(ArrayRef<WasmDataSegment> Segments) {
Sam Clegg7c395942017-09-14 23:07:53 +0000808 if (Segments.empty())
809 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000810
811 SectionBookkeeping Section;
812 startSection(Section, wasm::WASM_SEC_DATA);
813
Sam Clegg7c395942017-09-14 23:07:53 +0000814 encodeULEB128(Segments.size(), getStream()); // count
815
816 for (const WasmDataSegment & Segment : Segments) {
817 encodeULEB128(0, getStream()); // memory index
818 write8(wasm::WASM_OPCODE_I32_CONST);
819 encodeSLEB128(Segment.Offset, getStream()); // offset
820 write8(wasm::WASM_OPCODE_END);
821 encodeULEB128(Segment.Data.size(), getStream()); // size
822 Segment.Section->setSectionOffset(getStream().tell() - Section.ContentsOffset);
823 writeBytes(Segment.Data); // data
824 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000825
826 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000827 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000828
829 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000830}
831
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000832void WasmObjectWriter::writeCodeRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000833 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
834 // for descriptions of the reloc sections.
835
836 if (CodeRelocations.empty())
837 return;
838
839 SectionBookkeeping Section;
840 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE");
841
842 encodeULEB128(wasm::WASM_SEC_CODE, getStream());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000843 encodeULEB128(CodeRelocations.size(), getStream());
Sam Clegg9e15f352017-06-03 02:01:24 +0000844
Sam Clegg7c395942017-09-14 23:07:53 +0000845 writeRelocations(CodeRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000846
847 endSection(Section);
848}
849
Sam Clegg7c395942017-09-14 23:07:53 +0000850void WasmObjectWriter::writeDataRelocSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000851 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
852 // for descriptions of the reloc sections.
853
854 if (DataRelocations.empty())
855 return;
856
857 SectionBookkeeping Section;
858 startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA");
859
860 encodeULEB128(wasm::WASM_SEC_DATA, getStream());
861 encodeULEB128(DataRelocations.size(), getStream());
862
Sam Clegg7c395942017-09-14 23:07:53 +0000863 writeRelocations(DataRelocations);
Sam Clegg9e15f352017-06-03 02:01:24 +0000864
865 endSection(Section);
866}
867
868void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Cleggd95ed952017-09-20 19:03:35 +0000869 ArrayRef<WasmDataSegment> Segments, uint32_t DataSize,
Sam Cleggea7cace2018-01-09 23:43:14 +0000870 ArrayRef<std::pair<StringRef, uint32_t>> SymbolFlags,
871 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
872 const std::map<StringRef, std::vector<WasmComdatEntry>>& Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000873 SectionBookkeeping Section;
874 startSection(Section, wasm::WASM_SEC_CUSTOM, "linking");
Sam Cleggb7787fd2017-06-20 04:04:59 +0000875 SectionBookkeeping SubSection;
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
Sam Clegg31a2c802017-09-20 21:17:04 +0000877 if (SymbolFlags.size() != 0) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000878 startSection(SubSection, wasm::WASM_SYMBOL_INFO);
Sam Clegg31a2c802017-09-20 21:17:04 +0000879 encodeULEB128(SymbolFlags.size(), getStream());
880 for (auto Pair: SymbolFlags) {
881 writeString(Pair.first);
882 encodeULEB128(Pair.second, getStream());
Sam Cleggb7787fd2017-06-20 04:04:59 +0000883 }
884 endSection(SubSection);
885 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
Sam Clegg9e1ade92017-06-27 20:27:59 +0000887 if (DataSize > 0) {
888 startSection(SubSection, wasm::WASM_DATA_SIZE);
889 encodeULEB128(DataSize, getStream());
890 endSection(SubSection);
Sam Clegg9e1ade92017-06-27 20:27:59 +0000891 }
892
Sam Cleggd95ed952017-09-20 19:03:35 +0000893 if (Segments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000894 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Sam Cleggd95ed952017-09-20 19:03:35 +0000895 encodeULEB128(Segments.size(), getStream());
Sam Clegg63ebb812017-09-29 16:50:08 +0000896 for (const WasmDataSegment &Segment : Segments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000897 writeString(Segment.Name);
Sam Clegg63ebb812017-09-29 16:50:08 +0000898 encodeULEB128(Segment.Alignment, getStream());
899 encodeULEB128(Segment.Flags, getStream());
900 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000901 endSection(SubSection);
902 }
903
Sam Cleggbafe6902017-12-15 00:17:10 +0000904 if (!InitFuncs.empty()) {
905 startSection(SubSection, wasm::WASM_INIT_FUNCS);
906 encodeULEB128(InitFuncs.size(), getStream());
907 for (auto &StartFunc : InitFuncs) {
908 encodeULEB128(StartFunc.first, getStream()); // priority
909 encodeULEB128(StartFunc.second, getStream()); // function index
910 }
911 endSection(SubSection);
912 }
913
Sam Cleggea7cace2018-01-09 23:43:14 +0000914 if (Comdats.size()) {
915 startSection(SubSection, wasm::WASM_COMDAT_INFO);
916 encodeULEB128(Comdats.size(), getStream());
917 for (const auto &C : Comdats) {
918 writeString(C.first);
919 encodeULEB128(0, getStream()); // flags for future use
920 encodeULEB128(C.second.size(), getStream());
921 for (const WasmComdatEntry &Entry : C.second) {
922 encodeULEB128(Entry.Kind, getStream());
923 encodeULEB128(Entry.Index, getStream());
924 }
925 }
926 endSection(SubSection);
927 }
928
Sam Clegg9e15f352017-06-03 02:01:24 +0000929 endSection(Section);
930}
931
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000932uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
933 assert(Symbol.isFunction());
934 assert(TypeIndices.count(&Symbol));
935 return TypeIndices[&Symbol];
936}
937
938uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
939 assert(Symbol.isFunction());
940
941 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000942 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
943 F.Returns = ResolvedSym->getReturns();
944 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000945
946 auto Pair =
947 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
948 if (Pair.second)
949 FunctionTypes.push_back(F);
950 TypeIndices[&Symbol] = Pair.first->second;
951
952 DEBUG(dbgs() << "registerFunctionType: " << Symbol << " new:" << Pair.second << "\n");
953 DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
954 return Pair.first->second;
955}
956
Dan Gohman18eafb62017-02-22 01:23:18 +0000957void WasmObjectWriter::writeObject(MCAssembler &Asm,
958 const MCAsmLayout &Layout) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000959 DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +0000960 MCContext &Ctx = Asm.getContext();
Sam Clegg6e7f1822018-01-31 19:50:14 +0000961 int32_t PtrType = is64Bit() ? wasm::WASM_TYPE_I64 : wasm::WASM_TYPE_I32;
Dan Gohmand934cb82017-02-24 23:18:00 +0000962
963 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +0000964 SmallVector<WasmFunction, 4> Functions;
965 SmallVector<uint32_t, 4> TableElems;
Dan Gohmand934cb82017-02-24 23:18:00 +0000966 SmallVector<WasmImport, 4> Imports;
967 SmallVector<WasmExport, 4> Exports;
Sam Clegg31a2c802017-09-20 21:17:04 +0000968 SmallVector<std::pair<StringRef, uint32_t>, 4> SymbolFlags;
Sam Cleggbafe6902017-12-15 00:17:10 +0000969 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +0000970 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +0000971 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg7c395942017-09-14 23:07:53 +0000972 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000973
Sam Cleggf950b242017-12-11 23:03:38 +0000974 // For now, always emit the memory import, since loads and stores are not
975 // valid without it. In the future, we could perhaps be more clever and omit
976 // it if there are no loads or stores.
977 MCSymbolWasm *MemorySym =
978 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
979 WasmImport MemImport;
980 MemImport.ModuleName = MemorySym->getModuleName();
981 MemImport.FieldName = MemorySym->getName();
982 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
983 Imports.push_back(MemImport);
984
985 // For now, always emit the table section, since indirect calls are not
986 // valid without it. In the future, we could perhaps be more clever and omit
987 // it if there are no indirect calls.
988 MCSymbolWasm *TableSym =
989 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
990 WasmImport TableImport;
991 TableImport.ModuleName = TableSym->getModuleName();
992 TableImport.FieldName = TableSym->getName();
993 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
994 TableImport.Type = wasm::WASM_TYPE_ANYFUNC;
995 Imports.push_back(TableImport);
996
Dan Gohman32ce5ca2017-12-05 18:29:48 +0000997 // Populate FunctionTypeIndices and Imports.
998 for (const MCSymbol &S : Asm.symbols()) {
999 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1000
1001 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001002 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001003 if (WS.isFunction())
1004 registerFunctionType(WS);
1005
1006 if (WS.isTemporary())
1007 continue;
1008
1009 // If the symbol is not defined in this translation unit, import it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001010 if ((!WS.isDefined() && !WS.isComdat()) ||
Sam Cleggd423f0d2018-01-11 20:35:17 +00001011 WS.isVariable()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001012 WasmImport Import;
1013 Import.ModuleName = WS.getModuleName();
1014 Import.FieldName = WS.getName();
1015
1016 if (WS.isFunction()) {
1017 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1018 Import.Type = getFunctionType(WS);
Sam Clegg9f3fe422018-01-17 19:28:43 +00001019 SymbolIndices[&WS] = NumFunctionImports;
1020 ++NumFunctionImports;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001021 } else {
1022 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6e7f1822018-01-31 19:50:14 +00001023 Import.Type = PtrType;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001024 Import.IsMutable = false;
1025 SymbolIndices[&WS] = NumGlobalImports;
1026
Dan Gohman83b16222017-12-20 00:10:28 +00001027 // If this global is the stack pointer, make it mutable.
Dan Gohmanad19047d2017-12-06 20:56:40 +00001028 if (WS.getName() == "__stack_pointer")
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001029 Import.IsMutable = true;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001030
1031 ++NumGlobalImports;
1032 }
1033
1034 Imports.push_back(Import);
1035 }
1036 }
1037
Sam Clegg759631c2017-09-15 20:54:59 +00001038 for (MCSection &Sec : Asm) {
1039 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg12fd3da2017-10-20 21:28:38 +00001040 if (!Section.isWasmData())
Sam Clegg759631c2017-09-15 20:54:59 +00001041 continue;
1042
Sam Cleggbafe6902017-12-15 00:17:10 +00001043 // .init_array sections are handled specially elsewhere.
1044 if (cast<MCSectionWasm>(Sec).getSectionName().startswith(".init_array"))
1045 continue;
1046
Sam Clegg329e76d2018-01-31 04:21:44 +00001047 uint32_t SegmentIndex = DataSegments.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001048 DataSize = alignTo(DataSize, Section.getAlignment());
1049 DataSegments.emplace_back();
1050 WasmDataSegment &Segment = DataSegments.back();
Sam Cleggd95ed952017-09-20 19:03:35 +00001051 Segment.Name = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001052 Segment.Offset = DataSize;
1053 Segment.Section = &Section;
Sam Clegg63ebb812017-09-29 16:50:08 +00001054 addData(Segment.Data, Section);
1055 Segment.Alignment = Section.getAlignment();
1056 Segment.Flags = 0;
Sam Clegg759631c2017-09-15 20:54:59 +00001057 DataSize += Segment.Data.size();
1058 Section.setMemoryOffset(Segment.Offset);
Sam Cleggea7cace2018-01-09 23:43:14 +00001059
1060 if (const MCSymbolWasm *C = Section.getGroup()) {
1061 Comdats[C->getName()].emplace_back(
Sam Clegg329e76d2018-01-31 04:21:44 +00001062 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
Sam Cleggea7cace2018-01-09 23:43:14 +00001063 }
Sam Clegg759631c2017-09-15 20:54:59 +00001064 }
1065
Sam Cleggb7787fd2017-06-20 04:04:59 +00001066 // Handle regular defined and undefined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001067 for (const MCSymbol &S : Asm.symbols()) {
1068 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1069 // or used in relocations.
1070 if (S.isTemporary() && S.getName().empty())
1071 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001072
Dan Gohmand934cb82017-02-24 23:18:00 +00001073 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001074 DEBUG(dbgs() << "MCSymbol: '" << S << "'"
Sam Clegg329e76d2018-01-31 04:21:44 +00001075 << " isDefined=" << S.isDefined()
1076 << " isExternal=" << S.isExternal()
1077 << " isTemporary=" << S.isTemporary()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001078 << " isFunction=" << WS.isFunction()
1079 << " isWeak=" << WS.isWeak()
Sam Clegga2b35da2017-12-03 01:19:23 +00001080 << " isHidden=" << WS.isHidden()
Sam Cleggb7787fd2017-06-20 04:04:59 +00001081 << " isVariable=" << WS.isVariable() << "\n");
1082
Sam Clegga2b35da2017-12-03 01:19:23 +00001083 if (WS.isWeak() || WS.isHidden()) {
1084 uint32_t Flags = (WS.isWeak() ? wasm::WASM_SYMBOL_BINDING_WEAK : 0) |
1085 (WS.isHidden() ? wasm::WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
1086 SymbolFlags.emplace_back(WS.getName(), Flags);
1087 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001088
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001089 if (WS.isVariable())
1090 continue;
1091
Dan Gohmand934cb82017-02-24 23:18:00 +00001092 unsigned Index;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001093
Dan Gohmand934cb82017-02-24 23:18:00 +00001094 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001095 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001096 if (WS.getOffset() != 0)
1097 report_fatal_error(
1098 "function sections must contain one function each");
1099
1100 if (WS.getSize() == 0)
1101 report_fatal_error(
1102 "function symbols must have a size set with .size");
1103
Dan Gohmand934cb82017-02-24 23:18:00 +00001104 // A definition. Take the next available index.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001105 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001106
1107 // Prepare the function.
1108 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001109 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001110 Func.Sym = &WS;
1111 SymbolIndices[&WS] = Index;
1112 Functions.push_back(Func);
1113 } else {
1114 // An import; the index was assigned above.
1115 Index = SymbolIndices.find(&WS)->second;
1116 }
1117
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001118 DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6006e092017-12-22 20:31:39 +00001119 } else {
Sam Cleggc38e9472017-06-02 01:05:24 +00001120 if (WS.isTemporary() && !WS.getSize())
1121 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001122
Sam Cleggcd65f692018-01-11 23:59:16 +00001123 if (!WS.isDefined())
Sam Cleggfe6414b2017-06-21 23:46:41 +00001124 continue;
Sam Cleggc38e9472017-06-02 01:05:24 +00001125
Sam Cleggfe6414b2017-06-21 23:46:41 +00001126 if (!WS.getSize())
1127 report_fatal_error("data symbols must have a size set with .size: " +
1128 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001129
Sam Cleggfe6414b2017-06-21 23:46:41 +00001130 int64_t Size = 0;
1131 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1132 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001133
Sam Clegg7c395942017-09-14 23:07:53 +00001134 // For each global, prepare a corresponding wasm global holding its
1135 // address. For externals these will also be named exports.
1136 Index = NumGlobalImports + Globals.size();
Sam Clegg759631c2017-09-15 20:54:59 +00001137 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001138 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001139
1140 WasmGlobal Global;
Sam Clegg6e7f1822018-01-31 19:50:14 +00001141 Global.Type.Type = PtrType;
1142 Global.Type.Mutable = false;
Sam Clegg759631c2017-09-15 20:54:59 +00001143 Global.InitialValue = DataSection.getMemoryOffset() + Layout.getSymbolOffset(WS);
Sam Clegg7c395942017-09-14 23:07:53 +00001144 SymbolIndices[&WS] = Index;
1145 DEBUG(dbgs() << " -> global index: " << Index << "\n");
1146 Globals.push_back(Global);
Dan Gohmand934cb82017-02-24 23:18:00 +00001147 }
1148
1149 // If the symbol is visible outside this translation unit, export it.
Sam Cleggcd65f692018-01-11 23:59:16 +00001150 if (WS.isDefined()) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001151 WasmExport Export;
1152 Export.FieldName = WS.getName();
1153 Export.Index = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001154 if (WS.isFunction())
1155 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1156 else
1157 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001158 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001159 Exports.push_back(Export);
Sam Cleggea7cace2018-01-09 23:43:14 +00001160
Sam Clegg31a2c802017-09-20 21:17:04 +00001161 if (!WS.isExternal())
1162 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggea7cace2018-01-09 23:43:14 +00001163
1164 if (WS.isFunction()) {
Sam Cleggcd65f692018-01-11 23:59:16 +00001165 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001166 if (const MCSymbolWasm *C = Section.getGroup())
1167 Comdats[C->getName()].emplace_back(
1168 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1169 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001170 }
1171 }
1172
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001173 // Handle weak aliases. We need to process these in a separate pass because
1174 // we need to have processed the target of the alias before the alias itself
1175 // and the symbols are not necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001176 for (const MCSymbol &S : Asm.symbols()) {
1177 if (!S.isVariable())
1178 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001179
Sam Cleggcd65f692018-01-11 23:59:16 +00001180 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001181
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001182 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001183 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1184 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001185 DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym << "'\n");
1186 assert(SymbolIndices.count(ResolvedSym) > 0);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001187 uint32_t Index = SymbolIndices.find(ResolvedSym)->second;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001188 DEBUG(dbgs() << " -> index:" << Index << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001189
1190 WasmExport Export;
1191 Export.FieldName = WS.getName();
1192 Export.Index = Index;
1193 if (WS.isFunction())
1194 Export.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1195 else
1196 Export.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001197 DEBUG(dbgs() << " -> export " << Exports.size() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001198 Exports.push_back(Export);
Sam Clegg31a2c802017-09-20 21:17:04 +00001199
1200 if (!WS.isExternal())
1201 SymbolFlags.emplace_back(WS.getName(), wasm::WASM_SYMBOL_BINDING_LOCAL);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001202 }
1203
Sam Clegg6006e092017-12-22 20:31:39 +00001204 {
1205 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001206 // Functions referenced by a relocation need to put in the table. This is
1207 // purely to make the object file's provisional values readable, and is
1208 // ignored by the linker, which re-calculates the relocations itself.
1209 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1210 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1211 return;
1212 assert(Rel.Symbol->isFunction());
1213 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
1214 uint32_t SymbolIndex = SymbolIndices.find(&WS)->second;
1215 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1216 if (TableIndices.try_emplace(&WS, TableIndex).second) {
1217 DEBUG(dbgs() << " -> adding " << WS.getName()
1218 << " to table: " << TableIndex << "\n");
1219 TableElems.push_back(SymbolIndex);
1220 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001221 }
1222 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001223
Sam Clegg6006e092017-12-22 20:31:39 +00001224 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1225 HandleReloc(RelEntry);
1226 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1227 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001228 }
1229
Sam Cleggbafe6902017-12-15 00:17:10 +00001230 // Translate .init_array section contents into start functions.
1231 for (const MCSection &S : Asm) {
1232 const auto &WS = static_cast<const MCSectionWasm &>(S);
1233 if (WS.getSectionName().startswith(".fini_array"))
1234 report_fatal_error(".fini_array sections are unsupported");
1235 if (!WS.getSectionName().startswith(".init_array"))
1236 continue;
1237 if (WS.getFragmentList().empty())
1238 continue;
1239 if (WS.getFragmentList().size() != 2)
1240 report_fatal_error("only one .init_array section fragment supported");
1241 const MCFragment &AlignFrag = *WS.begin();
1242 if (AlignFrag.getKind() != MCFragment::FT_Align)
1243 report_fatal_error(".init_array section should be aligned");
1244 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1245 report_fatal_error(".init_array section should be aligned for pointers");
1246 const MCFragment &Frag = *std::next(WS.begin());
1247 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1248 report_fatal_error("only data supported in .init_array section");
1249 uint16_t Priority = UINT16_MAX;
1250 if (WS.getSectionName().size() != 11) {
1251 if (WS.getSectionName()[11] != '.')
1252 report_fatal_error(".init_array section priority should start with '.'");
1253 if (WS.getSectionName().substr(12).getAsInteger(10, Priority))
1254 report_fatal_error("invalid .init_array section priority");
1255 }
1256 const auto &DataFrag = cast<MCDataFragment>(Frag);
1257 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1258 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1259 *end = (const uint8_t *)Contents.data() + Contents.size();
1260 p != end; ++p) {
1261 if (*p != 0)
1262 report_fatal_error("non-symbolic data in .init_array section");
1263 }
1264 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1265 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1266 const MCExpr *Expr = Fixup.getValue();
1267 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1268 if (!Sym)
1269 report_fatal_error("fixups in .init_array should be symbol references");
1270 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1271 report_fatal_error("symbols in .init_array should be for functions");
1272 auto I = SymbolIndices.find(cast<MCSymbolWasm>(&Sym->getSymbol()));
1273 if (I == SymbolIndices.end())
1274 report_fatal_error("symbols in .init_array should be defined");
1275 uint32_t Index = I->second;
1276 InitFuncs.push_back(std::make_pair(Priority, Index));
1277 }
1278 }
1279
Dan Gohman18eafb62017-02-22 01:23:18 +00001280 // Write out the Wasm header.
1281 writeHeader(Asm);
1282
Sam Clegg9e15f352017-06-03 02:01:24 +00001283 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001284 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001285 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001286 // Skip the "table" section; we import the table instead.
1287 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001288 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001289 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001290 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001291 writeCodeSection(Asm, Layout, Functions);
Sam Clegg7c395942017-09-14 23:07:53 +00001292 writeDataSection(DataSegments);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001293 writeCodeRelocSection();
Sam Clegg7c395942017-09-14 23:07:53 +00001294 writeDataRelocSection();
Sam Cleggbafe6902017-12-15 00:17:10 +00001295 writeLinkingMetaDataSection(DataSegments, DataSize, SymbolFlags,
Sam Cleggea7cace2018-01-09 23:43:14 +00001296 InitFuncs, Comdats);
Dan Gohman970d02c2017-03-30 23:58:19 +00001297
Dan Gohmand934cb82017-02-24 23:18:00 +00001298 // TODO: Translate the .comment section to the output.
Dan Gohmand934cb82017-02-24 23:18:00 +00001299 // TODO: Translate debug sections to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001300}
1301
Lang Hames60fbc7c2017-10-10 16:28:07 +00001302std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001303llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1304 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001305 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001306}