blob: a9ff7be2babc478e128a8379d8c44e526abb4a68 [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 Collingbourne59a6fc42018-05-21 18:28:57 +0000255 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000256
Dan Gohman18eafb62017-02-22 01:23:18 +0000257 ~WasmObjectWriter() override;
258
Dan Gohman0917c9e2018-01-15 17:06:23 +0000259private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000260 void reset() override {
261 CodeRelocations.clear();
262 DataRelocations.clear();
263 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000264 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000265 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000266 DataLocations.clear();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000267 CustomSectionsRelocations.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000268 FunctionTypeIndices.clear();
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000269 FunctionTypes.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000270 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000271 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000272 SectionFunctions.clear();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000273 MCObjectWriter::reset();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000274 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000275 NumGlobalImports = 0;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000276 }
277
Dan Gohman18eafb62017-02-22 01:23:18 +0000278 void writeHeader(const MCAssembler &Asm);
279
280 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
281 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000282 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000283
284 void executePostLayoutBinding(MCAssembler &Asm,
285 const MCAsmLayout &Layout) override;
286
Peter Collingbourne438390f2018-05-21 18:23:50 +0000287 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000288
Sam Cleggb7787fd2017-06-20 04:04:59 +0000289 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000290 encodeULEB128(Str.size(), W.OS);
291 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000292 }
293
Sam Clegg9e15f352017-06-03 02:01:24 +0000294 void writeValueType(wasm::ValType Ty) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000295 W.OS << static_cast<char>(Ty);
Sam Clegg9e15f352017-06-03 02:01:24 +0000296 }
297
Sam Clegg457fb0b2017-09-15 19:50:44 +0000298 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000299 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000300 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000301 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000302 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000303 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000304 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000305 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000306 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000307 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000308 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
309 ArrayRef<WasmRelocationEntry> Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000310 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000311 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000312 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000313 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000314 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
315 void writeCustomRelocSections();
316 void
317 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
318 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000319
Sam Clegg7c395942017-09-14 23:07:53 +0000320 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000321 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
322 uint64_t ContentsOffset);
323
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000324 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000325 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
326 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000327};
Sam Clegg9e15f352017-06-03 02:01:24 +0000328
Dan Gohman18eafb62017-02-22 01:23:18 +0000329} // end anonymous namespace
330
331WasmObjectWriter::~WasmObjectWriter() {}
332
Dan Gohmand934cb82017-02-24 23:18:00 +0000333// Write out a section header and a patchable section size field.
334void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000335 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000336 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000337 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000338
Peter Collingbournef17b1492018-05-21 18:17:42 +0000339 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000340
341 // The section size. We don't know the size yet, so reserve enough space
342 // for any 32-bit value; we'll patch it later.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000343 encodeULEB128(UINT32_MAX, W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000344
345 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000346 Section.ContentsOffset = W.OS.tell();
347 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000348 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000349}
Dan Gohmand934cb82017-02-24 23:18:00 +0000350
Sam Clegg2322a932018-04-23 19:16:19 +0000351void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
352 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000354 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000355
356 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000357 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000358
Dan Gohmand934cb82017-02-24 23:18:00 +0000359 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000360 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000361
362 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000363 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000364}
365
366// Now that the section is complete and we know how big it is, patch up the
367// section size field at the start of the section.
368void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000369 uint64_t Size = W.OS.tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000370 if (uint32_t(Size) != Size)
371 report_fatal_error("section size does not fit in a uint32_t");
372
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000373 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000374
375 // Write the final section size to the payload_len field, which follows
376 // the section id byte.
377 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000378 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000379 assert(SizeLen == 5);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000380 static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
381 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000382}
383
Dan Gohman18eafb62017-02-22 01:23:18 +0000384// Emit the Wasm header.
385void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000386 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
387 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000388}
389
390void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
391 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000392 // Build a map of sections to the function that defines them, for use
393 // in recordRelocation.
394 for (const MCSymbol &S : Asm.symbols()) {
395 const auto &WS = static_cast<const MCSymbolWasm &>(S);
396 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
397 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
398 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
399 if (!Pair.second)
400 report_fatal_error("section already has a defining function: " +
401 Sec.getSectionName());
402 }
403 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000404}
405
406void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
407 const MCAsmLayout &Layout,
408 const MCFragment *Fragment,
409 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000410 uint64_t &FixedValue) {
411 MCAsmBackend &Backend = Asm.getBackend();
412 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
413 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000414 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000415 uint64_t C = Target.getConstant();
416 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
417 MCContext &Ctx = Asm.getContext();
418
Sam Cleggbafe6902017-12-15 00:17:10 +0000419 // The .init_array isn't translated as data, so don't do relocations in it.
420 if (FixupSection.getSectionName().startswith(".init_array"))
421 return;
422
Dan Gohmand934cb82017-02-24 23:18:00 +0000423 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
424 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
425 "Should not have constructed this");
426
427 // Let A, B and C being the components of Target and R be the location of
428 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
429 // If it is pcrel, we want to compute (A - B + C - R).
430
431 // In general, Wasm has no relocations for -B. It can only represent (A + C)
432 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
433 // replace B to implement it: (A - R - K + C)
434 if (IsPCRel) {
435 Ctx.reportError(
436 Fixup.getLoc(),
437 "No relocation available to represent this relative expression");
438 return;
439 }
440
441 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
442
443 if (SymB.isUndefined()) {
444 Ctx.reportError(Fixup.getLoc(),
445 Twine("symbol '") + SymB.getName() +
446 "' can not be undefined in a subtraction expression");
447 return;
448 }
449
450 assert(!SymB.isAbsolute() && "Should have been folded");
451 const MCSection &SecB = SymB.getSection();
452 if (&SecB != &FixupSection) {
453 Ctx.reportError(Fixup.getLoc(),
454 "Cannot represent a difference across sections");
455 return;
456 }
457
458 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
459 uint64_t K = SymBOffset - FixupOffset;
460 IsPCRel = true;
461 C -= K;
462 }
463
464 // We either rejected the fixup or folded B into C at this point.
465 const MCSymbolRefExpr *RefA = Target.getSymA();
466 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
467
Dan Gohmand934cb82017-02-24 23:18:00 +0000468 if (SymA && SymA->isVariable()) {
469 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000470 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
471 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
472 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000473 }
474
475 // Put any constant offset in an addend. Offsets can be negative, and
476 // LLVM expects wrapping, in contrast to wasm's immediates which can't
477 // be negative and don't wrap.
478 FixedValue = 0;
479
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000480 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000481 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000482 assert(SymA);
483
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000484 // Absolute offset within a section or a function.
485 // Currently only supported for for metadata sections.
486 // See: test/MC/WebAssembly/blockaddress.ll
487 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
488 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
489 if (!FixupSection.getKind().isMetadata())
490 report_fatal_error("relocations for function or section offsets are "
491 "only supported in metadata sections");
492
493 const MCSymbol *SectionSymbol = nullptr;
494 const MCSection &SecA = SymA->getSection();
495 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000496 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000497 else
498 SectionSymbol = SecA.getBeginSymbol();
499 if (!SectionSymbol)
500 report_fatal_error("section symbol is required for relocation");
501
502 C += Layout.getSymbolOffset(*SymA);
503 SymA = cast<MCSymbolWasm>(SectionSymbol);
504 }
505
506 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
507 // against a named symbol.
508 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
509 if (SymA->getName().empty())
510 report_fatal_error("relocations against un-named temporaries are not yet "
511 "supported by wasm");
512
513 SymA->setUsedInReloc();
514 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000515
Dan Gohmand934cb82017-02-24 23:18:00 +0000516 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000517 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000518
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000519 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000520 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000521 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000522 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000523 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000524 CustomSectionsRelocations[&FixupSection].push_back(Rec);
525 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000526 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000527 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000528}
529
Dan Gohmand934cb82017-02-24 23:18:00 +0000530// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
531// to allow patching.
532static void
533WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
534 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000535 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000536 assert(SizeLen == 5);
537 Stream.pwrite((char *)Buffer, SizeLen, Offset);
538}
539
540// Write X as an signed LEB value at offset Offset in Stream, padded
541// to allow patching.
542static void
543WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) {
544 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000545 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000546 assert(SizeLen == 5);
547 Stream.pwrite((char *)Buffer, SizeLen, Offset);
548}
549
550// Write X as a plain integer value at offset Offset in Stream.
551static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
552 uint8_t Buffer[4];
553 support::endian::write32le(Buffer, X);
554 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
555}
556
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000557static const MCSymbolWasm* ResolveSymbol(const MCSymbolWasm& Symbol) {
558 if (Symbol.isVariable()) {
559 const MCExpr *Expr = Symbol.getVariableValue();
560 auto *Inner = cast<MCSymbolRefExpr>(Expr);
561 return cast<MCSymbolWasm>(&Inner->getSymbol());
562 }
563 return &Symbol;
564}
565
Dan Gohmand934cb82017-02-24 23:18:00 +0000566// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000567// by RelEntry. This value isn't used by the static linker; it just serves
568// to make the object format more readable and more likely to be directly
569// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000570uint32_t
571WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000572 switch (RelEntry.Type) {
573 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000574 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
575 // Provisional value is table address of the resolved symbol itself
576 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
577 assert(Sym->isFunction());
578 return TableIndices[Sym];
579 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000580 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000581 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000582 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000583 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
584 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
585 // Provisional value is function/global Wasm index
586 if (!WasmIndices.count(RelEntry.Symbol))
587 report_fatal_error("symbol not found in wasm index space: " +
588 RelEntry.Symbol->getName());
589 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000590 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
591 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000592 const auto &Section =
593 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
594 return Section.getSectionOffset() + RelEntry.Addend;
595 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000596 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
597 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
598 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000599 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000600 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
601 // For undefined symbols, use zero
602 if (!Sym->isDefined())
603 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000604 const wasm::WasmDataReference &Ref = DataLocations[Sym];
605 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000606 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000607 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000608 }
609 default:
610 llvm_unreachable("invalid relocation type");
611 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000612}
613
Sam Clegg759631c2017-09-15 20:54:59 +0000614static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000615 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000617
Sam Clegg63ebb812017-09-29 16:50:08 +0000618 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
619
Sam Clegg759631c2017-09-15 20:54:59 +0000620 for (const MCFragment &Frag : DataSection) {
621 if (Frag.hasInstructions())
622 report_fatal_error("only data supported in data sections");
623
624 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
625 if (Align->getValueSize() != 1)
626 report_fatal_error("only byte values supported for alignment");
627 // If nops are requested, use zeros, as this is the data section.
628 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
629 uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(),
630 Align->getAlignment()),
631 DataBytes.size() +
632 Align->getMaxBytesToEmit());
633 DataBytes.resize(Size, Value);
634 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000635 int64_t NumValues;
636 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000637 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000638 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
639 Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000640 } else {
641 const auto &DataFrag = cast<MCDataFragment>(Frag);
642 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
643
644 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
645 }
646 }
647
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000648 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000649}
650
Sam Clegg60ec3032018-01-23 01:23:17 +0000651uint32_t
652WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
653 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000654 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000655 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000656 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000657 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000658 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000659
Sam Clegg25d8e682018-05-08 00:08:21 +0000660 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000661}
662
Dan Gohmand934cb82017-02-24 23:18:00 +0000663// Apply the portions of the relocation records that we can handle ourselves
664// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000665void WasmObjectWriter::applyRelocations(
666 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000667 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000668 for (const WasmRelocationEntry &RelEntry : Relocations) {
669 uint64_t Offset = ContentsOffset +
670 RelEntry.FixupSection->getSectionOffset() +
671 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000672
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000674 uint32_t Value = getProvisionalValue(RelEntry);
675
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000676 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000677 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000678 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000679 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
680 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000681 WritePatchableLEB(Stream, Value, Offset);
682 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000683 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
684 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000685 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
686 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000687 WriteI32(Stream, Value, Offset);
688 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000689 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
690 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
691 WritePatchableSLEB(Stream, Value, Offset);
692 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000693 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000694 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000695 }
696 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000697}
698
Sam Clegg9e15f352017-06-03 02:01:24 +0000699void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000700 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000701 if (FunctionTypes.empty())
702 return;
703
704 SectionBookkeeping Section;
705 startSection(Section, wasm::WASM_SEC_TYPE);
706
Peter Collingbournef17b1492018-05-21 18:17:42 +0000707 encodeULEB128(FunctionTypes.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000708
709 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000710 W.OS << char(wasm::WASM_TYPE_FUNC);
711 encodeULEB128(FuncTy.Params.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 for (wasm::ValType Ty : FuncTy.Params)
713 writeValueType(Ty);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000714 encodeULEB128(FuncTy.Returns.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000715 for (wasm::ValType Ty : FuncTy.Returns)
716 writeValueType(Ty);
717 }
718
719 endSection(Section);
720}
721
Sam Clegg8defa952018-02-12 22:41:29 +0000722void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000723 uint32_t DataSize,
724 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000725 if (Imports.empty())
726 return;
727
Sam Cleggf950b242017-12-11 23:03:38 +0000728 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
729
Sam Clegg9e15f352017-06-03 02:01:24 +0000730 SectionBookkeeping Section;
731 startSection(Section, wasm::WASM_SEC_IMPORT);
732
Peter Collingbournef17b1492018-05-21 18:17:42 +0000733 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000734 for (const wasm::WasmImport &Import : Imports) {
735 writeString(Import.Module);
736 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000737 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000738
739 switch (Import.Kind) {
740 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000742 break;
743 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000744 W.OS << char(Import.Global.Type);
745 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000747 case wasm::WASM_EXTERNAL_MEMORY:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000748 encodeULEB128(0, W.OS); // flags
749 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000750 break;
751 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000752 W.OS << char(Import.Table.ElemType);
753 encodeULEB128(0, W.OS); // flags
754 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000755 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000756 default:
757 llvm_unreachable("unsupported import kind");
758 }
759 }
760
761 endSection(Section);
762}
763
Sam Clegg457fb0b2017-09-15 19:50:44 +0000764void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000765 if (Functions.empty())
766 return;
767
768 SectionBookkeeping Section;
769 startSection(Section, wasm::WASM_SEC_FUNCTION);
770
Peter Collingbournef17b1492018-05-21 18:17:42 +0000771 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000772 for (const WasmFunction &Func : Functions)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000773 encodeULEB128(Func.Type, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000774
775 endSection(Section);
776}
777
Sam Clegg7c395942017-09-14 23:07:53 +0000778void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000779 if (Globals.empty())
780 return;
781
782 SectionBookkeeping Section;
783 startSection(Section, wasm::WASM_SEC_GLOBAL);
784
Peter Collingbournef17b1492018-05-21 18:17:42 +0000785 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000787 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000788 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000789
Peter Collingbournef17b1492018-05-21 18:17:42 +0000790 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
791 encodeSLEB128(Global.InitialValue, W.OS);
792 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000793 }
794
795 endSection(Section);
796}
797
Sam Clegg8defa952018-02-12 22:41:29 +0000798void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000799 if (Exports.empty())
800 return;
801
802 SectionBookkeeping Section;
803 startSection(Section, wasm::WASM_SEC_EXPORT);
804
Peter Collingbournef17b1492018-05-21 18:17:42 +0000805 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000806 for (const wasm::WasmExport &Export : Exports) {
807 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000808 W.OS << char(Export.Kind);
809 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000810 }
811
812 endSection(Section);
813}
814
Sam Clegg457fb0b2017-09-15 19:50:44 +0000815void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000816 if (TableElems.empty())
817 return;
818
819 SectionBookkeeping Section;
820 startSection(Section, wasm::WASM_SEC_ELEM);
821
Peter Collingbournef17b1492018-05-21 18:17:42 +0000822 encodeULEB128(1, W.OS); // number of "segments"
823 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000824
825 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000826 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
827 encodeSLEB128(kInitialTableOffset, W.OS);
828 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000829
Peter Collingbournef17b1492018-05-21 18:17:42 +0000830 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000831 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000832 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
834 endSection(Section);
835}
836
Sam Clegg457fb0b2017-09-15 19:50:44 +0000837void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
838 const MCAsmLayout &Layout,
839 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 if (Functions.empty())
841 return;
842
843 SectionBookkeeping Section;
844 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000845 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000846
Peter Collingbournef17b1492018-05-21 18:17:42 +0000847 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000850 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000851
Sam Clegg9e15f352017-06-03 02:01:24 +0000852 int64_t Size = 0;
853 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
854 report_fatal_error(".size expression must be evaluatable");
855
Peter Collingbournef17b1492018-05-21 18:17:42 +0000856 encodeULEB128(Size, W.OS);
857 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
858 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859 }
860
Sam Clegg9e15f352017-06-03 02:01:24 +0000861 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000862 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000863
864 endSection(Section);
865}
866
Sam Clegg6c899ba2018-02-23 05:08:34 +0000867void WasmObjectWriter::writeDataSection() {
868 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000869 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000870
871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000873 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
Peter Collingbournef17b1492018-05-21 18:17:42 +0000875 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000876
Sam Clegg6c899ba2018-02-23 05:08:34 +0000877 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000878 encodeULEB128(0, W.OS); // memory index
879 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
880 encodeSLEB128(Segment.Offset, W.OS); // offset
881 W.OS << char(wasm::WASM_OPCODE_END);
882 encodeULEB128(Segment.Data.size(), W.OS); // size
883 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
884 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000885 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
887 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000888 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000889
890 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000891}
892
Sam Clegg6f08c842018-04-24 18:11:36 +0000893void WasmObjectWriter::writeRelocSection(
894 uint32_t SectionIndex, StringRef Name,
895 ArrayRef<WasmRelocationEntry> Relocations) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000896 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
897 // for descriptions of the reloc sections.
898
Sam Clegg6f08c842018-04-24 18:11:36 +0000899 if (Relocations.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000900 return;
901
902 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000903 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000904
Peter Collingbournef17b1492018-05-21 18:17:42 +0000905 encodeULEB128(SectionIndex, W.OS);
906 encodeULEB128(Relocations.size(), W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000907 for (const WasmRelocationEntry& RelEntry : Relocations) {
908 uint64_t Offset = RelEntry.Offset +
909 RelEntry.FixupSection->getSectionOffset();
910 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000911
Peter Collingbournef17b1492018-05-21 18:17:42 +0000912 W.OS << char(RelEntry.Type);
913 encodeULEB128(Offset, W.OS);
914 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000915 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000916 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000917 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000918
919 endSection(Section);
920}
921
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000922void WasmObjectWriter::writeCustomRelocSections() {
923 for (const auto &Sec : CustomSections) {
924 auto &Relocations = CustomSectionsRelocations[Sec.Section];
925 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
926 }
927}
928
Sam Clegg9e15f352017-06-03 02:01:24 +0000929void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000930 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000931 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000932 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000933 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000934 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000935 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000936
Sam Clegg6bb5a412018-04-26 18:15:32 +0000937 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000938 if (SymbolInfos.size() != 0) {
939 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000940 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000941 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000942 encodeULEB128(Sym.Kind, W.OS);
943 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000944 switch (Sym.Kind) {
945 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
946 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000947 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000948 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
949 writeString(Sym.Name);
950 break;
951 case wasm::WASM_SYMBOL_TYPE_DATA:
952 writeString(Sym.Name);
953 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000954 encodeULEB128(Sym.DataRef.Segment, W.OS);
955 encodeULEB128(Sym.DataRef.Offset, W.OS);
956 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000957 }
958 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000959 case wasm::WASM_SYMBOL_TYPE_SECTION: {
960 const uint32_t SectionIndex =
961 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000962 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000963 break;
964 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000965 default:
966 llvm_unreachable("unexpected kind");
967 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000968 }
969 endSection(SubSection);
970 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000971
Sam Clegg6c899ba2018-02-23 05:08:34 +0000972 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000973 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000974 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000975 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000976 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000977 encodeULEB128(Segment.Alignment, W.OS);
978 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000979 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000980 endSection(SubSection);
981 }
982
Sam Cleggbafe6902017-12-15 00:17:10 +0000983 if (!InitFuncs.empty()) {
984 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000985 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000986 for (auto &StartFunc : InitFuncs) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000987 encodeULEB128(StartFunc.first, W.OS); // priority
988 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +0000989 }
990 endSection(SubSection);
991 }
992
Sam Cleggea7cace2018-01-09 23:43:14 +0000993 if (Comdats.size()) {
994 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000995 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +0000996 for (const auto &C : Comdats) {
997 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000998 encodeULEB128(0, W.OS); // flags for future use
999 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001000 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001001 encodeULEB128(Entry.Kind, W.OS);
1002 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001003 }
1004 }
1005 endSection(SubSection);
1006 }
1007
Sam Clegg9e15f352017-06-03 02:01:24 +00001008 endSection(Section);
1009}
1010
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001011void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1012 const MCAsmLayout &Layout) {
1013 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001014 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001015 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001016 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001017
Peter Collingbournef17b1492018-05-21 18:17:42 +00001018 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1019 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001020
1021 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1022 CustomSection.OutputIndex = Section.Index;
1023
Sam Cleggcfd44a22018-04-05 17:01:39 +00001024 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001025
1026 // Apply fixups.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001027 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1028 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001029 }
1030}
1031
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001032uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm& Symbol) {
1033 assert(Symbol.isFunction());
1034 assert(TypeIndices.count(&Symbol));
1035 return TypeIndices[&Symbol];
1036}
1037
1038uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm& Symbol) {
1039 assert(Symbol.isFunction());
1040
1041 WasmFunctionType F;
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001042 const MCSymbolWasm* ResolvedSym = ResolveSymbol(Symbol);
1043 F.Returns = ResolvedSym->getReturns();
1044 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001045
1046 auto Pair =
1047 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1048 if (Pair.second)
1049 FunctionTypes.push_back(F);
1050 TypeIndices[&Symbol] = Pair.first->second;
1051
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001052 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1053 << " new:" << Pair.second << "\n");
1054 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001055 return Pair.first->second;
1056}
1057
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001058static bool isInSymtab(const MCSymbolWasm &Sym) {
1059 if (Sym.isUsedInReloc())
1060 return true;
1061
1062 if (Sym.isComdat() && !Sym.isDefined())
1063 return false;
1064
1065 if (Sym.isTemporary() && Sym.getName().empty())
1066 return false;
1067
1068 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1069 return false;
1070
1071 if (Sym.isSection())
1072 return false;
1073
1074 return true;
1075}
1076
Peter Collingbourne438390f2018-05-21 18:23:50 +00001077uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1078 const MCAsmLayout &Layout) {
1079 uint64_t StartOffset = W.OS.tell();
1080
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001081 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001082 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001083
1084 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001085 SmallVector<WasmFunction, 4> Functions;
1086 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001087 SmallVector<wasm::WasmImport, 4> Imports;
1088 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001089 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001090 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001091 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001092 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001093
Sam Cleggf950b242017-12-11 23:03:38 +00001094 // For now, always emit the memory import, since loads and stores are not
1095 // valid without it. In the future, we could perhaps be more clever and omit
1096 // it if there are no loads or stores.
1097 MCSymbolWasm *MemorySym =
1098 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001099 wasm::WasmImport MemImport;
1100 MemImport.Module = MemorySym->getModuleName();
1101 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001102 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1103 Imports.push_back(MemImport);
1104
1105 // For now, always emit the table section, since indirect calls are not
1106 // valid without it. In the future, we could perhaps be more clever and omit
1107 // it if there are no indirect calls.
1108 MCSymbolWasm *TableSym =
1109 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001110 wasm::WasmImport TableImport;
1111 TableImport.Module = TableSym->getModuleName();
1112 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001113 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001114 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001115 Imports.push_back(TableImport);
1116
Nicholas Wilson586320c2018-02-28 17:19:48 +00001117 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1118 // symbols. This must be done before populating WasmIndices for defined
1119 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001120 for (const MCSymbol &S : Asm.symbols()) {
1121 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1122
1123 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001124 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001125 if (WS.isFunction())
1126 registerFunctionType(WS);
1127
1128 if (WS.isTemporary())
1129 continue;
1130
1131 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001132 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001133 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001134 wasm::WasmImport Import;
1135 Import.Module = WS.getModuleName();
1136 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001137 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001138 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001139 Imports.push_back(Import);
1140 WasmIndices[&WS] = NumFunctionImports++;
1141 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001142 if (WS.isWeak())
1143 report_fatal_error("undefined global symbol cannot be weak");
1144
Sam Clegg6c899ba2018-02-23 05:08:34 +00001145 wasm::WasmImport Import;
1146 Import.Module = WS.getModuleName();
1147 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001148 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001149 Import.Global = WS.getGlobalType();
1150 Imports.push_back(Import);
1151 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001152 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001153 }
1154 }
1155
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001156 // Populate DataSegments and CustomSections, which must be done before
1157 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001158 for (MCSection &Sec : Asm) {
1159 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001160 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001161
Sam Cleggbafe6902017-12-15 00:17:10 +00001162 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001163 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001164 continue;
1165
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001166 // Code is handled separately
1167 if (Section.getKind().isText())
1168 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001169
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001170 if (Section.isWasmData()) {
1171 uint32_t SegmentIndex = DataSegments.size();
1172 DataSize = alignTo(DataSize, Section.getAlignment());
1173 DataSegments.emplace_back();
1174 WasmDataSegment &Segment = DataSegments.back();
1175 Segment.Name = SectionName;
1176 Segment.Offset = DataSize;
1177 Segment.Section = &Section;
1178 addData(Segment.Data, Section);
1179 Segment.Alignment = Section.getAlignment();
1180 Segment.Flags = 0;
1181 DataSize += Segment.Data.size();
1182 Section.setSegmentIndex(SegmentIndex);
1183
1184 if (const MCSymbolWasm *C = Section.getGroup()) {
1185 Comdats[C->getName()].emplace_back(
1186 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1187 }
1188 } else {
1189 // Create custom sections
1190 assert(Sec.getKind().isMetadata());
1191
1192 StringRef Name = SectionName;
1193
1194 // For user-defined custom sections, strip the prefix
1195 if (Name.startswith(".custom_section."))
1196 Name = Name.substr(strlen(".custom_section."));
1197
1198 MCSymbol* Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001199 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001200 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001201 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001202 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001203 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001204 }
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001205 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001206 }
Sam Clegg759631c2017-09-15 20:54:59 +00001207 }
1208
Nicholas Wilson586320c2018-02-28 17:19:48 +00001209 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001210 for (const MCSymbol &S : Asm.symbols()) {
1211 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1212 // or used in relocations.
1213 if (S.isTemporary() && S.getName().empty())
1214 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001215
Dan Gohmand934cb82017-02-24 23:18:00 +00001216 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001217 LLVM_DEBUG(
1218 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1219 << " isDefined=" << S.isDefined() << " isExternal="
1220 << S.isExternal() << " isTemporary=" << S.isTemporary()
1221 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1222 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001223
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001224 if (WS.isVariable())
1225 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001226 if (WS.isComdat() && !WS.isDefined())
1227 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001228
Dan Gohmand934cb82017-02-24 23:18:00 +00001229 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001230 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001231 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001232 if (WS.getOffset() != 0)
1233 report_fatal_error(
1234 "function sections must contain one function each");
1235
1236 if (WS.getSize() == 0)
1237 report_fatal_error(
1238 "function symbols must have a size set with .size");
1239
Sam Clegg6c899ba2018-02-23 05:08:34 +00001240 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001241 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001242 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001243 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001244 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001245 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001246 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001247
1248 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1249 if (const MCSymbolWasm *C = Section.getGroup()) {
1250 Comdats[C->getName()].emplace_back(
1251 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1252 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001253 } else {
1254 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001255 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001256 }
1257
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001258 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001259 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001260 if (WS.isTemporary() && !WS.getSize())
1261 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001262
Sam Clegg6c899ba2018-02-23 05:08:34 +00001263 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001264 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1265 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001266 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001267 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001268
Sam Cleggfe6414b2017-06-21 23:46:41 +00001269 if (!WS.getSize())
1270 report_fatal_error("data symbols must have a size set with .size: " +
1271 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001272
Sam Cleggfe6414b2017-06-21 23:46:41 +00001273 int64_t Size = 0;
1274 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1275 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001276
Sam Clegg759631c2017-09-15 20:54:59 +00001277 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001278 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001279
Sam Clegg6c899ba2018-02-23 05:08:34 +00001280 // For each data symbol, export it in the symtab as a reference to the
1281 // corresponding Wasm data segment.
1282 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1283 DataSection.getSegmentIndex(),
1284 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1285 static_cast<uint32_t>(Size)};
1286 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001287 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001288 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001289 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001290 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001291 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001292
Eric Christopher545932b2018-02-23 21:14:47 +00001293 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001294 LLVM_DEBUG(dbgs() << " -> global index: "
1295 << WasmIndices.find(&WS)->second << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001296 } else {
1297 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001298 }
1299 }
1300
Nicholas Wilson586320c2018-02-28 17:19:48 +00001301 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1302 // process these in a separate pass because we need to have processed the
1303 // target of the alias before the alias itself and the symbols are not
1304 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001305 for (const MCSymbol &S : Asm.symbols()) {
1306 if (!S.isVariable())
1307 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001308
Sam Cleggcd65f692018-01-11 23:59:16 +00001309 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001310
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001311 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001312 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1313 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001314 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1315 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001316
Sam Clegg6c899ba2018-02-23 05:08:34 +00001317 if (WS.isFunction()) {
1318 assert(WasmIndices.count(ResolvedSym) > 0);
1319 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1320 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001321 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001322 } else if (WS.isData()) {
1323 assert(DataLocations.count(ResolvedSym) > 0);
1324 const wasm::WasmDataReference &Ref =
1325 DataLocations.find(ResolvedSym)->second;
1326 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001327 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001328 } else {
1329 report_fatal_error("don't yet support global aliases");
1330 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001331 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001332
Nicholas Wilson586320c2018-02-28 17:19:48 +00001333 // Finally, populate the symbol table itself, in its "natural" order.
1334 for (const MCSymbol &S : Asm.symbols()) {
1335 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001336 if (!isInSymtab(WS)) {
1337 WS.setIndex(INVALID_INDEX);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001338 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001339 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001340 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001341
1342 uint32_t Flags = 0;
1343 if (WS.isWeak())
1344 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1345 if (WS.isHidden())
1346 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1347 if (!WS.isExternal() && WS.isDefined())
1348 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1349 if (WS.isUndefined())
1350 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1351
1352 wasm::WasmSymbolInfo Info;
1353 Info.Name = WS.getName();
1354 Info.Kind = WS.getType();
1355 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001356 if (!WS.isData()) {
1357 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001358 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001359 } else if (WS.isDefined()) {
1360 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001361 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001362 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001363 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001364 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001365 }
1366
Sam Clegg6006e092017-12-22 20:31:39 +00001367 {
1368 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001369 // Functions referenced by a relocation need to put in the table. This is
1370 // purely to make the object file's provisional values readable, and is
1371 // ignored by the linker, which re-calculates the relocations itself.
1372 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1373 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1374 return;
1375 assert(Rel.Symbol->isFunction());
1376 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001377 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001378 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1379 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001380 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1381 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001382 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001383 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001384 }
1385 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001386
Sam Clegg6006e092017-12-22 20:31:39 +00001387 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1388 HandleReloc(RelEntry);
1389 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1390 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001391 }
1392
Sam Cleggbafe6902017-12-15 00:17:10 +00001393 // Translate .init_array section contents into start functions.
1394 for (const MCSection &S : Asm) {
1395 const auto &WS = static_cast<const MCSectionWasm &>(S);
1396 if (WS.getSectionName().startswith(".fini_array"))
1397 report_fatal_error(".fini_array sections are unsupported");
1398 if (!WS.getSectionName().startswith(".init_array"))
1399 continue;
1400 if (WS.getFragmentList().empty())
1401 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001402
1403 // init_array is expected to contain a single non-empty data fragment
1404 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001405 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001406
1407 auto IT = WS.begin();
1408 const MCFragment &EmptyFrag = *IT;
1409 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1410 report_fatal_error(".init_array section should be aligned");
1411
1412 IT = std::next(IT);
1413 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001414 if (AlignFrag.getKind() != MCFragment::FT_Align)
1415 report_fatal_error(".init_array section should be aligned");
1416 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1417 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001418
1419 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001420 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1421 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001422
Sam Cleggbafe6902017-12-15 00:17:10 +00001423 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001424 unsigned PrefixLength = strlen(".init_array");
1425 if (WS.getSectionName().size() > PrefixLength) {
1426 if (WS.getSectionName()[PrefixLength] != '.')
Sam Cleggbafe6902017-12-15 00:17:10 +00001427 report_fatal_error(".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001428 if (WS.getSectionName()
1429 .substr(PrefixLength + 1)
1430 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001431 report_fatal_error("invalid .init_array section priority");
1432 }
1433 const auto &DataFrag = cast<MCDataFragment>(Frag);
1434 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1435 for (const uint8_t *p = (const uint8_t *)Contents.data(),
1436 *end = (const uint8_t *)Contents.data() + Contents.size();
1437 p != end; ++p) {
1438 if (*p != 0)
1439 report_fatal_error("non-symbolic data in .init_array section");
1440 }
1441 for (const MCFixup &Fixup : DataFrag.getFixups()) {
1442 assert(Fixup.getKind() == MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1443 const MCExpr *Expr = Fixup.getValue();
1444 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1445 if (!Sym)
1446 report_fatal_error("fixups in .init_array should be symbol references");
1447 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1448 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001449 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1450 report_fatal_error("symbols in .init_array should exist in symbtab");
1451 InitFuncs.push_back(
1452 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001453 }
1454 }
1455
Dan Gohman18eafb62017-02-22 01:23:18 +00001456 // Write out the Wasm header.
1457 writeHeader(Asm);
1458
Sam Clegg9e15f352017-06-03 02:01:24 +00001459 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001460 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001461 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001462 // Skip the "table" section; we import the table instead.
1463 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001464 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001465 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001466 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001467 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001468 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001469 writeCustomSections(Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001470 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001471 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1472 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001473 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001474
Dan Gohmand934cb82017-02-24 23:18:00 +00001475 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001476 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001477}
1478
Lang Hames60fbc7c2017-10-10 16:28:07 +00001479std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001480llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1481 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001482 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001483}