Parser.cpp 55 KB

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