Parser.cpp 54 KB

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