Parser.cpp 50 KB

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