blob: cbb12cab71eb999b11d30049e6665b3e643cbaf5 [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"
Nico Weber432a3882018-04-30 14:59:11 +000017#include "llvm/Config/llvm-config.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000019#include "llvm/MC/MCAsmLayout.h"
20#include "llvm/MC/MCAssembler.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000024#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionWasm.h"
26#include "llvm/MC/MCSymbolWasm.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000029#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000031#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000032#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000033#include "llvm/Support/StringSaver.h"
34#include <vector>
35
36using namespace llvm;
37
Sam Clegg5e3d33a2017-07-07 02:01:29 +000038#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000039
40namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000041
Sam Clegg30e1bbc2018-01-19 18:57:01 +000042// Went we ceate the indirect function table we start at 1, so that there is
43// and emtpy slot at 0 and therefore calling a null function pointer will trap.
44static const uint32_t kInitialTableOffset = 1;
45
Dan Gohmand934cb82017-02-24 23:18:00 +000046// For patching purposes, we need to remember where each section starts, both
47// for patching up the section size field, and for patching up references to
48// locations within the section.
49struct SectionBookkeeping {
50 // Where the size of the section is written.
51 uint64_t SizeOffset;
Sam Clegg6a31a0d2018-04-26 19:27:28 +000052 // Where the section header ends (without custom section name).
53 uint64_t PayloadOffset;
54 // Where the contents of the section starts.
Dan Gohmand934cb82017-02-24 23:18:00 +000055 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000056 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000057};
58
Sam Clegg9e15f352017-06-03 02:01:24 +000059// The signature of a wasm function, in a struct capable of being used as a
60// DenseMap key.
61struct WasmFunctionType {
62 // Support empty and tombstone instances, needed by DenseMap.
63 enum { Plain, Empty, Tombstone } State;
64
65 // The return types of the function.
66 SmallVector<wasm::ValType, 1> Returns;
67
68 // The parameter types of the function.
69 SmallVector<wasm::ValType, 4> Params;
70
71 WasmFunctionType() : State(Plain) {}
72
73 bool operator==(const WasmFunctionType &Other) const {
74 return State == Other.State && Returns == Other.Returns &&
75 Params == Other.Params;
76 }
77};
78
79// Traits for using WasmFunctionType in a DenseMap.
80struct WasmFunctionTypeDenseMapInfo {
81 static WasmFunctionType getEmptyKey() {
82 WasmFunctionType FuncTy;
83 FuncTy.State = WasmFunctionType::Empty;
84 return FuncTy;
85 }
86 static WasmFunctionType getTombstoneKey() {
87 WasmFunctionType FuncTy;
88 FuncTy.State = WasmFunctionType::Tombstone;
89 return FuncTy;
90 }
91 static unsigned getHashValue(const WasmFunctionType &FuncTy) {
92 uintptr_t Value = FuncTy.State;
93 for (wasm::ValType Ret : FuncTy.Returns)
94 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret));
95 for (wasm::ValType Param : FuncTy.Params)
96 Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param));
97 return Value;
98 }
99 static bool isEqual(const WasmFunctionType &LHS,
100 const WasmFunctionType &RHS) {
101 return LHS == RHS;
102 }
103};
104
Sam Clegg7c395942017-09-14 23:07:53 +0000105// A wasm data segment. A wasm binary contains only a single data section
106// but that can contain many segments, each with their own virtual location
107// in memory. Each MCSection data created by llvm is modeled as its own
108// wasm data segment.
109struct WasmDataSegment {
110 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000111 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000112 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000113 uint32_t Alignment;
114 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000115 SmallVector<char, 4> Data;
116};
117
Sam Clegg9e15f352017-06-03 02:01:24 +0000118// A wasm function to be written into the function section.
119struct WasmFunction {
120 int32_t Type;
121 const MCSymbolWasm *Sym;
122};
123
Sam Clegg9e15f352017-06-03 02:01:24 +0000124// A wasm global to be written into the global section.
125struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000126 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000127 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000128};
129
Sam Cleggea7cace2018-01-09 23:43:14 +0000130// Information about a single item which is part of a COMDAT. For each data
131// segment or function which is in the COMDAT, there is a corresponding
132// WasmComdatEntry.
133struct WasmComdatEntry {
134 unsigned Kind;
135 uint32_t Index;
136};
137
Sam Clegg6dc65e92017-06-06 16:38:59 +0000138// Information about a single relocation.
139struct WasmRelocationEntry {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000140 uint64_t Offset; // Where is the relocation.
141 const MCSymbolWasm *Symbol; // The symbol to relocate with.
142 int64_t Addend; // A value to add to the symbol.
143 unsigned Type; // The type of the relocation.
144 const MCSectionWasm *FixupSection;// The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000145
146 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
147 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000148 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000149 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
150 FixupSection(FixupSection) {}
151
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000152 bool hasAddend() const {
153 switch (Type) {
Sam Clegg13a2e892017-09-01 17:32:01 +0000154 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
155 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
156 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000157 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
158 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000159 return true;
160 default:
161 return false;
162 }
163 }
164
Sam Clegg6dc65e92017-06-06 16:38:59 +0000165 void print(raw_ostream &Out) const {
Sam Clegg5f87ab32018-05-14 22:42:07 +0000166 Out << wasm::relocTypetoString(Type)
Sam Clegga165f2d2018-04-30 19:40:57 +0000167 << " Off=" << Offset << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000168 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000169 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000170
Aaron Ballman615eb472017-10-15 14:32:27 +0000171#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000172 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
173#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000174};
175
Sam Clegg25d8e682018-05-08 00:08:21 +0000176static const uint32_t INVALID_INDEX = -1;
177
Sam Cleggcfd44a22018-04-05 17:01:39 +0000178struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000179
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000180 StringRef Name;
181 MCSectionWasm *Section;
182
183 uint32_t OutputContentsOffset;
184 uint32_t OutputIndex;
185
186 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
187 : Name(Name), Section(Section), OutputContentsOffset(0),
188 OutputIndex(INVALID_INDEX) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000189};
190
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000191#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000192raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000193 Rel.print(OS);
194 return OS;
195}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000196#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000197
Dan Gohman18eafb62017-02-22 01:23:18 +0000198class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000199 support::endian::Writer W;
200
Dan Gohman18eafb62017-02-22 01:23:18 +0000201 /// The target specific Wasm writer instance.
202 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
203
Dan Gohmand934cb82017-02-24 23:18:00 +0000204 // Relocations for fixing up references in the code section.
205 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000206 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000207
208 // Relocations for fixing up references in the data section.
209 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000210 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000211
Dan Gohmand934cb82017-02-24 23:18:00 +0000212 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000213 // Maps function symbols to the index of the type of the function
214 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000215 // Maps function symbols to the table element index space. Used
216 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000217 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Sam Clegga165f2d2018-04-30 19:40:57 +0000218 // Maps function/global symbols to the function/global/section index space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000219 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
220 // Maps data symbols to the Wasm segment and offset/size with the segment.
221 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000222
223 // Stores output data (index, relocations, content offset) for custom
224 // section.
225 std::vector<WasmCustomSection> CustomSections;
226 // Relocations for fixing up references in the custom sections.
227 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
228 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000229
Sam Cleggc0d41192018-05-17 17:15:15 +0000230 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000231 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
232
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000233 DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo>
234 FunctionTypeIndices;
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000235 SmallVector<WasmFunctionType, 4> FunctionTypes;
Sam Clegg7c395942017-09-14 23:07:53 +0000236 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000237 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000238 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000239 unsigned NumGlobalImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000240 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000241
Dan Gohman18eafb62017-02-22 01:23:18 +0000242 // TargetObjectWriter wrappers.
243 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000244 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
245 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000246 }
247
Sam Clegg2322a932018-04-23 19:16:19 +0000248 void startSection(SectionBookkeeping &Section, unsigned SectionId);
249 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000250 void endSection(SectionBookkeeping &Section);
251
Dan Gohman18eafb62017-02-22 01:23:18 +0000252public:
Lang Hames1301a872017-10-10 01:15:10 +0000253 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
254 raw_pwrite_stream &OS)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000255 : MCObjectWriter(OS, /*IsLittleEndian=*/true), W(OS, support::little),
Lang Hames1301a872017-10-10 01:15:10 +0000256 TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000257
Dan Gohman18eafb62017-02-22 01:23:18 +0000258 ~WasmObjectWriter() override;
259
Dan Gohman0917c9e2018-01-15 17:06:23 +0000260private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000261 void reset() override {
262 CodeRelocations.clear();
263 DataRelocations.clear();
264 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000265 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000266 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000267 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000268 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000269 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000270 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000271 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000272 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000273 SectionFunctions.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000274 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000275 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000276 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000277 }
278
Dan Gohman18eafb62017-02-22 01:23:18 +0000279 void writeHeader(const MCAssembler &Asm);
280
281 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
282 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000283 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000284
285 void executePostLayoutBinding(MCAssembler &Asm,
286 const MCAsmLayout &Layout) override;
287
288 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000289
Sam Cleggb7787fd2017-06-20 04:04:59 +0000290 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000291 encodeULEB128(Str.size(), W.OS);
292 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000293 }
294
Sam Clegg9e15f352017-06-03 02:01:24 +0000295 void writeValueType(wasm::ValType Ty) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000296 W.OS << static_cast<char>(Ty);
Sam Clegg9e15f352017-06-03 02:01:24 +0000297 }
298
Sam Clegg457fb0b2017-09-15 19:50:44 +0000299 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000300 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000301 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000302 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000303 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000304 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000305 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000306 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000307 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000308 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000309 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
310 ArrayRef<WasmRelocationEntry> Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000311 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000312 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000313 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000314 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000315 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
316 void writeCustomRelocSections();
317 void
318 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
319 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000320
Sam Clegg7c395942017-09-14 23:07:53 +0000321 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000322 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
323 uint64_t ContentsOffset);
324
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000325 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000326 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
327 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000328};
Sam Clegg9e15f352017-06-03 02:01:24 +0000329
Dan Gohman18eafb62017-02-22 01:23:18 +0000330} // end anonymous namespace
331
332WasmObjectWriter::~WasmObjectWriter() {}
333
Dan Gohmand934cb82017-02-24 23:18:00 +0000334// Write out a section header and a patchable section size field.
335void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000336 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000337 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000338 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000339
Peter Collingbournef17b1492018-05-21 18:17:42 +0000340 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000341
342 // The section size. We don't know the size yet, so reserve enough space
343 // for any 32-bit value; we'll patch it later.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000344 encodeULEB128(UINT32_MAX, W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000345
346 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000347 Section.ContentsOffset = W.OS.tell();
348 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000349 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000350}
Dan Gohmand934cb82017-02-24 23:18:00 +0000351
Sam Clegg2322a932018-04-23 19:16:19 +0000352void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
353 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000354 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000355 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000356
357 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000358 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000359
Dan Gohmand934cb82017-02-24 23:18:00 +0000360 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000361 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000362
363 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000364 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000365}
366
367// Now that the section is complete and we know how big it is, patch up the
368// section size field at the start of the section.
369void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000370 uint64_t Size = W.OS.tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000371 if (uint32_t(Size) != Size)
372 report_fatal_error("section size does not fit in a uint32_t");
373
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000374 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000375
376 // Write the final section size to the payload_len field, which follows
377 // the section id byte.
378 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000379 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000380 assert(SizeLen == 5);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000381 static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
382 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000383}
384
Dan Gohman18eafb62017-02-22 01:23:18 +0000385// Emit the Wasm header.
386void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000387 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
388 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000389}
390
391void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
392 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000393 // Build a map of sections to the function that defines them, for use
394 // in recordRelocation.
395 for (const MCSymbol &S : Asm.symbols()) {
396 const auto &WS = static_cast<const MCSymbolWasm &>(S);
397 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
398 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
399 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
400 if (!Pair.second)
401 report_fatal_error("section already has a defining function: " +
402 Sec.getSectionName());
403 }
404 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000405}
406
407void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
408 const MCAsmLayout &Layout,
409 const MCFragment *Fragment,
410 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000411 uint64_t &FixedValue) {
412 MCAsmBackend &Backend = Asm.getBackend();
413 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
414 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000415 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000416 uint64_t C = Target.getConstant();
417 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
418 MCContext &Ctx = Asm.getContext();
419
Sam Cleggbafe6902017-12-15 00:17:10 +0000420 // The .init_array isn't translated as data, so don't do relocations in it.
421 if (FixupSection.getSectionName().startswith(".init_array"))
422 return;
423
Dan Gohmand934cb82017-02-24 23:18:00 +0000424 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
425 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
426 "Should not have constructed this");
427
428 // Let A, B and C being the components of Target and R be the location of
429 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
430 // If it is pcrel, we want to compute (A - B + C - R).
431
432 // In general, Wasm has no relocations for -B. It can only represent (A + C)
433 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
434 // replace B to implement it: (A - R - K + C)
435 if (IsPCRel) {
436 Ctx.reportError(
437 Fixup.getLoc(),
438 "No relocation available to represent this relative expression");
439 return;
440 }
441
442 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
443
444 if (SymB.isUndefined()) {
445 Ctx.reportError(Fixup.getLoc(),
446 Twine("symbol '") + SymB.getName() +
447 "' can not be undefined in a subtraction expression");
448 return;
449 }
450
451 assert(!SymB.isAbsolute() && "Should have been folded");
452 const MCSection &SecB = SymB.getSection();
453 if (&SecB != &FixupSection) {
454 Ctx.reportError(Fixup.getLoc(),
455 "Cannot represent a difference across sections");
456 return;
457 }
458
459 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
460 uint64_t K = SymBOffset - FixupOffset;
461 IsPCRel = true;
462 C -= K;
463 }
464
465 // We either rejected the fixup or folded B into C at this point.
466 const MCSymbolRefExpr *RefA = Target.getSymA();
467 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
468
Dan Gohmand934cb82017-02-24 23:18:00 +0000469 if (SymA && SymA->isVariable()) {
470 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000471 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
472 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
473 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000474 }
475
476 // Put any constant offset in an addend. Offsets can be negative, and
477 // LLVM expects wrapping, in contrast to wasm's immediates which can't
478 // be negative and don't wrap.
479 FixedValue = 0;
480
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000481 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000482 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000483 assert(SymA);
484
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000485 // Absolute offset within a section or a function.
486 // Currently only supported for for metadata sections.
487 // See: test/MC/WebAssembly/blockaddress.ll
488 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
489 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
490 if (!FixupSection.getKind().isMetadata())
491 report_fatal_error("relocations for function or section offsets are "
492 "only supported in metadata sections");
493
494 const MCSymbol *SectionSymbol = nullptr;
495 const MCSection &SecA = SymA->getSection();
496 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000497 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000498 else
499 SectionSymbol = SecA.getBeginSymbol();
500 if (!SectionSymbol)
501 report_fatal_error("section symbol is required for relocation");
502
503 C += Layout.getSymbolOffset(*SymA);
504 SymA = cast<MCSymbolWasm>(SectionSymbol);
505 }
506
507 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
508 // against a named symbol.
509 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
510 if (SymA->getName().empty())
511 report_fatal_error("relocations against un-named temporaries are not yet "
512 "supported by wasm");
513
514 SymA->setUsedInReloc();
515 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000516
Dan Gohmand934cb82017-02-24 23:18:00 +0000517 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000518 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000519
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000520 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000521 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000522 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000523 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000524 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000525 CustomSectionsRelocations[&FixupSection].push_back(Rec);
526 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000527 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000528 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000529}
530
Dan Gohmand934cb82017-02-24 23:18:00 +0000531// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
532// to allow patching.
533static void
534WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
535 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000536 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000537 assert(SizeLen == 5);
538 Stream.pwrite((char *)Buffer, SizeLen, Offset);
539}
540
541// Write X as an signed LEB value at offset Offset in Stream, padded
542// to allow patching.
543static void
544WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
545 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000546 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000547 assert(SizeLen == 5);
548 Stream.pwrite((char *)Buffer, SizeLen, Offset);
549}
550
551// Write X as a plain integer value at offset Offset in Stream.
552static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
553 uint8_t Buffer[4];
554 support::endian::write32le(Buffer, X);
555 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
556}
557
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000558static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
559 if (Symbol.isVariable()) {
560 const MCExpr *Expr = Symbol.getVariableValue();
561 auto *Inner = cast<MCSymbolRefExpr>(Expr);
562 return cast<MCSymbolWasm>(&Inner->getSymbol());
563 }
564 return &Symbol;
565}
566
Dan Gohmand934cb82017-02-24 23:18:00 +0000567// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000568// by RelEntry. This value isn't used by the static linker; it just serves
569// to make the object format more readable and more likely to be directly
570// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000571uint32_t
572WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000573 switch (RelEntry.Type) {
574 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000575 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
576 // Provisional value is table address of the resolved symbol itself
577 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
578 assert(Sym->isFunction());
579 return TableIndices[Sym];
580 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000581 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000582 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000583 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000584 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
585 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
586 // Provisional value is function/global Wasm index
587 if (!WasmIndices.count(RelEntry.Symbol))
588 report_fatal_error("symbol not found in wasm index space: " +
589 RelEntry.Symbol->getName());
590 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000591 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
592 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000593 const auto &Section =
594 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
595 return Section.getSectionOffset() + RelEntry.Addend;
596 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000597 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
598 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
599 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000600 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000601 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
602 // For undefined symbols, use zero
603 if (!Sym->isDefined())
604 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000605 const wasm::WasmDataReference &Ref = DataLocations[Sym];
606 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000607 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000608 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 }
610 default:
611 llvm_unreachable("invalid relocation type");
612 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000613}
614
Sam Clegg759631c2017-09-15 20:54:59 +0000615static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000616 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000617 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000618
Sam Clegg63ebb812017-09-29 16:50:08 +0000619 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
620
Sam Clegg759631c2017-09-15 20:54:59 +0000621 for (const MCFragment &Frag : DataSection) {
622 if (Frag.hasInstructions())
623 report_fatal_error("only data supported in data sections");
624
625 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
626 if (Align->getValueSize() != 1)
627 report_fatal_error("only byte values supported for alignment");
628 // If nops are requested, use zeros, as this is the data section.
629 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
630 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
631 Align->getAlignment()),
632 DataBytes.size() +
633 Align->getMaxBytesToEmit());
634 DataBytes.resize(Size, Value);
635 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000636 int64_t NumValues;
637 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000638 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000639 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
640 Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000641 } else {
642 const auto &DataFrag = cast<MCDataFragment>(Frag);
643 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
644
645 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
646 }
647 }
648
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000649 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000650}
651
Sam Clegg60ec3032018-01-23 01:23:17 +0000652uint32_t
653WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
654 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000655 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000656 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000657 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000658 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000659 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000660
Sam Clegg25d8e682018-05-08 00:08:21 +0000661 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000662}
663
Dan Gohmand934cb82017-02-24 23:18:00 +0000664// Apply the portions of the relocation records that we can handle ourselves
665// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000666void WasmObjectWriter::applyRelocations(
667 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000668 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000669 for (const WasmRelocationEntry &RelEntry : Relocations) {
670 uint64_t Offset = ContentsOffset +
671 RelEntry.FixupSection->getSectionOffset() +
672 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000673
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000674 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000675 uint32_t Value = getProvisionalValue(RelEntry);
676
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000677 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000678 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000679 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000680 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
681 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000682 WritePatchableLEB(Stream, Value, Offset);
683 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000684 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
685 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000686 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
687 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000688 WriteI32(Stream, Value, Offset);
689 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000690 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
691 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
692 WritePatchableSLEB(Stream, Value, Offset);
693 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000694 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000695 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000696 }
697 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000698}
699
Sam Clegg9e15f352017-06-03 02:01:24 +0000700void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000701 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000702 if (FunctionTypes.empty())
703 return;
704
705 SectionBookkeeping Section;
706 startSection(Section, wasm::WASM_SEC_TYPE);
707
Peter Collingbournef17b1492018-05-21 18:17:42 +0000708 encodeULEB128(FunctionTypes.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000709
710 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000711 W.OS << char(wasm::WASM_TYPE_FUNC);
712 encodeULEB128(FuncTy.Params.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000713 for (wasm::ValType Ty : FuncTy.Params)
714 writeValueType(Ty);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000715 encodeULEB128(FuncTy.Returns.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000716 for (wasm::ValType Ty : FuncTy.Returns)
717 writeValueType(Ty);
718 }
719
720 endSection(Section);
721}
722
Sam Clegg8defa952018-02-12 22:41:29 +0000723void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000724 uint32_t DataSize,
725 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000726 if (Imports.empty())
727 return;
728
Sam Cleggf950b242017-12-11 23:03:38 +0000729 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
730
Sam Clegg9e15f352017-06-03 02:01:24 +0000731 SectionBookkeeping Section;
732 startSection(Section, wasm::WASM_SEC_IMPORT);
733
Peter Collingbournef17b1492018-05-21 18:17:42 +0000734 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000735 for (const wasm::WasmImport &Import : Imports) {
736 writeString(Import.Module);
737 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000738 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000739
740 switch (Import.Kind) {
741 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000742 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000743 break;
744 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000745 W.OS << char(Import.Global.Type);
746 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000747 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000748 case wasm::WASM_EXTERNAL_MEMORY:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 encodeULEB128(0, W.OS); // flags
750 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000751 break;
752 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000753 W.OS << char(Import.Table.ElemType);
754 encodeULEB128(0, W.OS); // flags
755 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000756 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000757 default:
758 llvm_unreachable("unsupported import kind");
759 }
760 }
761
762 endSection(Section);
763}
764
Sam Clegg457fb0b2017-09-15 19:50:44 +0000765void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000766 if (Functions.empty())
767 return;
768
769 SectionBookkeeping Section;
770 startSection(Section, wasm::WASM_SEC_FUNCTION);
771
Peter Collingbournef17b1492018-05-21 18:17:42 +0000772 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 for (const WasmFunction &Func : Functions)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000774 encodeULEB128(Func.Type, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000775
776 endSection(Section);
777}
778
Sam Clegg7c395942017-09-14 23:07:53 +0000779void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000780 if (Globals.empty())
781 return;
782
783 SectionBookkeeping Section;
784 startSection(Section, wasm::WASM_SEC_GLOBAL);
785
Peter Collingbournef17b1492018-05-21 18:17:42 +0000786 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000787 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000788 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000789 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000790
Peter Collingbournef17b1492018-05-21 18:17:42 +0000791 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
792 encodeSLEB128(Global.InitialValue, W.OS);
793 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000794 }
795
796 endSection(Section);
797}
798
Sam Clegg8defa952018-02-12 22:41:29 +0000799void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000800 if (Exports.empty())
801 return;
802
803 SectionBookkeeping Section;
804 startSection(Section, wasm::WASM_SEC_EXPORT);
805
Peter Collingbournef17b1492018-05-21 18:17:42 +0000806 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000807 for (const wasm::WasmExport &Export : Exports) {
808 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000809 W.OS << char(Export.Kind);
810 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000811 }
812
813 endSection(Section);
814}
815
Sam Clegg457fb0b2017-09-15 19:50:44 +0000816void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000817 if (TableElems.empty())
818 return;
819
820 SectionBookkeeping Section;
821 startSection(Section, wasm::WASM_SEC_ELEM);
822
Peter Collingbournef17b1492018-05-21 18:17:42 +0000823 encodeULEB128(1, W.OS); // number of "segments"
824 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000825
826 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000827 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
828 encodeSLEB128(kInitialTableOffset, W.OS);
829 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000830
Peter Collingbournef17b1492018-05-21 18:17:42 +0000831 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000832 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000833 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000834
835 endSection(Section);
836}
837
Sam Clegg457fb0b2017-09-15 19:50:44 +0000838void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
839 const MCAsmLayout &Layout,
840 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000841 if (Functions.empty())
842 return;
843
844 SectionBookkeeping Section;
845 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000846 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000847
Peter Collingbournef17b1492018-05-21 18:17:42 +0000848 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000849
850 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000851 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000852
Sam Clegg9e15f352017-06-03 02:01:24 +0000853 int64_t Size = 0;
854 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
855 report_fatal_error(".size expression must be evaluatable");
856
Peter Collingbournef17b1492018-05-21 18:17:42 +0000857 encodeULEB128(Size, W.OS);
858 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
859 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000860 }
861
Sam Clegg9e15f352017-06-03 02:01:24 +0000862 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000863 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000864
865 endSection(Section);
866}
867
Sam Clegg6c899ba2018-02-23 05:08:34 +0000868void WasmObjectWriter::writeDataSection() {
869 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000870 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
872 SectionBookkeeping Section;
873 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000874 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000875
Peter Collingbournef17b1492018-05-21 18:17:42 +0000876 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000877
Sam Clegg6c899ba2018-02-23 05:08:34 +0000878 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000879 encodeULEB128(0, W.OS); // memory index
880 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
881 encodeSLEB128(Segment.Offset, W.OS); // offset
882 W.OS << char(wasm::WASM_OPCODE_END);
883 encodeULEB128(Segment.Data.size(), W.OS); // size
884 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
885 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000886 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
888 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000889 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000890
891 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000892}
893
Sam Clegg6f08c842018-04-24 18:11:36 +0000894void WasmObjectWriter::writeRelocSection(
895 uint32_t SectionIndex, StringRef Name,
896 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000897 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
898 // for descriptions of the reloc sections.
899
Sam Clegg6f08c842018-04-24 18:11:36 +0000900 if (Relocations.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000901 return;
902
903 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000904 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000905
Peter Collingbournef17b1492018-05-21 18:17:42 +0000906 encodeULEB128(SectionIndex, W.OS);
907 encodeULEB128(Relocations.size(), W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000908 for (const WasmRelocationEntry& RelEntry : Relocations) {
909 uint64_t Offset = RelEntry.Offset +
910 RelEntry.FixupSection->getSectionOffset();
911 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000912
Peter Collingbournef17b1492018-05-21 18:17:42 +0000913 W.OS << char(RelEntry.Type);
914 encodeULEB128(Offset, W.OS);
915 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000916 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000917 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000918 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000919
920 endSection(Section);
921}
922
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000923void WasmObjectWriter::writeCustomRelocSections() {
924 for (const auto &Sec : CustomSections) {
925 auto &Relocations = CustomSectionsRelocations[Sec.Section];
926 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
927 }
928}
929
Sam Clegg9e15f352017-06-03 02:01:24 +0000930void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000931 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000932 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000933 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000934 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000935 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000936 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000937
Sam Clegg6bb5a412018-04-26 18:15:32 +0000938 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000939 if (SymbolInfos.size() != 0) {
940 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000941 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000942 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000943 encodeULEB128(Sym.Kind, W.OS);
944 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000945 switch (Sym.Kind) {
946 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
947 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000948 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000949 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
950 writeString(Sym.Name);
951 break;
952 case wasm::WASM_SYMBOL_TYPE_DATA:
953 writeString(Sym.Name);
954 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000955 encodeULEB128(Sym.DataRef.Segment, W.OS);
956 encodeULEB128(Sym.DataRef.Offset, W.OS);
957 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000958 }
959 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000960 case wasm::WASM_SYMBOL_TYPE_SECTION: {
961 const uint32_t SectionIndex =
962 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000963 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000964 break;
965 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000966 default:
967 llvm_unreachable("unexpected kind");
968 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000969 }
970 endSection(SubSection);
971 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000972
Sam Clegg6c899ba2018-02-23 05:08:34 +0000973 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000974 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000975 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000976 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000977 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000978 encodeULEB128(Segment.Alignment, W.OS);
979 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000980 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000981 endSection(SubSection);
982 }
983
Sam Cleggbafe6902017-12-15 00:17:10 +0000984 if (!InitFuncs.empty()) {
985 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000986 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000987 for (auto &StartFunc : InitFuncs) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000988 encodeULEB128(StartFunc.first, W.OS); // priority
989 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +0000990 }
991 endSection(SubSection);
992 }
993
Sam Cleggea7cace2018-01-09 23:43:14 +0000994 if (Comdats.size()) {
995 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000996 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +0000997 for (const auto &C : Comdats) {
998 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000999 encodeULEB128(0, W.OS); // flags for future use
1000 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001001 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001002 encodeULEB128(Entry.Kind, W.OS);
1003 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001004 }
1005 }
1006 endSection(SubSection);
1007 }
1008
Sam Clegg9e15f352017-06-03 02:01:24 +00001009 endSection(Section);
1010}
1011
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001012void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1013 const MCAsmLayout &Layout) {
1014 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001015 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001016 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001017 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001018
Peter Collingbournef17b1492018-05-21 18:17:42 +00001019 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1020 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001021
1022 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1023 CustomSection.OutputIndex = Section.Index;
1024
Sam Cleggcfd44a22018-04-05 17:01:39 +00001025 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001026
1027 // Apply fixups.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001028 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1029 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001030 }
1031}
1032
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001033uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
1034 assert(Symbol.isFunction());
1035 assert(TypeIndices.count(&Symbol));
1036 return TypeIndices[&Symbol];
1037}
1038
1039uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
1040 assert(Symbol.isFunction());
1041
1042 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001043 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
1044 F.Returns = ResolvedSym->getReturns();
1045 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001046
1047 auto Pair =
1048 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1049 if (Pair.second)
1050 FunctionTypes.push_back(F);
1051 TypeIndices[&Symbol] = Pair.first->second;
1052
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001053 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1054 << " new:" << Pair.second << "\n");
1055 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001056 return Pair.first->second;
1057}
1058
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001059static bool isInSymtab(const MCSymbolWasm &Sym) {
1060 if (Sym.isUsedInReloc())
1061 return true;
1062
1063 if (Sym.isComdat() && !Sym.isDefined())
1064 return false;
1065
1066 if (Sym.isTemporary() && Sym.getName().empty())
1067 return false;
1068
1069 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1070 return false;
1071
1072 if (Sym.isSection())
1073 return false;
1074
1075 return true;
1076}
1077
Dan Gohman18eafb62017-02-22 01:23:18 +00001078void WasmObjectWriter::writeObject(MCAssembler &Asm,
1079 const MCAsmLayout &Layout) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001080 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001081 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001082
1083 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001084 SmallVector<WasmFunction, 4> Functions;
1085 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001086 SmallVector<wasm::WasmImport, 4> Imports;
1087 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001088 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001089 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001090 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001091 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001092
Sam Cleggf950b242017-12-11 23:03:38 +00001093 // For now, always emit the memory import, since loads and stores are not
1094 // valid without it. In the future, we could perhaps be more clever and omit
1095 // it if there are no loads or stores.
1096 MCSymbolWasm *MemorySym =
1097 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001098 wasm::WasmImport MemImport;
1099 MemImport.Module = MemorySym->getModuleName();
1100 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001101 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1102 Imports.push_back(MemImport);
1103
1104 // For now, always emit the table section, since indirect calls are not
1105 // valid without it. In the future, we could perhaps be more clever and omit
1106 // it if there are no indirect calls.
1107 MCSymbolWasm *TableSym =
1108 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001109 wasm::WasmImport TableImport;
1110 TableImport.Module = TableSym->getModuleName();
1111 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001112 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001113 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001114 Imports.push_back(TableImport);
1115
Nicholas Wilson586320c2018-02-28 17:19:48 +00001116 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1117 // symbols. This must be done before populating WasmIndices for defined
1118 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001119 for (const MCSymbol &S : Asm.symbols()) {
1120 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1121
1122 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001123 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001124 if (WS.isFunction())
1125 registerFunctionType(WS);
1126
1127 if (WS.isTemporary())
1128 continue;
1129
1130 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001131 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001132 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001133 wasm::WasmImport Import;
1134 Import.Module = WS.getModuleName();
1135 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001136 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001137 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001138 Imports.push_back(Import);
1139 WasmIndices[&WS] = NumFunctionImports++;
1140 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001141 if (WS.isWeak())
1142 report_fatal_error("undefined global symbol cannot be weak");
1143
Sam Clegg6c899ba2018-02-23 05:08:34 +00001144 wasm::WasmImport Import;
1145 Import.Module = WS.getModuleName();
1146 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001147 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001148 Import.Global = WS.getGlobalType();
1149 Imports.push_back(Import);
1150 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001151 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001152 }
1153 }
1154
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001155 // Populate DataSegments and CustomSections, which must be done before
1156 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001157 for (MCSection &Sec : Asm) {
1158 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001159 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001160
Sam Cleggbafe6902017-12-15 00:17:10 +00001161 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001162 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001163 continue;
1164
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001165 // Code is handled separately
1166 if (Section.getKind().isText())
1167 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001168
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001169 if (Section.isWasmData()) {
1170 uint32_t SegmentIndex = DataSegments.size();
1171 DataSize = alignTo(DataSize, Section.getAlignment());
1172 DataSegments.emplace_back();
1173 WasmDataSegment &Segment = DataSegments.back();
1174 Segment.Name = SectionName;
1175 Segment.Offset = DataSize;
1176 Segment.Section = &Section;
1177 addData(Segment.Data, Section);
1178 Segment.Alignment = Section.getAlignment();
1179 Segment.Flags = 0;
1180 DataSize += Segment.Data.size();
1181 Section.setSegmentIndex(SegmentIndex);
1182
1183 if (const MCSymbolWasm *C = Section.getGroup()) {
1184 Comdats[C->getName()].emplace_back(
1185 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1186 }
1187 } else {
1188 // Create custom sections
1189 assert(Sec.getKind().isMetadata());
1190
1191 StringRef Name = SectionName;
1192
1193 // For user-defined custom sections, strip the prefix
1194 if (Name.startswith(".custom_section."))
1195 Name = Name.substr(strlen(".custom_section."));
1196
1197 MCSymbol* Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001198 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001199 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001200 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001201 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001202 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001203 }
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001204 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001205 }
Sam Clegg759631c2017-09-15 20:54:59 +00001206 }
1207
Nicholas Wilson586320c2018-02-28 17:19:48 +00001208 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001209 for (const MCSymbol &S : Asm.symbols()) {
1210 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1211 // or used in relocations.
1212 if (S.isTemporary() && S.getName().empty())
1213 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001214
Dan Gohmand934cb82017-02-24 23:18:00 +00001215 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001216 LLVM_DEBUG(
1217 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1218 << " isDefined=" << S.isDefined() << " isExternal="
1219 << S.isExternal() << " isTemporary=" << S.isTemporary()
1220 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1221 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001222
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001223 if (WS.isVariable())
1224 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001225 if (WS.isComdat() && !WS.isDefined())
1226 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001227
Dan Gohmand934cb82017-02-24 23:18:00 +00001228 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001229 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001230 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001231 if (WS.getOffset() != 0)
1232 report_fatal_error(
1233 "function sections must contain one function each");
1234
1235 if (WS.getSize() == 0)
1236 report_fatal_error(
1237 "function symbols must have a size set with .size");
1238
Sam Clegg6c899ba2018-02-23 05:08:34 +00001239 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001240 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001241 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001242 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001244 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001245 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001246
1247 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1248 if (const MCSymbolWasm *C = Section.getGroup()) {
1249 Comdats[C->getName()].emplace_back(
1250 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1251 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001252 } else {
1253 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001254 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001255 }
1256
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001257 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001258 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001259 if (WS.isTemporary() && !WS.getSize())
1260 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001261
Sam Clegg6c899ba2018-02-23 05:08:34 +00001262 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001263 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1264 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001265 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001266 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001267
Sam Cleggfe6414b2017-06-21 23:46:41 +00001268 if (!WS.getSize())
1269 report_fatal_error("data symbols must have a size set with .size: " +
1270 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001271
Sam Cleggfe6414b2017-06-21 23:46:41 +00001272 int64_t Size = 0;
1273 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1274 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001275
Sam Clegg759631c2017-09-15 20:54:59 +00001276 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001277 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001278
Sam Clegg6c899ba2018-02-23 05:08:34 +00001279 // For each data symbol, export it in the symtab as a reference to the
1280 // corresponding Wasm data segment.
1281 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1282 DataSection.getSegmentIndex(),
1283 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1284 static_cast<uint32_t>(Size)};
1285 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001286 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001287 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001288 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001289 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001290 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001291
Eric Christopher545932b2018-02-23 21:14:47 +00001292 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001293 LLVM_DEBUG(dbgs() << " -> global index: "
1294 << WasmIndices.find(&WS)->second << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001295 } else {
1296 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001297 }
1298 }
1299
Nicholas Wilson586320c2018-02-28 17:19:48 +00001300 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1301 // process these in a separate pass because we need to have processed the
1302 // target of the alias before the alias itself and the symbols are not
1303 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001304 for (const MCSymbol &S : Asm.symbols()) {
1305 if (!S.isVariable())
1306 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001307
Sam Cleggcd65f692018-01-11 23:59:16 +00001308 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001309
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001310 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001311 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1312 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001313 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1314 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001315
Sam Clegg6c899ba2018-02-23 05:08:34 +00001316 if (WS.isFunction()) {
1317 assert(WasmIndices.count(ResolvedSym) > 0);
1318 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1319 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001320 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001321 } else if (WS.isData()) {
1322 assert(DataLocations.count(ResolvedSym) > 0);
1323 const wasm::WasmDataReference &Ref =
1324 DataLocations.find(ResolvedSym)->second;
1325 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001326 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001327 } else {
1328 report_fatal_error("don't yet support global aliases");
1329 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001330 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001331
Nicholas Wilson586320c2018-02-28 17:19:48 +00001332 // Finally, populate the symbol table itself, in its "natural" order.
1333 for (const MCSymbol &S : Asm.symbols()) {
1334 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001335 if (!isInSymtab(WS)) {
1336 WS.setIndex(INVALID_INDEX);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001337 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001338 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001339 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001340
1341 uint32_t Flags = 0;
1342 if (WS.isWeak())
1343 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1344 if (WS.isHidden())
1345 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1346 if (!WS.isExternal() && WS.isDefined())
1347 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1348 if (WS.isUndefined())
1349 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1350
1351 wasm::WasmSymbolInfo Info;
1352 Info.Name = WS.getName();
1353 Info.Kind = WS.getType();
1354 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001355 if (!WS.isData()) {
1356 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001357 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001358 } else if (WS.isDefined()) {
1359 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001360 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001361 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001362 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001363 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001364 }
1365
Sam Clegg6006e092017-12-22 20:31:39 +00001366 {
1367 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001368 // Functions referenced by a relocation need to put in the table. This is
1369 // purely to make the object file's provisional values readable, and is
1370 // ignored by the linker, which re-calculates the relocations itself.
1371 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1372 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1373 return;
1374 assert(Rel.Symbol->isFunction());
1375 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001376 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001377 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1378 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001379 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1380 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001381 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001382 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001383 }
1384 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001385
Sam Clegg6006e092017-12-22 20:31:39 +00001386 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1387 HandleReloc(RelEntry);
1388 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1389 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001390 }
1391
Sam Cleggbafe6902017-12-15 00:17:10 +00001392 // Translate .init_array section contents into start functions.
1393 for (const MCSection &S : Asm) {
1394 const auto &WS = static_cast<const MCSectionWasm &>(S);
1395 if (WS.getSectionName().startswith(".fini_array"))
1396 report_fatal_error(".fini_array sections are unsupported");
1397 if (!WS.getSectionName().startswith(".init_array"))
1398 continue;
1399 if (WS.getFragmentList().empty())
1400 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001401
1402 // init_array is expected to contain a single non-empty data fragment
1403 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001404 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001405
1406 auto IT = WS.begin();
1407 const MCFragment &EmptyFrag = *IT;
1408 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1409 report_fatal_error(".init_array section should be aligned");
1410
1411 IT = std::next(IT);
1412 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001413 if (AlignFrag.getKind() != MCFragment::FT_Align)
1414 report_fatal_error(".init_array section should be aligned");
1415 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1416 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001417
1418 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001419 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1420 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001421
Sam Cleggbafe6902017-12-15 00:17:10 +00001422 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001423 unsigned PrefixLength = strlen(".init_array");
1424 if (WS.getSectionName().size() > PrefixLength) {
1425 if (WS.getSectionName()[PrefixLength] != '.')
Sam Cleggbafe6902017-12-15 00:17:10 +00001426 report_fatal_error(".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001427 if (WS.getSectionName()
1428 .substr(PrefixLength + 1)
1429 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001430 report_fatal_error("invalid .init_array section priority");
1431 }
1432 const auto &DataFrag = cast<MCDataFragment>(Frag);
1433 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1434 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1435 *end = (const uint8_t *)Contents.data() + Contents.size();
1436 p != end; ++p) {
1437 if (*p != 0)
1438 report_fatal_error("non-symbolic data in .init_array section");
1439 }
1440 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1441 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1442 const MCExpr *Expr = Fixup.getValue();
1443 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1444 if (!Sym)
1445 report_fatal_error("fixups in .init_array should be symbol references");
1446 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1447 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001448 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1449 report_fatal_error("symbols in .init_array should exist in symbtab");
1450 InitFuncs.push_back(
1451 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001452 }
1453 }
1454
Dan Gohman18eafb62017-02-22 01:23:18 +00001455 // Write out the Wasm header.
1456 writeHeader(Asm);
1457
Sam Clegg9e15f352017-06-03 02:01:24 +00001458 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001459 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001460 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001461 // Skip the "table" section; we import the table instead.
1462 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001463 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001464 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001465 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001466 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001467 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001468 writeCustomSections(Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001469 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001470 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1471 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001472 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001473
Dan Gohmand934cb82017-02-24 23:18:00 +00001474 // TODO: Translate the .comment section to the output.
Dan Gohman18eafb62017-02-22 01:23:18 +00001475}
1476
Lang Hames60fbc7c2017-10-10 16:28:07 +00001477std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001478llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1479 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001480 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001481}