blob: 0014b695b9006a3d8ea7d258450b66fd8494b4a9 [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;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000253 std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000254 // Relocations for fixing up references in the custom sections.
255 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
256 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000257
Sam Cleggc0d41192018-05-17 17:15:15 +0000258 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000259 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
260
Heejin Ahnda419bd2018-11-14 02:46:21 +0000261 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
262 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg7c395942017-09-14 23:07:53 +0000263 SmallVector<WasmGlobal, 4> Globals;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000264 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000265 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000266 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000267 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000268 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000269
Dan Gohman18eafb62017-02-22 01:23:18 +0000270 // TargetObjectWriter wrappers.
271 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000272 unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup) const {
273 return TargetObjectWriter->getRelocType(Target, Fixup);
Dan Gohman18eafb62017-02-22 01:23:18 +0000274 }
275
Sam Clegg2322a932018-04-23 19:16:19 +0000276 void startSection(SectionBookkeeping &Section, unsigned SectionId);
277 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000278 void endSection(SectionBookkeeping &Section);
279
Dan Gohman18eafb62017-02-22 01:23:18 +0000280public:
Lang Hames1301a872017-10-10 01:15:10 +0000281 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
282 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000283 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000284
Dan Gohman0917c9e2018-01-15 17:06:23 +0000285private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000286 void reset() override {
287 CodeRelocations.clear();
288 DataRelocations.clear();
289 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000290 WasmIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000291 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000292 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000293 CustomSections.clear();
294 ProducersSection.reset();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000295 TargetFeaturesSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000296 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000297 SignatureIndices.clear();
298 Signatures.clear();
Sam Clegg7c395942017-09-14 23:07:53 +0000299 Globals.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000300 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000301 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000302 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000303 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000304 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000305 }
306
Dan Gohman18eafb62017-02-22 01:23:18 +0000307 void writeHeader(const MCAssembler &Asm);
308
309 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
310 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000311 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000312
313 void executePostLayoutBinding(MCAssembler &Asm,
314 const MCAsmLayout &Layout) override;
315
Peter Collingbourne438390f2018-05-21 18:23:50 +0000316 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000317
Sam Cleggb7787fd2017-06-20 04:04:59 +0000318 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000319 encodeULEB128(Str.size(), W.OS);
320 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000321 }
322
Heejin Ahnf208f632018-09-05 01:27:38 +0000323 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000324
Heejin Ahnda419bd2018-11-14 02:46:21 +0000325 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000326 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000327 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000328 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg7c395942017-09-14 23:07:53 +0000329 void writeGlobalSection();
Sam Clegg8defa952018-02-12 22:41:29 +0000330 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000331 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000332 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000333 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000334 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000335 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000336 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000337 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000338 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000339 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000340 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000341 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000342 void writeCustomSection(WasmCustomSection &CustomSection,
343 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000344 void writeCustomRelocSections();
345 void
346 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
347 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000348
Sam Clegg7c395942017-09-14 23:07:53 +0000349 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000350 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
351 uint64_t ContentsOffset);
352
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000353 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000354 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000355 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000356 void registerFunctionType(const MCSymbolWasm &Symbol);
357 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000358};
Sam Clegg9e15f352017-06-03 02:01:24 +0000359
Dan Gohman18eafb62017-02-22 01:23:18 +0000360} // end anonymous namespace
361
Dan Gohmand934cb82017-02-24 23:18:00 +0000362// Write out a section header and a patchable section size field.
363void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000364 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000365 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000366 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000367
Peter Collingbournef17b1492018-05-21 18:17:42 +0000368 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000369
370 // The section size. We don't know the size yet, so reserve enough space
371 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000372 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000373
374 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000375 Section.ContentsOffset = W.OS.tell();
376 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000377 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000378}
Dan Gohmand934cb82017-02-24 23:18:00 +0000379
Sam Clegg2322a932018-04-23 19:16:19 +0000380void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
381 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000382 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000383 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000384
385 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000386 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000387
Dan Gohmand934cb82017-02-24 23:18:00 +0000388 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000389 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000390
391 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000392 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000393}
394
395// Now that the section is complete and we know how big it is, patch up the
396// section size field at the start of the section.
397void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000398 uint64_t Size = W.OS.tell();
399 // /dev/null doesn't support seek/tell and can report offset of 0.
400 // Simply skip this patching in that case.
401 if (!Size)
402 return;
403
404 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000405 if (uint32_t(Size) != Size)
406 report_fatal_error("section size does not fit in a uint32_t");
407
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000409
410 // Write the final section size to the payload_len field, which follows
411 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000412 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000413 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000414}
415
Dan Gohman18eafb62017-02-22 01:23:18 +0000416// Emit the Wasm header.
417void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000418 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
419 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000420}
421
422void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
423 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000424 // Build a map of sections to the function that defines them, for use
425 // in recordRelocation.
426 for (const MCSymbol &S : Asm.symbols()) {
427 const auto &WS = static_cast<const MCSymbolWasm &>(S);
428 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
429 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
430 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
431 if (!Pair.second)
432 report_fatal_error("section already has a defining function: " +
433 Sec.getSectionName());
434 }
435 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000436}
437
438void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
439 const MCAsmLayout &Layout,
440 const MCFragment *Fragment,
441 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000442 uint64_t &FixedValue) {
443 MCAsmBackend &Backend = Asm.getBackend();
444 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
445 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000446 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000447 uint64_t C = Target.getConstant();
448 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
449 MCContext &Ctx = Asm.getContext();
450
Sam Cleggbafe6902017-12-15 00:17:10 +0000451 // The .init_array isn't translated as data, so don't do relocations in it.
452 if (FixupSection.getSectionName().startswith(".init_array"))
453 return;
454
Dan Gohmand934cb82017-02-24 23:18:00 +0000455 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
456 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
457 "Should not have constructed this");
458
459 // Let A, B and C being the components of Target and R be the location of
460 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
461 // If it is pcrel, we want to compute (A - B + C - R).
462
463 // In general, Wasm has no relocations for -B. It can only represent (A + C)
464 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
465 // replace B to implement it: (A - R - K + C)
466 if (IsPCRel) {
467 Ctx.reportError(
468 Fixup.getLoc(),
469 "No relocation available to represent this relative expression");
470 return;
471 }
472
473 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
474
475 if (SymB.isUndefined()) {
476 Ctx.reportError(Fixup.getLoc(),
477 Twine("symbol '") + SymB.getName() +
478 "' can not be undefined in a subtraction expression");
479 return;
480 }
481
482 assert(!SymB.isAbsolute() && "Should have been folded");
483 const MCSection &SecB = SymB.getSection();
484 if (&SecB != &FixupSection) {
485 Ctx.reportError(Fixup.getLoc(),
486 "Cannot represent a difference across sections");
487 return;
488 }
489
490 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
491 uint64_t K = SymBOffset - FixupOffset;
492 IsPCRel = true;
493 C -= K;
494 }
495
496 // We either rejected the fixup or folded B into C at this point.
497 const MCSymbolRefExpr *RefA = Target.getSymA();
498 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
499
Dan Gohmand934cb82017-02-24 23:18:00 +0000500 if (SymA && SymA->isVariable()) {
501 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000502 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
503 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
504 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000505 }
506
507 // Put any constant offset in an addend. Offsets can be negative, and
508 // LLVM expects wrapping, in contrast to wasm's immediates which can't
509 // be negative and don't wrap.
510 FixedValue = 0;
511
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000512 unsigned Type = getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000513 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000514 assert(SymA);
515
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000516 // Absolute offset within a section or a function.
517 // Currently only supported for for metadata sections.
518 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000519 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
520 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000521 if (!FixupSection.getKind().isMetadata())
522 report_fatal_error("relocations for function or section offsets are "
523 "only supported in metadata sections");
524
525 const MCSymbol *SectionSymbol = nullptr;
526 const MCSection &SecA = SymA->getSection();
527 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000528 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000529 else
530 SectionSymbol = SecA.getBeginSymbol();
531 if (!SectionSymbol)
532 report_fatal_error("section symbol is required for relocation");
533
534 C += Layout.getSymbolOffset(*SymA);
535 SymA = cast<MCSymbolWasm>(SectionSymbol);
536 }
537
Sam Cleggd1152a22019-02-04 17:28:46 +0000538 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000539 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000540 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000541 if (SymA->getName().empty())
542 report_fatal_error("relocations against un-named temporaries are not yet "
543 "supported by wasm");
544
545 SymA->setUsedInReloc();
546 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000547
Dan Gohmand934cb82017-02-24 23:18:00 +0000548 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000549 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000550
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000551 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000552 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000553 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000554 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000555 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000556 CustomSectionsRelocations[&FixupSection].push_back(Rec);
557 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000558 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000559 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000560}
561
Heejin Ahn18c56a02019-02-04 19:13:39 +0000562static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggffba00b2019-02-22 21:41:42 +0000563 const MCSymbolWasm* Ret = &Symbol;
564 while (Ret->isVariable()) {
565 const MCExpr *Expr = Ret->getVariableValue();
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000566 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Cleggffba00b2019-02-22 21:41:42 +0000567 Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000568 }
Sam Cleggffba00b2019-02-22 21:41:42 +0000569 return Ret;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000570}
571
Dan Gohmand934cb82017-02-24 23:18:00 +0000572// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000573// by RelEntry. This value isn't used by the static linker; it just serves
574// to make the object format more readable and more likely to be directly
575// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000576uint32_t
577WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg60ec3032018-01-23 01:23:17 +0000578 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000579 case wasm::R_WASM_TABLE_INDEX_SLEB:
580 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000581 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000582 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000583 assert(Sym->isFunction());
584 return TableIndices[Sym];
585 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000586 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000587 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000588 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000589 case wasm::R_WASM_FUNCTION_INDEX_LEB:
590 case wasm::R_WASM_GLOBAL_INDEX_LEB:
591 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000592 // Provisional value is function/global/event Wasm index
Sam Clegg6c899ba2018-02-23 05:08:34 +0000593 if (!WasmIndices.count(RelEntry.Symbol))
594 report_fatal_error("symbol not found in wasm index space: " +
595 RelEntry.Symbol->getName());
596 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000597 case wasm::R_WASM_FUNCTION_OFFSET_I32:
598 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000599 const auto &Section =
600 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
601 return Section.getSectionOffset() + RelEntry.Addend;
602 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000603 case wasm::R_WASM_MEMORY_ADDR_LEB:
604 case wasm::R_WASM_MEMORY_ADDR_I32:
605 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000606 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000607 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000608 // For undefined symbols, use zero
609 if (!Sym->isDefined())
610 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000611 const wasm::WasmDataReference &Ref = DataLocations[Sym];
612 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000613 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000614 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000615 }
616 default:
617 llvm_unreachable("invalid relocation type");
618 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000619}
620
Sam Clegg759631c2017-09-15 20:54:59 +0000621static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000622 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000623 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000624
Sam Clegg63ebb812017-09-29 16:50:08 +0000625 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
626
Sam Clegg759631c2017-09-15 20:54:59 +0000627 for (const MCFragment &Frag : DataSection) {
628 if (Frag.hasInstructions())
629 report_fatal_error("only data supported in data sections");
630
631 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
632 if (Align->getValueSize() != 1)
633 report_fatal_error("only byte values supported for alignment");
634 // If nops are requested, use zeros, as this is the data section.
635 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000636 uint64_t Size =
637 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
638 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000639 DataBytes.resize(Size, Value);
640 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000641 int64_t NumValues;
642 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000643 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000644 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
645 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000646 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
647 const SmallVectorImpl<char> &Contents = LEB->getContents();
648 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000649 } else {
650 const auto &DataFrag = cast<MCDataFragment>(Frag);
651 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000652 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
653 }
654 }
655
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000657}
658
Sam Clegg60ec3032018-01-23 01:23:17 +0000659uint32_t
660WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000661 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000662 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000663 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000664 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000665 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000666 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000667
Sam Clegg25d8e682018-05-08 00:08:21 +0000668 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000669}
670
Dan Gohmand934cb82017-02-24 23:18:00 +0000671// Apply the portions of the relocation records that we can handle ourselves
672// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000673void WasmObjectWriter::applyRelocations(
674 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000675 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000676 for (const WasmRelocationEntry &RelEntry : Relocations) {
677 uint64_t Offset = ContentsOffset +
678 RelEntry.FixupSection->getSectionOffset() +
679 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000680
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000681 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000682 uint32_t Value = getProvisionalValue(RelEntry);
683
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000684 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000685 case wasm::R_WASM_FUNCTION_INDEX_LEB:
686 case wasm::R_WASM_TYPE_INDEX_LEB:
687 case wasm::R_WASM_GLOBAL_INDEX_LEB:
688 case wasm::R_WASM_MEMORY_ADDR_LEB:
689 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000690 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000691 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000692 case wasm::R_WASM_TABLE_INDEX_I32:
693 case wasm::R_WASM_MEMORY_ADDR_I32:
694 case wasm::R_WASM_FUNCTION_OFFSET_I32:
695 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000696 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000697 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000698 case wasm::R_WASM_TABLE_INDEX_SLEB:
699 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000700 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000701 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000702 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000703 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000704 }
705 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000706}
707
Heejin Ahnda419bd2018-11-14 02:46:21 +0000708void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
709 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000710 return;
711
712 SectionBookkeeping Section;
713 startSection(Section, wasm::WASM_SEC_TYPE);
714
Heejin Ahnda419bd2018-11-14 02:46:21 +0000715 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000716
Heejin Ahnda419bd2018-11-14 02:46:21 +0000717 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000718 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000719 encodeULEB128(Sig.Params.size(), W.OS);
720 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000721 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000722 encodeULEB128(Sig.Returns.size(), W.OS);
723 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000724 writeValueType(Ty);
725 }
726
727 endSection(Section);
728}
729
Sam Clegg8defa952018-02-12 22:41:29 +0000730void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000731 uint32_t DataSize,
732 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000733 if (Imports.empty())
734 return;
735
Sam Cleggf950b242017-12-11 23:03:38 +0000736 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
737
Sam Clegg9e15f352017-06-03 02:01:24 +0000738 SectionBookkeeping Section;
739 startSection(Section, wasm::WASM_SEC_IMPORT);
740
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000742 for (const wasm::WasmImport &Import : Imports) {
743 writeString(Import.Module);
744 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000745 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000746
747 switch (Import.Kind) {
748 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 break;
751 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000752 W.OS << char(Import.Global.Type);
753 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000754 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000755 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000756 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000757 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000758 break;
759 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000760 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000761 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000762 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000763 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000764 case wasm::WASM_EXTERNAL_EVENT:
765 encodeULEB128(Import.Event.Attribute, W.OS);
766 encodeULEB128(Import.Event.SigIndex, W.OS);
767 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000768 default:
769 llvm_unreachable("unsupported import kind");
770 }
771 }
772
773 endSection(Section);
774}
775
Sam Clegg457fb0b2017-09-15 19:50:44 +0000776void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000777 if (Functions.empty())
778 return;
779
780 SectionBookkeeping Section;
781 startSection(Section, wasm::WASM_SEC_FUNCTION);
782
Peter Collingbournef17b1492018-05-21 18:17:42 +0000783 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000784 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000785 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000786
787 endSection(Section);
788}
789
Sam Clegg7c395942017-09-14 23:07:53 +0000790void WasmObjectWriter::writeGlobalSection() {
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 if (Globals.empty())
792 return;
793
794 SectionBookkeeping Section;
795 startSection(Section, wasm::WASM_SEC_GLOBAL);
796
Peter Collingbournef17b1492018-05-21 18:17:42 +0000797 encodeULEB128(Globals.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000798 for (const WasmGlobal &Global : Globals) {
Sam Clegg6e7f1822018-01-31 19:50:14 +0000799 writeValueType(static_cast<wasm::ValType>(Global.Type.Type));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000800 W.OS << char(Global.Type.Mutable);
Sam Clegg9e15f352017-06-03 02:01:24 +0000801
Peter Collingbournef17b1492018-05-21 18:17:42 +0000802 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
803 encodeSLEB128(Global.InitialValue, W.OS);
804 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000805 }
806
807 endSection(Section);
808}
809
Heejin Ahnda419bd2018-11-14 02:46:21 +0000810void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
811 if (Events.empty())
812 return;
813
814 SectionBookkeeping Section;
815 startSection(Section, wasm::WASM_SEC_EVENT);
816
817 encodeULEB128(Events.size(), W.OS);
818 for (const wasm::WasmEventType &Event : Events) {
819 encodeULEB128(Event.Attribute, W.OS);
820 encodeULEB128(Event.SigIndex, W.OS);
821 }
822
823 endSection(Section);
824}
825
Sam Clegg8defa952018-02-12 22:41:29 +0000826void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000827 if (Exports.empty())
828 return;
829
830 SectionBookkeeping Section;
831 startSection(Section, wasm::WASM_SEC_EXPORT);
832
Peter Collingbournef17b1492018-05-21 18:17:42 +0000833 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000834 for (const wasm::WasmExport &Export : Exports) {
835 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000836 W.OS << char(Export.Kind);
837 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000838 }
839
840 endSection(Section);
841}
842
Sam Clegg457fb0b2017-09-15 19:50:44 +0000843void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000844 if (TableElems.empty())
845 return;
846
847 SectionBookkeeping Section;
848 startSection(Section, wasm::WASM_SEC_ELEM);
849
Peter Collingbournef17b1492018-05-21 18:17:42 +0000850 encodeULEB128(1, W.OS); // number of "segments"
851 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000852
853 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000854 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000855 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000856 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000857
Peter Collingbournef17b1492018-05-21 18:17:42 +0000858 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000859 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000860 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000861
862 endSection(Section);
863}
864
Sam Clegg457fb0b2017-09-15 19:50:44 +0000865void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
866 const MCAsmLayout &Layout,
867 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000868 if (Functions.empty())
869 return;
870
871 SectionBookkeeping Section;
872 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000873 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
Peter Collingbournef17b1492018-05-21 18:17:42 +0000875 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000876
877 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000878 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000879
Sam Clegg9e15f352017-06-03 02:01:24 +0000880 int64_t Size = 0;
881 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
882 report_fatal_error(".size expression must be evaluatable");
883
Peter Collingbournef17b1492018-05-21 18:17:42 +0000884 encodeULEB128(Size, W.OS);
885 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
886 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000887 }
888
Sam Clegg9e15f352017-06-03 02:01:24 +0000889 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000890 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000891
892 endSection(Section);
893}
894
Sam Clegg6c899ba2018-02-23 05:08:34 +0000895void WasmObjectWriter::writeDataSection() {
896 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000897 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000898
899 SectionBookkeeping Section;
900 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000901 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000902
Peter Collingbournef17b1492018-05-21 18:17:42 +0000903 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000904
Sam Clegg6c899ba2018-02-23 05:08:34 +0000905 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000906 encodeULEB128(Segment.InitFlags, W.OS); // flags
907 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
908 encodeULEB128(0, W.OS); // memory index
909 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
910 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
911 encodeSLEB128(Segment.Offset, W.OS); // offset
912 W.OS << char(wasm::WASM_OPCODE_END);
913 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000914 encodeULEB128(Segment.Data.size(), W.OS); // size
915 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
916 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000917 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000918
919 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000920 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000921
922 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000923}
924
Sam Clegg6f08c842018-04-24 18:11:36 +0000925void WasmObjectWriter::writeRelocSection(
926 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000927 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000928 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
929 // for descriptions of the reloc sections.
930
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000931 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000932 return;
933
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000934 // First, ensure the relocations are sorted in offset order. In general they
935 // should already be sorted since `recordRelocation` is called in offset
936 // order, but for the code section we combine many MC sections into single
937 // wasm section, and this order is determined by the order of Asm.Symbols()
938 // not the sections order.
939 std::stable_sort(
940 Relocs.begin(), Relocs.end(),
941 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
942 return (A.Offset + A.FixupSection->getSectionOffset()) <
943 (B.Offset + B.FixupSection->getSectionOffset());
944 });
945
Sam Clegg9e15f352017-06-03 02:01:24 +0000946 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000947 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000948
Peter Collingbournef17b1492018-05-21 18:17:42 +0000949 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000950 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000951 for (const WasmRelocationEntry &RelEntry : Relocs) {
952 uint64_t Offset =
953 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000954 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000955
Peter Collingbournef17b1492018-05-21 18:17:42 +0000956 W.OS << char(RelEntry.Type);
957 encodeULEB128(Offset, W.OS);
958 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000959 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000960 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000961 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000962
963 endSection(Section);
964}
965
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000966void WasmObjectWriter::writeCustomRelocSections() {
967 for (const auto &Sec : CustomSections) {
968 auto &Relocations = CustomSectionsRelocations[Sec.Section];
969 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
970 }
971}
972
Sam Clegg9e15f352017-06-03 02:01:24 +0000973void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000974 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000975 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000976 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000977 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000978 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000979 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000980
Sam Clegg6bb5a412018-04-26 18:15:32 +0000981 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000982 if (SymbolInfos.size() != 0) {
983 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000984 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000985 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000986 encodeULEB128(Sym.Kind, W.OS);
987 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000988 switch (Sym.Kind) {
989 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
990 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000991 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000992 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000993 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
994 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000995 writeString(Sym.Name);
996 break;
997 case wasm::WASM_SYMBOL_TYPE_DATA:
998 writeString(Sym.Name);
999 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001000 encodeULEB128(Sym.DataRef.Segment, W.OS);
1001 encodeULEB128(Sym.DataRef.Offset, W.OS);
1002 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001003 }
1004 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001005 case wasm::WASM_SYMBOL_TYPE_SECTION: {
1006 const uint32_t SectionIndex =
1007 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +00001008 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001009 break;
1010 }
Sam Clegg6c899ba2018-02-23 05:08:34 +00001011 default:
1012 llvm_unreachable("unexpected kind");
1013 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001014 }
1015 endSection(SubSection);
1016 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001017
Sam Clegg6c899ba2018-02-23 05:08:34 +00001018 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001019 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001020 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001021 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001022 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001023 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +00001024 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001025 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001026 endSection(SubSection);
1027 }
1028
Sam Cleggbafe6902017-12-15 00:17:10 +00001029 if (!InitFuncs.empty()) {
1030 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001031 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001032 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001033 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001034 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001035 }
1036 endSection(SubSection);
1037 }
1038
Sam Cleggea7cace2018-01-09 23:43:14 +00001039 if (Comdats.size()) {
1040 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001041 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001042 for (const auto &C : Comdats) {
1043 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001044 encodeULEB128(0, W.OS); // flags for future use
1045 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001046 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001047 encodeULEB128(Entry.Kind, W.OS);
1048 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001049 }
1050 }
1051 endSection(SubSection);
1052 }
1053
Sam Clegg9e15f352017-06-03 02:01:24 +00001054 endSection(Section);
1055}
1056
Thomas Livelycbda16e2019-01-17 02:29:55 +00001057void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1058 const MCAssembler &Asm,
1059 const MCAsmLayout &Layout) {
1060 SectionBookkeeping Section;
1061 auto *Sec = CustomSection.Section;
1062 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001063
Thomas Livelycbda16e2019-01-17 02:29:55 +00001064 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1065 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001066
Thomas Livelycbda16e2019-01-17 02:29:55 +00001067 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1068 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001069
Thomas Livelycbda16e2019-01-17 02:29:55 +00001070 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001071
Thomas Livelycbda16e2019-01-17 02:29:55 +00001072 // Apply fixups.
1073 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1074 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001075}
1076
Heejin Ahnf208f632018-09-05 01:27:38 +00001077uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001078 assert(Symbol.isFunction());
1079 assert(TypeIndices.count(&Symbol));
1080 return TypeIndices[&Symbol];
1081}
1082
Heejin Ahnda419bd2018-11-14 02:46:21 +00001083uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1084 assert(Symbol.isEvent());
1085 assert(TypeIndices.count(&Symbol));
1086 return TypeIndices[&Symbol];
1087}
1088
Heejin Ahn38b12f52018-11-20 00:38:10 +00001089void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001090 assert(Symbol.isFunction());
1091
Heejin Ahnda419bd2018-11-14 02:46:21 +00001092 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001093 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001094 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001095 S.Returns = Sig->Returns;
1096 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001097 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001098
Heejin Ahnda419bd2018-11-14 02:46:21 +00001099 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001100 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001101 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001102 TypeIndices[&Symbol] = Pair.first->second;
1103
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001104 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1105 << " new:" << Pair.second << "\n");
1106 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001107}
1108
Heejin Ahn38b12f52018-11-20 00:38:10 +00001109void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001110 assert(Symbol.isEvent());
1111
1112 // TODO Currently we don't generate imported exceptions, but if we do, we
1113 // should have a way of infering types of imported exceptions.
1114 WasmSignature S;
1115 if (auto *Sig = Symbol.getSignature()) {
1116 S.Returns = Sig->Returns;
1117 S.Params = Sig->Params;
1118 }
1119
1120 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1121 if (Pair.second)
1122 Signatures.push_back(S);
1123 TypeIndices[&Symbol] = Pair.first->second;
1124
1125 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1126 << "\n");
1127 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001128}
1129
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001130static bool isInSymtab(const MCSymbolWasm &Sym) {
1131 if (Sym.isUsedInReloc())
1132 return true;
1133
1134 if (Sym.isComdat() && !Sym.isDefined())
1135 return false;
1136
1137 if (Sym.isTemporary() && Sym.getName().empty())
1138 return false;
1139
1140 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1141 return false;
1142
1143 if (Sym.isSection())
1144 return false;
1145
1146 return true;
1147}
1148
Peter Collingbourne438390f2018-05-21 18:23:50 +00001149uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1150 const MCAsmLayout &Layout) {
1151 uint64_t StartOffset = W.OS.tell();
1152
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001153 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001154
1155 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001156 SmallVector<WasmFunction, 4> Functions;
1157 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001158 SmallVector<wasm::WasmImport, 4> Imports;
1159 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001160 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001161 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001162 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001163 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001164 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001165
Sam Cleggf950b242017-12-11 23:03:38 +00001166 // For now, always emit the memory import, since loads and stores are not
1167 // valid without it. In the future, we could perhaps be more clever and omit
1168 // it if there are no loads or stores.
Sam Clegg8defa952018-02-12 22:41:29 +00001169 wasm::WasmImport MemImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001170 MemImport.Module = "env";
1171 MemImport.Field = "__linear_memory";
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.
Sam Clegg8defa952018-02-12 22:41:29 +00001178 wasm::WasmImport TableImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001179 TableImport.Module = "env";
1180 TableImport.Field = "__indirect_function_table";
Sam Cleggf950b242017-12-11 23:03:38 +00001181 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001182 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001183 Imports.push_back(TableImport);
1184
Heejin Ahnda419bd2018-11-14 02:46:21 +00001185 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001186 // symbols. This must be done before populating WasmIndices for defined
1187 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001188 for (const MCSymbol &S : Asm.symbols()) {
1189 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1190
1191 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001192 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001193 if (WS.isFunction())
1194 registerFunctionType(WS);
1195
Heejin Ahnda419bd2018-11-14 02:46:21 +00001196 if (WS.isEvent())
1197 registerEventType(WS);
1198
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001199 if (WS.isTemporary())
1200 continue;
1201
1202 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001203 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001204 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001205 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001206 Import.Module = WS.getImportModule();
1207 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001208 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001209 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001210 Imports.push_back(Import);
1211 WasmIndices[&WS] = NumFunctionImports++;
1212 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001213 if (WS.isWeak())
1214 report_fatal_error("undefined global symbol cannot be weak");
1215
Sam Clegg6c899ba2018-02-23 05:08:34 +00001216 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001217 Import.Module = WS.getImportModule();
1218 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001219 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001220 Import.Global = WS.getGlobalType();
1221 Imports.push_back(Import);
1222 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001223 } else if (WS.isEvent()) {
1224 if (WS.isWeak())
1225 report_fatal_error("undefined event symbol cannot be weak");
1226
1227 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001228 Import.Module = WS.getImportModule();
1229 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001230 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1231 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1232 Import.Event.SigIndex = getEventType(WS);
1233 Imports.push_back(Import);
1234 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001235 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001236 }
1237 }
1238
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001239 // Populate DataSegments and CustomSections, which must be done before
1240 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001241 for (MCSection &Sec : Asm) {
1242 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001243 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001244
Sam Cleggbafe6902017-12-15 00:17:10 +00001245 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001246 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001247 continue;
1248
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001249 // Code is handled separately
1250 if (Section.getKind().isText())
1251 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001252
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001253 if (Section.isWasmData()) {
1254 uint32_t SegmentIndex = DataSegments.size();
1255 DataSize = alignTo(DataSize, Section.getAlignment());
1256 DataSegments.emplace_back();
1257 WasmDataSegment &Segment = DataSegments.back();
1258 Segment.Name = SectionName;
Simon Pilgrim9b49f362019-02-24 13:31:52 +00001259 Segment.InitFlags =
1260 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001261 Segment.Offset = DataSize;
1262 Segment.Section = &Section;
1263 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001264 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001265 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001266 DataSize += Segment.Data.size();
1267 Section.setSegmentIndex(SegmentIndex);
1268
1269 if (const MCSymbolWasm *C = Section.getGroup()) {
1270 Comdats[C->getName()].emplace_back(
1271 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1272 }
1273 } else {
1274 // Create custom sections
1275 assert(Sec.getKind().isMetadata());
1276
1277 StringRef Name = SectionName;
1278
1279 // For user-defined custom sections, strip the prefix
1280 if (Name.startswith(".custom_section."))
1281 Name = Name.substr(strlen(".custom_section."));
1282
Heejin Ahnf208f632018-09-05 01:27:38 +00001283 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001284 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001285 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001286 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001287 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001288 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001289 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001290
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001291 // Separate out the producers and target features sections
Thomas Livelycbda16e2019-01-17 02:29:55 +00001292 if (Name == "producers") {
1293 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1294 continue;
1295 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001296 if (Name == "target_features") {
1297 TargetFeaturesSection =
1298 llvm::make_unique<WasmCustomSection>(Name, &Section);
1299 continue;
1300 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001301
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001302 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001303 }
Sam Clegg759631c2017-09-15 20:54:59 +00001304 }
1305
Nicholas Wilson586320c2018-02-28 17:19:48 +00001306 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001307 for (const MCSymbol &S : Asm.symbols()) {
1308 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1309 // or used in relocations.
1310 if (S.isTemporary() && S.getName().empty())
1311 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001312
Dan Gohmand934cb82017-02-24 23:18:00 +00001313 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001314 LLVM_DEBUG(
1315 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1316 << " isDefined=" << S.isDefined() << " isExternal="
1317 << S.isExternal() << " isTemporary=" << S.isTemporary()
1318 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1319 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001320
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001321 if (WS.isVariable())
1322 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001323 if (WS.isComdat() && !WS.isDefined())
1324 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001325
Dan Gohmand934cb82017-02-24 23:18:00 +00001326 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001327 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001328 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001329 if (WS.getOffset() != 0)
1330 report_fatal_error(
1331 "function sections must contain one function each");
1332
Heejin Ahn18c56a02019-02-04 19:13:39 +00001333 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001334 report_fatal_error(
1335 "function symbols must have a size set with .size");
1336
Sam Clegg6c899ba2018-02-23 05:08:34 +00001337 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001338 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001339 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001340 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001341 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001342 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001343 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001344
1345 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1346 if (const MCSymbolWasm *C = Section.getGroup()) {
1347 Comdats[C->getName()].emplace_back(
1348 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1349 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001350 } else {
1351 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001352 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001353 }
1354
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001355 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001356
Sam Clegg6c899ba2018-02-23 05:08:34 +00001357 } else if (WS.isData()) {
Wouter van Oortmerssenf3feb6a2019-03-04 17:18:04 +00001358 if (!isInSymtab(WS))
Sam Cleggc38e9472017-06-02 01:05:24 +00001359 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001360
Sam Clegg6c899ba2018-02-23 05:08:34 +00001361 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001362 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1363 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001364 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001365 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001366
Sam Cleggfe6414b2017-06-21 23:46:41 +00001367 if (!WS.getSize())
1368 report_fatal_error("data symbols must have a size set with .size: " +
1369 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001370
Sam Cleggfe6414b2017-06-21 23:46:41 +00001371 int64_t Size = 0;
1372 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1373 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001374
Sam Clegg759631c2017-09-15 20:54:59 +00001375 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001376 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001377
Sam Clegg6c899ba2018-02-23 05:08:34 +00001378 // For each data symbol, export it in the symtab as a reference to the
1379 // corresponding Wasm data segment.
1380 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1381 DataSection.getSegmentIndex(),
1382 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1383 static_cast<uint32_t>(Size)};
1384 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001385 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001386
Sam Clegga165f2d2018-04-30 19:40:57 +00001387 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001388 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001389 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001390 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001391
Eric Christopher545932b2018-02-23 21:14:47 +00001392 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001393 LLVM_DEBUG(dbgs() << " -> global index: "
1394 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001395
1396 } else if (WS.isEvent()) {
1397 // C++ exception symbol (__cpp_exception)
1398 unsigned Index;
1399 if (WS.isDefined()) {
1400 Index = NumEventImports + Events.size();
1401 wasm::WasmEventType Event;
1402 Event.SigIndex = getEventType(WS);
1403 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1404 WasmIndices[&WS] = Index;
1405 Events.push_back(Event);
1406 } else {
1407 // An import; the index was assigned above.
1408 Index = WasmIndices.find(&WS)->second;
1409 }
1410 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1411 << "\n");
1412
Sam Clegga165f2d2018-04-30 19:40:57 +00001413 } else {
1414 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001415 }
1416 }
1417
Nicholas Wilson586320c2018-02-28 17:19:48 +00001418 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1419 // process these in a separate pass because we need to have processed the
1420 // target of the alias before the alias itself and the symbols are not
1421 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001422 for (const MCSymbol &S : Asm.symbols()) {
1423 if (!S.isVariable())
1424 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001425
Sam Cleggcd65f692018-01-11 23:59:16 +00001426 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001427
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001428 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001429 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001430 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001431 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1432 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001433
Sam Cleggffba00b2019-02-22 21:41:42 +00001434 if (ResolvedSym->isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001435 assert(WasmIndices.count(ResolvedSym) > 0);
1436 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1437 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001438 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggffba00b2019-02-22 21:41:42 +00001439 } else if (ResolvedSym->isData()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001440 assert(DataLocations.count(ResolvedSym) > 0);
1441 const wasm::WasmDataReference &Ref =
1442 DataLocations.find(ResolvedSym)->second;
1443 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001444 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001445 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001446 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001447 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001448 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001449
Nicholas Wilson586320c2018-02-28 17:19:48 +00001450 // Finally, populate the symbol table itself, in its "natural" order.
1451 for (const MCSymbol &S : Asm.symbols()) {
1452 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001453 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001454 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001455 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001456 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001457 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001458
1459 uint32_t Flags = 0;
1460 if (WS.isWeak())
1461 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1462 if (WS.isHidden())
1463 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1464 if (!WS.isExternal() && WS.isDefined())
1465 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1466 if (WS.isUndefined())
1467 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001468 if (WS.isExported())
1469 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Dan Gohman29874ce2019-02-07 22:03:32 +00001470 if (WS.getName() != WS.getImportName())
1471 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001472
1473 wasm::WasmSymbolInfo Info;
1474 Info.Name = WS.getName();
1475 Info.Kind = WS.getType();
1476 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001477 if (!WS.isData()) {
1478 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001479 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001480 } else if (WS.isDefined()) {
1481 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001482 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001483 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001484 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001485 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001486 }
1487
Sam Clegg6006e092017-12-22 20:31:39 +00001488 {
1489 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001490 // Functions referenced by a relocation need to put in the table. This is
1491 // purely to make the object file's provisional values readable, and is
1492 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001493 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1494 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001495 return;
1496 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001497 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001498 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001499 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001500 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001501 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1502 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001503 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001504 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001505 }
1506 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001507
Sam Clegg6006e092017-12-22 20:31:39 +00001508 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1509 HandleReloc(RelEntry);
1510 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1511 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001512 }
1513
Sam Cleggbafe6902017-12-15 00:17:10 +00001514 // Translate .init_array section contents into start functions.
1515 for (const MCSection &S : Asm) {
1516 const auto &WS = static_cast<const MCSectionWasm &>(S);
1517 if (WS.getSectionName().startswith(".fini_array"))
1518 report_fatal_error(".fini_array sections are unsupported");
1519 if (!WS.getSectionName().startswith(".init_array"))
1520 continue;
1521 if (WS.getFragmentList().empty())
1522 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001523
1524 // init_array is expected to contain a single non-empty data fragment
1525 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001526 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001527
1528 auto IT = WS.begin();
1529 const MCFragment &EmptyFrag = *IT;
1530 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1531 report_fatal_error(".init_array section should be aligned");
1532
1533 IT = std::next(IT);
1534 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001535 if (AlignFrag.getKind() != MCFragment::FT_Align)
1536 report_fatal_error(".init_array section should be aligned");
1537 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1538 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001539
1540 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001541 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1542 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001543
Sam Cleggbafe6902017-12-15 00:17:10 +00001544 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001545 unsigned PrefixLength = strlen(".init_array");
1546 if (WS.getSectionName().size() > PrefixLength) {
1547 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001548 report_fatal_error(
1549 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001550 if (WS.getSectionName()
1551 .substr(PrefixLength + 1)
1552 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001553 report_fatal_error("invalid .init_array section priority");
1554 }
1555 const auto &DataFrag = cast<MCDataFragment>(Frag);
1556 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001557 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001558 P = (const uint8_t *)Contents.data(),
1559 *End = (const uint8_t *)Contents.data() + Contents.size();
1560 P != End; ++P) {
1561 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001562 report_fatal_error("non-symbolic data in .init_array section");
1563 }
1564 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001565 assert(Fixup.getKind() ==
1566 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001567 const MCExpr *Expr = Fixup.getValue();
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001568 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1569 if (!SymRef)
Sam Cleggbafe6902017-12-15 00:17:10 +00001570 report_fatal_error("fixups in .init_array should be symbol references");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001571 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1572 if (TargetSym.getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001573 report_fatal_error("symbols in .init_array should exist in symbtab");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001574 if (!TargetSym.isFunction())
1575 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001576 InitFuncs.push_back(
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001577 std::make_pair(Priority, TargetSym.getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001578 }
1579 }
1580
Dan Gohman18eafb62017-02-22 01:23:18 +00001581 // Write out the Wasm header.
1582 writeHeader(Asm);
1583
Heejin Ahnda419bd2018-11-14 02:46:21 +00001584 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001585 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001586 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001587 // Skip the "table" section; we import the table instead.
1588 // Skip the "memory" section; we import the memory instead.
Sam Clegg7c395942017-09-14 23:07:53 +00001589 writeGlobalSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001590 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001591 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001592 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001593 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001594 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001595 for (auto &CustomSection : CustomSections)
1596 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001597 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001598 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1599 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001600 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001601 if (ProducersSection)
1602 writeCustomSection(*ProducersSection, Asm, Layout);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001603 if (TargetFeaturesSection)
1604 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001605
Dan Gohmand934cb82017-02-24 23:18:00 +00001606 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001607 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001608}
1609
Lang Hames60fbc7c2017-10-10 16:28:07 +00001610std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001611llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1612 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001613 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001614}