blob: 00d48659890bdc6f85ee0df68c5f994ab972ea72 [file] [log] [blame]
Dan Gohman18eafb62017-02-22 01:23:18 +00001//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Dan Gohman18eafb62017-02-22 01:23:18 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Wasm object file writer information.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SmallPtrSet.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000015#include "llvm/BinaryFormat/Wasm.h"
Nico Weber432a3882018-04-30 14:59:11 +000016#include "llvm/Config/llvm-config.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000017#include "llvm/MC/MCAsmBackend.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000018#include "llvm/MC/MCAsmLayout.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCExpr.h"
22#include "llvm/MC/MCFixupKindInfo.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000023#include "llvm/MC/MCObjectWriter.h"
24#include "llvm/MC/MCSectionWasm.h"
25#include "llvm/MC/MCSymbolWasm.h"
26#include "llvm/MC/MCValue.h"
27#include "llvm/MC/MCWasmObjectWriter.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000028#include "llvm/Support/Casting.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000029#include "llvm/Support/Debug.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000030#include "llvm/Support/ErrorHandling.h"
Dan Gohmand934cb82017-02-24 23:18:00 +000031#include "llvm/Support/LEB128.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000032#include "llvm/Support/StringSaver.h"
33#include <vector>
34
35using namespace llvm;
36
Sam Clegg5e3d33a2017-07-07 02:01:29 +000037#define DEBUG_TYPE "mc"
Dan Gohman18eafb62017-02-22 01:23:18 +000038
39namespace {
Sam Clegg9e15f352017-06-03 02:01:24 +000040
Sam Clegg30e1bbc2018-01-19 18:57:01 +000041// Went we ceate the indirect function table we start at 1, so that there is
42// and emtpy slot at 0 and therefore calling a null function pointer will trap.
Heejin Ahn18c56a02019-02-04 19:13:39 +000043static const uint32_t InitialTableOffset = 1;
Sam Clegg30e1bbc2018-01-19 18:57:01 +000044
Dan Gohmand934cb82017-02-24 23:18:00 +000045// For patching purposes, we need to remember where each section starts, both
46// for patching up the section size field, and for patching up references to
47// locations within the section.
48struct SectionBookkeeping {
49 // Where the size of the section is written.
50 uint64_t SizeOffset;
Sam Clegg6a31a0d2018-04-26 19:27:28 +000051 // Where the section header ends (without custom section name).
52 uint64_t PayloadOffset;
53 // Where the contents of the section starts.
Dan Gohmand934cb82017-02-24 23:18:00 +000054 uint64_t ContentsOffset;
Sam Clegg6f08c842018-04-24 18:11:36 +000055 uint32_t Index;
Dan Gohmand934cb82017-02-24 23:18:00 +000056};
57
Heejin Ahnda419bd2018-11-14 02:46:21 +000058// The signature of a wasm function or event, in a struct capable of being used
59// as a DenseMap key.
60// TODO: Consider using wasm::WasmSignature directly instead.
61struct WasmSignature {
Sam Clegg9e15f352017-06-03 02:01:24 +000062 // Support empty and tombstone instances, needed by DenseMap.
Heejin Ahn18c56a02019-02-04 19:13:39 +000063 enum { Plain, Empty, Tombstone } State = Plain;
Sam Clegg9e15f352017-06-03 02:01:24 +000064
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
Heejin Ahnda419bd2018-11-14 02:46:21 +000071 bool operator==(const WasmSignature &Other) const {
Sam Clegg9e15f352017-06-03 02:01:24 +000072 return State == Other.State && Returns == Other.Returns &&
73 Params == Other.Params;
74 }
75};
76
Heejin Ahnda419bd2018-11-14 02:46:21 +000077// Traits for using WasmSignature in a DenseMap.
78struct WasmSignatureDenseMapInfo {
79 static WasmSignature getEmptyKey() {
80 WasmSignature Sig;
81 Sig.State = WasmSignature::Empty;
82 return Sig;
Sam Clegg9e15f352017-06-03 02:01:24 +000083 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000084 static WasmSignature getTombstoneKey() {
85 WasmSignature Sig;
86 Sig.State = WasmSignature::Tombstone;
87 return Sig;
Sam Clegg9e15f352017-06-03 02:01:24 +000088 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000089 static unsigned getHashValue(const WasmSignature &Sig) {
90 uintptr_t Value = Sig.State;
91 for (wasm::ValType Ret : Sig.Returns)
Heejin Ahn48089142018-11-02 19:25:09 +000092 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
Heejin Ahnda419bd2018-11-14 02:46:21 +000093 for (wasm::ValType Param : Sig.Params)
Heejin Ahn48089142018-11-02 19:25:09 +000094 Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
Sam Clegg9e15f352017-06-03 02:01:24 +000095 return Value;
96 }
Heejin Ahnda419bd2018-11-14 02:46:21 +000097 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
Sam Clegg9e15f352017-06-03 02:01:24 +000098 return LHS == RHS;
99 }
100};
101
Sam Clegg7c395942017-09-14 23:07:53 +0000102// A wasm data segment. A wasm binary contains only a single data section
103// but that can contain many segments, each with their own virtual location
104// in memory. Each MCSection data created by llvm is modeled as its own
105// wasm data segment.
106struct WasmDataSegment {
107 MCSectionWasm *Section;
Sam Cleggd95ed952017-09-20 19:03:35 +0000108 StringRef Name;
Sam Clegg7c395942017-09-14 23:07:53 +0000109 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000110 uint32_t Alignment;
111 uint32_t Flags;
Sam Clegg7c395942017-09-14 23:07:53 +0000112 SmallVector<char, 4> Data;
113};
114
Sam Clegg9e15f352017-06-03 02:01:24 +0000115// A wasm function to be written into the function section.
116struct WasmFunction {
Heejin Ahnda419bd2018-11-14 02:46:21 +0000117 uint32_t SigIndex;
Sam Clegg9e15f352017-06-03 02:01:24 +0000118 const MCSymbolWasm *Sym;
119};
120
Sam Clegg9e15f352017-06-03 02:01:24 +0000121// A wasm global to be written into the global section.
122struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000123 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000124 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000125};
126
Sam Cleggea7cace2018-01-09 23:43:14 +0000127// Information about a single item which is part of a COMDAT. For each data
128// segment or function which is in the COMDAT, there is a corresponding
129// WasmComdatEntry.
130struct WasmComdatEntry {
131 unsigned Kind;
132 uint32_t Index;
133};
134
Sam Clegg6dc65e92017-06-06 16:38:59 +0000135// Information about a single relocation.
136struct WasmRelocationEntry {
Heejin Ahnf208f632018-09-05 01:27:38 +0000137 uint64_t Offset; // Where is the relocation.
138 const MCSymbolWasm *Symbol; // The symbol to relocate with.
139 int64_t Addend; // A value to add to the symbol.
140 unsigned Type; // The type of the relocation.
141 const MCSectionWasm *FixupSection; // The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000142
143 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
144 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000145 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000146 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
147 FixupSection(FixupSection) {}
148
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000149 bool hasAddend() const {
150 switch (Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000151 case wasm::R_WASM_MEMORY_ADDR_LEB:
152 case wasm::R_WASM_MEMORY_ADDR_SLEB:
153 case wasm::R_WASM_MEMORY_ADDR_I32:
154 case wasm::R_WASM_FUNCTION_OFFSET_I32:
155 case wasm::R_WASM_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000156 return true;
157 default:
158 return false;
159 }
160 }
161
Sam Clegg6dc65e92017-06-06 16:38:59 +0000162 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000163 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
164 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000165 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000166 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000167
Aaron Ballman615eb472017-10-15 14:32:27 +0000168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000169 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
170#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000171};
172
Heejin Ahn18c56a02019-02-04 19:13:39 +0000173static const uint32_t InvalidIndex = -1;
Sam Clegg25d8e682018-05-08 00:08:21 +0000174
Sam Cleggcfd44a22018-04-05 17:01:39 +0000175struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000176
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000177 StringRef Name;
178 MCSectionWasm *Section;
179
180 uint32_t OutputContentsOffset;
181 uint32_t OutputIndex;
182
183 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
184 : Name(Name), Section(Section), OutputContentsOffset(0),
Heejin Ahn18c56a02019-02-04 19:13:39 +0000185 OutputIndex(InvalidIndex) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000186};
187
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000188#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000189raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000190 Rel.print(OS);
191 return OS;
192}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000193#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000194
Sam Clegg19e8bef2019-01-30 22:47:35 +0000195// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
196// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000197static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000198 uint64_t Offset) {
199 uint8_t Buffer[5];
200 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
201 assert(SizeLen == 5);
202 Stream.pwrite((char *)Buffer, SizeLen, Offset);
203}
204
205// Write X as an signed LEB value at offset Offset in Stream, padded
206// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000207static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000208 uint64_t Offset) {
209 uint8_t Buffer[5];
210 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
211 assert(SizeLen == 5);
212 Stream.pwrite((char *)Buffer, SizeLen, Offset);
213}
214
215// Write X as a plain integer value at offset Offset in Stream.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000216static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
Sam Clegg19e8bef2019-01-30 22:47:35 +0000217 uint8_t Buffer[4];
218 support::endian::write32le(Buffer, X);
219 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
220}
221
Dan Gohman18eafb62017-02-22 01:23:18 +0000222class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000223 support::endian::Writer W;
224
Dan Gohman18eafb62017-02-22 01:23:18 +0000225 /// The target specific Wasm writer instance.
226 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
227
Dan Gohmand934cb82017-02-24 23:18:00 +0000228 // Relocations for fixing up references in the code section.
229 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000230 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000231
232 // Relocations for fixing up references in the data section.
233 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000234 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000235
Dan Gohmand934cb82017-02-24 23:18:00 +0000236 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000237 // Maps function symbols to the index of the type of the function
238 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000239 // Maps function symbols to the table element index space. Used
240 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000241 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000242 // Maps function/global symbols to the function/global/event/section index
243 // space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000244 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
245 // Maps data symbols to the Wasm segment and offset/size with the segment.
246 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000247
248 // Stores output data (index, relocations, content offset) for custom
249 // section.
250 std::vector<WasmCustomSection> CustomSections;
Thomas Livelycbda16e2019-01-17 02:29:55 +0000251 std::unique_ptr<WasmCustomSection> ProducersSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000252 // Relocations for fixing up references in the custom sections.
253 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
254 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000255
Sam Cleggc0d41192018-05-17 17:15:15 +0000256 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000257 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
258
Heejin Ahnda419bd2018-11-14 02:46:21 +0000259 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
260 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg7c395942017-09-14 23:07:53 +0000261 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000262 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000263 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000264 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000265 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000266 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000267
Dan Gohman18eafb62017-02-22 01:23:18 +0000268 // TargetObjectWriter wrappers.
269 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000270 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
271 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000272 }
273
Sam Clegg2322a932018-04-23 19:16:19 +0000274 void startSection(SectionBookkeeping &Section, unsigned SectionId);
275 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000276 void endSection(SectionBookkeeping &Section);
277
Dan Gohman18eafb62017-02-22 01:23:18 +0000278public:
Lang Hames1301a872017-10-10 01:15:10 +0000279 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
280 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000281 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000282
Dan Gohman0917c9e2018-01-15 17:06:23 +0000283private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000284 void reset() override {
285 CodeRelocations.clear();
286 DataRelocations.clear();
287 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000288 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000289 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000290 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000291 CustomSections.clear();
292 ProducersSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000293 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000294 SignatureIndices.clear();
295 Signatures.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000296 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000297 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000298 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000299 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000300 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000301 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000302 }
303
Dan Gohman18eafb62017-02-22 01:23:18 +0000304 void writeHeader(const MCAssembler &Asm);
305
306 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
307 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000308 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000309
310 void executePostLayoutBinding(MCAssembler &Asm,
311 const MCAsmLayout &Layout) override;
312
Peter Collingbourne438390f2018-05-21 18:23:50 +0000313 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000314
Sam Cleggb7787fd2017-06-20 04:04:59 +0000315 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000316 encodeULEB128(Str.size(), W.OS);
317 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000318 }
319
Heejin Ahnf208f632018-09-05 01:27:38 +0000320 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000321
Heejin Ahnda419bd2018-11-14 02:46:21 +0000322 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000323 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000324 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000325 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000326 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000327 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000328 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000329 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000330 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000331 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000332 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000333 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000334 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000335 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000336 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000337 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000338 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000339 void writeCustomSection(WasmCustomSection &CustomSection,
340 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000341 void writeCustomRelocSections();
342 void
343 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
344 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000345
Sam Clegg7c395942017-09-14 23:07:53 +0000346 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000347 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
348 uint64_t ContentsOffset);
349
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000350 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000351 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000352 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000353 void registerFunctionType(const MCSymbolWasm &Symbol);
354 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000355};
Sam Clegg9e15f352017-06-03 02:01:24 +0000356
Dan Gohman18eafb62017-02-22 01:23:18 +0000357} // end anonymous namespace
358
Dan Gohmand934cb82017-02-24 23:18:00 +0000359// Write out a section header and a patchable section size field.
360void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000361 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000362 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000363 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000364
Peter Collingbournef17b1492018-05-21 18:17:42 +0000365 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000366
367 // The section size. We don't know the size yet, so reserve enough space
368 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000369 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000370
371 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000372 Section.ContentsOffset = W.OS.tell();
373 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000374 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000375}
Dan Gohmand934cb82017-02-24 23:18:00 +0000376
Sam Clegg2322a932018-04-23 19:16:19 +0000377void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
378 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000379 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000380 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000381
382 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000383 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000384
Dan Gohmand934cb82017-02-24 23:18:00 +0000385 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000386 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000387
388 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000389 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000390}
391
392// Now that the section is complete and we know how big it is, patch up the
393// section size field at the start of the section.
394void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000395 uint64_t Size = W.OS.tell();
396 // /dev/null doesn't support seek/tell and can report offset of 0.
397 // Simply skip this patching in that case.
398 if (!Size)
399 return;
400
401 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000402 if (uint32_t(Size) != Size)
403 report_fatal_error("section size does not fit in a uint32_t");
404
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000405 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000406
407 // Write the final section size to the payload_len field, which follows
408 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000409 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000410 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000411}
412
Dan Gohman18eafb62017-02-22 01:23:18 +0000413// Emit the Wasm header.
414void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000415 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
416 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000417}
418
419void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
420 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000421 // Build a map of sections to the function that defines them, for use
422 // in recordRelocation.
423 for (const MCSymbol &S : Asm.symbols()) {
424 const auto &WS = static_cast<const MCSymbolWasm &>(S);
425 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
426 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
427 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
428 if (!Pair.second)
429 report_fatal_error("section already has a defining function: " +
430 Sec.getSectionName());
431 }
432 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000433}
434
435void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
436 const MCAsmLayout &Layout,
437 const MCFragment *Fragment,
438 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000439 uint64_t &FixedValue) {
440 MCAsmBackend &Backend = Asm.getBackend();
441 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
442 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000443 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000444 uint64_t C = Target.getConstant();
445 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
446 MCContext &Ctx = Asm.getContext();
447
Sam Cleggbafe6902017-12-15 00:17:10 +0000448 // The .init_array isn't translated as data, so don't do relocations in it.
449 if (FixupSection.getSectionName().startswith(".init_array"))
450 return;
451
Dan Gohmand934cb82017-02-24 23:18:00 +0000452 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
453 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
454 "Should not have constructed this");
455
456 // Let A, B and C being the components of Target and R be the location of
457 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
458 // If it is pcrel, we want to compute (A - B + C - R).
459
460 // In general, Wasm has no relocations for -B. It can only represent (A + C)
461 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
462 // replace B to implement it: (A - R - K + C)
463 if (IsPCRel) {
464 Ctx.reportError(
465 Fixup.getLoc(),
466 "No relocation available to represent this relative expression");
467 return;
468 }
469
470 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
471
472 if (SymB.isUndefined()) {
473 Ctx.reportError(Fixup.getLoc(),
474 Twine("symbol '") + SymB.getName() +
475 "' can not be undefined in a subtraction expression");
476 return;
477 }
478
479 assert(!SymB.isAbsolute() && "Should have been folded");
480 const MCSection &SecB = SymB.getSection();
481 if (&SecB != &FixupSection) {
482 Ctx.reportError(Fixup.getLoc(),
483 "Cannot represent a difference across sections");
484 return;
485 }
486
487 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
488 uint64_t K = SymBOffset - FixupOffset;
489 IsPCRel = true;
490 C -= K;
491 }
492
493 // We either rejected the fixup or folded B into C at this point.
494 const MCSymbolRefExpr *RefA = Target.getSymA();
495 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
496
Dan Gohmand934cb82017-02-24 23:18:00 +0000497 if (SymA && SymA->isVariable()) {
498 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000499 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
500 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
501 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000502 }
503
504 // Put any constant offset in an addend. Offsets can be negative, and
505 // LLVM expects wrapping, in contrast to wasm's immediates which can't
506 // be negative and don't wrap.
507 FixedValue = 0;
508
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000509 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000510 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000511 assert(SymA);
512
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000513 // Absolute offset within a section or a function.
514 // Currently only supported for for metadata sections.
515 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000516 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
517 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000518 if (!FixupSection.getKind().isMetadata())
519 report_fatal_error("relocations for function or section offsets are "
520 "only supported in metadata sections");
521
522 const MCSymbol *SectionSymbol = nullptr;
523 const MCSection &SecA = SymA->getSection();
524 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000525 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000526 else
527 SectionSymbol = SecA.getBeginSymbol();
528 if (!SectionSymbol)
529 report_fatal_error("section symbol is required for relocation");
530
531 C += Layout.getSymbolOffset(*SymA);
532 SymA = cast<MCSymbolWasm>(SectionSymbol);
533 }
534
Sam Cleggd1152a22019-02-04 17:28:46 +0000535 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000536 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000537 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000538 if (SymA->getName().empty())
539 report_fatal_error("relocations against un-named temporaries are not yet "
540 "supported by wasm");
541
542 SymA->setUsedInReloc();
543 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000544
Dan Gohmand934cb82017-02-24 23:18:00 +0000545 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000546 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000547
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000548 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000549 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000550 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000551 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000552 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000553 CustomSectionsRelocations[&FixupSection].push_back(Rec);
554 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000555 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000556 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000557}
558
Heejin Ahn18c56a02019-02-04 19:13:39 +0000559static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000560 if (Symbol.isVariable()) {
561 const MCExpr *Expr = Symbol.getVariableValue();
562 auto *Inner = cast<MCSymbolRefExpr>(Expr);
563 return cast<MCSymbolWasm>(&Inner->getSymbol());
564 }
565 return &Symbol;
566}
567
Dan Gohmand934cb82017-02-24 23:18:00 +0000568// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000569// by RelEntry. This value isn't used by the static linker; it just serves
570// to make the object format more readable and more likely to be directly
571// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000572uint32_t
573WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000574 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000575 case wasm::R_WASM_TABLE_INDEX_SLEB:
576 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000577 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000578 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000579 assert(Sym->isFunction());
580 return TableIndices[Sym];
581 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000582 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000583 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000584 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000585 case wasm::R_WASM_FUNCTION_INDEX_LEB:
586 case wasm::R_WASM_GLOBAL_INDEX_LEB:
587 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000588 // Provisional value is function/global/event Wasm index
Sam Clegg6c899ba2018-02-23 05:08:34 +0000589 if (!WasmIndices.count(RelEntry.Symbol))
590 report_fatal_error("symbol not found in wasm index space: " +
591 RelEntry.Symbol->getName());
592 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000593 case wasm::R_WASM_FUNCTION_OFFSET_I32:
594 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000595 const auto &Section =
596 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
597 return Section.getSectionOffset() + RelEntry.Addend;
598 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000599 case wasm::R_WASM_MEMORY_ADDR_LEB:
600 case wasm::R_WASM_MEMORY_ADDR_I32:
601 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000602 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000603 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000604 // For undefined symbols, use zero
605 if (!Sym->isDefined())
606 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000607 const wasm::WasmDataReference &Ref = DataLocations[Sym];
608 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000610 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000611 }
612 default:
613 llvm_unreachable("invalid relocation type");
614 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000615}
616
Sam Clegg759631c2017-09-15 20:54:59 +0000617static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000618 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000619 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000620
Sam Clegg63ebb812017-09-29 16:50:08 +0000621 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
622
Sam Clegg759631c2017-09-15 20:54:59 +0000623 for (const MCFragment &Frag : DataSection) {
624 if (Frag.hasInstructions())
625 report_fatal_error("only data supported in data sections");
626
627 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
628 if (Align->getValueSize() != 1)
629 report_fatal_error("only byte values supported for alignment");
630 // If nops are requested, use zeros, as this is the data section.
631 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000632 uint64_t Size =
633 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
634 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000635 DataBytes.resize(Size, Value);
636 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000637 int64_t NumValues;
638 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000639 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000640 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
641 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000642 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
643 const SmallVectorImpl<char> &Contents = LEB->getContents();
644 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000645 } else {
646 const auto &DataFrag = cast<MCDataFragment>(Frag);
647 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000648 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
649 }
650 }
651
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000652 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000653}
654
Sam Clegg60ec3032018-01-23 01:23:17 +0000655uint32_t
656WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000657 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000658 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000659 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000660 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000661 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000662 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000663
Sam Clegg25d8e682018-05-08 00:08:21 +0000664 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000665}
666
Dan Gohmand934cb82017-02-24 23:18:00 +0000667// Apply the portions of the relocation records that we can handle ourselves
668// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000669void WasmObjectWriter::applyRelocations(
670 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000671 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000672 for (const WasmRelocationEntry &RelEntry : Relocations) {
673 uint64_t Offset = ContentsOffset +
674 RelEntry.FixupSection->getSectionOffset() +
675 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000676
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000677 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000678 uint32_t Value = getProvisionalValue(RelEntry);
679
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000680 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000681 case wasm::R_WASM_FUNCTION_INDEX_LEB:
682 case wasm::R_WASM_TYPE_INDEX_LEB:
683 case wasm::R_WASM_GLOBAL_INDEX_LEB:
684 case wasm::R_WASM_MEMORY_ADDR_LEB:
685 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000686 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000687 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000688 case wasm::R_WASM_TABLE_INDEX_I32:
689 case wasm::R_WASM_MEMORY_ADDR_I32:
690 case wasm::R_WASM_FUNCTION_OFFSET_I32:
691 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000692 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000693 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000694 case wasm::R_WASM_TABLE_INDEX_SLEB:
695 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000696 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000697 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000698 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000699 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000700 }
701 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000702}
703
Heejin Ahnda419bd2018-11-14 02:46:21 +0000704void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
705 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000706 return;
707
708 SectionBookkeeping Section;
709 startSection(Section, wasm::WASM_SEC_TYPE);
710
Heejin Ahnda419bd2018-11-14 02:46:21 +0000711 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712
Heejin Ahnda419bd2018-11-14 02:46:21 +0000713 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000714 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000715 encodeULEB128(Sig.Params.size(), W.OS);
716 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000717 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000718 encodeULEB128(Sig.Returns.size(), W.OS);
719 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000720 writeValueType(Ty);
721 }
722
723 endSection(Section);
724}
725
Sam Clegg8defa952018-02-12 22:41:29 +0000726void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000727 uint32_t DataSize,
728 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000729 if (Imports.empty())
730 return;
731
Sam Cleggf950b242017-12-11 23:03:38 +0000732 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
733
Sam Clegg9e15f352017-06-03 02:01:24 +0000734 SectionBookkeeping Section;
735 startSection(Section, wasm::WASM_SEC_IMPORT);
736
Peter Collingbournef17b1492018-05-21 18:17:42 +0000737 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000738 for (const wasm::WasmImport &Import : Imports) {
739 writeString(Import.Module);
740 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000742
743 switch (Import.Kind) {
744 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000745 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 break;
747 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000748 W.OS << char(Import.Global.Type);
749 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000751 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000752 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000753 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000754 break;
755 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000756 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000757 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000758 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000759 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000760 case wasm::WASM_EXTERNAL_EVENT:
761 encodeULEB128(Import.Event.Attribute, W.OS);
762 encodeULEB128(Import.Event.SigIndex, W.OS);
763 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000764 default:
765 llvm_unreachable("unsupported import kind");
766 }
767 }
768
769 endSection(Section);
770}
771
Sam Clegg457fb0b2017-09-15 19:50:44 +0000772void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 if (Functions.empty())
774 return;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_FUNCTION);
778
Peter Collingbournef17b1492018-05-21 18:17:42 +0000779 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000780 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000781 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000782
783 endSection(Section);
784}
785
Sam Clegg7c395942017-09-14 23:07:53 +0000786void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000787 if (Globals.empty())
788 return;
789
790 SectionBookkeeping Section;
791 startSection(Section, wasm::WASM_SEC_GLOBAL);
792
Peter Collingbournef17b1492018-05-21 18:17:42 +0000793 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000794 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000795 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000796 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000797
Peter Collingbournef17b1492018-05-21 18:17:42 +0000798 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
799 encodeSLEB128(Global.InitialValue, W.OS);
800 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000801 }
802
803 endSection(Section);
804}
805
Heejin Ahnda419bd2018-11-14 02:46:21 +0000806void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
807 if (Events.empty())
808 return;
809
810 SectionBookkeeping Section;
811 startSection(Section, wasm::WASM_SEC_EVENT);
812
813 encodeULEB128(Events.size(), W.OS);
814 for (const wasm::WasmEventType &Event : Events) {
815 encodeULEB128(Event.Attribute, W.OS);
816 encodeULEB128(Event.SigIndex, W.OS);
817 }
818
819 endSection(Section);
820}
821
Sam Clegg8defa952018-02-12 22:41:29 +0000822void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000823 if (Exports.empty())
824 return;
825
826 SectionBookkeeping Section;
827 startSection(Section, wasm::WASM_SEC_EXPORT);
828
Peter Collingbournef17b1492018-05-21 18:17:42 +0000829 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000830 for (const wasm::WasmExport &Export : Exports) {
831 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000832 W.OS << char(Export.Kind);
833 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000834 }
835
836 endSection(Section);
837}
838
Sam Clegg457fb0b2017-09-15 19:50:44 +0000839void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000840 if (TableElems.empty())
841 return;
842
843 SectionBookkeeping Section;
844 startSection(Section, wasm::WASM_SEC_ELEM);
845
Peter Collingbournef17b1492018-05-21 18:17:42 +0000846 encodeULEB128(1, W.OS); // number of "segments"
847 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000850 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000851 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000852 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000853
Peter Collingbournef17b1492018-05-21 18:17:42 +0000854 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000855 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000856 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
858 endSection(Section);
859}
860
Sam Clegg457fb0b2017-09-15 19:50:44 +0000861void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
862 const MCAsmLayout &Layout,
863 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000864 if (Functions.empty())
865 return;
866
867 SectionBookkeeping Section;
868 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000869 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000870
Peter Collingbournef17b1492018-05-21 18:17:42 +0000871 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000872
873 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000874 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000875
Sam Clegg9e15f352017-06-03 02:01:24 +0000876 int64_t Size = 0;
877 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
878 report_fatal_error(".size expression must be evaluatable");
879
Peter Collingbournef17b1492018-05-21 18:17:42 +0000880 encodeULEB128(Size, W.OS);
881 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
882 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000883 }
884
Sam Clegg9e15f352017-06-03 02:01:24 +0000885 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000886 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000887
888 endSection(Section);
889}
890
Sam Clegg6c899ba2018-02-23 05:08:34 +0000891void WasmObjectWriter::writeDataSection() {
892 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000893 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000894
895 SectionBookkeeping Section;
896 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000897 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000898
Peter Collingbournef17b1492018-05-21 18:17:42 +0000899 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000900
Sam Clegg6c899ba2018-02-23 05:08:34 +0000901 for (const WasmDataSegment &Segment : DataSegments) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000902 encodeULEB128(0, W.OS); // memory index
903 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
904 encodeSLEB128(Segment.Offset, W.OS); // offset
905 W.OS << char(wasm::WASM_OPCODE_END);
906 encodeULEB128(Segment.Data.size(), W.OS); // size
907 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
908 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000909 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000910
911 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000912 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000913
914 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000915}
916
Sam Clegg6f08c842018-04-24 18:11:36 +0000917void WasmObjectWriter::writeRelocSection(
918 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000919 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000920 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
921 // for descriptions of the reloc sections.
922
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000923 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000924 return;
925
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000926 // First, ensure the relocations are sorted in offset order. In general they
927 // should already be sorted since `recordRelocation` is called in offset
928 // order, but for the code section we combine many MC sections into single
929 // wasm section, and this order is determined by the order of Asm.Symbols()
930 // not the sections order.
931 std::stable_sort(
932 Relocs.begin(), Relocs.end(),
933 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
934 return (A.Offset + A.FixupSection->getSectionOffset()) <
935 (B.Offset + B.FixupSection->getSectionOffset());
936 });
937
Sam Clegg9e15f352017-06-03 02:01:24 +0000938 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000939 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000940
Peter Collingbournef17b1492018-05-21 18:17:42 +0000941 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000942 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000943 for (const WasmRelocationEntry &RelEntry : Relocs) {
944 uint64_t Offset =
945 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000946 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000947
Peter Collingbournef17b1492018-05-21 18:17:42 +0000948 W.OS << char(RelEntry.Type);
949 encodeULEB128(Offset, W.OS);
950 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000951 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000952 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000953 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000954
955 endSection(Section);
956}
957
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000958void WasmObjectWriter::writeCustomRelocSections() {
959 for (const auto &Sec : CustomSections) {
960 auto &Relocations = CustomSectionsRelocations[Sec.Section];
961 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
962 }
963}
964
Sam Clegg9e15f352017-06-03 02:01:24 +0000965void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000966 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000967 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000968 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000969 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000970 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000971 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000972
Sam Clegg6bb5a412018-04-26 18:15:32 +0000973 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000974 if (SymbolInfos.size() != 0) {
975 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000976 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000977 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000978 encodeULEB128(Sym.Kind, W.OS);
979 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000980 switch (Sym.Kind) {
981 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
982 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000983 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000984 encodeULEB128(Sym.ElementIndex, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000985 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0)
986 writeString(Sym.Name);
987 break;
988 case wasm::WASM_SYMBOL_TYPE_DATA:
989 writeString(Sym.Name);
990 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000991 encodeULEB128(Sym.DataRef.Segment, W.OS);
992 encodeULEB128(Sym.DataRef.Offset, W.OS);
993 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000994 }
995 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000996 case wasm::WASM_SYMBOL_TYPE_SECTION: {
997 const uint32_t SectionIndex =
998 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000999 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001000 break;
1001 }
Sam Clegg6c899ba2018-02-23 05:08:34 +00001002 default:
1003 llvm_unreachable("unexpected kind");
1004 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001005 }
1006 endSection(SubSection);
1007 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001008
Sam Clegg6c899ba2018-02-23 05:08:34 +00001009 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001010 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001011 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001012 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001013 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001014 encodeULEB128(Segment.Alignment, W.OS);
1015 encodeULEB128(Segment.Flags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001016 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001017 endSection(SubSection);
1018 }
1019
Sam Cleggbafe6902017-12-15 00:17:10 +00001020 if (!InitFuncs.empty()) {
1021 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001022 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001023 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001024 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001025 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001026 }
1027 endSection(SubSection);
1028 }
1029
Sam Cleggea7cace2018-01-09 23:43:14 +00001030 if (Comdats.size()) {
1031 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001032 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001033 for (const auto &C : Comdats) {
1034 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001035 encodeULEB128(0, W.OS); // flags for future use
1036 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001037 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001038 encodeULEB128(Entry.Kind, W.OS);
1039 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001040 }
1041 }
1042 endSection(SubSection);
1043 }
1044
Sam Clegg9e15f352017-06-03 02:01:24 +00001045 endSection(Section);
1046}
1047
Thomas Livelycbda16e2019-01-17 02:29:55 +00001048void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1049 const MCAssembler &Asm,
1050 const MCAsmLayout &Layout) {
1051 SectionBookkeeping Section;
1052 auto *Sec = CustomSection.Section;
1053 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001054
Thomas Livelycbda16e2019-01-17 02:29:55 +00001055 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1056 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001057
Thomas Livelycbda16e2019-01-17 02:29:55 +00001058 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1059 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001060
Thomas Livelycbda16e2019-01-17 02:29:55 +00001061 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001062
Thomas Livelycbda16e2019-01-17 02:29:55 +00001063 // Apply fixups.
1064 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1065 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001066}
1067
Heejin Ahnf208f632018-09-05 01:27:38 +00001068uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001069 assert(Symbol.isFunction());
1070 assert(TypeIndices.count(&Symbol));
1071 return TypeIndices[&Symbol];
1072}
1073
Heejin Ahnda419bd2018-11-14 02:46:21 +00001074uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1075 assert(Symbol.isEvent());
1076 assert(TypeIndices.count(&Symbol));
1077 return TypeIndices[&Symbol];
1078}
1079
Heejin Ahn38b12f52018-11-20 00:38:10 +00001080void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001081 assert(Symbol.isFunction());
1082
Heejin Ahnda419bd2018-11-14 02:46:21 +00001083 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001084 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001085 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001086 S.Returns = Sig->Returns;
1087 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001088 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001089
Heejin Ahnda419bd2018-11-14 02:46:21 +00001090 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001091 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001092 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001093 TypeIndices[&Symbol] = Pair.first->second;
1094
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001095 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1096 << " new:" << Pair.second << "\n");
1097 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001098}
1099
Heejin Ahn38b12f52018-11-20 00:38:10 +00001100void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001101 assert(Symbol.isEvent());
1102
1103 // TODO Currently we don't generate imported exceptions, but if we do, we
1104 // should have a way of infering types of imported exceptions.
1105 WasmSignature S;
1106 if (auto *Sig = Symbol.getSignature()) {
1107 S.Returns = Sig->Returns;
1108 S.Params = Sig->Params;
1109 }
1110
1111 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1112 if (Pair.second)
1113 Signatures.push_back(S);
1114 TypeIndices[&Symbol] = Pair.first->second;
1115
1116 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1117 << "\n");
1118 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001119}
1120
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001121static bool isInSymtab(const MCSymbolWasm &Sym) {
1122 if (Sym.isUsedInReloc())
1123 return true;
1124
1125 if (Sym.isComdat() && !Sym.isDefined())
1126 return false;
1127
1128 if (Sym.isTemporary() && Sym.getName().empty())
1129 return false;
1130
1131 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1132 return false;
1133
1134 if (Sym.isSection())
1135 return false;
1136
1137 return true;
1138}
1139
Peter Collingbourne438390f2018-05-21 18:23:50 +00001140uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1141 const MCAsmLayout &Layout) {
1142 uint64_t StartOffset = W.OS.tell();
1143
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001144 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001145 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001146
1147 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001148 SmallVector<WasmFunction, 4> Functions;
1149 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001150 SmallVector<wasm::WasmImport, 4> Imports;
1151 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001152 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001153 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001154 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001155 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001156 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001157
Sam Cleggf950b242017-12-11 23:03:38 +00001158 // For now, always emit the memory import, since loads and stores are not
1159 // valid without it. In the future, we could perhaps be more clever and omit
1160 // it if there are no loads or stores.
Heejin Ahn18c56a02019-02-04 19:13:39 +00001161 auto *MemorySym =
Sam Cleggf950b242017-12-11 23:03:38 +00001162 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001163 wasm::WasmImport MemImport;
Dan Gohmanf726e442019-02-01 22:27:34 +00001164 MemImport.Module = MemorySym->getImportModule();
1165 MemImport.Field = MemorySym->getImportName();
Sam Cleggf950b242017-12-11 23:03:38 +00001166 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1167 Imports.push_back(MemImport);
1168
1169 // For now, always emit the table section, since indirect calls are not
1170 // valid without it. In the future, we could perhaps be more clever and omit
1171 // it if there are no indirect calls.
Heejin Ahn18c56a02019-02-04 19:13:39 +00001172 auto *TableSym =
Sam Cleggf950b242017-12-11 23:03:38 +00001173 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001174 wasm::WasmImport TableImport;
Dan Gohmanf726e442019-02-01 22:27:34 +00001175 TableImport.Module = TableSym->getImportModule();
1176 TableImport.Field = TableSym->getImportName();
Sam Cleggf950b242017-12-11 23:03:38 +00001177 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001178 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001179 Imports.push_back(TableImport);
1180
Heejin Ahnda419bd2018-11-14 02:46:21 +00001181 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001182 // symbols. This must be done before populating WasmIndices for defined
1183 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001184 for (const MCSymbol &S : Asm.symbols()) {
1185 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1186
1187 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001188 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001189 if (WS.isFunction())
1190 registerFunctionType(WS);
1191
Heejin Ahnda419bd2018-11-14 02:46:21 +00001192 if (WS.isEvent())
1193 registerEventType(WS);
1194
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001195 if (WS.isTemporary())
1196 continue;
1197
1198 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001199 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001200 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001201 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001202 Import.Module = WS.getImportModule();
1203 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001204 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001205 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001206 Imports.push_back(Import);
1207 WasmIndices[&WS] = NumFunctionImports++;
1208 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001209 if (WS.isWeak())
1210 report_fatal_error("undefined global symbol cannot be weak");
1211
Sam Clegg6c899ba2018-02-23 05:08:34 +00001212 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001213 Import.Module = WS.getImportModule();
1214 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001215 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001216 Import.Global = WS.getGlobalType();
1217 Imports.push_back(Import);
1218 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001219 } else if (WS.isEvent()) {
1220 if (WS.isWeak())
1221 report_fatal_error("undefined event symbol cannot be weak");
1222
1223 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001224 Import.Module = WS.getImportModule();
1225 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001226 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1227 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1228 Import.Event.SigIndex = getEventType(WS);
1229 Imports.push_back(Import);
1230 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001231 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001232 }
1233 }
1234
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001235 // Populate DataSegments and CustomSections, which must be done before
1236 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001237 for (MCSection &Sec : Asm) {
1238 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001239 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001240
Sam Cleggbafe6902017-12-15 00:17:10 +00001241 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001242 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001243 continue;
1244
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001245 // Code is handled separately
1246 if (Section.getKind().isText())
1247 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001248
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001249 if (Section.isWasmData()) {
1250 uint32_t SegmentIndex = DataSegments.size();
1251 DataSize = alignTo(DataSize, Section.getAlignment());
1252 DataSegments.emplace_back();
1253 WasmDataSegment &Segment = DataSegments.back();
1254 Segment.Name = SectionName;
1255 Segment.Offset = DataSize;
1256 Segment.Section = &Section;
1257 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001258 Segment.Alignment = Log2_32(Section.getAlignment());
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001259 Segment.Flags = 0;
1260 DataSize += Segment.Data.size();
1261 Section.setSegmentIndex(SegmentIndex);
1262
1263 if (const MCSymbolWasm *C = Section.getGroup()) {
1264 Comdats[C->getName()].emplace_back(
1265 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1266 }
1267 } else {
1268 // Create custom sections
1269 assert(Sec.getKind().isMetadata());
1270
1271 StringRef Name = SectionName;
1272
1273 // For user-defined custom sections, strip the prefix
1274 if (Name.startswith(".custom_section."))
1275 Name = Name.substr(strlen(".custom_section."));
1276
Heejin Ahnf208f632018-09-05 01:27:38 +00001277 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001278 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001279 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001280 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001281 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001282 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001283 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001284
1285 // Separate out the producers section
1286 if (Name == "producers") {
1287 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1288 continue;
1289 }
1290
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001291 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001292 }
Sam Clegg759631c2017-09-15 20:54:59 +00001293 }
1294
Nicholas Wilson586320c2018-02-28 17:19:48 +00001295 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001296 for (const MCSymbol &S : Asm.symbols()) {
1297 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1298 // or used in relocations.
1299 if (S.isTemporary() && S.getName().empty())
1300 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001301
Dan Gohmand934cb82017-02-24 23:18:00 +00001302 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001303 LLVM_DEBUG(
1304 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1305 << " isDefined=" << S.isDefined() << " isExternal="
1306 << S.isExternal() << " isTemporary=" << S.isTemporary()
1307 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1308 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001309
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001310 if (WS.isVariable())
1311 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001312 if (WS.isComdat() && !WS.isDefined())
1313 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001314
Dan Gohmand934cb82017-02-24 23:18:00 +00001315 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001316 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001317 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001318 if (WS.getOffset() != 0)
1319 report_fatal_error(
1320 "function sections must contain one function each");
1321
Heejin Ahn18c56a02019-02-04 19:13:39 +00001322 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001323 report_fatal_error(
1324 "function symbols must have a size set with .size");
1325
Sam Clegg6c899ba2018-02-23 05:08:34 +00001326 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001327 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001328 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001329 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001330 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001331 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001332 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001333
1334 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1335 if (const MCSymbolWasm *C = Section.getGroup()) {
1336 Comdats[C->getName()].emplace_back(
1337 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1338 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001339 } else {
1340 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001341 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001342 }
1343
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001344 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001345
Sam Clegg6c899ba2018-02-23 05:08:34 +00001346 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001347 if (WS.isTemporary() && !WS.getSize())
1348 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001349
Sam Clegg6c899ba2018-02-23 05:08:34 +00001350 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001351 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1352 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001353 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001354 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001355
Sam Cleggfe6414b2017-06-21 23:46:41 +00001356 if (!WS.getSize())
1357 report_fatal_error("data symbols must have a size set with .size: " +
1358 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001359
Sam Cleggfe6414b2017-06-21 23:46:41 +00001360 int64_t Size = 0;
1361 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1362 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001363
Sam Clegg759631c2017-09-15 20:54:59 +00001364 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001365 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001366
Sam Clegg6c899ba2018-02-23 05:08:34 +00001367 // For each data symbol, export it in the symtab as a reference to the
1368 // corresponding Wasm data segment.
1369 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1370 DataSection.getSegmentIndex(),
1371 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1372 static_cast<uint32_t>(Size)};
1373 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001374 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001375
Sam Clegga165f2d2018-04-30 19:40:57 +00001376 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001377 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001378 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001379 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001380
Eric Christopher545932b2018-02-23 21:14:47 +00001381 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001382 LLVM_DEBUG(dbgs() << " -> global index: "
1383 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001384
1385 } else if (WS.isEvent()) {
1386 // C++ exception symbol (__cpp_exception)
1387 unsigned Index;
1388 if (WS.isDefined()) {
1389 Index = NumEventImports + Events.size();
1390 wasm::WasmEventType Event;
1391 Event.SigIndex = getEventType(WS);
1392 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1393 WasmIndices[&WS] = Index;
1394 Events.push_back(Event);
1395 } else {
1396 // An import; the index was assigned above.
1397 Index = WasmIndices.find(&WS)->second;
1398 }
1399 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1400 << "\n");
1401
Sam Clegga165f2d2018-04-30 19:40:57 +00001402 } else {
1403 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001404 }
1405 }
1406
Nicholas Wilson586320c2018-02-28 17:19:48 +00001407 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1408 // process these in a separate pass because we need to have processed the
1409 // target of the alias before the alias itself and the symbols are not
1410 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001411 for (const MCSymbol &S : Asm.symbols()) {
1412 if (!S.isVariable())
1413 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001414
Sam Cleggcd65f692018-01-11 23:59:16 +00001415 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001416
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001417 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001418 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001419 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001420 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1421 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001422
Sam Clegg6c899ba2018-02-23 05:08:34 +00001423 if (WS.isFunction()) {
1424 assert(WasmIndices.count(ResolvedSym) > 0);
1425 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1426 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001427 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001428 } else if (WS.isData()) {
1429 assert(DataLocations.count(ResolvedSym) > 0);
1430 const wasm::WasmDataReference &Ref =
1431 DataLocations.find(ResolvedSym)->second;
1432 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001433 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001434 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001435 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001436 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001437 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001438
Nicholas Wilson586320c2018-02-28 17:19:48 +00001439 // Finally, populate the symbol table itself, in its "natural" order.
1440 for (const MCSymbol &S : Asm.symbols()) {
1441 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001442 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001443 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001444 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001445 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001446 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001447
1448 uint32_t Flags = 0;
1449 if (WS.isWeak())
1450 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1451 if (WS.isHidden())
1452 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1453 if (!WS.isExternal() && WS.isDefined())
1454 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1455 if (WS.isUndefined())
1456 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001457 if (WS.isExported())
1458 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001459
1460 wasm::WasmSymbolInfo Info;
1461 Info.Name = WS.getName();
1462 Info.Kind = WS.getType();
1463 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001464 if (!WS.isData()) {
1465 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001466 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001467 } else if (WS.isDefined()) {
1468 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001469 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001470 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001471 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001472 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001473 }
1474
Sam Clegg6006e092017-12-22 20:31:39 +00001475 {
1476 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001477 // Functions referenced by a relocation need to put in the table. This is
1478 // purely to make the object file's provisional values readable, and is
1479 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001480 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1481 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001482 return;
1483 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001484 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001485 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001486 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001487 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001488 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1489 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001490 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001491 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001492 }
1493 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001494
Sam Clegg6006e092017-12-22 20:31:39 +00001495 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1496 HandleReloc(RelEntry);
1497 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1498 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001499 }
1500
Sam Cleggbafe6902017-12-15 00:17:10 +00001501 // Translate .init_array section contents into start functions.
1502 for (const MCSection &S : Asm) {
1503 const auto &WS = static_cast<const MCSectionWasm &>(S);
1504 if (WS.getSectionName().startswith(".fini_array"))
1505 report_fatal_error(".fini_array sections are unsupported");
1506 if (!WS.getSectionName().startswith(".init_array"))
1507 continue;
1508 if (WS.getFragmentList().empty())
1509 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001510
1511 // init_array is expected to contain a single non-empty data fragment
1512 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001513 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001514
1515 auto IT = WS.begin();
1516 const MCFragment &EmptyFrag = *IT;
1517 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1518 report_fatal_error(".init_array section should be aligned");
1519
1520 IT = std::next(IT);
1521 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001522 if (AlignFrag.getKind() != MCFragment::FT_Align)
1523 report_fatal_error(".init_array section should be aligned");
1524 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1525 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001526
1527 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001528 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1529 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001530
Sam Cleggbafe6902017-12-15 00:17:10 +00001531 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001532 unsigned PrefixLength = strlen(".init_array");
1533 if (WS.getSectionName().size() > PrefixLength) {
1534 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001535 report_fatal_error(
1536 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001537 if (WS.getSectionName()
1538 .substr(PrefixLength + 1)
1539 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001540 report_fatal_error("invalid .init_array section priority");
1541 }
1542 const auto &DataFrag = cast<MCDataFragment>(Frag);
1543 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001544 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001545 P = (const uint8_t *)Contents.data(),
1546 *End = (const uint8_t *)Contents.data() + Contents.size();
1547 P != End; ++P) {
1548 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001549 report_fatal_error("non-symbolic data in .init_array section");
1550 }
1551 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001552 assert(Fixup.getKind() ==
1553 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001554 const MCExpr *Expr = Fixup.getValue();
1555 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1556 if (!Sym)
1557 report_fatal_error("fixups in .init_array should be symbol references");
1558 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1559 report_fatal_error("symbols in .init_array should be for functions");
Heejin Ahn18c56a02019-02-04 19:13:39 +00001560 if (Sym->getSymbol().getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001561 report_fatal_error("symbols in .init_array should exist in symbtab");
1562 InitFuncs.push_back(
1563 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001564 }
1565 }
1566
Dan Gohman18eafb62017-02-22 01:23:18 +00001567 // Write out the Wasm header.
1568 writeHeader(Asm);
1569
Heejin Ahnda419bd2018-11-14 02:46:21 +00001570 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001571 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001572 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001573 // Skip the "table" section; we import the table instead.
1574 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001575 writeGlobalSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001576 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001577 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001578 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001579 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001580 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001581 for (auto &CustomSection : CustomSections)
1582 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001583 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001584 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1585 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001586 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001587 if (ProducersSection)
1588 writeCustomSection(*ProducersSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001589
Dan Gohmand934cb82017-02-24 23:18:00 +00001590 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001591 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001592}
1593
Lang Hames60fbc7c2017-10-10 16:28:07 +00001594std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001595llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1596 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001597 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001598}