Interpreter.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibWasm/AbstractMachine/AbstractMachine.h>
  8. #include <LibWasm/AbstractMachine/Configuration.h>
  9. #include <LibWasm/AbstractMachine/Interpreter.h>
  10. #include <LibWasm/Opcode.h>
  11. #include <LibWasm/Printer/Printer.h>
  12. #include <math.h>
  13. namespace Wasm {
  14. #define TRAP_IF_NOT(x) \
  15. do { \
  16. if (trap_if_not(x)) { \
  17. dbgln_if(WASM_TRACE_DEBUG, "Trapped because {} failed, at line {}", #x, __LINE__); \
  18. return; \
  19. } \
  20. } while (false)
  21. #define TRAP_IF_NOT_NORETURN(x) \
  22. do { \
  23. if (trap_if_not(x)) { \
  24. dbgln_if(WASM_TRACE_DEBUG, "Trapped because {} failed, at line {}", #x, __LINE__); \
  25. } \
  26. } while (false)
  27. void BytecodeInterpreter::interpret(Configuration& configuration)
  28. {
  29. auto& instructions = configuration.frame().expression().instructions();
  30. auto max_ip_value = InstructionPointer { instructions.size() };
  31. auto& current_ip_value = configuration.ip();
  32. while (current_ip_value < max_ip_value) {
  33. auto& instruction = instructions[current_ip_value.value()];
  34. auto old_ip = current_ip_value;
  35. interpret(configuration, current_ip_value, instruction);
  36. if (m_do_trap)
  37. return;
  38. if (current_ip_value == old_ip) // If no jump occurred
  39. ++current_ip_value;
  40. }
  41. }
  42. void BytecodeInterpreter::branch_to_label(Configuration& configuration, LabelIndex index)
  43. {
  44. dbgln_if(WASM_TRACE_DEBUG, "Branch to label with index {}...", index.value());
  45. auto label = configuration.nth_label(index.value());
  46. TRAP_IF_NOT(label.has_value());
  47. dbgln_if(WASM_TRACE_DEBUG, "...which is actually IP {}, and has {} result(s)", label->continuation().value(), label->arity());
  48. auto results = pop_values(configuration, label->arity());
  49. size_t drop_count = index.value() + 1;
  50. for (; !configuration.stack().is_empty();) {
  51. auto& entry = configuration.stack().peek();
  52. if (entry.has<Label>()) {
  53. if (--drop_count == 0)
  54. break;
  55. }
  56. configuration.stack().pop();
  57. }
  58. for (auto& result : results)
  59. configuration.stack().push(move(result));
  60. configuration.ip() = label->continuation();
  61. }
  62. template<typename ReadType, typename PushType>
  63. void BytecodeInterpreter::load_and_push(Configuration& configuration, const Instruction& instruction)
  64. {
  65. auto& address = configuration.frame().module().memories().first();
  66. auto memory = configuration.store().get(address);
  67. if (!memory) {
  68. m_do_trap = true;
  69. return;
  70. }
  71. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  72. auto base = configuration.stack().peek().get<Value>().to<i32>();
  73. if (!base.has_value()) {
  74. m_do_trap = true;
  75. return;
  76. }
  77. auto instance_address = base.value() + static_cast<i64>(arg.offset);
  78. if (instance_address < 0 || static_cast<u64>(instance_address + sizeof(ReadType)) > memory->size()) {
  79. m_do_trap = true;
  80. dbgln("LibWasm: Memory access out of bounds (expected 0 <= {} and {} <= {})", instance_address, instance_address + sizeof(ReadType), memory->size());
  81. return;
  82. }
  83. dbgln_if(WASM_TRACE_DEBUG, "load({} : {}) -> stack", instance_address, sizeof(ReadType));
  84. auto slice = memory->data().bytes().slice(instance_address, sizeof(ReadType));
  85. if constexpr (sizeof(ReadType) == 1)
  86. configuration.stack().peek() = Value(static_cast<PushType>(slice[0]));
  87. else
  88. configuration.stack().peek() = Value(read_value<PushType>(slice));
  89. }
  90. void BytecodeInterpreter::store_to_memory(Configuration& configuration, const Instruction& instruction, ReadonlyBytes data)
  91. {
  92. auto& address = configuration.frame().module().memories().first();
  93. auto memory = configuration.store().get(address);
  94. TRAP_IF_NOT(memory);
  95. auto& arg = instruction.arguments().get<Instruction::MemoryArgument>();
  96. auto base = configuration.stack().pop().get<Value>().to<i32>();
  97. TRAP_IF_NOT(base.has_value());
  98. auto instance_address = base.value() + static_cast<i64>(arg.offset);
  99. if (instance_address < 0 || static_cast<u64>(instance_address + data.size()) > memory->size()) {
  100. m_do_trap = true;
  101. dbgln("LibWasm: Memory access out of bounds (expected 0 <= {} and {} <= {})", instance_address, instance_address + data.size(), memory->size());
  102. return;
  103. }
  104. dbgln_if(WASM_TRACE_DEBUG, "tempoaray({}b) -> store({})", data.size(), instance_address);
  105. data.copy_to(memory->data().bytes().slice(instance_address, data.size()));
  106. }
  107. void BytecodeInterpreter::call_address(Configuration& configuration, FunctionAddress address)
  108. {
  109. auto instance = configuration.store().get(address);
  110. TRAP_IF_NOT(instance);
  111. const FunctionType* type { nullptr };
  112. instance->visit([&](const auto& function) { type = &function.type(); });
  113. TRAP_IF_NOT(type);
  114. Vector<Value> args;
  115. args.ensure_capacity(type->parameters().size());
  116. auto span = configuration.stack().entries().span().slice_from_end(type->parameters().size());
  117. for (auto& entry : span) {
  118. auto* ptr = entry.get_pointer<Value>();
  119. TRAP_IF_NOT(ptr != nullptr);
  120. args.unchecked_append(*ptr);
  121. }
  122. configuration.stack().entries().remove(configuration.stack().size() - span.size(), span.size());
  123. Result result { Trap {} };
  124. {
  125. CallFrameHandle handle { *this, configuration };
  126. result = configuration.call(*this, address, move(args));
  127. }
  128. if (result.is_trap()) {
  129. m_do_trap = true;
  130. return;
  131. }
  132. configuration.stack().entries().ensure_capacity(configuration.stack().size() + result.values().size());
  133. for (auto& entry : result.values())
  134. configuration.stack().entries().unchecked_append(move(entry));
  135. }
  136. #define BINARY_NUMERIC_OPERATION(type, operator, cast, ...) \
  137. do { \
  138. auto rhs = configuration.stack().pop().get<Value>().to<type>(); \
  139. auto lhs = configuration.stack().peek().get<Value>().to<type>(); \
  140. TRAP_IF_NOT(lhs.has_value()); \
  141. TRAP_IF_NOT(rhs.has_value()); \
  142. __VA_ARGS__; \
  143. auto result = lhs.value() operator rhs.value(); \
  144. dbgln_if(WASM_TRACE_DEBUG, "{} {} {} = {}", lhs.value(), #operator, rhs.value(), result); \
  145. configuration.stack().peek() = Value(cast(result)); \
  146. return; \
  147. } while (false)
  148. #define OVF_CHECKED_BINARY_NUMERIC_OPERATION(type, operator, cast, ...) \
  149. do { \
  150. auto rhs = configuration.stack().pop().get<Value>().to<type>(); \
  151. auto ulhs = configuration.stack().peek().get<Value>().to<type>(); \
  152. TRAP_IF_NOT(ulhs.has_value()); \
  153. TRAP_IF_NOT(rhs.has_value()); \
  154. dbgln_if(WASM_TRACE_DEBUG, "{} {} {} = ??", ulhs.value(), #operator, rhs.value()); \
  155. __VA_ARGS__; \
  156. Checked lhs = ulhs.value(); \
  157. lhs operator##= rhs.value(); \
  158. TRAP_IF_NOT(!lhs.has_overflow()); \
  159. auto result = lhs.value(); \
  160. dbgln_if(WASM_TRACE_DEBUG, "{} {} {} = {}", ulhs.value(), #operator, rhs.value(), result); \
  161. configuration.stack().peek() = Value(cast(result)); \
  162. return; \
  163. } while (false)
  164. #define BINARY_PREFIX_NUMERIC_OPERATION(type, operation, cast, ...) \
  165. do { \
  166. auto rhs = configuration.stack().pop().get<Value>().to<type>(); \
  167. auto lhs = configuration.stack().peek().get<Value>().to<type>(); \
  168. TRAP_IF_NOT(lhs.has_value()); \
  169. TRAP_IF_NOT(rhs.has_value()); \
  170. auto result = operation(lhs.value(), rhs.value()); \
  171. dbgln_if(WASM_TRACE_DEBUG, "{}({} {}) = {}", #operation, lhs.value(), rhs.value(), result); \
  172. configuration.stack().peek() = Value(cast(result)); \
  173. return; \
  174. } while (false)
  175. #define UNARY_MAP(pop_type, operation, ...) \
  176. do { \
  177. auto value = configuration.stack().peek().get<Value>().to<pop_type>(); \
  178. TRAP_IF_NOT(value.has_value()); \
  179. auto result = operation(value.value()); \
  180. dbgln_if(WASM_TRACE_DEBUG, "map({}) {} = {}", #operation, value.value(), result); \
  181. configuration.stack().peek() = Value(__VA_ARGS__(result)); \
  182. return; \
  183. } while (false)
  184. #define UNARY_NUMERIC_OPERATION(type, operation) \
  185. UNARY_MAP(type, operation, type)
  186. #define LOAD_AND_PUSH(read_type, push_type) \
  187. do { \
  188. return load_and_push<read_type, push_type>(configuration, instruction); \
  189. return; \
  190. } while (false)
  191. #define POP_AND_STORE(pop_type, store_type) \
  192. do { \
  193. auto value = ConvertToRaw<pop_type> {}(*configuration.stack().pop().get<Value>().to<pop_type>()); \
  194. dbgln_if(WASM_TRACE_DEBUG, "stack({}) -> temporary({}b)", value, sizeof(store_type)); \
  195. store_to_memory(configuration, instruction, { &value, sizeof(store_type) }); \
  196. return; \
  197. } while (false)
  198. template<typename T>
  199. T BytecodeInterpreter::read_value(ReadonlyBytes data)
  200. {
  201. T value;
  202. InputMemoryStream stream { data };
  203. auto ok = IsSigned<T> ? LEB128::read_signed(stream, value) : LEB128::read_unsigned(stream, value);
  204. if (stream.handle_any_error() || !ok)
  205. m_do_trap = true;
  206. return value;
  207. }
  208. template<>
  209. float BytecodeInterpreter::read_value<float>(ReadonlyBytes data)
  210. {
  211. InputMemoryStream stream { data };
  212. LittleEndian<u32> raw_value;
  213. stream >> raw_value;
  214. if (stream.handle_any_error())
  215. m_do_trap = true;
  216. return bit_cast<float>(static_cast<u32>(raw_value));
  217. }
  218. template<>
  219. double BytecodeInterpreter::read_value<double>(ReadonlyBytes data)
  220. {
  221. InputMemoryStream stream { data };
  222. LittleEndian<u64> raw_value;
  223. stream >> raw_value;
  224. if (stream.handle_any_error())
  225. m_do_trap = true;
  226. return bit_cast<double>(static_cast<u64>(raw_value));
  227. }
  228. template<typename T>
  229. struct ConvertToRaw {
  230. T operator()(T value)
  231. {
  232. return value;
  233. }
  234. };
  235. template<>
  236. struct ConvertToRaw<float> {
  237. u32 operator()(float value)
  238. {
  239. LittleEndian<u32> res;
  240. ReadonlyBytes bytes { &value, sizeof(float) };
  241. InputMemoryStream stream { bytes };
  242. stream >> res;
  243. VERIFY(!stream.has_any_error());
  244. return static_cast<u32>(res);
  245. }
  246. };
  247. template<>
  248. struct ConvertToRaw<double> {
  249. u64 operator()(double value)
  250. {
  251. LittleEndian<u64> res;
  252. ReadonlyBytes bytes { &value, sizeof(double) };
  253. InputMemoryStream stream { bytes };
  254. stream >> res;
  255. VERIFY(!stream.has_any_error());
  256. return static_cast<u64>(res);
  257. }
  258. };
  259. template<typename V, typename T>
  260. MakeSigned<T> BytecodeInterpreter::checked_signed_truncate(V value)
  261. {
  262. if (isnan(value) || isinf(value)) { // "undefined", let's just trap.
  263. m_do_trap = true;
  264. return 0;
  265. }
  266. double truncated;
  267. if constexpr (IsSame<float, V>)
  268. truncated = truncf(value);
  269. else
  270. truncated = trunc(value);
  271. using SignedT = MakeSigned<T>;
  272. if (NumericLimits<SignedT>::min() <= truncated && static_cast<double>(NumericLimits<SignedT>::max()) >= truncated)
  273. return static_cast<SignedT>(truncated);
  274. dbgln_if(WASM_TRACE_DEBUG, "Truncate out of range error");
  275. m_do_trap = true;
  276. return true;
  277. }
  278. template<typename V, typename T>
  279. MakeUnsigned<T> BytecodeInterpreter::checked_unsigned_truncate(V value)
  280. {
  281. if (isnan(value) || isinf(value)) { // "undefined", let's just trap.
  282. m_do_trap = true;
  283. return 0;
  284. }
  285. double truncated;
  286. if constexpr (IsSame<float, V>)
  287. truncated = truncf(value);
  288. else
  289. truncated = trunc(value);
  290. using UnsignedT = MakeUnsigned<T>;
  291. if (NumericLimits<UnsignedT>::min() <= truncated && static_cast<double>(NumericLimits<UnsignedT>::max()) >= truncated)
  292. return static_cast<UnsignedT>(truncated);
  293. dbgln_if(WASM_TRACE_DEBUG, "Truncate out of range error");
  294. m_do_trap = true;
  295. return true;
  296. }
  297. Vector<Value> BytecodeInterpreter::pop_values(Configuration& configuration, size_t count)
  298. {
  299. Vector<Value> results;
  300. results.resize(count);
  301. for (size_t i = 0; i < count; ++i) {
  302. auto top_of_stack = configuration.stack().pop();
  303. if (auto value = top_of_stack.get_pointer<Value>())
  304. results[i] = move(*value);
  305. else
  306. TRAP_IF_NOT_NORETURN(value);
  307. }
  308. return results;
  309. }
  310. void BytecodeInterpreter::interpret(Configuration& configuration, InstructionPointer& ip, const Instruction& instruction)
  311. {
  312. dbgln_if(WASM_TRACE_DEBUG, "Executing instruction {} at ip {}", instruction_name(instruction.opcode()), ip.value());
  313. switch (instruction.opcode().value()) {
  314. case Instructions::unreachable.value():
  315. m_do_trap = true;
  316. return;
  317. case Instructions::nop.value():
  318. return;
  319. case Instructions::local_get.value():
  320. configuration.stack().push(Value(configuration.frame().locals()[instruction.arguments().get<LocalIndex>().value()]));
  321. return;
  322. case Instructions::local_set.value(): {
  323. auto entry = configuration.stack().pop();
  324. configuration.frame().locals()[instruction.arguments().get<LocalIndex>().value()] = move(entry.get<Value>());
  325. return;
  326. }
  327. case Instructions::i32_const.value():
  328. configuration.stack().push(Value(ValueType { ValueType::I32 }, static_cast<i64>(instruction.arguments().get<i32>())));
  329. return;
  330. case Instructions::i64_const.value():
  331. configuration.stack().push(Value(ValueType { ValueType::I64 }, instruction.arguments().get<i64>()));
  332. return;
  333. case Instructions::f32_const.value():
  334. configuration.stack().push(Value(ValueType { ValueType::F32 }, static_cast<double>(instruction.arguments().get<float>())));
  335. return;
  336. case Instructions::f64_const.value():
  337. configuration.stack().push(Value(ValueType { ValueType::F64 }, instruction.arguments().get<double>()));
  338. return;
  339. case Instructions::block.value(): {
  340. size_t arity = 0;
  341. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  342. if (args.block_type.kind() != BlockType::Empty)
  343. arity = 1;
  344. configuration.stack().push(Label(arity, args.end_ip));
  345. return;
  346. }
  347. case Instructions::loop.value(): {
  348. size_t arity = 0;
  349. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  350. if (args.block_type.kind() != BlockType::Empty)
  351. arity = 1;
  352. configuration.stack().push(Label(arity, ip.value() + 1));
  353. return;
  354. }
  355. case Instructions::if_.value(): {
  356. size_t arity = 0;
  357. auto& args = instruction.arguments().get<Instruction::StructuredInstructionArgs>();
  358. if (args.block_type.kind() != BlockType::Empty)
  359. arity = 1;
  360. auto entry = configuration.stack().pop();
  361. auto value = entry.get<Value>().to<i32>();
  362. TRAP_IF_NOT(value.has_value());
  363. auto end_label = Label(arity, args.end_ip.value());
  364. if (value.value() == 0) {
  365. if (args.else_ip.has_value()) {
  366. configuration.ip() = args.else_ip.value();
  367. configuration.stack().push(move(end_label));
  368. } else {
  369. configuration.ip() = args.end_ip.value() + 1;
  370. }
  371. } else {
  372. configuration.stack().push(move(end_label));
  373. }
  374. return;
  375. }
  376. case Instructions::structured_end.value():
  377. case Instructions::structured_else.value(): {
  378. auto label = configuration.nth_label(0);
  379. TRAP_IF_NOT(label.has_value());
  380. size_t end = configuration.stack().size() - label->arity() - 1;
  381. size_t start = end;
  382. while (start > 0 && start < configuration.stack().size() && !configuration.stack().entries()[start].has<Label>())
  383. --start;
  384. configuration.stack().entries().remove(start, end - start + 1);
  385. if (instruction.opcode() == Instructions::structured_end)
  386. return;
  387. // Jump to the end label
  388. configuration.ip() = label->continuation();
  389. return;
  390. }
  391. case Instructions::return_.value(): {
  392. auto& frame = configuration.frame();
  393. size_t end = configuration.stack().size() - frame.arity();
  394. size_t start = end;
  395. for (; start + 1 > 0 && start < configuration.stack().size(); --start) {
  396. auto& entry = configuration.stack().entries()[start];
  397. if (entry.has<Frame>()) {
  398. // Leave the frame, _and_ its label.
  399. start += 2;
  400. break;
  401. }
  402. }
  403. configuration.stack().entries().remove(start, end - start);
  404. // Jump past the call/indirect instruction
  405. configuration.ip() = configuration.frame().expression().instructions().size();
  406. return;
  407. }
  408. case Instructions::br.value():
  409. return branch_to_label(configuration, instruction.arguments().get<LabelIndex>());
  410. case Instructions::br_if.value(): {
  411. if (configuration.stack().pop().get<Value>().to<i32>().value_or(0) == 0)
  412. return;
  413. return branch_to_label(configuration, instruction.arguments().get<LabelIndex>());
  414. }
  415. case Instructions::br_table.value():
  416. goto unimplemented;
  417. case Instructions::call.value(): {
  418. auto index = instruction.arguments().get<FunctionIndex>();
  419. TRAP_IF_NOT(index.value() < configuration.frame().module().functions().size());
  420. auto address = configuration.frame().module().functions()[index.value()];
  421. dbgln_if(WASM_TRACE_DEBUG, "call({})", address.value());
  422. call_address(configuration, address);
  423. return;
  424. }
  425. case Instructions::call_indirect.value(): {
  426. auto& args = instruction.arguments().get<Instruction::IndirectCallArgs>();
  427. TRAP_IF_NOT(args.table.value() < configuration.frame().module().tables().size());
  428. auto table_address = configuration.frame().module().tables()[args.table.value()];
  429. auto table_instance = configuration.store().get(table_address);
  430. auto index = configuration.stack().pop().get<Value>().to<i32>();
  431. TRAP_IF_NOT(index.has_value());
  432. if (index.value() < 0 || static_cast<size_t>(index.value()) >= table_instance->elements().size()) {
  433. dbgln("LibWasm: Element access out of bounds, expected {0} > 0 and {0} < {1}", index.value(), table_instance->elements().size());
  434. m_do_trap = true;
  435. return;
  436. }
  437. auto element = table_instance->elements()[index.value()];
  438. if (!element.has_value() || !element->ref().has<FunctionAddress>()) {
  439. dbgln("LibWasm: call_indirect attempted with invalid address element (not a function)");
  440. m_do_trap = true;
  441. return;
  442. }
  443. auto address = element->ref().get<FunctionAddress>();
  444. dbgln_if(WASM_TRACE_DEBUG, "call_indirect({} -> {})", index.value(), address.value());
  445. call_address(configuration, address);
  446. return;
  447. }
  448. case Instructions::i32_load.value():
  449. LOAD_AND_PUSH(i32, i32);
  450. case Instructions::i64_load.value():
  451. LOAD_AND_PUSH(i64, i64);
  452. case Instructions::f32_load.value():
  453. LOAD_AND_PUSH(float, float);
  454. case Instructions::f64_load.value():
  455. LOAD_AND_PUSH(double, double);
  456. case Instructions::i32_load8_s.value():
  457. LOAD_AND_PUSH(i8, i32);
  458. case Instructions::i32_load8_u.value():
  459. LOAD_AND_PUSH(u8, i32);
  460. case Instructions::i32_load16_s.value():
  461. LOAD_AND_PUSH(i16, i32);
  462. case Instructions::i32_load16_u.value():
  463. LOAD_AND_PUSH(u16, i32);
  464. case Instructions::i64_load8_s.value():
  465. LOAD_AND_PUSH(i8, i64);
  466. case Instructions::i64_load8_u.value():
  467. LOAD_AND_PUSH(u8, i64);
  468. case Instructions::i64_load16_s.value():
  469. LOAD_AND_PUSH(i16, i64);
  470. case Instructions::i64_load16_u.value():
  471. LOAD_AND_PUSH(u16, i64);
  472. case Instructions::i64_load32_s.value():
  473. LOAD_AND_PUSH(i32, i64);
  474. case Instructions::i64_load32_u.value():
  475. LOAD_AND_PUSH(u32, i64);
  476. case Instructions::i32_store.value():
  477. POP_AND_STORE(i32, i32);
  478. case Instructions::i64_store.value():
  479. POP_AND_STORE(i64, i64);
  480. case Instructions::f32_store.value():
  481. POP_AND_STORE(float, float);
  482. case Instructions::f64_store.value():
  483. POP_AND_STORE(double, double);
  484. case Instructions::i32_store8.value():
  485. POP_AND_STORE(i32, i8);
  486. case Instructions::i32_store16.value():
  487. POP_AND_STORE(i32, i16);
  488. case Instructions::i64_store8.value():
  489. POP_AND_STORE(i64, i8);
  490. case Instructions::i64_store16.value():
  491. POP_AND_STORE(i64, i16);
  492. case Instructions::i64_store32.value():
  493. POP_AND_STORE(i64, i32);
  494. case Instructions::local_tee.value(): {
  495. auto value = configuration.stack().peek().get<Value>();
  496. auto local_index = instruction.arguments().get<LocalIndex>();
  497. TRAP_IF_NOT(configuration.frame().locals().size() > local_index.value());
  498. dbgln_if(WASM_TRACE_DEBUG, "stack:peek -> locals({})", local_index.value());
  499. configuration.frame().locals()[local_index.value()] = move(value);
  500. return;
  501. }
  502. case Instructions::global_get.value(): {
  503. auto global_index = instruction.arguments().get<GlobalIndex>();
  504. TRAP_IF_NOT(configuration.frame().module().globals().size() > global_index.value());
  505. auto address = configuration.frame().module().globals()[global_index.value()];
  506. dbgln_if(WASM_TRACE_DEBUG, "global({}) -> stack", address.value());
  507. auto global = configuration.store().get(address);
  508. configuration.stack().push(Value(global->value()));
  509. return;
  510. }
  511. case Instructions::global_set.value(): {
  512. auto global_index = instruction.arguments().get<GlobalIndex>();
  513. TRAP_IF_NOT(configuration.frame().module().globals().size() > global_index.value());
  514. auto address = configuration.frame().module().globals()[global_index.value()];
  515. auto value = configuration.stack().pop().get<Value>();
  516. dbgln_if(WASM_TRACE_DEBUG, "stack -> global({})", address.value());
  517. auto global = configuration.store().get(address);
  518. global->set_value(move(value));
  519. return;
  520. }
  521. case Instructions::memory_size.value(): {
  522. TRAP_IF_NOT(configuration.frame().module().memories().size() > 0);
  523. auto address = configuration.frame().module().memories()[0];
  524. auto instance = configuration.store().get(address);
  525. auto pages = instance->size() / Constants::page_size;
  526. dbgln_if(WASM_TRACE_DEBUG, "memory.size -> stack({})", pages);
  527. configuration.stack().push(Value((i32)pages));
  528. return;
  529. }
  530. case Instructions::memory_grow.value(): {
  531. TRAP_IF_NOT(configuration.frame().module().memories().size() > 0);
  532. auto address = configuration.frame().module().memories()[0];
  533. auto instance = configuration.store().get(address);
  534. i32 old_pages = instance->size() / Constants::page_size;
  535. auto new_pages = configuration.stack().peek().get<Value>().to<i32>();
  536. TRAP_IF_NOT(new_pages.has_value());
  537. dbgln_if(WASM_TRACE_DEBUG, "memory.grow({}), previously {} pages...", *new_pages, old_pages);
  538. if (instance->grow(new_pages.value() * Constants::page_size))
  539. configuration.stack().peek() = Value((i32)old_pages);
  540. else
  541. configuration.stack().peek() = Value((i32)-1);
  542. return;
  543. }
  544. case Instructions::table_get.value():
  545. case Instructions::table_set.value():
  546. goto unimplemented;
  547. case Instructions::ref_null.value(): {
  548. auto type = instruction.arguments().get<ValueType>();
  549. TRAP_IF_NOT(type.is_reference());
  550. configuration.stack().push(Value(Value::Null { type }));
  551. return;
  552. };
  553. case Instructions::ref_func.value(): {
  554. auto index = instruction.arguments().get<FunctionIndex>().value();
  555. auto& functions = configuration.frame().module().functions();
  556. TRAP_IF_NOT(functions.size() > index);
  557. auto address = functions[index];
  558. configuration.stack().push(Value(ValueType(ValueType::FunctionReference), address.value()));
  559. return;
  560. }
  561. case Instructions::ref_is_null.value(): {
  562. auto top = configuration.stack().peek().get_pointer<Value>();
  563. TRAP_IF_NOT(top);
  564. TRAP_IF_NOT(top->type().is_reference());
  565. auto is_null = top->to<Value::Null>().has_value();
  566. configuration.stack().peek() = Value(ValueType(ValueType::I32), static_cast<u64>(is_null ? 1 : 0));
  567. return;
  568. }
  569. case Instructions::drop.value():
  570. configuration.stack().pop();
  571. return;
  572. case Instructions::select.value():
  573. case Instructions::select_typed.value(): {
  574. // Note: The type seems to only be used for validation.
  575. auto value = configuration.stack().pop().get<Value>().to<i32>();
  576. TRAP_IF_NOT(value.has_value());
  577. dbgln_if(WASM_TRACE_DEBUG, "select({})", value.value());
  578. auto rhs = move(configuration.stack().pop().get<Value>());
  579. auto lhs = move(configuration.stack().peek().get<Value>());
  580. configuration.stack().peek() = value.value() != 0 ? move(lhs) : move(rhs);
  581. return;
  582. }
  583. case Instructions::i32_eqz.value():
  584. UNARY_NUMERIC_OPERATION(i32, 0 ==);
  585. case Instructions::i32_eq.value():
  586. BINARY_NUMERIC_OPERATION(i32, ==, i32);
  587. case Instructions::i32_ne.value():
  588. BINARY_NUMERIC_OPERATION(i32, !=, i32);
  589. case Instructions::i32_lts.value():
  590. BINARY_NUMERIC_OPERATION(i32, <, i32);
  591. case Instructions::i32_ltu.value():
  592. BINARY_NUMERIC_OPERATION(u32, <, i32);
  593. case Instructions::i32_gts.value():
  594. BINARY_NUMERIC_OPERATION(i32, >, i32);
  595. case Instructions::i32_gtu.value():
  596. BINARY_NUMERIC_OPERATION(u32, >, i32);
  597. case Instructions::i32_les.value():
  598. BINARY_NUMERIC_OPERATION(i32, <=, i32);
  599. case Instructions::i32_leu.value():
  600. BINARY_NUMERIC_OPERATION(u32, <=, i32);
  601. case Instructions::i32_ges.value():
  602. BINARY_NUMERIC_OPERATION(i32, >=, i32);
  603. case Instructions::i32_geu.value():
  604. BINARY_NUMERIC_OPERATION(u32, >=, i32);
  605. case Instructions::i64_eqz.value():
  606. UNARY_NUMERIC_OPERATION(i64, 0ull ==);
  607. case Instructions::i64_eq.value():
  608. BINARY_NUMERIC_OPERATION(i64, ==, i32);
  609. case Instructions::i64_ne.value():
  610. BINARY_NUMERIC_OPERATION(i64, !=, i32);
  611. case Instructions::i64_lts.value():
  612. BINARY_NUMERIC_OPERATION(i64, <, i32);
  613. case Instructions::i64_ltu.value():
  614. BINARY_NUMERIC_OPERATION(u64, <, i32);
  615. case Instructions::i64_gts.value():
  616. BINARY_NUMERIC_OPERATION(i64, >, i32);
  617. case Instructions::i64_gtu.value():
  618. BINARY_NUMERIC_OPERATION(u64, >, i32);
  619. case Instructions::i64_les.value():
  620. BINARY_NUMERIC_OPERATION(i64, <=, i32);
  621. case Instructions::i64_leu.value():
  622. BINARY_NUMERIC_OPERATION(u64, <=, i32);
  623. case Instructions::i64_ges.value():
  624. BINARY_NUMERIC_OPERATION(i64, >=, i32);
  625. case Instructions::i64_geu.value():
  626. BINARY_NUMERIC_OPERATION(u64, >=, i32);
  627. case Instructions::f32_eq.value():
  628. BINARY_NUMERIC_OPERATION(float, ==, i32);
  629. case Instructions::f32_ne.value():
  630. BINARY_NUMERIC_OPERATION(float, !=, i32);
  631. case Instructions::f32_lt.value():
  632. BINARY_NUMERIC_OPERATION(float, <, i32);
  633. case Instructions::f32_gt.value():
  634. BINARY_NUMERIC_OPERATION(float, >, i32);
  635. case Instructions::f32_le.value():
  636. BINARY_NUMERIC_OPERATION(float, <=, i32);
  637. case Instructions::f32_ge.value():
  638. BINARY_NUMERIC_OPERATION(float, >=, i32);
  639. case Instructions::f64_eq.value():
  640. BINARY_NUMERIC_OPERATION(double, ==, i32);
  641. case Instructions::f64_ne.value():
  642. BINARY_NUMERIC_OPERATION(double, !=, i32);
  643. case Instructions::f64_lt.value():
  644. BINARY_NUMERIC_OPERATION(double, <, i32);
  645. case Instructions::f64_gt.value():
  646. BINARY_NUMERIC_OPERATION(double, >, i32);
  647. case Instructions::f64_le.value():
  648. BINARY_NUMERIC_OPERATION(double, <=, i32);
  649. case Instructions::f64_ge.value():
  650. BINARY_NUMERIC_OPERATION(double, >, i32);
  651. case Instructions::i32_clz.value():
  652. case Instructions::i32_ctz.value():
  653. case Instructions::i32_popcnt.value():
  654. goto unimplemented;
  655. case Instructions::i32_add.value():
  656. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i32, +, i32);
  657. case Instructions::i32_sub.value():
  658. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i32, -, i32);
  659. case Instructions::i32_mul.value():
  660. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i32, *, i32);
  661. case Instructions::i32_divs.value():
  662. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i32, /, i32, TRAP_IF_NOT(rhs.value() != 0));
  663. case Instructions::i32_divu.value():
  664. OVF_CHECKED_BINARY_NUMERIC_OPERATION(u32, /, i32, TRAP_IF_NOT(rhs.value() != 0));
  665. case Instructions::i32_rems.value():
  666. BINARY_NUMERIC_OPERATION(i32, %, i32, TRAP_IF_NOT(rhs.value() != 0));
  667. case Instructions::i32_remu.value():
  668. BINARY_NUMERIC_OPERATION(u32, %, i32, TRAP_IF_NOT(rhs.value() != 0));
  669. case Instructions::i32_and.value():
  670. BINARY_NUMERIC_OPERATION(i32, &, i32);
  671. case Instructions::i32_or.value():
  672. BINARY_NUMERIC_OPERATION(i32, |, i32);
  673. case Instructions::i32_xor.value():
  674. BINARY_NUMERIC_OPERATION(i32, ^, i32);
  675. case Instructions::i32_shl.value():
  676. BINARY_NUMERIC_OPERATION(i32, <<, i32);
  677. case Instructions::i32_shrs.value():
  678. BINARY_NUMERIC_OPERATION(i32, >>, i32);
  679. case Instructions::i32_shru.value():
  680. BINARY_NUMERIC_OPERATION(u32, >>, i32);
  681. case Instructions::i32_rotl.value():
  682. case Instructions::i32_rotr.value():
  683. case Instructions::i64_clz.value():
  684. case Instructions::i64_ctz.value():
  685. case Instructions::i64_popcnt.value():
  686. goto unimplemented;
  687. case Instructions::i64_add.value():
  688. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i64, +, i64);
  689. case Instructions::i64_sub.value():
  690. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i64, -, i64);
  691. case Instructions::i64_mul.value():
  692. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i64, *, i64);
  693. case Instructions::i64_divs.value():
  694. OVF_CHECKED_BINARY_NUMERIC_OPERATION(i64, /, i64, TRAP_IF_NOT(rhs.value() != 0));
  695. case Instructions::i64_divu.value():
  696. OVF_CHECKED_BINARY_NUMERIC_OPERATION(u64, /, i64, TRAP_IF_NOT(rhs.value() != 0));
  697. case Instructions::i64_rems.value():
  698. BINARY_NUMERIC_OPERATION(i64, %, i64, TRAP_IF_NOT(rhs.value() != 0));
  699. case Instructions::i64_remu.value():
  700. BINARY_NUMERIC_OPERATION(u64, %, i64, TRAP_IF_NOT(rhs.value() != 0));
  701. case Instructions::i64_and.value():
  702. BINARY_NUMERIC_OPERATION(i64, &, i64);
  703. case Instructions::i64_or.value():
  704. BINARY_NUMERIC_OPERATION(i64, |, i64);
  705. case Instructions::i64_xor.value():
  706. BINARY_NUMERIC_OPERATION(i64, ^, i64);
  707. case Instructions::i64_shl.value():
  708. BINARY_NUMERIC_OPERATION(i64, <<, i64);
  709. case Instructions::i64_shrs.value():
  710. BINARY_NUMERIC_OPERATION(i64, >>, i64);
  711. case Instructions::i64_shru.value():
  712. BINARY_NUMERIC_OPERATION(u64, >>, i64);
  713. case Instructions::i64_rotl.value():
  714. case Instructions::i64_rotr.value():
  715. goto unimplemented;
  716. case Instructions::f32_abs.value():
  717. UNARY_NUMERIC_OPERATION(float, fabsf);
  718. case Instructions::f32_neg.value():
  719. UNARY_NUMERIC_OPERATION(float, -);
  720. case Instructions::f32_ceil.value():
  721. UNARY_NUMERIC_OPERATION(float, ceilf);
  722. case Instructions::f32_floor.value():
  723. UNARY_NUMERIC_OPERATION(float, floorf);
  724. case Instructions::f32_trunc.value():
  725. UNARY_NUMERIC_OPERATION(float, truncf);
  726. case Instructions::f32_nearest.value():
  727. UNARY_NUMERIC_OPERATION(float, roundf);
  728. case Instructions::f32_sqrt.value():
  729. UNARY_NUMERIC_OPERATION(float, sqrtf);
  730. case Instructions::f32_add.value():
  731. BINARY_NUMERIC_OPERATION(float, +, float);
  732. case Instructions::f32_sub.value():
  733. BINARY_NUMERIC_OPERATION(float, -, float);
  734. case Instructions::f32_mul.value():
  735. BINARY_NUMERIC_OPERATION(float, *, float);
  736. case Instructions::f32_div.value():
  737. BINARY_NUMERIC_OPERATION(float, /, float);
  738. case Instructions::f32_min.value():
  739. BINARY_PREFIX_NUMERIC_OPERATION(float, min, float);
  740. case Instructions::f32_max.value():
  741. BINARY_PREFIX_NUMERIC_OPERATION(float, max, float);
  742. case Instructions::f32_copysign.value():
  743. BINARY_PREFIX_NUMERIC_OPERATION(float, copysignf, float);
  744. case Instructions::f64_abs.value():
  745. UNARY_NUMERIC_OPERATION(double, fabs);
  746. case Instructions::f64_neg.value():
  747. UNARY_NUMERIC_OPERATION(double, -);
  748. case Instructions::f64_ceil.value():
  749. UNARY_NUMERIC_OPERATION(double, ceil);
  750. case Instructions::f64_floor.value():
  751. UNARY_NUMERIC_OPERATION(double, floor);
  752. case Instructions::f64_trunc.value():
  753. UNARY_NUMERIC_OPERATION(double, trunc);
  754. case Instructions::f64_nearest.value():
  755. UNARY_NUMERIC_OPERATION(double, round);
  756. case Instructions::f64_sqrt.value():
  757. UNARY_NUMERIC_OPERATION(double, sqrt);
  758. case Instructions::f64_add.value():
  759. BINARY_NUMERIC_OPERATION(double, +, double);
  760. case Instructions::f64_sub.value():
  761. BINARY_NUMERIC_OPERATION(double, -, double);
  762. case Instructions::f64_mul.value():
  763. BINARY_NUMERIC_OPERATION(double, *, double);
  764. case Instructions::f64_div.value():
  765. BINARY_NUMERIC_OPERATION(double, /, double);
  766. case Instructions::f64_min.value():
  767. BINARY_PREFIX_NUMERIC_OPERATION(double, min, double);
  768. case Instructions::f64_max.value():
  769. BINARY_PREFIX_NUMERIC_OPERATION(double, max, double);
  770. case Instructions::f64_copysign.value():
  771. BINARY_PREFIX_NUMERIC_OPERATION(double, copysign, double);
  772. case Instructions::i32_wrap_i64.value():
  773. UNARY_MAP(i64, i32, i32);
  774. case Instructions::i32_trunc_sf32.value(): {
  775. auto fn = [this](auto& v) { return checked_signed_truncate<float, i32>(v); };
  776. UNARY_MAP(float, fn, i32);
  777. }
  778. case Instructions::i32_trunc_uf32.value(): {
  779. auto fn = [this](auto& value) { return checked_unsigned_truncate<float, i32>(value); };
  780. UNARY_MAP(float, fn, i32);
  781. }
  782. case Instructions::i32_trunc_sf64.value(): {
  783. auto fn = [this](auto& value) { return checked_signed_truncate<double, i32>(value); };
  784. UNARY_MAP(double, fn, i32);
  785. }
  786. case Instructions::i32_trunc_uf64.value(): {
  787. auto fn = [this](auto& value) { return checked_unsigned_truncate<double, i32>(value); };
  788. UNARY_MAP(double, fn, i32);
  789. }
  790. case Instructions::i64_trunc_sf32.value(): {
  791. auto fn = [this](auto& value) { return checked_signed_truncate<float, i64>(value); };
  792. UNARY_MAP(float, fn, i64);
  793. }
  794. case Instructions::i64_trunc_uf32.value(): {
  795. auto fn = [this](auto& value) { return checked_unsigned_truncate<float, i64>(value); };
  796. UNARY_MAP(float, fn, i64);
  797. }
  798. case Instructions::i64_trunc_sf64.value(): {
  799. auto fn = [this](auto& value) { return checked_signed_truncate<double, i64>(value); };
  800. UNARY_MAP(double, fn, i64);
  801. }
  802. case Instructions::i64_trunc_uf64.value(): {
  803. auto fn = [this](auto& value) { return checked_unsigned_truncate<double, i64>(value); };
  804. UNARY_MAP(double, fn, i64);
  805. }
  806. case Instructions::i64_extend_si32.value():
  807. UNARY_MAP(i32, i64, i64);
  808. case Instructions::i64_extend_ui32.value():
  809. UNARY_MAP(u32, i64, i64);
  810. case Instructions::f32_convert_si32.value():
  811. UNARY_MAP(i32, float, float);
  812. case Instructions::f32_convert_ui32.value():
  813. UNARY_MAP(u32, float, float);
  814. case Instructions::f32_convert_si64.value():
  815. UNARY_MAP(i64, float, float);
  816. case Instructions::f32_convert_ui64.value():
  817. UNARY_MAP(u32, float, float);
  818. case Instructions::f32_demote_f64.value():
  819. UNARY_MAP(double, float, float);
  820. case Instructions::f64_convert_si32.value():
  821. UNARY_MAP(i32, double, double);
  822. case Instructions::f64_convert_ui32.value():
  823. UNARY_MAP(u32, double, double);
  824. case Instructions::f64_convert_si64.value():
  825. UNARY_MAP(i64, double, double);
  826. case Instructions::f64_convert_ui64.value():
  827. UNARY_MAP(u64, double, double);
  828. case Instructions::f64_promote_f32.value():
  829. UNARY_MAP(float, double, double);
  830. case Instructions::i32_reinterpret_f32.value():
  831. UNARY_MAP(float, bit_cast<i32>, i32);
  832. case Instructions::i64_reinterpret_f64.value():
  833. UNARY_MAP(double, bit_cast<i64>, i64);
  834. case Instructions::f32_reinterpret_i32.value():
  835. UNARY_MAP(i32, bit_cast<float>, float);
  836. case Instructions::f64_reinterpret_i64.value():
  837. UNARY_MAP(i64, bit_cast<double>, double);
  838. case Instructions::i32_trunc_sat_f32_s.value():
  839. case Instructions::i32_trunc_sat_f32_u.value():
  840. case Instructions::i32_trunc_sat_f64_s.value():
  841. case Instructions::i32_trunc_sat_f64_u.value():
  842. case Instructions::i64_trunc_sat_f32_s.value():
  843. case Instructions::i64_trunc_sat_f32_u.value():
  844. case Instructions::i64_trunc_sat_f64_s.value():
  845. case Instructions::i64_trunc_sat_f64_u.value():
  846. case Instructions::memory_init.value():
  847. case Instructions::data_drop.value():
  848. case Instructions::memory_copy.value():
  849. case Instructions::memory_fill.value():
  850. case Instructions::table_init.value():
  851. case Instructions::elem_drop.value():
  852. case Instructions::table_copy.value():
  853. case Instructions::table_grow.value():
  854. case Instructions::table_size.value():
  855. case Instructions::table_fill.value():
  856. case Instructions::i32_extend8_s.value():
  857. case Instructions::i32_extend16_s.value():
  858. case Instructions::i64_extend8_s.value():
  859. case Instructions::i64_extend16_s.value():
  860. case Instructions::i64_extend32_s.value():
  861. default:
  862. unimplemented:;
  863. dbgln("Instruction '{}' not implemented", instruction_name(instruction.opcode()));
  864. m_do_trap = true;
  865. return;
  866. }
  867. }
  868. void DebuggerBytecodeInterpreter::interpret(Configuration& configuration, InstructionPointer& ip, const Instruction& instruction)
  869. {
  870. if (pre_interpret_hook) {
  871. auto result = pre_interpret_hook(configuration, ip, instruction);
  872. if (!result) {
  873. m_do_trap = true;
  874. return;
  875. }
  876. }
  877. ScopeGuard guard { [&] {
  878. if (post_interpret_hook) {
  879. auto result = post_interpret_hook(configuration, ip, instruction, *this);
  880. if (!result) {
  881. m_do_trap = true;
  882. return;
  883. }
  884. }
  885. } };
  886. BytecodeInterpreter::interpret(configuration, ip, instruction);
  887. }
  888. }