blob: 8743eb7ee3c92546ed5391aa619d0094e49428a0 [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) {
429 MCAsmBackend &Backend = Asm.getBackend();
430 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
431 MCFixupKindInfo::FKF_IsPCRel;
Sam Cleggfe6414b2017-06-21 23:46:41 +0000432 const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
Dan Gohmand934cb82017-02-24 23:18:00 +0000433 uint64_t C = Target.getConstant();
434 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
435 MCContext &Ctx = Asm.getContext();
436
Sam Cleggbafe6902017-12-15 00:17:10 +0000437 // The .init_array isn't translated as data, so don't do relocations in it.
438 if (FixupSection.getSectionName().startswith(".init_array"))
439 return;
440
Dan Gohmand934cb82017-02-24 23:18:00 +0000441 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
442 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
443 "Should not have constructed this");
444
445 // Let A, B and C being the components of Target and R be the location of
446 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
447 // If it is pcrel, we want to compute (A - B + C - R).
448
449 // In general, Wasm has no relocations for -B. It can only represent (A + C)
450 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
451 // replace B to implement it: (A - R - K + C)
452 if (IsPCRel) {
453 Ctx.reportError(
454 Fixup.getLoc(),
455 "No relocation available to represent this relative expression");
456 return;
457 }
458
459 const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
460
461 if (SymB.isUndefined()) {
462 Ctx.reportError(Fixup.getLoc(),
463 Twine("symbol '") + SymB.getName() +
464 "' can not be undefined in a subtraction expression");
465 return;
466 }
467
468 assert(!SymB.isAbsolute() && "Should have been folded");
469 const MCSection &SecB = SymB.getSection();
470 if (&SecB != &FixupSection) {
471 Ctx.reportError(Fixup.getLoc(),
472 "Cannot represent a difference across sections");
473 return;
474 }
475
476 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
477 uint64_t K = SymBOffset - FixupOffset;
478 IsPCRel = true;
479 C -= K;
480 }
481
482 // We either rejected the fixup or folded B into C at this point.
483 const MCSymbolRefExpr *RefA = Target.getSymA();
484 const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr;
485
Dan Gohmand934cb82017-02-24 23:18:00 +0000486 if (SymA && SymA->isVariable()) {
487 const MCExpr *Expr = SymA->getVariableValue();
Sam Clegg6ad8f192017-07-11 02:21:57 +0000488 const auto *Inner = cast<MCSymbolRefExpr>(Expr);
489 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
490 llvm_unreachable("weakref used in reloc not yet implemented");
Dan Gohmand934cb82017-02-24 23:18:00 +0000491 }
492
493 // Put any constant offset in an addend. Offsets can be negative, and
494 // LLVM expects wrapping, in contrast to wasm's immediates which can't
495 // be negative and don't wrap.
496 FixedValue = 0;
497
Sam Clegga5e175c2019-03-28 02:07:28 +0000498 unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
Sam Cleggae03c1e72017-06-13 18:51:50 +0000499 assert(!IsPCRel);
Sam Clegg9d24fb72017-06-16 23:59:10 +0000500 assert(SymA);
501
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000502 // Absolute offset within a section or a function.
503 // Currently only supported for for metadata sections.
504 // See: test/MC/WebAssembly/blockaddress.ll
Sam Cleggd1152a22019-02-04 17:28:46 +0000505 if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
506 Type == wasm::R_WASM_SECTION_OFFSET_I32) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000507 if (!FixupSection.getKind().isMetadata())
508 report_fatal_error("relocations for function or section offsets are "
509 "only supported in metadata sections");
510
511 const MCSymbol *SectionSymbol = nullptr;
512 const MCSection &SecA = SymA->getSection();
513 if (SecA.getKind().isText())
Sam Clegg6ccb59b2018-05-16 20:09:05 +0000514 SectionSymbol = SectionFunctions.find(&SecA)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000515 else
516 SectionSymbol = SecA.getBeginSymbol();
517 if (!SectionSymbol)
518 report_fatal_error("section symbol is required for relocation");
519
520 C += Layout.getSymbolOffset(*SymA);
521 SymA = cast<MCSymbolWasm>(SectionSymbol);
522 }
523
Sam Cleggd1152a22019-02-04 17:28:46 +0000524 // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000525 // against a named symbol.
Sam Cleggd1152a22019-02-04 17:28:46 +0000526 if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +0000527 if (SymA->getName().empty())
528 report_fatal_error("relocations against un-named temporaries are not yet "
529 "supported by wasm");
530
531 SymA->setUsedInReloc();
532 }
Sam Cleggae03c1e72017-06-13 18:51:50 +0000533
Sam Clegg492f7522019-03-26 19:46:15 +0000534 if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
535 SymA->setUsedInGOT();
536
Dan Gohmand934cb82017-02-24 23:18:00 +0000537 WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000538 LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
Dan Gohmand934cb82017-02-24 23:18:00 +0000539
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000540 if (FixupSection.isWasmData()) {
Dan Gohmand934cb82017-02-24 23:18:00 +0000541 DataRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000542 } else if (FixupSection.getKind().isText()) {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000543 CodeRelocations.push_back(Rec);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000544 } else if (FixupSection.getKind().isMetadata()) {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000545 CustomSectionsRelocations[&FixupSection].push_back(Rec);
546 } else {
Sam Clegg12fd3da2017-10-20 21:28:38 +0000547 llvm_unreachable("unexpected section type");
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000548 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000549}
550
Heejin Ahn18c56a02019-02-04 19:13:39 +0000551static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
Sam Cleggffba00b2019-02-22 21:41:42 +0000552 const MCSymbolWasm* Ret = &Symbol;
553 while (Ret->isVariable()) {
554 const MCExpr *Expr = Ret->getVariableValue();
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000555 auto *Inner = cast<MCSymbolRefExpr>(Expr);
Sam Cleggffba00b2019-02-22 21:41:42 +0000556 Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000557 }
Sam Cleggffba00b2019-02-22 21:41:42 +0000558 return Ret;
Sam Cleggaff1c4d2017-09-15 19:22:01 +0000559}
560
Dan Gohmand934cb82017-02-24 23:18:00 +0000561// Compute a value to write into the code at the location covered
Sam Clegg60ec3032018-01-23 01:23:17 +0000562// by RelEntry. This value isn't used by the static linker; it just serves
563// to make the object format more readable and more likely to be directly
564// useable.
Sam Clegg7c395942017-09-14 23:07:53 +0000565uint32_t
566WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
Sam Clegg492f7522019-03-26 19:46:15 +0000567 if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && !RelEntry.Symbol->isGlobal()) {
568 assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
569 return GOTIndices[RelEntry.Symbol];
570 }
571
Sam Clegg60ec3032018-01-23 01:23:17 +0000572 switch (RelEntry.Type) {
Sam Clegg2a7cac92019-04-04 17:43:50 +0000573 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000574 case wasm::R_WASM_TABLE_INDEX_SLEB:
575 case wasm::R_WASM_TABLE_INDEX_I32: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000576 // Provisional value is table address of the resolved symbol itself
Heejin Ahn18c56a02019-02-04 19:13:39 +0000577 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Cleggf9edbe92018-01-31 19:28:47 +0000578 assert(Sym->isFunction());
579 return TableIndices[Sym];
580 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000581 case wasm::R_WASM_TYPE_INDEX_LEB:
Sam Clegg6c899ba2018-02-23 05:08:34 +0000582 // Provisional value is same as the index
Sam Clegg60ec3032018-01-23 01:23:17 +0000583 return getRelocationIndexValue(RelEntry);
Sam Cleggd1152a22019-02-04 17:28:46 +0000584 case wasm::R_WASM_FUNCTION_INDEX_LEB:
585 case wasm::R_WASM_GLOBAL_INDEX_LEB:
586 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000587 // Provisional value is function/global/event Wasm index
Sam Clegg492f7522019-03-26 19:46:15 +0000588 assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
Sam Clegg6c899ba2018-02-23 05:08:34 +0000589 return WasmIndices[RelEntry.Symbol];
Sam Cleggd1152a22019-02-04 17:28:46 +0000590 case wasm::R_WASM_FUNCTION_OFFSET_I32:
591 case wasm::R_WASM_SECTION_OFFSET_I32: {
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000592 const auto &Section =
593 static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
594 return Section.getSectionOffset() + RelEntry.Addend;
595 }
Sam Cleggd1152a22019-02-04 17:28:46 +0000596 case wasm::R_WASM_MEMORY_ADDR_LEB:
597 case wasm::R_WASM_MEMORY_ADDR_I32:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000598 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000599 case wasm::R_WASM_MEMORY_ADDR_SLEB: {
Sam Cleggf9edbe92018-01-31 19:28:47 +0000600 // Provisional value is address of the global
Heejin Ahn18c56a02019-02-04 19:13:39 +0000601 const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
Sam Clegg60ec3032018-01-23 01:23:17 +0000602 // For undefined symbols, use zero
603 if (!Sym->isDefined())
604 return 0;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000605 const wasm::WasmDataReference &Ref = DataLocations[Sym];
606 const WasmDataSegment &Segment = DataSegments[Ref.Segment];
Sam Clegg60ec3032018-01-23 01:23:17 +0000607 // Ignore overflow. LLVM allows address arithmetic to silently wrap.
Sam Clegg6c899ba2018-02-23 05:08:34 +0000608 return Segment.Offset + Ref.Offset + RelEntry.Addend;
Sam Clegg60ec3032018-01-23 01:23:17 +0000609 }
610 default:
611 llvm_unreachable("invalid relocation type");
612 }
Dan Gohmand934cb82017-02-24 23:18:00 +0000613}
614
Sam Clegg759631c2017-09-15 20:54:59 +0000615static void addData(SmallVectorImpl<char> &DataBytes,
Sam Clegg63ebb812017-09-29 16:50:08 +0000616 MCSectionWasm &DataSection) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000617 LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000618
Sam Clegg63ebb812017-09-29 16:50:08 +0000619 DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
620
Sam Clegg759631c2017-09-15 20:54:59 +0000621 for (const MCFragment &Frag : DataSection) {
622 if (Frag.hasInstructions())
623 report_fatal_error("only data supported in data sections");
624
625 if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
626 if (Align->getValueSize() != 1)
627 report_fatal_error("only byte values supported for alignment");
628 // If nops are requested, use zeros, as this is the data section.
629 uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
Heejin Ahnf208f632018-09-05 01:27:38 +0000630 uint64_t Size =
631 std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
632 DataBytes.size() + Align->getMaxBytesToEmit());
Sam Clegg759631c2017-09-15 20:54:59 +0000633 DataBytes.resize(Size, Value);
634 } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
Nirav Dave588fad42018-05-18 17:45:48 +0000635 int64_t NumValues;
636 if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
Rafael Espindolad707c372018-01-09 22:48:37 +0000637 llvm_unreachable("The fill should be an assembler constant");
Nirav Dave588fad42018-05-18 17:45:48 +0000638 DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
639 Fill->getValue());
Heejin Ahn24faf852018-10-25 23:55:10 +0000640 } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
641 const SmallVectorImpl<char> &Contents = LEB->getContents();
642 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
Sam Clegg759631c2017-09-15 20:54:59 +0000643 } else {
644 const auto &DataFrag = cast<MCDataFragment>(Frag);
645 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Sam Clegg759631c2017-09-15 20:54:59 +0000646 DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
647 }
648 }
649
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000650 LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
Sam Clegg759631c2017-09-15 20:54:59 +0000651}
652
Sam Clegg60ec3032018-01-23 01:23:17 +0000653uint32_t
654WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000655 if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
Sam Cleggb7787fd2017-06-20 04:04:59 +0000656 if (!TypeIndices.count(RelEntry.Symbol))
Sam Clegg5e3d33a2017-07-07 02:01:29 +0000657 report_fatal_error("symbol not found in type index space: " +
Sam Cleggb7787fd2017-06-20 04:04:59 +0000658 RelEntry.Symbol->getName());
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000659 return TypeIndices[RelEntry.Symbol];
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000660 }
Sam Clegg60ec3032018-01-23 01:23:17 +0000661
Sam Clegg25d8e682018-05-08 00:08:21 +0000662 return RelEntry.Symbol->getIndex();
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000663}
664
Dan Gohmand934cb82017-02-24 23:18:00 +0000665// Apply the portions of the relocation records that we can handle ourselves
666// directly.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000667void WasmObjectWriter::applyRelocations(
668 ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000669 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
Dan Gohmand934cb82017-02-24 23:18:00 +0000670 for (const WasmRelocationEntry &RelEntry : Relocations) {
671 uint64_t Offset = ContentsOffset +
672 RelEntry.FixupSection->getSectionOffset() +
673 RelEntry.Offset;
Dan Gohmand934cb82017-02-24 23:18:00 +0000674
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000675 LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
Sam Clegg60ec3032018-01-23 01:23:17 +0000676 uint32_t Value = getProvisionalValue(RelEntry);
677
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000678 switch (RelEntry.Type) {
Sam Cleggd1152a22019-02-04 17:28:46 +0000679 case wasm::R_WASM_FUNCTION_INDEX_LEB:
680 case wasm::R_WASM_TYPE_INDEX_LEB:
681 case wasm::R_WASM_GLOBAL_INDEX_LEB:
682 case wasm::R_WASM_MEMORY_ADDR_LEB:
683 case wasm::R_WASM_EVENT_INDEX_LEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000684 writePatchableLEB(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000685 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000686 case wasm::R_WASM_TABLE_INDEX_I32:
687 case wasm::R_WASM_MEMORY_ADDR_I32:
688 case wasm::R_WASM_FUNCTION_OFFSET_I32:
689 case wasm::R_WASM_SECTION_OFFSET_I32:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000690 writeI32(Stream, Value, Offset);
Dan Gohmand934cb82017-02-24 23:18:00 +0000691 break;
Sam Cleggd1152a22019-02-04 17:28:46 +0000692 case wasm::R_WASM_TABLE_INDEX_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000693 case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
Sam Cleggd1152a22019-02-04 17:28:46 +0000694 case wasm::R_WASM_MEMORY_ADDR_SLEB:
Sam Clegg2a7cac92019-04-04 17:43:50 +0000695 case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
Heejin Ahn18c56a02019-02-04 19:13:39 +0000696 writePatchableSLEB(Stream, Value, Offset);
Sam Clegg60ec3032018-01-23 01:23:17 +0000697 break;
Dan Gohmand934cb82017-02-24 23:18:00 +0000698 default:
Sam Clegg9d24fb72017-06-16 23:59:10 +0000699 llvm_unreachable("invalid relocation type");
Dan Gohmand934cb82017-02-24 23:18:00 +0000700 }
701 }
Dan Gohman18eafb62017-02-22 01:23:18 +0000702}
703
Heejin Ahnda419bd2018-11-14 02:46:21 +0000704void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
705 if (Signatures.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000706 return;
707
708 SectionBookkeeping Section;
709 startSection(Section, wasm::WASM_SEC_TYPE);
710
Heejin Ahnda419bd2018-11-14 02:46:21 +0000711 encodeULEB128(Signatures.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000712
Heejin Ahnda419bd2018-11-14 02:46:21 +0000713 for (const WasmSignature &Sig : Signatures) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000714 W.OS << char(wasm::WASM_TYPE_FUNC);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000715 encodeULEB128(Sig.Params.size(), W.OS);
716 for (wasm::ValType Ty : Sig.Params)
Sam Clegg9e15f352017-06-03 02:01:24 +0000717 writeValueType(Ty);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000718 encodeULEB128(Sig.Returns.size(), W.OS);
719 for (wasm::ValType Ty : Sig.Returns)
Sam Clegg9e15f352017-06-03 02:01:24 +0000720 writeValueType(Ty);
721 }
722
723 endSection(Section);
724}
725
Sam Clegg8defa952018-02-12 22:41:29 +0000726void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
Sam Cleggf950b242017-12-11 23:03:38 +0000727 uint32_t DataSize,
728 uint32_t NumElements) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000729 if (Imports.empty())
730 return;
731
Sam Cleggf950b242017-12-11 23:03:38 +0000732 uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
733
Sam Clegg9e15f352017-06-03 02:01:24 +0000734 SectionBookkeeping Section;
735 startSection(Section, wasm::WASM_SEC_IMPORT);
736
Peter Collingbournef17b1492018-05-21 18:17:42 +0000737 encodeULEB128(Imports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000738 for (const wasm::WasmImport &Import : Imports) {
739 writeString(Import.Module);
740 writeString(Import.Field);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000741 W.OS << char(Import.Kind);
Sam Clegg9e15f352017-06-03 02:01:24 +0000742
743 switch (Import.Kind) {
744 case wasm::WASM_EXTERNAL_FUNCTION:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000745 encodeULEB128(Import.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000746 break;
747 case wasm::WASM_EXTERNAL_GLOBAL:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000748 W.OS << char(Import.Global.Type);
749 W.OS << char(Import.Global.Mutable ? 1 : 0);
Sam Clegg9e15f352017-06-03 02:01:24 +0000750 break;
Sam Cleggf950b242017-12-11 23:03:38 +0000751 case wasm::WASM_EXTERNAL_MEMORY:
Heejin Ahnf208f632018-09-05 01:27:38 +0000752 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000753 encodeULEB128(NumPages, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000754 break;
755 case wasm::WASM_EXTERNAL_TABLE:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000756 W.OS << char(Import.Table.ElemType);
Heejin Ahnf208f632018-09-05 01:27:38 +0000757 encodeULEB128(0, W.OS); // flags
Peter Collingbournef17b1492018-05-21 18:17:42 +0000758 encodeULEB128(NumElements, W.OS); // initial
Sam Cleggf950b242017-12-11 23:03:38 +0000759 break;
Heejin Ahnda419bd2018-11-14 02:46:21 +0000760 case wasm::WASM_EXTERNAL_EVENT:
761 encodeULEB128(Import.Event.Attribute, W.OS);
762 encodeULEB128(Import.Event.SigIndex, W.OS);
763 break;
Sam Clegg9e15f352017-06-03 02:01:24 +0000764 default:
765 llvm_unreachable("unsupported import kind");
766 }
767 }
768
769 endSection(Section);
770}
771
Sam Clegg457fb0b2017-09-15 19:50:44 +0000772void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000773 if (Functions.empty())
774 return;
775
776 SectionBookkeeping Section;
777 startSection(Section, wasm::WASM_SEC_FUNCTION);
778
Peter Collingbournef17b1492018-05-21 18:17:42 +0000779 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000780 for (const WasmFunction &Func : Functions)
Heejin Ahnda419bd2018-11-14 02:46:21 +0000781 encodeULEB128(Func.SigIndex, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000782
783 endSection(Section);
784}
785
Heejin Ahnda419bd2018-11-14 02:46:21 +0000786void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
787 if (Events.empty())
788 return;
789
790 SectionBookkeeping Section;
791 startSection(Section, wasm::WASM_SEC_EVENT);
792
793 encodeULEB128(Events.size(), W.OS);
794 for (const wasm::WasmEventType &Event : Events) {
795 encodeULEB128(Event.Attribute, W.OS);
796 encodeULEB128(Event.SigIndex, W.OS);
797 }
798
799 endSection(Section);
800}
801
Sam Clegg8defa952018-02-12 22:41:29 +0000802void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000803 if (Exports.empty())
804 return;
805
806 SectionBookkeeping Section;
807 startSection(Section, wasm::WASM_SEC_EXPORT);
808
Peter Collingbournef17b1492018-05-21 18:17:42 +0000809 encodeULEB128(Exports.size(), W.OS);
Sam Clegg8defa952018-02-12 22:41:29 +0000810 for (const wasm::WasmExport &Export : Exports) {
811 writeString(Export.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000812 W.OS << char(Export.Kind);
813 encodeULEB128(Export.Index, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000814 }
815
816 endSection(Section);
817}
818
Sam Clegg457fb0b2017-09-15 19:50:44 +0000819void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000820 if (TableElems.empty())
821 return;
822
823 SectionBookkeeping Section;
824 startSection(Section, wasm::WASM_SEC_ELEM);
825
Peter Collingbournef17b1492018-05-21 18:17:42 +0000826 encodeULEB128(1, W.OS); // number of "segments"
827 encodeULEB128(0, W.OS); // the table index
Sam Clegg9e15f352017-06-03 02:01:24 +0000828
829 // init expr for starting offset
Peter Collingbournef17b1492018-05-21 18:17:42 +0000830 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000831 encodeSLEB128(InitialTableOffset, W.OS);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000832 W.OS << char(wasm::WASM_OPCODE_END);
Sam Clegg9e15f352017-06-03 02:01:24 +0000833
Peter Collingbournef17b1492018-05-21 18:17:42 +0000834 encodeULEB128(TableElems.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000835 for (uint32_t Elem : TableElems)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000836 encodeULEB128(Elem, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000837
838 endSection(Section);
839}
840
Thomas Livelyfef8de62019-04-12 22:27:48 +0000841void WasmObjectWriter::writeDataCountSection() {
842 if (DataSegments.empty())
843 return;
844
845 SectionBookkeeping Section;
846 startSection(Section, wasm::WASM_SEC_DATACOUNT);
847 encodeULEB128(DataSegments.size(), W.OS);
848 endSection(Section);
849}
850
Sam Clegg457fb0b2017-09-15 19:50:44 +0000851void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
852 const MCAsmLayout &Layout,
853 ArrayRef<WasmFunction> Functions) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000854 if (Functions.empty())
855 return;
856
857 SectionBookkeeping Section;
858 startSection(Section, wasm::WASM_SEC_CODE);
Sam Clegg6f08c842018-04-24 18:11:36 +0000859 CodeSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000860
Peter Collingbournef17b1492018-05-21 18:17:42 +0000861 encodeULEB128(Functions.size(), W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000862
863 for (const WasmFunction &Func : Functions) {
Sam Cleggfe6414b2017-06-21 23:46:41 +0000864 auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
Sam Clegg9e15f352017-06-03 02:01:24 +0000865
Sam Clegg9e15f352017-06-03 02:01:24 +0000866 int64_t Size = 0;
867 if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
868 report_fatal_error(".size expression must be evaluatable");
869
Peter Collingbournef17b1492018-05-21 18:17:42 +0000870 encodeULEB128(Size, W.OS);
871 FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
872 Asm.writeSectionData(W.OS, &FuncSection, Layout);
Sam Clegg9e15f352017-06-03 02:01:24 +0000873 }
874
Sam Clegg9e15f352017-06-03 02:01:24 +0000875 // Apply fixups.
Sam Cleggacd7d2b2017-06-06 19:15:05 +0000876 applyRelocations(CodeRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000877
878 endSection(Section);
879}
880
Sam Clegg6c899ba2018-02-23 05:08:34 +0000881void WasmObjectWriter::writeDataSection() {
882 if (DataSegments.empty())
Sam Clegg7c395942017-09-14 23:07:53 +0000883 return;
Sam Clegg9e15f352017-06-03 02:01:24 +0000884
885 SectionBookkeeping Section;
886 startSection(Section, wasm::WASM_SEC_DATA);
Sam Clegg6f08c842018-04-24 18:11:36 +0000887 DataSectionIndex = Section.Index;
Sam Clegg9e15f352017-06-03 02:01:24 +0000888
Peter Collingbournef17b1492018-05-21 18:17:42 +0000889 encodeULEB128(DataSegments.size(), W.OS); // count
Sam Clegg7c395942017-09-14 23:07:53 +0000890
Sam Clegg6c899ba2018-02-23 05:08:34 +0000891 for (const WasmDataSegment &Segment : DataSegments) {
Thomas Lively2e150402019-02-19 22:56:19 +0000892 encodeULEB128(Segment.InitFlags, W.OS); // flags
893 if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
894 encodeULEB128(0, W.OS); // memory index
895 if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
896 W.OS << char(wasm::WASM_OPCODE_I32_CONST);
897 encodeSLEB128(Segment.Offset, W.OS); // offset
898 W.OS << char(wasm::WASM_OPCODE_END);
899 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000900 encodeULEB128(Segment.Data.size(), W.OS); // size
901 Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
902 W.OS << Segment.Data; // data
Sam Clegg7c395942017-09-14 23:07:53 +0000903 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000904
905 // Apply fixups.
Sam Clegg7c395942017-09-14 23:07:53 +0000906 applyRelocations(DataRelocations, Section.ContentsOffset);
Sam Clegg9e15f352017-06-03 02:01:24 +0000907
908 endSection(Section);
Sam Clegg9e15f352017-06-03 02:01:24 +0000909}
910
Sam Clegg6f08c842018-04-24 18:11:36 +0000911void WasmObjectWriter::writeRelocSection(
912 uint32_t SectionIndex, StringRef Name,
Heejin Ahnf208f632018-09-05 01:27:38 +0000913 std::vector<WasmRelocationEntry> &Relocs) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000914 // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
915 // for descriptions of the reloc sections.
916
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000917 if (Relocs.empty())
Sam Clegg9e15f352017-06-03 02:01:24 +0000918 return;
919
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000920 // First, ensure the relocations are sorted in offset order. In general they
921 // should already be sorted since `recordRelocation` is called in offset
922 // order, but for the code section we combine many MC sections into single
923 // wasm section, and this order is determined by the order of Asm.Symbols()
924 // not the sections order.
Fangrui Songefd94c52019-04-23 14:51:27 +0000925 llvm::stable_sort(
926 Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000927 return (A.Offset + A.FixupSection->getSectionOffset()) <
928 (B.Offset + B.FixupSection->getSectionOffset());
929 });
930
Sam Clegg9e15f352017-06-03 02:01:24 +0000931 SectionBookkeeping Section;
Sam Clegg6f08c842018-04-24 18:11:36 +0000932 startCustomSection(Section, std::string("reloc.") + Name.str());
Sam Clegg9e15f352017-06-03 02:01:24 +0000933
Peter Collingbournef17b1492018-05-21 18:17:42 +0000934 encodeULEB128(SectionIndex, W.OS);
Sam Cleggf77dc2a2018-08-22 17:27:31 +0000935 encodeULEB128(Relocs.size(), W.OS);
Heejin Ahnf208f632018-09-05 01:27:38 +0000936 for (const WasmRelocationEntry &RelEntry : Relocs) {
937 uint64_t Offset =
938 RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
Sam Clegg6f08c842018-04-24 18:11:36 +0000939 uint32_t Index = getRelocationIndexValue(RelEntry);
Sam Clegg9e15f352017-06-03 02:01:24 +0000940
Peter Collingbournef17b1492018-05-21 18:17:42 +0000941 W.OS << char(RelEntry.Type);
942 encodeULEB128(Offset, W.OS);
943 encodeULEB128(Index, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000944 if (RelEntry.hasAddend())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000945 encodeSLEB128(RelEntry.Addend, W.OS);
Sam Clegg6f08c842018-04-24 18:11:36 +0000946 }
Sam Clegg9e15f352017-06-03 02:01:24 +0000947
948 endSection(Section);
949}
950
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000951void WasmObjectWriter::writeCustomRelocSections() {
952 for (const auto &Sec : CustomSections) {
953 auto &Relocations = CustomSectionsRelocations[Sec.Section];
954 writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
955 }
956}
957
Sam Clegg9e15f352017-06-03 02:01:24 +0000958void WasmObjectWriter::writeLinkingMetaDataSection(
Sam Clegg86b4a092018-02-27 23:57:37 +0000959 ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
Sam Cleggea7cace2018-01-09 23:43:14 +0000960 ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
Sam Clegg6c899ba2018-02-23 05:08:34 +0000961 const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
Sam Clegg9e15f352017-06-03 02:01:24 +0000962 SectionBookkeeping Section;
Sam Clegg2322a932018-04-23 19:16:19 +0000963 startCustomSection(Section, "linking");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000964 encodeULEB128(wasm::WasmMetadataVersion, W.OS);
Sam Clegg9e15f352017-06-03 02:01:24 +0000965
Sam Clegg6bb5a412018-04-26 18:15:32 +0000966 SectionBookkeeping SubSection;
Sam Clegg6c899ba2018-02-23 05:08:34 +0000967 if (SymbolInfos.size() != 0) {
968 startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000969 encodeULEB128(SymbolInfos.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000970 for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000971 encodeULEB128(Sym.Kind, W.OS);
972 encodeULEB128(Sym.Flags, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000973 switch (Sym.Kind) {
974 case wasm::WASM_SYMBOL_TYPE_FUNCTION:
975 case wasm::WASM_SYMBOL_TYPE_GLOBAL:
Heejin Ahnda419bd2018-11-14 02:46:21 +0000976 case wasm::WASM_SYMBOL_TYPE_EVENT:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000977 encodeULEB128(Sym.ElementIndex, W.OS);
Dan Gohman29874ce2019-02-07 22:03:32 +0000978 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
979 (Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0)
Sam Clegg6c899ba2018-02-23 05:08:34 +0000980 writeString(Sym.Name);
981 break;
982 case wasm::WASM_SYMBOL_TYPE_DATA:
983 writeString(Sym.Name);
984 if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000985 encodeULEB128(Sym.DataRef.Segment, W.OS);
986 encodeULEB128(Sym.DataRef.Offset, W.OS);
987 encodeULEB128(Sym.DataRef.Size, W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +0000988 }
989 break;
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000990 case wasm::WASM_SYMBOL_TYPE_SECTION: {
991 const uint32_t SectionIndex =
992 CustomSections[Sym.ElementIndex].OutputIndex;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000993 encodeULEB128(SectionIndex, W.OS);
Sam Clegg6a31a0d2018-04-26 19:27:28 +0000994 break;
995 }
Sam Clegg6c899ba2018-02-23 05:08:34 +0000996 default:
997 llvm_unreachable("unexpected kind");
998 }
Sam Cleggb7787fd2017-06-20 04:04:59 +0000999 }
1000 endSection(SubSection);
1001 }
Sam Clegg9e15f352017-06-03 02:01:24 +00001002
Sam Clegg6c899ba2018-02-23 05:08:34 +00001003 if (DataSegments.size()) {
Sam Clegg63ebb812017-09-29 16:50:08 +00001004 startSection(SubSection, wasm::WASM_SEGMENT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001005 encodeULEB128(DataSegments.size(), W.OS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001006 for (const WasmDataSegment &Segment : DataSegments) {
Sam Cleggd95ed952017-09-20 19:03:35 +00001007 writeString(Segment.Name);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001008 encodeULEB128(Segment.Alignment, W.OS);
Thomas Lively2e150402019-02-19 22:56:19 +00001009 encodeULEB128(Segment.LinkerFlags, W.OS);
Sam Clegg63ebb812017-09-29 16:50:08 +00001010 }
Sam Cleggd95ed952017-09-20 19:03:35 +00001011 endSection(SubSection);
1012 }
1013
Sam Cleggbafe6902017-12-15 00:17:10 +00001014 if (!InitFuncs.empty()) {
1015 startSection(SubSection, wasm::WASM_INIT_FUNCS);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001016 encodeULEB128(InitFuncs.size(), W.OS);
Sam Cleggbafe6902017-12-15 00:17:10 +00001017 for (auto &StartFunc : InitFuncs) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001018 encodeULEB128(StartFunc.first, W.OS); // priority
Peter Collingbournef17b1492018-05-21 18:17:42 +00001019 encodeULEB128(StartFunc.second, W.OS); // function index
Sam Cleggbafe6902017-12-15 00:17:10 +00001020 }
1021 endSection(SubSection);
1022 }
1023
Sam Cleggea7cace2018-01-09 23:43:14 +00001024 if (Comdats.size()) {
1025 startSection(SubSection, wasm::WASM_COMDAT_INFO);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001026 encodeULEB128(Comdats.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001027 for (const auto &C : Comdats) {
1028 writeString(C.first);
Peter Collingbournef17b1492018-05-21 18:17:42 +00001029 encodeULEB128(0, W.OS); // flags for future use
1030 encodeULEB128(C.second.size(), W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001031 for (const WasmComdatEntry &Entry : C.second) {
Peter Collingbournef17b1492018-05-21 18:17:42 +00001032 encodeULEB128(Entry.Kind, W.OS);
1033 encodeULEB128(Entry.Index, W.OS);
Sam Cleggea7cace2018-01-09 23:43:14 +00001034 }
1035 }
1036 endSection(SubSection);
1037 }
1038
Sam Clegg9e15f352017-06-03 02:01:24 +00001039 endSection(Section);
1040}
1041
Thomas Livelycbda16e2019-01-17 02:29:55 +00001042void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1043 const MCAssembler &Asm,
1044 const MCAsmLayout &Layout) {
1045 SectionBookkeeping Section;
1046 auto *Sec = CustomSection.Section;
1047 startCustomSection(Section, CustomSection.Name);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001048
Thomas Livelycbda16e2019-01-17 02:29:55 +00001049 Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1050 Asm.writeSectionData(W.OS, Sec, Layout);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001051
Thomas Livelycbda16e2019-01-17 02:29:55 +00001052 CustomSection.OutputContentsOffset = Section.ContentsOffset;
1053 CustomSection.OutputIndex = Section.Index;
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001054
Thomas Livelycbda16e2019-01-17 02:29:55 +00001055 endSection(Section);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001056
Thomas Livelycbda16e2019-01-17 02:29:55 +00001057 // Apply fixups.
1058 auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1059 applyRelocations(Relocations, CustomSection.OutputContentsOffset);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001060}
1061
Heejin Ahnf208f632018-09-05 01:27:38 +00001062uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001063 assert(Symbol.isFunction());
1064 assert(TypeIndices.count(&Symbol));
1065 return TypeIndices[&Symbol];
1066}
1067
Heejin Ahnda419bd2018-11-14 02:46:21 +00001068uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1069 assert(Symbol.isEvent());
1070 assert(TypeIndices.count(&Symbol));
1071 return TypeIndices[&Symbol];
1072}
1073
Heejin Ahn38b12f52018-11-20 00:38:10 +00001074void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001075 assert(Symbol.isFunction());
1076
Heejin Ahnda419bd2018-11-14 02:46:21 +00001077 WasmSignature S;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001078 const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
Derek Schuff77a7a382018-10-03 22:22:48 +00001079 if (auto *Sig = ResolvedSym->getSignature()) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001080 S.Returns = Sig->Returns;
1081 S.Params = Sig->Params;
Derek Schuff77a7a382018-10-03 22:22:48 +00001082 }
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001083
Heejin Ahnda419bd2018-11-14 02:46:21 +00001084 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001085 if (Pair.second)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001086 Signatures.push_back(S);
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001087 TypeIndices[&Symbol] = Pair.first->second;
1088
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001089 LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1090 << " new:" << Pair.second << "\n");
1091 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001092}
1093
Heejin Ahn38b12f52018-11-20 00:38:10 +00001094void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001095 assert(Symbol.isEvent());
1096
1097 // TODO Currently we don't generate imported exceptions, but if we do, we
1098 // should have a way of infering types of imported exceptions.
1099 WasmSignature S;
1100 if (auto *Sig = Symbol.getSignature()) {
1101 S.Returns = Sig->Returns;
1102 S.Params = Sig->Params;
1103 }
1104
1105 auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1106 if (Pair.second)
1107 Signatures.push_back(S);
1108 TypeIndices[&Symbol] = Pair.first->second;
1109
1110 LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1111 << "\n");
1112 LLVM_DEBUG(dbgs() << " -> type index: " << Pair.first->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001113}
1114
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001115static bool isInSymtab(const MCSymbolWasm &Sym) {
1116 if (Sym.isUsedInReloc())
1117 return true;
1118
1119 if (Sym.isComdat() && !Sym.isDefined())
1120 return false;
1121
1122 if (Sym.isTemporary() && Sym.getName().empty())
1123 return false;
1124
1125 if (Sym.isTemporary() && Sym.isData() && !Sym.getSize())
1126 return false;
1127
1128 if (Sym.isSection())
1129 return false;
1130
1131 return true;
1132}
1133
Peter Collingbourne438390f2018-05-21 18:23:50 +00001134uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1135 const MCAsmLayout &Layout) {
1136 uint64_t StartOffset = W.OS.tell();
1137
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001138 LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
Dan Gohmand934cb82017-02-24 23:18:00 +00001139
1140 // Collect information from the available symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001141 SmallVector<WasmFunction, 4> Functions;
1142 SmallVector<uint32_t, 4> TableElems;
Sam Clegg8defa952018-02-12 22:41:29 +00001143 SmallVector<wasm::WasmImport, 4> Imports;
1144 SmallVector<wasm::WasmExport, 4> Exports;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001145 SmallVector<wasm::WasmEventType, 1> Events;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001146 SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
Sam Cleggbafe6902017-12-15 00:17:10 +00001147 SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
Sam Cleggea7cace2018-01-09 23:43:14 +00001148 std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
Sam Clegg7c395942017-09-14 23:07:53 +00001149 uint32_t DataSize = 0;
Dan Gohmand934cb82017-02-24 23:18:00 +00001150
Sam Cleggf950b242017-12-11 23:03:38 +00001151 // For now, always emit the memory import, since loads and stores are not
1152 // valid without it. In the future, we could perhaps be more clever and omit
1153 // it if there are no loads or stores.
Sam Clegg8defa952018-02-12 22:41:29 +00001154 wasm::WasmImport MemImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001155 MemImport.Module = "env";
1156 MemImport.Field = "__linear_memory";
Sam Cleggf950b242017-12-11 23:03:38 +00001157 MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1158 Imports.push_back(MemImport);
1159
1160 // For now, always emit the table section, since indirect calls are not
1161 // valid without it. In the future, we could perhaps be more clever and omit
1162 // it if there are no indirect calls.
Sam Clegg8defa952018-02-12 22:41:29 +00001163 wasm::WasmImport TableImport;
Sam Clegg1ed3a042019-02-21 17:05:19 +00001164 TableImport.Module = "env";
1165 TableImport.Field = "__indirect_function_table";
Sam Cleggf950b242017-12-11 23:03:38 +00001166 TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
Thomas Lively6a87dda2019-01-08 06:25:55 +00001167 TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
Sam Cleggf950b242017-12-11 23:03:38 +00001168 Imports.push_back(TableImport);
1169
Heejin Ahnda419bd2018-11-14 02:46:21 +00001170 // Populate SignatureIndices, and Imports and WasmIndices for undefined
Nicholas Wilson586320c2018-02-28 17:19:48 +00001171 // symbols. This must be done before populating WasmIndices for defined
1172 // symbols.
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001173 for (const MCSymbol &S : Asm.symbols()) {
1174 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1175
1176 // Register types for all functions, including those with private linkage
Sam Clegg9f3fe422018-01-17 19:28:43 +00001177 // (because wasm always needs a type signature).
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001178 if (WS.isFunction())
1179 registerFunctionType(WS);
1180
Heejin Ahnda419bd2018-11-14 02:46:21 +00001181 if (WS.isEvent())
1182 registerEventType(WS);
1183
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001184 if (WS.isTemporary())
1185 continue;
1186
1187 // If the symbol is not defined in this translation unit, import it.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001188 if (!WS.isDefined() && !WS.isComdat()) {
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001189 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001190 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001191 Import.Module = WS.getImportModule();
1192 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001193 Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
Sam Clegg8defa952018-02-12 22:41:29 +00001194 Import.SigIndex = getFunctionType(WS);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001195 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001196 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001197 WasmIndices[&WS] = NumFunctionImports++;
1198 } else if (WS.isGlobal()) {
Nicholas Wilson15f349f2018-03-09 16:30:44 +00001199 if (WS.isWeak())
1200 report_fatal_error("undefined global symbol cannot be weak");
1201
Sam Clegg6c899ba2018-02-23 05:08:34 +00001202 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001203 Import.Field = WS.getImportName();
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001204 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
Sam Clegg492f7522019-03-26 19:46:15 +00001205 Import.Module = WS.getImportModule();
Sam Clegg6c899ba2018-02-23 05:08:34 +00001206 Import.Global = WS.getGlobalType();
1207 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001208 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001209 WasmIndices[&WS] = NumGlobalImports++;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001210 } else if (WS.isEvent()) {
1211 if (WS.isWeak())
1212 report_fatal_error("undefined event symbol cannot be weak");
1213
1214 wasm::WasmImport Import;
Dan Gohmanf726e442019-02-01 22:27:34 +00001215 Import.Module = WS.getImportModule();
1216 Import.Field = WS.getImportName();
Heejin Ahnda419bd2018-11-14 02:46:21 +00001217 Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1218 Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1219 Import.Event.SigIndex = getEventType(WS);
1220 Imports.push_back(Import);
Sam Clegg492f7522019-03-26 19:46:15 +00001221 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001222 WasmIndices[&WS] = NumEventImports++;
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001223 }
Dan Gohman32ce5ca2017-12-05 18:29:48 +00001224 }
1225 }
1226
Sam Clegg492f7522019-03-26 19:46:15 +00001227 // Add imports for GOT globals
1228 for (const MCSymbol &S : Asm.symbols()) {
1229 const auto &WS = static_cast<const MCSymbolWasm &>(S);
1230 if (WS.isUsedInGOT()) {
1231 wasm::WasmImport Import;
1232 if (WS.isFunction())
1233 Import.Module = "GOT.func";
1234 else
1235 Import.Module = "GOT.mem";
1236 Import.Field = WS.getName();
1237 Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1238 Import.Global = {wasm::WASM_TYPE_I32, true};
1239 Imports.push_back(Import);
1240 assert(GOTIndices.count(&WS) == 0);
1241 GOTIndices[&WS] = NumGlobalImports++;
1242 }
1243 }
1244
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001245 // Populate DataSegments and CustomSections, which must be done before
1246 // populating DataLocations.
Sam Clegg759631c2017-09-15 20:54:59 +00001247 for (MCSection &Sec : Asm) {
1248 auto &Section = static_cast<MCSectionWasm &>(Sec);
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001249 StringRef SectionName = Section.getSectionName();
Sam Clegg759631c2017-09-15 20:54:59 +00001250
Sam Cleggbafe6902017-12-15 00:17:10 +00001251 // .init_array sections are handled specially elsewhere.
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001252 if (SectionName.startswith(".init_array"))
Sam Cleggbafe6902017-12-15 00:17:10 +00001253 continue;
1254
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001255 // Code is handled separately
1256 if (Section.getKind().isText())
1257 continue;
Sam Cleggea7cace2018-01-09 23:43:14 +00001258
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001259 if (Section.isWasmData()) {
1260 uint32_t SegmentIndex = DataSegments.size();
1261 DataSize = alignTo(DataSize, Section.getAlignment());
1262 DataSegments.emplace_back();
1263 WasmDataSegment &Segment = DataSegments.back();
1264 Segment.Name = SectionName;
Simon Pilgrim9b49f362019-02-24 13:31:52 +00001265 Segment.InitFlags =
1266 Section.getPassive() ? (uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE : 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001267 Segment.Offset = DataSize;
1268 Segment.Section = &Section;
1269 addData(Segment.Data, Section);
Sam Clegg56c587a2019-01-16 01:34:48 +00001270 Segment.Alignment = Log2_32(Section.getAlignment());
Thomas Lively2e150402019-02-19 22:56:19 +00001271 Segment.LinkerFlags = 0;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001272 DataSize += Segment.Data.size();
1273 Section.setSegmentIndex(SegmentIndex);
1274
1275 if (const MCSymbolWasm *C = Section.getGroup()) {
1276 Comdats[C->getName()].emplace_back(
1277 WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1278 }
1279 } else {
1280 // Create custom sections
1281 assert(Sec.getKind().isMetadata());
1282
1283 StringRef Name = SectionName;
1284
1285 // For user-defined custom sections, strip the prefix
1286 if (Name.startswith(".custom_section."))
1287 Name = Name.substr(strlen(".custom_section."));
1288
Heejin Ahnf208f632018-09-05 01:27:38 +00001289 MCSymbol *Begin = Sec.getBeginSymbol();
Sam Cleggfb807d42018-05-07 19:40:50 +00001290 if (Begin) {
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001291 WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
Sam Cleggb210c642018-05-10 17:38:35 +00001292 if (SectionName != Begin->getName())
Sam Cleggfb807d42018-05-07 19:40:50 +00001293 report_fatal_error("section name and begin symbol should match: " +
Sam Cleggb210c642018-05-10 17:38:35 +00001294 Twine(SectionName));
Sam Cleggfb807d42018-05-07 19:40:50 +00001295 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001296
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001297 // Separate out the producers and target features sections
Thomas Livelycbda16e2019-01-17 02:29:55 +00001298 if (Name == "producers") {
1299 ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1300 continue;
1301 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001302 if (Name == "target_features") {
1303 TargetFeaturesSection =
1304 llvm::make_unique<WasmCustomSection>(Name, &Section);
1305 continue;
1306 }
Thomas Livelycbda16e2019-01-17 02:29:55 +00001307
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001308 CustomSections.emplace_back(Name, &Section);
Sam Cleggea7cace2018-01-09 23:43:14 +00001309 }
Sam Clegg759631c2017-09-15 20:54:59 +00001310 }
1311
Nicholas Wilson586320c2018-02-28 17:19:48 +00001312 // Populate WasmIndices and DataLocations for defined symbols.
Dan Gohmand934cb82017-02-24 23:18:00 +00001313 for (const MCSymbol &S : Asm.symbols()) {
1314 // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1315 // or used in relocations.
1316 if (S.isTemporary() && S.getName().empty())
1317 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001318
Dan Gohmand934cb82017-02-24 23:18:00 +00001319 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001320 LLVM_DEBUG(
1321 dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1322 << " isDefined=" << S.isDefined() << " isExternal="
1323 << S.isExternal() << " isTemporary=" << S.isTemporary()
1324 << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1325 << " isVariable=" << WS.isVariable() << "\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001326
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001327 if (WS.isVariable())
1328 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001329 if (WS.isComdat() && !WS.isDefined())
1330 continue;
Sam Cleggb7787fd2017-06-20 04:04:59 +00001331
Dan Gohmand934cb82017-02-24 23:18:00 +00001332 if (WS.isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001333 unsigned Index;
Sam Cleggcd65f692018-01-11 23:59:16 +00001334 if (WS.isDefined()) {
Sam Cleggb7787fd2017-06-20 04:04:59 +00001335 if (WS.getOffset() != 0)
1336 report_fatal_error(
1337 "function sections must contain one function each");
1338
Heejin Ahn18c56a02019-02-04 19:13:39 +00001339 if (WS.getSize() == nullptr)
Sam Cleggb7787fd2017-06-20 04:04:59 +00001340 report_fatal_error(
1341 "function symbols must have a size set with .size");
1342
Sam Clegg6c899ba2018-02-23 05:08:34 +00001343 // A definition. Write out the function body.
Sam Clegg9f3fe422018-01-17 19:28:43 +00001344 Index = NumFunctionImports + Functions.size();
Dan Gohmand934cb82017-02-24 23:18:00 +00001345 WasmFunction Func;
Heejin Ahnda419bd2018-11-14 02:46:21 +00001346 Func.SigIndex = getFunctionType(WS);
Dan Gohmand934cb82017-02-24 23:18:00 +00001347 Func.Sym = &WS;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001348 WasmIndices[&WS] = Index;
Dan Gohmand934cb82017-02-24 23:18:00 +00001349 Functions.push_back(Func);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001350
1351 auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1352 if (const MCSymbolWasm *C = Section.getGroup()) {
1353 Comdats[C->getName()].emplace_back(
1354 WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1355 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001356 } else {
1357 // An import; the index was assigned above.
Sam Clegg6c899ba2018-02-23 05:08:34 +00001358 Index = WasmIndices.find(&WS)->second;
Dan Gohmand934cb82017-02-24 23:18:00 +00001359 }
1360
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001361 LLVM_DEBUG(dbgs() << " -> function index: " << Index << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001362
Sam Clegg6c899ba2018-02-23 05:08:34 +00001363 } else if (WS.isData()) {
Wouter van Oortmerssenf3feb6a2019-03-04 17:18:04 +00001364 if (!isInSymtab(WS))
Sam Cleggc38e9472017-06-02 01:05:24 +00001365 continue;
Dan Gohmand934cb82017-02-24 23:18:00 +00001366
Sam Clegg6c899ba2018-02-23 05:08:34 +00001367 if (!WS.isDefined()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001368 LLVM_DEBUG(dbgs() << " -> segment index: -1"
1369 << "\n");
Sam Cleggfe6414b2017-06-21 23:46:41 +00001370 continue;
Sam Clegg6c899ba2018-02-23 05:08:34 +00001371 }
Sam Cleggc38e9472017-06-02 01:05:24 +00001372
Sam Cleggfe6414b2017-06-21 23:46:41 +00001373 if (!WS.getSize())
1374 report_fatal_error("data symbols must have a size set with .size: " +
1375 WS.getName());
Sam Cleggc38e9472017-06-02 01:05:24 +00001376
Sam Cleggfe6414b2017-06-21 23:46:41 +00001377 int64_t Size = 0;
1378 if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1379 report_fatal_error(".size expression must be evaluatable");
Dan Gohmand934cb82017-02-24 23:18:00 +00001380
Sam Clegg759631c2017-09-15 20:54:59 +00001381 auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
Sam Cleggea7cace2018-01-09 23:43:14 +00001382 assert(DataSection.isWasmData());
Sam Clegg7c395942017-09-14 23:07:53 +00001383
Sam Clegg6c899ba2018-02-23 05:08:34 +00001384 // For each data symbol, export it in the symtab as a reference to the
1385 // corresponding Wasm data segment.
1386 wasm::WasmDataReference Ref = wasm::WasmDataReference{
1387 DataSection.getSegmentIndex(),
1388 static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1389 static_cast<uint32_t>(Size)};
1390 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001391 LLVM_DEBUG(dbgs() << " -> segment index: " << Ref.Segment << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001392
Sam Clegga165f2d2018-04-30 19:40:57 +00001393 } else if (WS.isGlobal()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001394 // A "true" Wasm global (currently just __stack_pointer)
Eric Christopher545932b2018-02-23 21:14:47 +00001395 if (WS.isDefined())
Sam Clegg6c899ba2018-02-23 05:08:34 +00001396 report_fatal_error("don't yet support defined globals");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001397
Eric Christopher545932b2018-02-23 21:14:47 +00001398 // An import; the index was assigned above
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001399 LLVM_DEBUG(dbgs() << " -> global index: "
1400 << WasmIndices.find(&WS)->second << "\n");
Heejin Ahnda419bd2018-11-14 02:46:21 +00001401
1402 } else if (WS.isEvent()) {
1403 // C++ exception symbol (__cpp_exception)
1404 unsigned Index;
1405 if (WS.isDefined()) {
1406 Index = NumEventImports + Events.size();
1407 wasm::WasmEventType Event;
1408 Event.SigIndex = getEventType(WS);
1409 Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
Sam Clegg492f7522019-03-26 19:46:15 +00001410 assert(WasmIndices.count(&WS) == 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001411 WasmIndices[&WS] = Index;
1412 Events.push_back(Event);
1413 } else {
1414 // An import; the index was assigned above.
Sam Clegg492f7522019-03-26 19:46:15 +00001415 assert(WasmIndices.count(&WS) > 0);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001416 Index = WasmIndices.find(&WS)->second;
1417 }
1418 LLVM_DEBUG(dbgs() << " -> event index: " << WasmIndices.find(&WS)->second
1419 << "\n");
1420
Sam Clegga165f2d2018-04-30 19:40:57 +00001421 } else {
1422 assert(WS.isSection());
Dan Gohmand934cb82017-02-24 23:18:00 +00001423 }
1424 }
1425
Nicholas Wilson586320c2018-02-28 17:19:48 +00001426 // Populate WasmIndices and DataLocations for aliased symbols. We need to
1427 // process these in a separate pass because we need to have processed the
1428 // target of the alias before the alias itself and the symbols are not
1429 // necessarily ordered in this way.
Sam Cleggb7787fd2017-06-20 04:04:59 +00001430 for (const MCSymbol &S : Asm.symbols()) {
1431 if (!S.isVariable())
1432 continue;
Sam Clegg31a2c802017-09-20 21:17:04 +00001433
Sam Cleggcd65f692018-01-11 23:59:16 +00001434 assert(S.isDefined());
Sam Cleggb7787fd2017-06-20 04:04:59 +00001435
Sam Clegg5e3d33a2017-07-07 02:01:29 +00001436 // Find the target symbol of this weak alias and export that index
Sam Cleggaff1c4d2017-09-15 19:22:01 +00001437 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Heejin Ahn18c56a02019-02-04 19:13:39 +00001438 const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001439 LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1440 << "'\n");
Sam Cleggb7787fd2017-06-20 04:04:59 +00001441
Sam Cleggffba00b2019-02-22 21:41:42 +00001442 if (ResolvedSym->isFunction()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001443 assert(WasmIndices.count(ResolvedSym) > 0);
1444 uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
Sam Clegg492f7522019-03-26 19:46:15 +00001445 assert(WasmIndices.count(&WS) == 0);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001446 WasmIndices[&WS] = WasmIndex;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001447 LLVM_DEBUG(dbgs() << " -> index:" << WasmIndex << "\n");
Sam Cleggffba00b2019-02-22 21:41:42 +00001448 } else if (ResolvedSym->isData()) {
Sam Clegg6c899ba2018-02-23 05:08:34 +00001449 assert(DataLocations.count(ResolvedSym) > 0);
1450 const wasm::WasmDataReference &Ref =
1451 DataLocations.find(ResolvedSym)->second;
1452 DataLocations[&WS] = Ref;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001453 LLVM_DEBUG(dbgs() << " -> index:" << Ref.Segment << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001454 } else {
Heejin Ahnda419bd2018-11-14 02:46:21 +00001455 report_fatal_error("don't yet support global/event aliases");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001456 }
Nicholas Wilson586320c2018-02-28 17:19:48 +00001457 }
Sam Clegg31a2c802017-09-20 21:17:04 +00001458
Nicholas Wilson586320c2018-02-28 17:19:48 +00001459 // Finally, populate the symbol table itself, in its "natural" order.
1460 for (const MCSymbol &S : Asm.symbols()) {
1461 const auto &WS = static_cast<const MCSymbolWasm &>(S);
Sam Clegg25d8e682018-05-08 00:08:21 +00001462 if (!isInSymtab(WS)) {
Heejin Ahn18c56a02019-02-04 19:13:39 +00001463 WS.setIndex(InvalidIndex);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001464 continue;
Sam Clegg25d8e682018-05-08 00:08:21 +00001465 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001466 LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
Nicholas Wilson586320c2018-02-28 17:19:48 +00001467
1468 uint32_t Flags = 0;
1469 if (WS.isWeak())
1470 Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1471 if (WS.isHidden())
1472 Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1473 if (!WS.isExternal() && WS.isDefined())
1474 Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1475 if (WS.isUndefined())
1476 Flags |= wasm::WASM_SYMBOL_UNDEFINED;
Sam Cleggd6ef8da2019-02-07 01:24:44 +00001477 if (WS.isExported())
1478 Flags |= wasm::WASM_SYMBOL_EXPORTED;
Dan Gohman29874ce2019-02-07 22:03:32 +00001479 if (WS.getName() != WS.getImportName())
1480 Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
Nicholas Wilson586320c2018-02-28 17:19:48 +00001481
1482 wasm::WasmSymbolInfo Info;
1483 Info.Name = WS.getName();
1484 Info.Kind = WS.getType();
1485 Info.Flags = Flags;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001486 if (!WS.isData()) {
1487 assert(WasmIndices.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001488 Info.ElementIndex = WasmIndices.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001489 } else if (WS.isDefined()) {
1490 assert(DataLocations.count(&WS) > 0);
Nicholas Wilson586320c2018-02-28 17:19:48 +00001491 Info.DataRef = DataLocations.find(&WS)->second;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001492 }
Sam Clegg25d8e682018-05-08 00:08:21 +00001493 WS.setIndex(SymbolInfos.size());
Nicholas Wilson586320c2018-02-28 17:19:48 +00001494 SymbolInfos.emplace_back(Info);
Sam Cleggb7787fd2017-06-20 04:04:59 +00001495 }
1496
Sam Clegg6006e092017-12-22 20:31:39 +00001497 {
1498 auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
Sam Cleggf9edbe92018-01-31 19:28:47 +00001499 // Functions referenced by a relocation need to put in the table. This is
1500 // purely to make the object file's provisional values readable, and is
1501 // ignored by the linker, which re-calculates the relocations itself.
Sam Cleggd1152a22019-02-04 17:28:46 +00001502 if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1503 Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB)
Sam Cleggf9edbe92018-01-31 19:28:47 +00001504 return;
1505 assert(Rel.Symbol->isFunction());
Heejin Ahn18c56a02019-02-04 19:13:39 +00001506 const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001507 uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
Heejin Ahn18c56a02019-02-04 19:13:39 +00001508 uint32_t TableIndex = TableElems.size() + InitialTableOffset;
Sam Cleggf9edbe92018-01-31 19:28:47 +00001509 if (TableIndices.try_emplace(&WS, TableIndex).second) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001510 LLVM_DEBUG(dbgs() << " -> adding " << WS.getName()
1511 << " to table: " << TableIndex << "\n");
Sam Clegg6c899ba2018-02-23 05:08:34 +00001512 TableElems.push_back(FunctionIndex);
Sam Cleggf9edbe92018-01-31 19:28:47 +00001513 registerFunctionType(WS);
Sam Clegg6006e092017-12-22 20:31:39 +00001514 }
1515 };
Dan Gohman970d02c2017-03-30 23:58:19 +00001516
Sam Clegg6006e092017-12-22 20:31:39 +00001517 for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1518 HandleReloc(RelEntry);
1519 for (const WasmRelocationEntry &RelEntry : DataRelocations)
1520 HandleReloc(RelEntry);
Dan Gohmand934cb82017-02-24 23:18:00 +00001521 }
1522
Sam Cleggbafe6902017-12-15 00:17:10 +00001523 // Translate .init_array section contents into start functions.
1524 for (const MCSection &S : Asm) {
1525 const auto &WS = static_cast<const MCSectionWasm &>(S);
1526 if (WS.getSectionName().startswith(".fini_array"))
1527 report_fatal_error(".fini_array sections are unsupported");
1528 if (!WS.getSectionName().startswith(".init_array"))
1529 continue;
1530 if (WS.getFragmentList().empty())
1531 continue;
Sam Cleggb210c642018-05-10 17:38:35 +00001532
1533 // init_array is expected to contain a single non-empty data fragment
1534 if (WS.getFragmentList().size() != 3)
Sam Cleggbafe6902017-12-15 00:17:10 +00001535 report_fatal_error("only one .init_array section fragment supported");
Sam Cleggb210c642018-05-10 17:38:35 +00001536
1537 auto IT = WS.begin();
1538 const MCFragment &EmptyFrag = *IT;
1539 if (EmptyFrag.getKind() != MCFragment::FT_Data)
1540 report_fatal_error(".init_array section should be aligned");
1541
1542 IT = std::next(IT);
1543 const MCFragment &AlignFrag = *IT;
Sam Cleggbafe6902017-12-15 00:17:10 +00001544 if (AlignFrag.getKind() != MCFragment::FT_Align)
1545 report_fatal_error(".init_array section should be aligned");
1546 if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 8 : 4))
1547 report_fatal_error(".init_array section should be aligned for pointers");
Sam Cleggb210c642018-05-10 17:38:35 +00001548
1549 const MCFragment &Frag = *std::next(IT);
Sam Cleggbafe6902017-12-15 00:17:10 +00001550 if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data)
1551 report_fatal_error("only data supported in .init_array section");
Sam Cleggb210c642018-05-10 17:38:35 +00001552
Sam Cleggbafe6902017-12-15 00:17:10 +00001553 uint16_t Priority = UINT16_MAX;
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001554 unsigned PrefixLength = strlen(".init_array");
1555 if (WS.getSectionName().size() > PrefixLength) {
1556 if (WS.getSectionName()[PrefixLength] != '.')
Heejin Ahnf208f632018-09-05 01:27:38 +00001557 report_fatal_error(
1558 ".init_array section priority should start with '.'");
Sam Clegg4d57fbd2018-05-02 23:11:38 +00001559 if (WS.getSectionName()
1560 .substr(PrefixLength + 1)
1561 .getAsInteger(10, Priority))
Sam Cleggbafe6902017-12-15 00:17:10 +00001562 report_fatal_error("invalid .init_array section priority");
1563 }
1564 const auto &DataFrag = cast<MCDataFragment>(Frag);
1565 const SmallVectorImpl<char> &Contents = DataFrag.getContents();
Heejin Ahnf208f632018-09-05 01:27:38 +00001566 for (const uint8_t *
Heejin Ahn18c56a02019-02-04 19:13:39 +00001567 P = (const uint8_t *)Contents.data(),
1568 *End = (const uint8_t *)Contents.data() + Contents.size();
1569 P != End; ++P) {
1570 if (*P != 0)
Sam Cleggbafe6902017-12-15 00:17:10 +00001571 report_fatal_error("non-symbolic data in .init_array section");
1572 }
1573 for (const MCFixup &Fixup : DataFrag.getFixups()) {
Heejin Ahnf208f632018-09-05 01:27:38 +00001574 assert(Fixup.getKind() ==
1575 MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
Sam Cleggbafe6902017-12-15 00:17:10 +00001576 const MCExpr *Expr = Fixup.getValue();
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001577 auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1578 if (!SymRef)
Sam Cleggbafe6902017-12-15 00:17:10 +00001579 report_fatal_error("fixups in .init_array should be symbol references");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001580 const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1581 if (TargetSym.getIndex() == InvalidIndex)
Sam Clegg25d8e682018-05-08 00:08:21 +00001582 report_fatal_error("symbols in .init_array should exist in symbtab");
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001583 if (!TargetSym.isFunction())
1584 report_fatal_error("symbols in .init_array should be for functions");
Sam Clegg25d8e682018-05-08 00:08:21 +00001585 InitFuncs.push_back(
Sam Clegg8fffa1d2019-02-22 22:29:34 +00001586 std::make_pair(Priority, TargetSym.getIndex()));
Sam Cleggbafe6902017-12-15 00:17:10 +00001587 }
1588 }
1589
Dan Gohman18eafb62017-02-22 01:23:18 +00001590 // Write out the Wasm header.
1591 writeHeader(Asm);
1592
Heejin Ahnda419bd2018-11-14 02:46:21 +00001593 writeTypeSection(Signatures);
Sam Cleggf950b242017-12-11 23:03:38 +00001594 writeImportSection(Imports, DataSize, TableElems.size());
Sam Clegg9e15f352017-06-03 02:01:24 +00001595 writeFunctionSection(Functions);
Sam Cleggf950b242017-12-11 23:03:38 +00001596 // Skip the "table" section; we import the table instead.
1597 // Skip the "memory" section; we import the memory instead.
Heejin Ahnda419bd2018-11-14 02:46:21 +00001598 writeEventSection(Events);
Sam Clegg9e15f352017-06-03 02:01:24 +00001599 writeExportSection(Exports);
Sam Clegg9e15f352017-06-03 02:01:24 +00001600 writeElemSection(TableElems);
Thomas Livelyfef8de62019-04-12 22:27:48 +00001601 writeDataCountSection();
Sam Cleggacd7d2b2017-06-06 19:15:05 +00001602 writeCodeSection(Asm, Layout, Functions);
Sam Clegg6c899ba2018-02-23 05:08:34 +00001603 writeDataSection();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001604 for (auto &CustomSection : CustomSections)
1605 writeCustomSection(CustomSection, Asm, Layout);
Nicholas Wilsonc22bfb62018-03-05 12:59:03 +00001606 writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
Sam Clegg6f08c842018-04-24 18:11:36 +00001607 writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1608 writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
Sam Clegg6a31a0d2018-04-26 19:27:28 +00001609 writeCustomRelocSections();
Thomas Livelycbda16e2019-01-17 02:29:55 +00001610 if (ProducersSection)
1611 writeCustomSection(*ProducersSection, Asm, Layout);
Thomas Livelyf6f4f842019-03-20 20:26:45 +00001612 if (TargetFeaturesSection)
1613 writeCustomSection(*TargetFeaturesSection, Asm, Layout);
Dan Gohman970d02c2017-03-30 23:58:19 +00001614
Dan Gohmand934cb82017-02-24 23:18:00 +00001615 // TODO: Translate the .comment section to the output.
Peter Collingbourne438390f2018-05-21 18:23:50 +00001616 return W.OS.tell() - StartOffset;
Dan Gohman18eafb62017-02-22 01:23:18 +00001617}
1618
Lang Hames60fbc7c2017-10-10 16:28:07 +00001619std::unique_ptr<MCObjectWriter>
Lang Hames1301a872017-10-10 01:15:10 +00001620llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1621 raw_pwrite_stream &OS) {
Dan Gohman0917c9e2018-01-15 17:06:23 +00001622 return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
Dan Gohman18eafb62017-02-22 01:23:18 +00001623}