blob: 10f16ba3c8f7226f613798d696dc38c8f484dab6 [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;
Thomas Lively2e150402019-02-19 22:56:19 +0000109 uint32_t InitFlags;
Sam Clegg7c395942017-09-14 23:07:53 +0000110 uint32_t Offset;
Sam Clegg63ebb812017-09-29 16:50:08 +0000111 uint32_t Alignment;
Thomas Lively2e150402019-02-19 22:56:19 +0000112 uint32_t LinkerFlags;
Sam Clegg7c395942017-09-14 23:07:53 +0000113 SmallVector<char, 4> Data;
114};
115
Sam Clegg9e15f352017-06-03 02:01:24 +0000116// A wasm function to be written into the function section.
117struct WasmFunction {
Heejin Ahnda419bd2018-11-14 02:46:21 +0000118 uint32_t SigIndex;
Sam Clegg9e15f352017-06-03 02:01:24 +0000119 const MCSymbolWasm *Sym;
120};
121
Sam Clegg9e15f352017-06-03 02:01:24 +0000122// A wasm global to be written into the global section.
123struct WasmGlobal {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000124 wasm::WasmGlobalType Type;
Sam Clegg9e15f352017-06-03 02:01:24 +0000125 uint64_t InitialValue;
Sam Clegg9e15f352017-06-03 02:01:24 +0000126};
127
Sam Cleggea7cace2018-01-09 23:43:14 +0000128// Information about a single item which is part of a COMDAT. For each data
129// segment or function which is in the COMDAT, there is a corresponding
130// WasmComdatEntry.
131struct WasmComdatEntry {
132 unsigned Kind;
133 uint32_t Index;
134};
135
Sam Clegg6dc65e92017-06-06 16:38:59 +0000136// Information about a single relocation.
137struct WasmRelocationEntry {
Heejin Ahnf208f632018-09-05 01:27:38 +0000138 uint64_t Offset; // Where is the relocation.
139 const MCSymbolWasm *Symbol; // The symbol to relocate with.
140 int64_t Addend; // A value to add to the symbol.
141 unsigned Type; // The type of the relocation.
142 const MCSectionWasm *FixupSection; // The section the relocation is targeting.
Sam Clegg6dc65e92017-06-06 16:38:59 +0000143
144 WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
145 int64_t Addend, unsigned Type,
Sam Cleggfe6414b2017-06-21 23:46:41 +0000146 const MCSectionWasm *FixupSection)
Sam Clegg6dc65e92017-06-06 16:38:59 +0000147 : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
148 FixupSection(FixupSection) {}
149
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000150 bool hasAddend() const {
151 switch (Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000152 case wasm::R_WASM_MEMORY_ADDR_LEB:
153 case wasm::R_WASM_MEMORY_ADDR_SLEB:
154 case wasm::R_WASM_MEMORY_ADDR_I32:
155 case wasm::R_WASM_FUNCTION_OFFSET_I32:
156 case wasm::R_WASM_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000157 return true;
158 default:
159 return false;
160 }
161 }
162
Sam Clegg6dc65e92017-06-06 16:38:59 +0000163 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000164 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
165 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000166 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000167 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000168
Aaron Ballman615eb472017-10-15 14:32:27 +0000169#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000170 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
171#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000172};
173
Heejin Ahn18c56a02019-02-04 19:13:39 +0000174static const uint32_t InvalidIndex = -1;
Sam Clegg25d8e682018-05-08 00:08:21 +0000175
Sam Cleggcfd44a22018-04-05 17:01:39 +0000176struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000177
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000178 StringRef Name;
179 MCSectionWasm *Section;
180
181 uint32_t OutputContentsOffset;
182 uint32_t OutputIndex;
183
184 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
185 : Name(Name), Section(Section), OutputContentsOffset(0),
Heejin Ahn18c56a02019-02-04 19:13:39 +0000186 OutputIndex(InvalidIndex) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000187};
188
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000189#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000190raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000191 Rel.print(OS);
192 return OS;
193}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000194#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000195
Sam Clegg19e8bef2019-01-30 22:47:35 +0000196// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
197// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000198static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000199 uint64_t Offset) {
200 uint8_t Buffer[5];
201 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
202 assert(SizeLen == 5);
203 Stream.pwrite((char *)Buffer, SizeLen, Offset);
204}
205
206// Write X as an signed LEB value at offset Offset in Stream, padded
207// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000208static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000209 uint64_t Offset) {
210 uint8_t Buffer[5];
211 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
212 assert(SizeLen == 5);
213 Stream.pwrite((char *)Buffer, SizeLen, Offset);
214}
215
216// Write X as a plain integer value at offset Offset in Stream.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000217static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
Sam Clegg19e8bef2019-01-30 22:47:35 +0000218 uint8_t Buffer[4];
219 support::endian::write32le(Buffer, X);
220 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
221}
222
Dan Gohman18eafb62017-02-22 01:23:18 +0000223class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000224 support::endian::Writer W;
225
Dan Gohman18eafb62017-02-22 01:23:18 +0000226 /// The target specific Wasm writer instance.
227 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
228
Dan Gohmand934cb82017-02-24 23:18:00 +0000229 // Relocations for fixing up references in the code section.
230 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000231 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000232
233 // Relocations for fixing up references in the data section.
234 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000235 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000236
Dan Gohmand934cb82017-02-24 23:18:00 +0000237 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000238 // Maps function symbols to the index of the type of the function
239 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000240 // Maps function symbols to the table element index space. Used
241 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000242 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000243 // Maps function/global symbols to the function/global/event/section index
244 // space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000245 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
246 // Maps data symbols to the Wasm segment and offset/size with the segment.
247 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000248
249 // Stores output data (index, relocations, content offset) for custom
250 // section.
251 std::vector<WasmCustomSection> CustomSections;
Thomas Livelycbda16e2019-01-17 02:29:55 +0000252 std::unique_ptr<WasmCustomSection> ProducersSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000253 // Relocations for fixing up references in the custom sections.
254 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
255 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000256
Sam Cleggc0d41192018-05-17 17:15:15 +0000257 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000258 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
259
Heejin Ahnda419bd2018-11-14 02:46:21 +0000260 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
261 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg7c395942017-09-14 23:07:53 +0000262 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000263 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000264 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000265 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000266 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000267 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000268
Dan Gohman18eafb62017-02-22 01:23:18 +0000269 // TargetObjectWriter wrappers.
270 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000271 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
272 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000273 }
274
Sam Clegg2322a932018-04-23 19:16:19 +0000275 void startSection(SectionBookkeeping &Section, unsigned SectionId);
276 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000277 void endSection(SectionBookkeeping &Section);
278
Dan Gohman18eafb62017-02-22 01:23:18 +0000279public:
Lang Hames1301a872017-10-10 01:15:10 +0000280 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
281 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000282 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000283
Dan Gohman0917c9e2018-01-15 17:06:23 +0000284private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000285 void reset() override {
286 CodeRelocations.clear();
287 DataRelocations.clear();
288 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000289 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000290 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000291 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000292 CustomSections.clear();
293 ProducersSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000294 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000295 SignatureIndices.clear();
296 Signatures.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000297 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000298 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000299 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000300 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000301 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000302 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000303 }
304
Dan Gohman18eafb62017-02-22 01:23:18 +0000305 void writeHeader(const MCAssembler &Asm);
306
307 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
308 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000309 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000310
311 void executePostLayoutBinding(MCAssembler &Asm,
312 const MCAsmLayout &Layout) override;
313
Peter Collingbourne438390f2018-05-21 18:23:50 +0000314 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000315
Sam Cleggb7787fd2017-06-20 04:04:59 +0000316 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000317 encodeULEB128(Str.size(), W.OS);
318 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000319 }
320
Heejin Ahnf208f632018-09-05 01:27:38 +0000321 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000322
Heejin Ahnda419bd2018-11-14 02:46:21 +0000323 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000324 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000325 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000326 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000327 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000328 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000329 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000330 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000331 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000332 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000333 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000334 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000335 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000336 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000337 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000338 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000339 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000340 void writeCustomSection(WasmCustomSection &CustomSection,
341 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000342 void writeCustomRelocSections();
343 void
344 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
345 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000346
Sam Clegg7c395942017-09-14 23:07:53 +0000347 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000348 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
349 uint64_t ContentsOffset);
350
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000351 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000352 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000353 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000354 void registerFunctionType(const MCSymbolWasm &Symbol);
355 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000356};
Sam Clegg9e15f352017-06-03 02:01:24 +0000357
Dan Gohman18eafb62017-02-22 01:23:18 +0000358} // end anonymous namespace
359
Dan Gohmand934cb82017-02-24 23:18:00 +0000360// Write out a section header and a patchable section size field.
361void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000362 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000363 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000364 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000365
Peter Collingbournef17b1492018-05-21 18:17:42 +0000366 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000367
368 // The section size. We don't know the size yet, so reserve enough space
369 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000370 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000371
372 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000373 Section.ContentsOffset = W.OS.tell();
374 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000375 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000376}
Dan Gohmand934cb82017-02-24 23:18:00 +0000377
Sam Clegg2322a932018-04-23 19:16:19 +0000378void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
379 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000380 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000381 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000382
383 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000384 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000385
Dan Gohmand934cb82017-02-24 23:18:00 +0000386 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000387 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000388
389 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000390 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000391}
392
393// Now that the section is complete and we know how big it is, patch up the
394// section size field at the start of the section.
395void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000396 uint64_t Size = W.OS.tell();
397 // /dev/null doesn't support seek/tell and can report offset of 0.
398 // Simply skip this patching in that case.
399 if (!Size)
400 return;
401
402 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000403 if (uint32_t(Size) != Size)
404 report_fatal_error("section size does not fit in a uint32_t");
405
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000406 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000407
408 // Write the final section size to the payload_len field, which follows
409 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000410 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000411 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000412}
413
Dan Gohman18eafb62017-02-22 01:23:18 +0000414// Emit the Wasm header.
415void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000416 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
417 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000418}
419
420void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
421 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000422 // Build a map of sections to the function that defines them, for use
423 // in recordRelocation.
424 for (const MCSymbol &S : Asm.symbols()) {
425 const auto &WS = static_cast<const MCSymbolWasm &>(S);
426 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
427 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
428 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
429 if (!Pair.second)
430 report_fatal_error("section already has a defining function: " +
431 Sec.getSectionName());
432 }
433 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000434}
435
436void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
437 const MCAsmLayout &Layout,
438 const MCFragment *Fragment,
439 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000440 uint64_t &FixedValue) {
441 MCAsmBackend &Backend = Asm.getBackend();
442 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
443 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000444 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000445 uint64_t C = Target.getConstant();
446 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
447 MCContext &Ctx = Asm.getContext();
448
Sam Cleggbafe6902017-12-15 00:17:10 +0000449 // The .init_array isn't translated as data, so don't do relocations in it.
450 if (FixupSection.getSectionName().startswith(".init_array"))
451 return;
452
Dan Gohmand934cb82017-02-24 23:18:00 +0000453 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
454 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
455 "Should not have constructed this");
456
457 // Let A, B and C being the components of Target and R be the location of
458 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
459 // If it is pcrel, we want to compute (A - B + C - R).
460
461 // In general, Wasm has no relocations for -B. It can only represent (A + C)
462 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
463 // replace B to implement it: (A - R - K + C)
464 if (IsPCRel) {
465 Ctx.reportError(
466 Fixup.getLoc(),
467 "No relocation available to represent this relative expression");
468 return;
469 }
470
471 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
472
473 if (SymB.isUndefined()) {
474 Ctx.reportError(Fixup.getLoc(),
475 Twine("symbol '") + SymB.getName() +
476 "' can not be undefined in a subtraction expression");
477 return;
478 }
479
480 assert(!SymB.isAbsolute() && "Should have been folded");
481 const MCSection &SecB = SymB.getSection();
482 if (&SecB != &FixupSection) {
483 Ctx.reportError(Fixup.getLoc(),
484 "Cannot represent a difference across sections");
485 return;
486 }
487
488 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
489 uint64_t K = SymBOffset - FixupOffset;
490 IsPCRel = true;
491 C -= K;
492 }
493
494 // We either rejected the fixup or folded B into C at this point.
495 const MCSymbolRefExpr *RefA = Target.getSymA();
496 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
497
Dan Gohmand934cb82017-02-24 23:18:00 +0000498 if (SymA && SymA->isVariable()) {
499 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000500 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
501 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
502 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000503 }
504
505 // Put any constant offset in an addend. Offsets can be negative, and
506 // LLVM expects wrapping, in contrast to wasm's immediates which can't
507 // be negative and don't wrap.
508 FixedValue = 0;
509
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000510 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000511 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000512 assert(SymA);
513
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000514 // Absolute offset within a section or a function.
515 // Currently only supported for for metadata sections.
516 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000517 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
518 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000519 if (!FixupSection.getKind().isMetadata())
520 report_fatal_error("relocations for function or section offsets are "
521 "only supported in metadata sections");
522
523 const MCSymbol *SectionSymbol = nullptr;
524 const MCSection &SecA = SymA->getSection();
525 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000526 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000527 else
528 SectionSymbol = SecA.getBeginSymbol();
529 if (!SectionSymbol)
530 report_fatal_error("section symbol is required for relocation");
531
532 C += Layout.getSymbolOffset(*SymA);
533 SymA = cast<MCSymbolWasm>(SectionSymbol);
534 }
535
Sam Cleggd1152a22019-02-04 17:28:46 +0000536 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000537 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000538 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000539 if (SymA->getName().empty())
540 report_fatal_error("relocations against un-named temporaries are not yet "
541 "supported by wasm");
542
543 SymA->setUsedInReloc();
544 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000545
Dan Gohmand934cb82017-02-24 23:18:00 +0000546 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000547 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000548
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000549 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000550 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000551 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000552 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000553 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000554 CustomSectionsRelocations[&FixupSection].push_back(Rec);
555 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000556 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000557 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000558}
559
Heejin Ahn18c56a02019-02-04 19:13:39 +0000560static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000561 if (Symbol.isVariable()) {
562 const MCExpr *Expr = Symbol.getVariableValue();
563 auto *Inner = cast<MCSymbolRefExpr>(Expr);
564 return cast<MCSymbolWasm>(&Inner->getSymbol());
565 }
566 return &Symbol;
567}
568
Dan Gohmand934cb82017-02-24 23:18:00 +0000569// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000570// by RelEntry. This value isn't used by the static linker; it just serves
571// to make the object format more readable and more likely to be directly
572// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000573uint32_t
574WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000575 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000576 case wasm::R_WASM_TABLE_INDEX_SLEB:
577 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000578 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000579 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000580 assert(Sym->isFunction());
581 return TableIndices[Sym];
582 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000583 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000584 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000585 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000586 case wasm::R_WASM_FUNCTION_INDEX_LEB:
587 case wasm::R_WASM_GLOBAL_INDEX_LEB:
588 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000589 // Provisional value is function/global/event Wasm index
Sam Clegg6c899ba2018-02-23 05:08:34 +0000590 if (!WasmIndices.count(RelEntry.Symbol))
591 report_fatal_error("symbol not found in wasm index space: " +
592 RelEntry.Symbol->getName());
593 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000594 case wasm::R_WASM_FUNCTION_OFFSET_I32:
595 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000596 const auto &Section =
597 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
598 return Section.getSectionOffset() + RelEntry.Addend;
599 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000600 case wasm::R_WASM_MEMORY_ADDR_LEB:
601 case wasm::R_WASM_MEMORY_ADDR_I32:
602 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000603 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000604 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000605 // For undefined symbols, use zero
606 if (!Sym->isDefined())
607 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000608 const wasm::WasmDataReference &Ref = DataLocations[Sym];
609 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000610 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000611 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000612 }
613 default:
614 llvm_unreachable("invalid relocation type");
615 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000616}
617
Sam Clegg759631c2017-09-15 20:54:59 +0000618static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000619 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000620 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000621
Sam Clegg63ebb812017-09-29 16:50:08 +0000622 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
623
Sam Clegg759631c2017-09-15 20:54:59 +0000624 for (const MCFragment &Frag : DataSection) {
625 if (Frag.hasInstructions())
626 report_fatal_error("only data supported in data sections");
627
628 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
629 if (Align->getValueSize() != 1)
630 report_fatal_error("only byte values supported for alignment");
631 // If nops are requested, use zeros, as this is the data section.
632 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000633 uint64_t Size =
634 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
635 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000636 DataBytes.resize(Size, Value);
637 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000638 int64_t NumValues;
639 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000640 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000641 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
642 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000643 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
644 const SmallVectorImpl<char> &Contents = LEB->getContents();
645 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000646 } else {
647 const auto &DataFrag = cast<MCDataFragment>(Frag);
648 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000649 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
650 }
651 }
652
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000653 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000654}
655
Sam Clegg60ec3032018-01-23 01:23:17 +0000656uint32_t
657WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000658 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000659 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000660 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000661 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000662 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000663 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000664
Sam Clegg25d8e682018-05-08 00:08:21 +0000665 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000666}
667
Dan Gohmand934cb82017-02-24 23:18:00 +0000668// Apply the portions of the relocation records that we can handle ourselves
669// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000670void WasmObjectWriter::applyRelocations(
671 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000672 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000673 for (const WasmRelocationEntry &RelEntry : Relocations) {
674 uint64_t Offset = ContentsOffset +
675 RelEntry.FixupSection->getSectionOffset() +
676 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000677
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000679 uint32_t Value = getProvisionalValue(RelEntry);
680
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000681 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000682 case wasm::R_WASM_FUNCTION_INDEX_LEB:
683 case wasm::R_WASM_TYPE_INDEX_LEB:
684 case wasm::R_WASM_GLOBAL_INDEX_LEB:
685 case wasm::R_WASM_MEMORY_ADDR_LEB:
686 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000687 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000688 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000689 case wasm::R_WASM_TABLE_INDEX_I32:
690 case wasm::R_WASM_MEMORY_ADDR_I32:
691 case wasm::R_WASM_FUNCTION_OFFSET_I32:
692 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000693 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000694 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000695 case wasm::R_WASM_TABLE_INDEX_SLEB:
696 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000697 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000698 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000699 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000700 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000701 }
702 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000703}
704
Heejin Ahnda419bd2018-11-14 02:46:21 +0000705void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
706 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000707 return;
708
709 SectionBookkeeping Section;
710 startSection(Section, wasm::WASM_SEC_TYPE);
711
Heejin Ahnda419bd2018-11-14 02:46:21 +0000712 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000713
Heejin Ahnda419bd2018-11-14 02:46:21 +0000714 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000715 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000716 encodeULEB128(Sig.Params.size(), W.OS);
717 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000718 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000719 encodeULEB128(Sig.Returns.size(), W.OS);
720 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000721 writeValueType(Ty);
722 }
723
724 endSection(Section);
725}
726
Sam Clegg8defa952018-02-12 22:41:29 +0000727void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000728 uint32_t DataSize,
729 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000730 if (Imports.empty())
731 return;
732
Sam Cleggf950b242017-12-11 23:03:38 +0000733 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
734
Sam Clegg9e15f352017-06-03 02:01:24 +0000735 SectionBookkeeping Section;
736 startSection(Section, wasm::WASM_SEC_IMPORT);
737
Peter Collingbournef17b1492018-05-21 18:17:42 +0000738 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000739 for (const wasm::WasmImport &Import : Imports) {
740 writeString(Import.Module);
741 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000742 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000743
744 switch (Import.Kind) {
745 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000746 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000747 break;
748 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 W.OS << char(Import.Global.Type);
750 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000751 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000752 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000753 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000754 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000755 break;
756 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000757 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000758 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000759 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000760 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000761 case wasm::WASM_EXTERNAL_EVENT:
762 encodeULEB128(Import.Event.Attribute, W.OS);
763 encodeULEB128(Import.Event.SigIndex, W.OS);
764 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000765 default:
766 llvm_unreachable("unsupported import kind");
767 }
768 }
769
770 endSection(Section);
771}
772
Sam Clegg457fb0b2017-09-15 19:50:44 +0000773void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000774 if (Functions.empty())
775 return;
776
777 SectionBookkeeping Section;
778 startSection(Section, wasm::WASM_SEC_FUNCTION);
779
Peter Collingbournef17b1492018-05-21 18:17:42 +0000780 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000781 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000782 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000783
784 endSection(Section);
785}
786
Sam Clegg7c395942017-09-14 23:07:53 +0000787void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000788 if (Globals.empty())
789 return;
790
791 SectionBookkeeping Section;
792 startSection(Section, wasm::WASM_SEC_GLOBAL);
793
Peter Collingbournef17b1492018-05-21 18:17:42 +0000794 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000795 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000796 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000797 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000798
Peter Collingbournef17b1492018-05-21 18:17:42 +0000799 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
800 encodeSLEB128(Global.InitialValue, W.OS);
801 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000802 }
803
804 endSection(Section);
805}
806
Heejin Ahnda419bd2018-11-14 02:46:21 +0000807void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
808 if (Events.empty())
809 return;
810
811 SectionBookkeeping Section;
812 startSection(Section, wasm::WASM_SEC_EVENT);
813
814 encodeULEB128(Events.size(), W.OS);
815 for (const wasm::WasmEventType &Event : Events) {
816 encodeULEB128(Event.Attribute, W.OS);
817 encodeULEB128(Event.SigIndex, W.OS);
818 }
819
820 endSection(Section);
821}
822
Sam Clegg8defa952018-02-12 22:41:29 +0000823void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000824 if (Exports.empty())
825 return;
826
827 SectionBookkeeping Section;
828 startSection(Section, wasm::WASM_SEC_EXPORT);
829
Peter Collingbournef17b1492018-05-21 18:17:42 +0000830 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000831 for (const wasm::WasmExport &Export : Exports) {
832 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000833 W.OS << char(Export.Kind);
834 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000835 }
836
837 endSection(Section);
838}
839
Sam Clegg457fb0b2017-09-15 19:50:44 +0000840void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000841 if (TableElems.empty())
842 return;
843
844 SectionBookkeeping Section;
845 startSection(Section, wasm::WASM_SEC_ELEM);
846
Peter Collingbournef17b1492018-05-21 18:17:42 +0000847 encodeULEB128(1, W.OS); // number of "segments"
848 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000849
850 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000851 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000852 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000853 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000854
Peter Collingbournef17b1492018-05-21 18:17:42 +0000855 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000856 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000857 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000858
859 endSection(Section);
860}
861
Sam Clegg457fb0b2017-09-15 19:50:44 +0000862void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
863 const MCAsmLayout &Layout,
864 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000865 if (Functions.empty())
866 return;
867
868 SectionBookkeeping Section;
869 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000870 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000871
Peter Collingbournef17b1492018-05-21 18:17:42 +0000872 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000873
874 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000875 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
Sam Clegg9e15f352017-06-03 02:01:24 +0000877 int64_t Size = 0;
878 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
879 report_fatal_error(".size expression must be evaluatable");
880
Peter Collingbournef17b1492018-05-21 18:17:42 +0000881 encodeULEB128(Size, W.OS);
882 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
883 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000884 }
885
Sam Clegg9e15f352017-06-03 02:01:24 +0000886 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000887 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000888
889 endSection(Section);
890}
891
Sam Clegg6c899ba2018-02-23 05:08:34 +0000892void WasmObjectWriter::writeDataSection() {
893 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000894 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000895
896 SectionBookkeeping Section;
897 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000898 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000899
Peter Collingbournef17b1492018-05-21 18:17:42 +0000900 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000901
Sam Clegg6c899ba2018-02-23 05:08:34 +0000902 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000903 encodeULEB128(Segment.InitFlags, W.OS); // flags
904 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
905 encodeULEB128(0, W.OS); // memory index
906 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
907 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
908 encodeSLEB128(Segment.Offset, W.OS); // offset
909 W.OS << char(wasm::WASM_OPCODE_END);
910 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000911 encodeULEB128(Segment.Data.size(), W.OS); // size
912 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
913 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000914 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000915
916 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000917 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000918
919 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000920}
921
Sam Clegg6f08c842018-04-24 18:11:36 +0000922void WasmObjectWriter::writeRelocSection(
923 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000924 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000925 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
926 // for descriptions of the reloc sections.
927
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000928 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000929 return;
930
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000931 // First, ensure the relocations are sorted in offset order. In general they
932 // should already be sorted since `recordRelocation` is called in offset
933 // order, but for the code section we combine many MC sections into single
934 // wasm section, and this order is determined by the order of Asm.Symbols()
935 // not the sections order.
936 std::stable_sort(
937 Relocs.begin(), Relocs.end(),
938 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
939 return (A.Offset + A.FixupSection->getSectionOffset()) <
940 (B.Offset + B.FixupSection->getSectionOffset());
941 });
942
Sam Clegg9e15f352017-06-03 02:01:24 +0000943 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000944 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000945
Peter Collingbournef17b1492018-05-21 18:17:42 +0000946 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000947 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000948 for (const WasmRelocationEntry &RelEntry : Relocs) {
949 uint64_t Offset =
950 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000951 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000952
Peter Collingbournef17b1492018-05-21 18:17:42 +0000953 W.OS << char(RelEntry.Type);
954 encodeULEB128(Offset, W.OS);
955 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000956 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000957 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000958 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000959
960 endSection(Section);
961}
962
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000963void WasmObjectWriter::writeCustomRelocSections() {
964 for (const auto &Sec : CustomSections) {
965 auto &Relocations = CustomSectionsRelocations[Sec.Section];
966 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
967 }
968}
969
Sam Clegg9e15f352017-06-03 02:01:24 +0000970void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000971 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000972 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000973 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000974 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000975 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000976 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000977
Sam Clegg6bb5a412018-04-26 18:15:32 +0000978 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000979 if (SymbolInfos.size() != 0) {
980 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000981 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000982 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000983 encodeULEB128(Sym.Kind, W.OS);
984 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000985 switch (Sym.Kind) {
986 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
987 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000988 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000989 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000990 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
991 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000992 writeString(Sym.Name);
993 break;
994 case wasm::WASM_SYMBOL_TYPE_DATA:
995 writeString(Sym.Name);
996 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000997 encodeULEB128(Sym.DataRef.Segment, W.OS);
998 encodeULEB128(Sym.DataRef.Offset, W.OS);
999 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001000 }
1001 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001002 case wasm::WASM_SYMBOL_TYPE_SECTION: {
1003 const uint32_t SectionIndex =
1004 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +00001005 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001006 break;
1007 }
Sam Clegg6c899ba2018-02-23 05:08:34 +00001008 default:
1009 llvm_unreachable("unexpected kind");
1010 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001011 }
1012 endSection(SubSection);
1013 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001014
Sam Clegg6c899ba2018-02-23 05:08:34 +00001015 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001016 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001017 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001018 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001019 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001020 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +00001021 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001022 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001023 endSection(SubSection);
1024 }
1025
Sam Cleggbafe6902017-12-15 00:17:10 +00001026 if (!InitFuncs.empty()) {
1027 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001028 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001029 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001030 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001031 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001032 }
1033 endSection(SubSection);
1034 }
1035
Sam Cleggea7cace2018-01-09 23:43:14 +00001036 if (Comdats.size()) {
1037 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001038 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001039 for (const auto &C : Comdats) {
1040 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001041 encodeULEB128(0, W.OS); // flags for future use
1042 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001043 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001044 encodeULEB128(Entry.Kind, W.OS);
1045 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001046 }
1047 }
1048 endSection(SubSection);
1049 }
1050
Sam Clegg9e15f352017-06-03 02:01:24 +00001051 endSection(Section);
1052}
1053
Thomas Livelycbda16e2019-01-17 02:29:55 +00001054void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1055 const MCAssembler &Asm,
1056 const MCAsmLayout &Layout) {
1057 SectionBookkeeping Section;
1058 auto *Sec = CustomSection.Section;
1059 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001060
Thomas Livelycbda16e2019-01-17 02:29:55 +00001061 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1062 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001063
Thomas Livelycbda16e2019-01-17 02:29:55 +00001064 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1065 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001066
Thomas Livelycbda16e2019-01-17 02:29:55 +00001067 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001068
Thomas Livelycbda16e2019-01-17 02:29:55 +00001069 // Apply fixups.
1070 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1071 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001072}
1073
Heejin Ahnf208f632018-09-05 01:27:38 +00001074uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001075 assert(Symbol.isFunction());
1076 assert(TypeIndices.count(&Symbol));
1077 return TypeIndices[&Symbol];
1078}
1079
Heejin Ahnda419bd2018-11-14 02:46:21 +00001080uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1081 assert(Symbol.isEvent());
1082 assert(TypeIndices.count(&Symbol));
1083 return TypeIndices[&Symbol];
1084}
1085
Heejin Ahn38b12f52018-11-20 00:38:10 +00001086void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001087 assert(Symbol.isFunction());
1088
Heejin Ahnda419bd2018-11-14 02:46:21 +00001089 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001090 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001091 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001092 S.Returns = Sig->Returns;
1093 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001094 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001095
Heejin Ahnda419bd2018-11-14 02:46:21 +00001096 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001097 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001098 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001099 TypeIndices[&Symbol] = Pair.first->second;
1100
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001101 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1102 << " new:" << Pair.second << "\n");
1103 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001104}
1105
Heejin Ahn38b12f52018-11-20 00:38:10 +00001106void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001107 assert(Symbol.isEvent());
1108
1109 // TODO Currently we don't generate imported exceptions, but if we do, we
1110 // should have a way of infering types of imported exceptions.
1111 WasmSignature S;
1112 if (auto *Sig = Symbol.getSignature()) {
1113 S.Returns = Sig->Returns;
1114 S.Params = Sig->Params;
1115 }
1116
1117 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1118 if (Pair.second)
1119 Signatures.push_back(S);
1120 TypeIndices[&Symbol] = Pair.first->second;
1121
1122 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1123 << "\n");
1124 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001125}
1126
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001127static bool isInSymtab(const MCSymbolWasm &Sym) {
1128 if (Sym.isUsedInReloc())
1129 return true;
1130
1131 if (Sym.isComdat() && !Sym.isDefined())
1132 return false;
1133
1134 if (Sym.isTemporary() && Sym.getName().empty())
1135 return false;
1136
1137 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1138 return false;
1139
1140 if (Sym.isSection())
1141 return false;
1142
1143 return true;
1144}
1145
Peter Collingbourne438390f2018-05-21 18:23:50 +00001146uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1147 const MCAsmLayout &Layout) {
1148 uint64_t StartOffset = W.OS.tell();
1149
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001150 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohman82607f52017-02-24 23:46:05 +00001151 MCContext &Ctx = Asm.getContext();
Dan Gohmand934cb82017-02-24 23:18:00 +00001152
1153 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001154 SmallVector<WasmFunction, 4> Functions;
1155 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001156 SmallVector<wasm::WasmImport, 4> Imports;
1157 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001158 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001159 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001160 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001161 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001162 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001163
Sam Cleggf950b242017-12-11 23:03:38 +00001164 // For now, always emit the memory import, since loads and stores are not
1165 // valid without it. In the future, we could perhaps be more clever and omit
1166 // it if there are no loads or stores.
Heejin Ahn18c56a02019-02-04 19:13:39 +00001167 auto *MemorySym =
Sam Cleggf950b242017-12-11 23:03:38 +00001168 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__linear_memory"));
Sam Clegg8defa952018-02-12 22:41:29 +00001169 wasm::WasmImport MemImport;
Dan Gohmanf726e442019-02-01 22:27:34 +00001170 MemImport.Module = MemorySym->getImportModule();
1171 MemImport.Field = MemorySym->getImportName();
Sam Cleggf950b242017-12-11 23:03:38 +00001172 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1173 Imports.push_back(MemImport);
1174
1175 // For now, always emit the table section, since indirect calls are not
1176 // valid without it. In the future, we could perhaps be more clever and omit
1177 // it if there are no indirect calls.
Heejin Ahn18c56a02019-02-04 19:13:39 +00001178 auto *TableSym =
Sam Cleggf950b242017-12-11 23:03:38 +00001179 cast<MCSymbolWasm>(Ctx.getOrCreateSymbol("__indirect_function_table"));
Sam Clegg8defa952018-02-12 22:41:29 +00001180 wasm::WasmImport TableImport;
Dan Gohmanf726e442019-02-01 22:27:34 +00001181 TableImport.Module = TableSym->getImportModule();
1182 TableImport.Field = TableSym->getImportName();
Sam Cleggf950b242017-12-11 23:03:38 +00001183 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001184 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001185 Imports.push_back(TableImport);
1186
Heejin Ahnda419bd2018-11-14 02:46:21 +00001187 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001188 // symbols. This must be done before populating WasmIndices for defined
1189 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001190 for (const MCSymbol &S : Asm.symbols()) {
1191 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1192
1193 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001194 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001195 if (WS.isFunction())
1196 registerFunctionType(WS);
1197
Heejin Ahnda419bd2018-11-14 02:46:21 +00001198 if (WS.isEvent())
1199 registerEventType(WS);
1200
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001201 if (WS.isTemporary())
1202 continue;
1203
1204 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001205 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001206 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001207 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001208 Import.Module = WS.getImportModule();
1209 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001210 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001211 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001212 Imports.push_back(Import);
1213 WasmIndices[&WS] = NumFunctionImports++;
1214 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001215 if (WS.isWeak())
1216 report_fatal_error("undefined global symbol cannot be weak");
1217
Sam Clegg6c899ba2018-02-23 05:08:34 +00001218 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001219 Import.Module = WS.getImportModule();
1220 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001221 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001222 Import.Global = WS.getGlobalType();
1223 Imports.push_back(Import);
1224 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001225 } else if (WS.isEvent()) {
1226 if (WS.isWeak())
1227 report_fatal_error("undefined event symbol cannot be weak");
1228
1229 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001230 Import.Module = WS.getImportModule();
1231 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001232 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1233 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1234 Import.Event.SigIndex = getEventType(WS);
1235 Imports.push_back(Import);
1236 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001237 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001238 }
1239 }
1240
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001241 // Populate DataSegments and CustomSections, which must be done before
1242 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001243 for (MCSection &Sec : Asm) {
1244 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001245 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001246
Sam Cleggbafe6902017-12-15 00:17:10 +00001247 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001248 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001249 continue;
1250
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001251 // Code is handled separately
1252 if (Section.getKind().isText())
1253 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001254
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001255 if (Section.isWasmData()) {
1256 uint32_t SegmentIndex = DataSegments.size();
1257 DataSize = alignTo(DataSize, Section.getAlignment());
1258 DataSegments.emplace_back();
1259 WasmDataSegment &Segment = DataSegments.back();
1260 Segment.Name = SectionName;
Thomas Lively2e150402019-02-19 22:56:19 +00001261 Segment.InitFlags = Section.getPassive() ? wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001262 Segment.Offset = DataSize;
1263 Segment.Section = &Section;
1264 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001265 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001266 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001267 DataSize += Segment.Data.size();
1268 Section.setSegmentIndex(SegmentIndex);
1269
1270 if (const MCSymbolWasm *C = Section.getGroup()) {
1271 Comdats[C->getName()].emplace_back(
1272 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1273 }
1274 } else {
1275 // Create custom sections
1276 assert(Sec.getKind().isMetadata());
1277
1278 StringRef Name = SectionName;
1279
1280 // For user-defined custom sections, strip the prefix
1281 if (Name.startswith(".custom_section."))
1282 Name = Name.substr(strlen(".custom_section."));
1283
Heejin Ahnf208f632018-09-05 01:27:38 +00001284 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001285 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001286 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001287 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001288 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001289 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001290 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001291
1292 // Separate out the producers section
1293 if (Name == "producers") {
1294 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1295 continue;
1296 }
1297
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001298 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001299 }
Sam Clegg759631c2017-09-15 20:54:59 +00001300 }
1301
Nicholas Wilson586320c2018-02-28 17:19:48 +00001302 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001303 for (const MCSymbol &S : Asm.symbols()) {
1304 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1305 // or used in relocations.
1306 if (S.isTemporary() && S.getName().empty())
1307 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001308
Dan Gohmand934cb82017-02-24 23:18:00 +00001309 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001310 LLVM_DEBUG(
1311 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1312 << " isDefined=" << S.isDefined() << " isExternal="
1313 << S.isExternal() << " isTemporary=" << S.isTemporary()
1314 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1315 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001316
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001317 if (WS.isVariable())
1318 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001319 if (WS.isComdat() && !WS.isDefined())
1320 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001321
Dan Gohmand934cb82017-02-24 23:18:00 +00001322 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001323 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001324 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001325 if (WS.getOffset() != 0)
1326 report_fatal_error(
1327 "function sections must contain one function each");
1328
Heejin Ahn18c56a02019-02-04 19:13:39 +00001329 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001330 report_fatal_error(
1331 "function symbols must have a size set with .size");
1332
Sam Clegg6c899ba2018-02-23 05:08:34 +00001333 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001334 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001335 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001336 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001337 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001338 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001339 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001340
1341 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1342 if (const MCSymbolWasm *C = Section.getGroup()) {
1343 Comdats[C->getName()].emplace_back(
1344 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1345 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001346 } else {
1347 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001348 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001349 }
1350
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001351 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001352
Sam Clegg6c899ba2018-02-23 05:08:34 +00001353 } else if (WS.isData()) {
Sam Cleggc38e9472017-06-02 01:05:24 +00001354 if (WS.isTemporary() && !WS.getSize())
1355 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001356
Sam Clegg6c899ba2018-02-23 05:08:34 +00001357 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001358 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1359 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001360 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001361 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001362
Sam Cleggfe6414b2017-06-21 23:46:41 +00001363 if (!WS.getSize())
1364 report_fatal_error("data symbols must have a size set with .size: " +
1365 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001366
Sam Cleggfe6414b2017-06-21 23:46:41 +00001367 int64_t Size = 0;
1368 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1369 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001370
Sam Clegg759631c2017-09-15 20:54:59 +00001371 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001372 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001373
Sam Clegg6c899ba2018-02-23 05:08:34 +00001374 // For each data symbol, export it in the symtab as a reference to the
1375 // corresponding Wasm data segment.
1376 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1377 DataSection.getSegmentIndex(),
1378 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1379 static_cast<uint32_t>(Size)};
1380 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001381 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001382
Sam Clegga165f2d2018-04-30 19:40:57 +00001383 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001384 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001385 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001386 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001387
Eric Christopher545932b2018-02-23 21:14:47 +00001388 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001389 LLVM_DEBUG(dbgs() << " -> global index: "
1390 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001391
1392 } else if (WS.isEvent()) {
1393 // C++ exception symbol (__cpp_exception)
1394 unsigned Index;
1395 if (WS.isDefined()) {
1396 Index = NumEventImports + Events.size();
1397 wasm::WasmEventType Event;
1398 Event.SigIndex = getEventType(WS);
1399 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1400 WasmIndices[&WS] = Index;
1401 Events.push_back(Event);
1402 } else {
1403 // An import; the index was assigned above.
1404 Index = WasmIndices.find(&WS)->second;
1405 }
1406 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1407 << "\n");
1408
Sam Clegga165f2d2018-04-30 19:40:57 +00001409 } else {
1410 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001411 }
1412 }
1413
Nicholas Wilson586320c2018-02-28 17:19:48 +00001414 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1415 // process these in a separate pass because we need to have processed the
1416 // target of the alias before the alias itself and the symbols are not
1417 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001418 for (const MCSymbol &S : Asm.symbols()) {
1419 if (!S.isVariable())
1420 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001421
Sam Cleggcd65f692018-01-11 23:59:16 +00001422 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001423
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001424 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001425 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001426 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001427 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1428 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001429
Sam Clegg6c899ba2018-02-23 05:08:34 +00001430 if (WS.isFunction()) {
1431 assert(WasmIndices.count(ResolvedSym) > 0);
1432 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1433 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001434 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001435 } else if (WS.isData()) {
1436 assert(DataLocations.count(ResolvedSym) > 0);
1437 const wasm::WasmDataReference &Ref =
1438 DataLocations.find(ResolvedSym)->second;
1439 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001440 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001441 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001442 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001443 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001444 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001445
Nicholas Wilson586320c2018-02-28 17:19:48 +00001446 // Finally, populate the symbol table itself, in its "natural" order.
1447 for (const MCSymbol &S : Asm.symbols()) {
1448 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001449 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001450 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001451 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001452 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001453 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001454
1455 uint32_t Flags = 0;
1456 if (WS.isWeak())
1457 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1458 if (WS.isHidden())
1459 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1460 if (!WS.isExternal() && WS.isDefined())
1461 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1462 if (WS.isUndefined())
1463 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001464 if (WS.isExported())
1465 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Dan Gohman29874ce2019-02-07 22:03:32 +00001466 if (WS.getName() != WS.getImportName())
1467 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001468
1469 wasm::WasmSymbolInfo Info;
1470 Info.Name = WS.getName();
1471 Info.Kind = WS.getType();
1472 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001473 if (!WS.isData()) {
1474 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001475 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001476 } else if (WS.isDefined()) {
1477 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001478 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001479 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001480 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001481 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001482 }
1483
Sam Clegg6006e092017-12-22 20:31:39 +00001484 {
1485 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001486 // Functions referenced by a relocation need to put in the table. This is
1487 // purely to make the object file's provisional values readable, and is
1488 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001489 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1490 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001491 return;
1492 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001493 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001494 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001495 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001496 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001497 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1498 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001499 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001500 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001501 }
1502 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001503
Sam Clegg6006e092017-12-22 20:31:39 +00001504 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1505 HandleReloc(RelEntry);
1506 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1507 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001508 }
1509
Sam Cleggbafe6902017-12-15 00:17:10 +00001510 // Translate .init_array section contents into start functions.
1511 for (const MCSection &S : Asm) {
1512 const auto &WS = static_cast<const MCSectionWasm &>(S);
1513 if (WS.getSectionName().startswith(".fini_array"))
1514 report_fatal_error(".fini_array sections are unsupported");
1515 if (!WS.getSectionName().startswith(".init_array"))
1516 continue;
1517 if (WS.getFragmentList().empty())
1518 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001519
1520 // init_array is expected to contain a single non-empty data fragment
1521 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001522 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001523
1524 auto IT = WS.begin();
1525 const MCFragment &EmptyFrag = *IT;
1526 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1527 report_fatal_error(".init_array section should be aligned");
1528
1529 IT = std::next(IT);
1530 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001531 if (AlignFrag.getKind() != MCFragment::FT_Align)
1532 report_fatal_error(".init_array section should be aligned");
1533 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1534 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001535
1536 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001537 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1538 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001539
Sam Cleggbafe6902017-12-15 00:17:10 +00001540 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001541 unsigned PrefixLength = strlen(".init_array");
1542 if (WS.getSectionName().size() > PrefixLength) {
1543 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001544 report_fatal_error(
1545 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001546 if (WS.getSectionName()
1547 .substr(PrefixLength + 1)
1548 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001549 report_fatal_error("invalid .init_array section priority");
1550 }
1551 const auto &DataFrag = cast<MCDataFragment>(Frag);
1552 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001553 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001554 P = (const uint8_t *)Contents.data(),
1555 *End = (const uint8_t *)Contents.data() + Contents.size();
1556 P != End; ++P) {
1557 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001558 report_fatal_error("non-symbolic data in .init_array section");
1559 }
1560 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001561 assert(Fixup.getKind() ==
1562 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001563 const MCExpr *Expr = Fixup.getValue();
1564 auto *Sym = dyn_cast<MCSymbolRefExpr>(Expr);
1565 if (!Sym)
1566 report_fatal_error("fixups in .init_array should be symbol references");
1567 if (Sym->getKind() != MCSymbolRefExpr::VK_WebAssembly_FUNCTION)
1568 report_fatal_error("symbols in .init_array should be for functions");
Heejin Ahn18c56a02019-02-04 19:13:39 +00001569 if (Sym->getSymbol().getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001570 report_fatal_error("symbols in .init_array should exist in symbtab");
1571 InitFuncs.push_back(
1572 std::make_pair(Priority, Sym->getSymbol().getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001573 }
1574 }
1575
Dan Gohman18eafb62017-02-22 01:23:18 +00001576 // Write out the Wasm header.
1577 writeHeader(Asm);
1578
Heejin Ahnda419bd2018-11-14 02:46:21 +00001579 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001580 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001581 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001582 // Skip the "table" section; we import the table instead.
1583 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001584 writeGlobalSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001585 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001586 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001587 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001588 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001589 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001590 for (auto &CustomSection : CustomSections)
1591 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001592 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001593 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1594 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001595 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001596 if (ProducersSection)
1597 writeCustomSection(*ProducersSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001598
Dan Gohmand934cb82017-02-24 23:18:00 +00001599 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001600 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001601}
1602
Lang Hames60fbc7c2017-10-10 16:28:07 +00001603std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001604llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1605 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001606 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001607}