Parser.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/LEB128.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/ScopeLogger.h>
  10. #include <LibCore/MemoryStream.h>
  11. #include <LibWasm/Types.h>
  12. namespace Wasm {
  13. ParseError with_eof_check(Core::Stream::Stream const& stream, ParseError error_if_not_eof)
  14. {
  15. if (stream.is_eof())
  16. return ParseError::UnexpectedEof;
  17. return error_if_not_eof;
  18. }
  19. template<typename T>
  20. static auto parse_vector(Core::Stream::Stream& stream)
  21. {
  22. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  23. if constexpr (requires { T::parse(stream); }) {
  24. using ResultT = typename decltype(T::parse(stream))::ValueType;
  25. size_t count;
  26. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  27. if (!LEB128::read_unsigned(wrapped_stream, count))
  28. return ParseResult<Vector<ResultT>> { with_eof_check(stream, ParseError::ExpectedSize) };
  29. Vector<ResultT> entries;
  30. for (size_t i = 0; i < count; ++i) {
  31. auto result = T::parse(stream);
  32. if (result.is_error())
  33. return ParseResult<Vector<ResultT>> { result.error() };
  34. entries.append(result.release_value());
  35. }
  36. return ParseResult<Vector<ResultT>> { move(entries) };
  37. } else {
  38. size_t count;
  39. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  40. if (!LEB128::read_unsigned(wrapped_stream, count))
  41. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  42. Vector<T> entries;
  43. for (size_t i = 0; i < count; ++i) {
  44. if constexpr (IsSame<T, size_t>) {
  45. size_t value;
  46. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  47. if (!LEB128::read_unsigned(wrapped_stream, value))
  48. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  49. entries.append(value);
  50. } else if constexpr (IsSame<T, ssize_t>) {
  51. ssize_t value;
  52. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  53. if (!LEB128::read_signed(wrapped_stream, value))
  54. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  55. entries.append(value);
  56. } else if constexpr (IsSame<T, u8>) {
  57. if (count > Constants::max_allowed_vector_size)
  58. return ParseResult<Vector<T>> { ParseError::HugeAllocationRequested };
  59. entries.resize(count);
  60. if (stream.read_entire_buffer({ entries.data(), entries.size() }).is_error())
  61. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::InvalidInput) };
  62. break; // Note: We read this all in one go!
  63. }
  64. }
  65. return ParseResult<Vector<T>> { move(entries) };
  66. }
  67. }
  68. static ParseResult<DeprecatedString> parse_name(Core::Stream::Stream& stream)
  69. {
  70. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  71. auto data = parse_vector<u8>(stream);
  72. if (data.is_error())
  73. return data.error();
  74. return DeprecatedString::copy(data.value());
  75. }
  76. template<typename T>
  77. struct ParseUntilAnyOfResult {
  78. u8 terminator { 0 };
  79. Vector<T> values;
  80. };
  81. template<typename T, u8... terminators, typename... Args>
  82. static ParseResult<ParseUntilAnyOfResult<T>> parse_until_any_of(Core::Stream::Stream& stream, Args&... args)
  83. requires(requires(Core::Stream::Stream& stream, Args... args) { T::parse(stream, args...); })
  84. {
  85. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  86. ReconsumableStream new_stream { stream };
  87. ParseUntilAnyOfResult<T> result;
  88. for (;;) {
  89. auto byte_or_error = new_stream.read_value<u8>();
  90. if (byte_or_error.is_error())
  91. return with_eof_check(stream, ParseError::ExpectedValueOrTerminator);
  92. auto byte = byte_or_error.release_value();
  93. constexpr auto equals = [](auto&& a, auto&& b) { return a == b; };
  94. if ((... || equals(byte, terminators))) {
  95. result.terminator = byte;
  96. return result;
  97. }
  98. new_stream.unread({ &byte, 1 });
  99. auto parse_result = T::parse(new_stream, args...);
  100. if (parse_result.is_error())
  101. return parse_result.error();
  102. result.values.extend(parse_result.release_value());
  103. }
  104. }
  105. ParseResult<ValueType> ValueType::parse(Core::Stream::Stream& stream)
  106. {
  107. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ValueType"sv);
  108. auto tag_or_error = stream.read_value<u8>();
  109. if (tag_or_error.is_error())
  110. return with_eof_check(stream, ParseError::ExpectedKindTag);
  111. auto tag = tag_or_error.release_value();
  112. switch (tag) {
  113. case Constants::i32_tag:
  114. return ValueType(I32);
  115. case Constants::i64_tag:
  116. return ValueType(I64);
  117. case Constants::f32_tag:
  118. return ValueType(F32);
  119. case Constants::f64_tag:
  120. return ValueType(F64);
  121. case Constants::function_reference_tag:
  122. return ValueType(FunctionReference);
  123. case Constants::extern_reference_tag:
  124. return ValueType(ExternReference);
  125. default:
  126. return with_eof_check(stream, ParseError::InvalidTag);
  127. }
  128. }
  129. ParseResult<ResultType> ResultType::parse(Core::Stream::Stream& stream)
  130. {
  131. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ResultType"sv);
  132. auto types = parse_vector<ValueType>(stream);
  133. if (types.is_error())
  134. return types.error();
  135. return ResultType { types.release_value() };
  136. }
  137. ParseResult<FunctionType> FunctionType::parse(Core::Stream::Stream& stream)
  138. {
  139. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionType"sv);
  140. auto tag_or_error = stream.read_value<u8>();
  141. if (tag_or_error.is_error())
  142. return with_eof_check(stream, ParseError::ExpectedKindTag);
  143. auto tag = tag_or_error.release_value();
  144. if (tag != Constants::function_signature_tag) {
  145. dbgln("Expected 0x60, but found {:#x}", tag);
  146. return with_eof_check(stream, ParseError::InvalidTag);
  147. }
  148. auto parameters_result = parse_vector<ValueType>(stream);
  149. if (parameters_result.is_error())
  150. return parameters_result.error();
  151. auto results_result = parse_vector<ValueType>(stream);
  152. if (results_result.is_error())
  153. return results_result.error();
  154. return FunctionType { parameters_result.release_value(), results_result.release_value() };
  155. }
  156. ParseResult<Limits> Limits::parse(Core::Stream::Stream& stream)
  157. {
  158. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Limits"sv);
  159. auto flag_or_error = stream.read_value<u8>();
  160. if (flag_or_error.is_error())
  161. return with_eof_check(stream, ParseError::ExpectedKindTag);
  162. auto flag = flag_or_error.release_value();
  163. if (flag > 1)
  164. return with_eof_check(stream, ParseError::InvalidTag);
  165. size_t min;
  166. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  167. if (!LEB128::read_unsigned(wrapped_stream, min))
  168. return with_eof_check(stream, ParseError::ExpectedSize);
  169. Optional<u32> max;
  170. if (flag) {
  171. size_t value;
  172. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  173. if (!LEB128::read_unsigned(wrapped_stream, value))
  174. return with_eof_check(stream, ParseError::ExpectedSize);
  175. max = value;
  176. }
  177. return Limits { static_cast<u32>(min), move(max) };
  178. }
  179. ParseResult<MemoryType> MemoryType::parse(Core::Stream::Stream& stream)
  180. {
  181. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemoryType"sv);
  182. auto limits_result = Limits::parse(stream);
  183. if (limits_result.is_error())
  184. return limits_result.error();
  185. return MemoryType { limits_result.release_value() };
  186. }
  187. ParseResult<TableType> TableType::parse(Core::Stream::Stream& stream)
  188. {
  189. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableType"sv);
  190. auto type_result = ValueType::parse(stream);
  191. if (type_result.is_error())
  192. return type_result.error();
  193. if (!type_result.value().is_reference())
  194. return with_eof_check(stream, ParseError::InvalidType);
  195. auto limits_result = Limits::parse(stream);
  196. if (limits_result.is_error())
  197. return limits_result.error();
  198. return TableType { type_result.release_value(), limits_result.release_value() };
  199. }
  200. ParseResult<GlobalType> GlobalType::parse(Core::Stream::Stream& stream)
  201. {
  202. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalType"sv);
  203. auto type_result = ValueType::parse(stream);
  204. if (type_result.is_error())
  205. return type_result.error();
  206. auto mutable_or_error = stream.read_value<u8>();
  207. if (mutable_or_error.is_error())
  208. return with_eof_check(stream, ParseError::ExpectedKindTag);
  209. auto mutable_ = mutable_or_error.release_value();
  210. if (mutable_ > 1)
  211. return with_eof_check(stream, ParseError::InvalidTag);
  212. return GlobalType { type_result.release_value(), mutable_ == 0x01 };
  213. }
  214. ParseResult<BlockType> BlockType::parse(Core::Stream::Stream& stream)
  215. {
  216. ScopeLogger<WASM_BINPARSER_DEBUG> logger("BlockType"sv);
  217. auto kind_or_error = stream.read_value<u8>();
  218. if (kind_or_error.is_error())
  219. return with_eof_check(stream, ParseError::ExpectedKindTag);
  220. auto kind = kind_or_error.release_value();
  221. if (kind == Constants::empty_block_tag)
  222. return BlockType {};
  223. {
  224. auto value_stream = Core::Stream::FixedMemoryStream::construct(ReadonlyBytes { &kind, 1 }).release_value_but_fixme_should_propagate_errors();
  225. if (auto value_type = ValueType::parse(*value_stream); !value_type.is_error())
  226. return BlockType { value_type.release_value() };
  227. }
  228. ReconsumableStream new_stream { stream };
  229. new_stream.unread({ &kind, 1 });
  230. ssize_t index_value;
  231. Core::Stream::WrapInAKInputStream wrapped_new_stream { new_stream };
  232. if (!LEB128::read_signed(wrapped_new_stream, index_value))
  233. return with_eof_check(stream, ParseError::ExpectedIndex);
  234. if (index_value < 0) {
  235. dbgln("Invalid type index {}", index_value);
  236. return with_eof_check(stream, ParseError::InvalidIndex);
  237. }
  238. return BlockType { TypeIndex(index_value) };
  239. }
  240. ParseResult<Vector<Instruction>> Instruction::parse(Core::Stream::Stream& stream, InstructionPointer& ip)
  241. {
  242. struct NestedInstructionState {
  243. Vector<Instruction> prior_instructions;
  244. OpCode opcode;
  245. BlockType block_type;
  246. InstructionPointer end_ip;
  247. Optional<InstructionPointer> else_ip;
  248. };
  249. Vector<NestedInstructionState, 4> nested_instructions;
  250. Vector<Instruction> resulting_instructions;
  251. do {
  252. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Instruction"sv);
  253. auto byte_or_error = stream.read_value<u8>();
  254. if (byte_or_error.is_error())
  255. return with_eof_check(stream, ParseError::ExpectedKindTag);
  256. auto byte = byte_or_error.release_value();
  257. if (!nested_instructions.is_empty()) {
  258. auto& nested_structure = nested_instructions.last();
  259. if (byte == 0x0b) {
  260. // block/loop/if end
  261. nested_structure.end_ip = ip + (nested_structure.else_ip.has_value() ? 1 : 0);
  262. ++ip;
  263. // Transform op(..., instr*) -> op(...) instr* op(end(ip))
  264. auto instructions = move(nested_structure.prior_instructions);
  265. instructions.ensure_capacity(instructions.size() + 2 + resulting_instructions.size());
  266. instructions.append(Instruction { nested_structure.opcode, StructuredInstructionArgs { nested_structure.block_type, nested_structure.end_ip, nested_structure.else_ip } });
  267. instructions.extend(move(resulting_instructions));
  268. instructions.append(Instruction { Instructions::structured_end });
  269. resulting_instructions = move(instructions);
  270. nested_instructions.take_last();
  271. continue;
  272. }
  273. if (byte == 0x05) {
  274. // if...else
  275. // Transform op(..., instr*, instr*) -> op(...) instr* op(else(ip) instr* op(end(ip))
  276. resulting_instructions.append(Instruction { Instructions::structured_else });
  277. ++ip;
  278. nested_structure.else_ip = ip.value();
  279. continue;
  280. }
  281. }
  282. OpCode opcode { byte };
  283. ++ip;
  284. switch (opcode.value()) {
  285. case Instructions::block.value():
  286. case Instructions::loop.value():
  287. case Instructions::if_.value(): {
  288. auto block_type = BlockType::parse(stream);
  289. if (block_type.is_error())
  290. return block_type.error();
  291. nested_instructions.append({ move(resulting_instructions), opcode, block_type.release_value(), {}, {} });
  292. resulting_instructions = {};
  293. break;
  294. }
  295. case Instructions::br.value():
  296. case Instructions::br_if.value(): {
  297. // branches with a single label immediate
  298. auto index = GenericIndexParser<LabelIndex>::parse(stream);
  299. if (index.is_error())
  300. return index.error();
  301. resulting_instructions.append(Instruction { opcode, index.release_value() });
  302. break;
  303. }
  304. case Instructions::br_table.value(): {
  305. // br_table label* label
  306. auto labels = parse_vector<GenericIndexParser<LabelIndex>>(stream);
  307. if (labels.is_error())
  308. return labels.error();
  309. auto default_label = GenericIndexParser<LabelIndex>::parse(stream);
  310. if (default_label.is_error())
  311. return default_label.error();
  312. resulting_instructions.append(Instruction { opcode, TableBranchArgs { labels.release_value(), default_label.release_value() } });
  313. break;
  314. }
  315. case Instructions::call.value(): {
  316. // call function
  317. auto function_index = GenericIndexParser<FunctionIndex>::parse(stream);
  318. if (function_index.is_error())
  319. return function_index.error();
  320. resulting_instructions.append(Instruction { opcode, function_index.release_value() });
  321. break;
  322. }
  323. case Instructions::call_indirect.value(): {
  324. // call_indirect type table
  325. auto type_index = GenericIndexParser<TypeIndex>::parse(stream);
  326. if (type_index.is_error())
  327. return type_index.error();
  328. auto table_index = GenericIndexParser<TableIndex>::parse(stream);
  329. if (table_index.is_error())
  330. return table_index.error();
  331. resulting_instructions.append(Instruction { opcode, IndirectCallArgs { type_index.release_value(), table_index.release_value() } });
  332. break;
  333. }
  334. case Instructions::i32_load.value():
  335. case Instructions::i64_load.value():
  336. case Instructions::f32_load.value():
  337. case Instructions::f64_load.value():
  338. case Instructions::i32_load8_s.value():
  339. case Instructions::i32_load8_u.value():
  340. case Instructions::i32_load16_s.value():
  341. case Instructions::i32_load16_u.value():
  342. case Instructions::i64_load8_s.value():
  343. case Instructions::i64_load8_u.value():
  344. case Instructions::i64_load16_s.value():
  345. case Instructions::i64_load16_u.value():
  346. case Instructions::i64_load32_s.value():
  347. case Instructions::i64_load32_u.value():
  348. case Instructions::i32_store.value():
  349. case Instructions::i64_store.value():
  350. case Instructions::f32_store.value():
  351. case Instructions::f64_store.value():
  352. case Instructions::i32_store8.value():
  353. case Instructions::i32_store16.value():
  354. case Instructions::i64_store8.value():
  355. case Instructions::i64_store16.value():
  356. case Instructions::i64_store32.value(): {
  357. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  358. // op (align offset)
  359. size_t align;
  360. if (!LEB128::read_unsigned(wrapped_stream, align))
  361. return with_eof_check(stream, ParseError::InvalidInput);
  362. size_t offset;
  363. if (!LEB128::read_unsigned(wrapped_stream, offset))
  364. return with_eof_check(stream, ParseError::InvalidInput);
  365. resulting_instructions.append(Instruction { opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset) } });
  366. break;
  367. }
  368. case Instructions::local_get.value():
  369. case Instructions::local_set.value():
  370. case Instructions::local_tee.value(): {
  371. auto index = GenericIndexParser<LocalIndex>::parse(stream);
  372. if (index.is_error())
  373. return index.error();
  374. resulting_instructions.append(Instruction { opcode, index.release_value() });
  375. break;
  376. }
  377. case Instructions::global_get.value():
  378. case Instructions::global_set.value(): {
  379. auto index = GenericIndexParser<GlobalIndex>::parse(stream);
  380. if (index.is_error())
  381. return index.error();
  382. resulting_instructions.append(Instruction { opcode, index.release_value() });
  383. break;
  384. }
  385. case Instructions::memory_size.value():
  386. case Instructions::memory_grow.value(): {
  387. // op 0x0
  388. // The zero is currently unused.
  389. auto unused_or_error = stream.read_value<u8>();
  390. if (unused_or_error.is_error())
  391. return with_eof_check(stream, ParseError::ExpectedKindTag);
  392. auto unused = unused_or_error.release_value();
  393. if (unused != 0x00) {
  394. dbgln("Invalid tag in memory_grow {}", unused);
  395. return with_eof_check(stream, ParseError::InvalidTag);
  396. }
  397. resulting_instructions.append(Instruction { opcode });
  398. break;
  399. }
  400. case Instructions::i32_const.value(): {
  401. i32 value;
  402. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  403. if (!LEB128::read_signed(wrapped_stream, value))
  404. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  405. resulting_instructions.append(Instruction { opcode, value });
  406. break;
  407. }
  408. case Instructions::i64_const.value(): {
  409. // op literal
  410. i64 value;
  411. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  412. if (!LEB128::read_signed(wrapped_stream, value))
  413. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  414. resulting_instructions.append(Instruction { opcode, value });
  415. break;
  416. }
  417. case Instructions::f32_const.value(): {
  418. // op literal
  419. LittleEndian<u32> value;
  420. if (stream.read_entire_buffer(value.bytes()).is_error())
  421. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  422. auto floating = bit_cast<float>(static_cast<u32>(value));
  423. resulting_instructions.append(Instruction { opcode, floating });
  424. break;
  425. }
  426. case Instructions::f64_const.value(): {
  427. // op literal
  428. LittleEndian<u64> value;
  429. if (stream.read_entire_buffer(value.bytes()).is_error())
  430. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  431. auto floating = bit_cast<double>(static_cast<u64>(value));
  432. resulting_instructions.append(Instruction { opcode, floating });
  433. break;
  434. }
  435. case Instructions::table_get.value():
  436. case Instructions::table_set.value(): {
  437. auto index = GenericIndexParser<TableIndex>::parse(stream);
  438. if (index.is_error())
  439. return index.error();
  440. resulting_instructions.append(Instruction { opcode, index.release_value() });
  441. break;
  442. }
  443. case Instructions::select_typed.value(): {
  444. auto types = parse_vector<ValueType>(stream);
  445. if (types.is_error())
  446. return types.error();
  447. resulting_instructions.append(Instruction { opcode, types.release_value() });
  448. break;
  449. }
  450. case Instructions::ref_null.value(): {
  451. auto type = ValueType::parse(stream);
  452. if (type.is_error())
  453. return type.error();
  454. if (!type.value().is_reference())
  455. return ParseError::InvalidType;
  456. resulting_instructions.append(Instruction { opcode, type.release_value() });
  457. break;
  458. }
  459. case Instructions::ref_func.value(): {
  460. auto index = GenericIndexParser<FunctionIndex>::parse(stream);
  461. if (index.is_error())
  462. return index.error();
  463. resulting_instructions.append(Instruction { opcode, index.release_value() });
  464. break;
  465. }
  466. case Instructions::ref_is_null.value():
  467. case Instructions::unreachable.value():
  468. case Instructions::nop.value():
  469. case Instructions::return_.value():
  470. case Instructions::drop.value():
  471. case Instructions::select.value():
  472. case Instructions::i32_eqz.value():
  473. case Instructions::i32_eq.value():
  474. case Instructions::i32_ne.value():
  475. case Instructions::i32_lts.value():
  476. case Instructions::i32_ltu.value():
  477. case Instructions::i32_gts.value():
  478. case Instructions::i32_gtu.value():
  479. case Instructions::i32_les.value():
  480. case Instructions::i32_leu.value():
  481. case Instructions::i32_ges.value():
  482. case Instructions::i32_geu.value():
  483. case Instructions::i64_eqz.value():
  484. case Instructions::i64_eq.value():
  485. case Instructions::i64_ne.value():
  486. case Instructions::i64_lts.value():
  487. case Instructions::i64_ltu.value():
  488. case Instructions::i64_gts.value():
  489. case Instructions::i64_gtu.value():
  490. case Instructions::i64_les.value():
  491. case Instructions::i64_leu.value():
  492. case Instructions::i64_ges.value():
  493. case Instructions::i64_geu.value():
  494. case Instructions::f32_eq.value():
  495. case Instructions::f32_ne.value():
  496. case Instructions::f32_lt.value():
  497. case Instructions::f32_gt.value():
  498. case Instructions::f32_le.value():
  499. case Instructions::f32_ge.value():
  500. case Instructions::f64_eq.value():
  501. case Instructions::f64_ne.value():
  502. case Instructions::f64_lt.value():
  503. case Instructions::f64_gt.value():
  504. case Instructions::f64_le.value():
  505. case Instructions::f64_ge.value():
  506. case Instructions::i32_clz.value():
  507. case Instructions::i32_ctz.value():
  508. case Instructions::i32_popcnt.value():
  509. case Instructions::i32_add.value():
  510. case Instructions::i32_sub.value():
  511. case Instructions::i32_mul.value():
  512. case Instructions::i32_divs.value():
  513. case Instructions::i32_divu.value():
  514. case Instructions::i32_rems.value():
  515. case Instructions::i32_remu.value():
  516. case Instructions::i32_and.value():
  517. case Instructions::i32_or.value():
  518. case Instructions::i32_xor.value():
  519. case Instructions::i32_shl.value():
  520. case Instructions::i32_shrs.value():
  521. case Instructions::i32_shru.value():
  522. case Instructions::i32_rotl.value():
  523. case Instructions::i32_rotr.value():
  524. case Instructions::i64_clz.value():
  525. case Instructions::i64_ctz.value():
  526. case Instructions::i64_popcnt.value():
  527. case Instructions::i64_add.value():
  528. case Instructions::i64_sub.value():
  529. case Instructions::i64_mul.value():
  530. case Instructions::i64_divs.value():
  531. case Instructions::i64_divu.value():
  532. case Instructions::i64_rems.value():
  533. case Instructions::i64_remu.value():
  534. case Instructions::i64_and.value():
  535. case Instructions::i64_or.value():
  536. case Instructions::i64_xor.value():
  537. case Instructions::i64_shl.value():
  538. case Instructions::i64_shrs.value():
  539. case Instructions::i64_shru.value():
  540. case Instructions::i64_rotl.value():
  541. case Instructions::i64_rotr.value():
  542. case Instructions::f32_abs.value():
  543. case Instructions::f32_neg.value():
  544. case Instructions::f32_ceil.value():
  545. case Instructions::f32_floor.value():
  546. case Instructions::f32_trunc.value():
  547. case Instructions::f32_nearest.value():
  548. case Instructions::f32_sqrt.value():
  549. case Instructions::f32_add.value():
  550. case Instructions::f32_sub.value():
  551. case Instructions::f32_mul.value():
  552. case Instructions::f32_div.value():
  553. case Instructions::f32_min.value():
  554. case Instructions::f32_max.value():
  555. case Instructions::f32_copysign.value():
  556. case Instructions::f64_abs.value():
  557. case Instructions::f64_neg.value():
  558. case Instructions::f64_ceil.value():
  559. case Instructions::f64_floor.value():
  560. case Instructions::f64_trunc.value():
  561. case Instructions::f64_nearest.value():
  562. case Instructions::f64_sqrt.value():
  563. case Instructions::f64_add.value():
  564. case Instructions::f64_sub.value():
  565. case Instructions::f64_mul.value():
  566. case Instructions::f64_div.value():
  567. case Instructions::f64_min.value():
  568. case Instructions::f64_max.value():
  569. case Instructions::f64_copysign.value():
  570. case Instructions::i32_wrap_i64.value():
  571. case Instructions::i32_trunc_sf32.value():
  572. case Instructions::i32_trunc_uf32.value():
  573. case Instructions::i32_trunc_sf64.value():
  574. case Instructions::i32_trunc_uf64.value():
  575. case Instructions::i64_extend_si32.value():
  576. case Instructions::i64_extend_ui32.value():
  577. case Instructions::i64_trunc_sf32.value():
  578. case Instructions::i64_trunc_uf32.value():
  579. case Instructions::i64_trunc_sf64.value():
  580. case Instructions::i64_trunc_uf64.value():
  581. case Instructions::f32_convert_si32.value():
  582. case Instructions::f32_convert_ui32.value():
  583. case Instructions::f32_convert_si64.value():
  584. case Instructions::f32_convert_ui64.value():
  585. case Instructions::f32_demote_f64.value():
  586. case Instructions::f64_convert_si32.value():
  587. case Instructions::f64_convert_ui32.value():
  588. case Instructions::f64_convert_si64.value():
  589. case Instructions::f64_convert_ui64.value():
  590. case Instructions::f64_promote_f32.value():
  591. case Instructions::i32_reinterpret_f32.value():
  592. case Instructions::i64_reinterpret_f64.value():
  593. case Instructions::f32_reinterpret_i32.value():
  594. case Instructions::f64_reinterpret_i64.value():
  595. case Instructions::i32_extend8_s.value():
  596. case Instructions::i32_extend16_s.value():
  597. case Instructions::i64_extend8_s.value():
  598. case Instructions::i64_extend16_s.value():
  599. case Instructions::i64_extend32_s.value():
  600. resulting_instructions.append(Instruction { opcode });
  601. break;
  602. case 0xfc: {
  603. // These are multibyte instructions.
  604. u32 selector;
  605. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  606. if (!LEB128::read_unsigned(wrapped_stream, selector))
  607. return with_eof_check(stream, ParseError::InvalidInput);
  608. switch (selector) {
  609. case Instructions::i32_trunc_sat_f32_s_second:
  610. case Instructions::i32_trunc_sat_f32_u_second:
  611. case Instructions::i32_trunc_sat_f64_s_second:
  612. case Instructions::i32_trunc_sat_f64_u_second:
  613. case Instructions::i64_trunc_sat_f32_s_second:
  614. case Instructions::i64_trunc_sat_f32_u_second:
  615. case Instructions::i64_trunc_sat_f64_s_second:
  616. case Instructions::i64_trunc_sat_f64_u_second:
  617. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
  618. break;
  619. case Instructions::memory_init_second: {
  620. auto index = GenericIndexParser<DataIndex>::parse(stream);
  621. if (index.is_error())
  622. return index.error();
  623. auto unused_or_error = stream.read_value<u8>();
  624. if (unused_or_error.is_error())
  625. return with_eof_check(stream, ParseError::InvalidInput);
  626. auto unused = unused_or_error.release_value();
  627. if (unused != 0x00)
  628. return ParseError::InvalidImmediate;
  629. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
  630. break;
  631. }
  632. case Instructions::data_drop_second: {
  633. auto index = GenericIndexParser<DataIndex>::parse(stream);
  634. if (index.is_error())
  635. return index.error();
  636. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
  637. break;
  638. }
  639. case Instructions::memory_copy_second: {
  640. for (size_t i = 0; i < 2; ++i) {
  641. auto unused_or_error = stream.read_value<u8>();
  642. if (unused_or_error.is_error())
  643. return with_eof_check(stream, ParseError::InvalidInput);
  644. auto unused = unused_or_error.release_value();
  645. if (unused != 0x00)
  646. return ParseError::InvalidImmediate;
  647. }
  648. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
  649. break;
  650. }
  651. case Instructions::memory_fill_second: {
  652. auto unused_or_error = stream.read_value<u8>();
  653. if (unused_or_error.is_error())
  654. return with_eof_check(stream, ParseError::InvalidInput);
  655. auto unused = unused_or_error.release_value();
  656. if (unused != 0x00)
  657. return ParseError::InvalidImmediate;
  658. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector } });
  659. break;
  660. }
  661. case Instructions::table_init_second: {
  662. auto element_index = GenericIndexParser<ElementIndex>::parse(stream);
  663. if (element_index.is_error())
  664. return element_index.error();
  665. auto table_index = GenericIndexParser<TableIndex>::parse(stream);
  666. if (table_index.is_error())
  667. return table_index.error();
  668. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, TableElementArgs { element_index.release_value(), table_index.release_value() } });
  669. break;
  670. }
  671. case Instructions::elem_drop_second: {
  672. auto element_index = GenericIndexParser<ElementIndex>::parse(stream);
  673. if (element_index.is_error())
  674. return element_index.error();
  675. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, element_index.release_value() });
  676. break;
  677. }
  678. case Instructions::table_copy_second: {
  679. auto lhs = GenericIndexParser<TableIndex>::parse(stream);
  680. if (lhs.is_error())
  681. return lhs.error();
  682. auto rhs = GenericIndexParser<TableIndex>::parse(stream);
  683. if (rhs.is_error())
  684. return rhs.error();
  685. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, TableTableArgs { lhs.release_value(), rhs.release_value() } });
  686. break;
  687. }
  688. case Instructions::table_grow_second:
  689. case Instructions::table_size_second:
  690. case Instructions::table_fill_second: {
  691. auto index = GenericIndexParser<TableIndex>::parse(stream);
  692. if (index.is_error())
  693. return index.error();
  694. resulting_instructions.append(Instruction { OpCode { 0xfc00 | selector }, index.release_value() });
  695. break;
  696. }
  697. default:
  698. return ParseError::UnknownInstruction;
  699. }
  700. }
  701. }
  702. } while (!nested_instructions.is_empty());
  703. return resulting_instructions;
  704. }
  705. ParseResult<CustomSection> CustomSection::parse(Core::Stream::Stream& stream)
  706. {
  707. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CustomSection"sv);
  708. auto name = parse_name(stream);
  709. if (name.is_error())
  710. return name.error();
  711. ByteBuffer data_buffer;
  712. if (data_buffer.try_resize(64).is_error())
  713. return ParseError::OutOfMemory;
  714. while (!stream.is_eof()) {
  715. char buf[16];
  716. auto span_or_error = stream.read({ buf, 16 });
  717. if (span_or_error.is_error())
  718. break;
  719. auto size = span_or_error.release_value().size();
  720. if (size == 0)
  721. break;
  722. if (data_buffer.try_append(buf, size).is_error())
  723. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  724. }
  725. return CustomSection(name.release_value(), move(data_buffer));
  726. }
  727. ParseResult<TypeSection> TypeSection::parse(Core::Stream::Stream& stream)
  728. {
  729. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection"sv);
  730. auto types = parse_vector<FunctionType>(stream);
  731. if (types.is_error())
  732. return types.error();
  733. return TypeSection { types.release_value() };
  734. }
  735. ParseResult<ImportSection::Import> ImportSection::Import::parse(Core::Stream::Stream& stream)
  736. {
  737. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import"sv);
  738. auto module = parse_name(stream);
  739. if (module.is_error())
  740. return module.error();
  741. auto name = parse_name(stream);
  742. if (name.is_error())
  743. return name.error();
  744. auto tag_or_error = stream.read_value<u8>();
  745. if (tag_or_error.is_error())
  746. return with_eof_check(stream, ParseError::ExpectedKindTag);
  747. auto tag = tag_or_error.release_value();
  748. switch (tag) {
  749. case Constants::extern_function_tag: {
  750. auto index = GenericIndexParser<TypeIndex>::parse(stream);
  751. if (index.is_error())
  752. return index.error();
  753. return Import { module.release_value(), name.release_value(), index.release_value() };
  754. }
  755. case Constants::extern_table_tag:
  756. return parse_with_type<TableType>(stream, module, name);
  757. case Constants::extern_memory_tag:
  758. return parse_with_type<MemoryType>(stream, module, name);
  759. case Constants::extern_global_tag:
  760. return parse_with_type<GlobalType>(stream, module, name);
  761. default:
  762. return with_eof_check(stream, ParseError::InvalidTag);
  763. }
  764. }
  765. ParseResult<ImportSection> ImportSection::parse(Core::Stream::Stream& stream)
  766. {
  767. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection"sv);
  768. auto imports = parse_vector<Import>(stream);
  769. if (imports.is_error())
  770. return imports.error();
  771. return ImportSection { imports.release_value() };
  772. }
  773. ParseResult<FunctionSection> FunctionSection::parse(Core::Stream::Stream& stream)
  774. {
  775. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection"sv);
  776. auto indices = parse_vector<size_t>(stream);
  777. if (indices.is_error())
  778. return indices.error();
  779. Vector<TypeIndex> typed_indices;
  780. typed_indices.ensure_capacity(indices.value().size());
  781. for (auto entry : indices.value())
  782. typed_indices.append(entry);
  783. return FunctionSection { move(typed_indices) };
  784. }
  785. ParseResult<TableSection::Table> TableSection::Table::parse(Core::Stream::Stream& stream)
  786. {
  787. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table"sv);
  788. auto type = TableType::parse(stream);
  789. if (type.is_error())
  790. return type.error();
  791. return Table { type.release_value() };
  792. }
  793. ParseResult<TableSection> TableSection::parse(Core::Stream::Stream& stream)
  794. {
  795. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection"sv);
  796. auto tables = parse_vector<Table>(stream);
  797. if (tables.is_error())
  798. return tables.error();
  799. return TableSection { tables.release_value() };
  800. }
  801. ParseResult<MemorySection::Memory> MemorySection::Memory::parse(Core::Stream::Stream& stream)
  802. {
  803. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory"sv);
  804. auto type = MemoryType::parse(stream);
  805. if (type.is_error())
  806. return type.error();
  807. return Memory { type.release_value() };
  808. }
  809. ParseResult<MemorySection> MemorySection::parse(Core::Stream::Stream& stream)
  810. {
  811. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection"sv);
  812. auto memories = parse_vector<Memory>(stream);
  813. if (memories.is_error())
  814. return memories.error();
  815. return MemorySection { memories.release_value() };
  816. }
  817. ParseResult<Expression> Expression::parse(Core::Stream::Stream& stream)
  818. {
  819. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression"sv);
  820. InstructionPointer ip { 0 };
  821. auto instructions = parse_until_any_of<Instruction, 0x0b>(stream, ip);
  822. if (instructions.is_error())
  823. return instructions.error();
  824. return Expression { move(instructions.value().values) };
  825. }
  826. ParseResult<GlobalSection::Global> GlobalSection::Global::parse(Core::Stream::Stream& stream)
  827. {
  828. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global"sv);
  829. auto type = GlobalType::parse(stream);
  830. if (type.is_error())
  831. return type.error();
  832. auto exprs = Expression::parse(stream);
  833. if (exprs.is_error())
  834. return exprs.error();
  835. return Global { type.release_value(), exprs.release_value() };
  836. }
  837. ParseResult<GlobalSection> GlobalSection::parse(Core::Stream::Stream& stream)
  838. {
  839. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection"sv);
  840. auto result = parse_vector<Global>(stream);
  841. if (result.is_error())
  842. return result.error();
  843. return GlobalSection { result.release_value() };
  844. }
  845. ParseResult<ExportSection::Export> ExportSection::Export::parse(Core::Stream::Stream& stream)
  846. {
  847. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export"sv);
  848. auto name = parse_name(stream);
  849. if (name.is_error())
  850. return name.error();
  851. auto tag_or_error = stream.read_value<u8>();
  852. if (tag_or_error.is_error())
  853. return with_eof_check(stream, ParseError::ExpectedKindTag);
  854. auto tag = tag_or_error.release_value();
  855. size_t index;
  856. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  857. if (!LEB128::read_unsigned(wrapped_stream, index))
  858. return with_eof_check(stream, ParseError::ExpectedIndex);
  859. switch (tag) {
  860. case Constants::extern_function_tag:
  861. return Export { name.release_value(), ExportDesc { FunctionIndex { index } } };
  862. case Constants::extern_table_tag:
  863. return Export { name.release_value(), ExportDesc { TableIndex { index } } };
  864. case Constants::extern_memory_tag:
  865. return Export { name.release_value(), ExportDesc { MemoryIndex { index } } };
  866. case Constants::extern_global_tag:
  867. return Export { name.release_value(), ExportDesc { GlobalIndex { index } } };
  868. default:
  869. return with_eof_check(stream, ParseError::InvalidTag);
  870. }
  871. }
  872. ParseResult<ExportSection> ExportSection::parse(Core::Stream::Stream& stream)
  873. {
  874. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection"sv);
  875. auto result = parse_vector<Export>(stream);
  876. if (result.is_error())
  877. return result.error();
  878. return ExportSection { result.release_value() };
  879. }
  880. ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(Core::Stream::Stream& stream)
  881. {
  882. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction"sv);
  883. auto index = GenericIndexParser<FunctionIndex>::parse(stream);
  884. if (index.is_error())
  885. return index.error();
  886. return StartFunction { index.release_value() };
  887. }
  888. ParseResult<StartSection> StartSection::parse(Core::Stream::Stream& stream)
  889. {
  890. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection"sv);
  891. auto result = StartFunction::parse(stream);
  892. if (result.is_error())
  893. return result.error();
  894. return StartSection { result.release_value() };
  895. }
  896. ParseResult<ElementSection::SegmentType0> ElementSection::SegmentType0::parse(Core::Stream::Stream& stream)
  897. {
  898. auto expression = Expression::parse(stream);
  899. if (expression.is_error())
  900. return expression.error();
  901. auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
  902. if (indices.is_error())
  903. return indices.error();
  904. return SegmentType0 { indices.release_value(), Active { 0, expression.release_value() } };
  905. }
  906. ParseResult<ElementSection::SegmentType1> ElementSection::SegmentType1::parse(Core::Stream::Stream& stream)
  907. {
  908. auto kind_or_error = stream.read_value<u8>();
  909. if (kind_or_error.is_error())
  910. return with_eof_check(stream, ParseError::ExpectedKindTag);
  911. auto kind = kind_or_error.release_value();
  912. if (kind != 0)
  913. return ParseError::InvalidTag;
  914. auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
  915. if (indices.is_error())
  916. return indices.error();
  917. return SegmentType1 { indices.release_value() };
  918. }
  919. ParseResult<ElementSection::SegmentType2> ElementSection::SegmentType2::parse(Core::Stream::Stream& stream)
  920. {
  921. dbgln("Type 2");
  922. (void)stream;
  923. return ParseError::NotImplemented;
  924. }
  925. ParseResult<ElementSection::SegmentType3> ElementSection::SegmentType3::parse(Core::Stream::Stream& stream)
  926. {
  927. dbgln("Type 3");
  928. (void)stream;
  929. return ParseError::NotImplemented;
  930. }
  931. ParseResult<ElementSection::SegmentType4> ElementSection::SegmentType4::parse(Core::Stream::Stream& stream)
  932. {
  933. dbgln("Type 4");
  934. (void)stream;
  935. return ParseError::NotImplemented;
  936. }
  937. ParseResult<ElementSection::SegmentType5> ElementSection::SegmentType5::parse(Core::Stream::Stream& stream)
  938. {
  939. dbgln("Type 5");
  940. (void)stream;
  941. return ParseError::NotImplemented;
  942. }
  943. ParseResult<ElementSection::SegmentType6> ElementSection::SegmentType6::parse(Core::Stream::Stream& stream)
  944. {
  945. dbgln("Type 6");
  946. (void)stream;
  947. return ParseError::NotImplemented;
  948. }
  949. ParseResult<ElementSection::SegmentType7> ElementSection::SegmentType7::parse(Core::Stream::Stream& stream)
  950. {
  951. dbgln("Type 7");
  952. (void)stream;
  953. return ParseError::NotImplemented;
  954. }
  955. ParseResult<ElementSection::Element> ElementSection::Element::parse(Core::Stream::Stream& stream)
  956. {
  957. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element"sv);
  958. auto tag_or_error = stream.read_value<u8>();
  959. if (tag_or_error.is_error())
  960. return with_eof_check(stream, ParseError::ExpectedKindTag);
  961. auto tag = tag_or_error.release_value();
  962. switch (tag) {
  963. case 0x00:
  964. if (auto result = SegmentType0::parse(stream); result.is_error()) {
  965. return result.error();
  966. } else {
  967. Vector<Instruction> instructions;
  968. for (auto& index : result.value().function_indices)
  969. instructions.empend(Instructions::ref_func, index);
  970. return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, move(result.value().mode) };
  971. }
  972. case 0x01:
  973. if (auto result = SegmentType1::parse(stream); result.is_error()) {
  974. return result.error();
  975. } else {
  976. Vector<Instruction> instructions;
  977. for (auto& index : result.value().function_indices)
  978. instructions.empend(Instructions::ref_func, index);
  979. return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, Passive {} };
  980. }
  981. case 0x02:
  982. if (auto result = SegmentType2::parse(stream); result.is_error()) {
  983. return result.error();
  984. } else {
  985. return ParseError::NotImplemented;
  986. }
  987. case 0x03:
  988. if (auto result = SegmentType3::parse(stream); result.is_error()) {
  989. return result.error();
  990. } else {
  991. return ParseError::NotImplemented;
  992. }
  993. case 0x04:
  994. if (auto result = SegmentType4::parse(stream); result.is_error()) {
  995. return result.error();
  996. } else {
  997. return ParseError::NotImplemented;
  998. }
  999. case 0x05:
  1000. if (auto result = SegmentType5::parse(stream); result.is_error()) {
  1001. return result.error();
  1002. } else {
  1003. return ParseError::NotImplemented;
  1004. }
  1005. case 0x06:
  1006. if (auto result = SegmentType6::parse(stream); result.is_error()) {
  1007. return result.error();
  1008. } else {
  1009. return ParseError::NotImplemented;
  1010. }
  1011. case 0x07:
  1012. if (auto result = SegmentType7::parse(stream); result.is_error()) {
  1013. return result.error();
  1014. } else {
  1015. return ParseError::NotImplemented;
  1016. }
  1017. default:
  1018. return ParseError::InvalidTag;
  1019. }
  1020. }
  1021. ParseResult<ElementSection> ElementSection::parse(Core::Stream::Stream& stream)
  1022. {
  1023. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection"sv);
  1024. auto result = parse_vector<Element>(stream);
  1025. if (result.is_error())
  1026. return result.error();
  1027. return ElementSection { result.release_value() };
  1028. }
  1029. ParseResult<Locals> Locals::parse(Core::Stream::Stream& stream)
  1030. {
  1031. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals"sv);
  1032. size_t count;
  1033. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  1034. if (!LEB128::read_unsigned(wrapped_stream, count))
  1035. return with_eof_check(stream, ParseError::InvalidSize);
  1036. if (count > Constants::max_allowed_function_locals_per_type)
  1037. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  1038. auto type = ValueType::parse(stream);
  1039. if (type.is_error())
  1040. return type.error();
  1041. return Locals { static_cast<u32>(count), type.release_value() };
  1042. }
  1043. ParseResult<CodeSection::Func> CodeSection::Func::parse(Core::Stream::Stream& stream)
  1044. {
  1045. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func"sv);
  1046. auto locals = parse_vector<Locals>(stream);
  1047. if (locals.is_error())
  1048. return locals.error();
  1049. auto body = Expression::parse(stream);
  1050. if (body.is_error())
  1051. return body.error();
  1052. return Func { locals.release_value(), body.release_value() };
  1053. }
  1054. ParseResult<CodeSection::Code> CodeSection::Code::parse(Core::Stream::Stream& stream)
  1055. {
  1056. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code"sv);
  1057. size_t size;
  1058. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  1059. if (!LEB128::read_unsigned(wrapped_stream, size))
  1060. return with_eof_check(stream, ParseError::InvalidSize);
  1061. auto constrained_stream = ConstrainedStream { stream, size };
  1062. auto func = Func::parse(constrained_stream);
  1063. if (func.is_error())
  1064. return func.error();
  1065. return Code { static_cast<u32>(size), func.release_value() };
  1066. }
  1067. ParseResult<CodeSection> CodeSection::parse(Core::Stream::Stream& stream)
  1068. {
  1069. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection"sv);
  1070. auto result = parse_vector<Code>(stream);
  1071. if (result.is_error())
  1072. return result.error();
  1073. return CodeSection { result.release_value() };
  1074. }
  1075. ParseResult<DataSection::Data> DataSection::Data::parse(Core::Stream::Stream& stream)
  1076. {
  1077. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data"sv);
  1078. auto tag_or_error = stream.read_value<u8>();
  1079. if (tag_or_error.is_error())
  1080. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1081. auto tag = tag_or_error.release_value();
  1082. if (tag > 0x02)
  1083. return with_eof_check(stream, ParseError::InvalidTag);
  1084. if (tag == 0x00) {
  1085. auto expr = Expression::parse(stream);
  1086. if (expr.is_error())
  1087. return expr.error();
  1088. auto init = parse_vector<u8>(stream);
  1089. if (init.is_error())
  1090. return init.error();
  1091. return Data { Active { init.release_value(), { 0 }, expr.release_value() } };
  1092. }
  1093. if (tag == 0x01) {
  1094. auto init = parse_vector<u8>(stream);
  1095. if (init.is_error())
  1096. return init.error();
  1097. return Data { Passive { init.release_value() } };
  1098. }
  1099. if (tag == 0x02) {
  1100. auto index = GenericIndexParser<MemoryIndex>::parse(stream);
  1101. if (index.is_error())
  1102. return index.error();
  1103. auto expr = Expression::parse(stream);
  1104. if (expr.is_error())
  1105. return expr.error();
  1106. auto init = parse_vector<u8>(stream);
  1107. if (init.is_error())
  1108. return init.error();
  1109. return Data { Active { init.release_value(), index.release_value(), expr.release_value() } };
  1110. }
  1111. VERIFY_NOT_REACHED();
  1112. }
  1113. ParseResult<DataSection> DataSection::parse(Core::Stream::Stream& stream)
  1114. {
  1115. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection"sv);
  1116. auto data = parse_vector<Data>(stream);
  1117. if (data.is_error())
  1118. return data.error();
  1119. return DataSection { data.release_value() };
  1120. }
  1121. ParseResult<DataCountSection> DataCountSection::parse([[maybe_unused]] Core::Stream::Stream& stream)
  1122. {
  1123. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection"sv);
  1124. u32 value;
  1125. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  1126. if (!LEB128::read_unsigned(wrapped_stream, value)) {
  1127. if (stream.is_eof()) {
  1128. // The section simply didn't contain anything.
  1129. return DataCountSection { {} };
  1130. }
  1131. return ParseError::ExpectedSize;
  1132. }
  1133. return DataCountSection { value };
  1134. }
  1135. ParseResult<Module> Module::parse(Core::Stream::Stream& stream)
  1136. {
  1137. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module"sv);
  1138. u8 buf[4];
  1139. if (stream.read_entire_buffer({ buf, 4 }).is_error())
  1140. return with_eof_check(stream, ParseError::InvalidInput);
  1141. if (Bytes { buf, 4 } != wasm_magic.span())
  1142. return with_eof_check(stream, ParseError::InvalidModuleMagic);
  1143. if (stream.read_entire_buffer({ buf, 4 }).is_error())
  1144. return with_eof_check(stream, ParseError::InvalidInput);
  1145. if (Bytes { buf, 4 } != wasm_version.span())
  1146. return with_eof_check(stream, ParseError::InvalidModuleVersion);
  1147. Vector<AnySection> sections;
  1148. for (;;) {
  1149. auto section_id_or_error = stream.read_value<u8>();
  1150. if (stream.is_eof())
  1151. break;
  1152. if (section_id_or_error.is_error())
  1153. return with_eof_check(stream, ParseError::ExpectedIndex);
  1154. auto section_id = section_id_or_error.release_value();
  1155. size_t section_size;
  1156. Core::Stream::WrapInAKInputStream wrapped_stream { stream };
  1157. if (!LEB128::read_unsigned(wrapped_stream, section_size))
  1158. return with_eof_check(stream, ParseError::ExpectedSize);
  1159. auto section_stream = ConstrainedStream { stream, section_size };
  1160. switch (section_id) {
  1161. case CustomSection::section_id:
  1162. sections.append(TRY(CustomSection::parse(section_stream)));
  1163. continue;
  1164. case TypeSection::section_id:
  1165. sections.append(TRY(TypeSection::parse(section_stream)));
  1166. continue;
  1167. case ImportSection::section_id:
  1168. sections.append(TRY(ImportSection::parse(section_stream)));
  1169. continue;
  1170. case FunctionSection::section_id:
  1171. sections.append(TRY(FunctionSection::parse(section_stream)));
  1172. continue;
  1173. case TableSection::section_id:
  1174. sections.append(TRY(TableSection::parse(section_stream)));
  1175. continue;
  1176. case MemorySection::section_id:
  1177. sections.append(TRY(MemorySection::parse(section_stream)));
  1178. continue;
  1179. case GlobalSection::section_id:
  1180. sections.append(TRY(GlobalSection::parse(section_stream)));
  1181. continue;
  1182. case ExportSection::section_id:
  1183. sections.append(TRY(ExportSection::parse(section_stream)));
  1184. continue;
  1185. case StartSection::section_id:
  1186. sections.append(TRY(StartSection::parse(section_stream)));
  1187. continue;
  1188. case ElementSection::section_id:
  1189. sections.append(TRY(ElementSection::parse(section_stream)));
  1190. continue;
  1191. case CodeSection::section_id:
  1192. sections.append(TRY(CodeSection::parse(section_stream)));
  1193. continue;
  1194. case DataSection::section_id:
  1195. sections.append(TRY(DataSection::parse(section_stream)));
  1196. continue;
  1197. case DataCountSection::section_id:
  1198. sections.append(TRY(DataCountSection::parse(section_stream)));
  1199. continue;
  1200. default:
  1201. return with_eof_check(stream, ParseError::InvalidIndex);
  1202. }
  1203. }
  1204. return Module { move(sections) };
  1205. }
  1206. bool Module::populate_sections()
  1207. {
  1208. auto is_ok = true;
  1209. FunctionSection const* function_section { nullptr };
  1210. for_each_section_of_type<FunctionSection>([&](FunctionSection const& section) { function_section = &section; });
  1211. for_each_section_of_type<CodeSection>([&](CodeSection const& section) {
  1212. if (!function_section) {
  1213. is_ok = false;
  1214. return;
  1215. }
  1216. size_t index = 0;
  1217. for (auto& entry : section.functions()) {
  1218. if (function_section->types().size() <= index) {
  1219. is_ok = false;
  1220. return;
  1221. }
  1222. auto& type_index = function_section->types()[index];
  1223. Vector<ValueType> locals;
  1224. for (auto& local : entry.func().locals()) {
  1225. for (size_t i = 0; i < local.n(); ++i)
  1226. locals.append(local.type());
  1227. }
  1228. m_functions.empend(type_index, move(locals), entry.func().body());
  1229. ++index;
  1230. }
  1231. });
  1232. return is_ok;
  1233. }
  1234. DeprecatedString parse_error_to_deprecated_string(ParseError error)
  1235. {
  1236. switch (error) {
  1237. case ParseError::UnexpectedEof:
  1238. return "Unexpected end-of-file";
  1239. case ParseError::ExpectedIndex:
  1240. return "Expected a valid index value";
  1241. case ParseError::ExpectedKindTag:
  1242. return "Expected a valid kind tag";
  1243. case ParseError::ExpectedSize:
  1244. return "Expected a valid LEB128-encoded size";
  1245. case ParseError::ExpectedValueOrTerminator:
  1246. return "Expected either a terminator or a value";
  1247. case ParseError::InvalidIndex:
  1248. return "An index parsed was semantically invalid";
  1249. case ParseError::InvalidInput:
  1250. return "Input data contained invalid bytes";
  1251. case ParseError::InvalidModuleMagic:
  1252. return "Incorrect module magic (did not match \\0asm)";
  1253. case ParseError::InvalidModuleVersion:
  1254. return "Incorrect module version";
  1255. case ParseError::InvalidSize:
  1256. return "A parsed size did not make sense in context";
  1257. case ParseError::InvalidTag:
  1258. return "A parsed tag did not make sense in context";
  1259. case ParseError::InvalidType:
  1260. return "A parsed type did not make sense in context";
  1261. case ParseError::NotImplemented:
  1262. return "The parser encountered an unimplemented feature";
  1263. case ParseError::HugeAllocationRequested:
  1264. return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
  1265. case ParseError::OutOfMemory:
  1266. return "The parser hit an OOM condition";
  1267. case ParseError::ExpectedFloatingImmediate:
  1268. return "Expected a floating point immediate";
  1269. case ParseError::ExpectedSignedImmediate:
  1270. return "Expected a signed integer immediate";
  1271. case ParseError::InvalidImmediate:
  1272. return "A parsed instruction immediate was invalid for the instruction it was used for";
  1273. case ParseError::UnknownInstruction:
  1274. return "A parsed instruction was not known to this parser";
  1275. }
  1276. return "Unknown error";
  1277. }
  1278. }