blob: 636770959182755eee69e7767e5cb8cc4210521f [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:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000154 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000155 case wasm::R_WASM_MEMORY_ADDR_I32:
156 case wasm::R_WASM_FUNCTION_OFFSET_I32:
157 case wasm::R_WASM_SECTION_OFFSET_I32:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000158 return true;
159 default:
160 return false;
161 }
162 }
163
Sam Clegg6dc65e92017-06-06 16:38:59 +0000164 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000165 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
166 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000167 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000168 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000169
Aaron Ballman615eb472017-10-15 14:32:27 +0000170#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000171 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
172#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000173};
174
Heejin Ahn18c56a02019-02-04 19:13:39 +0000175static const uint32_t InvalidIndex = -1;
Sam Clegg25d8e682018-05-08 00:08:21 +0000176
Sam Cleggcfd44a22018-04-05 17:01:39 +0000177struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000178
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000179 StringRef Name;
180 MCSectionWasm *Section;
181
182 uint32_t OutputContentsOffset;
183 uint32_t OutputIndex;
184
185 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
186 : Name(Name), Section(Section), OutputContentsOffset(0),
Heejin Ahn18c56a02019-02-04 19:13:39 +0000187 OutputIndex(InvalidIndex) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000188};
189
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000190#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000191raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000192 Rel.print(OS);
193 return OS;
194}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000195#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000196
Sam Clegg19e8bef2019-01-30 22:47:35 +0000197// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
198// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000199static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000200 uint64_t Offset) {
201 uint8_t Buffer[5];
202 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
203 assert(SizeLen == 5);
204 Stream.pwrite((char *)Buffer, SizeLen, Offset);
205}
206
207// Write X as an signed LEB value at offset Offset in Stream, padded
208// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000209static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000210 uint64_t Offset) {
211 uint8_t Buffer[5];
212 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
213 assert(SizeLen == 5);
214 Stream.pwrite((char *)Buffer, SizeLen, Offset);
215}
216
217// Write X as a plain integer value at offset Offset in Stream.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000218static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
Sam Clegg19e8bef2019-01-30 22:47:35 +0000219 uint8_t Buffer[4];
220 support::endian::write32le(Buffer, X);
221 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
222}
223
Dan Gohman18eafb62017-02-22 01:23:18 +0000224class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000225 support::endian::Writer W;
226
Dan Gohman18eafb62017-02-22 01:23:18 +0000227 /// The target specific Wasm writer instance.
228 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
229
Dan Gohmand934cb82017-02-24 23:18:00 +0000230 // Relocations for fixing up references in the code section.
231 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000232 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000233
234 // Relocations for fixing up references in the data section.
235 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000236 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000237
Dan Gohmand934cb82017-02-24 23:18:00 +0000238 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000239 // Maps function symbols to the index of the type of the function
240 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000241 // Maps function symbols to the table element index space. Used
242 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000243 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000244 // Maps function/global symbols to the function/global/event/section index
245 // space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000246 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
Sam Clegg492f7522019-03-26 19:46:15 +0000247 DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000248 // Maps data symbols to the Wasm segment and offset/size with the segment.
249 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000250
251 // Stores output data (index, relocations, content offset) for custom
252 // section.
253 std::vector<WasmCustomSection> CustomSections;
Thomas Livelycbda16e2019-01-17 02:29:55 +0000254 std::unique_ptr<WasmCustomSection> ProducersSection;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000255 std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000256 // Relocations for fixing up references in the custom sections.
257 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
258 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000259
Sam Cleggc0d41192018-05-17 17:15:15 +0000260 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000261 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
262
Heejin Ahnda419bd2018-11-14 02:46:21 +0000263 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
264 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000265 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000266 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000267 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000268 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000269 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000270
Dan Gohman18eafb62017-02-22 01:23:18 +0000271 // TargetObjectWriter wrappers.
272 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Dan Gohman18eafb62017-02-22 01:23:18 +0000273
Sam Clegg2322a932018-04-23 19:16:19 +0000274 void startSection(SectionBookkeeping &Section, unsigned SectionId);
275 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000276 void endSection(SectionBookkeeping &Section);
277
Dan Gohman18eafb62017-02-22 01:23:18 +0000278public:
Lang Hames1301a872017-10-10 01:15:10 +0000279 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
280 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000281 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000282
Dan Gohman0917c9e2018-01-15 17:06:23 +0000283private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000284 void reset() override {
285 CodeRelocations.clear();
286 DataRelocations.clear();
287 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000288 WasmIndices.clear();
Sam Clegg492f7522019-03-26 19:46:15 +0000289 GOTIndices.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();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000294 TargetFeaturesSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000295 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000296 SignatureIndices.clear();
297 Signatures.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 Clegg8defa952018-02-12 22:41:29 +0000327 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000328 void writeElemSection(ArrayRef<uint32_t> TableElems);
Sam Clegg9e15f352017-06-03 02:01:24 +0000329 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000330 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000331 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000332 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000333 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000334 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000335 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000336 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000337 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000338 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000339 void writeCustomSection(WasmCustomSection &CustomSection,
340 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000341 void writeCustomRelocSections();
342 void
343 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
344 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000345
Sam Clegg7c395942017-09-14 23:07:53 +0000346 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000347 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
348 uint64_t ContentsOffset);
349
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000350 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000351 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000352 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000353 void registerFunctionType(const MCSymbolWasm &Symbol);
354 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000355};
Sam Clegg9e15f352017-06-03 02:01:24 +0000356
Dan Gohman18eafb62017-02-22 01:23:18 +0000357} // end anonymous namespace
358
Dan Gohmand934cb82017-02-24 23:18:00 +0000359// Write out a section header and a patchable section size field.
360void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000361 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000362 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000363 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000364
Peter Collingbournef17b1492018-05-21 18:17:42 +0000365 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000366
367 // The section size. We don't know the size yet, so reserve enough space
368 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000369 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000370
371 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000372 Section.ContentsOffset = W.OS.tell();
373 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000374 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000375}
Dan Gohmand934cb82017-02-24 23:18:00 +0000376
Sam Clegg2322a932018-04-23 19:16:19 +0000377void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
378 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000379 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000380 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000381
382 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000383 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000384
Dan Gohmand934cb82017-02-24 23:18:00 +0000385 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000386 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000387
388 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000389 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000390}
391
392// Now that the section is complete and we know how big it is, patch up the
393// section size field at the start of the section.
394void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000395 uint64_t Size = W.OS.tell();
396 // /dev/null doesn't support seek/tell and can report offset of 0.
397 // Simply skip this patching in that case.
398 if (!Size)
399 return;
400
401 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000402 if (uint32_t(Size) != Size)
403 report_fatal_error("section size does not fit in a uint32_t");
404
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000405 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000406
407 // Write the final section size to the payload_len field, which follows
408 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000409 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000410 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000411}
412
Dan Gohman18eafb62017-02-22 01:23:18 +0000413// Emit the Wasm header.
414void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000415 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
416 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000417}
418
419void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
420 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000421 // Build a map of sections to the function that defines them, for use
422 // in recordRelocation.
423 for (const MCSymbol &S : Asm.symbols()) {
424 const auto &WS = static_cast<const MCSymbolWasm &>(S);
425 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
426 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
427 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
428 if (!Pair.second)
429 report_fatal_error("section already has a defining function: " +
430 Sec.getSectionName());
431 }
432 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000433}
434
435void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
436 const MCAsmLayout &Layout,
437 const MCFragment *Fragment,
438 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000439 uint64_t &FixedValue) {
440 MCAsmBackend &Backend = Asm.getBackend();
441 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
442 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000443 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000444 uint64_t C = Target.getConstant();
445 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
446 MCContext &Ctx = Asm.getContext();
447
Sam Cleggbafe6902017-12-15 00:17:10 +0000448 // The .init_array isn't translated as data, so don't do relocations in it.
449 if (FixupSection.getSectionName().startswith(".init_array"))
450 return;
451
Dan Gohmand934cb82017-02-24 23:18:00 +0000452 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
453 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
454 "Should not have constructed this");
455
456 // Let A, B and C being the components of Target and R be the location of
457 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
458 // If it is pcrel, we want to compute (A - B + C - R).
459
460 // In general, Wasm has no relocations for -B. It can only represent (A + C)
461 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
462 // replace B to implement it: (A - R - K + C)
463 if (IsPCRel) {
464 Ctx.reportError(
465 Fixup.getLoc(),
466 "No relocation available to represent this relative expression");
467 return;
468 }
469
470 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
471
472 if (SymB.isUndefined()) {
473 Ctx.reportError(Fixup.getLoc(),
474 Twine("symbol '") + SymB.getName() +
475 "' can not be undefined in a subtraction expression");
476 return;
477 }
478
479 assert(!SymB.isAbsolute() && "Should have been folded");
480 const MCSection &SecB = SymB.getSection();
481 if (&SecB != &FixupSection) {
482 Ctx.reportError(Fixup.getLoc(),
483 "Cannot represent a difference across sections");
484 return;
485 }
486
487 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
488 uint64_t K = SymBOffset - FixupOffset;
489 IsPCRel = true;
490 C -= K;
491 }
492
493 // We either rejected the fixup or folded B into C at this point.
494 const MCSymbolRefExpr *RefA = Target.getSymA();
495 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
496
Dan Gohmand934cb82017-02-24 23:18:00 +0000497 if (SymA && SymA->isVariable()) {
498 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000499 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
500 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
501 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000502 }
503
504 // Put any constant offset in an addend. Offsets can be negative, and
505 // LLVM expects wrapping, in contrast to wasm's immediates which can't
506 // be negative and don't wrap.
507 FixedValue = 0;
508
Sam Clegga5e175c2019-03-28 02:07:28 +0000509 unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000510 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000511 assert(SymA);
512
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000513 // Absolute offset within a section or a function.
514 // Currently only supported for for metadata sections.
515 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000516 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
517 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000518 if (!FixupSection.getKind().isMetadata())
519 report_fatal_error("relocations for function or section offsets are "
520 "only supported in metadata sections");
521
522 const MCSymbol *SectionSymbol = nullptr;
523 const MCSection &SecA = SymA->getSection();
524 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000525 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000526 else
527 SectionSymbol = SecA.getBeginSymbol();
528 if (!SectionSymbol)
529 report_fatal_error("section symbol is required for relocation");
530
531 C += Layout.getSymbolOffset(*SymA);
532 SymA = cast<MCSymbolWasm>(SectionSymbol);
533 }
534
Sam Cleggd1152a22019-02-04 17:28:46 +0000535 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000536 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000537 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000538 if (SymA->getName().empty())
539 report_fatal_error("relocations against un-named temporaries are not yet "
540 "supported by wasm");
541
542 SymA->setUsedInReloc();
543 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000544
Sam Clegg492f7522019-03-26 19:46:15 +0000545 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
546 SymA->setUsedInGOT();
547
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 Clegg492f7522019-03-26 19:46:15 +0000578 if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
579 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
580 return GOTIndices[RelEntry.Symbol];
581 }
582
Sam Clegg60ec3032018-01-23 01:23:17 +0000583 switch (RelEntry.Type) {
Sam Clegg2a7cac92019-04-04 17:43:50 +0000584 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000585 case wasm::R_WASM_TABLE_INDEX_SLEB:
586 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000587 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000588 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000589 assert(Sym->isFunction());
590 return TableIndices[Sym];
591 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000592 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000593 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000594 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000595 case wasm::R_WASM_FUNCTION_INDEX_LEB:
596 case wasm::R_WASM_GLOBAL_INDEX_LEB:
597 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000598 // Provisional value is function/global/event Wasm index
Sam Clegg492f7522019-03-26 19:46:15 +0000599 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
Sam Clegg6c899ba2018-02-23 05:08:34 +0000600 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000601 case wasm::R_WASM_FUNCTION_OFFSET_I32:
602 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000603 const auto &Section =
604 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
605 return Section.getSectionOffset() + RelEntry.Addend;
606 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000607 case wasm::R_WASM_MEMORY_ADDR_LEB:
608 case wasm::R_WASM_MEMORY_ADDR_I32:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000609 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000610 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000611 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000612 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000613 // For undefined symbols, use zero
614 if (!Sym->isDefined())
615 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000616 const wasm::WasmDataReference &Ref = DataLocations[Sym];
617 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000618 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000619 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000620 }
621 default:
622 llvm_unreachable("invalid relocation type");
623 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000624}
625
Sam Clegg759631c2017-09-15 20:54:59 +0000626static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000627 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000628 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000629
Sam Clegg63ebb812017-09-29 16:50:08 +0000630 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
631
Sam Clegg759631c2017-09-15 20:54:59 +0000632 for (const MCFragment &Frag : DataSection) {
633 if (Frag.hasInstructions())
634 report_fatal_error("only data supported in data sections");
635
636 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
637 if (Align->getValueSize() != 1)
638 report_fatal_error("only byte values supported for alignment");
639 // If nops are requested, use zeros, as this is the data section.
640 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000641 uint64_t Size =
642 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
643 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000644 DataBytes.resize(Size, Value);
645 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000646 int64_t NumValues;
647 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000648 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000649 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
650 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000651 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
652 const SmallVectorImpl<char> &Contents = LEB->getContents();
653 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000654 } else {
655 const auto &DataFrag = cast<MCDataFragment>(Frag);
656 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000657 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
658 }
659 }
660
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000661 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000662}
663
Sam Clegg60ec3032018-01-23 01:23:17 +0000664uint32_t
665WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000666 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000667 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000668 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000669 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000670 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000671 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000672
Sam Clegg25d8e682018-05-08 00:08:21 +0000673 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000674}
675
Dan Gohmand934cb82017-02-24 23:18:00 +0000676// Apply the portions of the relocation records that we can handle ourselves
677// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000678void WasmObjectWriter::applyRelocations(
679 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000680 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000681 for (const WasmRelocationEntry &RelEntry : Relocations) {
682 uint64_t Offset = ContentsOffset +
683 RelEntry.FixupSection->getSectionOffset() +
684 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000685
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000687 uint32_t Value = getProvisionalValue(RelEntry);
688
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000689 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000690 case wasm::R_WASM_FUNCTION_INDEX_LEB:
691 case wasm::R_WASM_TYPE_INDEX_LEB:
692 case wasm::R_WASM_GLOBAL_INDEX_LEB:
693 case wasm::R_WASM_MEMORY_ADDR_LEB:
694 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000695 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000696 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000697 case wasm::R_WASM_TABLE_INDEX_I32:
698 case wasm::R_WASM_MEMORY_ADDR_I32:
699 case wasm::R_WASM_FUNCTION_OFFSET_I32:
700 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000701 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000702 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000703 case wasm::R_WASM_TABLE_INDEX_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000704 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000705 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000706 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000707 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000708 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000709 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000710 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000711 }
712 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000713}
714
Heejin Ahnda419bd2018-11-14 02:46:21 +0000715void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
716 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000717 return;
718
719 SectionBookkeeping Section;
720 startSection(Section, wasm::WASM_SEC_TYPE);
721
Heejin Ahnda419bd2018-11-14 02:46:21 +0000722 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000723
Heejin Ahnda419bd2018-11-14 02:46:21 +0000724 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000725 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000726 encodeULEB128(Sig.Params.size(), W.OS);
727 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000728 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000729 encodeULEB128(Sig.Returns.size(), W.OS);
730 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000731 writeValueType(Ty);
732 }
733
734 endSection(Section);
735}
736
Sam Clegg8defa952018-02-12 22:41:29 +0000737void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000738 uint32_t DataSize,
739 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000740 if (Imports.empty())
741 return;
742
Sam Cleggf950b242017-12-11 23:03:38 +0000743 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
744
Sam Clegg9e15f352017-06-03 02:01:24 +0000745 SectionBookkeeping Section;
746 startSection(Section, wasm::WASM_SEC_IMPORT);
747
Peter Collingbournef17b1492018-05-21 18:17:42 +0000748 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000749 for (const wasm::WasmImport &Import : Imports) {
750 writeString(Import.Module);
751 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000752 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000753
754 switch (Import.Kind) {
755 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000756 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000757 break;
758 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000759 W.OS << char(Import.Global.Type);
760 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000761 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000762 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000763 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000764 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000765 break;
766 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000767 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000768 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000769 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000770 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000771 case wasm::WASM_EXTERNAL_EVENT:
772 encodeULEB128(Import.Event.Attribute, W.OS);
773 encodeULEB128(Import.Event.SigIndex, W.OS);
774 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000775 default:
776 llvm_unreachable("unsupported import kind");
777 }
778 }
779
780 endSection(Section);
781}
782
Sam Clegg457fb0b2017-09-15 19:50:44 +0000783void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000784 if (Functions.empty())
785 return;
786
787 SectionBookkeeping Section;
788 startSection(Section, wasm::WASM_SEC_FUNCTION);
789
Peter Collingbournef17b1492018-05-21 18:17:42 +0000790 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000792 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000793
794 endSection(Section);
795}
796
Heejin Ahnda419bd2018-11-14 02:46:21 +0000797void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
798 if (Events.empty())
799 return;
800
801 SectionBookkeeping Section;
802 startSection(Section, wasm::WASM_SEC_EVENT);
803
804 encodeULEB128(Events.size(), W.OS);
805 for (const wasm::WasmEventType &Event : Events) {
806 encodeULEB128(Event.Attribute, W.OS);
807 encodeULEB128(Event.SigIndex, W.OS);
808 }
809
810 endSection(Section);
811}
812
Sam Clegg8defa952018-02-12 22:41:29 +0000813void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000814 if (Exports.empty())
815 return;
816
817 SectionBookkeeping Section;
818 startSection(Section, wasm::WASM_SEC_EXPORT);
819
Peter Collingbournef17b1492018-05-21 18:17:42 +0000820 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000821 for (const wasm::WasmExport &Export : Exports) {
822 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000823 W.OS << char(Export.Kind);
824 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000825 }
826
827 endSection(Section);
828}
829
Sam Clegg457fb0b2017-09-15 19:50:44 +0000830void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000831 if (TableElems.empty())
832 return;
833
834 SectionBookkeeping Section;
835 startSection(Section, wasm::WASM_SEC_ELEM);
836
Peter Collingbournef17b1492018-05-21 18:17:42 +0000837 encodeULEB128(1, W.OS); // number of "segments"
838 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000839
840 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000841 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000842 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000843 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000844
Peter Collingbournef17b1492018-05-21 18:17:42 +0000845 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000846 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000847 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 endSection(Section);
850}
851
Sam Clegg457fb0b2017-09-15 19:50:44 +0000852void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
853 const MCAsmLayout &Layout,
854 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000855 if (Functions.empty())
856 return;
857
858 SectionBookkeeping Section;
859 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000860 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000861
Peter Collingbournef17b1492018-05-21 18:17:42 +0000862 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000863
864 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000865 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000866
Sam Clegg9e15f352017-06-03 02:01:24 +0000867 int64_t Size = 0;
868 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
869 report_fatal_error(".size expression must be evaluatable");
870
Peter Collingbournef17b1492018-05-21 18:17:42 +0000871 encodeULEB128(Size, W.OS);
872 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
873 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000874 }
875
Sam Clegg9e15f352017-06-03 02:01:24 +0000876 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000877 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000878
879 endSection(Section);
880}
881
Sam Clegg6c899ba2018-02-23 05:08:34 +0000882void WasmObjectWriter::writeDataSection() {
883 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000884 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000885
886 SectionBookkeeping Section;
887 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000888 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000889
Peter Collingbournef17b1492018-05-21 18:17:42 +0000890 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000891
Sam Clegg6c899ba2018-02-23 05:08:34 +0000892 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000893 encodeULEB128(Segment.InitFlags, W.OS); // flags
894 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
895 encodeULEB128(0, W.OS); // memory index
896 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
897 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
898 encodeSLEB128(Segment.Offset, W.OS); // offset
899 W.OS << char(wasm::WASM_OPCODE_END);
900 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000901 encodeULEB128(Segment.Data.size(), W.OS); // size
902 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
903 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000904 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000905
906 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000907 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000908
909 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000910}
911
Sam Clegg6f08c842018-04-24 18:11:36 +0000912void WasmObjectWriter::writeRelocSection(
913 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000914 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000915 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
916 // for descriptions of the reloc sections.
917
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000918 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000919 return;
920
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000921 // First, ensure the relocations are sorted in offset order. In general they
922 // should already be sorted since `recordRelocation` is called in offset
923 // order, but for the code section we combine many MC sections into single
924 // wasm section, and this order is determined by the order of Asm.Symbols()
925 // not the sections order.
926 std::stable_sort(
927 Relocs.begin(), Relocs.end(),
928 [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
929 return (A.Offset + A.FixupSection->getSectionOffset()) <
930 (B.Offset + B.FixupSection->getSectionOffset());
931 });
932
Sam Clegg9e15f352017-06-03 02:01:24 +0000933 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000934 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000935
Peter Collingbournef17b1492018-05-21 18:17:42 +0000936 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000937 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000938 for (const WasmRelocationEntry &RelEntry : Relocs) {
939 uint64_t Offset =
940 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000941 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000942
Peter Collingbournef17b1492018-05-21 18:17:42 +0000943 W.OS << char(RelEntry.Type);
944 encodeULEB128(Offset, W.OS);
945 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000946 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000947 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000948 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000949
950 endSection(Section);
951}
952
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000953void WasmObjectWriter::writeCustomRelocSections() {
954 for (const auto &Sec : CustomSections) {
955 auto &Relocations = CustomSectionsRelocations[Sec.Section];
956 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
957 }
958}
959
Sam Clegg9e15f352017-06-03 02:01:24 +0000960void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000961 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000962 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000963 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000964 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000965 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000966 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000967
Sam Clegg6bb5a412018-04-26 18:15:32 +0000968 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000969 if (SymbolInfos.size() != 0) {
970 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000971 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000972 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000973 encodeULEB128(Sym.Kind, W.OS);
974 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000975 switch (Sym.Kind) {
976 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
977 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000978 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000979 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000980 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
981 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000982 writeString(Sym.Name);
983 break;
984 case wasm::WASM_SYMBOL_TYPE_DATA:
985 writeString(Sym.Name);
986 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000987 encodeULEB128(Sym.DataRef.Segment, W.OS);
988 encodeULEB128(Sym.DataRef.Offset, W.OS);
989 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000990 }
991 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000992 case wasm::WASM_SYMBOL_TYPE_SECTION: {
993 const uint32_t SectionIndex =
994 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000995 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000996 break;
997 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000998 default:
999 llvm_unreachable("unexpected kind");
1000 }
Sam Cleggb7787fd2017-06-20 04:04:59 +00001001 }
1002 endSection(SubSection);
1003 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001004
Sam Clegg6c899ba2018-02-23 05:08:34 +00001005 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001006 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001007 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001008 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001009 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001010 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +00001011 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001012 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001013 endSection(SubSection);
1014 }
1015
Sam Cleggbafe6902017-12-15 00:17:10 +00001016 if (!InitFuncs.empty()) {
1017 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001018 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001019 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001020 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001021 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001022 }
1023 endSection(SubSection);
1024 }
1025
Sam Cleggea7cace2018-01-09 23:43:14 +00001026 if (Comdats.size()) {
1027 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001028 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001029 for (const auto &C : Comdats) {
1030 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001031 encodeULEB128(0, W.OS); // flags for future use
1032 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001033 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001034 encodeULEB128(Entry.Kind, W.OS);
1035 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001036 }
1037 }
1038 endSection(SubSection);
1039 }
1040
Sam Clegg9e15f352017-06-03 02:01:24 +00001041 endSection(Section);
1042}
1043
Thomas Livelycbda16e2019-01-17 02:29:55 +00001044void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1045 const MCAssembler &Asm,
1046 const MCAsmLayout &Layout) {
1047 SectionBookkeeping Section;
1048 auto *Sec = CustomSection.Section;
1049 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001050
Thomas Livelycbda16e2019-01-17 02:29:55 +00001051 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1052 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001053
Thomas Livelycbda16e2019-01-17 02:29:55 +00001054 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1055 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001056
Thomas Livelycbda16e2019-01-17 02:29:55 +00001057 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001058
Thomas Livelycbda16e2019-01-17 02:29:55 +00001059 // Apply fixups.
1060 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1061 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001062}
1063
Heejin Ahnf208f632018-09-05 01:27:38 +00001064uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001065 assert(Symbol.isFunction());
1066 assert(TypeIndices.count(&Symbol));
1067 return TypeIndices[&Symbol];
1068}
1069
Heejin Ahnda419bd2018-11-14 02:46:21 +00001070uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1071 assert(Symbol.isEvent());
1072 assert(TypeIndices.count(&Symbol));
1073 return TypeIndices[&Symbol];
1074}
1075
Heejin Ahn38b12f52018-11-20 00:38:10 +00001076void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001077 assert(Symbol.isFunction());
1078
Heejin Ahnda419bd2018-11-14 02:46:21 +00001079 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001080 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001081 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001082 S.Returns = Sig->Returns;
1083 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001084 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001085
Heejin Ahnda419bd2018-11-14 02:46:21 +00001086 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001087 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001088 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001089 TypeIndices[&Symbol] = Pair.first->second;
1090
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001091 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1092 << " new:" << Pair.second << "\n");
1093 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001094}
1095
Heejin Ahn38b12f52018-11-20 00:38:10 +00001096void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001097 assert(Symbol.isEvent());
1098
1099 // TODO Currently we don't generate imported exceptions, but if we do, we
1100 // should have a way of infering types of imported exceptions.
1101 WasmSignature S;
1102 if (auto *Sig = Symbol.getSignature()) {
1103 S.Returns = Sig->Returns;
1104 S.Params = Sig->Params;
1105 }
1106
1107 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1108 if (Pair.second)
1109 Signatures.push_back(S);
1110 TypeIndices[&Symbol] = Pair.first->second;
1111
1112 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1113 << "\n");
1114 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001115}
1116
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001117static bool isInSymtab(const MCSymbolWasm &Sym) {
1118 if (Sym.isUsedInReloc())
1119 return true;
1120
1121 if (Sym.isComdat() && !Sym.isDefined())
1122 return false;
1123
1124 if (Sym.isTemporary() && Sym.getName().empty())
1125 return false;
1126
1127 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1128 return false;
1129
1130 if (Sym.isSection())
1131 return false;
1132
1133 return true;
1134}
1135
Peter Collingbourne438390f2018-05-21 18:23:50 +00001136uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1137 const MCAsmLayout &Layout) {
1138 uint64_t StartOffset = W.OS.tell();
1139
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001140 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001141
1142 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001143 SmallVector<WasmFunction, 4> Functions;
1144 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001145 SmallVector<wasm::WasmImport, 4> Imports;
1146 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001147 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001148 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001149 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001150 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001151 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001152
Sam Cleggf950b242017-12-11 23:03:38 +00001153 // For now, always emit the memory import, since loads and stores are not
1154 // valid without it. In the future, we could perhaps be more clever and omit
1155 // it if there are no loads or stores.
Sam Clegg8defa952018-02-12 22:41:29 +00001156 wasm::WasmImport MemImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001157 MemImport.Module = "env";
1158 MemImport.Field = "__linear_memory";
Sam Cleggf950b242017-12-11 23:03:38 +00001159 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1160 Imports.push_back(MemImport);
1161
1162 // For now, always emit the table section, since indirect calls are not
1163 // valid without it. In the future, we could perhaps be more clever and omit
1164 // it if there are no indirect calls.
Sam Clegg8defa952018-02-12 22:41:29 +00001165 wasm::WasmImport TableImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001166 TableImport.Module = "env";
1167 TableImport.Field = "__indirect_function_table";
Sam Cleggf950b242017-12-11 23:03:38 +00001168 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001169 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001170 Imports.push_back(TableImport);
1171
Heejin Ahnda419bd2018-11-14 02:46:21 +00001172 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001173 // symbols. This must be done before populating WasmIndices for defined
1174 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001175 for (const MCSymbol &S : Asm.symbols()) {
1176 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1177
1178 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001179 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001180 if (WS.isFunction())
1181 registerFunctionType(WS);
1182
Heejin Ahnda419bd2018-11-14 02:46:21 +00001183 if (WS.isEvent())
1184 registerEventType(WS);
1185
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001186 if (WS.isTemporary())
1187 continue;
1188
1189 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001190 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001191 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001192 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001193 Import.Module = WS.getImportModule();
1194 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001195 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001196 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001197 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001198 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001199 WasmIndices[&WS] = NumFunctionImports++;
1200 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001201 if (WS.isWeak())
1202 report_fatal_error("undefined global symbol cannot be weak");
1203
Sam Clegg6c899ba2018-02-23 05:08:34 +00001204 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001205 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001206 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg492f7522019-03-26 19:46:15 +00001207 Import.Module = WS.getImportModule();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001208 Import.Global = WS.getGlobalType();
1209 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001210 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001211 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001212 } else if (WS.isEvent()) {
1213 if (WS.isWeak())
1214 report_fatal_error("undefined event symbol cannot be weak");
1215
1216 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001217 Import.Module = WS.getImportModule();
1218 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001219 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1220 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1221 Import.Event.SigIndex = getEventType(WS);
1222 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001223 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001224 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001225 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001226 }
1227 }
1228
Sam Clegg492f7522019-03-26 19:46:15 +00001229 // Add imports for GOT globals
1230 for (const MCSymbol &S : Asm.symbols()) {
1231 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1232 if (WS.isUsedInGOT()) {
1233 wasm::WasmImport Import;
1234 if (WS.isFunction())
1235 Import.Module = "GOT.func";
1236 else
1237 Import.Module = "GOT.mem";
1238 Import.Field = WS.getName();
1239 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1240 Import.Global = {wasm::WASM_TYPE_I32, true};
1241 Imports.push_back(Import);
1242 assert(GOTIndices.count(&WS) == 0);
1243 GOTIndices[&WS] = NumGlobalImports++;
1244 }
1245 }
1246
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001247 // Populate DataSegments and CustomSections, which must be done before
1248 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001249 for (MCSection &Sec : Asm) {
1250 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001251 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001252
Sam Cleggbafe6902017-12-15 00:17:10 +00001253 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001254 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001255 continue;
1256
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001257 // Code is handled separately
1258 if (Section.getKind().isText())
1259 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001260
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001261 if (Section.isWasmData()) {
1262 uint32_t SegmentIndex = DataSegments.size();
1263 DataSize = alignTo(DataSize, Section.getAlignment());
1264 DataSegments.emplace_back();
1265 WasmDataSegment &Segment = DataSegments.back();
1266 Segment.Name = SectionName;
Simon Pilgrim9b49f362019-02-24 13:31:52 +00001267 Segment.InitFlags =
1268 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001269 Segment.Offset = DataSize;
1270 Segment.Section = &Section;
1271 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001272 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001273 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001274 DataSize += Segment.Data.size();
1275 Section.setSegmentIndex(SegmentIndex);
1276
1277 if (const MCSymbolWasm *C = Section.getGroup()) {
1278 Comdats[C->getName()].emplace_back(
1279 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1280 }
1281 } else {
1282 // Create custom sections
1283 assert(Sec.getKind().isMetadata());
1284
1285 StringRef Name = SectionName;
1286
1287 // For user-defined custom sections, strip the prefix
1288 if (Name.startswith(".custom_section."))
1289 Name = Name.substr(strlen(".custom_section."));
1290
Heejin Ahnf208f632018-09-05 01:27:38 +00001291 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001292 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001293 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001294 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001295 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001296 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001297 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001298
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001299 // Separate out the producers and target features sections
Thomas Livelycbda16e2019-01-17 02:29:55 +00001300 if (Name == "producers") {
1301 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1302 continue;
1303 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001304 if (Name == "target_features") {
1305 TargetFeaturesSection =
1306 llvm::make_unique<WasmCustomSection>(Name, &Section);
1307 continue;
1308 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001309
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001310 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001311 }
Sam Clegg759631c2017-09-15 20:54:59 +00001312 }
1313
Nicholas Wilson586320c2018-02-28 17:19:48 +00001314 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001315 for (const MCSymbol &S : Asm.symbols()) {
1316 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1317 // or used in relocations.
1318 if (S.isTemporary() && S.getName().empty())
1319 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001320
Dan Gohmand934cb82017-02-24 23:18:00 +00001321 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001322 LLVM_DEBUG(
1323 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1324 << " isDefined=" << S.isDefined() << " isExternal="
1325 << S.isExternal() << " isTemporary=" << S.isTemporary()
1326 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1327 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001328
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001329 if (WS.isVariable())
1330 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001331 if (WS.isComdat() && !WS.isDefined())
1332 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001333
Dan Gohmand934cb82017-02-24 23:18:00 +00001334 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001335 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001336 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001337 if (WS.getOffset() != 0)
1338 report_fatal_error(
1339 "function sections must contain one function each");
1340
Heejin Ahn18c56a02019-02-04 19:13:39 +00001341 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001342 report_fatal_error(
1343 "function symbols must have a size set with .size");
1344
Sam Clegg6c899ba2018-02-23 05:08:34 +00001345 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001346 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001347 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001348 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001349 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001350 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001351 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001352
1353 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1354 if (const MCSymbolWasm *C = Section.getGroup()) {
1355 Comdats[C->getName()].emplace_back(
1356 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1357 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001358 } else {
1359 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001360 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001361 }
1362
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001363 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001364
Sam Clegg6c899ba2018-02-23 05:08:34 +00001365 } else if (WS.isData()) {
Wouter van Oortmerssenf3feb6a2019-03-04 17:18:04 +00001366 if (!isInSymtab(WS))
Sam Cleggc38e9472017-06-02 01:05:24 +00001367 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001368
Sam Clegg6c899ba2018-02-23 05:08:34 +00001369 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001370 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1371 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001372 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001373 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001374
Sam Cleggfe6414b2017-06-21 23:46:41 +00001375 if (!WS.getSize())
1376 report_fatal_error("data symbols must have a size set with .size: " +
1377 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001378
Sam Cleggfe6414b2017-06-21 23:46:41 +00001379 int64_t Size = 0;
1380 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1381 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001382
Sam Clegg759631c2017-09-15 20:54:59 +00001383 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001384 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001385
Sam Clegg6c899ba2018-02-23 05:08:34 +00001386 // For each data symbol, export it in the symtab as a reference to the
1387 // corresponding Wasm data segment.
1388 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1389 DataSection.getSegmentIndex(),
1390 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1391 static_cast<uint32_t>(Size)};
1392 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001393 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001394
Sam Clegga165f2d2018-04-30 19:40:57 +00001395 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001396 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001397 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001398 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001399
Eric Christopher545932b2018-02-23 21:14:47 +00001400 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001401 LLVM_DEBUG(dbgs() << " -> global index: "
1402 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001403
1404 } else if (WS.isEvent()) {
1405 // C++ exception symbol (__cpp_exception)
1406 unsigned Index;
1407 if (WS.isDefined()) {
1408 Index = NumEventImports + Events.size();
1409 wasm::WasmEventType Event;
1410 Event.SigIndex = getEventType(WS);
1411 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
Sam Clegg492f7522019-03-26 19:46:15 +00001412 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001413 WasmIndices[&WS] = Index;
1414 Events.push_back(Event);
1415 } else {
1416 // An import; the index was assigned above.
Sam Clegg492f7522019-03-26 19:46:15 +00001417 assert(WasmIndices.count(&WS) > 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001418 Index = WasmIndices.find(&WS)->second;
1419 }
1420 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1421 << "\n");
1422
Sam Clegga165f2d2018-04-30 19:40:57 +00001423 } else {
1424 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001425 }
1426 }
1427
Nicholas Wilson586320c2018-02-28 17:19:48 +00001428 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1429 // process these in a separate pass because we need to have processed the
1430 // target of the alias before the alias itself and the symbols are not
1431 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001432 for (const MCSymbol &S : Asm.symbols()) {
1433 if (!S.isVariable())
1434 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001435
Sam Cleggcd65f692018-01-11 23:59:16 +00001436 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001437
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001438 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001439 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001440 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001441 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1442 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001443
Sam Cleggffba00b2019-02-22 21:41:42 +00001444 if (ResolvedSym->isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001445 assert(WasmIndices.count(ResolvedSym) > 0);
1446 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
Sam Clegg492f7522019-03-26 19:46:15 +00001447 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001448 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001449 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggffba00b2019-02-22 21:41:42 +00001450 } else if (ResolvedSym->isData()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001451 assert(DataLocations.count(ResolvedSym) > 0);
1452 const wasm::WasmDataReference &Ref =
1453 DataLocations.find(ResolvedSym)->second;
1454 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001455 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001456 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001457 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001458 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001459 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001460
Nicholas Wilson586320c2018-02-28 17:19:48 +00001461 // Finally, populate the symbol table itself, in its "natural" order.
1462 for (const MCSymbol &S : Asm.symbols()) {
1463 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001464 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001465 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001466 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001467 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001468 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001469
1470 uint32_t Flags = 0;
1471 if (WS.isWeak())
1472 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1473 if (WS.isHidden())
1474 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1475 if (!WS.isExternal() && WS.isDefined())
1476 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1477 if (WS.isUndefined())
1478 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001479 if (WS.isExported())
1480 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Dan Gohman29874ce2019-02-07 22:03:32 +00001481 if (WS.getName() != WS.getImportName())
1482 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001483
1484 wasm::WasmSymbolInfo Info;
1485 Info.Name = WS.getName();
1486 Info.Kind = WS.getType();
1487 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001488 if (!WS.isData()) {
1489 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001490 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001491 } else if (WS.isDefined()) {
1492 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001493 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001494 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001495 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001496 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001497 }
1498
Sam Clegg6006e092017-12-22 20:31:39 +00001499 {
1500 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001501 // Functions referenced by a relocation need to put in the table. This is
1502 // purely to make the object file's provisional values readable, and is
1503 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001504 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1505 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001506 return;
1507 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001508 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001509 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001510 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001511 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001512 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1513 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001514 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001515 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001516 }
1517 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001518
Sam Clegg6006e092017-12-22 20:31:39 +00001519 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1520 HandleReloc(RelEntry);
1521 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1522 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001523 }
1524
Sam Cleggbafe6902017-12-15 00:17:10 +00001525 // Translate .init_array section contents into start functions.
1526 for (const MCSection &S : Asm) {
1527 const auto &WS = static_cast<const MCSectionWasm &>(S);
1528 if (WS.getSectionName().startswith(".fini_array"))
1529 report_fatal_error(".fini_array sections are unsupported");
1530 if (!WS.getSectionName().startswith(".init_array"))
1531 continue;
1532 if (WS.getFragmentList().empty())
1533 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001534
1535 // init_array is expected to contain a single non-empty data fragment
1536 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001537 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001538
1539 auto IT = WS.begin();
1540 const MCFragment &EmptyFrag = *IT;
1541 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1542 report_fatal_error(".init_array section should be aligned");
1543
1544 IT = std::next(IT);
1545 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001546 if (AlignFrag.getKind() != MCFragment::FT_Align)
1547 report_fatal_error(".init_array section should be aligned");
1548 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1549 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001550
1551 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001552 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1553 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001554
Sam Cleggbafe6902017-12-15 00:17:10 +00001555 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001556 unsigned PrefixLength = strlen(".init_array");
1557 if (WS.getSectionName().size() > PrefixLength) {
1558 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001559 report_fatal_error(
1560 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001561 if (WS.getSectionName()
1562 .substr(PrefixLength + 1)
1563 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001564 report_fatal_error("invalid .init_array section priority");
1565 }
1566 const auto &DataFrag = cast<MCDataFragment>(Frag);
1567 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001568 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001569 P = (const uint8_t *)Contents.data(),
1570 *End = (const uint8_t *)Contents.data() + Contents.size();
1571 P != End; ++P) {
1572 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001573 report_fatal_error("non-symbolic data in .init_array section");
1574 }
1575 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001576 assert(Fixup.getKind() ==
1577 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001578 const MCExpr *Expr = Fixup.getValue();
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001579 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1580 if (!SymRef)
Sam Cleggbafe6902017-12-15 00:17:10 +00001581 report_fatal_error("fixups in .init_array should be symbol references");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001582 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1583 if (TargetSym.getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001584 report_fatal_error("symbols in .init_array should exist in symbtab");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001585 if (!TargetSym.isFunction())
1586 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001587 InitFuncs.push_back(
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001588 std::make_pair(Priority, TargetSym.getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001589 }
1590 }
1591
Dan Gohman18eafb62017-02-22 01:23:18 +00001592 // Write out the Wasm header.
1593 writeHeader(Asm);
1594
Heejin Ahnda419bd2018-11-14 02:46:21 +00001595 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001596 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001597 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001598 // Skip the "table" section; we import the table instead.
1599 // Skip the "memory" section; we import the memory instead.
Heejin Ahnda419bd2018-11-14 02:46:21 +00001600 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001601 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001602 writeElemSection(TableElems);
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001603 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001604 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001605 for (auto &CustomSection : CustomSections)
1606 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001607 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001608 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1609 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001610 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001611 if (ProducersSection)
1612 writeCustomSection(*ProducersSection, Asm, Layout);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001613 if (TargetFeaturesSection)
1614 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001615
Dan Gohmand934cb82017-02-24 23:18:00 +00001616 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001617 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001618}
1619
Lang Hames60fbc7c2017-10-10 16:28:07 +00001620std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001621llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1622 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001623 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001624}