1//==- WebAssemblyDisassembler.cpp - Disassembler for WebAssembly -*- C++ -*-==//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file is part of the WebAssembly Disassembler.
11///
12/// It contains code to translate the data produced by the decoder into
13/// MCInsts.
14///
15//===----------------------------------------------------------------------===//
16
17#include "MCTargetDesc/WebAssemblyMCAsmInfo.h"
18#include "MCTargetDesc/WebAssemblyMCTypeUtilities.h"
19#include "TargetInfo/WebAssemblyTargetInfo.h"
20#include "llvm/BinaryFormat/Wasm.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCDisassembler/MCDisassembler.h"
23#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCSymbolWasm.h"
28#include "llvm/MC/TargetRegistry.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/Endian.h"
31#include "llvm/Support/LEB128.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "wasm-disassembler"
36
37using DecodeStatus = MCDisassembler::DecodeStatus;
38
39#include "WebAssemblyGenDisassemblerTables.inc"
40
41static constexpr int WebAssemblyInstructionTableSize = 256;
42
43namespace {
44class WebAssemblyDisassembler final : public MCDisassembler {
45 std::unique_ptr<const MCInstrInfo> MCII;
46
47 DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
48 ArrayRef<uint8_t> Bytes, uint64_t Address,
49 raw_ostream &CStream) const override;
50
51 Expected<bool> onSymbolStart(SymbolInfoTy &Symbol, uint64_t &Size,
52 ArrayRef<uint8_t> Bytes,
53 uint64_t Address) const override;
54
55public:
56 WebAssemblyDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx,
57 std::unique_ptr<const MCInstrInfo> MCII)
58 : MCDisassembler(STI, Ctx), MCII(std::move(MCII)) {}
59};
60} // end anonymous namespace
61
62static MCDisassembler *createWebAssemblyDisassembler(const Target &T,
63 const MCSubtargetInfo &STI,
64 MCContext &Ctx) {
65 std::unique_ptr<const MCInstrInfo> MCII(T.createMCInstrInfo());
66 return new WebAssemblyDisassembler(STI, Ctx, std::move(MCII));
67}
68
69extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
70LLVMInitializeWebAssemblyDisassembler() {
71 // Register the disassembler for each target.
72 TargetRegistry::RegisterMCDisassembler(T&: getTheWebAssemblyTarget32(),
73 Fn: createWebAssemblyDisassembler);
74 TargetRegistry::RegisterMCDisassembler(T&: getTheWebAssemblyTarget64(),
75 Fn: createWebAssemblyDisassembler);
76}
77
78static int nextByte(ArrayRef<uint8_t> Bytes, uint64_t &Size) {
79 if (Size >= Bytes.size())
80 return -1;
81 auto V = Bytes[Size];
82 Size++;
83 return V;
84}
85
86static bool nextLEB(int64_t &Val, ArrayRef<uint8_t> Bytes, uint64_t &Size,
87 bool Signed) {
88 unsigned N = 0;
89 const char *Error = nullptr;
90 Val = Signed ? decodeSLEB128(p: Bytes.data() + Size, n: &N,
91 end: Bytes.data() + Bytes.size(), error: &Error)
92 : static_cast<int64_t>(decodeULEB128(p: Bytes.data() + Size, n: &N,
93 end: Bytes.data() + Bytes.size(),
94 error: &Error));
95 if (Error)
96 return false;
97 Size += N;
98 return true;
99}
100
101static bool parseLEBImmediate(MCInst &MI, uint64_t &Size,
102 ArrayRef<uint8_t> Bytes, bool Signed) {
103 int64_t Val;
104 if (!nextLEB(Val, Bytes, Size, Signed))
105 return false;
106 MI.addOperand(Op: MCOperand::createImm(Val));
107 return true;
108}
109
110template <typename T>
111bool parseImmediate(MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes) {
112 if (Size + sizeof(T) > Bytes.size())
113 return false;
114 T Val =
115 support::endian::read<T, llvm::endianness::little>(Bytes.data() + Size);
116 Size += sizeof(T);
117 if (std::is_floating_point<T>::value) {
118 MI.addOperand(
119 Op: MCOperand::createDFPImm(Val: bit_cast<uint64_t>(from: static_cast<double>(Val))));
120 } else {
121 MI.addOperand(Op: MCOperand::createImm(Val: static_cast<int64_t>(Val)));
122 }
123 return true;
124}
125
126Expected<bool> WebAssemblyDisassembler::onSymbolStart(SymbolInfoTy &Symbol,
127 uint64_t &Size,
128 ArrayRef<uint8_t> Bytes,
129 uint64_t Address) const {
130 Size = 0;
131 if (Symbol.Type == wasm::WASM_SYMBOL_TYPE_SECTION) {
132 // Start of a code section: we're parsing only the function count.
133 int64_t FunctionCount;
134 if (!nextLEB(Val&: FunctionCount, Bytes, Size, Signed: false))
135 return false;
136 outs() << " # " << FunctionCount << " functions in section.";
137 } else {
138 // Parse the start of a single function.
139 int64_t BodySize, LocalEntryCount;
140 if (!nextLEB(Val&: BodySize, Bytes, Size, Signed: false) ||
141 !nextLEB(Val&: LocalEntryCount, Bytes, Size, Signed: false))
142 return false;
143 if (LocalEntryCount) {
144 outs() << " .local ";
145 for (int64_t I = 0; I < LocalEntryCount; I++) {
146 int64_t Count, Type;
147 if (!nextLEB(Val&: Count, Bytes, Size, Signed: false) ||
148 !nextLEB(Val&: Type, Bytes, Size, Signed: false))
149 return false;
150 for (int64_t J = 0; J < Count; J++) {
151 if (I || J)
152 outs() << ", ";
153 outs() << WebAssembly::anyTypeToString(Type);
154 }
155 }
156 }
157 }
158 outs() << "\n";
159 return true;
160}
161
162MCDisassembler::DecodeStatus WebAssemblyDisassembler::getInstruction(
163 MCInst &MI, uint64_t &Size, ArrayRef<uint8_t> Bytes, uint64_t /*Address*/,
164 raw_ostream &CS) const {
165 CommentStream = &CS;
166 Size = 0;
167 int Opc = nextByte(Bytes, Size);
168 if (Opc < 0)
169 return MCDisassembler::Fail;
170 const auto *WasmInst = &InstructionTable0[Opc];
171 // If this is a prefix byte, indirect to another table.
172 if (WasmInst->ET == ET_Prefix) {
173 WasmInst = nullptr;
174 // Linear search, so far only 4 entries.
175 for (const auto &[Prefix, Table] : PrefixTable) {
176 if (Prefix == Opc) {
177 WasmInst = Table;
178 break;
179 }
180 }
181 if (!WasmInst)
182 return MCDisassembler::Fail;
183 int64_t PrefixedOpc;
184 if (!nextLEB(Val&: PrefixedOpc, Bytes, Size, Signed: false))
185 return MCDisassembler::Fail;
186 if (PrefixedOpc < 0 || PrefixedOpc >= WebAssemblyInstructionTableSize)
187 return MCDisassembler::Fail;
188 WasmInst += PrefixedOpc;
189 }
190 if (WasmInst->ET == ET_Unused)
191 return MCDisassembler::Fail;
192 // At this point we must have a valid instruction to decode.
193 assert(WasmInst->ET == ET_Instruction);
194 MI.setOpcode(WasmInst->Opcode);
195 // Parse any operands.
196 for (uint8_t OPI = 0; OPI < WasmInst->NumOperands; OPI++) {
197 auto OT = OperandTable[WasmInst->OperandStart + OPI];
198 switch (OT) {
199 // ULEB operands:
200 case WebAssembly::OPERAND_BASIC_BLOCK:
201 case WebAssembly::OPERAND_LOCAL:
202 case WebAssembly::OPERAND_GLOBAL:
203 case WebAssembly::OPERAND_FUNCTION32:
204 case WebAssembly::OPERAND_TABLE:
205 case WebAssembly::OPERAND_OFFSET32:
206 case WebAssembly::OPERAND_OFFSET64:
207 case WebAssembly::OPERAND_P2ALIGN:
208 case WebAssembly::OPERAND_TYPEINDEX:
209 case WebAssembly::OPERAND_TAG:
210 case MCOI::OPERAND_IMMEDIATE: {
211 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false))
212 return MCDisassembler::Fail;
213 if (OT == WebAssembly::OPERAND_P2ALIGN) {
214 // The byte that encodes P2align also encodes whether a memory index
215 // and/or ordering is present.
216 int64_t Val = MI.getOperand(i: MI.getNumOperands() - 1).getImm();
217 if (Val & wasm::WASM_MEMARG_HAS_MEM_ORDER) {
218 // Clear the order so we just have the alignment in this operand.
219 MI.getOperand(i: MI.getNumOperands() - 1)
220 .setImm(Val & ~wasm::WASM_MEMARG_HAS_MEM_ORDER);
221 if (Size >= Bytes.size())
222 return MCDisassembler::Fail;
223 uint8_t Order = Bytes[Size++];
224 // If we have a memory ordering, it must have been preceded by a
225 // MEMORDER operand which was added as a placeholder (because we are
226 // iterating in MI operand order which has mem order first, but this
227 // byte is encoded first).
228 assert(OPI > 0 &&
229 OperandTable[WasmInst->OperandStart + OPI - 1] ==
230 WebAssembly::OPERAND_MEMORDER &&
231 "P2ALIGN with memory order not preceded by MEMORDER");
232 if (Order == wasm::WASM_MEM_ORDER_RMW_ACQ_REL ||
233 Order == wasm::WASM_MEM_ORDER_ACQ_REL)
234 MI.getOperand(i: MI.getNumOperands() - 2)
235 .setImm(wasm::WASM_MEM_ORDER_ACQ_REL);
236 else
237 MI.getOperand(i: MI.getNumOperands() - 2)
238 .setImm(wasm::WASM_MEM_ORDER_SEQ_CST);
239 }
240 }
241 break;
242 }
243 // SLEB operands:
244 case WebAssembly::OPERAND_I32IMM:
245 case WebAssembly::OPERAND_I64IMM: {
246 if (!parseLEBImmediate(MI, Size, Bytes, Signed: true))
247 return MCDisassembler::Fail;
248 break;
249 }
250 // block_type operands:
251 case WebAssembly::OPERAND_SIGNATURE: {
252 int64_t Val;
253 uint64_t PrevSize = Size;
254 if (!nextLEB(Val, Bytes, Size, Signed: true))
255 return MCDisassembler::Fail;
256 if (Val < 0) {
257 // Negative values are single septet value types or empty types
258 if (Size != PrevSize + 1) {
259 MI.addOperand(
260 Op: MCOperand::createImm(Val: int64_t(WebAssembly::BlockType::Invalid)));
261 } else {
262 MI.addOperand(Op: MCOperand::createImm(Val: Val & 0x7f));
263 }
264 } else {
265 // We don't have access to the signature, so create a symbol without one
266 MCSymbol *Sym = getContext().createTempSymbol(Name: "typeindex", AlwaysAddSuffix: true);
267 auto *WasmSym = static_cast<MCSymbolWasm *>(Sym);
268 WasmSym->setType(wasm::WASM_SYMBOL_TYPE_FUNCTION);
269 const MCExpr *Expr = MCSymbolRefExpr::create(
270 Symbol: WasmSym, specifier: WebAssembly::S_TYPEINDEX, Ctx&: getContext());
271 MI.addOperand(Op: MCOperand::createExpr(Val: Expr));
272 }
273 break;
274 }
275 // FP operands.
276 case WebAssembly::OPERAND_F32IMM: {
277 if (!parseImmediate<float>(MI, Size, Bytes))
278 return MCDisassembler::Fail;
279 break;
280 }
281 case WebAssembly::OPERAND_F64IMM: {
282 if (!parseImmediate<double>(MI, Size, Bytes))
283 return MCDisassembler::Fail;
284 break;
285 }
286 // Vector lane operands (not LEB encoded).
287 case WebAssembly::OPERAND_VEC_I8IMM: {
288 if (!parseImmediate<uint8_t>(MI, Size, Bytes))
289 return MCDisassembler::Fail;
290 break;
291 }
292 case WebAssembly::OPERAND_MEMORDER: {
293 uint8_t Val;
294 if (OPI + 1 < WasmInst->NumOperands &&
295 OperandTable[WasmInst->OperandStart + OPI + 1] ==
296 WebAssembly::OPERAND_P2ALIGN) {
297 // If we have P2ALIGN next, it will be encoded as part of the memarg,
298 // which has not been parsed yet. Default to SEQ_CST
299 // and we will update it when we parse P2ALIGN if necessary.
300 Val = wasm::WASM_MEM_ORDER_SEQ_CST;
301 } else {
302 // atomic.fence instructions have no p2align operand.
303 if (Size >= Bytes.size())
304 return MCDisassembler::Fail;
305 Val = Bytes[Size++];
306 }
307 if (Val == wasm::WASM_MEM_ORDER_RMW_ACQ_REL ||
308 Val == wasm::WASM_MEM_ORDER_ACQ_REL)
309 MI.addOperand(Op: MCOperand::createImm(Val: wasm::WASM_MEM_ORDER_ACQ_REL));
310 else
311 MI.addOperand(Op: MCOperand::createImm(Val: wasm::WASM_MEM_ORDER_SEQ_CST));
312 break;
313 }
314 case WebAssembly::OPERAND_VEC_I16IMM: {
315 if (!parseImmediate<uint16_t>(MI, Size, Bytes))
316 return MCDisassembler::Fail;
317 break;
318 }
319 case WebAssembly::OPERAND_VEC_I32IMM: {
320 if (!parseImmediate<uint32_t>(MI, Size, Bytes))
321 return MCDisassembler::Fail;
322 break;
323 }
324 case WebAssembly::OPERAND_VEC_I64IMM: {
325 if (!parseImmediate<uint64_t>(MI, Size, Bytes))
326 return MCDisassembler::Fail;
327 break;
328 }
329 case WebAssembly::OPERAND_BRLIST: {
330 int64_t TargetTableLen;
331 if (!nextLEB(Val&: TargetTableLen, Bytes, Size, Signed: false))
332 return MCDisassembler::Fail;
333 for (int64_t I = 0; I < TargetTableLen; I++) {
334 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false))
335 return MCDisassembler::Fail;
336 }
337 // Default case.
338 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false))
339 return MCDisassembler::Fail;
340 break;
341 }
342 case WebAssembly::OPERAND_CATCH_LIST: {
343 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false))
344 return MCDisassembler::Fail;
345 int64_t NumCatches = MI.getOperand(i: MI.getNumOperands() - 1).getImm();
346 for (int64_t I = 0; I < NumCatches; I++) {
347 if (!parseImmediate<uint8_t>(MI, Size, Bytes))
348 return MCDisassembler::Fail;
349 int64_t CatchOpcode = MI.getOperand(i: MI.getNumOperands() - 1).getImm();
350 if (CatchOpcode == wasm::WASM_OPCODE_CATCH ||
351 CatchOpcode == wasm::WASM_OPCODE_CATCH_REF) {
352 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false)) // tag index
353 return MCDisassembler::Fail;
354 }
355 if (!parseLEBImmediate(MI, Size, Bytes, Signed: false)) // destination
356 return MCDisassembler::Fail;
357 }
358 break;
359 }
360 case MCOI::OPERAND_REGISTER:
361 // The tablegen header currently does not have any register operands since
362 // we use only the stack (_S) instructions.
363 // If you hit this that probably means a bad instruction definition in
364 // tablegen.
365 llvm_unreachable("Register operand in WebAssemblyDisassembler");
366 default:
367 llvm_unreachable("Unknown operand type in WebAssemblyDisassembler");
368 }
369 }
370 return MCDisassembler::Success;
371}
372