blob: c1ff3cc2480cdfd70524d6fa4ac62cc3d5f7a94b [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 Gohmanda84b682019-08-29 22:40:00 +0000261 bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
Dan Gohman18eafb62017-02-22 01:23:18 +0000262
Sam Clegg2322a932018-04-23 19:16:19 +0000263 void startSection(SectionBookkeeping &Section, unsigned SectionId);
264 void startCustomSection(SectionBookkeeping &Section, StringRef Name);
Dan Gohmand934cb82017-02-24 23:18:00 +0000265 void endSection(SectionBookkeeping &Section);
266
Dan Gohman18eafb62017-02-22 01:23:18 +0000267public:
Lang Hames1301a872017-10-10 01:15:10 +0000268 WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
269 raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000270 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
Dan Gohman18eafb62017-02-22 01:23:18 +0000271
Dan Gohman0917c9e2018-01-15 17:06:23 +0000272private:
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000273 void reset() override {
274 CodeRelocations.clear();
275 DataRelocations.clear();
276 TypeIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000277 WasmIndices.clear();
Sam Clegg492f7522019-03-26 19:46:15 +0000278 GOTIndices.clear();
Sam Cleggf9edbe92018-01-31 19:28:47 +0000279 TableIndices.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000280 DataLocations.clear();
Thomas Livelycbda16e2019-01-17 02:29:55 +0000281 CustomSections.clear();
282 ProducersSection.reset();
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000283 TargetFeaturesSection.reset();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000284 CustomSectionsRelocations.clear();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000285 SignatureIndices.clear();
286 Signatures.clear();
Sam Clegg6c899ba2018-02-23 05:08:34 +0000287 DataSegments.clear();
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000288 SectionFunctions.clear();
Sam Clegg9f3fe422018-01-17 19:28:43 +0000289 NumFunctionImports = 0;
Sam Clegg7c395942017-09-14 23:07:53 +0000290 NumGlobalImports = 0;
Sam Clegg105bdc22018-05-30 02:57:20 +0000291 MCObjectWriter::reset();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000292 }
293
Dan Gohman18eafb62017-02-22 01:23:18 +0000294 void writeHeader(const MCAssembler &Asm);
295
296 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
297 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000298 MCValue Target, uint64_t &FixedValue) override;
Dan Gohman18eafb62017-02-22 01:23:18 +0000299
300 void executePostLayoutBinding(MCAssembler &Asm,
301 const MCAsmLayout &Layout) override;
302
Peter Collingbourne438390f2018-05-21 18:23:50 +0000303 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Sam Clegg9e15f352017-06-03 02:01:24 +0000304
Sam Cleggb7787fd2017-06-20 04:04:59 +0000305 void writeString(const StringRef Str) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000306 encodeULEB128(Str.size(), W.OS);
307 W.OS << Str;
Sam Cleggb7787fd2017-06-20 04:04:59 +0000308 }
309
Heejin Ahnf208f632018-09-05 01:27:38 +0000310 void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
Sam Clegg9e15f352017-06-03 02:01:24 +0000311
Heejin Ahnda419bd2018-11-14 02:46:21 +0000312 void writeTypeSection(ArrayRef<WasmSignature> Signatures);
Sam Clegg8defa952018-02-12 22:41:29 +0000313 void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
Sam Cleggf950b242017-12-11 23:03:38 +0000314 uint32_t NumElements);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000315 void writeFunctionSection(ArrayRef<WasmFunction> Functions);
Sam Clegg8defa952018-02-12 22:41:29 +0000316 void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
Sam Clegg457fb0b2017-09-15 19:50:44 +0000317 void writeElemSection(ArrayRef<uint32_t> TableElems);
Thomas Livelyfef8de62019-04-12 22:27:48 +0000318 void writeDataCountSection();
Sam Clegg9e15f352017-06-03 02:01:24 +0000319 void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
Sam Clegg457fb0b2017-09-15 19:50:44 +0000320 ArrayRef<WasmFunction> Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000321 void writeDataSection();
Heejin Ahnda419bd2018-11-14 02:46:21 +0000322 void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
Sam Clegg6f08c842018-04-24 18:11:36 +0000323 void writeRelocSection(uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000324 std::vector<WasmRelocationEntry> &Relocations);
Sam Clegg31a2c802017-09-20 21:17:04 +0000325 void writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000326 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000327 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000328 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
Thomas Livelycbda16e2019-01-17 02:29:55 +0000329 void writeCustomSection(WasmCustomSection &CustomSection,
330 const MCAssembler &Asm, const MCAsmLayout &Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000331 void writeCustomRelocSections();
332 void
333 updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
334 const MCAsmLayout &Layout);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000335
Sam Clegg7c395942017-09-14 23:07:53 +0000336 uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000337 void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
338 uint64_t ContentsOffset);
339
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000340 uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
Sam Clegg6f08c842018-04-24 18:11:36 +0000341 uint32_t getFunctionType(const MCSymbolWasm &Symbol);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000342 uint32_t getEventType(const MCSymbolWasm &Symbol);
Heejin Ahn38b12f52018-11-20 00:38:10 +0000343 void registerFunctionType(const MCSymbolWasm &Symbol);
344 void registerEventType(const MCSymbolWasm &Symbol);
Dan Gohman18eafb62017-02-22 01:23:18 +0000345};
Sam Clegg9e15f352017-06-03 02:01:24 +0000346
Dan Gohman18eafb62017-02-22 01:23:18 +0000347} // end anonymous namespace
348
Dan Gohmand934cb82017-02-24 23:18:00 +0000349// Write out a section header and a patchable section size field.
350void WasmObjectWriter::startSection(SectionBookkeeping &Section,
Sam Clegg2322a932018-04-23 19:16:19 +0000351 unsigned SectionId) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000352 LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000353 W.OS << char(SectionId);
Dan Gohmand934cb82017-02-24 23:18:00 +0000354
Peter Collingbournef17b1492018-05-21 18:17:42 +0000355 Section.SizeOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000356
357 // The section size. We don't know the size yet, so reserve enough space
358 // for any 32-bit value; we'll patch it later.
Sam Clegg19e8bef2019-01-30 22:47:35 +0000359 encodeULEB128(0, W.OS, 5);
Dan Gohmand934cb82017-02-24 23:18:00 +0000360
361 // The position where the section starts, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000362 Section.ContentsOffset = W.OS.tell();
363 Section.PayloadOffset = W.OS.tell();
Sam Clegg6f08c842018-04-24 18:11:36 +0000364 Section.Index = SectionCount++;
Sam Clegg2322a932018-04-23 19:16:19 +0000365}
Dan Gohmand934cb82017-02-24 23:18:00 +0000366
Sam Clegg2322a932018-04-23 19:16:19 +0000367void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
368 StringRef Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000369 LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
Sam Clegg2322a932018-04-23 19:16:19 +0000370 startSection(Section, wasm::WASM_SEC_CUSTOM);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000371
372 // The position where the section header ends, for measuring its size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000373 Section.PayloadOffset = W.OS.tell();
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000374
Dan Gohmand934cb82017-02-24 23:18:00 +0000375 // Custom sections in wasm also have a string identifier.
Sam Clegg2322a932018-04-23 19:16:19 +0000376 writeString(Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000377
378 // The position where the custom section starts.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000379 Section.ContentsOffset = W.OS.tell();
Dan Gohmand934cb82017-02-24 23:18:00 +0000380}
381
382// Now that the section is complete and we know how big it is, patch up the
383// section size field at the start of the section.
384void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
Sam Cleggc0affde2019-01-31 22:38:22 +0000385 uint64_t Size = W.OS.tell();
386 // /dev/null doesn't support seek/tell and can report offset of 0.
387 // Simply skip this patching in that case.
388 if (!Size)
389 return;
390
391 Size -= Section.PayloadOffset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000392 if (uint32_t(Size) != Size)
393 report_fatal_error("section size does not fit in a uint32_t");
394
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000395 LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000396
397 // Write the final section size to the payload_len field, which follows
398 // the section id byte.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000399 writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
Sam Clegg19e8bef2019-01-30 22:47:35 +0000400 Section.SizeOffset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000401}
402
Dan Gohman18eafb62017-02-22 01:23:18 +0000403// Emit the Wasm header.
404void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000405 W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
406 W.write<uint32_t>(wasm::WasmVersion);
Dan Gohman18eafb62017-02-22 01:23:18 +0000407}
408
409void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
410 const MCAsmLayout &Layout) {
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000411 // Build a map of sections to the function that defines them, for use
412 // in recordRelocation.
413 for (const MCSymbol &S : Asm.symbols()) {
414 const auto &WS = static_cast<const MCSymbolWasm &>(S);
415 if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
416 const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
417 auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
418 if (!Pair.second)
419 report_fatal_error("section already has a defining function: " +
420 Sec.getSectionName());
421 }
422 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000423}
424
425void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
426 const MCAsmLayout &Layout,
427 const MCFragment *Fragment,
428 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000429 uint64_t &FixedValue) {
Sam Cleggecc5e802019-08-20 00:33:50 +0000430 // The WebAssembly backend should never generate FKF_IsPCRel fixups
Fangrui Songe828ce12019-08-20 02:02:57 +0000431 assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
Sam Cleggecc5e802019-08-20 00:33:50 +0000432 MCFixupKindInfo::FKF_IsPCRel));
433
Sam Cleggfe6414b2017-06-21 23:46:41 +0000434 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000435 uint64_t C = Target.getConstant();
436 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
437 MCContext &Ctx = Asm.getContext();
438
Sam Cleggbafe6902017-12-15 00:17:10 +0000439 // The .init_array isn't translated as data, so don't do relocations in it.
440 if (FixupSection.getSectionName().startswith(".init_array"))
441 return;
442
Dan Gohmand934cb82017-02-24 23:18:00 +0000443 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
Sam Cleggecc5e802019-08-20 00:33:50 +0000444 // To get here the A - B expression must have failed evaluateAsRelocatable.
445 // This means either A or B must be undefined and in WebAssembly we can't
446 // support either of those cases.
Dan Gohmand934cb82017-02-24 23:18:00 +0000447 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
Sam Cleggecc5e802019-08-20 00:33:50 +0000448 Ctx.reportError(
449 Fixup.getLoc(),
450 Twine("symbol '") + SymB.getName() +
451 "': unsupported subtraction expression used in relocation.");
452 return;
Dan Gohmand934cb82017-02-24 23:18:00 +0000453 }
454
455 // We either rejected the fixup or folded B into C at this point.
456 const MCSymbolRefExpr *RefA = Target.getSymA();
Sam Cleggecc5e802019-08-20 00:33:50 +0000457 const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
Dan Gohmand934cb82017-02-24 23:18:00 +0000458
Sam Cleggecc5e802019-08-20 00:33:50 +0000459 if (SymA->isVariable()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000460 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000461 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
462 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
463 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000464 }
465
466 // Put any constant offset in an addend. Offsets can be negative, and
467 // LLVM expects wrapping, in contrast to wasm's immediates which can't
468 // be negative and don't wrap.
469 FixedValue = 0;
470
Sam Clegga5e175c2019-03-28 02:07:28 +0000471 unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000472
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000473 // Absolute offset within a section or a function.
474 // Currently only supported for for metadata sections.
475 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000476 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
477 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000478 if (!FixupSection.getKind().isMetadata())
479 report_fatal_error("relocations for function or section offsets are "
480 "only supported in metadata sections");
481
482 const MCSymbol *SectionSymbol = nullptr;
483 const MCSection &SecA = SymA->getSection();
484 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000485 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000486 else
487 SectionSymbol = SecA.getBeginSymbol();
488 if (!SectionSymbol)
489 report_fatal_error("section symbol is required for relocation");
490
491 C += Layout.getSymbolOffset(*SymA);
492 SymA = cast<MCSymbolWasm>(SectionSymbol);
493 }
494
Sam Cleggd1152a22019-02-04 17:28:46 +0000495 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000496 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000497 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000498 if (SymA->getName().empty())
499 report_fatal_error("relocations against un-named temporaries are not yet "
500 "supported by wasm");
501
502 SymA->setUsedInReloc();
503 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000504
Sam Clegg492f7522019-03-26 19:46:15 +0000505 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
506 SymA->setUsedInGOT();
507
Dan Gohmand934cb82017-02-24 23:18:00 +0000508 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000509 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000510
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000511 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000512 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000513 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000514 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000515 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000516 CustomSectionsRelocations[&FixupSection].push_back(Rec);
517 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000518 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000519 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000520}
521
Heejin Ahn18c56a02019-02-04 19:13:39 +0000522static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggffba00b2019-02-22 21:41:42 +0000523 const MCSymbolWasm* Ret = &Symbol;
524 while (Ret->isVariable()) {
525 const MCExpr *Expr = Ret->getVariableValue();
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000526 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Cleggffba00b2019-02-22 21:41:42 +0000527 Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000528 }
Sam Cleggffba00b2019-02-22 21:41:42 +0000529 return Ret;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000530}
531
Dan Gohmand934cb82017-02-24 23:18:00 +0000532// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000533// by RelEntry. This value isn't used by the static linker; it just serves
534// to make the object format more readable and more likely to be directly
535// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000536uint32_t
537WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg492f7522019-03-26 19:46:15 +0000538 if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
539 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
540 return GOTIndices[RelEntry.Symbol];
541 }
542
Sam Clegg60ec3032018-01-23 01:23:17 +0000543 switch (RelEntry.Type) {
Sam Clegg2a7cac92019-04-04 17:43:50 +0000544 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000545 case wasm::R_WASM_TABLE_INDEX_SLEB:
546 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000547 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000548 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000549 assert(Sym->isFunction());
550 return TableIndices[Sym];
551 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000552 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000553 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000554 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000555 case wasm::R_WASM_FUNCTION_INDEX_LEB:
556 case wasm::R_WASM_GLOBAL_INDEX_LEB:
557 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000558 // Provisional value is function/global/event Wasm index
Sam Clegg492f7522019-03-26 19:46:15 +0000559 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
Sam Clegg6c899ba2018-02-23 05:08:34 +0000560 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000561 case wasm::R_WASM_FUNCTION_OFFSET_I32:
562 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000563 const auto &Section =
564 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
565 return Section.getSectionOffset() + RelEntry.Addend;
566 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000567 case wasm::R_WASM_MEMORY_ADDR_LEB:
568 case wasm::R_WASM_MEMORY_ADDR_I32:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000569 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000570 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000571 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000572 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000573 // For undefined symbols, use zero
574 if (!Sym->isDefined())
575 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000576 const wasm::WasmDataReference &Ref = DataLocations[Sym];
577 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000578 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000579 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000580 }
581 default:
582 llvm_unreachable("invalid relocation type");
583 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000584}
585
Sam Clegg759631c2017-09-15 20:54:59 +0000586static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000587 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000588 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000589
Sam Clegg63ebb812017-09-29 16:50:08 +0000590 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
591
Sam Clegg759631c2017-09-15 20:54:59 +0000592 for (const MCFragment &Frag : DataSection) {
593 if (Frag.hasInstructions())
594 report_fatal_error("only data supported in data sections");
595
596 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
597 if (Align->getValueSize() != 1)
598 report_fatal_error("only byte values supported for alignment");
599 // If nops are requested, use zeros, as this is the data section.
600 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000601 uint64_t Size =
602 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
603 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000604 DataBytes.resize(Size, Value);
605 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000606 int64_t NumValues;
607 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000608 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000609 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
610 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000611 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
612 const SmallVectorImpl<char> &Contents = LEB->getContents();
613 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000614 } else {
615 const auto &DataFrag = cast<MCDataFragment>(Frag);
616 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000617 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
618 }
619 }
620
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000621 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000622}
623
Sam Clegg60ec3032018-01-23 01:23:17 +0000624uint32_t
625WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000626 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000627 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000628 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000629 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000630 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000631 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000632
Sam Clegg25d8e682018-05-08 00:08:21 +0000633 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000634}
635
Dan Gohmand934cb82017-02-24 23:18:00 +0000636// Apply the portions of the relocation records that we can handle ourselves
637// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000638void WasmObjectWriter::applyRelocations(
639 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000640 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000641 for (const WasmRelocationEntry &RelEntry : Relocations) {
642 uint64_t Offset = ContentsOffset +
643 RelEntry.FixupSection->getSectionOffset() +
644 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000645
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000646 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000647 uint32_t Value = getProvisionalValue(RelEntry);
648
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000649 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000650 case wasm::R_WASM_FUNCTION_INDEX_LEB:
651 case wasm::R_WASM_TYPE_INDEX_LEB:
652 case wasm::R_WASM_GLOBAL_INDEX_LEB:
653 case wasm::R_WASM_MEMORY_ADDR_LEB:
654 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000655 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000656 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000657 case wasm::R_WASM_TABLE_INDEX_I32:
658 case wasm::R_WASM_MEMORY_ADDR_I32:
659 case wasm::R_WASM_FUNCTION_OFFSET_I32:
660 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000661 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000662 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000663 case wasm::R_WASM_TABLE_INDEX_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000664 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000665 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000666 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000667 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000668 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000669 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000670 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000671 }
672 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000673}
674
Heejin Ahnda419bd2018-11-14 02:46:21 +0000675void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
676 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000677 return;
678
679 SectionBookkeeping Section;
680 startSection(Section, wasm::WASM_SEC_TYPE);
681
Heejin Ahnda419bd2018-11-14 02:46:21 +0000682 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000683
Heejin Ahnda419bd2018-11-14 02:46:21 +0000684 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000685 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000686 encodeULEB128(Sig.Params.size(), W.OS);
687 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000688 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000689 encodeULEB128(Sig.Returns.size(), W.OS);
690 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000691 writeValueType(Ty);
692 }
693
694 endSection(Section);
695}
696
Sam Clegg8defa952018-02-12 22:41:29 +0000697void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000698 uint32_t DataSize,
699 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000700 if (Imports.empty())
701 return;
702
Sam Cleggf950b242017-12-11 23:03:38 +0000703 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
704
Sam Clegg9e15f352017-06-03 02:01:24 +0000705 SectionBookkeeping Section;
706 startSection(Section, wasm::WASM_SEC_IMPORT);
707
Peter Collingbournef17b1492018-05-21 18:17:42 +0000708 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000709 for (const wasm::WasmImport &Import : Imports) {
710 writeString(Import.Module);
711 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000712 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000713
714 switch (Import.Kind) {
715 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000716 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000717 break;
718 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000719 W.OS << char(Import.Global.Type);
720 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000721 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000722 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000723 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000724 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000725 break;
726 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000727 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000728 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000729 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000730 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000731 case wasm::WASM_EXTERNAL_EVENT:
732 encodeULEB128(Import.Event.Attribute, W.OS);
733 encodeULEB128(Import.Event.SigIndex, W.OS);
734 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000735 default:
736 llvm_unreachable("unsupported import kind");
737 }
738 }
739
740 endSection(Section);
741}
742
Sam Clegg457fb0b2017-09-15 19:50:44 +0000743void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000744 if (Functions.empty())
745 return;
746
747 SectionBookkeeping Section;
748 startSection(Section, wasm::WASM_SEC_FUNCTION);
749
Peter Collingbournef17b1492018-05-21 18:17:42 +0000750 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000751 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000752 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000753
754 endSection(Section);
755}
756
Heejin Ahnda419bd2018-11-14 02:46:21 +0000757void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
758 if (Events.empty())
759 return;
760
761 SectionBookkeeping Section;
762 startSection(Section, wasm::WASM_SEC_EVENT);
763
764 encodeULEB128(Events.size(), W.OS);
765 for (const wasm::WasmEventType &Event : Events) {
766 encodeULEB128(Event.Attribute, W.OS);
767 encodeULEB128(Event.SigIndex, W.OS);
768 }
769
770 endSection(Section);
771}
772
Sam Clegg8defa952018-02-12 22:41:29 +0000773void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000774 if (Exports.empty())
775 return;
776
777 SectionBookkeeping Section;
778 startSection(Section, wasm::WASM_SEC_EXPORT);
779
Peter Collingbournef17b1492018-05-21 18:17:42 +0000780 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000781 for (const wasm::WasmExport &Export : Exports) {
782 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000783 W.OS << char(Export.Kind);
784 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000785 }
786
787 endSection(Section);
788}
789
Sam Clegg457fb0b2017-09-15 19:50:44 +0000790void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000791 if (TableElems.empty())
792 return;
793
794 SectionBookkeeping Section;
795 startSection(Section, wasm::WASM_SEC_ELEM);
796
Peter Collingbournef17b1492018-05-21 18:17:42 +0000797 encodeULEB128(1, W.OS); // number of "segments"
798 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000799
800 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000801 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000802 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000803 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000804
Peter Collingbournef17b1492018-05-21 18:17:42 +0000805 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000806 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000807 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000808
809 endSection(Section);
810}
811
Thomas Livelyfef8de62019-04-12 22:27:48 +0000812void WasmObjectWriter::writeDataCountSection() {
813 if (DataSegments.empty())
814 return;
815
816 SectionBookkeeping Section;
817 startSection(Section, wasm::WASM_SEC_DATACOUNT);
818 encodeULEB128(DataSegments.size(), W.OS);
819 endSection(Section);
820}
821
Sam Clegg457fb0b2017-09-15 19:50:44 +0000822void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
823 const MCAsmLayout &Layout,
824 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000825 if (Functions.empty())
826 return;
827
828 SectionBookkeeping Section;
829 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000830 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000831
Peter Collingbournef17b1492018-05-21 18:17:42 +0000832 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
834 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000835 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000836
Sam Clegg9e15f352017-06-03 02:01:24 +0000837 int64_t Size = 0;
838 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
839 report_fatal_error(".size expression must be evaluatable");
840
Peter Collingbournef17b1492018-05-21 18:17:42 +0000841 encodeULEB128(Size, W.OS);
842 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
843 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000844 }
845
Sam Clegg9e15f352017-06-03 02:01:24 +0000846 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000847 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000848
849 endSection(Section);
850}
851
Sam Clegg6c899ba2018-02-23 05:08:34 +0000852void WasmObjectWriter::writeDataSection() {
853 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000854 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000855
856 SectionBookkeeping Section;
857 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000858 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000859
Peter Collingbournef17b1492018-05-21 18:17:42 +0000860 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000861
Sam Clegg6c899ba2018-02-23 05:08:34 +0000862 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000863 encodeULEB128(Segment.InitFlags, W.OS); // flags
864 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
865 encodeULEB128(0, W.OS); // memory index
866 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
867 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
868 encodeSLEB128(Segment.Offset, W.OS); // offset
869 W.OS << char(wasm::WASM_OPCODE_END);
870 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000871 encodeULEB128(Segment.Data.size(), W.OS); // size
872 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
873 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000874 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000875
876 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000877 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000878
879 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000880}
881
Sam Clegg6f08c842018-04-24 18:11:36 +0000882void WasmObjectWriter::writeRelocSection(
883 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000884 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000885 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
886 // for descriptions of the reloc sections.
887
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000888 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000889 return;
890
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000891 // First, ensure the relocations are sorted in offset order. In general they
892 // should already be sorted since `recordRelocation` is called in offset
893 // order, but for the code section we combine many MC sections into single
894 // wasm section, and this order is determined by the order of Asm.Symbols()
895 // not the sections order.
Fangrui Songefd94c52019-04-23 14:51:27 +0000896 llvm::stable_sort(
897 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000898 return (A.Offset + A.FixupSection->getSectionOffset()) <
899 (B.Offset + B.FixupSection->getSectionOffset());
900 });
901
Sam Clegg9e15f352017-06-03 02:01:24 +0000902 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000903 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000904
Peter Collingbournef17b1492018-05-21 18:17:42 +0000905 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000906 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000907 for (const WasmRelocationEntry &RelEntry : Relocs) {
908 uint64_t Offset =
909 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000910 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000911
Peter Collingbournef17b1492018-05-21 18:17:42 +0000912 W.OS << char(RelEntry.Type);
913 encodeULEB128(Offset, W.OS);
914 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000915 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000916 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000917 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000918
919 endSection(Section);
920}
921
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000922void WasmObjectWriter::writeCustomRelocSections() {
923 for (const auto &Sec : CustomSections) {
924 auto &Relocations = CustomSectionsRelocations[Sec.Section];
925 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
926 }
927}
928
Sam Clegg9e15f352017-06-03 02:01:24 +0000929void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000930 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000931 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000932 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000933 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000934 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000935 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000936
Sam Clegg6bb5a412018-04-26 18:15:32 +0000937 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000938 if (SymbolInfos.size() != 0) {
939 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000940 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000941 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000942 encodeULEB128(Sym.Kind, W.OS);
943 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000944 switch (Sym.Kind) {
945 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
946 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000947 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000948 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000949 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
950 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000951 writeString(Sym.Name);
952 break;
953 case wasm::WASM_SYMBOL_TYPE_DATA:
954 writeString(Sym.Name);
955 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000956 encodeULEB128(Sym.DataRef.Segment, W.OS);
957 encodeULEB128(Sym.DataRef.Offset, W.OS);
958 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000959 }
960 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000961 case wasm::WASM_SYMBOL_TYPE_SECTION: {
962 const uint32_t SectionIndex =
963 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000964 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000965 break;
966 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000967 default:
968 llvm_unreachable("unexpected kind");
969 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000970 }
971 endSection(SubSection);
972 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000973
Sam Clegg6c899ba2018-02-23 05:08:34 +0000974 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +0000975 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000976 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000977 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +0000978 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000979 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +0000980 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +0000981 }
Sam Cleggd95ed952017-09-20 19:03:35 +0000982 endSection(SubSection);
983 }
984
Sam Cleggbafe6902017-12-15 00:17:10 +0000985 if (!InitFuncs.empty()) {
986 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000987 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +0000988 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000989 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +0000990 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +0000991 }
992 endSection(SubSection);
993 }
994
Sam Cleggea7cace2018-01-09 23:43:14 +0000995 if (Comdats.size()) {
996 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000997 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +0000998 for (const auto &C : Comdats) {
999 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001000 encodeULEB128(0, W.OS); // flags for future use
1001 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001002 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001003 encodeULEB128(Entry.Kind, W.OS);
1004 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001005 }
1006 }
1007 endSection(SubSection);
1008 }
1009
Sam Clegg9e15f352017-06-03 02:01:24 +00001010 endSection(Section);
1011}
1012
Thomas Livelycbda16e2019-01-17 02:29:55 +00001013void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1014 const MCAssembler &Asm,
1015 const MCAsmLayout &Layout) {
1016 SectionBookkeeping Section;
1017 auto *Sec = CustomSection.Section;
1018 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001019
Thomas Livelycbda16e2019-01-17 02:29:55 +00001020 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1021 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001022
Thomas Livelycbda16e2019-01-17 02:29:55 +00001023 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1024 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001025
Thomas Livelycbda16e2019-01-17 02:29:55 +00001026 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001027
Thomas Livelycbda16e2019-01-17 02:29:55 +00001028 // Apply fixups.
1029 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1030 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001031}
1032
Heejin Ahnf208f632018-09-05 01:27:38 +00001033uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001034 assert(Symbol.isFunction());
1035 assert(TypeIndices.count(&Symbol));
1036 return TypeIndices[&Symbol];
1037}
1038
Heejin Ahnda419bd2018-11-14 02:46:21 +00001039uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1040 assert(Symbol.isEvent());
1041 assert(TypeIndices.count(&Symbol));
1042 return TypeIndices[&Symbol];
1043}
1044
Heejin Ahn38b12f52018-11-20 00:38:10 +00001045void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001046 assert(Symbol.isFunction());
1047
Heejin Ahnda419bd2018-11-14 02:46:21 +00001048 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001049 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001050 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001051 S.Returns = Sig->Returns;
1052 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001053 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001054
Heejin Ahnda419bd2018-11-14 02:46:21 +00001055 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001056 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001057 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001058 TypeIndices[&Symbol] = Pair.first->second;
1059
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001060 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1061 << " new:" << Pair.second << "\n");
1062 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001063}
1064
Heejin Ahn38b12f52018-11-20 00:38:10 +00001065void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001066 assert(Symbol.isEvent());
1067
1068 // TODO Currently we don't generate imported exceptions, but if we do, we
1069 // should have a way of infering types of imported exceptions.
1070 WasmSignature S;
1071 if (auto *Sig = Symbol.getSignature()) {
1072 S.Returns = Sig->Returns;
1073 S.Params = Sig->Params;
1074 }
1075
1076 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1077 if (Pair.second)
1078 Signatures.push_back(S);
1079 TypeIndices[&Symbol] = Pair.first->second;
1080
1081 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1082 << "\n");
1083 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001084}
1085
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001086static bool isInSymtab(const MCSymbolWasm &Sym) {
1087 if (Sym.isUsedInReloc())
1088 return true;
1089
1090 if (Sym.isComdat() && !Sym.isDefined())
1091 return false;
1092
1093 if (Sym.isTemporary() && Sym.getName().empty())
1094 return false;
1095
1096 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1097 return false;
1098
1099 if (Sym.isSection())
1100 return false;
1101
1102 return true;
1103}
1104
Peter Collingbourne438390f2018-05-21 18:23:50 +00001105uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1106 const MCAsmLayout &Layout) {
1107 uint64_t StartOffset = W.OS.tell();
1108
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001109 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001110
1111 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001112 SmallVector<WasmFunction, 4> Functions;
1113 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001114 SmallVector<wasm::WasmImport, 4> Imports;
1115 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001116 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001117 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001118 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001119 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001120 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001121
Sam Cleggf950b242017-12-11 23:03:38 +00001122 // For now, always emit the memory import, since loads and stores are not
1123 // valid without it. In the future, we could perhaps be more clever and omit
1124 // it if there are no loads or stores.
Sam Clegg8defa952018-02-12 22:41:29 +00001125 wasm::WasmImport MemImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001126 MemImport.Module = "env";
1127 MemImport.Field = "__linear_memory";
Sam Cleggf950b242017-12-11 23:03:38 +00001128 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1129 Imports.push_back(MemImport);
1130
1131 // For now, always emit the table section, since indirect calls are not
1132 // valid without it. In the future, we could perhaps be more clever and omit
1133 // it if there are no indirect calls.
Sam Clegg8defa952018-02-12 22:41:29 +00001134 wasm::WasmImport TableImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001135 TableImport.Module = "env";
1136 TableImport.Field = "__indirect_function_table";
Sam Cleggf950b242017-12-11 23:03:38 +00001137 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001138 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001139 Imports.push_back(TableImport);
1140
Heejin Ahnda419bd2018-11-14 02:46:21 +00001141 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001142 // symbols. This must be done before populating WasmIndices for defined
1143 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001144 for (const MCSymbol &S : Asm.symbols()) {
1145 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1146
1147 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001148 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001149 if (WS.isFunction())
1150 registerFunctionType(WS);
1151
Heejin Ahnda419bd2018-11-14 02:46:21 +00001152 if (WS.isEvent())
1153 registerEventType(WS);
1154
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001155 if (WS.isTemporary())
1156 continue;
1157
1158 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001159 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001160 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001161 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001162 Import.Module = WS.getImportModule();
1163 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001164 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001165 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001166 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001167 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001168 WasmIndices[&WS] = NumFunctionImports++;
1169 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001170 if (WS.isWeak())
1171 report_fatal_error("undefined global symbol cannot be weak");
1172
Sam Clegg6c899ba2018-02-23 05:08:34 +00001173 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001174 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001175 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg492f7522019-03-26 19:46:15 +00001176 Import.Module = WS.getImportModule();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001177 Import.Global = WS.getGlobalType();
1178 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001179 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001180 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001181 } else if (WS.isEvent()) {
1182 if (WS.isWeak())
1183 report_fatal_error("undefined event symbol cannot be weak");
1184
1185 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001186 Import.Module = WS.getImportModule();
1187 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001188 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1189 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1190 Import.Event.SigIndex = getEventType(WS);
1191 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001192 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001193 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001194 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001195 }
1196 }
1197
Sam Clegg492f7522019-03-26 19:46:15 +00001198 // Add imports for GOT globals
1199 for (const MCSymbol &S : Asm.symbols()) {
1200 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1201 if (WS.isUsedInGOT()) {
1202 wasm::WasmImport Import;
1203 if (WS.isFunction())
1204 Import.Module = "GOT.func";
1205 else
1206 Import.Module = "GOT.mem";
1207 Import.Field = WS.getName();
1208 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1209 Import.Global = {wasm::WASM_TYPE_I32, true};
1210 Imports.push_back(Import);
1211 assert(GOTIndices.count(&WS) == 0);
1212 GOTIndices[&WS] = NumGlobalImports++;
1213 }
1214 }
1215
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001216 // Populate DataSegments and CustomSections, which must be done before
1217 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001218 for (MCSection &Sec : Asm) {
1219 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001220 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001221
Sam Cleggbafe6902017-12-15 00:17:10 +00001222 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001223 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001224 continue;
1225
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001226 // Code is handled separately
1227 if (Section.getKind().isText())
1228 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001229
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001230 if (Section.isWasmData()) {
1231 uint32_t SegmentIndex = DataSegments.size();
1232 DataSize = alignTo(DataSize, Section.getAlignment());
1233 DataSegments.emplace_back();
1234 WasmDataSegment &Segment = DataSegments.back();
1235 Segment.Name = SectionName;
Simon Pilgrim9b49f362019-02-24 13:31:52 +00001236 Segment.InitFlags =
1237 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001238 Segment.Offset = DataSize;
1239 Segment.Section = &Section;
1240 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001241 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001242 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001243 DataSize += Segment.Data.size();
1244 Section.setSegmentIndex(SegmentIndex);
1245
1246 if (const MCSymbolWasm *C = Section.getGroup()) {
1247 Comdats[C->getName()].emplace_back(
1248 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1249 }
1250 } else {
1251 // Create custom sections
1252 assert(Sec.getKind().isMetadata());
1253
1254 StringRef Name = SectionName;
1255
1256 // For user-defined custom sections, strip the prefix
1257 if (Name.startswith(".custom_section."))
1258 Name = Name.substr(strlen(".custom_section."));
1259
Heejin Ahnf208f632018-09-05 01:27:38 +00001260 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001261 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001262 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001263 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001264 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001265 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001266 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001267
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001268 // Separate out the producers and target features sections
Thomas Livelycbda16e2019-01-17 02:29:55 +00001269 if (Name == "producers") {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001270 ProducersSection = std::make_unique<WasmCustomSection>(Name, &Section);
Thomas Livelycbda16e2019-01-17 02:29:55 +00001271 continue;
1272 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001273 if (Name == "target_features") {
1274 TargetFeaturesSection =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001275 std::make_unique<WasmCustomSection>(Name, &Section);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001276 continue;
1277 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001278
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001279 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001280 }
Sam Clegg759631c2017-09-15 20:54:59 +00001281 }
1282
Nicholas Wilson586320c2018-02-28 17:19:48 +00001283 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001284 for (const MCSymbol &S : Asm.symbols()) {
1285 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1286 // or used in relocations.
1287 if (S.isTemporary() && S.getName().empty())
1288 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001289
Dan Gohmand934cb82017-02-24 23:18:00 +00001290 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001291 LLVM_DEBUG(
1292 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1293 << " isDefined=" << S.isDefined() << " isExternal="
1294 << S.isExternal() << " isTemporary=" << S.isTemporary()
1295 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1296 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001297
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001298 if (WS.isVariable())
1299 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001300 if (WS.isComdat() && !WS.isDefined())
1301 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001302
Dan Gohmand934cb82017-02-24 23:18:00 +00001303 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001304 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001305 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001306 if (WS.getOffset() != 0)
1307 report_fatal_error(
1308 "function sections must contain one function each");
1309
Heejin Ahn18c56a02019-02-04 19:13:39 +00001310 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001311 report_fatal_error(
1312 "function symbols must have a size set with .size");
1313
Sam Clegg6c899ba2018-02-23 05:08:34 +00001314 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001315 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001316 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001317 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001318 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001319 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001320 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001321
1322 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1323 if (const MCSymbolWasm *C = Section.getGroup()) {
1324 Comdats[C->getName()].emplace_back(
1325 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1326 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001327 } else {
1328 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001329 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001330 }
1331
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001332 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001333
Sam Clegg6c899ba2018-02-23 05:08:34 +00001334 } else if (WS.isData()) {
Wouter van Oortmerssenf3feb6a2019-03-04 17:18:04 +00001335 if (!isInSymtab(WS))
Sam Cleggc38e9472017-06-02 01:05:24 +00001336 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001337
Sam Clegg6c899ba2018-02-23 05:08:34 +00001338 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001339 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1340 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001341 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001342 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001343
Sam Cleggfe6414b2017-06-21 23:46:41 +00001344 if (!WS.getSize())
1345 report_fatal_error("data symbols must have a size set with .size: " +
1346 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001347
Sam Cleggfe6414b2017-06-21 23:46:41 +00001348 int64_t Size = 0;
1349 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1350 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001351
Sam Clegg759631c2017-09-15 20:54:59 +00001352 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Clegg079cba02019-09-25 23:33:16 +00001353 if (!DataSection.isWasmData())
1354 report_fatal_error("data symbols must live in a data section: " +
1355 WS.getName());
Sam Clegg7c395942017-09-14 23:07:53 +00001356
Sam Clegg6c899ba2018-02-23 05:08:34 +00001357 // For each data symbol, export it in the symtab as a reference to the
1358 // corresponding Wasm data segment.
1359 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1360 DataSection.getSegmentIndex(),
1361 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1362 static_cast<uint32_t>(Size)};
1363 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001364 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001365
Sam Clegga165f2d2018-04-30 19:40:57 +00001366 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001367 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001368 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001369 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001370
Eric Christopher545932b2018-02-23 21:14:47 +00001371 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001372 LLVM_DEBUG(dbgs() << " -> global index: "
1373 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001374
1375 } else if (WS.isEvent()) {
1376 // C++ exception symbol (__cpp_exception)
1377 unsigned Index;
1378 if (WS.isDefined()) {
1379 Index = NumEventImports + Events.size();
1380 wasm::WasmEventType Event;
1381 Event.SigIndex = getEventType(WS);
1382 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
Sam Clegg492f7522019-03-26 19:46:15 +00001383 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001384 WasmIndices[&WS] = Index;
1385 Events.push_back(Event);
1386 } else {
1387 // An import; the index was assigned above.
Sam Clegg492f7522019-03-26 19:46:15 +00001388 assert(WasmIndices.count(&WS) > 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001389 }
1390 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1391 << "\n");
1392
Sam Clegga165f2d2018-04-30 19:40:57 +00001393 } else {
1394 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001395 }
1396 }
1397
Nicholas Wilson586320c2018-02-28 17:19:48 +00001398 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1399 // process these in a separate pass because we need to have processed the
1400 // target of the alias before the alias itself and the symbols are not
1401 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001402 for (const MCSymbol &S : Asm.symbols()) {
1403 if (!S.isVariable())
1404 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001405
Sam Cleggcd65f692018-01-11 23:59:16 +00001406 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001407
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001408 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001409 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001410 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001411 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1412 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001413
Sam Cleggffba00b2019-02-22 21:41:42 +00001414 if (ResolvedSym->isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001415 assert(WasmIndices.count(ResolvedSym) > 0);
1416 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
Sam Clegg492f7522019-03-26 19:46:15 +00001417 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001418 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001419 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggffba00b2019-02-22 21:41:42 +00001420 } else if (ResolvedSym->isData()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001421 assert(DataLocations.count(ResolvedSym) > 0);
1422 const wasm::WasmDataReference &Ref =
1423 DataLocations.find(ResolvedSym)->second;
1424 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001425 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001426 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001427 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001428 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001429 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001430
Nicholas Wilson586320c2018-02-28 17:19:48 +00001431 // Finally, populate the symbol table itself, in its "natural" order.
1432 for (const MCSymbol &S : Asm.symbols()) {
1433 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001434 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001435 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001436 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001437 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001438 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001439
1440 uint32_t Flags = 0;
1441 if (WS.isWeak())
1442 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1443 if (WS.isHidden())
1444 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1445 if (!WS.isExternal() && WS.isDefined())
1446 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1447 if (WS.isUndefined())
1448 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Dan Gohmanda84b682019-08-29 22:40:00 +00001449 if (WS.isNoStrip()) {
1450 Flags |= wasm::WASM_SYMBOL_NO_STRIP;
1451 if (isEmscripten()) {
1452 Flags |= wasm::WASM_SYMBOL_EXPORTED;
1453 }
1454 }
Dan Gohman29874ce2019-02-07 22:03:32 +00001455 if (WS.getName() != WS.getImportName())
1456 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001457
1458 wasm::WasmSymbolInfo Info;
1459 Info.Name = WS.getName();
1460 Info.Kind = WS.getType();
1461 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001462 if (!WS.isData()) {
1463 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001464 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001465 } else if (WS.isDefined()) {
1466 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001467 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001468 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001469 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001470 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001471 }
1472
Sam Clegg6006e092017-12-22 20:31:39 +00001473 {
1474 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001475 // Functions referenced by a relocation need to put in the table. This is
1476 // purely to make the object file's provisional values readable, and is
1477 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001478 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1479 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001480 return;
1481 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001482 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001483 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001484 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001485 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001486 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1487 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001488 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001489 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001490 }
1491 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001492
Sam Clegg6006e092017-12-22 20:31:39 +00001493 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1494 HandleReloc(RelEntry);
1495 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1496 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001497 }
1498
Sam Cleggbafe6902017-12-15 00:17:10 +00001499 // Translate .init_array section contents into start functions.
1500 for (const MCSection &S : Asm) {
1501 const auto &WS = static_cast<const MCSectionWasm &>(S);
1502 if (WS.getSectionName().startswith(".fini_array"))
1503 report_fatal_error(".fini_array sections are unsupported");
1504 if (!WS.getSectionName().startswith(".init_array"))
1505 continue;
1506 if (WS.getFragmentList().empty())
1507 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001508
1509 // init_array is expected to contain a single non-empty data fragment
1510 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001511 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001512
1513 auto IT = WS.begin();
1514 const MCFragment &EmptyFrag = *IT;
1515 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1516 report_fatal_error(".init_array section should be aligned");
1517
1518 IT = std::next(IT);
1519 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001520 if (AlignFrag.getKind() != MCFragment::FT_Align)
1521 report_fatal_error(".init_array section should be aligned");
1522 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1523 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001524
1525 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001526 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1527 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001528
Sam Cleggbafe6902017-12-15 00:17:10 +00001529 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001530 unsigned PrefixLength = strlen(".init_array");
1531 if (WS.getSectionName().size() > PrefixLength) {
1532 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001533 report_fatal_error(
1534 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001535 if (WS.getSectionName()
1536 .substr(PrefixLength + 1)
1537 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001538 report_fatal_error("invalid .init_array section priority");
1539 }
1540 const auto &DataFrag = cast<MCDataFragment>(Frag);
1541 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001542 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001543 P = (const uint8_t *)Contents.data(),
1544 *End = (const uint8_t *)Contents.data() + Contents.size();
1545 P != End; ++P) {
1546 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001547 report_fatal_error("non-symbolic data in .init_array section");
1548 }
1549 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001550 assert(Fixup.getKind() ==
1551 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001552 const MCExpr *Expr = Fixup.getValue();
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001553 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1554 if (!SymRef)
Sam Cleggbafe6902017-12-15 00:17:10 +00001555 report_fatal_error("fixups in .init_array should be symbol references");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001556 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1557 if (TargetSym.getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001558 report_fatal_error("symbols in .init_array should exist in symbtab");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001559 if (!TargetSym.isFunction())
1560 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001561 InitFuncs.push_back(
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001562 std::make_pair(Priority, TargetSym.getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001563 }
1564 }
1565
Dan Gohman18eafb62017-02-22 01:23:18 +00001566 // Write out the Wasm header.
1567 writeHeader(Asm);
1568
Heejin Ahnda419bd2018-11-14 02:46:21 +00001569 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001570 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001571 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001572 // Skip the "table" section; we import the table instead.
1573 // Skip the "memory" section; we import the memory instead.
Heejin Ahnda419bd2018-11-14 02:46:21 +00001574 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001575 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001576 writeElemSection(TableElems);
Thomas Livelyfef8de62019-04-12 22:27:48 +00001577 writeDataCountSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001578 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001579 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001580 for (auto &CustomSection : CustomSections)
1581 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001582 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001583 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1584 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001585 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001586 if (ProducersSection)
1587 writeCustomSection(*ProducersSection, Asm, Layout);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001588 if (TargetFeaturesSection)
1589 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001590
Dan Gohmand934cb82017-02-24 23:18:00 +00001591 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001592 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001593}
1594
Lang Hames60fbc7c2017-10-10 16:28:07 +00001595std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001596llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1597 raw_pwrite_stream &OS) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001598 return std::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001599}