Parser.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ConstrainedStream.h>
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/LEB128.h>
  10. #include <AK/MemoryStream.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/ScopeLogger.h>
  13. #include <AK/UFixedBigInt.h>
  14. #include <LibWasm/Types.h>
  15. namespace Wasm {
  16. ParseError with_eof_check(Stream const& stream, ParseError error_if_not_eof)
  17. {
  18. if (stream.is_eof())
  19. return ParseError::UnexpectedEof;
  20. return error_if_not_eof;
  21. }
  22. template<typename T>
  23. static auto parse_vector(Stream& stream)
  24. {
  25. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  26. if constexpr (requires { T::parse(stream); }) {
  27. using ResultT = typename decltype(T::parse(stream))::ResultType;
  28. auto count_or_error = stream.read_value<LEB128<u32>>();
  29. if (count_or_error.is_error())
  30. return ParseResult<Vector<ResultT>> { with_eof_check(stream, ParseError::ExpectedSize) };
  31. size_t count = count_or_error.release_value();
  32. Vector<ResultT> entries;
  33. for (size_t i = 0; i < count; ++i) {
  34. auto result = T::parse(stream);
  35. if (result.is_error())
  36. return ParseResult<Vector<ResultT>> { result.error() };
  37. entries.append(result.release_value());
  38. }
  39. return ParseResult<Vector<ResultT>> { move(entries) };
  40. } else {
  41. auto count_or_error = stream.read_value<LEB128<u32>>();
  42. if (count_or_error.is_error())
  43. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  44. size_t count = count_or_error.release_value();
  45. Vector<T> entries;
  46. for (size_t i = 0; i < count; ++i) {
  47. if constexpr (IsSame<T, u32>) {
  48. auto value_or_error = stream.read_value<LEB128<u32>>();
  49. if (value_or_error.is_error())
  50. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  51. size_t value = value_or_error.release_value();
  52. entries.append(value);
  53. } else if constexpr (IsSame<T, ssize_t>) {
  54. auto value_or_error = stream.read_value<LEB128<ssize_t>>();
  55. if (value_or_error.is_error())
  56. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  57. ssize_t value = value_or_error.release_value();
  58. entries.append(value);
  59. } else if constexpr (IsSame<T, u8>) {
  60. if (count > Constants::max_allowed_vector_size)
  61. return ParseResult<Vector<T>> { ParseError::HugeAllocationRequested };
  62. entries.resize(count);
  63. if (stream.read_until_filled({ entries.data(), entries.size() }).is_error())
  64. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::InvalidInput) };
  65. break; // Note: We read this all in one go!
  66. }
  67. }
  68. return ParseResult<Vector<T>> { move(entries) };
  69. }
  70. }
  71. static ParseResult<ByteString> parse_name(Stream& stream)
  72. {
  73. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  74. auto data = TRY(parse_vector<u8>(stream));
  75. return ByteString::copy(data);
  76. }
  77. template<typename T>
  78. struct ParseUntilAnyOfResult {
  79. u8 terminator { 0 };
  80. Vector<T> values;
  81. };
  82. template<typename T, u8... terminators, typename... Args>
  83. static ParseResult<ParseUntilAnyOfResult<T>> parse_until_any_of(Stream& stream, Args&... args)
  84. requires(requires(Stream& stream, Args... args) { T::parse(stream, args...); })
  85. {
  86. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  87. ReconsumableStream new_stream { stream };
  88. ParseUntilAnyOfResult<T> result;
  89. for (;;) {
  90. auto byte_or_error = new_stream.read_value<u8>();
  91. if (byte_or_error.is_error())
  92. return with_eof_check(stream, ParseError::ExpectedValueOrTerminator);
  93. auto byte = byte_or_error.release_value();
  94. constexpr auto equals = [](auto&& a, auto&& b) { return a == b; };
  95. if ((... || equals(byte, terminators))) {
  96. result.terminator = byte;
  97. return result;
  98. }
  99. new_stream.unread({ &byte, 1 });
  100. auto parse_result = TRY(T::parse(new_stream, args...));
  101. result.values.extend(parse_result);
  102. }
  103. }
  104. ParseResult<ValueType> ValueType::parse(Stream& stream)
  105. {
  106. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ValueType"sv);
  107. auto tag_or_error = stream.read_value<u8>();
  108. if (tag_or_error.is_error())
  109. return with_eof_check(stream, ParseError::ExpectedKindTag);
  110. auto tag = tag_or_error.release_value();
  111. switch (tag) {
  112. case Constants::i32_tag:
  113. return ValueType(I32);
  114. case Constants::i64_tag:
  115. return ValueType(I64);
  116. case Constants::f32_tag:
  117. return ValueType(F32);
  118. case Constants::f64_tag:
  119. return ValueType(F64);
  120. case Constants::v128_tag:
  121. return ValueType(V128);
  122. case Constants::function_reference_tag:
  123. return ValueType(FunctionReference);
  124. case Constants::extern_reference_tag:
  125. return ValueType(ExternReference);
  126. default:
  127. return with_eof_check(stream, ParseError::InvalidTag);
  128. }
  129. }
  130. ParseResult<ResultType> ResultType::parse(Stream& stream)
  131. {
  132. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ResultType"sv);
  133. auto types = TRY(parse_vector<ValueType>(stream));
  134. return ResultType { types };
  135. }
  136. ParseResult<FunctionType> FunctionType::parse(Stream& stream)
  137. {
  138. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionType"sv);
  139. auto tag_or_error = stream.read_value<u8>();
  140. if (tag_or_error.is_error())
  141. return with_eof_check(stream, ParseError::ExpectedKindTag);
  142. auto tag = tag_or_error.release_value();
  143. if (tag != Constants::function_signature_tag) {
  144. dbgln("Expected 0x60, but found {:#x}", tag);
  145. return with_eof_check(stream, ParseError::InvalidTag);
  146. }
  147. auto parameters_result = TRY(parse_vector<ValueType>(stream));
  148. auto results_result = TRY(parse_vector<ValueType>(stream));
  149. return FunctionType { parameters_result, results_result };
  150. }
  151. ParseResult<Limits> Limits::parse(Stream& stream)
  152. {
  153. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Limits"sv);
  154. auto flag_or_error = stream.read_value<u8>();
  155. if (flag_or_error.is_error())
  156. return with_eof_check(stream, ParseError::ExpectedKindTag);
  157. auto flag = flag_or_error.release_value();
  158. if (flag > 1)
  159. return with_eof_check(stream, ParseError::InvalidTag);
  160. auto min_or_error = stream.read_value<LEB128<u32>>();
  161. if (min_or_error.is_error())
  162. return with_eof_check(stream, ParseError::ExpectedSize);
  163. size_t min = min_or_error.release_value();
  164. Optional<u32> max;
  165. if (flag) {
  166. auto value_or_error = stream.read_value<LEB128<u32>>();
  167. if (value_or_error.is_error())
  168. return with_eof_check(stream, ParseError::ExpectedSize);
  169. max = value_or_error.release_value();
  170. }
  171. return Limits { static_cast<u32>(min), move(max) };
  172. }
  173. ParseResult<MemoryType> MemoryType::parse(Stream& stream)
  174. {
  175. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemoryType"sv);
  176. auto limits_result = TRY(Limits::parse(stream));
  177. return MemoryType { limits_result };
  178. }
  179. ParseResult<TableType> TableType::parse(Stream& stream)
  180. {
  181. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableType"sv);
  182. auto type_result = TRY(ValueType::parse(stream));
  183. if (!type_result.is_reference())
  184. return with_eof_check(stream, ParseError::InvalidType);
  185. auto limits_result = TRY(Limits::parse(stream));
  186. return TableType { type_result, limits_result };
  187. }
  188. ParseResult<GlobalType> GlobalType::parse(Stream& stream)
  189. {
  190. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalType"sv);
  191. auto type_result = TRY(ValueType::parse(stream));
  192. auto mutable_or_error = stream.read_value<u8>();
  193. if (mutable_or_error.is_error())
  194. return with_eof_check(stream, ParseError::ExpectedKindTag);
  195. auto mutable_ = mutable_or_error.release_value();
  196. if (mutable_ > 1)
  197. return with_eof_check(stream, ParseError::InvalidTag);
  198. return GlobalType { type_result, mutable_ == 0x01 };
  199. }
  200. ParseResult<BlockType> BlockType::parse(Stream& stream)
  201. {
  202. ScopeLogger<WASM_BINPARSER_DEBUG> logger("BlockType"sv);
  203. auto kind_or_error = stream.read_value<u8>();
  204. if (kind_or_error.is_error())
  205. return with_eof_check(stream, ParseError::ExpectedKindTag);
  206. auto kind = kind_or_error.release_value();
  207. if (kind == Constants::empty_block_tag)
  208. return BlockType {};
  209. {
  210. FixedMemoryStream value_stream { ReadonlyBytes { &kind, 1 } };
  211. if (auto value_type = ValueType::parse(value_stream); !value_type.is_error())
  212. return BlockType { value_type.release_value() };
  213. }
  214. ReconsumableStream new_stream { stream };
  215. new_stream.unread({ &kind, 1 });
  216. // FIXME: should be an i33. Right now, we're missing a potential last bit at
  217. // the end. See https://webassembly.github.io/spec/core/binary/instructions.html#binary-blocktype
  218. auto index_value_or_error = new_stream.read_value<LEB128<i32>>();
  219. if (index_value_or_error.is_error())
  220. return with_eof_check(stream, ParseError::ExpectedIndex);
  221. i32 index_value = index_value_or_error.release_value();
  222. if (index_value < 0) {
  223. dbgln("Invalid type index {}", index_value);
  224. return with_eof_check(stream, ParseError::InvalidIndex);
  225. }
  226. return BlockType { TypeIndex(index_value) };
  227. }
  228. ParseResult<Vector<Instruction>> Instruction::parse(Stream& stream, InstructionPointer& ip)
  229. {
  230. struct NestedInstructionState {
  231. Vector<Instruction> prior_instructions;
  232. OpCode opcode;
  233. BlockType block_type;
  234. InstructionPointer end_ip;
  235. Optional<InstructionPointer> else_ip;
  236. };
  237. Vector<NestedInstructionState, 4> nested_instructions;
  238. Vector<Instruction> resulting_instructions;
  239. do {
  240. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Instruction"sv);
  241. auto byte_or_error = stream.read_value<u8>();
  242. if (byte_or_error.is_error())
  243. return with_eof_check(stream, ParseError::ExpectedKindTag);
  244. auto byte = byte_or_error.release_value();
  245. if (!nested_instructions.is_empty()) {
  246. auto& nested_structure = nested_instructions.last();
  247. if (byte == 0x0b) {
  248. // block/loop/if end
  249. nested_structure.end_ip = ip + (nested_structure.else_ip.has_value() ? 1 : 0);
  250. ++ip;
  251. // Transform op(..., instr*) -> op(...) instr* op(end(ip))
  252. auto instructions = move(nested_structure.prior_instructions);
  253. instructions.ensure_capacity(instructions.size() + 2 + resulting_instructions.size());
  254. instructions.append(Instruction { nested_structure.opcode, StructuredInstructionArgs { nested_structure.block_type, nested_structure.end_ip, nested_structure.else_ip } });
  255. instructions.extend(move(resulting_instructions));
  256. instructions.append(Instruction { Instructions::structured_end });
  257. resulting_instructions = move(instructions);
  258. nested_instructions.take_last();
  259. continue;
  260. }
  261. if (byte == 0x05) {
  262. // if...else
  263. // Transform op(..., instr*, instr*) -> op(...) instr* op(else(ip) instr* op(end(ip))
  264. resulting_instructions.append(Instruction { Instructions::structured_else });
  265. ++ip;
  266. nested_structure.else_ip = ip.value();
  267. continue;
  268. }
  269. }
  270. OpCode opcode { byte };
  271. ++ip;
  272. switch (opcode.value()) {
  273. case Instructions::block.value():
  274. case Instructions::loop.value():
  275. case Instructions::if_.value(): {
  276. auto block_type = TRY(BlockType::parse(stream));
  277. nested_instructions.append({ move(resulting_instructions), opcode, block_type, {}, {} });
  278. resulting_instructions = {};
  279. break;
  280. }
  281. case Instructions::br.value():
  282. case Instructions::br_if.value(): {
  283. // branches with a single label immediate
  284. auto index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
  285. resulting_instructions.append(Instruction { opcode, index });
  286. break;
  287. }
  288. case Instructions::br_table.value(): {
  289. // br_table label* label
  290. auto labels = TRY(parse_vector<GenericIndexParser<LabelIndex>>(stream));
  291. auto default_label = TRY(GenericIndexParser<LabelIndex>::parse(stream));
  292. resulting_instructions.append(Instruction { opcode, TableBranchArgs { labels, default_label } });
  293. break;
  294. }
  295. case Instructions::call.value(): {
  296. // call function
  297. auto function_index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  298. resulting_instructions.append(Instruction { opcode, function_index });
  299. break;
  300. }
  301. case Instructions::call_indirect.value(): {
  302. // call_indirect type table
  303. auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
  304. auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  305. resulting_instructions.append(Instruction { opcode, IndirectCallArgs { type_index, table_index } });
  306. break;
  307. }
  308. case Instructions::i32_load.value():
  309. case Instructions::i64_load.value():
  310. case Instructions::f32_load.value():
  311. case Instructions::f64_load.value():
  312. case Instructions::i32_load8_s.value():
  313. case Instructions::i32_load8_u.value():
  314. case Instructions::i32_load16_s.value():
  315. case Instructions::i32_load16_u.value():
  316. case Instructions::i64_load8_s.value():
  317. case Instructions::i64_load8_u.value():
  318. case Instructions::i64_load16_s.value():
  319. case Instructions::i64_load16_u.value():
  320. case Instructions::i64_load32_s.value():
  321. case Instructions::i64_load32_u.value():
  322. case Instructions::i32_store.value():
  323. case Instructions::i64_store.value():
  324. case Instructions::f32_store.value():
  325. case Instructions::f64_store.value():
  326. case Instructions::i32_store8.value():
  327. case Instructions::i32_store16.value():
  328. case Instructions::i64_store8.value():
  329. case Instructions::i64_store16.value():
  330. case Instructions::i64_store32.value(): {
  331. // op (align [multi-memory: memindex] offset)
  332. auto align_or_error = stream.read_value<LEB128<u32>>();
  333. if (align_or_error.is_error())
  334. return with_eof_check(stream, ParseError::InvalidInput);
  335. size_t align = align_or_error.release_value();
  336. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  337. size_t memory_index = 0;
  338. if ((align & 0x20) != 0) {
  339. align &= ~0x20;
  340. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  341. if (memory_index_or_error.is_error())
  342. return with_eof_check(stream, ParseError::InvalidInput);
  343. memory_index = memory_index_or_error.release_value();
  344. }
  345. auto offset_or_error = stream.read_value<LEB128<u32>>();
  346. if (offset_or_error.is_error())
  347. return with_eof_check(stream, ParseError::InvalidInput);
  348. size_t offset = offset_or_error.release_value();
  349. resulting_instructions.append(Instruction { opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) } });
  350. break;
  351. }
  352. case Instructions::local_get.value():
  353. case Instructions::local_set.value():
  354. case Instructions::local_tee.value(): {
  355. auto index = TRY(GenericIndexParser<LocalIndex>::parse(stream));
  356. resulting_instructions.append(Instruction { opcode, index });
  357. break;
  358. }
  359. case Instructions::global_get.value():
  360. case Instructions::global_set.value(): {
  361. auto index = TRY(GenericIndexParser<GlobalIndex>::parse(stream));
  362. resulting_instructions.append(Instruction { opcode, index });
  363. break;
  364. }
  365. case Instructions::memory_size.value():
  366. case Instructions::memory_grow.value(): {
  367. // op [multi-memory: memindex]|0x00
  368. auto memory_index_or_error = stream.read_value<u8>();
  369. if (memory_index_or_error.is_error())
  370. return with_eof_check(stream, ParseError::ExpectedKindTag);
  371. auto memory_index = memory_index_or_error.release_value();
  372. resulting_instructions.append(Instruction { opcode, MemoryIndexArgument { MemoryIndex(memory_index) } });
  373. break;
  374. }
  375. case Instructions::i32_const.value(): {
  376. auto value_or_error = stream.read_value<LEB128<i32>>();
  377. if (value_or_error.is_error())
  378. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  379. i32 value = value_or_error.release_value();
  380. resulting_instructions.append(Instruction { opcode, value });
  381. break;
  382. }
  383. case Instructions::i64_const.value(): {
  384. // op literal
  385. auto value_or_error = stream.read_value<LEB128<i64>>();
  386. if (value_or_error.is_error())
  387. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  388. i64 value = value_or_error.release_value();
  389. resulting_instructions.append(Instruction { opcode, value });
  390. break;
  391. }
  392. case Instructions::f32_const.value(): {
  393. // op literal
  394. auto value_or_error = stream.read_value<LittleEndian<u32>>();
  395. if (value_or_error.is_error())
  396. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  397. auto value = value_or_error.release_value();
  398. auto floating = bit_cast<float>(static_cast<u32>(value));
  399. resulting_instructions.append(Instruction { opcode, floating });
  400. break;
  401. }
  402. case Instructions::f64_const.value(): {
  403. // op literal
  404. auto value_or_error = stream.read_value<LittleEndian<u64>>();
  405. if (value_or_error.is_error())
  406. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  407. auto value = value_or_error.release_value();
  408. auto floating = bit_cast<double>(static_cast<u64>(value));
  409. resulting_instructions.append(Instruction { opcode, floating });
  410. break;
  411. }
  412. case Instructions::table_get.value():
  413. case Instructions::table_set.value(): {
  414. auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  415. resulting_instructions.append(Instruction { opcode, index });
  416. break;
  417. }
  418. case Instructions::select_typed.value(): {
  419. auto types = TRY(parse_vector<ValueType>(stream));
  420. resulting_instructions.append(Instruction { opcode, types });
  421. break;
  422. }
  423. case Instructions::ref_null.value(): {
  424. auto type = TRY(ValueType::parse(stream));
  425. if (!type.is_reference())
  426. return ParseError::InvalidType;
  427. resulting_instructions.append(Instruction { opcode, type });
  428. break;
  429. }
  430. case Instructions::ref_func.value(): {
  431. auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  432. resulting_instructions.append(Instruction { opcode, index });
  433. break;
  434. }
  435. case Instructions::ref_is_null.value():
  436. case Instructions::unreachable.value():
  437. case Instructions::nop.value():
  438. case Instructions::return_.value():
  439. case Instructions::drop.value():
  440. case Instructions::select.value():
  441. case Instructions::i32_eqz.value():
  442. case Instructions::i32_eq.value():
  443. case Instructions::i32_ne.value():
  444. case Instructions::i32_lts.value():
  445. case Instructions::i32_ltu.value():
  446. case Instructions::i32_gts.value():
  447. case Instructions::i32_gtu.value():
  448. case Instructions::i32_les.value():
  449. case Instructions::i32_leu.value():
  450. case Instructions::i32_ges.value():
  451. case Instructions::i32_geu.value():
  452. case Instructions::i64_eqz.value():
  453. case Instructions::i64_eq.value():
  454. case Instructions::i64_ne.value():
  455. case Instructions::i64_lts.value():
  456. case Instructions::i64_ltu.value():
  457. case Instructions::i64_gts.value():
  458. case Instructions::i64_gtu.value():
  459. case Instructions::i64_les.value():
  460. case Instructions::i64_leu.value():
  461. case Instructions::i64_ges.value():
  462. case Instructions::i64_geu.value():
  463. case Instructions::f32_eq.value():
  464. case Instructions::f32_ne.value():
  465. case Instructions::f32_lt.value():
  466. case Instructions::f32_gt.value():
  467. case Instructions::f32_le.value():
  468. case Instructions::f32_ge.value():
  469. case Instructions::f64_eq.value():
  470. case Instructions::f64_ne.value():
  471. case Instructions::f64_lt.value():
  472. case Instructions::f64_gt.value():
  473. case Instructions::f64_le.value():
  474. case Instructions::f64_ge.value():
  475. case Instructions::i32_clz.value():
  476. case Instructions::i32_ctz.value():
  477. case Instructions::i32_popcnt.value():
  478. case Instructions::i32_add.value():
  479. case Instructions::i32_sub.value():
  480. case Instructions::i32_mul.value():
  481. case Instructions::i32_divs.value():
  482. case Instructions::i32_divu.value():
  483. case Instructions::i32_rems.value():
  484. case Instructions::i32_remu.value():
  485. case Instructions::i32_and.value():
  486. case Instructions::i32_or.value():
  487. case Instructions::i32_xor.value():
  488. case Instructions::i32_shl.value():
  489. case Instructions::i32_shrs.value():
  490. case Instructions::i32_shru.value():
  491. case Instructions::i32_rotl.value():
  492. case Instructions::i32_rotr.value():
  493. case Instructions::i64_clz.value():
  494. case Instructions::i64_ctz.value():
  495. case Instructions::i64_popcnt.value():
  496. case Instructions::i64_add.value():
  497. case Instructions::i64_sub.value():
  498. case Instructions::i64_mul.value():
  499. case Instructions::i64_divs.value():
  500. case Instructions::i64_divu.value():
  501. case Instructions::i64_rems.value():
  502. case Instructions::i64_remu.value():
  503. case Instructions::i64_and.value():
  504. case Instructions::i64_or.value():
  505. case Instructions::i64_xor.value():
  506. case Instructions::i64_shl.value():
  507. case Instructions::i64_shrs.value():
  508. case Instructions::i64_shru.value():
  509. case Instructions::i64_rotl.value():
  510. case Instructions::i64_rotr.value():
  511. case Instructions::f32_abs.value():
  512. case Instructions::f32_neg.value():
  513. case Instructions::f32_ceil.value():
  514. case Instructions::f32_floor.value():
  515. case Instructions::f32_trunc.value():
  516. case Instructions::f32_nearest.value():
  517. case Instructions::f32_sqrt.value():
  518. case Instructions::f32_add.value():
  519. case Instructions::f32_sub.value():
  520. case Instructions::f32_mul.value():
  521. case Instructions::f32_div.value():
  522. case Instructions::f32_min.value():
  523. case Instructions::f32_max.value():
  524. case Instructions::f32_copysign.value():
  525. case Instructions::f64_abs.value():
  526. case Instructions::f64_neg.value():
  527. case Instructions::f64_ceil.value():
  528. case Instructions::f64_floor.value():
  529. case Instructions::f64_trunc.value():
  530. case Instructions::f64_nearest.value():
  531. case Instructions::f64_sqrt.value():
  532. case Instructions::f64_add.value():
  533. case Instructions::f64_sub.value():
  534. case Instructions::f64_mul.value():
  535. case Instructions::f64_div.value():
  536. case Instructions::f64_min.value():
  537. case Instructions::f64_max.value():
  538. case Instructions::f64_copysign.value():
  539. case Instructions::i32_wrap_i64.value():
  540. case Instructions::i32_trunc_sf32.value():
  541. case Instructions::i32_trunc_uf32.value():
  542. case Instructions::i32_trunc_sf64.value():
  543. case Instructions::i32_trunc_uf64.value():
  544. case Instructions::i64_extend_si32.value():
  545. case Instructions::i64_extend_ui32.value():
  546. case Instructions::i64_trunc_sf32.value():
  547. case Instructions::i64_trunc_uf32.value():
  548. case Instructions::i64_trunc_sf64.value():
  549. case Instructions::i64_trunc_uf64.value():
  550. case Instructions::f32_convert_si32.value():
  551. case Instructions::f32_convert_ui32.value():
  552. case Instructions::f32_convert_si64.value():
  553. case Instructions::f32_convert_ui64.value():
  554. case Instructions::f32_demote_f64.value():
  555. case Instructions::f64_convert_si32.value():
  556. case Instructions::f64_convert_ui32.value():
  557. case Instructions::f64_convert_si64.value():
  558. case Instructions::f64_convert_ui64.value():
  559. case Instructions::f64_promote_f32.value():
  560. case Instructions::i32_reinterpret_f32.value():
  561. case Instructions::i64_reinterpret_f64.value():
  562. case Instructions::f32_reinterpret_i32.value():
  563. case Instructions::f64_reinterpret_i64.value():
  564. case Instructions::i32_extend8_s.value():
  565. case Instructions::i32_extend16_s.value():
  566. case Instructions::i64_extend8_s.value():
  567. case Instructions::i64_extend16_s.value():
  568. case Instructions::i64_extend32_s.value():
  569. resulting_instructions.append(Instruction { opcode });
  570. break;
  571. case 0xfc:
  572. case 0xfd: {
  573. // These are multibyte instructions.
  574. auto selector_or_error = stream.read_value<LEB128<u32>>();
  575. if (selector_or_error.is_error())
  576. return with_eof_check(stream, ParseError::InvalidInput);
  577. u32 selector = selector_or_error.release_value();
  578. OpCode full_opcode = static_cast<u64>(opcode.value()) << 56 | selector;
  579. switch (full_opcode.value()) {
  580. case Instructions::i32_trunc_sat_f32_s.value():
  581. case Instructions::i32_trunc_sat_f32_u.value():
  582. case Instructions::i32_trunc_sat_f64_s.value():
  583. case Instructions::i32_trunc_sat_f64_u.value():
  584. case Instructions::i64_trunc_sat_f32_s.value():
  585. case Instructions::i64_trunc_sat_f32_u.value():
  586. case Instructions::i64_trunc_sat_f64_s.value():
  587. case Instructions::i64_trunc_sat_f64_u.value():
  588. resulting_instructions.append(Instruction { full_opcode });
  589. break;
  590. case Instructions::memory_init.value(): {
  591. auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
  592. // Proposal "multi-memory", literal 0x00 is replaced with a memory index.
  593. auto memory_index_or_error = stream.read_value<u8>();
  594. if (memory_index_or_error.is_error())
  595. return with_eof_check(stream, ParseError::InvalidInput);
  596. auto memory_index = memory_index_or_error.release_value();
  597. resulting_instructions.append(Instruction { full_opcode, MemoryInitArgs { index, MemoryIndex(memory_index) } });
  598. break;
  599. }
  600. case Instructions::data_drop.value(): {
  601. auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
  602. resulting_instructions.append(Instruction { full_opcode, index });
  603. break;
  604. }
  605. case Instructions::memory_copy.value(): {
  606. // Proposal "multi-memory", literal 0x00 is replaced with two memory indices, destination and source, respectively.
  607. MemoryIndex indices[] = { 0, 0 };
  608. for (size_t i = 0; i < 2; ++i) {
  609. auto memory_index_or_error = stream.read_value<u8>();
  610. if (memory_index_or_error.is_error())
  611. return with_eof_check(stream, ParseError::InvalidInput);
  612. indices[i] = memory_index_or_error.release_value();
  613. }
  614. resulting_instructions.append(Instruction { full_opcode, MemoryCopyArgs { indices[1], indices[0] } });
  615. break;
  616. }
  617. case Instructions::memory_fill.value(): {
  618. // Proposal "multi-memory", literal 0x00 is replaced with a memory index.
  619. auto memory_index_or_error = stream.read_value<u8>();
  620. if (memory_index_or_error.is_error())
  621. return with_eof_check(stream, ParseError::InvalidInput);
  622. auto memory_index = memory_index_or_error.release_value();
  623. resulting_instructions.append(Instruction { full_opcode, MemoryIndexArgument { MemoryIndex { memory_index } } });
  624. break;
  625. }
  626. case Instructions::table_init.value(): {
  627. auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
  628. auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  629. resulting_instructions.append(Instruction { full_opcode, TableElementArgs { element_index, table_index } });
  630. break;
  631. }
  632. case Instructions::elem_drop.value(): {
  633. auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
  634. resulting_instructions.append(Instruction { full_opcode, element_index });
  635. break;
  636. }
  637. case Instructions::table_copy.value(): {
  638. auto lhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
  639. auto rhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
  640. resulting_instructions.append(Instruction { full_opcode, TableTableArgs { lhs, rhs } });
  641. break;
  642. }
  643. case Instructions::table_grow.value():
  644. case Instructions::table_size.value():
  645. case Instructions::table_fill.value(): {
  646. auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  647. resulting_instructions.append(Instruction { full_opcode, index });
  648. break;
  649. }
  650. case Instructions::v128_load.value():
  651. case Instructions::v128_load8x8_s.value():
  652. case Instructions::v128_load8x8_u.value():
  653. case Instructions::v128_load16x4_s.value():
  654. case Instructions::v128_load16x4_u.value():
  655. case Instructions::v128_load32x2_s.value():
  656. case Instructions::v128_load32x2_u.value():
  657. case Instructions::v128_load8_splat.value():
  658. case Instructions::v128_load16_splat.value():
  659. case Instructions::v128_load32_splat.value():
  660. case Instructions::v128_load64_splat.value():
  661. case Instructions::v128_store.value(): {
  662. // op (align [multi-memory memindex] offset)
  663. auto align_or_error = stream.read_value<LEB128<u32>>();
  664. if (align_or_error.is_error())
  665. return with_eof_check(stream, ParseError::ExpectedIndex);
  666. size_t align = align_or_error.release_value();
  667. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  668. size_t memory_index = 0;
  669. if ((align & 0x20) != 0) {
  670. align &= ~0x20;
  671. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  672. if (memory_index_or_error.is_error())
  673. return with_eof_check(stream, ParseError::InvalidInput);
  674. memory_index = memory_index_or_error.release_value();
  675. }
  676. auto offset_or_error = stream.read_value<LEB128<u32>>();
  677. if (offset_or_error.is_error())
  678. return with_eof_check(stream, ParseError::ExpectedIndex);
  679. size_t offset = offset_or_error.release_value();
  680. resulting_instructions.append(Instruction { full_opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) } });
  681. break;
  682. }
  683. case Instructions::v128_load8_lane.value():
  684. case Instructions::v128_load16_lane.value():
  685. case Instructions::v128_load32_lane.value():
  686. case Instructions::v128_load64_lane.value():
  687. case Instructions::v128_store8_lane.value():
  688. case Instructions::v128_store16_lane.value():
  689. case Instructions::v128_store32_lane.value():
  690. case Instructions::v128_store64_lane.value(): {
  691. // op (align [multi-memory: memindex] offset) (index)
  692. auto align_or_error = stream.read_value<LEB128<u32>>();
  693. if (align_or_error.is_error())
  694. return with_eof_check(stream, ParseError::ExpectedIndex);
  695. size_t align = align_or_error.release_value();
  696. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  697. size_t memory_index = 0;
  698. if ((align & 0x20) != 0) {
  699. align &= ~0x20;
  700. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  701. if (memory_index_or_error.is_error())
  702. return with_eof_check(stream, ParseError::InvalidInput);
  703. memory_index = memory_index_or_error.release_value();
  704. }
  705. auto offset_or_error = stream.read_value<LEB128<u32>>();
  706. if (offset_or_error.is_error())
  707. return with_eof_check(stream, ParseError::ExpectedIndex);
  708. size_t offset = offset_or_error.release_value();
  709. auto index_or_error = stream.read_value<u8>();
  710. if (index_or_error.is_error())
  711. return with_eof_check(stream, ParseError::InvalidInput);
  712. auto index = index_or_error.release_value();
  713. resulting_instructions.append(Instruction { full_opcode, MemoryAndLaneArgument { { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) }, index } });
  714. break;
  715. }
  716. case Instructions::v128_const.value(): {
  717. // op (literal:16)
  718. auto value_or_error = stream.read_value<LittleEndian<u128>>();
  719. if (value_or_error.is_error())
  720. return with_eof_check(stream, ParseError::InvalidImmediate);
  721. resulting_instructions.append(Instruction { full_opcode, value_or_error.release_value() });
  722. break;
  723. }
  724. case Instructions::i8x16_shuffle.value(): {
  725. // op 16x(lane)
  726. u8 lanes[16];
  727. for (size_t i = 0; i < 16; ++i) {
  728. auto value_or_error = stream.read_value<u8>();
  729. if (value_or_error.is_error())
  730. return with_eof_check(stream, ParseError::InvalidInput);
  731. lanes[i] = value_or_error.release_value();
  732. }
  733. resulting_instructions.append(Instruction { full_opcode, ShuffleArgument(lanes) });
  734. break;
  735. }
  736. case Instructions::i8x16_extract_lane_s.value():
  737. case Instructions::i8x16_extract_lane_u.value():
  738. case Instructions::i8x16_replace_lane.value():
  739. case Instructions::i16x8_extract_lane_s.value():
  740. case Instructions::i16x8_extract_lane_u.value():
  741. case Instructions::i16x8_replace_lane.value():
  742. case Instructions::i32x4_extract_lane.value():
  743. case Instructions::i32x4_replace_lane.value():
  744. case Instructions::i64x2_extract_lane.value():
  745. case Instructions::i64x2_replace_lane.value():
  746. case Instructions::f32x4_extract_lane.value():
  747. case Instructions::f32x4_replace_lane.value():
  748. case Instructions::f64x2_extract_lane.value():
  749. case Instructions::f64x2_replace_lane.value(): {
  750. // op (lane)
  751. auto lane_or_error = stream.read_value<u8>();
  752. if (lane_or_error.is_error())
  753. return with_eof_check(stream, ParseError::InvalidInput);
  754. auto lane = lane_or_error.release_value();
  755. resulting_instructions.append(Instruction { full_opcode, LaneIndex { lane } });
  756. break;
  757. }
  758. case Instructions::i8x16_swizzle.value():
  759. case Instructions::i8x16_splat.value():
  760. case Instructions::i16x8_splat.value():
  761. case Instructions::i32x4_splat.value():
  762. case Instructions::i64x2_splat.value():
  763. case Instructions::f32x4_splat.value():
  764. case Instructions::f64x2_splat.value():
  765. case Instructions::i8x16_eq.value():
  766. case Instructions::i8x16_ne.value():
  767. case Instructions::i8x16_lt_s.value():
  768. case Instructions::i8x16_lt_u.value():
  769. case Instructions::i8x16_gt_s.value():
  770. case Instructions::i8x16_gt_u.value():
  771. case Instructions::i8x16_le_s.value():
  772. case Instructions::i8x16_le_u.value():
  773. case Instructions::i8x16_ge_s.value():
  774. case Instructions::i8x16_ge_u.value():
  775. case Instructions::i16x8_eq.value():
  776. case Instructions::i16x8_ne.value():
  777. case Instructions::i16x8_lt_s.value():
  778. case Instructions::i16x8_lt_u.value():
  779. case Instructions::i16x8_gt_s.value():
  780. case Instructions::i16x8_gt_u.value():
  781. case Instructions::i16x8_le_s.value():
  782. case Instructions::i16x8_le_u.value():
  783. case Instructions::i16x8_ge_s.value():
  784. case Instructions::i16x8_ge_u.value():
  785. case Instructions::i32x4_eq.value():
  786. case Instructions::i32x4_ne.value():
  787. case Instructions::i32x4_lt_s.value():
  788. case Instructions::i32x4_lt_u.value():
  789. case Instructions::i32x4_gt_s.value():
  790. case Instructions::i32x4_gt_u.value():
  791. case Instructions::i32x4_le_s.value():
  792. case Instructions::i32x4_le_u.value():
  793. case Instructions::i32x4_ge_s.value():
  794. case Instructions::i32x4_ge_u.value():
  795. case Instructions::f32x4_eq.value():
  796. case Instructions::f32x4_ne.value():
  797. case Instructions::f32x4_lt.value():
  798. case Instructions::f32x4_gt.value():
  799. case Instructions::f32x4_le.value():
  800. case Instructions::f32x4_ge.value():
  801. case Instructions::f64x2_eq.value():
  802. case Instructions::f64x2_ne.value():
  803. case Instructions::f64x2_lt.value():
  804. case Instructions::f64x2_gt.value():
  805. case Instructions::f64x2_le.value():
  806. case Instructions::f64x2_ge.value():
  807. case Instructions::v128_not.value():
  808. case Instructions::v128_and.value():
  809. case Instructions::v128_andnot.value():
  810. case Instructions::v128_or.value():
  811. case Instructions::v128_xor.value():
  812. case Instructions::v128_bitselect.value():
  813. case Instructions::v128_any_true.value():
  814. case Instructions::v128_load32_zero.value():
  815. case Instructions::v128_load64_zero.value():
  816. case Instructions::f32x4_demote_f64x2_zero.value():
  817. case Instructions::f64x2_promote_low_f32x4.value():
  818. case Instructions::i8x16_abs.value():
  819. case Instructions::i8x16_neg.value():
  820. case Instructions::i8x16_popcnt.value():
  821. case Instructions::i8x16_all_true.value():
  822. case Instructions::i8x16_bitmask.value():
  823. case Instructions::i8x16_narrow_i16x8_s.value():
  824. case Instructions::i8x16_narrow_i16x8_u.value():
  825. case Instructions::f32x4_ceil.value():
  826. case Instructions::f32x4_floor.value():
  827. case Instructions::f32x4_trunc.value():
  828. case Instructions::f32x4_nearest.value():
  829. case Instructions::i8x16_shl.value():
  830. case Instructions::i8x16_shr_s.value():
  831. case Instructions::i8x16_shr_u.value():
  832. case Instructions::i8x16_add.value():
  833. case Instructions::i8x16_add_sat_s.value():
  834. case Instructions::i8x16_add_sat_u.value():
  835. case Instructions::i8x16_sub.value():
  836. case Instructions::i8x16_sub_sat_s.value():
  837. case Instructions::i8x16_sub_sat_u.value():
  838. case Instructions::f64x2_ceil.value():
  839. case Instructions::f64x2_floor.value():
  840. case Instructions::i8x16_min_s.value():
  841. case Instructions::i8x16_min_u.value():
  842. case Instructions::i8x16_max_s.value():
  843. case Instructions::i8x16_max_u.value():
  844. case Instructions::f64x2_trunc.value():
  845. case Instructions::i8x16_avgr_u.value():
  846. case Instructions::i16x8_extadd_pairwise_i8x16_s.value():
  847. case Instructions::i16x8_extadd_pairwise_i8x16_u.value():
  848. case Instructions::i32x4_extadd_pairwise_i16x8_s.value():
  849. case Instructions::i32x4_extadd_pairwise_i16x8_u.value():
  850. case Instructions::i16x8_abs.value():
  851. case Instructions::i16x8_neg.value():
  852. case Instructions::i16x8_q15mulr_sat_s.value():
  853. case Instructions::i16x8_all_true.value():
  854. case Instructions::i16x8_bitmask.value():
  855. case Instructions::i16x8_narrow_i32x4_s.value():
  856. case Instructions::i16x8_narrow_i32x4_u.value():
  857. case Instructions::i16x8_extend_low_i8x16_s.value():
  858. case Instructions::i16x8_extend_high_i8x16_s.value():
  859. case Instructions::i16x8_extend_low_i8x16_u.value():
  860. case Instructions::i16x8_extend_high_i8x16_u.value():
  861. case Instructions::i16x8_shl.value():
  862. case Instructions::i16x8_shr_s.value():
  863. case Instructions::i16x8_shr_u.value():
  864. case Instructions::i16x8_add.value():
  865. case Instructions::i16x8_add_sat_s.value():
  866. case Instructions::i16x8_add_sat_u.value():
  867. case Instructions::i16x8_sub.value():
  868. case Instructions::i16x8_sub_sat_s.value():
  869. case Instructions::i16x8_sub_sat_u.value():
  870. case Instructions::f64x2_nearest.value():
  871. case Instructions::i16x8_mul.value():
  872. case Instructions::i16x8_min_s.value():
  873. case Instructions::i16x8_min_u.value():
  874. case Instructions::i16x8_max_s.value():
  875. case Instructions::i16x8_max_u.value():
  876. case Instructions::i16x8_avgr_u.value():
  877. case Instructions::i16x8_extmul_low_i8x16_s.value():
  878. case Instructions::i16x8_extmul_high_i8x16_s.value():
  879. case Instructions::i16x8_extmul_low_i8x16_u.value():
  880. case Instructions::i16x8_extmul_high_i8x16_u.value():
  881. case Instructions::i32x4_abs.value():
  882. case Instructions::i32x4_neg.value():
  883. case Instructions::i32x4_all_true.value():
  884. case Instructions::i32x4_bitmask.value():
  885. case Instructions::i32x4_extend_low_i16x8_s.value():
  886. case Instructions::i32x4_extend_high_i16x8_s.value():
  887. case Instructions::i32x4_extend_low_i16x8_u.value():
  888. case Instructions::i32x4_extend_high_i16x8_u.value():
  889. case Instructions::i32x4_shl.value():
  890. case Instructions::i32x4_shr_s.value():
  891. case Instructions::i32x4_shr_u.value():
  892. case Instructions::i32x4_add.value():
  893. case Instructions::i32x4_sub.value():
  894. case Instructions::i32x4_mul.value():
  895. case Instructions::i32x4_min_s.value():
  896. case Instructions::i32x4_min_u.value():
  897. case Instructions::i32x4_max_s.value():
  898. case Instructions::i32x4_max_u.value():
  899. case Instructions::i32x4_dot_i16x8_s.value():
  900. case Instructions::i32x4_extmul_low_i16x8_s.value():
  901. case Instructions::i32x4_extmul_high_i16x8_s.value():
  902. case Instructions::i32x4_extmul_low_i16x8_u.value():
  903. case Instructions::i32x4_extmul_high_i16x8_u.value():
  904. case Instructions::i64x2_abs.value():
  905. case Instructions::i64x2_neg.value():
  906. case Instructions::i64x2_all_true.value():
  907. case Instructions::i64x2_bitmask.value():
  908. case Instructions::i64x2_extend_low_i32x4_s.value():
  909. case Instructions::i64x2_extend_high_i32x4_s.value():
  910. case Instructions::i64x2_extend_low_i32x4_u.value():
  911. case Instructions::i64x2_extend_high_i32x4_u.value():
  912. case Instructions::i64x2_shl.value():
  913. case Instructions::i64x2_shr_s.value():
  914. case Instructions::i64x2_shr_u.value():
  915. case Instructions::i64x2_add.value():
  916. case Instructions::i64x2_sub.value():
  917. case Instructions::i64x2_mul.value():
  918. case Instructions::i64x2_eq.value():
  919. case Instructions::i64x2_ne.value():
  920. case Instructions::i64x2_lt_s.value():
  921. case Instructions::i64x2_gt_s.value():
  922. case Instructions::i64x2_le_s.value():
  923. case Instructions::i64x2_ge_s.value():
  924. case Instructions::i64x2_extmul_low_i32x4_s.value():
  925. case Instructions::i64x2_extmul_high_i32x4_s.value():
  926. case Instructions::i64x2_extmul_low_i32x4_u.value():
  927. case Instructions::i64x2_extmul_high_i32x4_u.value():
  928. case Instructions::f32x4_abs.value():
  929. case Instructions::f32x4_neg.value():
  930. case Instructions::f32x4_sqrt.value():
  931. case Instructions::f32x4_add.value():
  932. case Instructions::f32x4_sub.value():
  933. case Instructions::f32x4_mul.value():
  934. case Instructions::f32x4_div.value():
  935. case Instructions::f32x4_min.value():
  936. case Instructions::f32x4_max.value():
  937. case Instructions::f32x4_pmin.value():
  938. case Instructions::f32x4_pmax.value():
  939. case Instructions::f64x2_abs.value():
  940. case Instructions::f64x2_neg.value():
  941. case Instructions::f64x2_sqrt.value():
  942. case Instructions::f64x2_add.value():
  943. case Instructions::f64x2_sub.value():
  944. case Instructions::f64x2_mul.value():
  945. case Instructions::f64x2_div.value():
  946. case Instructions::f64x2_min.value():
  947. case Instructions::f64x2_max.value():
  948. case Instructions::f64x2_pmin.value():
  949. case Instructions::f64x2_pmax.value():
  950. case Instructions::i32x4_trunc_sat_f32x4_s.value():
  951. case Instructions::i32x4_trunc_sat_f32x4_u.value():
  952. case Instructions::f32x4_convert_i32x4_s.value():
  953. case Instructions::f32x4_convert_i32x4_u.value():
  954. case Instructions::i32x4_trunc_sat_f64x2_s_zero.value():
  955. case Instructions::i32x4_trunc_sat_f64x2_u_zero.value():
  956. case Instructions::f64x2_convert_low_i32x4_s.value():
  957. case Instructions::f64x2_convert_low_i32x4_u.value():
  958. // op
  959. resulting_instructions.append(Instruction { full_opcode });
  960. break;
  961. default:
  962. return ParseError::UnknownInstruction;
  963. }
  964. }
  965. }
  966. } while (!nested_instructions.is_empty());
  967. return resulting_instructions;
  968. }
  969. ParseResult<CustomSection> CustomSection::parse(Stream& stream)
  970. {
  971. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CustomSection"sv);
  972. auto name = TRY(parse_name(stream));
  973. ByteBuffer data_buffer;
  974. if (data_buffer.try_resize(64).is_error())
  975. return ParseError::OutOfMemory;
  976. while (!stream.is_eof()) {
  977. char buf[16];
  978. auto span_or_error = stream.read_some({ buf, 16 });
  979. if (span_or_error.is_error())
  980. break;
  981. auto size = span_or_error.release_value().size();
  982. if (size == 0)
  983. break;
  984. if (data_buffer.try_append(buf, size).is_error())
  985. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  986. }
  987. return CustomSection(name, move(data_buffer));
  988. }
  989. ParseResult<TypeSection> TypeSection::parse(Stream& stream)
  990. {
  991. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection"sv);
  992. auto types = TRY(parse_vector<FunctionType>(stream));
  993. return TypeSection { types };
  994. }
  995. ParseResult<ImportSection::Import> ImportSection::Import::parse(Stream& stream)
  996. {
  997. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import"sv);
  998. auto module = TRY(parse_name(stream));
  999. auto name = TRY(parse_name(stream));
  1000. auto tag_or_error = stream.read_value<u8>();
  1001. if (tag_or_error.is_error())
  1002. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1003. auto tag = tag_or_error.release_value();
  1004. switch (tag) {
  1005. case Constants::extern_function_tag: {
  1006. auto index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
  1007. return Import { module, name, index };
  1008. }
  1009. case Constants::extern_table_tag:
  1010. return parse_with_type<TableType>(stream, module, name);
  1011. case Constants::extern_memory_tag:
  1012. return parse_with_type<MemoryType>(stream, module, name);
  1013. case Constants::extern_global_tag:
  1014. return parse_with_type<GlobalType>(stream, module, name);
  1015. default:
  1016. return with_eof_check(stream, ParseError::InvalidTag);
  1017. }
  1018. }
  1019. ParseResult<ImportSection> ImportSection::parse(Stream& stream)
  1020. {
  1021. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection"sv);
  1022. auto imports = TRY(parse_vector<Import>(stream));
  1023. return ImportSection { imports };
  1024. }
  1025. ParseResult<FunctionSection> FunctionSection::parse(Stream& stream)
  1026. {
  1027. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection"sv);
  1028. auto indices = TRY(parse_vector<u32>(stream));
  1029. Vector<TypeIndex> typed_indices;
  1030. typed_indices.ensure_capacity(indices.size());
  1031. for (auto entry : indices)
  1032. typed_indices.append(entry);
  1033. return FunctionSection { move(typed_indices) };
  1034. }
  1035. ParseResult<TableSection::Table> TableSection::Table::parse(Stream& stream)
  1036. {
  1037. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table"sv);
  1038. auto type = TRY(TableType::parse(stream));
  1039. return Table { type };
  1040. }
  1041. ParseResult<TableSection> TableSection::parse(Stream& stream)
  1042. {
  1043. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection"sv);
  1044. auto tables = TRY(parse_vector<Table>(stream));
  1045. return TableSection { tables };
  1046. }
  1047. ParseResult<MemorySection::Memory> MemorySection::Memory::parse(Stream& stream)
  1048. {
  1049. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory"sv);
  1050. auto type = TRY(MemoryType::parse(stream));
  1051. return Memory { type };
  1052. }
  1053. ParseResult<MemorySection> MemorySection::parse(Stream& stream)
  1054. {
  1055. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection"sv);
  1056. auto memories = TRY(parse_vector<Memory>(stream));
  1057. return MemorySection { memories };
  1058. }
  1059. ParseResult<Expression> Expression::parse(Stream& stream)
  1060. {
  1061. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression"sv);
  1062. InstructionPointer ip { 0 };
  1063. auto instructions = parse_until_any_of<Instruction, 0x0b>(stream, ip);
  1064. if (instructions.is_error())
  1065. return instructions.error();
  1066. return Expression { move(instructions.value().values) };
  1067. }
  1068. ParseResult<GlobalSection::Global> GlobalSection::Global::parse(Stream& stream)
  1069. {
  1070. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global"sv);
  1071. auto type = TRY(GlobalType::parse(stream));
  1072. auto exprs = TRY(Expression::parse(stream));
  1073. return Global { type, exprs };
  1074. }
  1075. ParseResult<GlobalSection> GlobalSection::parse(Stream& stream)
  1076. {
  1077. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection"sv);
  1078. auto result = TRY(parse_vector<Global>(stream));
  1079. return GlobalSection { result };
  1080. }
  1081. ParseResult<ExportSection::Export> ExportSection::Export::parse(Stream& stream)
  1082. {
  1083. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export"sv);
  1084. auto name = TRY(parse_name(stream));
  1085. auto tag_or_error = stream.read_value<u8>();
  1086. if (tag_or_error.is_error())
  1087. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1088. auto tag = tag_or_error.release_value();
  1089. auto index_or_error = stream.read_value<LEB128<u32>>();
  1090. if (index_or_error.is_error())
  1091. return with_eof_check(stream, ParseError::ExpectedIndex);
  1092. size_t index = index_or_error.release_value();
  1093. switch (tag) {
  1094. case Constants::extern_function_tag:
  1095. return Export { name, ExportDesc { FunctionIndex { index } } };
  1096. case Constants::extern_table_tag:
  1097. return Export { name, ExportDesc { TableIndex { index } } };
  1098. case Constants::extern_memory_tag:
  1099. return Export { name, ExportDesc { MemoryIndex { index } } };
  1100. case Constants::extern_global_tag:
  1101. return Export { name, ExportDesc { GlobalIndex { index } } };
  1102. default:
  1103. return with_eof_check(stream, ParseError::InvalidTag);
  1104. }
  1105. }
  1106. ParseResult<ExportSection> ExportSection::parse(Stream& stream)
  1107. {
  1108. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection"sv);
  1109. auto result = TRY(parse_vector<Export>(stream));
  1110. return ExportSection { result };
  1111. }
  1112. ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(Stream& stream)
  1113. {
  1114. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction"sv);
  1115. auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  1116. return StartFunction { index };
  1117. }
  1118. ParseResult<StartSection> StartSection::parse(Stream& stream)
  1119. {
  1120. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection"sv);
  1121. auto result = TRY(StartFunction::parse(stream));
  1122. return StartSection { result };
  1123. }
  1124. ParseResult<ElementSection::Element> ElementSection::Element::parse(Stream& stream)
  1125. {
  1126. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element"sv);
  1127. auto tag_or_error = stream.read_value<LEB128<u32>>();
  1128. if (tag_or_error.is_error())
  1129. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1130. auto tag = tag_or_error.release_value();
  1131. if (tag > 0x07)
  1132. return ParseError::InvalidTag;
  1133. auto has_passive = (tag & 0x01) != 0;
  1134. auto has_explicit_index = (tag & 0x02) != 0;
  1135. auto has_exprs = (tag & 0x04) != 0;
  1136. Variant<Active, Passive, Declarative> mode = Passive {};
  1137. if (has_passive) {
  1138. if (has_explicit_index) {
  1139. mode = Declarative {};
  1140. } else {
  1141. mode = Passive {};
  1142. }
  1143. } else {
  1144. TableIndex table_index = 0;
  1145. if (has_explicit_index)
  1146. table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  1147. auto expression = TRY(Expression::parse(stream));
  1148. mode = Active { table_index, expression };
  1149. }
  1150. auto type = ValueType(ValueType::FunctionReference);
  1151. if (has_passive || has_explicit_index) {
  1152. if (has_exprs) {
  1153. type = TRY(ValueType::parse(stream));
  1154. } else {
  1155. auto extern_or_error = stream.read_value<u8>();
  1156. if (extern_or_error.is_error())
  1157. return with_eof_check(stream, ParseError::InvalidType);
  1158. // Make sure that this is a function, as it's technically only the
  1159. // allowed one.
  1160. if (extern_or_error.release_value() != 0x00) {
  1161. return ParseError::InvalidType;
  1162. }
  1163. type = ValueType(ValueType::FunctionReference);
  1164. }
  1165. }
  1166. Vector<Expression> items;
  1167. if (!has_exprs) {
  1168. auto indices = TRY(parse_vector<GenericIndexParser<FunctionIndex>>(stream));
  1169. Vector<Instruction> instructions;
  1170. for (auto& index : indices)
  1171. instructions.empend(Instructions::ref_func, index);
  1172. items = { Expression { move(instructions) } };
  1173. } else {
  1174. items = TRY(parse_vector<Expression>(stream));
  1175. }
  1176. return Element { type, move(items), move(mode) };
  1177. }
  1178. ParseResult<ElementSection> ElementSection::parse(Stream& stream)
  1179. {
  1180. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection"sv);
  1181. auto result = TRY(parse_vector<Element>(stream));
  1182. return ElementSection { result };
  1183. }
  1184. ParseResult<Locals> Locals::parse(Stream& stream)
  1185. {
  1186. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals"sv);
  1187. auto count_or_error = stream.read_value<LEB128<u32>>();
  1188. if (count_or_error.is_error())
  1189. return with_eof_check(stream, ParseError::InvalidSize);
  1190. size_t count = count_or_error.release_value();
  1191. if (count > Constants::max_allowed_function_locals_per_type)
  1192. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  1193. auto type = TRY(ValueType::parse(stream));
  1194. return Locals { static_cast<u32>(count), type };
  1195. }
  1196. ParseResult<CodeSection::Func> CodeSection::Func::parse(Stream& stream)
  1197. {
  1198. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func"sv);
  1199. auto locals = TRY(parse_vector<Locals>(stream));
  1200. auto body = TRY(Expression::parse(stream));
  1201. return Func { locals, body };
  1202. }
  1203. ParseResult<CodeSection::Code> CodeSection::Code::parse(Stream& stream)
  1204. {
  1205. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code"sv);
  1206. auto size_or_error = stream.read_value<LEB128<u32>>();
  1207. if (size_or_error.is_error())
  1208. return with_eof_check(stream, ParseError::InvalidSize);
  1209. size_t size = size_or_error.release_value();
  1210. auto constrained_stream = ConstrainedStream { MaybeOwned<Stream>(stream), size };
  1211. auto func = TRY(Func::parse(constrained_stream));
  1212. return Code { static_cast<u32>(size), func };
  1213. }
  1214. ParseResult<CodeSection> CodeSection::parse(Stream& stream)
  1215. {
  1216. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection"sv);
  1217. auto result = TRY(parse_vector<Code>(stream));
  1218. return CodeSection { result };
  1219. }
  1220. ParseResult<DataSection::Data> DataSection::Data::parse(Stream& stream)
  1221. {
  1222. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data"sv);
  1223. auto tag_or_error = stream.read_value<LEB128<u32>>();
  1224. if (tag_or_error.is_error())
  1225. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1226. auto tag = tag_or_error.release_value();
  1227. if (tag > 0x02)
  1228. return with_eof_check(stream, ParseError::InvalidTag);
  1229. if (tag == 0x00) {
  1230. auto expr = TRY(Expression::parse(stream));
  1231. auto init = TRY(parse_vector<u8>(stream));
  1232. return Data { Active { init, { 0 }, expr } };
  1233. }
  1234. if (tag == 0x01) {
  1235. auto init = TRY(parse_vector<u8>(stream));
  1236. return Data { Passive { init } };
  1237. }
  1238. if (tag == 0x02) {
  1239. auto index = TRY(GenericIndexParser<MemoryIndex>::parse(stream));
  1240. auto expr = TRY(Expression::parse(stream));
  1241. auto init = TRY(parse_vector<u8>(stream));
  1242. return Data { Active { init, index, expr } };
  1243. }
  1244. VERIFY_NOT_REACHED();
  1245. }
  1246. ParseResult<DataSection> DataSection::parse(Stream& stream)
  1247. {
  1248. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection"sv);
  1249. auto data = TRY(parse_vector<Data>(stream));
  1250. return DataSection { data };
  1251. }
  1252. ParseResult<DataCountSection> DataCountSection::parse([[maybe_unused]] Stream& stream)
  1253. {
  1254. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection"sv);
  1255. auto value_or_error = stream.read_value<LEB128<u32>>();
  1256. if (value_or_error.is_error()) {
  1257. if (stream.is_eof()) {
  1258. // The section simply didn't contain anything.
  1259. return DataCountSection { {} };
  1260. }
  1261. return ParseError::ExpectedSize;
  1262. }
  1263. u32 value = value_or_error.release_value();
  1264. return DataCountSection { value };
  1265. }
  1266. ParseResult<Module> Module::parse(Stream& stream)
  1267. {
  1268. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module"sv);
  1269. u8 buf[4];
  1270. if (stream.read_until_filled({ buf, 4 }).is_error())
  1271. return with_eof_check(stream, ParseError::InvalidInput);
  1272. if (Bytes { buf, 4 } != wasm_magic.span())
  1273. return with_eof_check(stream, ParseError::InvalidModuleMagic);
  1274. if (stream.read_until_filled({ buf, 4 }).is_error())
  1275. return with_eof_check(stream, ParseError::InvalidInput);
  1276. if (Bytes { buf, 4 } != wasm_version.span())
  1277. return with_eof_check(stream, ParseError::InvalidModuleVersion);
  1278. Vector<AnySection> sections;
  1279. for (;;) {
  1280. auto section_id_or_error = stream.read_value<u8>();
  1281. if (stream.is_eof())
  1282. break;
  1283. if (section_id_or_error.is_error())
  1284. return with_eof_check(stream, ParseError::ExpectedIndex);
  1285. auto section_id = section_id_or_error.release_value();
  1286. auto section_size_or_error = stream.read_value<LEB128<u32>>();
  1287. if (section_size_or_error.is_error())
  1288. return with_eof_check(stream, ParseError::ExpectedSize);
  1289. size_t section_size = section_size_or_error.release_value();
  1290. auto section_stream = ConstrainedStream { MaybeOwned<Stream>(stream), section_size };
  1291. switch (section_id) {
  1292. case CustomSection::section_id:
  1293. sections.append(TRY(CustomSection::parse(section_stream)));
  1294. continue;
  1295. case TypeSection::section_id:
  1296. sections.append(TRY(TypeSection::parse(section_stream)));
  1297. continue;
  1298. case ImportSection::section_id:
  1299. sections.append(TRY(ImportSection::parse(section_stream)));
  1300. continue;
  1301. case FunctionSection::section_id:
  1302. sections.append(TRY(FunctionSection::parse(section_stream)));
  1303. continue;
  1304. case TableSection::section_id:
  1305. sections.append(TRY(TableSection::parse(section_stream)));
  1306. continue;
  1307. case MemorySection::section_id:
  1308. sections.append(TRY(MemorySection::parse(section_stream)));
  1309. continue;
  1310. case GlobalSection::section_id:
  1311. sections.append(TRY(GlobalSection::parse(section_stream)));
  1312. continue;
  1313. case ExportSection::section_id:
  1314. sections.append(TRY(ExportSection::parse(section_stream)));
  1315. continue;
  1316. case StartSection::section_id:
  1317. sections.append(TRY(StartSection::parse(section_stream)));
  1318. continue;
  1319. case ElementSection::section_id:
  1320. sections.append(TRY(ElementSection::parse(section_stream)));
  1321. continue;
  1322. case CodeSection::section_id:
  1323. sections.append(TRY(CodeSection::parse(section_stream)));
  1324. continue;
  1325. case DataSection::section_id:
  1326. sections.append(TRY(DataSection::parse(section_stream)));
  1327. continue;
  1328. case DataCountSection::section_id:
  1329. sections.append(TRY(DataCountSection::parse(section_stream)));
  1330. continue;
  1331. default:
  1332. return with_eof_check(stream, ParseError::InvalidIndex);
  1333. }
  1334. }
  1335. return Module { move(sections) };
  1336. }
  1337. bool Module::populate_sections()
  1338. {
  1339. auto is_ok = true;
  1340. FunctionSection const* function_section { nullptr };
  1341. for_each_section_of_type<FunctionSection>([&](FunctionSection const& section) { function_section = &section; });
  1342. for_each_section_of_type<CodeSection>([&](CodeSection const& section) {
  1343. if (!function_section) {
  1344. is_ok = false;
  1345. return;
  1346. }
  1347. size_t index = 0;
  1348. for (auto& entry : section.functions()) {
  1349. if (function_section->types().size() <= index) {
  1350. is_ok = false;
  1351. return;
  1352. }
  1353. auto& type_index = function_section->types()[index];
  1354. Vector<ValueType> locals;
  1355. for (auto& local : entry.func().locals()) {
  1356. for (size_t i = 0; i < local.n(); ++i)
  1357. locals.append(local.type());
  1358. }
  1359. m_functions.empend(type_index, move(locals), entry.func().body());
  1360. ++index;
  1361. }
  1362. });
  1363. return is_ok;
  1364. }
  1365. ByteString parse_error_to_byte_string(ParseError error)
  1366. {
  1367. switch (error) {
  1368. case ParseError::UnexpectedEof:
  1369. return "Unexpected end-of-file";
  1370. case ParseError::ExpectedIndex:
  1371. return "Expected a valid index value";
  1372. case ParseError::ExpectedKindTag:
  1373. return "Expected a valid kind tag";
  1374. case ParseError::ExpectedSize:
  1375. return "Expected a valid LEB128-encoded size";
  1376. case ParseError::ExpectedValueOrTerminator:
  1377. return "Expected either a terminator or a value";
  1378. case ParseError::InvalidIndex:
  1379. return "An index parsed was semantically invalid";
  1380. case ParseError::InvalidInput:
  1381. return "Input data contained invalid bytes";
  1382. case ParseError::InvalidModuleMagic:
  1383. return "Incorrect module magic (did not match \\0asm)";
  1384. case ParseError::InvalidModuleVersion:
  1385. return "Incorrect module version";
  1386. case ParseError::InvalidSize:
  1387. return "A parsed size did not make sense in context";
  1388. case ParseError::InvalidTag:
  1389. return "A parsed tag did not make sense in context";
  1390. case ParseError::InvalidType:
  1391. return "A parsed type did not make sense in context";
  1392. case ParseError::NotImplemented:
  1393. return "The parser encountered an unimplemented feature";
  1394. case ParseError::HugeAllocationRequested:
  1395. return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
  1396. case ParseError::OutOfMemory:
  1397. return "The parser hit an OOM condition";
  1398. case ParseError::ExpectedFloatingImmediate:
  1399. return "Expected a floating point immediate";
  1400. case ParseError::ExpectedSignedImmediate:
  1401. return "Expected a signed integer immediate";
  1402. case ParseError::InvalidImmediate:
  1403. return "A parsed instruction immediate was invalid for the instruction it was used for";
  1404. case ParseError::UnknownInstruction:
  1405. return "A parsed instruction was not known to this parser";
  1406. }
  1407. return "Unknown error";
  1408. }
  1409. }