Parser.cpp 53 KB

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