blob: 2c28f01958f653431aa032a7200754d07eae9546 [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 {
Heejin Ahnf208f632018-09-05 01:27:38 +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 {
Heejin Ahnf208f632018-09-05 01:27:38 +0000166 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
167 << ", 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 Clegg9f3fe422018-01-17 19:28:43 +0000273 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000274 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000275 MCObjectWriter::reset();
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
Heejin Ahnf208f632018-09-05 01:27:38 +0000294 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000295
Sam Clegg457fb0b2017-09-15 19:50:44 +0000296 void writeTypeSection(ArrayRef<WasmFunctionType> FunctionTypes);
Sam Clegg8defa952018-02-12 22:41:29 +0000297 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000298 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000299 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000300 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000301 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000302 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000303 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000304 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000305 void writeDataSection();
Sam Clegg6f08c842018-04-24 18:11:36 +0000306 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000307 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000308 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000309 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000310 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000311 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000312 void writeCustomSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
313 void writeCustomRelocSections();
314 void
315 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
316 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000317
Sam Clegg7c395942017-09-14 23:07:53 +0000318 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000319 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
320 uint64_t ContentsOffset);
321
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000322 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000323 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
324 uint32_t registerFunctionType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000325};
Sam Clegg9e15f352017-06-03 02:01:24 +0000326
Dan Gohman18eafb62017-02-22 01:23:18 +0000327} // end anonymous namespace
328
329WasmObjectWriter::~WasmObjectWriter() {}
330
Dan Gohmand934cb82017-02-24 23:18:00 +0000331// Write out a section header and a patchable section size field.
332void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000333 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000334 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000335 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000336
Peter Collingbournef17b1492018-05-21 18:17:42 +0000337 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000338
339 // The section size. We don't know the size yet, so reserve enough space
340 // for any 32-bit value; we'll patch it later.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000341 encodeULEB128(UINT32_MAX, W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000342
343 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000344 Section.ContentsOffset = W.OS.tell();
345 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000346 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000347}
Dan Gohmand934cb82017-02-24 23:18:00 +0000348
Sam Clegg2322a932018-04-23 19:16:19 +0000349void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
350 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000351 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000352 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000353
354 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000355 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000356
Dan Gohmand934cb82017-02-24 23:18:00 +0000357 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000358 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000359
360 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000361 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000362}
363
364// Now that the section is complete and we know how big it is, patch up the
365// section size field at the start of the section.
366void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000367 uint64_t Size = W.OS.tell() - Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000368 if (uint32_t(Size) != Size)
369 report_fatal_error("section size does not fit in a uint32_t");
370
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000371 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000372
373 // Write the final section size to the payload_len field, which follows
374 // the section id byte.
375 uint8_t Buffer[16];
Sam Clegg66a99e42017-09-15 20:34:47 +0000376 unsigned SizeLen = encodeULEB128(Size, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000377 assert(SizeLen == 5);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000378 static_cast<raw_pwrite_stream &>(W.OS).pwrite((char *)Buffer, SizeLen,
379 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000380}
381
Dan Gohman18eafb62017-02-22 01:23:18 +0000382// Emit the Wasm header.
383void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000384 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
385 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000386}
387
388void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
389 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000390 // Build a map of sections to the function that defines them, for use
391 // in recordRelocation.
392 for (const MCSymbol &S : Asm.symbols()) {
393 const auto &WS = static_cast<const MCSymbolWasm &>(S);
394 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
395 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
396 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
397 if (!Pair.second)
398 report_fatal_error("section already has a defining function: " +
399 Sec.getSectionName());
400 }
401 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000402}
403
404void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
405 const MCAsmLayout &Layout,
406 const MCFragment *Fragment,
407 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000408 uint64_t &FixedValue) {
409 MCAsmBackend &Backend = Asm.getBackend();
410 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
411 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000412 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000413 uint64_t C = Target.getConstant();
414 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
415 MCContext &Ctx = Asm.getContext();
416
Sam Cleggbafe6902017-12-15 00:17:10 +0000417 // The .init_array isn't translated as data, so don't do relocations in it.
418 if (FixupSection.getSectionName().startswith(".init_array"))
419 return;
420
Dan Gohmand934cb82017-02-24 23:18:00 +0000421 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
422 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
423 "Should not have constructed this");
424
425 // Let A, B and C being the components of Target and R be the location of
426 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
427 // If it is pcrel, we want to compute (A - B + C - R).
428
429 // In general, Wasm has no relocations for -B. It can only represent (A + C)
430 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
431 // replace B to implement it: (A - R - K + C)
432 if (IsPCRel) {
433 Ctx.reportError(
434 Fixup.getLoc(),
435 "No relocation available to represent this relative expression");
436 return;
437 }
438
439 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
440
441 if (SymB.isUndefined()) {
442 Ctx.reportError(Fixup.getLoc(),
443 Twine("symbol '") + SymB.getName() +
444 "' can not be undefined in a subtraction expression");
445 return;
446 }
447
448 assert(!SymB.isAbsolute() && "Should have been folded");
449 const MCSection &SecB = SymB.getSection();
450 if (&SecB != &FixupSection) {
451 Ctx.reportError(Fixup.getLoc(),
452 "Cannot represent a difference across sections");
453 return;
454 }
455
456 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
457 uint64_t K = SymBOffset - FixupOffset;
458 IsPCRel = true;
459 C -= K;
460 }
461
462 // We either rejected the fixup or folded B into C at this point.
463 const MCSymbolRefExpr *RefA = Target.getSymA();
464 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
465
Dan Gohmand934cb82017-02-24 23:18:00 +0000466 if (SymA && SymA->isVariable()) {
467 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000468 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
469 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
470 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000471 }
472
473 // Put any constant offset in an addend. Offsets can be negative, and
474 // LLVM expects wrapping, in contrast to wasm's immediates which can't
475 // be negative and don't wrap.
476 FixedValue = 0;
477
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000478 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000479 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000480 assert(SymA);
481
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000482 // Absolute offset within a section or a function.
483 // Currently only supported for for metadata sections.
484 // See: test/MC/WebAssembly/blockaddress.ll
485 if (Type == wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32 ||
486 Type == wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32) {
487 if (!FixupSection.getKind().isMetadata())
488 report_fatal_error("relocations for function or section offsets are "
489 "only supported in metadata sections");
490
491 const MCSymbol *SectionSymbol = nullptr;
492 const MCSection &SecA = SymA->getSection();
493 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000494 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000495 else
496 SectionSymbol = SecA.getBeginSymbol();
497 if (!SectionSymbol)
498 report_fatal_error("section symbol is required for relocation");
499
500 C += Layout.getSymbolOffset(*SymA);
501 SymA = cast<MCSymbolWasm>(SectionSymbol);
502 }
503
504 // Relocation other than R_WEBASSEMBLY_TYPE_INDEX_LEB are required to be
505 // against a named symbol.
506 if (Type != wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
507 if (SymA->getName().empty())
508 report_fatal_error("relocations against un-named temporaries are not yet "
509 "supported by wasm");
510
511 SymA->setUsedInReloc();
512 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000513
Dan Gohmand934cb82017-02-24 23:18:00 +0000514 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000515 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000516
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000517 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000518 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000519 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000520 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000521 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000522 CustomSectionsRelocations[&FixupSection].push_back(Rec);
523 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000524 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000525 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000526}
527
Dan Gohmand934cb82017-02-24 23:18:00 +0000528// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
529// to allow patching.
Heejin Ahnf208f632018-09-05 01:27:38 +0000530static void WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
531 uint64_t Offset) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000532 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000533 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000534 assert(SizeLen == 5);
535 Stream.pwrite((char *)Buffer, SizeLen, Offset);
536}
537
538// Write X as an signed LEB value at offset Offset in Stream, padded
539// to allow patching.
Heejin Ahnf208f632018-09-05 01:27:38 +0000540static void WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
541 uint64_t Offset) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000542 uint8_t Buffer[5];
Sam Clegg66a99e42017-09-15 20:34:47 +0000543 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000544 assert(SizeLen == 5);
545 Stream.pwrite((char *)Buffer, SizeLen, Offset);
546}
547
548// Write X as a plain integer value at offset Offset in Stream.
549static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
550 uint8_t Buffer[4];
551 support::endian::write32le(Buffer, X);
552 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
553}
554
Heejin Ahnf208f632018-09-05 01:27:38 +0000555static const MCSymbolWasm *ResolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000556 if (Symbol.isVariable()) {
557 const MCExpr *Expr = Symbol.getVariableValue();
558 auto *Inner = cast<MCSymbolRefExpr>(Expr);
559 return cast<MCSymbolWasm>(&Inner->getSymbol());
560 }
561 return &Symbol;
562}
563
Dan Gohmand934cb82017-02-24 23:18:00 +0000564// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000565// by RelEntry. This value isn't used by the static linker; it just serves
566// to make the object format more readable and more likely to be directly
567// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000568uint32_t
569WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000570 switch (RelEntry.Type) {
571 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
Sam Cleggf9edbe92018-01-31 19:28:47 +0000572 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: {
573 // Provisional value is table address of the resolved symbol itself
574 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
575 assert(Sym->isFunction());
576 return TableIndices[Sym];
577 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000578 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000579 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000580 return getRelocationIndexValue(RelEntry);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000581 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
582 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
583 // Provisional value is function/global Wasm index
584 if (!WasmIndices.count(RelEntry.Symbol))
585 report_fatal_error("symbol not found in wasm index space: " +
586 RelEntry.Symbol->getName());
587 return WasmIndices[RelEntry.Symbol];
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000588 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
589 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000590 const auto &Section =
591 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
592 return Section.getSectionOffset() + RelEntry.Addend;
593 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000594 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
595 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
596 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000597 // Provisional value is address of the global
Sam Clegg60ec3032018-01-23 01:23:17 +0000598 const MCSymbolWasm *Sym = ResolveSymbol(*RelEntry.Symbol);
599 // For undefined symbols, use zero
600 if (!Sym->isDefined())
601 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000602 const wasm::WasmDataReference &Ref = DataLocations[Sym];
603 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000604 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000605 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000606 }
607 default:
608 llvm_unreachable("invalid relocation type");
609 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000610}
611
Sam Clegg759631c2017-09-15 20:54:59 +0000612static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000613 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000614 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000615
Sam Clegg63ebb812017-09-29 16:50:08 +0000616 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
617
Sam Clegg759631c2017-09-15 20:54:59 +0000618 for (const MCFragment &Frag : DataSection) {
619 if (Frag.hasInstructions())
620 report_fatal_error("only data supported in data sections");
621
622 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
623 if (Align->getValueSize() != 1)
624 report_fatal_error("only byte values supported for alignment");
625 // If nops are requested, use zeros, as this is the data section.
626 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000627 uint64_t Size =
628 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
629 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000630 DataBytes.resize(Size, Value);
631 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000632 int64_t NumValues;
633 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000634 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000635 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
636 Fill->getValue());
Sam Clegg759631c2017-09-15 20:54:59 +0000637 } else {
638 const auto &DataFrag = cast<MCDataFragment>(Frag);
639 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
640
641 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
642 }
643 }
644
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000645 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000646}
647
Sam Clegg60ec3032018-01-23 01:23:17 +0000648uint32_t
649WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
650 if (RelEntry.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000651 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000652 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000653 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000654 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000655 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000656
Sam Clegg25d8e682018-05-08 00:08:21 +0000657 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000658}
659
Dan Gohmand934cb82017-02-24 23:18:00 +0000660// Apply the portions of the relocation records that we can handle ourselves
661// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000662void WasmObjectWriter::applyRelocations(
663 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000664 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000665 for (const WasmRelocationEntry &RelEntry : Relocations) {
666 uint64_t Offset = ContentsOffset +
667 RelEntry.FixupSection->getSectionOffset() +
668 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000669
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000670 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000671 uint32_t Value = getProvisionalValue(RelEntry);
672
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000673 switch (RelEntry.Type) {
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000674 case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000675 case wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB:
Sam Clegg60ec3032018-01-23 01:23:17 +0000676 case wasm::R_WEBASSEMBLY_GLOBAL_INDEX_LEB:
677 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_LEB:
Dan Gohmand934cb82017-02-24 23:18:00 +0000678 WritePatchableLEB(Stream, Value, Offset);
679 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000680 case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32:
681 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_I32:
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000682 case wasm::R_WEBASSEMBLY_FUNCTION_OFFSET_I32:
683 case wasm::R_WEBASSEMBLY_SECTION_OFFSET_I32:
Dan Gohmand934cb82017-02-24 23:18:00 +0000684 WriteI32(Stream, Value, Offset);
685 break;
Sam Clegg60ec3032018-01-23 01:23:17 +0000686 case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB:
687 case wasm::R_WEBASSEMBLY_MEMORY_ADDR_SLEB:
688 WritePatchableSLEB(Stream, Value, Offset);
689 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000690 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000691 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000692 }
693 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000694}
695
Sam Clegg9e15f352017-06-03 02:01:24 +0000696void WasmObjectWriter::writeTypeSection(
Sam Clegg457fb0b2017-09-15 19:50:44 +0000697 ArrayRef<WasmFunctionType> FunctionTypes) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000698 if (FunctionTypes.empty())
699 return;
700
701 SectionBookkeeping Section;
702 startSection(Section, wasm::WASM_SEC_TYPE);
703
Peter Collingbournef17b1492018-05-21 18:17:42 +0000704 encodeULEB128(FunctionTypes.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000705
706 for (const WasmFunctionType &FuncTy : FunctionTypes) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000707 W.OS << char(wasm::WASM_TYPE_FUNC);
708 encodeULEB128(FuncTy.Params.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000709 for (wasm::ValType Ty : FuncTy.Params)
710 writeValueType(Ty);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000711 encodeULEB128(FuncTy.Returns.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712 for (wasm::ValType Ty : FuncTy.Returns)
713 writeValueType(Ty);
714 }
715
716 endSection(Section);
717}
718
Sam Clegg8defa952018-02-12 22:41:29 +0000719void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000720 uint32_t DataSize,
721 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000722 if (Imports.empty())
723 return;
724
Sam Cleggf950b242017-12-11 23:03:38 +0000725 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
726
Sam Clegg9e15f352017-06-03 02:01:24 +0000727 SectionBookkeeping Section;
728 startSection(Section, wasm::WASM_SEC_IMPORT);
729
Peter Collingbournef17b1492018-05-21 18:17:42 +0000730 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000731 for (const wasm::WasmImport &Import : Imports) {
732 writeString(Import.Module);
733 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000734 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000735
736 switch (Import.Kind) {
737 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000738 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000739 break;
740 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 W.OS << char(Import.Global.Type);
742 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000743 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000744 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000745 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000746 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000747 break;
748 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000750 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000751 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000752 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000753 default:
754 llvm_unreachable("unsupported import kind");
755 }
756 }
757
758 endSection(Section);
759}
760
Sam Clegg457fb0b2017-09-15 19:50:44 +0000761void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000762 if (Functions.empty())
763 return;
764
765 SectionBookkeeping Section;
766 startSection(Section, wasm::WASM_SEC_FUNCTION);
767
Peter Collingbournef17b1492018-05-21 18:17:42 +0000768 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000769 for (const WasmFunction &Func : Functions)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000770 encodeULEB128(Func.Type, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000771
772 endSection(Section);
773}
774
Sam Clegg7c395942017-09-14 23:07:53 +0000775void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000776 if (Globals.empty())
777 return;
778
779 SectionBookkeeping Section;
780 startSection(Section, wasm::WASM_SEC_GLOBAL);
781
Peter Collingbournef17b1492018-05-21 18:17:42 +0000782 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000783 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000784 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000785 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786
Peter Collingbournef17b1492018-05-21 18:17:42 +0000787 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
788 encodeSLEB128(Global.InitialValue, W.OS);
789 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000790 }
791
792 endSection(Section);
793}
794
Sam Clegg8defa952018-02-12 22:41:29 +0000795void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000796 if (Exports.empty())
797 return;
798
799 SectionBookkeeping Section;
800 startSection(Section, wasm::WASM_SEC_EXPORT);
801
Peter Collingbournef17b1492018-05-21 18:17:42 +0000802 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000803 for (const wasm::WasmExport &Export : Exports) {
804 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000805 W.OS << char(Export.Kind);
806 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000807 }
808
809 endSection(Section);
810}
811
Sam Clegg457fb0b2017-09-15 19:50:44 +0000812void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000813 if (TableElems.empty())
814 return;
815
816 SectionBookkeeping Section;
817 startSection(Section, wasm::WASM_SEC_ELEM);
818
Peter Collingbournef17b1492018-05-21 18:17:42 +0000819 encodeULEB128(1, W.OS); // number of "segments"
820 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000821
822 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000823 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
824 encodeSLEB128(kInitialTableOffset, W.OS);
825 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000826
Peter Collingbournef17b1492018-05-21 18:17:42 +0000827 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000828 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000829 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000830
831 endSection(Section);
832}
833
Sam Clegg457fb0b2017-09-15 19:50:44 +0000834void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
835 const MCAsmLayout &Layout,
836 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000837 if (Functions.empty())
838 return;
839
840 SectionBookkeeping Section;
841 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000842 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000843
Peter Collingbournef17b1492018-05-21 18:17:42 +0000844 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000845
846 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000847 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
Sam Clegg9e15f352017-06-03 02:01:24 +0000849 int64_t Size = 0;
850 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
851 report_fatal_error(".size expression must be evaluatable");
852
Peter Collingbournef17b1492018-05-21 18:17:42 +0000853 encodeULEB128(Size, W.OS);
854 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
855 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000856 }
857
Sam Clegg9e15f352017-06-03 02:01:24 +0000858 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000859 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000860
861 endSection(Section);
862}
863
Sam Clegg6c899ba2018-02-23 05:08:34 +0000864void WasmObjectWriter::writeDataSection() {
865 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000866 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000867
868 SectionBookkeeping Section;
869 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000870 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
Peter Collingbournef17b1492018-05-21 18:17:42 +0000872 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000873
Sam Clegg6c899ba2018-02-23 05:08:34 +0000874 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000875 encodeULEB128(0, W.OS); // memory index
876 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
877 encodeSLEB128(Segment.Offset, W.OS); // offset
878 W.OS << char(wasm::WASM_OPCODE_END);
879 encodeULEB128(Segment.Data.size(), W.OS); // size
880 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
881 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000882 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000883
884 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000885 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000886
887 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000888}
889
Sam Clegg6f08c842018-04-24 18:11:36 +0000890void WasmObjectWriter::writeRelocSection(
891 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000892 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000893 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
894 // for descriptions of the reloc sections.
895
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000896 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000897 return;
898
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000899 // First, ensure the relocations are sorted in offset order. In general they
900 // should already be sorted since `recordRelocation` is called in offset
901 // order, but for the code section we combine many MC sections into single
902 // wasm section, and this order is determined by the order of Asm.Symbols()
903 // not the sections order.
904 std::stable_sort(
905 Relocs.begin(), Relocs.end(),
906 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
907 return (A.Offset + A.FixupSection->getSectionOffset()) <
908 (B.Offset + B.FixupSection->getSectionOffset());
909 });
910
Sam Clegg9e15f352017-06-03 02:01:24 +0000911 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000912 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000913
Peter Collingbournef17b1492018-05-21 18:17:42 +0000914 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000915 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000916 for (const WasmRelocationEntry &RelEntry : Relocs) {
917 uint64_t Offset =
918 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000919 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000920
Peter Collingbournef17b1492018-05-21 18:17:42 +0000921 W.OS << char(RelEntry.Type);
922 encodeULEB128(Offset, W.OS);
923 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000924 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000925 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000926 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000927
928 endSection(Section);
929}
930
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000931void WasmObjectWriter::writeCustomRelocSections() {
932 for (const auto &Sec : CustomSections) {
933 auto &Relocations = CustomSectionsRelocations[Sec.Section];
934 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
935 }
936}
937
Sam Clegg9e15f352017-06-03 02:01:24 +0000938void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000939 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000940 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000941 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000942 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000943 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000944 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000945
Sam Clegg6bb5a412018-04-26 18:15:32 +0000946 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000947 if (SymbolInfos.size() != 0) {
948 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000949 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000950 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000951 encodeULEB128(Sym.Kind, W.OS);
952 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000953 switch (Sym.Kind) {
954 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
955 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000956 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000957 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
958 writeString(Sym.Name);
959 break;
960 case wasm::WASM_SYMBOL_TYPE_DATA:
961 writeString(Sym.Name);
962 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000963 encodeULEB128(Sym.DataRef.Segment, W.OS);
964 encodeULEB128(Sym.DataRef.Offset, W.OS);
965 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000966 }
967 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000968 case wasm::WASM_SYMBOL_TYPE_SECTION: {
969 const uint32_t SectionIndex =
970 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000971 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000972 break;
973 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000974 default:
975 llvm_unreachable("unexpected kind");
976 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000977 }
978 endSection(SubSection);
979 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000980
Sam Clegg6c899ba2018-02-23 05:08:34 +0000981 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000982 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000983 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000984 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000985 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000986 encodeULEB128(Segment.Alignment, W.OS);
987 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000988 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000989 endSection(SubSection);
990 }
991
Sam Cleggbafe6902017-12-15 00:17:10 +0000992 if (!InitFuncs.empty()) {
993 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000994 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000995 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000996 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +0000997 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +0000998 }
999 endSection(SubSection);
1000 }
1001
Sam Cleggea7cace2018-01-09 23:43:14 +00001002 if (Comdats.size()) {
1003 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001004 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001005 for (const auto &C : Comdats) {
1006 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001007 encodeULEB128(0, W.OS); // flags for future use
1008 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001009 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001010 encodeULEB128(Entry.Kind, W.OS);
1011 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001012 }
1013 }
1014 endSection(SubSection);
1015 }
1016
Sam Clegg9e15f352017-06-03 02:01:24 +00001017 endSection(Section);
1018}
1019
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001020void WasmObjectWriter::writeCustomSections(const MCAssembler &Asm,
1021 const MCAsmLayout &Layout) {
1022 for (auto &CustomSection : CustomSections) {
Sam Cleggcfd44a22018-04-05 17:01:39 +00001023 SectionBookkeeping Section;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001024 auto *Sec = CustomSection.Section;
Sam Clegg2322a932018-04-23 19:16:19 +00001025 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001026
Peter Collingbournef17b1492018-05-21 18:17:42 +00001027 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1028 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001029
1030 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1031 CustomSection.OutputIndex = Section.Index;
1032
Sam Cleggcfd44a22018-04-05 17:01:39 +00001033 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001034
1035 // Apply fixups.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001036 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1037 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001038 }
1039}
1040
Heejin Ahnf208f632018-09-05 01:27:38 +00001041uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001042 assert(Symbol.isFunction());
1043 assert(TypeIndices.count(&Symbol));
1044 return TypeIndices[&Symbol];
1045}
1046
Heejin Ahnf208f632018-09-05 01:27:38 +00001047uint32_t WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001048 assert(Symbol.isFunction());
1049
1050 WasmFunctionType F;
Heejin Ahnf208f632018-09-05 01:27:38 +00001051 const MCSymbolWasm *ResolvedSym = ResolveSymbol(Symbol);
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001052 F.Returns = ResolvedSym->getReturns();
1053 F.Params = ResolvedSym->getParams();
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001054
1055 auto Pair =
1056 FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size()));
1057 if (Pair.second)
1058 FunctionTypes.push_back(F);
1059 TypeIndices[&Symbol] = Pair.first->second;
1060
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001061 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1062 << " new:" << Pair.second << "\n");
1063 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001064 return Pair.first->second;
1065}
1066
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001067static bool isInSymtab(const MCSymbolWasm &Sym) {
1068 if (Sym.isUsedInReloc())
1069 return true;
1070
1071 if (Sym.isComdat() && !Sym.isDefined())
1072 return false;
1073
1074 if (Sym.isTemporary() && Sym.getName().empty())
1075 return false;
1076
1077 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1078 return false;
1079
1080 if (Sym.isSection())
1081 return false;
1082
1083 return true;
1084}
1085
Peter Collingbourne438390f2018-05-21 18:23:50 +00001086uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1087 const MCAsmLayout &Layout) {
1088 uint64_t StartOffset = W.OS.tell();
1089
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001090 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001091 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001092
1093 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001094 SmallVector<WasmFunction, 4> Functions;
1095 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001096 SmallVector<wasm::WasmImport, 4> Imports;
1097 SmallVector<wasm::WasmExport, 4> Exports;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001098 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001099 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001100 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001101 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001102
Sam Cleggf950b242017-12-11 23:03:38 +00001103 // For now, always emit the memory import, since loads and stores are not
1104 // valid without it. In the future, we could perhaps be more clever and omit
1105 // it if there are no loads or stores.
1106 MCSymbolWasm *MemorySym =
1107 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001108 wasm::WasmImport MemImport;
1109 MemImport.Module = MemorySym->getModuleName();
1110 MemImport.Field = MemorySym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001111 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1112 Imports.push_back(MemImport);
1113
1114 // For now, always emit the table section, since indirect calls are not
1115 // valid without it. In the future, we could perhaps be more clever and omit
1116 // it if there are no indirect calls.
1117 MCSymbolWasm *TableSym =
1118 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001119 wasm::WasmImport TableImport;
1120 TableImport.Module = TableSym->getModuleName();
1121 TableImport.Field = TableSym->getName();
Sam Cleggf950b242017-12-11 23:03:38 +00001122 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Sam Clegg8defa952018-02-12 22:41:29 +00001123 TableImport.Table.ElemType = wasm::WASM_TYPE_ANYFUNC;
Sam Cleggf950b242017-12-11 23:03:38 +00001124 Imports.push_back(TableImport);
1125
Nicholas Wilson586320c2018-02-28 17:19:48 +00001126 // Populate FunctionTypeIndices, and Imports and WasmIndices for undefined
1127 // symbols. This must be done before populating WasmIndices for defined
1128 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001129 for (const MCSymbol &S : Asm.symbols()) {
1130 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1131
1132 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001133 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001134 if (WS.isFunction())
1135 registerFunctionType(WS);
1136
1137 if (WS.isTemporary())
1138 continue;
1139
1140 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001141 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001142 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001143 wasm::WasmImport Import;
1144 Import.Module = WS.getModuleName();
1145 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001146 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001147 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001148 Imports.push_back(Import);
1149 WasmIndices[&WS] = NumFunctionImports++;
1150 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001151 if (WS.isWeak())
1152 report_fatal_error("undefined global symbol cannot be weak");
1153
Sam Clegg6c899ba2018-02-23 05:08:34 +00001154 wasm::WasmImport Import;
1155 Import.Module = WS.getModuleName();
1156 Import.Field = WS.getName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001157 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001158 Import.Global = WS.getGlobalType();
1159 Imports.push_back(Import);
1160 WasmIndices[&WS] = NumGlobalImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001161 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001162 }
1163 }
1164
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001165 // Populate DataSegments and CustomSections, which must be done before
1166 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001167 for (MCSection &Sec : Asm) {
1168 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001169 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001170
Sam Cleggbafe6902017-12-15 00:17:10 +00001171 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001172 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001173 continue;
1174
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001175 // Code is handled separately
1176 if (Section.getKind().isText())
1177 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001178
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001179 if (Section.isWasmData()) {
1180 uint32_t SegmentIndex = DataSegments.size();
1181 DataSize = alignTo(DataSize, Section.getAlignment());
1182 DataSegments.emplace_back();
1183 WasmDataSegment &Segment = DataSegments.back();
1184 Segment.Name = SectionName;
1185 Segment.Offset = DataSize;
1186 Segment.Section = &Section;
1187 addData(Segment.Data, Section);
1188 Segment.Alignment = Section.getAlignment();
1189 Segment.Flags = 0;
1190 DataSize += Segment.Data.size();
1191 Section.setSegmentIndex(SegmentIndex);
1192
1193 if (const MCSymbolWasm *C = Section.getGroup()) {
1194 Comdats[C->getName()].emplace_back(
1195 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1196 }
1197 } else {
1198 // Create custom sections
1199 assert(Sec.getKind().isMetadata());
1200
1201 StringRef Name = SectionName;
1202
1203 // For user-defined custom sections, strip the prefix
1204 if (Name.startswith(".custom_section."))
1205 Name = Name.substr(strlen(".custom_section."));
1206
Heejin Ahnf208f632018-09-05 01:27:38 +00001207 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001208 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001209 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001210 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001211 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001212 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001213 }
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001214 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001215 }
Sam Clegg759631c2017-09-15 20:54:59 +00001216 }
1217
Nicholas Wilson586320c2018-02-28 17:19:48 +00001218 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001219 for (const MCSymbol &S : Asm.symbols()) {
1220 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1221 // or used in relocations.
1222 if (S.isTemporary() && S.getName().empty())
1223 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001224
Dan Gohmand934cb82017-02-24 23:18:00 +00001225 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001226 LLVM_DEBUG(
1227 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1228 << " isDefined=" << S.isDefined() << " isExternal="
1229 << S.isExternal() << " isTemporary=" << S.isTemporary()
1230 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1231 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001232
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001233 if (WS.isVariable())
1234 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001235 if (WS.isComdat() && !WS.isDefined())
1236 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001237
Dan Gohmand934cb82017-02-24 23:18:00 +00001238 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001239 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001240 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001241 if (WS.getOffset() != 0)
1242 report_fatal_error(
1243 "function sections must contain one function each");
1244
1245 if (WS.getSize() == 0)
1246 report_fatal_error(
1247 "function symbols must have a size set with .size");
1248
Sam Clegg6c899ba2018-02-23 05:08:34 +00001249 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001250 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001251 WasmFunction Func;
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001252 Func.Type = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001253 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001254 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001255 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001256
1257 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1258 if (const MCSymbolWasm *C = Section.getGroup()) {
1259 Comdats[C->getName()].emplace_back(
1260 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1261 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001262 } else {
1263 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001264 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001265 }
1266
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001267 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001268 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001269 if (WS.isTemporary() && !WS.getSize())
1270 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001271
Sam Clegg6c899ba2018-02-23 05:08:34 +00001272 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001273 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1274 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001275 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001276 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001277
Sam Cleggfe6414b2017-06-21 23:46:41 +00001278 if (!WS.getSize())
1279 report_fatal_error("data symbols must have a size set with .size: " +
1280 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001281
Sam Cleggfe6414b2017-06-21 23:46:41 +00001282 int64_t Size = 0;
1283 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1284 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001285
Sam Clegg759631c2017-09-15 20:54:59 +00001286 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001287 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001288
Sam Clegg6c899ba2018-02-23 05:08:34 +00001289 // For each data symbol, export it in the symtab as a reference to the
1290 // corresponding Wasm data segment.
1291 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1292 DataSection.getSegmentIndex(),
1293 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1294 static_cast<uint32_t>(Size)};
1295 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001296 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001297 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001298 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001299 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001300 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001301
Eric Christopher545932b2018-02-23 21:14:47 +00001302 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001303 LLVM_DEBUG(dbgs() << " -> global index: "
1304 << WasmIndices.find(&WS)->second << "\n");
Sam Clegga165f2d2018-04-30 19:40:57 +00001305 } else {
1306 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001307 }
1308 }
1309
Nicholas Wilson586320c2018-02-28 17:19:48 +00001310 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1311 // process these in a separate pass because we need to have processed the
1312 // target of the alias before the alias itself and the symbols are not
1313 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001314 for (const MCSymbol &S : Asm.symbols()) {
1315 if (!S.isVariable())
1316 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001317
Sam Cleggcd65f692018-01-11 23:59:16 +00001318 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001319
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001320 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001321 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1322 const MCSymbolWasm *ResolvedSym = ResolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001323 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1324 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001325
Sam Clegg6c899ba2018-02-23 05:08:34 +00001326 if (WS.isFunction()) {
1327 assert(WasmIndices.count(ResolvedSym) > 0);
1328 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1329 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001330 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001331 } else if (WS.isData()) {
1332 assert(DataLocations.count(ResolvedSym) > 0);
1333 const wasm::WasmDataReference &Ref =
1334 DataLocations.find(ResolvedSym)->second;
1335 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001336 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001337 } else {
1338 report_fatal_error("don't yet support global aliases");
1339 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001340 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001341
Nicholas Wilson586320c2018-02-28 17:19:48 +00001342 // Finally, populate the symbol table itself, in its "natural" order.
1343 for (const MCSymbol &S : Asm.symbols()) {
1344 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001345 if (!isInSymtab(WS)) {
1346 WS.setIndex(INVALID_INDEX);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001347 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001348 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001349 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001350
1351 uint32_t Flags = 0;
1352 if (WS.isWeak())
1353 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1354 if (WS.isHidden())
1355 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1356 if (!WS.isExternal() && WS.isDefined())
1357 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1358 if (WS.isUndefined())
1359 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1360
1361 wasm::WasmSymbolInfo Info;
1362 Info.Name = WS.getName();
1363 Info.Kind = WS.getType();
1364 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001365 if (!WS.isData()) {
1366 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001367 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001368 } else if (WS.isDefined()) {
1369 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001370 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001371 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001372 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001373 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001374 }
1375
Sam Clegg6006e092017-12-22 20:31:39 +00001376 {
1377 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001378 // Functions referenced by a relocation need to put in the table. This is
1379 // purely to make the object file's provisional values readable, and is
1380 // ignored by the linker, which re-calculates the relocations itself.
1381 if (Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_I32 &&
1382 Rel.Type != wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB)
1383 return;
1384 assert(Rel.Symbol->isFunction());
1385 const MCSymbolWasm &WS = *ResolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001386 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001387 uint32_t TableIndex = TableElems.size() + kInitialTableOffset;
1388 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001389 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1390 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001391 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001392 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001393 }
1394 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001395
Sam Clegg6006e092017-12-22 20:31:39 +00001396 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1397 HandleReloc(RelEntry);
1398 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1399 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001400 }
1401
Sam Cleggbafe6902017-12-15 00:17:10 +00001402 // Translate .init_array section contents into start functions.
1403 for (const MCSection &S : Asm) {
1404 const auto &WS = static_cast<const MCSectionWasm &>(S);
1405 if (WS.getSectionName().startswith(".fini_array"))
1406 report_fatal_error(".fini_array sections are unsupported");
1407 if (!WS.getSectionName().startswith(".init_array"))
1408 continue;
1409 if (WS.getFragmentList().empty())
1410 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001411
1412 // init_array is expected to contain a single non-empty data fragment
1413 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001414 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001415
1416 auto IT = WS.begin();
1417 const MCFragment &EmptyFrag = *IT;
1418 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1419 report_fatal_error(".init_array section should be aligned");
1420
1421 IT = std::next(IT);
1422 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001423 if (AlignFrag.getKind() != MCFragment::FT_Align)
1424 report_fatal_error(".init_array section should be aligned");
1425 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1426 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001427
1428 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001429 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1430 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001431
Sam Cleggbafe6902017-12-15 00:17:10 +00001432 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001433 unsigned PrefixLength = strlen(".init_array");
1434 if (WS.getSectionName().size() > PrefixLength) {
1435 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001436 report_fatal_error(
1437 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001438 if (WS.getSectionName()
1439 .substr(PrefixLength + 1)
1440 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001441 report_fatal_error("invalid .init_array section priority");
1442 }
1443 const auto &DataFrag = cast<MCDataFragment>(Frag);
1444 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001445 for (const uint8_t *
1446 p = (const uint8_t *)Contents.data(),
1447 *end = (const uint8_t *)Contents.data() + Contents.size();
Sam Cleggbafe6902017-12-15 00:17:10 +00001448 p != end; ++p) {
1449 if (*p != 0)
1450 report_fatal_error("non-symbolic data in .init_array section");
1451 }
1452 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001453 assert(Fixup.getKind() ==
1454 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001455 const MCExpr *Expr = Fixup.getValue();
1456 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1457 if (!Sym)
1458 report_fatal_error("fixups in .init_array should be symbol references");
1459 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1460 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001461 if (Sym->getSymbol().getIndex() == INVALID_INDEX)
1462 report_fatal_error("symbols in .init_array should exist in symbtab");
1463 InitFuncs.push_back(
1464 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001465 }
1466 }
1467
Dan Gohman18eafb62017-02-22 01:23:18 +00001468 // Write out the Wasm header.
1469 writeHeader(Asm);
1470
Sam Clegg9e15f352017-06-03 02:01:24 +00001471 writeTypeSection(FunctionTypes);
Sam Cleggf950b242017-12-11 23:03:38 +00001472 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001473 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001474 // Skip the "table" section; we import the table instead.
1475 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001476 writeGlobalSection();
Sam Clegg9e15f352017-06-03 02:01:24 +00001477 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001478 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001479 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001480 writeDataSection();
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001481 writeCustomSections(Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001482 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001483 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1484 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001485 writeCustomRelocSections();
Dan Gohman970d02c2017-03-30 23:58:19 +00001486
Dan Gohmand934cb82017-02-24 23:18:00 +00001487 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001488 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001489}
1490
Lang Hames60fbc7c2017-10-10 16:28:07 +00001491std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001492llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1493 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001494 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001495}