BytecodeInterpreter.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ByteReader.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Endian.h>
  10. #include <AK/MemoryStream.h>
  11. #include <AK/SIMDExtras.h>
  12. #include <LibWasm/AbstractMachine/AbstractMachine.h>
  13. #include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
  14. #include <LibWasm/AbstractMachine/Configuration.h>
  15. #include <LibWasm/AbstractMachine/Operators.h>
  16. #include <LibWasm/Opcode.h>
  17. #include <LibWasm/Printer/Printer.h>
  18. using namespace AK::SIMD;
  19. namespace Wasm {
  20. #define TRAP_IF_NOT(x) \
  21. do { \
  22. if (trap_if_not(x, #x##sv)) { \
  23. dbgln_if(WASM_TRACE_DEBUG, "Trapped because {} failed, at line {}", #x, __LINE__); \
  24. return; \
  25. } \
  26. } while (false)
  27. #define TRAP_IF_NOT_NORETURN(x) \
  28. do { \
  29. if (trap_if_not(x, #x##sv)) { \
  30. dbgln_if(WASM_TRACE_DEBUG, "Trapped because {} failed, at line {}", #x, __LINE__); \
  31. } \
  32. } while (false)
  33. void BytecodeInterpreter::interpret(Configuration& configuration)
  34. {
  35. m_trap = Empty {};
  36. auto& instructions = configuration.frame().expression().instructions();
  37. auto max_ip_value = InstructionPointer { instructions.size() };
  38. auto& current_ip_value = configuration.ip();
  39. auto const should_limit_instruction_count = configuration.should_limit_instruction_count();
  40. u64 executed_instructions = 0;
  41. while (current_ip_value < max_ip_value) {
  42. if (should_limit_instruction_count) {
  43. if (executed_instructions++ >= Constants::max_allowed_executed_instructions_per_call) [[unlikely]] {
  44. m_trap = Trap { "Exceeded maximum allowed number of instructions" };
  45. return;
  46. }
  47. }
  48. auto& instruction = instructions[current_ip_value.value()];
  49. auto old_ip = current_ip_value;
  50. interpret(configuration, current_ip_value, instruction);
  51. if (did_trap())
  52. return;
  53. if (current_ip_value == old_ip) // If no jump occurred
  54. ++current_ip_value;
  55. }
  56. }
  57. void BytecodeInterpreter::branch_to_label(Configuration& configuration, LabelIndex index)
  58. {
  59. dbgln_if(WASM_TRACE_DEBUG, "Branch to label with index {}...", index.value());
  60. auto label = configuration.nth_label(index.value());
  61. dbgln_if(WASM_TRACE_DEBUG, "...which is actually IP {}, and has {} result(s)", label->continuation().value(), label->arity());
  62. auto results = pop_values(configuration, label->arity());
  63. size_t drop_count = index.value() + 1;
  64. for (; !configuration.stack().is_empty();) {
  65. auto& entry = configuration.stack().peek();
  66. if (entry.has<Label>()) {
  67. if (--drop_count == 0)
  68. break;
  69. }
  70. configuration.stack().pop();
  71. }
  72. for (auto& result : results)
  73. configuration.stack().push(move(result));
  74. configuration.ip() = label->continuation();
  75. }
  76. template<typename ReadType, typename PushType>
  77. void BytecodeInterpreter::load_and_push(Configuration& configuration, Instruction const& instruction)
  78. {
  79. auto& address = configuration.frame().module().memories().first();
  80. auto memory = configuration.store().get(address);
  81. if (!memory) {
  82. m_trap = Trap { "Nonexistent memory" };
  83. return;
  84. }
  85. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  86. auto& entry = configuration.stack().peek();
  87. auto base = entry.get<Value>().to<i32>();
  88. if (!base.has_value()) {
  89. m_trap = Trap { "Memory access out of bounds" };
  90. return;
  91. }
  92. u64 instance_address = static_cast<u64>(bit_cast<u32>(base.value())) + arg.offset;
  93. Checked addition { instance_address };
  94. addition += sizeof(ReadType);
  95. if (addition.has_overflow() || addition.value() > memory->size()) {
  96. m_trap = Trap { "Memory access out of bounds" };
  97. dbgln("LibWasm: Memory access out of bounds (expected {} to be less than or equal to {})", instance_address + sizeof(ReadType), memory->size());
  98. return;
  99. }
  100. dbgln_if(WASM_TRACE_DEBUG, "load({} : {}) -> stack", instance_address, sizeof(ReadType));
  101. auto slice = memory->data().bytes().slice(instance_address, sizeof(ReadType));
  102. configuration.stack().peek() = Value(static_cast<PushType>(read_value<ReadType>(slice)));
  103. }
  104. template<typename TDst, typename TSrc>
  105. ALWAYS_INLINE static TDst convert_vector(TSrc v)
  106. {
  107. return __builtin_convertvector(v, TDst);
  108. }
  109. template<size_t M, size_t N, template<typename> typename SetSign>
  110. void BytecodeInterpreter::load_and_push_mxn(Configuration& configuration, Instruction const& instruction)
  111. {
  112. auto& address = configuration.frame().module().memories().first();
  113. auto memory = configuration.store().get(address);
  114. if (!memory) {
  115. m_trap = Trap { "Nonexistent memory" };
  116. return;
  117. }
  118. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  119. auto& entry = configuration.stack().peek();
  120. auto base = entry.get<Value>().to<i32>();
  121. if (!base.has_value()) {
  122. m_trap = Trap { "Memory access out of bounds" };
  123. return;
  124. }
  125. u64 instance_address = static_cast<u64>(bit_cast<u32>(base.value())) + arg.offset;
  126. Checked addition { instance_address };
  127. addition += M * N / 8;
  128. if (addition.has_overflow() || addition.value() > memory->size()) {
  129. m_trap = Trap { "Memory access out of bounds" };
  130. dbgln("LibWasm: Memory access out of bounds (expected {} to be less than or equal to {})", instance_address + M * N / 8, memory->size());
  131. return;
  132. }
  133. dbgln_if(WASM_TRACE_DEBUG, "vec-load({} : {}) -> stack", instance_address, M * N / 8);
  134. auto slice = memory->data().bytes().slice(instance_address, M * N / 8);
  135. using V64 = NativeVectorType<M, N, SetSign>;
  136. using V128 = NativeVectorType<M * 2, N, SetSign>;
  137. V64 bytes { 0 };
  138. if (bit_cast<FlatPtr>(slice.data()) % sizeof(V64) == 0)
  139. bytes = *bit_cast<V64*>(slice.data());
  140. else
  141. ByteReader::load(slice.data(), bytes);
  142. configuration.stack().peek() = Value(bit_cast<u128>(convert_vector<V128>(bytes)));
  143. }
  144. template<size_t M>
  145. void BytecodeInterpreter::load_and_push_m_splat(Configuration& configuration, Instruction const& instruction)
  146. {
  147. auto& address = configuration.frame().module().memories().first();
  148. auto memory = configuration.store().get(address);
  149. if (!memory) {
  150. m_trap = Trap { "Nonexistent memory" };
  151. return;
  152. }
  153. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  154. auto& entry = configuration.stack().peek();
  155. auto base = entry.get<Value>().to<i32>();
  156. if (!base.has_value()) {
  157. m_trap = Trap { "Memory access out of bounds" };
  158. return;
  159. }
  160. u64 instance_address = static_cast<u64>(bit_cast<u32>(base.value())) + arg.offset;
  161. Checked addition { instance_address };
  162. addition += M / 8;
  163. if (addition.has_overflow() || addition.value() > memory->size()) {
  164. m_trap = Trap { "Memory access out of bounds" };
  165. dbgln("LibWasm: Memory access out of bounds (expected {} to be less than or equal to {})", instance_address + M / 8, memory->size());
  166. return;
  167. }
  168. dbgln_if(WASM_TRACE_DEBUG, "vec-splat({} : {}) -> stack", instance_address, M / 8);
  169. auto slice = memory->data().bytes().slice(instance_address, M / 8);
  170. auto value = read_value<NativeIntegralType<M>>(slice);
  171. set_top_m_splat<M, NativeIntegralType>(configuration, value);
  172. }
  173. template<size_t M, template<size_t> typename NativeType>
  174. void BytecodeInterpreter::set_top_m_splat(Wasm::Configuration& configuration, NativeType<M> value)
  175. {
  176. auto push = [&](auto result) {
  177. configuration.stack().peek() = Value(bit_cast<u128>(result));
  178. };
  179. if constexpr (IsFloatingPoint<NativeType<32>>) {
  180. if constexpr (M == 32) // 32 -> 32x4
  181. push(expand4(value));
  182. else if constexpr (M == 64) // 64 -> 64x2
  183. push(f64x2 { value, value });
  184. else
  185. static_assert(DependentFalse<NativeType<M>>, "Invalid vector size");
  186. } else {
  187. if constexpr (M == 8) // 8 -> 8x4 -> 32x4
  188. push(expand4(bit_cast<u32>(u8x4 { value, value, value, value })));
  189. else if constexpr (M == 16) // 16 -> 16x2 -> 32x4
  190. push(expand4(bit_cast<u32>(u16x2 { value, value })));
  191. else if constexpr (M == 32) // 32 -> 32x4
  192. push(expand4(value));
  193. else if constexpr (M == 64) // 64 -> 64x2
  194. push(u64x2 { value, value });
  195. else
  196. static_assert(DependentFalse<NativeType<M>>, "Invalid vector size");
  197. }
  198. }
  199. template<size_t M, template<size_t> typename NativeType>
  200. void BytecodeInterpreter::pop_and_push_m_splat(Wasm::Configuration& configuration, Instruction const&)
  201. {
  202. using PopT = Conditional<M <= 32, NativeType<32>, NativeType<64>>;
  203. using ReadT = NativeType<M>;
  204. auto entry = configuration.stack().peek();
  205. auto value = static_cast<ReadT>(*entry.get<Value>().to<PopT>());
  206. dbgln_if(WASM_TRACE_DEBUG, "stack({}) -> splat({})", value, M);
  207. set_top_m_splat<M, NativeType>(configuration, value);
  208. }
  209. template<typename M, template<typename> typename SetSign, typename VectorType>
  210. Optional<VectorType> BytecodeInterpreter::pop_vector(Configuration& configuration)
  211. {
  212. auto value = peek_vector<M, SetSign, VectorType>(configuration);
  213. if (value.has_value())
  214. configuration.stack().pop();
  215. return value;
  216. }
  217. template<typename M, template<typename> typename SetSign, typename VectorType>
  218. Optional<VectorType> BytecodeInterpreter::peek_vector(Configuration& configuration)
  219. {
  220. auto& entry = configuration.stack().peek();
  221. auto value = entry.get<Value>().value().get_pointer<u128>();
  222. if (!value)
  223. return {};
  224. auto vector = bit_cast<VectorType>(*value);
  225. dbgln_if(WASM_TRACE_DEBUG, "stack({}) peek-> vector({:x})", *value, bit_cast<u128>(vector));
  226. return vector;
  227. }
  228. template<typename VectorType>
  229. static u128 shuffle_vector(VectorType values, VectorType indices)
  230. {
  231. auto vector = bit_cast<VectorType>(values);
  232. auto indices_vector = bit_cast<VectorType>(indices);
  233. return bit_cast<u128>(shuffle(vector, indices_vector));
  234. }
  235. void BytecodeInterpreter::call_address(Configuration& configuration, FunctionAddress address)
  236. {
  237. TRAP_IF_NOT(m_stack_info.size_free() >= Constants::minimum_stack_space_to_keep_free);
  238. auto instance = configuration.store().get(address);
  239. FunctionType const* type { nullptr };
  240. instance->visit([&](auto const& function) { type = &function.type(); });
  241. TRAP_IF_NOT(configuration.stack().entries().size() > type->parameters().size());
  242. Vector<Value> args;
  243. args.ensure_capacity(type->parameters().size());
  244. auto span = configuration.stack().entries().span().slice_from_end(type->parameters().size());
  245. for (auto& entry : span) {
  246. auto* call_argument = entry.get_pointer<Value>();
  247. TRAP_IF_NOT(call_argument);
  248. args.unchecked_append(move(*call_argument));
  249. }
  250. configuration.stack().entries().remove(configuration.stack().size() - span.size(), span.size());
  251. Result result { Trap { ""sv } };
  252. {
  253. CallFrameHandle handle { *this, configuration };
  254. result = configuration.call(*this, address, move(args));
  255. }
  256. if (result.is_trap()) {
  257. m_trap = move(result.trap());
  258. return;
  259. }
  260. if (result.is_completion()) {
  261. m_trap = move(result.completion());
  262. return;
  263. }
  264. configuration.stack().entries().ensure_capacity(configuration.stack().size() + result.values().size());
  265. for (auto& entry : result.values().in_reverse())
  266. configuration.stack().entries().unchecked_append(move(entry));
  267. }
  268. template<typename PopTypeLHS, typename PushType, typename Operator, typename PopTypeRHS>
  269. void BytecodeInterpreter::binary_numeric_operation(Configuration& configuration)
  270. {
  271. auto rhs_entry = configuration.stack().pop();
  272. auto& lhs_entry = configuration.stack().peek();
  273. auto rhs_ptr = rhs_entry.get_pointer<Value>();
  274. auto lhs_ptr = lhs_entry.get_pointer<Value>();
  275. auto rhs = rhs_ptr->to<PopTypeRHS>();
  276. auto lhs = lhs_ptr->to<PopTypeLHS>();
  277. PushType result;
  278. auto call_result = Operator {}(lhs.value(), rhs.value());
  279. if constexpr (IsSpecializationOf<decltype(call_result), AK::Result>) {
  280. if (call_result.is_error()) {
  281. trap_if_not(false, call_result.error());
  282. return;
  283. }
  284. result = call_result.release_value();
  285. } else {
  286. result = call_result;
  287. }
  288. dbgln_if(WASM_TRACE_DEBUG, "{} {} {} = {}", lhs.value(), Operator::name(), rhs.value(), result);
  289. lhs_entry = Value(result);
  290. }
  291. template<typename PopType, typename PushType, typename Operator>
  292. void BytecodeInterpreter::unary_operation(Configuration& configuration)
  293. {
  294. auto& entry = configuration.stack().peek();
  295. auto entry_ptr = entry.get_pointer<Value>();
  296. auto value = entry_ptr->to<PopType>();
  297. auto call_result = Operator {}(*value);
  298. PushType result;
  299. if constexpr (IsSpecializationOf<decltype(call_result), AK::Result>) {
  300. if (call_result.is_error()) {
  301. trap_if_not(false, call_result.error());
  302. return;
  303. }
  304. result = call_result.release_value();
  305. } else {
  306. result = call_result;
  307. }
  308. dbgln_if(WASM_TRACE_DEBUG, "map({}) {} = {}", Operator::name(), *value, result);
  309. entry = Value(result);
  310. }
  311. template<typename T>
  312. struct ConvertToRaw {
  313. T operator()(T value)
  314. {
  315. return LittleEndian<T>(value);
  316. }
  317. };
  318. template<>
  319. struct ConvertToRaw<float> {
  320. u32 operator()(float value)
  321. {
  322. ReadonlyBytes bytes { &value, sizeof(float) };
  323. FixedMemoryStream stream { bytes };
  324. auto res = stream.read_value<LittleEndian<u32>>().release_value_but_fixme_should_propagate_errors();
  325. return static_cast<u32>(res);
  326. }
  327. };
  328. template<>
  329. struct ConvertToRaw<double> {
  330. u64 operator()(double value)
  331. {
  332. ReadonlyBytes bytes { &value, sizeof(double) };
  333. FixedMemoryStream stream { bytes };
  334. auto res = stream.read_value<LittleEndian<u64>>().release_value_but_fixme_should_propagate_errors();
  335. return static_cast<u64>(res);
  336. }
  337. };
  338. template<typename PopT, typename StoreT>
  339. void BytecodeInterpreter::pop_and_store(Configuration& configuration, Instruction const& instruction)
  340. {
  341. auto entry = configuration.stack().pop();
  342. auto value = ConvertToRaw<StoreT> {}(*entry.get<Value>().to<PopT>());
  343. dbgln_if(WASM_TRACE_DEBUG, "stack({}) -> temporary({}b)", value, sizeof(StoreT));
  344. auto base_entry = configuration.stack().pop();
  345. auto base = base_entry.get<Value>().to<i32>();
  346. store_to_memory(configuration, instruction, { &value, sizeof(StoreT) }, *base);
  347. }
  348. void BytecodeInterpreter::store_to_memory(Configuration& configuration, Instruction const& instruction, ReadonlyBytes data, i32 base)
  349. {
  350. auto& address = configuration.frame().module().memories().first();
  351. auto memory = configuration.store().get(address);
  352. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  353. u64 instance_address = static_cast<u64>(bit_cast<u32>(base)) + arg.offset;
  354. Checked addition { instance_address };
  355. addition += data.size();
  356. if (addition.has_overflow() || addition.value() > memory->size()) {
  357. m_trap = Trap { "Memory access out of bounds" };
  358. dbgln("LibWasm: Memory access out of bounds (expected 0 <= {} and {} <= {})", instance_address, instance_address + data.size(), memory->size());
  359. return;
  360. }
  361. dbgln_if(WASM_TRACE_DEBUG, "temporary({}b) -> store({})", data.size(), instance_address);
  362. data.copy_to(memory->data().bytes().slice(instance_address, data.size()));
  363. }
  364. template<typename T>
  365. T BytecodeInterpreter::read_value(ReadonlyBytes data)
  366. {
  367. FixedMemoryStream stream { data };
  368. auto value_or_error = stream.read_value<LittleEndian<T>>();
  369. if (value_or_error.is_error()) {
  370. dbgln("Read from {} failed", data.data());
  371. m_trap = Trap { "Read from memory failed" };
  372. }
  373. return value_or_error.release_value();
  374. }
  375. template<>
  376. float BytecodeInterpreter::read_value<float>(ReadonlyBytes data)
  377. {
  378. FixedMemoryStream stream { data };
  379. auto raw_value_or_error = stream.read_value<LittleEndian<u32>>();
  380. if (raw_value_or_error.is_error())
  381. m_trap = Trap { "Read from memory failed" };
  382. auto raw_value = raw_value_or_error.release_value();
  383. return bit_cast<float>(static_cast<u32>(raw_value));
  384. }
  385. template<>
  386. double BytecodeInterpreter::read_value<double>(ReadonlyBytes data)
  387. {
  388. FixedMemoryStream stream { data };
  389. auto raw_value_or_error = stream.read_value<LittleEndian<u64>>();
  390. if (raw_value_or_error.is_error())
  391. m_trap = Trap { "Read from memory failed" };
  392. auto raw_value = raw_value_or_error.release_value();
  393. return bit_cast<double>(static_cast<u64>(raw_value));
  394. }
  395. template<typename V, typename T>
  396. MakeSigned<T> BytecodeInterpreter::checked_signed_truncate(V value)
  397. {
  398. if (isnan(value) || isinf(value)) { // "undefined", let's just trap.
  399. m_trap = Trap { "Signed truncation undefined behavior" };
  400. return 0;
  401. }
  402. double truncated;
  403. if constexpr (IsSame<float, V>)
  404. truncated = truncf(value);
  405. else
  406. truncated = trunc(value);
  407. using SignedT = MakeSigned<T>;
  408. if (NumericLimits<SignedT>::min() <= truncated && static_cast<double>(NumericLimits<SignedT>::max()) >= truncated)
  409. return static_cast<SignedT>(truncated);
  410. dbgln_if(WASM_TRACE_DEBUG, "Truncate out of range error");
  411. m_trap = Trap { "Signed truncation out of range" };
  412. return true;
  413. }
  414. template<typename V, typename T>
  415. MakeUnsigned<T> BytecodeInterpreter::checked_unsigned_truncate(V value)
  416. {
  417. if (isnan(value) || isinf(value)) { // "undefined", let's just trap.
  418. m_trap = Trap { "Unsigned truncation undefined behavior" };
  419. return 0;
  420. }
  421. double truncated;
  422. if constexpr (IsSame<float, V>)
  423. truncated = truncf(value);
  424. else
  425. truncated = trunc(value);
  426. using UnsignedT = MakeUnsigned<T>;
  427. if (NumericLimits<UnsignedT>::min() <= truncated && static_cast<double>(NumericLimits<UnsignedT>::max()) >= truncated)
  428. return static_cast<UnsignedT>(truncated);
  429. dbgln_if(WASM_TRACE_DEBUG, "Truncate out of range error");
  430. m_trap = Trap { "Unsigned truncation out of range" };
  431. return true;
  432. }
  433. Vector<Value> BytecodeInterpreter::pop_values(Configuration& configuration, size_t count)
  434. {
  435. Vector<Value> results;
  436. results.resize(count);
  437. for (size_t i = 0; i < count; ++i) {
  438. auto top_of_stack = configuration.stack().pop();
  439. if (auto value = top_of_stack.get_pointer<Value>())
  440. results[i] = move(*value);
  441. else
  442. TRAP_IF_NOT_NORETURN(value);
  443. }
  444. return results;
  445. }
  446. void BytecodeInterpreter::interpret(Configuration& configuration, InstructionPointer& ip, Instruction const& instruction)
  447. {
  448. dbgln_if(WASM_TRACE_DEBUG, "Executing instruction {} at ip {}", instruction_name(instruction.opcode()), ip.value());
  449. switch (instruction.opcode().value()) {
  450. case Instructions::unreachable.value():
  451. m_trap = Trap { "Unreachable" };
  452. return;
  453. case Instructions::nop.value():
  454. return;
  455. case Instructions::local_get.value():
  456. configuration.stack().push(Value(configuration.frame().locals()[instruction.arguments().get<LocalIndex>().value()]));
  457. return;
  458. case Instructions::local_set.value(): {
  459. auto entry = configuration.stack().pop();
  460. configuration.frame().locals()[instruction.arguments().get<LocalIndex>().value()] = move(entry.get<Value>());
  461. return;
  462. }
  463. case Instructions::i32_const.value():
  464. configuration.stack().push(Value(ValueType { ValueType::I32 }, static_cast<i64>(instruction.arguments().get<i32>())));
  465. return;
  466. case Instructions::i64_const.value():
  467. configuration.stack().push(Value(ValueType { ValueType::I64 }, instruction.arguments().get<i64>()));
  468. return;
  469. case Instructions::f32_const.value():
  470. configuration.stack().push(Value(ValueType { ValueType::F32 }, static_cast<double>(instruction.arguments().get<float>())));
  471. return;
  472. case Instructions::f64_const.value():
  473. configuration.stack().push(Value(ValueType { ValueType::F64 }, instruction.arguments().get<double>()));
  474. return;
  475. case Instructions::block.value(): {
  476. size_t arity = 0;
  477. size_t parameter_count = 0;
  478. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  479. switch (args.block_type.kind()) {
  480. case BlockType::Empty:
  481. break;
  482. case BlockType::Type:
  483. arity = 1;
  484. break;
  485. case BlockType::Index: {
  486. auto& type = configuration.frame().module().types()[args.block_type.type_index().value()];
  487. arity = type.results().size();
  488. parameter_count = type.parameters().size();
  489. }
  490. }
  491. configuration.stack().entries().insert(configuration.stack().size() - parameter_count, Label(arity, args.end_ip));
  492. return;
  493. }
  494. case Instructions::loop.value(): {
  495. size_t arity = 0;
  496. size_t parameter_count = 0;
  497. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  498. switch (args.block_type.kind()) {
  499. case BlockType::Empty:
  500. break;
  501. case BlockType::Type:
  502. arity = 1;
  503. break;
  504. case BlockType::Index: {
  505. auto& type = configuration.frame().module().types()[args.block_type.type_index().value()];
  506. arity = type.results().size();
  507. parameter_count = type.parameters().size();
  508. }
  509. }
  510. configuration.stack().entries().insert(configuration.stack().size() - parameter_count, Label(arity, ip.value() + 1));
  511. return;
  512. }
  513. case Instructions::if_.value(): {
  514. size_t arity = 0;
  515. size_t parameter_count = 0;
  516. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  517. switch (args.block_type.kind()) {
  518. case BlockType::Empty:
  519. break;
  520. case BlockType::Type:
  521. arity = 1;
  522. break;
  523. case BlockType::Index: {
  524. auto& type = configuration.frame().module().types()[args.block_type.type_index().value()];
  525. arity = type.results().size();
  526. parameter_count = type.parameters().size();
  527. }
  528. }
  529. auto entry = configuration.stack().pop();
  530. auto value = entry.get<Value>().to<i32>();
  531. auto end_label = Label(arity, args.end_ip.value());
  532. if (value.value() == 0) {
  533. if (args.else_ip.has_value()) {
  534. configuration.ip() = args.else_ip.value();
  535. configuration.stack().entries().insert(configuration.stack().size() - parameter_count, end_label);
  536. } else {
  537. configuration.ip() = args.end_ip.value() + 1;
  538. }
  539. } else {
  540. configuration.stack().entries().insert(configuration.stack().size() - parameter_count, end_label);
  541. }
  542. return;
  543. }
  544. case Instructions::structured_end.value():
  545. case Instructions::structured_else.value(): {
  546. auto index = configuration.nth_label_index(0);
  547. auto label = configuration.stack().entries()[*index].get<Label>();
  548. configuration.stack().entries().remove(*index, 1);
  549. if (instruction.opcode() == Instructions::structured_end)
  550. return;
  551. // Jump to the end label
  552. configuration.ip() = label.continuation();
  553. return;
  554. }
  555. case Instructions::return_.value(): {
  556. auto& frame = configuration.frame();
  557. Checked checked_index { configuration.stack().size() };
  558. checked_index -= frame.arity();
  559. VERIFY(!checked_index.has_overflow());
  560. auto index = checked_index.value();
  561. size_t i = 1;
  562. for (; i <= index; ++i) {
  563. auto& entry = configuration.stack().entries()[index - i];
  564. if (entry.has<Label>()) {
  565. if (configuration.stack().entries()[index - i - 1].has<Frame>())
  566. break;
  567. }
  568. }
  569. configuration.stack().entries().remove(index - i + 1, i - 1);
  570. // Jump past the call/indirect instruction
  571. configuration.ip() = configuration.frame().expression().instructions().size();
  572. return;
  573. }
  574. case Instructions::br.value():
  575. return branch_to_label(configuration, instruction.arguments().get<LabelIndex>());
  576. case Instructions::br_if.value(): {
  577. auto entry = configuration.stack().pop();
  578. if (entry.get<Value>().to<i32>().value_or(0) == 0)
  579. return;
  580. return branch_to_label(configuration, instruction.arguments().get<LabelIndex>());
  581. }
  582. case Instructions::br_table.value(): {
  583. auto& arguments = instruction.arguments().get<Instruction::TableBranchArgs>();
  584. auto entry = configuration.stack().pop();
  585. auto maybe_i = entry.get<Value>().to<i32>();
  586. if (0 <= *maybe_i) {
  587. size_t i = *maybe_i;
  588. if (i < arguments.labels.size())
  589. return branch_to_label(configuration, arguments.labels[i]);
  590. }
  591. return branch_to_label(configuration, arguments.default_);
  592. }
  593. case Instructions::call.value(): {
  594. auto index = instruction.arguments().get<FunctionIndex>();
  595. auto address = configuration.frame().module().functions()[index.value()];
  596. dbgln_if(WASM_TRACE_DEBUG, "call({})", address.value());
  597. call_address(configuration, address);
  598. return;
  599. }
  600. case Instructions::call_indirect.value(): {
  601. auto& args = instruction.arguments().get<Instruction::IndirectCallArgs>();
  602. auto table_address = configuration.frame().module().tables()[args.table.value()];
  603. auto table_instance = configuration.store().get(table_address);
  604. auto entry = configuration.stack().pop();
  605. auto index = entry.get<Value>().to<i32>();
  606. TRAP_IF_NOT(index.value() >= 0);
  607. TRAP_IF_NOT(static_cast<size_t>(index.value()) < table_instance->elements().size());
  608. auto element = table_instance->elements()[index.value()];
  609. TRAP_IF_NOT(element.has_value());
  610. TRAP_IF_NOT(element->ref().has<Reference::Func>());
  611. auto address = element->ref().get<Reference::Func>().address;
  612. dbgln_if(WASM_TRACE_DEBUG, "call_indirect({} -> {})", index.value(), address.value());
  613. call_address(configuration, address);
  614. return;
  615. }
  616. case Instructions::i32_load.value():
  617. return load_and_push<i32, i32>(configuration, instruction);
  618. case Instructions::i64_load.value():
  619. return load_and_push<i64, i64>(configuration, instruction);
  620. case Instructions::f32_load.value():
  621. return load_and_push<float, float>(configuration, instruction);
  622. case Instructions::f64_load.value():
  623. return load_and_push<double, double>(configuration, instruction);
  624. case Instructions::i32_load8_s.value():
  625. return load_and_push<i8, i32>(configuration, instruction);
  626. case Instructions::i32_load8_u.value():
  627. return load_and_push<u8, i32>(configuration, instruction);
  628. case Instructions::i32_load16_s.value():
  629. return load_and_push<i16, i32>(configuration, instruction);
  630. case Instructions::i32_load16_u.value():
  631. return load_and_push<u16, i32>(configuration, instruction);
  632. case Instructions::i64_load8_s.value():
  633. return load_and_push<i8, i64>(configuration, instruction);
  634. case Instructions::i64_load8_u.value():
  635. return load_and_push<u8, i64>(configuration, instruction);
  636. case Instructions::i64_load16_s.value():
  637. return load_and_push<i16, i64>(configuration, instruction);
  638. case Instructions::i64_load16_u.value():
  639. return load_and_push<u16, i64>(configuration, instruction);
  640. case Instructions::i64_load32_s.value():
  641. return load_and_push<i32, i64>(configuration, instruction);
  642. case Instructions::i64_load32_u.value():
  643. return load_and_push<u32, i64>(configuration, instruction);
  644. case Instructions::i32_store.value():
  645. return pop_and_store<i32, i32>(configuration, instruction);
  646. case Instructions::i64_store.value():
  647. return pop_and_store<i64, i64>(configuration, instruction);
  648. case Instructions::f32_store.value():
  649. return pop_and_store<float, float>(configuration, instruction);
  650. case Instructions::f64_store.value():
  651. return pop_and_store<double, double>(configuration, instruction);
  652. case Instructions::i32_store8.value():
  653. return pop_and_store<i32, i8>(configuration, instruction);
  654. case Instructions::i32_store16.value():
  655. return pop_and_store<i32, i16>(configuration, instruction);
  656. case Instructions::i64_store8.value():
  657. return pop_and_store<i64, i8>(configuration, instruction);
  658. case Instructions::i64_store16.value():
  659. return pop_and_store<i64, i16>(configuration, instruction);
  660. case Instructions::i64_store32.value():
  661. return pop_and_store<i64, i32>(configuration, instruction);
  662. case Instructions::local_tee.value(): {
  663. auto& entry = configuration.stack().peek();
  664. auto value = entry.get<Value>();
  665. auto local_index = instruction.arguments().get<LocalIndex>();
  666. dbgln_if(WASM_TRACE_DEBUG, "stack:peek -> locals({})", local_index.value());
  667. configuration.frame().locals()[local_index.value()] = move(value);
  668. return;
  669. }
  670. case Instructions::global_get.value(): {
  671. auto global_index = instruction.arguments().get<GlobalIndex>();
  672. auto address = configuration.frame().module().globals()[global_index.value()];
  673. dbgln_if(WASM_TRACE_DEBUG, "global({}) -> stack", address.value());
  674. auto global = configuration.store().get(address);
  675. configuration.stack().push(Value(global->value()));
  676. return;
  677. }
  678. case Instructions::global_set.value(): {
  679. auto global_index = instruction.arguments().get<GlobalIndex>();
  680. auto address = configuration.frame().module().globals()[global_index.value()];
  681. auto entry = configuration.stack().pop();
  682. auto value = entry.get<Value>();
  683. dbgln_if(WASM_TRACE_DEBUG, "stack -> global({})", address.value());
  684. auto global = configuration.store().get(address);
  685. global->set_value(move(value));
  686. return;
  687. }
  688. case Instructions::memory_size.value(): {
  689. auto address = configuration.frame().module().memories()[0];
  690. auto instance = configuration.store().get(address);
  691. auto pages = instance->size() / Constants::page_size;
  692. dbgln_if(WASM_TRACE_DEBUG, "memory.size -> stack({})", pages);
  693. configuration.stack().push(Value((i32)pages));
  694. return;
  695. }
  696. case Instructions::memory_grow.value(): {
  697. auto address = configuration.frame().module().memories()[0];
  698. auto instance = configuration.store().get(address);
  699. i32 old_pages = instance->size() / Constants::page_size;
  700. auto& entry = configuration.stack().peek();
  701. auto new_pages = entry.get<Value>().to<i32>();
  702. dbgln_if(WASM_TRACE_DEBUG, "memory.grow({}), previously {} pages...", *new_pages, old_pages);
  703. if (instance->grow(new_pages.value() * Constants::page_size))
  704. configuration.stack().peek() = Value((i32)old_pages);
  705. else
  706. configuration.stack().peek() = Value((i32)-1);
  707. return;
  708. }
  709. // https://webassembly.github.io/spec/core/bikeshed/#exec-memory-fill
  710. case Instructions::memory_fill.value(): {
  711. auto address = configuration.frame().module().memories()[0];
  712. auto instance = configuration.store().get(address);
  713. auto count = configuration.stack().pop().get<Value>().to<i32>().value();
  714. auto value = configuration.stack().pop().get<Value>().to<i32>().value();
  715. auto destination_offset = configuration.stack().pop().get<Value>().to<i32>().value();
  716. TRAP_IF_NOT(static_cast<size_t>(destination_offset + count) <= instance->data().size());
  717. if (count == 0)
  718. return;
  719. Instruction synthetic_store_instruction {
  720. Instructions::i32_store8,
  721. Instruction::MemoryArgument { 0, 0 }
  722. };
  723. for (auto i = 0; i < count; ++i) {
  724. store_to_memory(configuration, synthetic_store_instruction, { &value, sizeof(value) }, destination_offset);
  725. }
  726. return;
  727. }
  728. // https://webassembly.github.io/spec/core/bikeshed/#exec-memory-copy
  729. case Instructions::memory_copy.value(): {
  730. auto address = configuration.frame().module().memories()[0];
  731. auto instance = configuration.store().get(address);
  732. auto count = configuration.stack().pop().get<Value>().to<i32>().value();
  733. auto source_offset = configuration.stack().pop().get<Value>().to<i32>().value();
  734. auto destination_offset = configuration.stack().pop().get<Value>().to<i32>().value();
  735. TRAP_IF_NOT(static_cast<size_t>(source_offset + count) <= instance->data().size());
  736. TRAP_IF_NOT(static_cast<size_t>(destination_offset + count) <= instance->data().size());
  737. if (count == 0)
  738. return;
  739. Instruction synthetic_store_instruction {
  740. Instructions::i32_store8,
  741. Instruction::MemoryArgument { 0, 0 }
  742. };
  743. if (destination_offset <= source_offset) {
  744. for (auto i = 0; i < count; ++i) {
  745. auto value = instance->data()[source_offset + i];
  746. store_to_memory(configuration, synthetic_store_instruction, { &value, sizeof(value) }, destination_offset + i);
  747. }
  748. } else {
  749. for (auto i = count - 1; i >= 0; --i) {
  750. auto value = instance->data()[source_offset + i];
  751. store_to_memory(configuration, synthetic_store_instruction, { &value, sizeof(value) }, destination_offset + i);
  752. }
  753. }
  754. return;
  755. }
  756. // https://webassembly.github.io/spec/core/bikeshed/#exec-memory-init
  757. case Instructions::memory_init.value(): {
  758. auto data_index = instruction.arguments().get<DataIndex>();
  759. auto& data_address = configuration.frame().module().datas()[data_index.value()];
  760. auto& data = *configuration.store().get(data_address);
  761. auto count = *configuration.stack().pop().get<Value>().to<i32>();
  762. auto source_offset = *configuration.stack().pop().get<Value>().to<i32>();
  763. auto destination_offset = *configuration.stack().pop().get<Value>().to<i32>();
  764. TRAP_IF_NOT(count > 0);
  765. TRAP_IF_NOT(source_offset + count > 0);
  766. TRAP_IF_NOT(static_cast<size_t>(source_offset + count) <= data.size());
  767. Instruction synthetic_store_instruction {
  768. Instructions::i32_store8,
  769. Instruction::MemoryArgument { 0, 0 }
  770. };
  771. for (size_t i = 0; i < (size_t)count; ++i) {
  772. auto value = data.data()[source_offset + i];
  773. store_to_memory(configuration, synthetic_store_instruction, { &value, sizeof(value) }, destination_offset + i);
  774. }
  775. return;
  776. }
  777. // https://webassembly.github.io/spec/core/bikeshed/#exec-data-drop
  778. case Instructions::data_drop.value(): {
  779. auto data_index = instruction.arguments().get<DataIndex>();
  780. auto data_address = configuration.frame().module().datas()[data_index.value()];
  781. *configuration.store().get(data_address) = DataInstance({});
  782. return;
  783. }
  784. case Instructions::table_get.value():
  785. case Instructions::table_set.value():
  786. goto unimplemented;
  787. case Instructions::ref_null.value(): {
  788. auto type = instruction.arguments().get<ValueType>();
  789. configuration.stack().push(Value(Reference(Reference::Null { type })));
  790. return;
  791. };
  792. case Instructions::ref_func.value(): {
  793. auto index = instruction.arguments().get<FunctionIndex>().value();
  794. auto& functions = configuration.frame().module().functions();
  795. auto address = functions[index];
  796. configuration.stack().push(Value(ValueType(ValueType::FunctionReference), address.value()));
  797. return;
  798. }
  799. case Instructions::ref_is_null.value(): {
  800. auto top = configuration.stack().peek().get_pointer<Value>();
  801. TRAP_IF_NOT(top->type().is_reference());
  802. auto is_null = top->to<Reference::Null>().has_value();
  803. configuration.stack().peek() = Value(ValueType(ValueType::I32), static_cast<u64>(is_null ? 1 : 0));
  804. return;
  805. }
  806. case Instructions::drop.value():
  807. configuration.stack().pop();
  808. return;
  809. case Instructions::select.value():
  810. case Instructions::select_typed.value(): {
  811. // Note: The type seems to only be used for validation.
  812. auto entry = configuration.stack().pop();
  813. auto value = entry.get<Value>().to<i32>();
  814. dbgln_if(WASM_TRACE_DEBUG, "select({})", value.value());
  815. auto rhs_entry = configuration.stack().pop();
  816. auto& lhs_entry = configuration.stack().peek();
  817. auto rhs = move(rhs_entry.get<Value>());
  818. auto lhs = move(lhs_entry.get<Value>());
  819. configuration.stack().peek() = value.value() != 0 ? move(lhs) : move(rhs);
  820. return;
  821. }
  822. case Instructions::i32_eqz.value():
  823. return unary_operation<i32, i32, Operators::EqualsZero>(configuration);
  824. case Instructions::i32_eq.value():
  825. return binary_numeric_operation<i32, i32, Operators::Equals>(configuration);
  826. case Instructions::i32_ne.value():
  827. return binary_numeric_operation<i32, i32, Operators::NotEquals>(configuration);
  828. case Instructions::i32_lts.value():
  829. return binary_numeric_operation<i32, i32, Operators::LessThan>(configuration);
  830. case Instructions::i32_ltu.value():
  831. return binary_numeric_operation<u32, i32, Operators::LessThan>(configuration);
  832. case Instructions::i32_gts.value():
  833. return binary_numeric_operation<i32, i32, Operators::GreaterThan>(configuration);
  834. case Instructions::i32_gtu.value():
  835. return binary_numeric_operation<u32, i32, Operators::GreaterThan>(configuration);
  836. case Instructions::i32_les.value():
  837. return binary_numeric_operation<i32, i32, Operators::LessThanOrEquals>(configuration);
  838. case Instructions::i32_leu.value():
  839. return binary_numeric_operation<u32, i32, Operators::LessThanOrEquals>(configuration);
  840. case Instructions::i32_ges.value():
  841. return binary_numeric_operation<i32, i32, Operators::GreaterThanOrEquals>(configuration);
  842. case Instructions::i32_geu.value():
  843. return binary_numeric_operation<u32, i32, Operators::GreaterThanOrEquals>(configuration);
  844. case Instructions::i64_eqz.value():
  845. return unary_operation<i64, i32, Operators::EqualsZero>(configuration);
  846. case Instructions::i64_eq.value():
  847. return binary_numeric_operation<i64, i32, Operators::Equals>(configuration);
  848. case Instructions::i64_ne.value():
  849. return binary_numeric_operation<i64, i32, Operators::NotEquals>(configuration);
  850. case Instructions::i64_lts.value():
  851. return binary_numeric_operation<i64, i32, Operators::LessThan>(configuration);
  852. case Instructions::i64_ltu.value():
  853. return binary_numeric_operation<u64, i32, Operators::LessThan>(configuration);
  854. case Instructions::i64_gts.value():
  855. return binary_numeric_operation<i64, i32, Operators::GreaterThan>(configuration);
  856. case Instructions::i64_gtu.value():
  857. return binary_numeric_operation<u64, i32, Operators::GreaterThan>(configuration);
  858. case Instructions::i64_les.value():
  859. return binary_numeric_operation<i64, i32, Operators::LessThanOrEquals>(configuration);
  860. case Instructions::i64_leu.value():
  861. return binary_numeric_operation<u64, i32, Operators::LessThanOrEquals>(configuration);
  862. case Instructions::i64_ges.value():
  863. return binary_numeric_operation<i64, i32, Operators::GreaterThanOrEquals>(configuration);
  864. case Instructions::i64_geu.value():
  865. return binary_numeric_operation<u64, i32, Operators::GreaterThanOrEquals>(configuration);
  866. case Instructions::f32_eq.value():
  867. return binary_numeric_operation<float, i32, Operators::Equals>(configuration);
  868. case Instructions::f32_ne.value():
  869. return binary_numeric_operation<float, i32, Operators::NotEquals>(configuration);
  870. case Instructions::f32_lt.value():
  871. return binary_numeric_operation<float, i32, Operators::LessThan>(configuration);
  872. case Instructions::f32_gt.value():
  873. return binary_numeric_operation<float, i32, Operators::GreaterThan>(configuration);
  874. case Instructions::f32_le.value():
  875. return binary_numeric_operation<float, i32, Operators::LessThanOrEquals>(configuration);
  876. case Instructions::f32_ge.value():
  877. return binary_numeric_operation<float, i32, Operators::GreaterThanOrEquals>(configuration);
  878. case Instructions::f64_eq.value():
  879. return binary_numeric_operation<double, i32, Operators::Equals>(configuration);
  880. case Instructions::f64_ne.value():
  881. return binary_numeric_operation<double, i32, Operators::NotEquals>(configuration);
  882. case Instructions::f64_lt.value():
  883. return binary_numeric_operation<double, i32, Operators::LessThan>(configuration);
  884. case Instructions::f64_gt.value():
  885. return binary_numeric_operation<double, i32, Operators::GreaterThan>(configuration);
  886. case Instructions::f64_le.value():
  887. return binary_numeric_operation<double, i32, Operators::LessThanOrEquals>(configuration);
  888. case Instructions::f64_ge.value():
  889. return binary_numeric_operation<double, i32, Operators::GreaterThanOrEquals>(configuration);
  890. case Instructions::i32_clz.value():
  891. return unary_operation<i32, i32, Operators::CountLeadingZeros>(configuration);
  892. case Instructions::i32_ctz.value():
  893. return unary_operation<i32, i32, Operators::CountTrailingZeros>(configuration);
  894. case Instructions::i32_popcnt.value():
  895. return unary_operation<i32, i32, Operators::PopCount>(configuration);
  896. case Instructions::i32_add.value():
  897. return binary_numeric_operation<u32, i32, Operators::Add>(configuration);
  898. case Instructions::i32_sub.value():
  899. return binary_numeric_operation<u32, i32, Operators::Subtract>(configuration);
  900. case Instructions::i32_mul.value():
  901. return binary_numeric_operation<u32, i32, Operators::Multiply>(configuration);
  902. case Instructions::i32_divs.value():
  903. return binary_numeric_operation<i32, i32, Operators::Divide>(configuration);
  904. case Instructions::i32_divu.value():
  905. return binary_numeric_operation<u32, i32, Operators::Divide>(configuration);
  906. case Instructions::i32_rems.value():
  907. return binary_numeric_operation<i32, i32, Operators::Modulo>(configuration);
  908. case Instructions::i32_remu.value():
  909. return binary_numeric_operation<u32, i32, Operators::Modulo>(configuration);
  910. case Instructions::i32_and.value():
  911. return binary_numeric_operation<i32, i32, Operators::BitAnd>(configuration);
  912. case Instructions::i32_or.value():
  913. return binary_numeric_operation<i32, i32, Operators::BitOr>(configuration);
  914. case Instructions::i32_xor.value():
  915. return binary_numeric_operation<i32, i32, Operators::BitXor>(configuration);
  916. case Instructions::i32_shl.value():
  917. return binary_numeric_operation<u32, i32, Operators::BitShiftLeft>(configuration);
  918. case Instructions::i32_shrs.value():
  919. return binary_numeric_operation<i32, i32, Operators::BitShiftRight>(configuration);
  920. case Instructions::i32_shru.value():
  921. return binary_numeric_operation<u32, i32, Operators::BitShiftRight>(configuration);
  922. case Instructions::i32_rotl.value():
  923. return binary_numeric_operation<u32, i32, Operators::BitRotateLeft>(configuration);
  924. case Instructions::i32_rotr.value():
  925. return binary_numeric_operation<u32, i32, Operators::BitRotateRight>(configuration);
  926. case Instructions::i64_clz.value():
  927. return unary_operation<i64, i64, Operators::CountLeadingZeros>(configuration);
  928. case Instructions::i64_ctz.value():
  929. return unary_operation<i64, i64, Operators::CountTrailingZeros>(configuration);
  930. case Instructions::i64_popcnt.value():
  931. return unary_operation<i64, i64, Operators::PopCount>(configuration);
  932. case Instructions::i64_add.value():
  933. return binary_numeric_operation<u64, i64, Operators::Add>(configuration);
  934. case Instructions::i64_sub.value():
  935. return binary_numeric_operation<u64, i64, Operators::Subtract>(configuration);
  936. case Instructions::i64_mul.value():
  937. return binary_numeric_operation<u64, i64, Operators::Multiply>(configuration);
  938. case Instructions::i64_divs.value():
  939. return binary_numeric_operation<i64, i64, Operators::Divide>(configuration);
  940. case Instructions::i64_divu.value():
  941. return binary_numeric_operation<u64, i64, Operators::Divide>(configuration);
  942. case Instructions::i64_rems.value():
  943. return binary_numeric_operation<i64, i64, Operators::Modulo>(configuration);
  944. case Instructions::i64_remu.value():
  945. return binary_numeric_operation<u64, i64, Operators::Modulo>(configuration);
  946. case Instructions::i64_and.value():
  947. return binary_numeric_operation<i64, i64, Operators::BitAnd>(configuration);
  948. case Instructions::i64_or.value():
  949. return binary_numeric_operation<i64, i64, Operators::BitOr>(configuration);
  950. case Instructions::i64_xor.value():
  951. return binary_numeric_operation<i64, i64, Operators::BitXor>(configuration);
  952. case Instructions::i64_shl.value():
  953. return binary_numeric_operation<u64, i64, Operators::BitShiftLeft>(configuration);
  954. case Instructions::i64_shrs.value():
  955. return binary_numeric_operation<i64, i64, Operators::BitShiftRight>(configuration);
  956. case Instructions::i64_shru.value():
  957. return binary_numeric_operation<u64, i64, Operators::BitShiftRight>(configuration);
  958. case Instructions::i64_rotl.value():
  959. return binary_numeric_operation<u64, i64, Operators::BitRotateLeft>(configuration);
  960. case Instructions::i64_rotr.value():
  961. return binary_numeric_operation<u64, i64, Operators::BitRotateRight>(configuration);
  962. case Instructions::f32_abs.value():
  963. return unary_operation<float, float, Operators::Absolute>(configuration);
  964. case Instructions::f32_neg.value():
  965. return unary_operation<float, float, Operators::Negate>(configuration);
  966. case Instructions::f32_ceil.value():
  967. return unary_operation<float, float, Operators::Ceil>(configuration);
  968. case Instructions::f32_floor.value():
  969. return unary_operation<float, float, Operators::Floor>(configuration);
  970. case Instructions::f32_trunc.value():
  971. return unary_operation<float, float, Operators::Truncate>(configuration);
  972. case Instructions::f32_nearest.value():
  973. return unary_operation<float, float, Operators::NearbyIntegral>(configuration);
  974. case Instructions::f32_sqrt.value():
  975. return unary_operation<float, float, Operators::SquareRoot>(configuration);
  976. case Instructions::f32_add.value():
  977. return binary_numeric_operation<float, float, Operators::Add>(configuration);
  978. case Instructions::f32_sub.value():
  979. return binary_numeric_operation<float, float, Operators::Subtract>(configuration);
  980. case Instructions::f32_mul.value():
  981. return binary_numeric_operation<float, float, Operators::Multiply>(configuration);
  982. case Instructions::f32_div.value():
  983. return binary_numeric_operation<float, float, Operators::Divide>(configuration);
  984. case Instructions::f32_min.value():
  985. return binary_numeric_operation<float, float, Operators::Minimum>(configuration);
  986. case Instructions::f32_max.value():
  987. return binary_numeric_operation<float, float, Operators::Maximum>(configuration);
  988. case Instructions::f32_copysign.value():
  989. return binary_numeric_operation<float, float, Operators::CopySign>(configuration);
  990. case Instructions::f64_abs.value():
  991. return unary_operation<double, double, Operators::Absolute>(configuration);
  992. case Instructions::f64_neg.value():
  993. return unary_operation<double, double, Operators::Negate>(configuration);
  994. case Instructions::f64_ceil.value():
  995. return unary_operation<double, double, Operators::Ceil>(configuration);
  996. case Instructions::f64_floor.value():
  997. return unary_operation<double, double, Operators::Floor>(configuration);
  998. case Instructions::f64_trunc.value():
  999. return unary_operation<double, double, Operators::Truncate>(configuration);
  1000. case Instructions::f64_nearest.value():
  1001. return unary_operation<double, double, Operators::NearbyIntegral>(configuration);
  1002. case Instructions::f64_sqrt.value():
  1003. return unary_operation<double, double, Operators::SquareRoot>(configuration);
  1004. case Instructions::f64_add.value():
  1005. return binary_numeric_operation<double, double, Operators::Add>(configuration);
  1006. case Instructions::f64_sub.value():
  1007. return binary_numeric_operation<double, double, Operators::Subtract>(configuration);
  1008. case Instructions::f64_mul.value():
  1009. return binary_numeric_operation<double, double, Operators::Multiply>(configuration);
  1010. case Instructions::f64_div.value():
  1011. return binary_numeric_operation<double, double, Operators::Divide>(configuration);
  1012. case Instructions::f64_min.value():
  1013. return binary_numeric_operation<double, double, Operators::Minimum>(configuration);
  1014. case Instructions::f64_max.value():
  1015. return binary_numeric_operation<double, double, Operators::Maximum>(configuration);
  1016. case Instructions::f64_copysign.value():
  1017. return binary_numeric_operation<double, double, Operators::CopySign>(configuration);
  1018. case Instructions::i32_wrap_i64.value():
  1019. return unary_operation<i64, i32, Operators::Wrap<i32>>(configuration);
  1020. case Instructions::i32_trunc_sf32.value():
  1021. return unary_operation<float, i32, Operators::CheckedTruncate<i32>>(configuration);
  1022. case Instructions::i32_trunc_uf32.value():
  1023. return unary_operation<float, i32, Operators::CheckedTruncate<u32>>(configuration);
  1024. case Instructions::i32_trunc_sf64.value():
  1025. return unary_operation<double, i32, Operators::CheckedTruncate<i32>>(configuration);
  1026. case Instructions::i32_trunc_uf64.value():
  1027. return unary_operation<double, i32, Operators::CheckedTruncate<u32>>(configuration);
  1028. case Instructions::i64_trunc_sf32.value():
  1029. return unary_operation<float, i64, Operators::CheckedTruncate<i64>>(configuration);
  1030. case Instructions::i64_trunc_uf32.value():
  1031. return unary_operation<float, i64, Operators::CheckedTruncate<u64>>(configuration);
  1032. case Instructions::i64_trunc_sf64.value():
  1033. return unary_operation<double, i64, Operators::CheckedTruncate<i64>>(configuration);
  1034. case Instructions::i64_trunc_uf64.value():
  1035. return unary_operation<double, i64, Operators::CheckedTruncate<u64>>(configuration);
  1036. case Instructions::i64_extend_si32.value():
  1037. return unary_operation<i32, i64, Operators::Extend<i64>>(configuration);
  1038. case Instructions::i64_extend_ui32.value():
  1039. return unary_operation<u32, i64, Operators::Extend<i64>>(configuration);
  1040. case Instructions::f32_convert_si32.value():
  1041. return unary_operation<i32, float, Operators::Convert<float>>(configuration);
  1042. case Instructions::f32_convert_ui32.value():
  1043. return unary_operation<u32, float, Operators::Convert<float>>(configuration);
  1044. case Instructions::f32_convert_si64.value():
  1045. return unary_operation<i64, float, Operators::Convert<float>>(configuration);
  1046. case Instructions::f32_convert_ui64.value():
  1047. return unary_operation<u64, float, Operators::Convert<float>>(configuration);
  1048. case Instructions::f32_demote_f64.value():
  1049. return unary_operation<double, float, Operators::Demote>(configuration);
  1050. case Instructions::f64_convert_si32.value():
  1051. return unary_operation<i32, double, Operators::Convert<double>>(configuration);
  1052. case Instructions::f64_convert_ui32.value():
  1053. return unary_operation<u32, double, Operators::Convert<double>>(configuration);
  1054. case Instructions::f64_convert_si64.value():
  1055. return unary_operation<i64, double, Operators::Convert<double>>(configuration);
  1056. case Instructions::f64_convert_ui64.value():
  1057. return unary_operation<u64, double, Operators::Convert<double>>(configuration);
  1058. case Instructions::f64_promote_f32.value():
  1059. return unary_operation<float, double, Operators::Promote>(configuration);
  1060. case Instructions::i32_reinterpret_f32.value():
  1061. return unary_operation<float, i32, Operators::Reinterpret<i32>>(configuration);
  1062. case Instructions::i64_reinterpret_f64.value():
  1063. return unary_operation<double, i64, Operators::Reinterpret<i64>>(configuration);
  1064. case Instructions::f32_reinterpret_i32.value():
  1065. return unary_operation<i32, float, Operators::Reinterpret<float>>(configuration);
  1066. case Instructions::f64_reinterpret_i64.value():
  1067. return unary_operation<i64, double, Operators::Reinterpret<double>>(configuration);
  1068. case Instructions::i32_extend8_s.value():
  1069. return unary_operation<i32, i32, Operators::SignExtend<i8>>(configuration);
  1070. case Instructions::i32_extend16_s.value():
  1071. return unary_operation<i32, i32, Operators::SignExtend<i16>>(configuration);
  1072. case Instructions::i64_extend8_s.value():
  1073. return unary_operation<i64, i64, Operators::SignExtend<i8>>(configuration);
  1074. case Instructions::i64_extend16_s.value():
  1075. return unary_operation<i64, i64, Operators::SignExtend<i16>>(configuration);
  1076. case Instructions::i64_extend32_s.value():
  1077. return unary_operation<i64, i64, Operators::SignExtend<i32>>(configuration);
  1078. case Instructions::i32_trunc_sat_f32_s.value():
  1079. return unary_operation<float, i32, Operators::SaturatingTruncate<i32>>(configuration);
  1080. case Instructions::i32_trunc_sat_f32_u.value():
  1081. return unary_operation<float, i32, Operators::SaturatingTruncate<u32>>(configuration);
  1082. case Instructions::i32_trunc_sat_f64_s.value():
  1083. return unary_operation<double, i32, Operators::SaturatingTruncate<i32>>(configuration);
  1084. case Instructions::i32_trunc_sat_f64_u.value():
  1085. return unary_operation<double, i32, Operators::SaturatingTruncate<u32>>(configuration);
  1086. case Instructions::i64_trunc_sat_f32_s.value():
  1087. return unary_operation<float, i64, Operators::SaturatingTruncate<i64>>(configuration);
  1088. case Instructions::i64_trunc_sat_f32_u.value():
  1089. return unary_operation<float, i64, Operators::SaturatingTruncate<u64>>(configuration);
  1090. case Instructions::i64_trunc_sat_f64_s.value():
  1091. return unary_operation<double, i64, Operators::SaturatingTruncate<i64>>(configuration);
  1092. case Instructions::i64_trunc_sat_f64_u.value():
  1093. return unary_operation<double, i64, Operators::SaturatingTruncate<u64>>(configuration);
  1094. case Instructions::v128_const.value():
  1095. configuration.stack().push(Value(instruction.arguments().get<u128>()));
  1096. return;
  1097. case Instructions::v128_load.value():
  1098. return load_and_push<u128, u128>(configuration, instruction);
  1099. case Instructions::v128_load8x8_s.value():
  1100. return load_and_push_mxn<8, 8, MakeSigned>(configuration, instruction);
  1101. case Instructions::v128_load8x8_u.value():
  1102. return load_and_push_mxn<8, 8, MakeUnsigned>(configuration, instruction);
  1103. case Instructions::v128_load16x4_s.value():
  1104. return load_and_push_mxn<16, 4, MakeSigned>(configuration, instruction);
  1105. case Instructions::v128_load16x4_u.value():
  1106. return load_and_push_mxn<16, 4, MakeUnsigned>(configuration, instruction);
  1107. case Instructions::v128_load32x2_s.value():
  1108. return load_and_push_mxn<32, 2, MakeSigned>(configuration, instruction);
  1109. case Instructions::v128_load32x2_u.value():
  1110. return load_and_push_mxn<32, 2, MakeUnsigned>(configuration, instruction);
  1111. case Instructions::v128_load8_splat.value():
  1112. return load_and_push_m_splat<8>(configuration, instruction);
  1113. case Instructions::v128_load16_splat.value():
  1114. return load_and_push_m_splat<16>(configuration, instruction);
  1115. case Instructions::v128_load32_splat.value():
  1116. return load_and_push_m_splat<32>(configuration, instruction);
  1117. case Instructions::v128_load64_splat.value():
  1118. return load_and_push_m_splat<64>(configuration, instruction);
  1119. case Instructions::i8x16_splat.value():
  1120. return pop_and_push_m_splat<8, NativeIntegralType>(configuration, instruction);
  1121. case Instructions::i16x8_splat.value():
  1122. return pop_and_push_m_splat<16, NativeIntegralType>(configuration, instruction);
  1123. case Instructions::i32x4_splat.value():
  1124. return pop_and_push_m_splat<32, NativeIntegralType>(configuration, instruction);
  1125. case Instructions::i64x2_splat.value():
  1126. return pop_and_push_m_splat<64, NativeIntegralType>(configuration, instruction);
  1127. case Instructions::f32x4_splat.value():
  1128. return pop_and_push_m_splat<32, NativeFloatingType>(configuration, instruction);
  1129. case Instructions::f64x2_splat.value():
  1130. return pop_and_push_m_splat<64, NativeFloatingType>(configuration, instruction);
  1131. case Instructions::i8x16_shuffle.value(): {
  1132. auto indices = pop_vector<u8, MakeSigned>(configuration);
  1133. TRAP_IF_NOT(indices.has_value());
  1134. auto vector = peek_vector<u8, MakeSigned>(configuration);
  1135. TRAP_IF_NOT(vector.has_value());
  1136. auto result = shuffle_vector(vector.value(), indices.value());
  1137. configuration.stack().peek() = Value(result);
  1138. return;
  1139. }
  1140. case Instructions::v128_store.value():
  1141. return pop_and_store<u128, u128>(configuration, instruction);
  1142. case Instructions::i8x16_shl.value():
  1143. return binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<16>, i32>(configuration);
  1144. case Instructions::i8x16_shr_u.value():
  1145. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<16, MakeUnsigned>, i32>(configuration);
  1146. case Instructions::i8x16_shr_s.value():
  1147. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<16, MakeSigned>, i32>(configuration);
  1148. case Instructions::i16x8_shl.value():
  1149. return binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<8>, i32>(configuration);
  1150. case Instructions::i16x8_shr_u.value():
  1151. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<8, MakeUnsigned>, i32>(configuration);
  1152. case Instructions::i16x8_shr_s.value():
  1153. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<8, MakeSigned>, i32>(configuration);
  1154. case Instructions::i32x4_shl.value():
  1155. return binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<4>, i32>(configuration);
  1156. case Instructions::i32x4_shr_u.value():
  1157. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<4, MakeUnsigned>, i32>(configuration);
  1158. case Instructions::i32x4_shr_s.value():
  1159. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<4, MakeSigned>, i32>(configuration);
  1160. case Instructions::i64x2_shl.value():
  1161. return binary_numeric_operation<u128, u128, Operators::VectorShiftLeft<2>, i32>(configuration);
  1162. case Instructions::i64x2_shr_u.value():
  1163. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<2, MakeUnsigned>, i32>(configuration);
  1164. case Instructions::i64x2_shr_s.value():
  1165. return binary_numeric_operation<u128, u128, Operators::VectorShiftRight<2, MakeSigned>, i32>(configuration);
  1166. case Instructions::table_init.value():
  1167. case Instructions::elem_drop.value():
  1168. case Instructions::table_copy.value():
  1169. case Instructions::table_grow.value():
  1170. case Instructions::table_size.value():
  1171. case Instructions::table_fill.value():
  1172. default:
  1173. unimplemented:;
  1174. dbgln_if(WASM_TRACE_DEBUG, "Instruction '{}' not implemented", instruction_name(instruction.opcode()));
  1175. m_trap = Trap { DeprecatedString::formatted("Unimplemented instruction {}", instruction_name(instruction.opcode())) };
  1176. return;
  1177. }
  1178. }
  1179. void DebuggerBytecodeInterpreter::interpret(Configuration& configuration, InstructionPointer& ip, Instruction const& instruction)
  1180. {
  1181. if (pre_interpret_hook) {
  1182. auto result = pre_interpret_hook(configuration, ip, instruction);
  1183. if (!result) {
  1184. m_trap = Trap { "Trapped by user request" };
  1185. return;
  1186. }
  1187. }
  1188. BytecodeInterpreter::interpret(configuration, ip, instruction);
  1189. if (post_interpret_hook) {
  1190. auto result = post_interpret_hook(configuration, ip, instruction, *this);
  1191. if (!result) {
  1192. m_trap = Trap { "Trapped by user request" };
  1193. return;
  1194. }
  1195. }
  1196. }
  1197. }