Parser.cpp 51 KB

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