Parser.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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(InputStream const& 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 > Constants::max_allowed_vector_size)
  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.extend(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 {:#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.extend(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.extend(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. ByteBuffer data_buffer;
  677. if (!data_buffer.try_resize(64))
  678. return ParseError::OutOfMemory;
  679. while (!stream.has_any_error() && !stream.unreliable_eof()) {
  680. char buf[16];
  681. auto size = stream.read({ buf, 16 });
  682. if (size == 0)
  683. break;
  684. if (!data_buffer.try_append(buf, size))
  685. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  686. }
  687. return CustomSection(name.release_value(), move(data_buffer));
  688. }
  689. ParseResult<TypeSection> TypeSection::parse(InputStream& stream)
  690. {
  691. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection");
  692. auto types = parse_vector<FunctionType>(stream);
  693. if (types.is_error())
  694. return types.error();
  695. return TypeSection { types.release_value() };
  696. }
  697. ParseResult<ImportSection::Import> ImportSection::Import::parse(InputStream& stream)
  698. {
  699. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import");
  700. auto module = parse_name(stream);
  701. if (module.is_error())
  702. return module.error();
  703. auto name = parse_name(stream);
  704. if (name.is_error())
  705. return name.error();
  706. u8 tag;
  707. stream >> tag;
  708. if (stream.has_any_error())
  709. return with_eof_check(stream, ParseError::ExpectedKindTag);
  710. switch (tag) {
  711. case Constants::extern_function_tag: {
  712. auto index = GenericIndexParser<TypeIndex>::parse(stream);
  713. if (index.is_error())
  714. return index.error();
  715. return Import { module.release_value(), name.release_value(), index.release_value() };
  716. }
  717. case Constants::extern_table_tag:
  718. return parse_with_type<TableType>(stream, module, name);
  719. case Constants::extern_memory_tag:
  720. return parse_with_type<MemoryType>(stream, module, name);
  721. case Constants::extern_global_tag:
  722. return parse_with_type<GlobalType>(stream, module, name);
  723. default:
  724. return with_eof_check(stream, ParseError::InvalidTag);
  725. }
  726. }
  727. ParseResult<ImportSection> ImportSection::parse(InputStream& stream)
  728. {
  729. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection");
  730. auto imports = parse_vector<Import>(stream);
  731. if (imports.is_error())
  732. return imports.error();
  733. return ImportSection { imports.release_value() };
  734. }
  735. ParseResult<FunctionSection> FunctionSection::parse(InputStream& stream)
  736. {
  737. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection");
  738. auto indices = parse_vector<size_t>(stream);
  739. if (indices.is_error())
  740. return indices.error();
  741. Vector<TypeIndex> typed_indices;
  742. typed_indices.ensure_capacity(indices.value().size());
  743. for (auto entry : indices.value())
  744. typed_indices.append(entry);
  745. return FunctionSection { move(typed_indices) };
  746. }
  747. ParseResult<TableSection::Table> TableSection::Table::parse(InputStream& stream)
  748. {
  749. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table");
  750. auto type = TableType::parse(stream);
  751. if (type.is_error())
  752. return type.error();
  753. return Table { type.release_value() };
  754. }
  755. ParseResult<TableSection> TableSection::parse(InputStream& stream)
  756. {
  757. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection");
  758. auto tables = parse_vector<Table>(stream);
  759. if (tables.is_error())
  760. return tables.error();
  761. return TableSection { tables.release_value() };
  762. }
  763. ParseResult<MemorySection::Memory> MemorySection::Memory::parse(InputStream& stream)
  764. {
  765. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory");
  766. auto type = MemoryType::parse(stream);
  767. if (type.is_error())
  768. return type.error();
  769. return Memory { type.release_value() };
  770. }
  771. ParseResult<MemorySection> MemorySection::parse(InputStream& stream)
  772. {
  773. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection");
  774. auto memorys = parse_vector<Memory>(stream);
  775. if (memorys.is_error())
  776. return memorys.error();
  777. return MemorySection { memorys.release_value() };
  778. }
  779. ParseResult<Expression> Expression::parse(InputStream& stream)
  780. {
  781. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression");
  782. InstructionPointer ip { 0 };
  783. auto instructions = parse_until_any_of<Instruction, 0x0b>(stream, ip);
  784. if (instructions.is_error())
  785. return instructions.error();
  786. return Expression { move(instructions.value().values) };
  787. }
  788. ParseResult<GlobalSection::Global> GlobalSection::Global::parse(InputStream& stream)
  789. {
  790. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global");
  791. auto type = GlobalType::parse(stream);
  792. if (type.is_error())
  793. return type.error();
  794. auto exprs = Expression::parse(stream);
  795. if (exprs.is_error())
  796. return exprs.error();
  797. return Global { type.release_value(), exprs.release_value() };
  798. }
  799. ParseResult<GlobalSection> GlobalSection::parse(InputStream& stream)
  800. {
  801. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection");
  802. auto result = parse_vector<Global>(stream);
  803. if (result.is_error())
  804. return result.error();
  805. return GlobalSection { result.release_value() };
  806. }
  807. ParseResult<ExportSection::Export> ExportSection::Export::parse(InputStream& stream)
  808. {
  809. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export");
  810. auto name = parse_name(stream);
  811. if (name.is_error())
  812. return name.error();
  813. u8 tag;
  814. stream >> tag;
  815. if (stream.has_any_error())
  816. return with_eof_check(stream, ParseError::ExpectedKindTag);
  817. size_t index;
  818. if (!LEB128::read_unsigned(stream, index))
  819. return with_eof_check(stream, ParseError::ExpectedIndex);
  820. switch (tag) {
  821. case Constants::extern_function_tag:
  822. return Export { name.release_value(), ExportDesc { FunctionIndex { index } } };
  823. case Constants::extern_table_tag:
  824. return Export { name.release_value(), ExportDesc { TableIndex { index } } };
  825. case Constants::extern_memory_tag:
  826. return Export { name.release_value(), ExportDesc { MemoryIndex { index } } };
  827. case Constants::extern_global_tag:
  828. return Export { name.release_value(), ExportDesc { GlobalIndex { index } } };
  829. default:
  830. return with_eof_check(stream, ParseError::InvalidTag);
  831. }
  832. }
  833. ParseResult<ExportSection> ExportSection::parse(InputStream& stream)
  834. {
  835. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection");
  836. auto result = parse_vector<Export>(stream);
  837. if (result.is_error())
  838. return result.error();
  839. return ExportSection { result.release_value() };
  840. }
  841. ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(InputStream& stream)
  842. {
  843. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction");
  844. auto index = GenericIndexParser<FunctionIndex>::parse(stream);
  845. if (index.is_error())
  846. return index.error();
  847. return StartFunction { index.release_value() };
  848. }
  849. ParseResult<StartSection> StartSection::parse(InputStream& stream)
  850. {
  851. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection");
  852. auto result = StartFunction::parse(stream);
  853. if (result.is_error())
  854. return result.error();
  855. return StartSection { result.release_value() };
  856. }
  857. ParseResult<ElementSection::SegmentType0> ElementSection::SegmentType0::parse(InputStream& stream)
  858. {
  859. auto expression = Expression::parse(stream);
  860. if (expression.is_error())
  861. return expression.error();
  862. auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
  863. if (indices.is_error())
  864. return indices.error();
  865. return SegmentType0 { indices.release_value(), Active { 0, expression.release_value() } };
  866. }
  867. ParseResult<ElementSection::SegmentType1> ElementSection::SegmentType1::parse(InputStream& stream)
  868. {
  869. u8 kind;
  870. stream >> kind;
  871. if (stream.has_any_error())
  872. return with_eof_check(stream, ParseError::ExpectedKindTag);
  873. if (kind != 0)
  874. return ParseError::InvalidTag;
  875. auto indices = parse_vector<GenericIndexParser<FunctionIndex>>(stream);
  876. if (indices.is_error())
  877. return indices.error();
  878. return SegmentType1 { indices.release_value() };
  879. }
  880. ParseResult<ElementSection::SegmentType2> ElementSection::SegmentType2::parse(InputStream& stream)
  881. {
  882. dbgln("Type 2");
  883. (void)stream;
  884. return ParseError::NotImplemented;
  885. }
  886. ParseResult<ElementSection::SegmentType3> ElementSection::SegmentType3::parse(InputStream& stream)
  887. {
  888. dbgln("Type 3");
  889. (void)stream;
  890. return ParseError::NotImplemented;
  891. }
  892. ParseResult<ElementSection::SegmentType4> ElementSection::SegmentType4::parse(InputStream& stream)
  893. {
  894. dbgln("Type 4");
  895. (void)stream;
  896. return ParseError::NotImplemented;
  897. }
  898. ParseResult<ElementSection::SegmentType5> ElementSection::SegmentType5::parse(InputStream& stream)
  899. {
  900. dbgln("Type 5");
  901. (void)stream;
  902. return ParseError::NotImplemented;
  903. }
  904. ParseResult<ElementSection::SegmentType6> ElementSection::SegmentType6::parse(InputStream& stream)
  905. {
  906. dbgln("Type 6");
  907. (void)stream;
  908. return ParseError::NotImplemented;
  909. }
  910. ParseResult<ElementSection::SegmentType7> ElementSection::SegmentType7::parse(InputStream& stream)
  911. {
  912. dbgln("Type 7");
  913. (void)stream;
  914. return ParseError::NotImplemented;
  915. }
  916. ParseResult<ElementSection::Element> ElementSection::Element::parse(InputStream& stream)
  917. {
  918. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element");
  919. u8 tag;
  920. stream >> tag;
  921. if (stream.has_any_error())
  922. return with_eof_check(stream, ParseError::ExpectedKindTag);
  923. switch (tag) {
  924. case 0x00:
  925. if (auto result = SegmentType0::parse(stream); result.is_error()) {
  926. return result.error();
  927. } else {
  928. Vector<Instruction> instructions;
  929. for (auto& index : result.value().function_indices)
  930. instructions.empend(Instructions::ref_func, index);
  931. return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, move(result.value().mode) };
  932. }
  933. case 0x01:
  934. if (auto result = SegmentType1::parse(stream); result.is_error()) {
  935. return result.error();
  936. } else {
  937. Vector<Instruction> instructions;
  938. for (auto& index : result.value().function_indices)
  939. instructions.empend(Instructions::ref_func, index);
  940. return Element { ValueType(ValueType::FunctionReference), { Expression { move(instructions) } }, Passive {} };
  941. }
  942. case 0x02:
  943. if (auto result = SegmentType2::parse(stream); result.is_error()) {
  944. return result.error();
  945. } else {
  946. return ParseError::NotImplemented;
  947. }
  948. case 0x03:
  949. if (auto result = SegmentType3::parse(stream); result.is_error()) {
  950. return result.error();
  951. } else {
  952. return ParseError::NotImplemented;
  953. }
  954. case 0x04:
  955. if (auto result = SegmentType4::parse(stream); result.is_error()) {
  956. return result.error();
  957. } else {
  958. return ParseError::NotImplemented;
  959. }
  960. case 0x05:
  961. if (auto result = SegmentType5::parse(stream); result.is_error()) {
  962. return result.error();
  963. } else {
  964. return ParseError::NotImplemented;
  965. }
  966. case 0x06:
  967. if (auto result = SegmentType6::parse(stream); result.is_error()) {
  968. return result.error();
  969. } else {
  970. return ParseError::NotImplemented;
  971. }
  972. case 0x07:
  973. if (auto result = SegmentType7::parse(stream); result.is_error()) {
  974. return result.error();
  975. } else {
  976. return ParseError::NotImplemented;
  977. }
  978. default:
  979. return ParseError::InvalidTag;
  980. }
  981. }
  982. ParseResult<ElementSection> ElementSection::parse(InputStream& stream)
  983. {
  984. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection");
  985. auto result = parse_vector<Element>(stream);
  986. if (result.is_error())
  987. return result.error();
  988. return ElementSection { result.release_value() };
  989. }
  990. ParseResult<Locals> Locals::parse(InputStream& stream)
  991. {
  992. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals");
  993. size_t count;
  994. if (!LEB128::read_unsigned(stream, count))
  995. return with_eof_check(stream, ParseError::InvalidSize);
  996. if (count > Constants::max_allowed_function_locals_per_type)
  997. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  998. auto type = ValueType::parse(stream);
  999. if (type.is_error())
  1000. return type.error();
  1001. return Locals { static_cast<u32>(count), type.release_value() };
  1002. }
  1003. ParseResult<CodeSection::Func> CodeSection::Func::parse(InputStream& stream)
  1004. {
  1005. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func");
  1006. auto locals = parse_vector<Locals>(stream);
  1007. if (locals.is_error())
  1008. return locals.error();
  1009. auto body = Expression::parse(stream);
  1010. if (body.is_error())
  1011. return body.error();
  1012. return Func { locals.release_value(), body.release_value() };
  1013. }
  1014. ParseResult<CodeSection::Code> CodeSection::Code::parse(InputStream& stream)
  1015. {
  1016. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code");
  1017. size_t size;
  1018. if (!LEB128::read_unsigned(stream, size))
  1019. return with_eof_check(stream, ParseError::InvalidSize);
  1020. auto constrained_stream = ConstrainedStream { stream, size };
  1021. ScopeGuard drain_errors {
  1022. [&] {
  1023. constrained_stream.handle_any_error();
  1024. }
  1025. };
  1026. auto func = Func::parse(constrained_stream);
  1027. if (func.is_error())
  1028. return func.error();
  1029. return Code { static_cast<u32>(size), func.release_value() };
  1030. }
  1031. ParseResult<CodeSection> CodeSection::parse(InputStream& stream)
  1032. {
  1033. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection");
  1034. auto result = parse_vector<Code>(stream);
  1035. if (result.is_error())
  1036. return result.error();
  1037. return CodeSection { result.release_value() };
  1038. }
  1039. ParseResult<DataSection::Data> DataSection::Data::parse(InputStream& stream)
  1040. {
  1041. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data");
  1042. u8 tag;
  1043. stream >> tag;
  1044. if (stream.has_any_error())
  1045. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1046. if (tag > 0x02)
  1047. return with_eof_check(stream, ParseError::InvalidTag);
  1048. if (tag == 0x00) {
  1049. auto expr = Expression::parse(stream);
  1050. if (expr.is_error())
  1051. return expr.error();
  1052. auto init = parse_vector<u8>(stream);
  1053. if (init.is_error())
  1054. return init.error();
  1055. return Data { Active { init.release_value(), { 0 }, expr.release_value() } };
  1056. }
  1057. if (tag == 0x01) {
  1058. auto init = parse_vector<u8>(stream);
  1059. if (init.is_error())
  1060. return init.error();
  1061. return Data { Passive { init.release_value() } };
  1062. }
  1063. if (tag == 0x02) {
  1064. auto index = GenericIndexParser<MemoryIndex>::parse(stream);
  1065. if (index.is_error())
  1066. return index.error();
  1067. auto expr = Expression::parse(stream);
  1068. if (expr.is_error())
  1069. return expr.error();
  1070. auto init = parse_vector<u8>(stream);
  1071. if (init.is_error())
  1072. return init.error();
  1073. return Data { Active { init.release_value(), index.release_value(), expr.release_value() } };
  1074. }
  1075. VERIFY_NOT_REACHED();
  1076. }
  1077. ParseResult<DataSection> DataSection::parse(InputStream& stream)
  1078. {
  1079. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection");
  1080. auto data = parse_vector<Data>(stream);
  1081. if (data.is_error())
  1082. return data.error();
  1083. return DataSection { data.release_value() };
  1084. }
  1085. ParseResult<DataCountSection> DataCountSection::parse([[maybe_unused]] InputStream& stream)
  1086. {
  1087. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection");
  1088. u32 value;
  1089. if (!LEB128::read_unsigned(stream, value)) {
  1090. if (stream.unreliable_eof()) {
  1091. // The section simply didn't contain anything.
  1092. return DataCountSection { {} };
  1093. }
  1094. return ParseError::ExpectedSize;
  1095. }
  1096. return DataCountSection { value };
  1097. }
  1098. ParseResult<Module> Module::parse(InputStream& stream)
  1099. {
  1100. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module");
  1101. u8 buf[4];
  1102. if (!stream.read_or_error({ buf, 4 }))
  1103. return with_eof_check(stream, ParseError::InvalidInput);
  1104. if (Bytes { buf, 4 } != wasm_magic.span())
  1105. return with_eof_check(stream, ParseError::InvalidModuleMagic);
  1106. if (!stream.read_or_error({ buf, 4 }))
  1107. return with_eof_check(stream, ParseError::InvalidInput);
  1108. if (Bytes { buf, 4 } != wasm_version.span())
  1109. return with_eof_check(stream, ParseError::InvalidModuleVersion);
  1110. Vector<AnySection> sections;
  1111. for (;;) {
  1112. u8 section_id;
  1113. stream >> section_id;
  1114. if (stream.unreliable_eof()) {
  1115. stream.handle_any_error();
  1116. break;
  1117. }
  1118. if (stream.has_any_error())
  1119. return with_eof_check(stream, ParseError::ExpectedIndex);
  1120. size_t section_size;
  1121. if (!LEB128::read_unsigned(stream, section_size))
  1122. return with_eof_check(stream, ParseError::ExpectedSize);
  1123. auto section_stream = ConstrainedStream { stream, section_size };
  1124. ScopeGuard drain_errors {
  1125. [&] {
  1126. section_stream.handle_any_error();
  1127. }
  1128. };
  1129. switch (section_id) {
  1130. case CustomSection::section_id: {
  1131. if (auto section = CustomSection::parse(section_stream); !section.is_error()) {
  1132. sections.append(section.release_value());
  1133. continue;
  1134. } else {
  1135. return section.error();
  1136. }
  1137. }
  1138. case TypeSection::section_id: {
  1139. if (auto section = TypeSection::parse(section_stream); !section.is_error()) {
  1140. sections.append(section.release_value());
  1141. continue;
  1142. } else {
  1143. return section.error();
  1144. }
  1145. }
  1146. case ImportSection::section_id: {
  1147. if (auto section = ImportSection::parse(section_stream); !section.is_error()) {
  1148. sections.append(section.release_value());
  1149. continue;
  1150. } else {
  1151. return section.error();
  1152. }
  1153. }
  1154. case FunctionSection::section_id: {
  1155. if (auto section = FunctionSection::parse(section_stream); !section.is_error()) {
  1156. sections.append(section.release_value());
  1157. continue;
  1158. } else {
  1159. return section.error();
  1160. }
  1161. }
  1162. case TableSection::section_id: {
  1163. if (auto section = TableSection::parse(section_stream); !section.is_error()) {
  1164. sections.append(section.release_value());
  1165. continue;
  1166. } else {
  1167. return section.error();
  1168. }
  1169. }
  1170. case MemorySection::section_id: {
  1171. if (auto section = MemorySection::parse(section_stream); !section.is_error()) {
  1172. sections.append(section.release_value());
  1173. continue;
  1174. } else {
  1175. return section.error();
  1176. }
  1177. }
  1178. case GlobalSection::section_id: {
  1179. if (auto section = GlobalSection::parse(section_stream); !section.is_error()) {
  1180. sections.append(section.release_value());
  1181. continue;
  1182. } else {
  1183. return section.error();
  1184. }
  1185. }
  1186. case ExportSection::section_id: {
  1187. if (auto section = ExportSection::parse(section_stream); !section.is_error()) {
  1188. sections.append(section.release_value());
  1189. continue;
  1190. } else {
  1191. return section.error();
  1192. }
  1193. }
  1194. case StartSection::section_id: {
  1195. if (auto section = StartSection::parse(section_stream); !section.is_error()) {
  1196. sections.append(section.release_value());
  1197. continue;
  1198. } else {
  1199. return section.error();
  1200. }
  1201. }
  1202. case ElementSection::section_id: {
  1203. if (auto section = ElementSection::parse(section_stream); !section.is_error()) {
  1204. sections.append(section.release_value());
  1205. continue;
  1206. } else {
  1207. return section.error();
  1208. }
  1209. }
  1210. case CodeSection::section_id: {
  1211. if (auto section = CodeSection::parse(section_stream); !section.is_error()) {
  1212. sections.append(section.release_value());
  1213. continue;
  1214. } else {
  1215. return section.error();
  1216. }
  1217. }
  1218. case DataSection::section_id: {
  1219. if (auto section = DataSection::parse(section_stream); !section.is_error()) {
  1220. sections.append(section.release_value());
  1221. continue;
  1222. } else {
  1223. return section.error();
  1224. }
  1225. }
  1226. case DataCountSection::section_id: {
  1227. if (auto section = DataCountSection::parse(section_stream); !section.is_error()) {
  1228. sections.append(section.release_value());
  1229. continue;
  1230. } else {
  1231. return section.error();
  1232. }
  1233. }
  1234. default:
  1235. return with_eof_check(stream, ParseError::InvalidIndex);
  1236. }
  1237. }
  1238. return Module { move(sections) };
  1239. }
  1240. void Module::populate_sections()
  1241. {
  1242. FunctionSection const* function_section { nullptr };
  1243. for_each_section_of_type<FunctionSection>([&](FunctionSection const& section) { function_section = &section; });
  1244. for_each_section_of_type<CodeSection>([&](CodeSection const& section) {
  1245. // FIXME: This should be considered invalid once validation is implemented.
  1246. if (!function_section)
  1247. return;
  1248. size_t index = 0;
  1249. for (auto& entry : section.functions()) {
  1250. auto& type_index = function_section->types()[index];
  1251. Vector<ValueType> locals;
  1252. for (auto& local : entry.func().locals()) {
  1253. for (size_t i = 0; i < local.n(); ++i)
  1254. locals.append(local.type());
  1255. }
  1256. m_functions.empend(type_index, move(locals), entry.func().body());
  1257. ++index;
  1258. }
  1259. });
  1260. }
  1261. String parse_error_to_string(ParseError error)
  1262. {
  1263. switch (error) {
  1264. case ParseError::UnexpectedEof:
  1265. return "Unexpected end-of-file";
  1266. case ParseError::ExpectedIndex:
  1267. return "Expected a valid index value";
  1268. case ParseError::ExpectedKindTag:
  1269. return "Expected a valid kind tag";
  1270. case ParseError::ExpectedSize:
  1271. return "Expected a valid LEB128-encoded size";
  1272. case ParseError::ExpectedValueOrTerminator:
  1273. return "Expected either a terminator or a value";
  1274. case ParseError::InvalidIndex:
  1275. return "An index parsed was semantically invalid";
  1276. case ParseError::InvalidInput:
  1277. return "Input data contained invalid bytes";
  1278. case ParseError::InvalidModuleMagic:
  1279. return "Incorrect module magic (did not match \\0asm)";
  1280. case ParseError::InvalidModuleVersion:
  1281. return "Incorrect module version";
  1282. case ParseError::InvalidSize:
  1283. return "A parsed size did not make sense in context";
  1284. case ParseError::InvalidTag:
  1285. return "A parsed tag did not make sense in context";
  1286. case ParseError::InvalidType:
  1287. return "A parsed type did not make sense in context";
  1288. case ParseError::NotImplemented:
  1289. return "The parser encountered an unimplemented feature";
  1290. case ParseError::HugeAllocationRequested:
  1291. return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
  1292. case ParseError::OutOfMemory:
  1293. return "The parser hit an OOM condition";
  1294. case ParseError::ExpectedFloatingImmediate:
  1295. return "Expected a floating point immediate";
  1296. case ParseError::ExpectedSignedImmediate:
  1297. return "Expected a signed integer immediate";
  1298. case ParseError::InvalidImmediate:
  1299. return "A parsed instruction immediate was invalid for the instruction it was used for";
  1300. case ParseError::UnknownInstruction:
  1301. return "A parsed instruction was not known to this parser";
  1302. }
  1303. return "Unknown error";
  1304. }
  1305. }