Parser.cpp 72 KB

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