blob: cb00241715a503720c3859c5ee2d463f4a0dab48 [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
Keno Fischercadcb9e2019-06-26 00:52:42 +0000150 bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000151
Sam Clegg6dc65e92017-06-06 16:38:59 +0000152 void print(raw_ostream &Out) const {
Heejin Ahnf208f632018-09-05 01:27:38 +0000153 Out << wasm::relocTypetoString(Type) << " Off=" << Offset
154 << ", Sym=" << *Symbol << ", Addend=" << Addend
Sam Clegg759631c2017-09-15 20:54:59 +0000155 << ", FixupSection=" << FixupSection->getSectionName();
Sam Clegg6dc65e92017-06-06 16:38:59 +0000156 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000157
Aaron Ballman615eb472017-10-15 14:32:27 +0000158#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Cleggb7787fd2017-06-20 04:04:59 +0000159 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
160#endif
Sam Clegg6dc65e92017-06-06 16:38:59 +0000161};
162
Heejin Ahn18c56a02019-02-04 19:13:39 +0000163static const uint32_t InvalidIndex = -1;
Sam Clegg25d8e682018-05-08 00:08:21 +0000164
Sam Cleggcfd44a22018-04-05 17:01:39 +0000165struct WasmCustomSection {
Sam Cleggcfd44a22018-04-05 17:01:39 +0000166
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000167 StringRef Name;
168 MCSectionWasm *Section;
169
170 uint32_t OutputContentsOffset;
171 uint32_t OutputIndex;
172
173 WasmCustomSection(StringRef Name, MCSectionWasm *Section)
174 : Name(Name), Section(Section), OutputContentsOffset(0),
Heejin Ahn18c56a02019-02-04 19:13:39 +0000175 OutputIndex(InvalidIndex) {}
Sam Cleggcfd44a22018-04-05 17:01:39 +0000176};
177
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000178#if !defined(NDEBUG)
Sam Clegg7f055de2017-06-20 04:47:58 +0000179raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000180 Rel.print(OS);
181 return OS;
182}
Sam Clegg1fb8daa2017-06-20 05:05:10 +0000183#endif
Sam Cleggb7787fd2017-06-20 04:04:59 +0000184
Sam Clegg19e8bef2019-01-30 22:47:35 +0000185// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
186// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000187static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000188 uint64_t Offset) {
189 uint8_t Buffer[5];
190 unsigned SizeLen = encodeULEB128(X, Buffer, 5);
191 assert(SizeLen == 5);
192 Stream.pwrite((char *)Buffer, SizeLen, Offset);
193}
194
195// Write X as an signed LEB value at offset Offset in Stream, padded
196// to allow patching.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000197static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000198 uint64_t Offset) {
199 uint8_t Buffer[5];
200 unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
201 assert(SizeLen == 5);
202 Stream.pwrite((char *)Buffer, SizeLen, Offset);
203}
204
205// Write X as a plain integer value at offset Offset in Stream.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000206static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
Sam Clegg19e8bef2019-01-30 22:47:35 +0000207 uint8_t Buffer[4];
208 support::endian::write32le(Buffer, X);
209 Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
210}
211
Dan Gohman18eafb62017-02-22 01:23:18 +0000212class WasmObjectWriter : public MCObjectWriter {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000213 support::endian::Writer W;
214
Dan Gohman18eafb62017-02-22 01:23:18 +0000215 /// The target specific Wasm writer instance.
216 std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
217
Dan Gohmand934cb82017-02-24 23:18:00 +0000218 // Relocations for fixing up references in the code section.
219 std::vector<WasmRelocationEntry> CodeRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000220 uint32_t CodeSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000221
222 // Relocations for fixing up references in the data section.
223 std::vector<WasmRelocationEntry> DataRelocations;
Sam Clegg6f08c842018-04-24 18:11:36 +0000224 uint32_t DataSectionIndex;
Dan Gohmand934cb82017-02-24 23:18:00 +0000225
Dan Gohmand934cb82017-02-24 23:18:00 +0000226 // Index values to use for fixing up call_indirect type indices.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000227 // Maps function symbols to the index of the type of the function
228 DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
Sam Cleggd99f6072017-06-12 23:52:44 +0000229 // Maps function symbols to the table element index space. Used
230 // for TABLE_INDEX relocation types (i.e. address taken functions).
Sam Cleggf9edbe92018-01-31 19:28:47 +0000231 DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000232 // Maps function/global symbols to the function/global/event/section index
233 // space.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000234 DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
Sam Clegg492f7522019-03-26 19:46:15 +0000235 DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000236 // Maps data symbols to the Wasm segment and offset/size with the segment.
237 DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000238
239 // Stores output data (index, relocations, content offset) for custom
240 // section.
241 std::vector<WasmCustomSection> CustomSections;
Thomas Livelycbda16e2019-01-17 02:29:55 +0000242 std::unique_ptr<WasmCustomSection> ProducersSection;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000243 std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000244 // Relocations for fixing up references in the custom sections.
245 DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
246 CustomSectionsRelocations;
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000247
Sam Cleggc0d41192018-05-17 17:15:15 +0000248 // Map from section to defining function symbol.
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000249 DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
250
Heejin Ahnda419bd2018-11-14 02:46:21 +0000251 DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
252 SmallVector<WasmSignature, 4> Signatures;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000253 SmallVector<WasmDataSegment, 4> DataSegments;
Sam Clegg9f3fe422018-01-17 19:28:43 +0000254 unsigned NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000255 unsigned NumGlobalImports = 0;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000256 unsigned NumEventImports = 0;
Chandler Carruth7e1c3342018-04-24 20:30:56 +0000257 uint32_t SectionCount = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +0000258
Dan Gohman18eafb62017-02-22 01:23:18 +0000259 // TargetObjectWriter wrappers.
260 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Dan Gohman18eafb62017-02-22 01:23:18 +0000261
Sam Clegg2322a932018-04-23 19:16:19 +0000262 void startSection(SectionBookkeeping &Section, unsigned SectionId);
263 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000264 void endSection(SectionBookkeeping &Section);
265
Dan Gohman18eafb62017-02-22 01:23:18 +0000266public:
Lang Hames1301a872017-10-10 01:15:10 +0000267 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
268 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000269 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000270
Dan Gohman0917c9e2018-01-15 17:06:23 +0000271private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000272 void reset() override {
273 CodeRelocations.clear();
274 DataRelocations.clear();
275 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000276 WasmIndices.clear();
Sam Clegg492f7522019-03-26 19:46:15 +0000277 GOTIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000278 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000279 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000280 CustomSections.clear();
281 ProducersSection.reset();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000282 TargetFeaturesSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000283 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000284 SignatureIndices.clear();
285 Signatures.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000286 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000287 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000288 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000289 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000290 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000291 }
292
Dan Gohman18eafb62017-02-22 01:23:18 +0000293 void writeHeader(const MCAssembler &Asm);
294
295 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
296 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000297 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000298
299 void executePostLayoutBinding(MCAssembler &Asm,
300 const MCAsmLayout &Layout) override;
301
Peter Collingbourne438390f2018-05-21 18:23:50 +0000302 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000303
Sam Cleggb7787fd2017-06-20 04:04:59 +0000304 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000305 encodeULEB128(Str.size(), W.OS);
306 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000307 }
308
Heejin Ahnf208f632018-09-05 01:27:38 +0000309 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000310
Heejin Ahnda419bd2018-11-14 02:46:21 +0000311 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000312 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000313 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000314 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg8defa952018-02-12 22:41:29 +0000315 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000316 void writeElemSection(ArrayRef<uint32_t> TableElems);
Thomas Livelyfef8de62019-04-12 22:27:48 +0000317 void writeDataCountSection();
Sam Clegg9e15f352017-06-03 02:01:24 +0000318 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000319 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000320 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000321 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000322 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000323 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000324 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000325 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000326 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000327 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000328 void writeCustomSection(WasmCustomSection &CustomSection,
329 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000330 void writeCustomRelocSections();
331 void
332 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
333 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000334
Sam Clegg7c395942017-09-14 23:07:53 +0000335 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000336 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
337 uint64_t ContentsOffset);
338
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000339 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000340 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000341 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000342 void registerFunctionType(const MCSymbolWasm &Symbol);
343 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000344};
Sam Clegg9e15f352017-06-03 02:01:24 +0000345
Dan Gohman18eafb62017-02-22 01:23:18 +0000346} // end anonymous namespace
347
Dan Gohmand934cb82017-02-24 23:18:00 +0000348// Write out a section header and a patchable section size field.
349void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000350 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000351 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000352 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000353
Peter Collingbournef17b1492018-05-21 18:17:42 +0000354 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000355
356 // The section size. We don't know the size yet, so reserve enough space
357 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000358 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000359
360 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000361 Section.ContentsOffset = W.OS.tell();
362 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000363 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000364}
Dan Gohmand934cb82017-02-24 23:18:00 +0000365
Sam Clegg2322a932018-04-23 19:16:19 +0000366void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
367 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000369 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000370
371 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000372 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000373
Dan Gohmand934cb82017-02-24 23:18:00 +0000374 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000375 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000376
377 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000378 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000379}
380
381// Now that the section is complete and we know how big it is, patch up the
382// section size field at the start of the section.
383void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000384 uint64_t Size = W.OS.tell();
385 // /dev/null doesn't support seek/tell and can report offset of 0.
386 // Simply skip this patching in that case.
387 if (!Size)
388 return;
389
390 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000391 if (uint32_t(Size) != Size)
392 report_fatal_error("section size does not fit in a uint32_t");
393
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000394 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000395
396 // Write the final section size to the payload_len field, which follows
397 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000398 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000399 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000400}
401
Dan Gohman18eafb62017-02-22 01:23:18 +0000402// Emit the Wasm header.
403void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000404 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
405 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000406}
407
408void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
409 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000410 // Build a map of sections to the function that defines them, for use
411 // in recordRelocation.
412 for (const MCSymbol &S : Asm.symbols()) {
413 const auto &WS = static_cast<const MCSymbolWasm &>(S);
414 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
415 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
416 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
417 if (!Pair.second)
418 report_fatal_error("section already has a defining function: " +
419 Sec.getSectionName());
420 }
421 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000422}
423
424void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
425 const MCAsmLayout &Layout,
426 const MCFragment *Fragment,
427 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000428 uint64_t &FixedValue) {
Sam Cleggecc5e802019-08-20 00:33:50 +0000429 // The WebAssembly backend should never generate FKF_IsPCRel fixups
Fangrui Songe828ce12019-08-20 02:02:57 +0000430 assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
Sam Cleggecc5e802019-08-20 00:33:50 +0000431 MCFixupKindInfo::FKF_IsPCRel));
432
Sam Cleggfe6414b2017-06-21 23:46:41 +0000433 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000434 uint64_t C = Target.getConstant();
435 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
436 MCContext &Ctx = Asm.getContext();
437
Sam Cleggbafe6902017-12-15 00:17:10 +0000438 // The .init_array isn't translated as data, so don't do relocations in it.
439 if (FixupSection.getSectionName().startswith(".init_array"))
440 return;
441
Dan Gohmand934cb82017-02-24 23:18:00 +0000442 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
Sam Cleggecc5e802019-08-20 00:33:50 +0000443 // To get here the A - B expression must have failed evaluateAsRelocatable.
444 // This means either A or B must be undefined and in WebAssembly we can't
445 // support either of those cases.
Dan Gohmand934cb82017-02-24 23:18:00 +0000446 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
Sam Cleggecc5e802019-08-20 00:33:50 +0000447 Ctx.reportError(
448 Fixup.getLoc(),
449 Twine("symbol '") + SymB.getName() +
450 "': unsupported subtraction expression used in relocation.");
451 return;
Dan Gohmand934cb82017-02-24 23:18:00 +0000452 }
453
454 // We either rejected the fixup or folded B into C at this point.
455 const MCSymbolRefExpr *RefA = Target.getSymA();
Sam Cleggecc5e802019-08-20 00:33:50 +0000456 const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
Dan Gohmand934cb82017-02-24 23:18:00 +0000457
Sam Cleggecc5e802019-08-20 00:33:50 +0000458 if (SymA->isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000459 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000460 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
461 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
462 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000463 }
464
465 // Put any constant offset in an addend. Offsets can be negative, and
466 // LLVM expects wrapping, in contrast to wasm's immediates which can't
467 // be negative and don't wrap.
468 FixedValue = 0;
469
Sam Clegga5e175c2019-03-28 02:07:28 +0000470 unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000471
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000472 // Absolute offset within a section or a function.
473 // Currently only supported for for metadata sections.
474 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000475 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
476 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000477 if (!FixupSection.getKind().isMetadata())
478 report_fatal_error("relocations for function or section offsets are "
479 "only supported in metadata sections");
480
481 const MCSymbol *SectionSymbol = nullptr;
482 const MCSection &SecA = SymA->getSection();
483 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000484 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000485 else
486 SectionSymbol = SecA.getBeginSymbol();
487 if (!SectionSymbol)
488 report_fatal_error("section symbol is required for relocation");
489
490 C += Layout.getSymbolOffset(*SymA);
491 SymA = cast<MCSymbolWasm>(SectionSymbol);
492 }
493
Sam Cleggd1152a22019-02-04 17:28:46 +0000494 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000495 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000496 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000497 if (SymA->getName().empty())
498 report_fatal_error("relocations against un-named temporaries are not yet "
499 "supported by wasm");
500
501 SymA->setUsedInReloc();
502 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000503
Sam Clegg492f7522019-03-26 19:46:15 +0000504 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
505 SymA->setUsedInGOT();
506
Dan Gohmand934cb82017-02-24 23:18:00 +0000507 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000509
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000510 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000511 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000512 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000513 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000514 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000515 CustomSectionsRelocations[&FixupSection].push_back(Rec);
516 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000517 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000518 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000519}
520
Heejin Ahn18c56a02019-02-04 19:13:39 +0000521static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggffba00b2019-02-22 21:41:42 +0000522 const MCSymbolWasm* Ret = &Symbol;
523 while (Ret->isVariable()) {
524 const MCExpr *Expr = Ret->getVariableValue();
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000525 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Cleggffba00b2019-02-22 21:41:42 +0000526 Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000527 }
Sam Cleggffba00b2019-02-22 21:41:42 +0000528 return Ret;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000529}
530
Dan Gohmand934cb82017-02-24 23:18:00 +0000531// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000532// by RelEntry. This value isn't used by the static linker; it just serves
533// to make the object format more readable and more likely to be directly
534// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000535uint32_t
536WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg492f7522019-03-26 19:46:15 +0000537 if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
538 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
539 return GOTIndices[RelEntry.Symbol];
540 }
541
Sam Clegg60ec3032018-01-23 01:23:17 +0000542 switch (RelEntry.Type) {
Sam Clegg2a7cac92019-04-04 17:43:50 +0000543 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000544 case wasm::R_WASM_TABLE_INDEX_SLEB:
545 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000546 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000547 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000548 assert(Sym->isFunction());
549 return TableIndices[Sym];
550 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000551 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000552 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000553 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000554 case wasm::R_WASM_FUNCTION_INDEX_LEB:
555 case wasm::R_WASM_GLOBAL_INDEX_LEB:
556 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000557 // Provisional value is function/global/event Wasm index
Sam Clegg492f7522019-03-26 19:46:15 +0000558 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
Sam Clegg6c899ba2018-02-23 05:08:34 +0000559 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000560 case wasm::R_WASM_FUNCTION_OFFSET_I32:
561 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000562 const auto &Section =
563 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
564 return Section.getSectionOffset() + RelEntry.Addend;
565 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000566 case wasm::R_WASM_MEMORY_ADDR_LEB:
567 case wasm::R_WASM_MEMORY_ADDR_I32:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000568 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000569 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000570 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000571 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000572 // For undefined symbols, use zero
573 if (!Sym->isDefined())
574 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000575 const wasm::WasmDataReference &Ref = DataLocations[Sym];
576 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000577 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000578 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000579 }
580 default:
581 llvm_unreachable("invalid relocation type");
582 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000583}
584
Sam Clegg759631c2017-09-15 20:54:59 +0000585static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000586 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000587 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000588
Sam Clegg63ebb812017-09-29 16:50:08 +0000589 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
590
Sam Clegg759631c2017-09-15 20:54:59 +0000591 for (const MCFragment &Frag : DataSection) {
592 if (Frag.hasInstructions())
593 report_fatal_error("only data supported in data sections");
594
595 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
596 if (Align->getValueSize() != 1)
597 report_fatal_error("only byte values supported for alignment");
598 // If nops are requested, use zeros, as this is the data section.
599 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000600 uint64_t Size =
601 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
602 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000603 DataBytes.resize(Size, Value);
604 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000605 int64_t NumValues;
606 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000607 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000608 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
609 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000610 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
611 const SmallVectorImpl<char> &Contents = LEB->getContents();
612 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000613 } else {
614 const auto &DataFrag = cast<MCDataFragment>(Frag);
615 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000616 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
617 }
618 }
619
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000620 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000621}
622
Sam Clegg60ec3032018-01-23 01:23:17 +0000623uint32_t
624WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000625 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000626 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000627 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000628 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000629 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000631
Sam Clegg25d8e682018-05-08 00:08:21 +0000632 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000633}
634
Dan Gohmand934cb82017-02-24 23:18:00 +0000635// Apply the portions of the relocation records that we can handle ourselves
636// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000637void WasmObjectWriter::applyRelocations(
638 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000639 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000640 for (const WasmRelocationEntry &RelEntry : Relocations) {
641 uint64_t Offset = ContentsOffset +
642 RelEntry.FixupSection->getSectionOffset() +
643 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000644
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000645 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000646 uint32_t Value = getProvisionalValue(RelEntry);
647
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000648 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000649 case wasm::R_WASM_FUNCTION_INDEX_LEB:
650 case wasm::R_WASM_TYPE_INDEX_LEB:
651 case wasm::R_WASM_GLOBAL_INDEX_LEB:
652 case wasm::R_WASM_MEMORY_ADDR_LEB:
653 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000654 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000655 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000656 case wasm::R_WASM_TABLE_INDEX_I32:
657 case wasm::R_WASM_MEMORY_ADDR_I32:
658 case wasm::R_WASM_FUNCTION_OFFSET_I32:
659 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000660 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000661 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000662 case wasm::R_WASM_TABLE_INDEX_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000663 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000664 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000665 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000666 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000667 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000668 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000669 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000670 }
671 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000672}
673
Heejin Ahnda419bd2018-11-14 02:46:21 +0000674void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
675 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000676 return;
677
678 SectionBookkeeping Section;
679 startSection(Section, wasm::WASM_SEC_TYPE);
680
Heejin Ahnda419bd2018-11-14 02:46:21 +0000681 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000682
Heejin Ahnda419bd2018-11-14 02:46:21 +0000683 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000684 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000685 encodeULEB128(Sig.Params.size(), W.OS);
686 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000687 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000688 encodeULEB128(Sig.Returns.size(), W.OS);
689 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000690 writeValueType(Ty);
691 }
692
693 endSection(Section);
694}
695
Sam Clegg8defa952018-02-12 22:41:29 +0000696void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000697 uint32_t DataSize,
698 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000699 if (Imports.empty())
700 return;
701
Sam Cleggf950b242017-12-11 23:03:38 +0000702 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
703
Sam Clegg9e15f352017-06-03 02:01:24 +0000704 SectionBookkeeping Section;
705 startSection(Section, wasm::WASM_SEC_IMPORT);
706
Peter Collingbournef17b1492018-05-21 18:17:42 +0000707 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000708 for (const wasm::WasmImport &Import : Imports) {
709 writeString(Import.Module);
710 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000711 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712
713 switch (Import.Kind) {
714 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000715 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000716 break;
717 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000718 W.OS << char(Import.Global.Type);
719 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000720 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000721 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000722 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000723 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000724 break;
725 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000726 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000727 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000728 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000729 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000730 case wasm::WASM_EXTERNAL_EVENT:
731 encodeULEB128(Import.Event.Attribute, W.OS);
732 encodeULEB128(Import.Event.SigIndex, W.OS);
733 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000734 default:
735 llvm_unreachable("unsupported import kind");
736 }
737 }
738
739 endSection(Section);
740}
741
Sam Clegg457fb0b2017-09-15 19:50:44 +0000742void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000743 if (Functions.empty())
744 return;
745
746 SectionBookkeeping Section;
747 startSection(Section, wasm::WASM_SEC_FUNCTION);
748
Peter Collingbournef17b1492018-05-21 18:17:42 +0000749 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000751 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000752
753 endSection(Section);
754}
755
Heejin Ahnda419bd2018-11-14 02:46:21 +0000756void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
757 if (Events.empty())
758 return;
759
760 SectionBookkeeping Section;
761 startSection(Section, wasm::WASM_SEC_EVENT);
762
763 encodeULEB128(Events.size(), W.OS);
764 for (const wasm::WasmEventType &Event : Events) {
765 encodeULEB128(Event.Attribute, W.OS);
766 encodeULEB128(Event.SigIndex, W.OS);
767 }
768
769 endSection(Section);
770}
771
Sam Clegg8defa952018-02-12 22:41:29 +0000772void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 if (Exports.empty())
774 return;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_EXPORT);
778
Peter Collingbournef17b1492018-05-21 18:17:42 +0000779 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000780 for (const wasm::WasmExport &Export : Exports) {
781 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000782 W.OS << char(Export.Kind);
783 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000784 }
785
786 endSection(Section);
787}
788
Sam Clegg457fb0b2017-09-15 19:50:44 +0000789void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000790 if (TableElems.empty())
791 return;
792
793 SectionBookkeeping Section;
794 startSection(Section, wasm::WASM_SEC_ELEM);
795
Peter Collingbournef17b1492018-05-21 18:17:42 +0000796 encodeULEB128(1, W.OS); // number of "segments"
797 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000798
799 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000800 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000801 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000802 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000803
Peter Collingbournef17b1492018-05-21 18:17:42 +0000804 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000805 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000806 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000807
808 endSection(Section);
809}
810
Thomas Livelyfef8de62019-04-12 22:27:48 +0000811void WasmObjectWriter::writeDataCountSection() {
812 if (DataSegments.empty())
813 return;
814
815 SectionBookkeeping Section;
816 startSection(Section, wasm::WASM_SEC_DATACOUNT);
817 encodeULEB128(DataSegments.size(), W.OS);
818 endSection(Section);
819}
820
Sam Clegg457fb0b2017-09-15 19:50:44 +0000821void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
822 const MCAsmLayout &Layout,
823 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000824 if (Functions.empty())
825 return;
826
827 SectionBookkeeping Section;
828 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000829 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000830
Peter Collingbournef17b1492018-05-21 18:17:42 +0000831 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000832
833 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000834 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000835
Sam Clegg9e15f352017-06-03 02:01:24 +0000836 int64_t Size = 0;
837 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
838 report_fatal_error(".size expression must be evaluatable");
839
Peter Collingbournef17b1492018-05-21 18:17:42 +0000840 encodeULEB128(Size, W.OS);
841 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
842 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000843 }
844
Sam Clegg9e15f352017-06-03 02:01:24 +0000845 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000846 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000847
848 endSection(Section);
849}
850
Sam Clegg6c899ba2018-02-23 05:08:34 +0000851void WasmObjectWriter::writeDataSection() {
852 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000853 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000854
855 SectionBookkeeping Section;
856 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000857 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000858
Peter Collingbournef17b1492018-05-21 18:17:42 +0000859 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000860
Sam Clegg6c899ba2018-02-23 05:08:34 +0000861 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000862 encodeULEB128(Segment.InitFlags, W.OS); // flags
863 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
864 encodeULEB128(0, W.OS); // memory index
865 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
866 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
867 encodeSLEB128(Segment.Offset, W.OS); // offset
868 W.OS << char(wasm::WASM_OPCODE_END);
869 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000870 encodeULEB128(Segment.Data.size(), W.OS); // size
871 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
872 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000873 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000874
875 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000876 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000877
878 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000879}
880
Sam Clegg6f08c842018-04-24 18:11:36 +0000881void WasmObjectWriter::writeRelocSection(
882 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000883 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000884 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
885 // for descriptions of the reloc sections.
886
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000887 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000888 return;
889
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000890 // First, ensure the relocations are sorted in offset order. In general they
891 // should already be sorted since `recordRelocation` is called in offset
892 // order, but for the code section we combine many MC sections into single
893 // wasm section, and this order is determined by the order of Asm.Symbols()
894 // not the sections order.
Fangrui Songefd94c52019-04-23 14:51:27 +0000895 llvm::stable_sort(
896 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000897 return (A.Offset + A.FixupSection->getSectionOffset()) <
898 (B.Offset + B.FixupSection->getSectionOffset());
899 });
900
Sam Clegg9e15f352017-06-03 02:01:24 +0000901 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000902 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000903
Peter Collingbournef17b1492018-05-21 18:17:42 +0000904 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000905 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000906 for (const WasmRelocationEntry &RelEntry : Relocs) {
907 uint64_t Offset =
908 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000909 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000910
Peter Collingbournef17b1492018-05-21 18:17:42 +0000911 W.OS << char(RelEntry.Type);
912 encodeULEB128(Offset, W.OS);
913 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000914 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000915 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000916 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000917
918 endSection(Section);
919}
920
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000921void WasmObjectWriter::writeCustomRelocSections() {
922 for (const auto &Sec : CustomSections) {
923 auto &Relocations = CustomSectionsRelocations[Sec.Section];
924 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
925 }
926}
927
Sam Clegg9e15f352017-06-03 02:01:24 +0000928void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000929 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000930 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000931 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000932 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000933 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000934 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000935
Sam Clegg6bb5a412018-04-26 18:15:32 +0000936 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000937 if (SymbolInfos.size() != 0) {
938 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000939 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000940 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000941 encodeULEB128(Sym.Kind, W.OS);
942 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000943 switch (Sym.Kind) {
944 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
945 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000946 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000947 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000948 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
949 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000950 writeString(Sym.Name);
951 break;
952 case wasm::WASM_SYMBOL_TYPE_DATA:
953 writeString(Sym.Name);
954 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000955 encodeULEB128(Sym.DataRef.Segment, W.OS);
956 encodeULEB128(Sym.DataRef.Offset, W.OS);
957 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000958 }
959 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000960 case wasm::WASM_SYMBOL_TYPE_SECTION: {
961 const uint32_t SectionIndex =
962 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000963 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000964 break;
965 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000966 default:
967 llvm_unreachable("unexpected kind");
968 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000969 }
970 endSection(SubSection);
971 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000972
Sam Clegg6c899ba2018-02-23 05:08:34 +0000973 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000974 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000975 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000976 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000977 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000978 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +0000979 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000980 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000981 endSection(SubSection);
982 }
983
Sam Cleggbafe6902017-12-15 00:17:10 +0000984 if (!InitFuncs.empty()) {
985 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000986 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000987 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000988 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +0000989 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +0000990 }
991 endSection(SubSection);
992 }
993
Sam Cleggea7cace2018-01-09 23:43:14 +0000994 if (Comdats.size()) {
995 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000996 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +0000997 for (const auto &C : Comdats) {
998 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000999 encodeULEB128(0, W.OS); // flags for future use
1000 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001001 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001002 encodeULEB128(Entry.Kind, W.OS);
1003 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001004 }
1005 }
1006 endSection(SubSection);
1007 }
1008
Sam Clegg9e15f352017-06-03 02:01:24 +00001009 endSection(Section);
1010}
1011
Thomas Livelycbda16e2019-01-17 02:29:55 +00001012void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1013 const MCAssembler &Asm,
1014 const MCAsmLayout &Layout) {
1015 SectionBookkeeping Section;
1016 auto *Sec = CustomSection.Section;
1017 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001018
Thomas Livelycbda16e2019-01-17 02:29:55 +00001019 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1020 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001021
Thomas Livelycbda16e2019-01-17 02:29:55 +00001022 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1023 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001024
Thomas Livelycbda16e2019-01-17 02:29:55 +00001025 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001026
Thomas Livelycbda16e2019-01-17 02:29:55 +00001027 // Apply fixups.
1028 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1029 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001030}
1031
Heejin Ahnf208f632018-09-05 01:27:38 +00001032uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001033 assert(Symbol.isFunction());
1034 assert(TypeIndices.count(&Symbol));
1035 return TypeIndices[&Symbol];
1036}
1037
Heejin Ahnda419bd2018-11-14 02:46:21 +00001038uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1039 assert(Symbol.isEvent());
1040 assert(TypeIndices.count(&Symbol));
1041 return TypeIndices[&Symbol];
1042}
1043
Heejin Ahn38b12f52018-11-20 00:38:10 +00001044void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001045 assert(Symbol.isFunction());
1046
Heejin Ahnda419bd2018-11-14 02:46:21 +00001047 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001048 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001049 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001050 S.Returns = Sig->Returns;
1051 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001052 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001053
Heejin Ahnda419bd2018-11-14 02:46:21 +00001054 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001055 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001056 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001057 TypeIndices[&Symbol] = Pair.first->second;
1058
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001059 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1060 << " new:" << Pair.second << "\n");
1061 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001062}
1063
Heejin Ahn38b12f52018-11-20 00:38:10 +00001064void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001065 assert(Symbol.isEvent());
1066
1067 // TODO Currently we don't generate imported exceptions, but if we do, we
1068 // should have a way of infering types of imported exceptions.
1069 WasmSignature S;
1070 if (auto *Sig = Symbol.getSignature()) {
1071 S.Returns = Sig->Returns;
1072 S.Params = Sig->Params;
1073 }
1074
1075 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1076 if (Pair.second)
1077 Signatures.push_back(S);
1078 TypeIndices[&Symbol] = Pair.first->second;
1079
1080 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1081 << "\n");
1082 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001083}
1084
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001085static bool isInSymtab(const MCSymbolWasm &Sym) {
1086 if (Sym.isUsedInReloc())
1087 return true;
1088
1089 if (Sym.isComdat() && !Sym.isDefined())
1090 return false;
1091
1092 if (Sym.isTemporary() && Sym.getName().empty())
1093 return false;
1094
1095 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1096 return false;
1097
1098 if (Sym.isSection())
1099 return false;
1100
1101 return true;
1102}
1103
Peter Collingbourne438390f2018-05-21 18:23:50 +00001104uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1105 const MCAsmLayout &Layout) {
1106 uint64_t StartOffset = W.OS.tell();
1107
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001108 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001109
1110 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001111 SmallVector<WasmFunction, 4> Functions;
1112 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001113 SmallVector<wasm::WasmImport, 4> Imports;
1114 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001115 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001116 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001117 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001118 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001119 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001120
Sam Cleggf950b242017-12-11 23:03:38 +00001121 // For now, always emit the memory import, since loads and stores are not
1122 // valid without it. In the future, we could perhaps be more clever and omit
1123 // it if there are no loads or stores.
Sam Clegg8defa952018-02-12 22:41:29 +00001124 wasm::WasmImport MemImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001125 MemImport.Module = "env";
1126 MemImport.Field = "__linear_memory";
Sam Cleggf950b242017-12-11 23:03:38 +00001127 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1128 Imports.push_back(MemImport);
1129
1130 // For now, always emit the table section, since indirect calls are not
1131 // valid without it. In the future, we could perhaps be more clever and omit
1132 // it if there are no indirect calls.
Sam Clegg8defa952018-02-12 22:41:29 +00001133 wasm::WasmImport TableImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001134 TableImport.Module = "env";
1135 TableImport.Field = "__indirect_function_table";
Sam Cleggf950b242017-12-11 23:03:38 +00001136 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001137 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001138 Imports.push_back(TableImport);
1139
Heejin Ahnda419bd2018-11-14 02:46:21 +00001140 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001141 // symbols. This must be done before populating WasmIndices for defined
1142 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001143 for (const MCSymbol &S : Asm.symbols()) {
1144 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1145
1146 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001147 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001148 if (WS.isFunction())
1149 registerFunctionType(WS);
1150
Heejin Ahnda419bd2018-11-14 02:46:21 +00001151 if (WS.isEvent())
1152 registerEventType(WS);
1153
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001154 if (WS.isTemporary())
1155 continue;
1156
1157 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001158 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001159 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001160 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001161 Import.Module = WS.getImportModule();
1162 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001163 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001164 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001165 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001166 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001167 WasmIndices[&WS] = NumFunctionImports++;
1168 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001169 if (WS.isWeak())
1170 report_fatal_error("undefined global symbol cannot be weak");
1171
Sam Clegg6c899ba2018-02-23 05:08:34 +00001172 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001173 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001174 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg492f7522019-03-26 19:46:15 +00001175 Import.Module = WS.getImportModule();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001176 Import.Global = WS.getGlobalType();
1177 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001178 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001179 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001180 } else if (WS.isEvent()) {
1181 if (WS.isWeak())
1182 report_fatal_error("undefined event symbol cannot be weak");
1183
1184 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001185 Import.Module = WS.getImportModule();
1186 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001187 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1188 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1189 Import.Event.SigIndex = getEventType(WS);
1190 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001191 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001192 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001193 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001194 }
1195 }
1196
Sam Clegg492f7522019-03-26 19:46:15 +00001197 // Add imports for GOT globals
1198 for (const MCSymbol &S : Asm.symbols()) {
1199 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1200 if (WS.isUsedInGOT()) {
1201 wasm::WasmImport Import;
1202 if (WS.isFunction())
1203 Import.Module = "GOT.func";
1204 else
1205 Import.Module = "GOT.mem";
1206 Import.Field = WS.getName();
1207 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1208 Import.Global = {wasm::WASM_TYPE_I32, true};
1209 Imports.push_back(Import);
1210 assert(GOTIndices.count(&WS) == 0);
1211 GOTIndices[&WS] = NumGlobalImports++;
1212 }
1213 }
1214
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001215 // Populate DataSegments and CustomSections, which must be done before
1216 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001217 for (MCSection &Sec : Asm) {
1218 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001219 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001220
Sam Cleggbafe6902017-12-15 00:17:10 +00001221 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001222 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001223 continue;
1224
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001225 // Code is handled separately
1226 if (Section.getKind().isText())
1227 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001228
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001229 if (Section.isWasmData()) {
1230 uint32_t SegmentIndex = DataSegments.size();
1231 DataSize = alignTo(DataSize, Section.getAlignment());
1232 DataSegments.emplace_back();
1233 WasmDataSegment &Segment = DataSegments.back();
1234 Segment.Name = SectionName;
Simon Pilgrim9b49f362019-02-24 13:31:52 +00001235 Segment.InitFlags =
1236 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001237 Segment.Offset = DataSize;
1238 Segment.Section = &Section;
1239 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001240 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001241 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001242 DataSize += Segment.Data.size();
1243 Section.setSegmentIndex(SegmentIndex);
1244
1245 if (const MCSymbolWasm *C = Section.getGroup()) {
1246 Comdats[C->getName()].emplace_back(
1247 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1248 }
1249 } else {
1250 // Create custom sections
1251 assert(Sec.getKind().isMetadata());
1252
1253 StringRef Name = SectionName;
1254
1255 // For user-defined custom sections, strip the prefix
1256 if (Name.startswith(".custom_section."))
1257 Name = Name.substr(strlen(".custom_section."));
1258
Heejin Ahnf208f632018-09-05 01:27:38 +00001259 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001260 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001261 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001262 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001263 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001264 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001265 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001266
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001267 // Separate out the producers and target features sections
Thomas Livelycbda16e2019-01-17 02:29:55 +00001268 if (Name == "producers") {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001269 ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
Thomas Livelycbda16e2019-01-17 02:29:55 +00001270 continue;
1271 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001272 if (Name == "target_features") {
1273 TargetFeaturesSection =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001274 std::make_unique<WasmCustomSection>(Name, &Section);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001275 continue;
1276 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001277
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001278 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001279 }
Sam Clegg759631c2017-09-15 20:54:59 +00001280 }
1281
Nicholas Wilson586320c2018-02-28 17:19:48 +00001282 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001283 for (const MCSymbol &S : Asm.symbols()) {
1284 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1285 // or used in relocations.
1286 if (S.isTemporary() && S.getName().empty())
1287 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001288
Dan Gohmand934cb82017-02-24 23:18:00 +00001289 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001290 LLVM_DEBUG(
1291 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1292 << " isDefined=" << S.isDefined() << " isExternal="
1293 << S.isExternal() << " isTemporary=" << S.isTemporary()
1294 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1295 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001296
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001297 if (WS.isVariable())
1298 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001299 if (WS.isComdat() && !WS.isDefined())
1300 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001301
Dan Gohmand934cb82017-02-24 23:18:00 +00001302 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001303 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001304 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001305 if (WS.getOffset() != 0)
1306 report_fatal_error(
1307 "function sections must contain one function each");
1308
Heejin Ahn18c56a02019-02-04 19:13:39 +00001309 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001310 report_fatal_error(
1311 "function symbols must have a size set with .size");
1312
Sam Clegg6c899ba2018-02-23 05:08:34 +00001313 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001314 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001315 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001316 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001317 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001318 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001319 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001320
1321 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1322 if (const MCSymbolWasm *C = Section.getGroup()) {
1323 Comdats[C->getName()].emplace_back(
1324 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1325 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001326 } else {
1327 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001328 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001329 }
1330
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001331 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001332
Sam Clegg6c899ba2018-02-23 05:08:34 +00001333 } else if (WS.isData()) {
Wouter van Oortmerssenf3feb6a2019-03-04 17:18:04 +00001334 if (!isInSymtab(WS))
Sam Cleggc38e9472017-06-02 01:05:24 +00001335 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001336
Sam Clegg6c899ba2018-02-23 05:08:34 +00001337 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001338 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1339 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001340 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001341 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001342
Sam Cleggfe6414b2017-06-21 23:46:41 +00001343 if (!WS.getSize())
1344 report_fatal_error("data symbols must have a size set with .size: " +
1345 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001346
Sam Cleggfe6414b2017-06-21 23:46:41 +00001347 int64_t Size = 0;
1348 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1349 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001350
Sam Clegg759631c2017-09-15 20:54:59 +00001351 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001352 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001353
Sam Clegg6c899ba2018-02-23 05:08:34 +00001354 // For each data symbol, export it in the symtab as a reference to the
1355 // corresponding Wasm data segment.
1356 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1357 DataSection.getSegmentIndex(),
1358 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1359 static_cast<uint32_t>(Size)};
1360 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001361 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001362
Sam Clegga165f2d2018-04-30 19:40:57 +00001363 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001364 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001365 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001366 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001367
Eric Christopher545932b2018-02-23 21:14:47 +00001368 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001369 LLVM_DEBUG(dbgs() << " -> global index: "
1370 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001371
1372 } else if (WS.isEvent()) {
1373 // C++ exception symbol (__cpp_exception)
1374 unsigned Index;
1375 if (WS.isDefined()) {
1376 Index = NumEventImports + Events.size();
1377 wasm::WasmEventType Event;
1378 Event.SigIndex = getEventType(WS);
1379 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
Sam Clegg492f7522019-03-26 19:46:15 +00001380 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001381 WasmIndices[&WS] = Index;
1382 Events.push_back(Event);
1383 } else {
1384 // An import; the index was assigned above.
Sam Clegg492f7522019-03-26 19:46:15 +00001385 assert(WasmIndices.count(&WS) > 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001386 }
1387 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1388 << "\n");
1389
Sam Clegga165f2d2018-04-30 19:40:57 +00001390 } else {
1391 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001392 }
1393 }
1394
Nicholas Wilson586320c2018-02-28 17:19:48 +00001395 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1396 // process these in a separate pass because we need to have processed the
1397 // target of the alias before the alias itself and the symbols are not
1398 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001399 for (const MCSymbol &S : Asm.symbols()) {
1400 if (!S.isVariable())
1401 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001402
Sam Cleggcd65f692018-01-11 23:59:16 +00001403 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001404
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001405 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001406 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001407 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001408 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1409 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001410
Sam Cleggffba00b2019-02-22 21:41:42 +00001411 if (ResolvedSym->isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001412 assert(WasmIndices.count(ResolvedSym) > 0);
1413 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
Sam Clegg492f7522019-03-26 19:46:15 +00001414 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001415 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001416 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggffba00b2019-02-22 21:41:42 +00001417 } else if (ResolvedSym->isData()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001418 assert(DataLocations.count(ResolvedSym) > 0);
1419 const wasm::WasmDataReference &Ref =
1420 DataLocations.find(ResolvedSym)->second;
1421 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001422 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001423 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001424 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001425 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001426 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001427
Nicholas Wilson586320c2018-02-28 17:19:48 +00001428 // Finally, populate the symbol table itself, in its "natural" order.
1429 for (const MCSymbol &S : Asm.symbols()) {
1430 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001431 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001432 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001433 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001434 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001435 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001436
1437 uint32_t Flags = 0;
1438 if (WS.isWeak())
1439 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1440 if (WS.isHidden())
1441 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1442 if (!WS.isExternal() && WS.isDefined())
1443 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1444 if (WS.isUndefined())
1445 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001446 if (WS.isExported())
1447 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Dan Gohman29874ce2019-02-07 22:03:32 +00001448 if (WS.getName() != WS.getImportName())
1449 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001450
1451 wasm::WasmSymbolInfo Info;
1452 Info.Name = WS.getName();
1453 Info.Kind = WS.getType();
1454 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001455 if (!WS.isData()) {
1456 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001457 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001458 } else if (WS.isDefined()) {
1459 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001460 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001461 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001462 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001463 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001464 }
1465
Sam Clegg6006e092017-12-22 20:31:39 +00001466 {
1467 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001468 // Functions referenced by a relocation need to put in the table. This is
1469 // purely to make the object file's provisional values readable, and is
1470 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001471 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1472 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001473 return;
1474 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001475 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001476 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001477 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001478 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001479 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1480 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001481 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001482 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001483 }
1484 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001485
Sam Clegg6006e092017-12-22 20:31:39 +00001486 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1487 HandleReloc(RelEntry);
1488 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1489 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001490 }
1491
Sam Cleggbafe6902017-12-15 00:17:10 +00001492 // Translate .init_array section contents into start functions.
1493 for (const MCSection &S : Asm) {
1494 const auto &WS = static_cast<const MCSectionWasm &>(S);
1495 if (WS.getSectionName().startswith(".fini_array"))
1496 report_fatal_error(".fini_array sections are unsupported");
1497 if (!WS.getSectionName().startswith(".init_array"))
1498 continue;
1499 if (WS.getFragmentList().empty())
1500 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001501
1502 // init_array is expected to contain a single non-empty data fragment
1503 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001504 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001505
1506 auto IT = WS.begin();
1507 const MCFragment &EmptyFrag = *IT;
1508 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1509 report_fatal_error(".init_array section should be aligned");
1510
1511 IT = std::next(IT);
1512 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001513 if (AlignFrag.getKind() != MCFragment::FT_Align)
1514 report_fatal_error(".init_array section should be aligned");
1515 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1516 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001517
1518 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001519 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1520 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001521
Sam Cleggbafe6902017-12-15 00:17:10 +00001522 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001523 unsigned PrefixLength = strlen(".init_array");
1524 if (WS.getSectionName().size() > PrefixLength) {
1525 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001526 report_fatal_error(
1527 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001528 if (WS.getSectionName()
1529 .substr(PrefixLength + 1)
1530 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001531 report_fatal_error("invalid .init_array section priority");
1532 }
1533 const auto &DataFrag = cast<MCDataFragment>(Frag);
1534 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001535 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001536 P = (const uint8_t *)Contents.data(),
1537 *End = (const uint8_t *)Contents.data() + Contents.size();
1538 P != End; ++P) {
1539 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001540 report_fatal_error("non-symbolic data in .init_array section");
1541 }
1542 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001543 assert(Fixup.getKind() ==
1544 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001545 const MCExpr *Expr = Fixup.getValue();
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001546 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1547 if (!SymRef)
Sam Cleggbafe6902017-12-15 00:17:10 +00001548 report_fatal_error("fixups in .init_array should be symbol references");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001549 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1550 if (TargetSym.getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001551 report_fatal_error("symbols in .init_array should exist in symbtab");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001552 if (!TargetSym.isFunction())
1553 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001554 InitFuncs.push_back(
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001555 std::make_pair(Priority, TargetSym.getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001556 }
1557 }
1558
Dan Gohman18eafb62017-02-22 01:23:18 +00001559 // Write out the Wasm header.
1560 writeHeader(Asm);
1561
Heejin Ahnda419bd2018-11-14 02:46:21 +00001562 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001563 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001564 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001565 // Skip the "table" section; we import the table instead.
1566 // Skip the "memory" section; we import the memory instead.
Heejin Ahnda419bd2018-11-14 02:46:21 +00001567 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001568 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001569 writeElemSection(TableElems);
Thomas Livelyfef8de62019-04-12 22:27:48 +00001570 writeDataCountSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001571 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001572 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001573 for (auto &CustomSection : CustomSections)
1574 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001575 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001576 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1577 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001578 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001579 if (ProducersSection)
1580 writeCustomSection(*ProducersSection, Asm, Layout);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001581 if (TargetFeaturesSection)
1582 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001583
Dan Gohmand934cb82017-02-24 23:18:00 +00001584 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001585 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001586}
1587
Lang Hames60fbc7c2017-10-10 16:28:07 +00001588std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001589llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1590 raw_pwrite_stream &OS) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001591 return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001592}