Parser.cpp 54 KB

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