Parser.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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 <AK/UFixedBigInt.h>
  14. #include <LibWasm/Types.h>
  15. namespace Wasm {
  16. ParseError with_eof_check(Stream const& stream, ParseError error_if_not_eof)
  17. {
  18. if (stream.is_eof())
  19. return ParseError::UnexpectedEof;
  20. return error_if_not_eof;
  21. }
  22. template<typename T>
  23. static auto parse_vector(Stream& stream)
  24. {
  25. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  26. if constexpr (requires { T::parse(stream); }) {
  27. using ResultT = typename decltype(T::parse(stream))::ResultType;
  28. auto count_or_error = stream.read_value<LEB128<u32>>();
  29. if (count_or_error.is_error())
  30. return ParseResult<Vector<ResultT>> { with_eof_check(stream, ParseError::ExpectedSize) };
  31. size_t count = count_or_error.release_value();
  32. Vector<ResultT> entries;
  33. entries.ensure_capacity(count);
  34. for (size_t i = 0; i < count; ++i) {
  35. auto result = T::parse(stream);
  36. if (result.is_error())
  37. return ParseResult<Vector<ResultT>> { result.error() };
  38. entries.append(result.release_value());
  39. }
  40. return ParseResult<Vector<ResultT>> { move(entries) };
  41. } else {
  42. auto count_or_error = stream.read_value<LEB128<u32>>();
  43. if (count_or_error.is_error())
  44. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  45. size_t count = count_or_error.release_value();
  46. Vector<T> entries;
  47. entries.ensure_capacity(count);
  48. for (size_t i = 0; i < count; ++i) {
  49. if constexpr (IsSame<T, u32>) {
  50. auto value_or_error = stream.read_value<LEB128<u32>>();
  51. if (value_or_error.is_error())
  52. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  53. size_t value = value_or_error.release_value();
  54. entries.append(value);
  55. } else if constexpr (IsSame<T, ssize_t>) {
  56. auto value_or_error = stream.read_value<LEB128<ssize_t>>();
  57. if (value_or_error.is_error())
  58. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::ExpectedSize) };
  59. ssize_t value = value_or_error.release_value();
  60. entries.append(value);
  61. } else if constexpr (IsSame<T, u8>) {
  62. if (count > Constants::max_allowed_vector_size)
  63. return ParseResult<Vector<T>> { ParseError::HugeAllocationRequested };
  64. entries.resize(count);
  65. if (stream.read_until_filled({ entries.data(), entries.size() }).is_error())
  66. return ParseResult<Vector<T>> { with_eof_check(stream, ParseError::InvalidInput) };
  67. break; // Note: We read this all in one go!
  68. }
  69. }
  70. return ParseResult<Vector<T>> { move(entries) };
  71. }
  72. }
  73. static ParseResult<ByteString> parse_name(Stream& stream)
  74. {
  75. ScopeLogger<WASM_BINPARSER_DEBUG> logger;
  76. auto data = TRY(parse_vector<u8>(stream));
  77. auto string = ByteString::copy(data);
  78. if (!Utf8View(string).validate(Utf8View::AllowSurrogates::No))
  79. return ParseError::InvalidUtf8;
  80. return string;
  81. }
  82. ParseResult<ValueType> ValueType::parse(Stream& stream)
  83. {
  84. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ValueType"sv);
  85. auto tag_or_error = stream.read_value<u8>();
  86. if (tag_or_error.is_error())
  87. return with_eof_check(stream, ParseError::ExpectedKindTag);
  88. auto tag = tag_or_error.release_value();
  89. switch (tag) {
  90. case Constants::i32_tag:
  91. return ValueType(I32);
  92. case Constants::i64_tag:
  93. return ValueType(I64);
  94. case Constants::f32_tag:
  95. return ValueType(F32);
  96. case Constants::f64_tag:
  97. return ValueType(F64);
  98. case Constants::v128_tag:
  99. return ValueType(V128);
  100. case Constants::function_reference_tag:
  101. return ValueType(FunctionReference);
  102. case Constants::extern_reference_tag:
  103. return ValueType(ExternReference);
  104. default:
  105. return with_eof_check(stream, ParseError::InvalidTag);
  106. }
  107. }
  108. ParseResult<ResultType> ResultType::parse(Stream& stream)
  109. {
  110. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ResultType"sv);
  111. auto types = TRY(parse_vector<ValueType>(stream));
  112. return ResultType { types };
  113. }
  114. ParseResult<FunctionType> FunctionType::parse(Stream& stream)
  115. {
  116. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionType"sv);
  117. auto tag_or_error = stream.read_value<u8>();
  118. if (tag_or_error.is_error())
  119. return with_eof_check(stream, ParseError::ExpectedKindTag);
  120. auto tag = tag_or_error.release_value();
  121. if (tag != Constants::function_signature_tag) {
  122. dbgln("Expected 0x60, but found {:#x}", tag);
  123. return with_eof_check(stream, ParseError::InvalidTag);
  124. }
  125. auto parameters_result = TRY(parse_vector<ValueType>(stream));
  126. auto results_result = TRY(parse_vector<ValueType>(stream));
  127. return FunctionType { parameters_result, results_result };
  128. }
  129. ParseResult<Limits> Limits::parse(Stream& stream)
  130. {
  131. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Limits"sv);
  132. auto flag_or_error = stream.read_value<u8>();
  133. if (flag_or_error.is_error())
  134. return with_eof_check(stream, ParseError::ExpectedKindTag);
  135. auto flag = flag_or_error.release_value();
  136. if (flag > 1)
  137. return with_eof_check(stream, ParseError::InvalidTag);
  138. auto min_or_error = stream.read_value<LEB128<u32>>();
  139. if (min_or_error.is_error())
  140. return with_eof_check(stream, ParseError::ExpectedSize);
  141. size_t min = min_or_error.release_value();
  142. Optional<u32> max;
  143. if (flag) {
  144. auto value_or_error = stream.read_value<LEB128<u32>>();
  145. if (value_or_error.is_error())
  146. return with_eof_check(stream, ParseError::ExpectedSize);
  147. max = value_or_error.release_value();
  148. }
  149. return Limits { static_cast<u32>(min), move(max) };
  150. }
  151. ParseResult<MemoryType> MemoryType::parse(Stream& stream)
  152. {
  153. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemoryType"sv);
  154. auto limits_result = TRY(Limits::parse(stream));
  155. return MemoryType { limits_result };
  156. }
  157. ParseResult<TableType> TableType::parse(Stream& stream)
  158. {
  159. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableType"sv);
  160. auto type_result = TRY(ValueType::parse(stream));
  161. if (!type_result.is_reference())
  162. return with_eof_check(stream, ParseError::InvalidType);
  163. auto limits_result = TRY(Limits::parse(stream));
  164. return TableType { type_result, limits_result };
  165. }
  166. ParseResult<GlobalType> GlobalType::parse(Stream& stream)
  167. {
  168. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalType"sv);
  169. auto type_result = TRY(ValueType::parse(stream));
  170. auto mutable_or_error = stream.read_value<u8>();
  171. if (mutable_or_error.is_error())
  172. return with_eof_check(stream, ParseError::ExpectedKindTag);
  173. auto mutable_ = mutable_or_error.release_value();
  174. if (mutable_ > 1)
  175. return with_eof_check(stream, ParseError::InvalidTag);
  176. return GlobalType { type_result, mutable_ == 0x01 };
  177. }
  178. ParseResult<BlockType> BlockType::parse(Stream& stream)
  179. {
  180. ScopeLogger<WASM_BINPARSER_DEBUG> logger("BlockType"sv);
  181. auto kind_or_error = stream.read_value<u8>();
  182. if (kind_or_error.is_error())
  183. return with_eof_check(stream, ParseError::ExpectedKindTag);
  184. auto kind = kind_or_error.release_value();
  185. if (kind == Constants::empty_block_tag)
  186. return BlockType {};
  187. {
  188. FixedMemoryStream value_stream { ReadonlyBytes { &kind, 1 } };
  189. if (auto value_type = ValueType::parse(value_stream); !value_type.is_error())
  190. return BlockType { value_type.release_value() };
  191. }
  192. ReconsumableStream new_stream { stream };
  193. new_stream.unread({ &kind, 1 });
  194. // FIXME: should be an i33. Right now, we're missing a potential last bit at
  195. // the end. See https://webassembly.github.io/spec/core/binary/instructions.html#binary-blocktype
  196. auto index_value_or_error = new_stream.read_value<LEB128<i32>>();
  197. if (index_value_or_error.is_error())
  198. return with_eof_check(stream, ParseError::ExpectedIndex);
  199. i32 index_value = index_value_or_error.release_value();
  200. if (index_value < 0) {
  201. dbgln("Invalid type index {}", index_value);
  202. return with_eof_check(stream, ParseError::InvalidIndex);
  203. }
  204. return BlockType { TypeIndex(index_value) };
  205. }
  206. ParseResult<Instruction> Instruction::parse(Stream& stream)
  207. {
  208. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Instruction"sv);
  209. auto byte_or_error = stream.read_value<u8>();
  210. if (byte_or_error.is_error())
  211. return with_eof_check(stream, ParseError::ExpectedKindTag);
  212. auto byte = byte_or_error.release_value();
  213. OpCode opcode { byte };
  214. switch (opcode.value()) {
  215. case Instructions::block.value():
  216. case Instructions::loop.value():
  217. case Instructions::if_.value(): {
  218. auto block_type = TRY(BlockType::parse(stream));
  219. return Instruction {
  220. opcode, StructuredInstructionArgs { block_type, {}, {} }
  221. };
  222. }
  223. case Instructions::br.value():
  224. case Instructions::br_if.value(): {
  225. // branches with a single label immediate
  226. auto index = TRY(GenericIndexParser<LabelIndex>::parse(stream));
  227. return Instruction { opcode, index };
  228. }
  229. case Instructions::br_table.value(): {
  230. // br_table label* label
  231. auto labels = TRY(parse_vector<GenericIndexParser<LabelIndex>>(stream));
  232. auto default_label = TRY(GenericIndexParser<LabelIndex>::parse(stream));
  233. return Instruction { opcode, TableBranchArgs { labels, default_label } };
  234. }
  235. case Instructions::call.value(): {
  236. // call function
  237. auto function_index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  238. return Instruction { opcode, function_index };
  239. }
  240. case Instructions::call_indirect.value(): {
  241. // call_indirect type table
  242. auto type_index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
  243. auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  244. return Instruction { opcode, IndirectCallArgs { type_index, table_index } };
  245. }
  246. case Instructions::i32_load.value():
  247. case Instructions::i64_load.value():
  248. case Instructions::f32_load.value():
  249. case Instructions::f64_load.value():
  250. case Instructions::i32_load8_s.value():
  251. case Instructions::i32_load8_u.value():
  252. case Instructions::i32_load16_s.value():
  253. case Instructions::i32_load16_u.value():
  254. case Instructions::i64_load8_s.value():
  255. case Instructions::i64_load8_u.value():
  256. case Instructions::i64_load16_s.value():
  257. case Instructions::i64_load16_u.value():
  258. case Instructions::i64_load32_s.value():
  259. case Instructions::i64_load32_u.value():
  260. case Instructions::i32_store.value():
  261. case Instructions::i64_store.value():
  262. case Instructions::f32_store.value():
  263. case Instructions::f64_store.value():
  264. case Instructions::i32_store8.value():
  265. case Instructions::i32_store16.value():
  266. case Instructions::i64_store8.value():
  267. case Instructions::i64_store16.value():
  268. case Instructions::i64_store32.value(): {
  269. // op (align [multi-memory: memindex] offset)
  270. auto align_or_error = stream.read_value<LEB128<u32>>();
  271. if (align_or_error.is_error())
  272. return with_eof_check(stream, ParseError::InvalidInput);
  273. size_t align = align_or_error.release_value();
  274. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  275. size_t memory_index = 0;
  276. if ((align & 0x40) != 0) {
  277. align &= ~0x40;
  278. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  279. if (memory_index_or_error.is_error())
  280. return with_eof_check(stream, ParseError::InvalidInput);
  281. memory_index = memory_index_or_error.release_value();
  282. }
  283. auto offset_or_error = stream.read_value<LEB128<u32>>();
  284. if (offset_or_error.is_error())
  285. return with_eof_check(stream, ParseError::InvalidInput);
  286. size_t offset = offset_or_error.release_value();
  287. return Instruction { opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) } };
  288. }
  289. case Instructions::local_get.value():
  290. case Instructions::local_set.value():
  291. case Instructions::local_tee.value(): {
  292. auto index = TRY(GenericIndexParser<LocalIndex>::parse(stream));
  293. return Instruction { opcode, index };
  294. }
  295. case Instructions::global_get.value():
  296. case Instructions::global_set.value(): {
  297. auto index = TRY(GenericIndexParser<GlobalIndex>::parse(stream));
  298. return Instruction { opcode, index };
  299. }
  300. case Instructions::memory_size.value():
  301. case Instructions::memory_grow.value(): {
  302. // op [multi-memory: memindex]|0x00
  303. auto memory_index_or_error = stream.read_value<u8>();
  304. if (memory_index_or_error.is_error())
  305. return with_eof_check(stream, ParseError::ExpectedKindTag);
  306. auto memory_index = memory_index_or_error.release_value();
  307. return Instruction { opcode, MemoryIndexArgument { MemoryIndex(memory_index) } };
  308. }
  309. case Instructions::i32_const.value(): {
  310. auto value_or_error = stream.read_value<LEB128<i32>>();
  311. if (value_or_error.is_error())
  312. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  313. i32 value = value_or_error.release_value();
  314. return Instruction { opcode, value };
  315. }
  316. case Instructions::i64_const.value(): {
  317. // op literal
  318. auto value_or_error = stream.read_value<LEB128<i64>>();
  319. if (value_or_error.is_error())
  320. return with_eof_check(stream, ParseError::ExpectedSignedImmediate);
  321. i64 value = value_or_error.release_value();
  322. return Instruction { opcode, value };
  323. }
  324. case Instructions::f32_const.value(): {
  325. // op literal
  326. auto value_or_error = stream.read_value<LittleEndian<u32>>();
  327. if (value_or_error.is_error())
  328. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  329. auto value = value_or_error.release_value();
  330. auto floating = bit_cast<float>(static_cast<u32>(value));
  331. return Instruction { opcode, floating };
  332. }
  333. case Instructions::f64_const.value(): {
  334. // op literal
  335. auto value_or_error = stream.read_value<LittleEndian<u64>>();
  336. if (value_or_error.is_error())
  337. return with_eof_check(stream, ParseError::ExpectedFloatingImmediate);
  338. auto value = value_or_error.release_value();
  339. auto floating = bit_cast<double>(static_cast<u64>(value));
  340. return Instruction { opcode, floating };
  341. }
  342. case Instructions::table_get.value():
  343. case Instructions::table_set.value(): {
  344. auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  345. return Instruction { opcode, index };
  346. }
  347. case Instructions::select_typed.value(): {
  348. auto types = TRY(parse_vector<ValueType>(stream));
  349. return Instruction { opcode, types };
  350. }
  351. case Instructions::ref_null.value(): {
  352. auto type = TRY(ValueType::parse(stream));
  353. if (!type.is_reference())
  354. return ParseError::InvalidType;
  355. return Instruction { opcode, type };
  356. }
  357. case Instructions::ref_func.value(): {
  358. auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  359. return Instruction { opcode, index };
  360. }
  361. case Instructions::structured_end.value():
  362. case Instructions::structured_else.value():
  363. case Instructions::ref_is_null.value():
  364. case Instructions::unreachable.value():
  365. case Instructions::nop.value():
  366. case Instructions::return_.value():
  367. case Instructions::drop.value():
  368. case Instructions::select.value():
  369. case Instructions::i32_eqz.value():
  370. case Instructions::i32_eq.value():
  371. case Instructions::i32_ne.value():
  372. case Instructions::i32_lts.value():
  373. case Instructions::i32_ltu.value():
  374. case Instructions::i32_gts.value():
  375. case Instructions::i32_gtu.value():
  376. case Instructions::i32_les.value():
  377. case Instructions::i32_leu.value():
  378. case Instructions::i32_ges.value():
  379. case Instructions::i32_geu.value():
  380. case Instructions::i64_eqz.value():
  381. case Instructions::i64_eq.value():
  382. case Instructions::i64_ne.value():
  383. case Instructions::i64_lts.value():
  384. case Instructions::i64_ltu.value():
  385. case Instructions::i64_gts.value():
  386. case Instructions::i64_gtu.value():
  387. case Instructions::i64_les.value():
  388. case Instructions::i64_leu.value():
  389. case Instructions::i64_ges.value():
  390. case Instructions::i64_geu.value():
  391. case Instructions::f32_eq.value():
  392. case Instructions::f32_ne.value():
  393. case Instructions::f32_lt.value():
  394. case Instructions::f32_gt.value():
  395. case Instructions::f32_le.value():
  396. case Instructions::f32_ge.value():
  397. case Instructions::f64_eq.value():
  398. case Instructions::f64_ne.value():
  399. case Instructions::f64_lt.value():
  400. case Instructions::f64_gt.value():
  401. case Instructions::f64_le.value():
  402. case Instructions::f64_ge.value():
  403. case Instructions::i32_clz.value():
  404. case Instructions::i32_ctz.value():
  405. case Instructions::i32_popcnt.value():
  406. case Instructions::i32_add.value():
  407. case Instructions::i32_sub.value():
  408. case Instructions::i32_mul.value():
  409. case Instructions::i32_divs.value():
  410. case Instructions::i32_divu.value():
  411. case Instructions::i32_rems.value():
  412. case Instructions::i32_remu.value():
  413. case Instructions::i32_and.value():
  414. case Instructions::i32_or.value():
  415. case Instructions::i32_xor.value():
  416. case Instructions::i32_shl.value():
  417. case Instructions::i32_shrs.value():
  418. case Instructions::i32_shru.value():
  419. case Instructions::i32_rotl.value():
  420. case Instructions::i32_rotr.value():
  421. case Instructions::i64_clz.value():
  422. case Instructions::i64_ctz.value():
  423. case Instructions::i64_popcnt.value():
  424. case Instructions::i64_add.value():
  425. case Instructions::i64_sub.value():
  426. case Instructions::i64_mul.value():
  427. case Instructions::i64_divs.value():
  428. case Instructions::i64_divu.value():
  429. case Instructions::i64_rems.value():
  430. case Instructions::i64_remu.value():
  431. case Instructions::i64_and.value():
  432. case Instructions::i64_or.value():
  433. case Instructions::i64_xor.value():
  434. case Instructions::i64_shl.value():
  435. case Instructions::i64_shrs.value():
  436. case Instructions::i64_shru.value():
  437. case Instructions::i64_rotl.value():
  438. case Instructions::i64_rotr.value():
  439. case Instructions::f32_abs.value():
  440. case Instructions::f32_neg.value():
  441. case Instructions::f32_ceil.value():
  442. case Instructions::f32_floor.value():
  443. case Instructions::f32_trunc.value():
  444. case Instructions::f32_nearest.value():
  445. case Instructions::f32_sqrt.value():
  446. case Instructions::f32_add.value():
  447. case Instructions::f32_sub.value():
  448. case Instructions::f32_mul.value():
  449. case Instructions::f32_div.value():
  450. case Instructions::f32_min.value():
  451. case Instructions::f32_max.value():
  452. case Instructions::f32_copysign.value():
  453. case Instructions::f64_abs.value():
  454. case Instructions::f64_neg.value():
  455. case Instructions::f64_ceil.value():
  456. case Instructions::f64_floor.value():
  457. case Instructions::f64_trunc.value():
  458. case Instructions::f64_nearest.value():
  459. case Instructions::f64_sqrt.value():
  460. case Instructions::f64_add.value():
  461. case Instructions::f64_sub.value():
  462. case Instructions::f64_mul.value():
  463. case Instructions::f64_div.value():
  464. case Instructions::f64_min.value():
  465. case Instructions::f64_max.value():
  466. case Instructions::f64_copysign.value():
  467. case Instructions::i32_wrap_i64.value():
  468. case Instructions::i32_trunc_sf32.value():
  469. case Instructions::i32_trunc_uf32.value():
  470. case Instructions::i32_trunc_sf64.value():
  471. case Instructions::i32_trunc_uf64.value():
  472. case Instructions::i64_extend_si32.value():
  473. case Instructions::i64_extend_ui32.value():
  474. case Instructions::i64_trunc_sf32.value():
  475. case Instructions::i64_trunc_uf32.value():
  476. case Instructions::i64_trunc_sf64.value():
  477. case Instructions::i64_trunc_uf64.value():
  478. case Instructions::f32_convert_si32.value():
  479. case Instructions::f32_convert_ui32.value():
  480. case Instructions::f32_convert_si64.value():
  481. case Instructions::f32_convert_ui64.value():
  482. case Instructions::f32_demote_f64.value():
  483. case Instructions::f64_convert_si32.value():
  484. case Instructions::f64_convert_ui32.value():
  485. case Instructions::f64_convert_si64.value():
  486. case Instructions::f64_convert_ui64.value():
  487. case Instructions::f64_promote_f32.value():
  488. case Instructions::i32_reinterpret_f32.value():
  489. case Instructions::i64_reinterpret_f64.value():
  490. case Instructions::f32_reinterpret_i32.value():
  491. case Instructions::f64_reinterpret_i64.value():
  492. case Instructions::i32_extend8_s.value():
  493. case Instructions::i32_extend16_s.value():
  494. case Instructions::i64_extend8_s.value():
  495. case Instructions::i64_extend16_s.value():
  496. case Instructions::i64_extend32_s.value():
  497. return Instruction { opcode };
  498. case 0xfc:
  499. case 0xfd: {
  500. // These are multibyte instructions.
  501. auto selector_or_error = stream.read_value<LEB128<u32>>();
  502. if (selector_or_error.is_error())
  503. return with_eof_check(stream, ParseError::InvalidInput);
  504. u32 selector = selector_or_error.release_value();
  505. OpCode full_opcode = static_cast<u64>(opcode.value()) << 56 | selector;
  506. switch (full_opcode.value()) {
  507. case Instructions::i32_trunc_sat_f32_s.value():
  508. case Instructions::i32_trunc_sat_f32_u.value():
  509. case Instructions::i32_trunc_sat_f64_s.value():
  510. case Instructions::i32_trunc_sat_f64_u.value():
  511. case Instructions::i64_trunc_sat_f32_s.value():
  512. case Instructions::i64_trunc_sat_f32_u.value():
  513. case Instructions::i64_trunc_sat_f64_s.value():
  514. case Instructions::i64_trunc_sat_f64_u.value():
  515. return Instruction { full_opcode };
  516. case Instructions::memory_init.value(): {
  517. auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
  518. // Proposal "multi-memory", literal 0x00 is replaced with a memory index.
  519. auto memory_index_or_error = stream.read_value<u8>();
  520. if (memory_index_or_error.is_error())
  521. return with_eof_check(stream, ParseError::InvalidInput);
  522. auto memory_index = memory_index_or_error.release_value();
  523. return Instruction { full_opcode, MemoryInitArgs { index, MemoryIndex(memory_index) } };
  524. }
  525. case Instructions::data_drop.value(): {
  526. auto index = TRY(GenericIndexParser<DataIndex>::parse(stream));
  527. return Instruction { full_opcode, index };
  528. }
  529. case Instructions::memory_copy.value(): {
  530. // Proposal "multi-memory", literal 0x00 is replaced with two memory indices, destination and source, respectively.
  531. MemoryIndex indices[] = { 0, 0 };
  532. for (size_t i = 0; i < 2; ++i) {
  533. auto memory_index_or_error = stream.read_value<u8>();
  534. if (memory_index_or_error.is_error())
  535. return with_eof_check(stream, ParseError::InvalidInput);
  536. indices[i] = memory_index_or_error.release_value();
  537. }
  538. return Instruction { full_opcode, MemoryCopyArgs { indices[1], indices[0] } };
  539. }
  540. case Instructions::memory_fill.value(): {
  541. // Proposal "multi-memory", literal 0x00 is replaced with a memory index.
  542. auto memory_index_or_error = stream.read_value<u8>();
  543. if (memory_index_or_error.is_error())
  544. return with_eof_check(stream, ParseError::InvalidInput);
  545. auto memory_index = memory_index_or_error.release_value();
  546. return Instruction { full_opcode, MemoryIndexArgument { MemoryIndex { memory_index } } };
  547. }
  548. case Instructions::table_init.value(): {
  549. auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
  550. auto table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  551. return Instruction { full_opcode, TableElementArgs { element_index, table_index } };
  552. }
  553. case Instructions::elem_drop.value(): {
  554. auto element_index = TRY(GenericIndexParser<ElementIndex>::parse(stream));
  555. return Instruction { full_opcode, element_index };
  556. }
  557. case Instructions::table_copy.value(): {
  558. auto lhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
  559. auto rhs = TRY(GenericIndexParser<TableIndex>::parse(stream));
  560. return Instruction { full_opcode, TableTableArgs { lhs, rhs } };
  561. }
  562. case Instructions::table_grow.value():
  563. case Instructions::table_size.value():
  564. case Instructions::table_fill.value(): {
  565. auto index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  566. return Instruction { full_opcode, index };
  567. }
  568. case Instructions::v128_load.value():
  569. case Instructions::v128_load8x8_s.value():
  570. case Instructions::v128_load8x8_u.value():
  571. case Instructions::v128_load16x4_s.value():
  572. case Instructions::v128_load16x4_u.value():
  573. case Instructions::v128_load32x2_s.value():
  574. case Instructions::v128_load32x2_u.value():
  575. case Instructions::v128_load8_splat.value():
  576. case Instructions::v128_load16_splat.value():
  577. case Instructions::v128_load32_splat.value():
  578. case Instructions::v128_load64_splat.value():
  579. case Instructions::v128_load32_zero.value():
  580. case Instructions::v128_load64_zero.value():
  581. case Instructions::v128_store.value(): {
  582. // op (align [multi-memory memindex] offset)
  583. auto align_or_error = stream.read_value<LEB128<u32>>();
  584. if (align_or_error.is_error())
  585. return with_eof_check(stream, ParseError::ExpectedIndex);
  586. size_t align = align_or_error.release_value();
  587. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  588. size_t memory_index = 0;
  589. if ((align & 0x20) != 0) {
  590. align &= ~0x20;
  591. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  592. if (memory_index_or_error.is_error())
  593. return with_eof_check(stream, ParseError::InvalidInput);
  594. memory_index = memory_index_or_error.release_value();
  595. }
  596. auto offset_or_error = stream.read_value<LEB128<u32>>();
  597. if (offset_or_error.is_error())
  598. return with_eof_check(stream, ParseError::ExpectedIndex);
  599. size_t offset = offset_or_error.release_value();
  600. return Instruction { full_opcode, MemoryArgument { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) } };
  601. }
  602. case Instructions::v128_load8_lane.value():
  603. case Instructions::v128_load16_lane.value():
  604. case Instructions::v128_load32_lane.value():
  605. case Instructions::v128_load64_lane.value():
  606. case Instructions::v128_store8_lane.value():
  607. case Instructions::v128_store16_lane.value():
  608. case Instructions::v128_store32_lane.value():
  609. case Instructions::v128_store64_lane.value(): {
  610. // op (align [multi-memory: memindex] offset) (index)
  611. auto align_or_error = stream.read_value<LEB128<u32>>();
  612. if (align_or_error.is_error())
  613. return with_eof_check(stream, ParseError::ExpectedIndex);
  614. size_t align = align_or_error.release_value();
  615. // Proposal "multi-memory", if bit 6 of alignment is set, then a memory index follows the alignment.
  616. size_t memory_index = 0;
  617. if ((align & 0x20) != 0) {
  618. align &= ~0x20;
  619. auto memory_index_or_error = stream.read_value<LEB128<u32>>();
  620. if (memory_index_or_error.is_error())
  621. return with_eof_check(stream, ParseError::InvalidInput);
  622. memory_index = memory_index_or_error.release_value();
  623. }
  624. auto offset_or_error = stream.read_value<LEB128<u32>>();
  625. if (offset_or_error.is_error())
  626. return with_eof_check(stream, ParseError::ExpectedIndex);
  627. size_t offset = offset_or_error.release_value();
  628. auto index_or_error = stream.read_value<u8>();
  629. if (index_or_error.is_error())
  630. return with_eof_check(stream, ParseError::InvalidInput);
  631. auto index = index_or_error.release_value();
  632. return Instruction { full_opcode, MemoryAndLaneArgument { { static_cast<u32>(align), static_cast<u32>(offset), MemoryIndex(memory_index) }, index } };
  633. }
  634. case Instructions::v128_const.value(): {
  635. // op (literal:16)
  636. auto value_or_error = stream.read_value<LittleEndian<u128>>();
  637. if (value_or_error.is_error())
  638. return with_eof_check(stream, ParseError::InvalidImmediate);
  639. return Instruction { full_opcode, value_or_error.release_value() };
  640. }
  641. case Instructions::i8x16_shuffle.value(): {
  642. // op 16x(lane)
  643. u8 lanes[16];
  644. for (size_t i = 0; i < 16; ++i) {
  645. auto value_or_error = stream.read_value<u8>();
  646. if (value_or_error.is_error())
  647. return with_eof_check(stream, ParseError::InvalidInput);
  648. lanes[i] = value_or_error.release_value();
  649. }
  650. return Instruction { full_opcode, ShuffleArgument(lanes) };
  651. }
  652. case Instructions::i8x16_extract_lane_s.value():
  653. case Instructions::i8x16_extract_lane_u.value():
  654. case Instructions::i8x16_replace_lane.value():
  655. case Instructions::i16x8_extract_lane_s.value():
  656. case Instructions::i16x8_extract_lane_u.value():
  657. case Instructions::i16x8_replace_lane.value():
  658. case Instructions::i32x4_extract_lane.value():
  659. case Instructions::i32x4_replace_lane.value():
  660. case Instructions::i64x2_extract_lane.value():
  661. case Instructions::i64x2_replace_lane.value():
  662. case Instructions::f32x4_extract_lane.value():
  663. case Instructions::f32x4_replace_lane.value():
  664. case Instructions::f64x2_extract_lane.value():
  665. case Instructions::f64x2_replace_lane.value(): {
  666. // op (lane)
  667. auto lane_or_error = stream.read_value<u8>();
  668. if (lane_or_error.is_error())
  669. return with_eof_check(stream, ParseError::InvalidInput);
  670. auto lane = lane_or_error.release_value();
  671. return Instruction { full_opcode, LaneIndex { lane } };
  672. }
  673. case Instructions::i8x16_swizzle.value():
  674. case Instructions::i8x16_splat.value():
  675. case Instructions::i16x8_splat.value():
  676. case Instructions::i32x4_splat.value():
  677. case Instructions::i64x2_splat.value():
  678. case Instructions::f32x4_splat.value():
  679. case Instructions::f64x2_splat.value():
  680. case Instructions::i8x16_eq.value():
  681. case Instructions::i8x16_ne.value():
  682. case Instructions::i8x16_lt_s.value():
  683. case Instructions::i8x16_lt_u.value():
  684. case Instructions::i8x16_gt_s.value():
  685. case Instructions::i8x16_gt_u.value():
  686. case Instructions::i8x16_le_s.value():
  687. case Instructions::i8x16_le_u.value():
  688. case Instructions::i8x16_ge_s.value():
  689. case Instructions::i8x16_ge_u.value():
  690. case Instructions::i16x8_eq.value():
  691. case Instructions::i16x8_ne.value():
  692. case Instructions::i16x8_lt_s.value():
  693. case Instructions::i16x8_lt_u.value():
  694. case Instructions::i16x8_gt_s.value():
  695. case Instructions::i16x8_gt_u.value():
  696. case Instructions::i16x8_le_s.value():
  697. case Instructions::i16x8_le_u.value():
  698. case Instructions::i16x8_ge_s.value():
  699. case Instructions::i16x8_ge_u.value():
  700. case Instructions::i32x4_eq.value():
  701. case Instructions::i32x4_ne.value():
  702. case Instructions::i32x4_lt_s.value():
  703. case Instructions::i32x4_lt_u.value():
  704. case Instructions::i32x4_gt_s.value():
  705. case Instructions::i32x4_gt_u.value():
  706. case Instructions::i32x4_le_s.value():
  707. case Instructions::i32x4_le_u.value():
  708. case Instructions::i32x4_ge_s.value():
  709. case Instructions::i32x4_ge_u.value():
  710. case Instructions::f32x4_eq.value():
  711. case Instructions::f32x4_ne.value():
  712. case Instructions::f32x4_lt.value():
  713. case Instructions::f32x4_gt.value():
  714. case Instructions::f32x4_le.value():
  715. case Instructions::f32x4_ge.value():
  716. case Instructions::f64x2_eq.value():
  717. case Instructions::f64x2_ne.value():
  718. case Instructions::f64x2_lt.value():
  719. case Instructions::f64x2_gt.value():
  720. case Instructions::f64x2_le.value():
  721. case Instructions::f64x2_ge.value():
  722. case Instructions::v128_not.value():
  723. case Instructions::v128_and.value():
  724. case Instructions::v128_andnot.value():
  725. case Instructions::v128_or.value():
  726. case Instructions::v128_xor.value():
  727. case Instructions::v128_bitselect.value():
  728. case Instructions::v128_any_true.value():
  729. case Instructions::f32x4_demote_f64x2_zero.value():
  730. case Instructions::f64x2_promote_low_f32x4.value():
  731. case Instructions::i8x16_abs.value():
  732. case Instructions::i8x16_neg.value():
  733. case Instructions::i8x16_popcnt.value():
  734. case Instructions::i8x16_all_true.value():
  735. case Instructions::i8x16_bitmask.value():
  736. case Instructions::i8x16_narrow_i16x8_s.value():
  737. case Instructions::i8x16_narrow_i16x8_u.value():
  738. case Instructions::f32x4_ceil.value():
  739. case Instructions::f32x4_floor.value():
  740. case Instructions::f32x4_trunc.value():
  741. case Instructions::f32x4_nearest.value():
  742. case Instructions::i8x16_shl.value():
  743. case Instructions::i8x16_shr_s.value():
  744. case Instructions::i8x16_shr_u.value():
  745. case Instructions::i8x16_add.value():
  746. case Instructions::i8x16_add_sat_s.value():
  747. case Instructions::i8x16_add_sat_u.value():
  748. case Instructions::i8x16_sub.value():
  749. case Instructions::i8x16_sub_sat_s.value():
  750. case Instructions::i8x16_sub_sat_u.value():
  751. case Instructions::f64x2_ceil.value():
  752. case Instructions::f64x2_floor.value():
  753. case Instructions::i8x16_min_s.value():
  754. case Instructions::i8x16_min_u.value():
  755. case Instructions::i8x16_max_s.value():
  756. case Instructions::i8x16_max_u.value():
  757. case Instructions::f64x2_trunc.value():
  758. case Instructions::i8x16_avgr_u.value():
  759. case Instructions::i16x8_extadd_pairwise_i8x16_s.value():
  760. case Instructions::i16x8_extadd_pairwise_i8x16_u.value():
  761. case Instructions::i32x4_extadd_pairwise_i16x8_s.value():
  762. case Instructions::i32x4_extadd_pairwise_i16x8_u.value():
  763. case Instructions::i16x8_abs.value():
  764. case Instructions::i16x8_neg.value():
  765. case Instructions::i16x8_q15mulr_sat_s.value():
  766. case Instructions::i16x8_all_true.value():
  767. case Instructions::i16x8_bitmask.value():
  768. case Instructions::i16x8_narrow_i32x4_s.value():
  769. case Instructions::i16x8_narrow_i32x4_u.value():
  770. case Instructions::i16x8_extend_low_i8x16_s.value():
  771. case Instructions::i16x8_extend_high_i8x16_s.value():
  772. case Instructions::i16x8_extend_low_i8x16_u.value():
  773. case Instructions::i16x8_extend_high_i8x16_u.value():
  774. case Instructions::i16x8_shl.value():
  775. case Instructions::i16x8_shr_s.value():
  776. case Instructions::i16x8_shr_u.value():
  777. case Instructions::i16x8_add.value():
  778. case Instructions::i16x8_add_sat_s.value():
  779. case Instructions::i16x8_add_sat_u.value():
  780. case Instructions::i16x8_sub.value():
  781. case Instructions::i16x8_sub_sat_s.value():
  782. case Instructions::i16x8_sub_sat_u.value():
  783. case Instructions::f64x2_nearest.value():
  784. case Instructions::i16x8_mul.value():
  785. case Instructions::i16x8_min_s.value():
  786. case Instructions::i16x8_min_u.value():
  787. case Instructions::i16x8_max_s.value():
  788. case Instructions::i16x8_max_u.value():
  789. case Instructions::i16x8_avgr_u.value():
  790. case Instructions::i16x8_extmul_low_i8x16_s.value():
  791. case Instructions::i16x8_extmul_high_i8x16_s.value():
  792. case Instructions::i16x8_extmul_low_i8x16_u.value():
  793. case Instructions::i16x8_extmul_high_i8x16_u.value():
  794. case Instructions::i32x4_abs.value():
  795. case Instructions::i32x4_neg.value():
  796. case Instructions::i32x4_all_true.value():
  797. case Instructions::i32x4_bitmask.value():
  798. case Instructions::i32x4_extend_low_i16x8_s.value():
  799. case Instructions::i32x4_extend_high_i16x8_s.value():
  800. case Instructions::i32x4_extend_low_i16x8_u.value():
  801. case Instructions::i32x4_extend_high_i16x8_u.value():
  802. case Instructions::i32x4_shl.value():
  803. case Instructions::i32x4_shr_s.value():
  804. case Instructions::i32x4_shr_u.value():
  805. case Instructions::i32x4_add.value():
  806. case Instructions::i32x4_sub.value():
  807. case Instructions::i32x4_mul.value():
  808. case Instructions::i32x4_min_s.value():
  809. case Instructions::i32x4_min_u.value():
  810. case Instructions::i32x4_max_s.value():
  811. case Instructions::i32x4_max_u.value():
  812. case Instructions::i32x4_dot_i16x8_s.value():
  813. case Instructions::i32x4_extmul_low_i16x8_s.value():
  814. case Instructions::i32x4_extmul_high_i16x8_s.value():
  815. case Instructions::i32x4_extmul_low_i16x8_u.value():
  816. case Instructions::i32x4_extmul_high_i16x8_u.value():
  817. case Instructions::i64x2_abs.value():
  818. case Instructions::i64x2_neg.value():
  819. case Instructions::i64x2_all_true.value():
  820. case Instructions::i64x2_bitmask.value():
  821. case Instructions::i64x2_extend_low_i32x4_s.value():
  822. case Instructions::i64x2_extend_high_i32x4_s.value():
  823. case Instructions::i64x2_extend_low_i32x4_u.value():
  824. case Instructions::i64x2_extend_high_i32x4_u.value():
  825. case Instructions::i64x2_shl.value():
  826. case Instructions::i64x2_shr_s.value():
  827. case Instructions::i64x2_shr_u.value():
  828. case Instructions::i64x2_add.value():
  829. case Instructions::i64x2_sub.value():
  830. case Instructions::i64x2_mul.value():
  831. case Instructions::i64x2_eq.value():
  832. case Instructions::i64x2_ne.value():
  833. case Instructions::i64x2_lt_s.value():
  834. case Instructions::i64x2_gt_s.value():
  835. case Instructions::i64x2_le_s.value():
  836. case Instructions::i64x2_ge_s.value():
  837. case Instructions::i64x2_extmul_low_i32x4_s.value():
  838. case Instructions::i64x2_extmul_high_i32x4_s.value():
  839. case Instructions::i64x2_extmul_low_i32x4_u.value():
  840. case Instructions::i64x2_extmul_high_i32x4_u.value():
  841. case Instructions::f32x4_abs.value():
  842. case Instructions::f32x4_neg.value():
  843. case Instructions::f32x4_sqrt.value():
  844. case Instructions::f32x4_add.value():
  845. case Instructions::f32x4_sub.value():
  846. case Instructions::f32x4_mul.value():
  847. case Instructions::f32x4_div.value():
  848. case Instructions::f32x4_min.value():
  849. case Instructions::f32x4_max.value():
  850. case Instructions::f32x4_pmin.value():
  851. case Instructions::f32x4_pmax.value():
  852. case Instructions::f64x2_abs.value():
  853. case Instructions::f64x2_neg.value():
  854. case Instructions::f64x2_sqrt.value():
  855. case Instructions::f64x2_add.value():
  856. case Instructions::f64x2_sub.value():
  857. case Instructions::f64x2_mul.value():
  858. case Instructions::f64x2_div.value():
  859. case Instructions::f64x2_min.value():
  860. case Instructions::f64x2_max.value():
  861. case Instructions::f64x2_pmin.value():
  862. case Instructions::f64x2_pmax.value():
  863. case Instructions::i32x4_trunc_sat_f32x4_s.value():
  864. case Instructions::i32x4_trunc_sat_f32x4_u.value():
  865. case Instructions::f32x4_convert_i32x4_s.value():
  866. case Instructions::f32x4_convert_i32x4_u.value():
  867. case Instructions::i32x4_trunc_sat_f64x2_s_zero.value():
  868. case Instructions::i32x4_trunc_sat_f64x2_u_zero.value():
  869. case Instructions::f64x2_convert_low_i32x4_s.value():
  870. case Instructions::f64x2_convert_low_i32x4_u.value():
  871. // op
  872. return Instruction { full_opcode };
  873. default:
  874. return ParseError::UnknownInstruction;
  875. }
  876. }
  877. }
  878. return ParseError::UnknownInstruction;
  879. }
  880. ParseResult<CustomSection> CustomSection::parse(Stream& stream)
  881. {
  882. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CustomSection"sv);
  883. auto name = TRY(parse_name(stream));
  884. ByteBuffer data_buffer;
  885. if (data_buffer.try_resize(64).is_error())
  886. return ParseError::OutOfMemory;
  887. while (!stream.is_eof()) {
  888. char buf[16];
  889. auto span_or_error = stream.read_some({ buf, 16 });
  890. if (span_or_error.is_error())
  891. break;
  892. auto size = span_or_error.release_value().size();
  893. if (size == 0)
  894. break;
  895. if (data_buffer.try_append(buf, size).is_error())
  896. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  897. }
  898. return CustomSection(name, move(data_buffer));
  899. }
  900. ParseResult<TypeSection> TypeSection::parse(Stream& stream)
  901. {
  902. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TypeSection"sv);
  903. auto types = TRY(parse_vector<FunctionType>(stream));
  904. return TypeSection { types };
  905. }
  906. ParseResult<ImportSection::Import> ImportSection::Import::parse(Stream& stream)
  907. {
  908. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Import"sv);
  909. auto module = TRY(parse_name(stream));
  910. auto name = TRY(parse_name(stream));
  911. auto tag_or_error = stream.read_value<u8>();
  912. if (tag_or_error.is_error())
  913. return with_eof_check(stream, ParseError::ExpectedKindTag);
  914. auto tag = tag_or_error.release_value();
  915. switch (tag) {
  916. case Constants::extern_function_tag: {
  917. auto index = TRY(GenericIndexParser<TypeIndex>::parse(stream));
  918. return Import { module, name, index };
  919. }
  920. case Constants::extern_table_tag:
  921. return parse_with_type<TableType>(stream, module, name);
  922. case Constants::extern_memory_tag:
  923. return parse_with_type<MemoryType>(stream, module, name);
  924. case Constants::extern_global_tag:
  925. return parse_with_type<GlobalType>(stream, module, name);
  926. default:
  927. return with_eof_check(stream, ParseError::InvalidTag);
  928. }
  929. }
  930. ParseResult<ImportSection> ImportSection::parse(Stream& stream)
  931. {
  932. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ImportSection"sv);
  933. auto imports = TRY(parse_vector<Import>(stream));
  934. return ImportSection { imports };
  935. }
  936. ParseResult<FunctionSection> FunctionSection::parse(Stream& stream)
  937. {
  938. ScopeLogger<WASM_BINPARSER_DEBUG> logger("FunctionSection"sv);
  939. auto indices = TRY(parse_vector<u32>(stream));
  940. Vector<TypeIndex> typed_indices;
  941. typed_indices.ensure_capacity(indices.size());
  942. for (auto entry : indices)
  943. typed_indices.append(entry);
  944. return FunctionSection { move(typed_indices) };
  945. }
  946. ParseResult<TableSection::Table> TableSection::Table::parse(Stream& stream)
  947. {
  948. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Table"sv);
  949. auto type = TRY(TableType::parse(stream));
  950. return Table { type };
  951. }
  952. ParseResult<TableSection> TableSection::parse(Stream& stream)
  953. {
  954. ScopeLogger<WASM_BINPARSER_DEBUG> logger("TableSection"sv);
  955. auto tables = TRY(parse_vector<Table>(stream));
  956. return TableSection { tables };
  957. }
  958. ParseResult<MemorySection::Memory> MemorySection::Memory::parse(Stream& stream)
  959. {
  960. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Memory"sv);
  961. auto type = TRY(MemoryType::parse(stream));
  962. return Memory { type };
  963. }
  964. ParseResult<MemorySection> MemorySection::parse(Stream& stream)
  965. {
  966. ScopeLogger<WASM_BINPARSER_DEBUG> logger("MemorySection"sv);
  967. auto memories = TRY(parse_vector<Memory>(stream));
  968. return MemorySection { memories };
  969. }
  970. ParseResult<Expression> Expression::parse(Stream& stream, Optional<size_t> size_hint)
  971. {
  972. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Expression"sv);
  973. InstructionPointer ip { 0 };
  974. Vector<InstructionPointer> stack;
  975. Vector<Instruction> instructions;
  976. if (size_hint.has_value())
  977. instructions.ensure_capacity(size_hint.release_value());
  978. while (true) {
  979. auto instruction = TRY(Instruction::parse(stream));
  980. switch (instruction.opcode().value()) {
  981. case Instructions::block.value():
  982. case Instructions::loop.value():
  983. case Instructions::if_.value():
  984. stack.append(ip);
  985. break;
  986. case Instructions::structured_end.value(): {
  987. if (stack.is_empty())
  988. return Expression { move(instructions) };
  989. auto entry = stack.take_last();
  990. auto& args = instructions[entry.value()].arguments().get<Instruction::StructuredInstructionArgs>();
  991. // Patch the end_ip of the last structured instruction
  992. args.end_ip = ip + (args.else_ip.has_value() ? 1 : 0);
  993. break;
  994. }
  995. case Instructions::structured_else.value(): {
  996. if (stack.is_empty())
  997. return ParseError::UnknownInstruction;
  998. auto entry = stack.last();
  999. auto& args = instructions[entry.value()].arguments().get<Instruction::StructuredInstructionArgs>();
  1000. args.else_ip = ip + 1;
  1001. break;
  1002. }
  1003. }
  1004. instructions.append(move(instruction));
  1005. ++ip;
  1006. }
  1007. return Expression { move(instructions) };
  1008. }
  1009. ParseResult<GlobalSection::Global> GlobalSection::Global::parse(Stream& stream)
  1010. {
  1011. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Global"sv);
  1012. auto type = TRY(GlobalType::parse(stream));
  1013. auto exprs = TRY(Expression::parse(stream));
  1014. return Global { type, exprs };
  1015. }
  1016. ParseResult<GlobalSection> GlobalSection::parse(Stream& stream)
  1017. {
  1018. ScopeLogger<WASM_BINPARSER_DEBUG> logger("GlobalSection"sv);
  1019. auto result = TRY(parse_vector<Global>(stream));
  1020. return GlobalSection { result };
  1021. }
  1022. ParseResult<ExportSection::Export> ExportSection::Export::parse(Stream& stream)
  1023. {
  1024. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Export"sv);
  1025. auto name = TRY(parse_name(stream));
  1026. auto tag_or_error = stream.read_value<u8>();
  1027. if (tag_or_error.is_error())
  1028. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1029. auto tag = tag_or_error.release_value();
  1030. auto index_or_error = stream.read_value<LEB128<u32>>();
  1031. if (index_or_error.is_error())
  1032. return with_eof_check(stream, ParseError::ExpectedIndex);
  1033. size_t index = index_or_error.release_value();
  1034. switch (tag) {
  1035. case Constants::extern_function_tag:
  1036. return Export { name, ExportDesc { FunctionIndex { index } } };
  1037. case Constants::extern_table_tag:
  1038. return Export { name, ExportDesc { TableIndex { index } } };
  1039. case Constants::extern_memory_tag:
  1040. return Export { name, ExportDesc { MemoryIndex { index } } };
  1041. case Constants::extern_global_tag:
  1042. return Export { name, ExportDesc { GlobalIndex { index } } };
  1043. default:
  1044. return with_eof_check(stream, ParseError::InvalidTag);
  1045. }
  1046. }
  1047. ParseResult<ExportSection> ExportSection::parse(Stream& stream)
  1048. {
  1049. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ExportSection"sv);
  1050. auto result = TRY(parse_vector<Export>(stream));
  1051. return ExportSection { result };
  1052. }
  1053. ParseResult<StartSection::StartFunction> StartSection::StartFunction::parse(Stream& stream)
  1054. {
  1055. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartFunction"sv);
  1056. auto index = TRY(GenericIndexParser<FunctionIndex>::parse(stream));
  1057. return StartFunction { index };
  1058. }
  1059. ParseResult<StartSection> StartSection::parse(Stream& stream)
  1060. {
  1061. ScopeLogger<WASM_BINPARSER_DEBUG> logger("StartSection"sv);
  1062. auto result = TRY(StartFunction::parse(stream));
  1063. return StartSection { result };
  1064. }
  1065. ParseResult<ElementSection::Element> ElementSection::Element::parse(Stream& stream)
  1066. {
  1067. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Element"sv);
  1068. auto tag_or_error = stream.read_value<LEB128<u32>>();
  1069. if (tag_or_error.is_error())
  1070. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1071. auto tag = tag_or_error.release_value();
  1072. if (tag > 0x07)
  1073. return ParseError::InvalidTag;
  1074. auto has_passive = (tag & 0x01) != 0;
  1075. auto has_explicit_index = (tag & 0x02) != 0;
  1076. auto has_exprs = (tag & 0x04) != 0;
  1077. Variant<Active, Passive, Declarative> mode = Passive {};
  1078. if (has_passive) {
  1079. if (has_explicit_index) {
  1080. mode = Declarative {};
  1081. } else {
  1082. mode = Passive {};
  1083. }
  1084. } else {
  1085. TableIndex table_index = 0;
  1086. if (has_explicit_index)
  1087. table_index = TRY(GenericIndexParser<TableIndex>::parse(stream));
  1088. auto expression = TRY(Expression::parse(stream));
  1089. mode = Active { table_index, expression };
  1090. }
  1091. auto type = ValueType(ValueType::FunctionReference);
  1092. if (has_passive || has_explicit_index) {
  1093. if (has_exprs) {
  1094. type = TRY(ValueType::parse(stream));
  1095. } else {
  1096. auto extern_or_error = stream.read_value<u8>();
  1097. if (extern_or_error.is_error())
  1098. return with_eof_check(stream, ParseError::InvalidType);
  1099. // Make sure that this is a function, as it's technically only the
  1100. // allowed one.
  1101. if (extern_or_error.release_value() != 0x00) {
  1102. return ParseError::InvalidType;
  1103. }
  1104. type = ValueType(ValueType::FunctionReference);
  1105. }
  1106. }
  1107. Vector<Expression> items;
  1108. if (!has_exprs) {
  1109. auto indices = TRY(parse_vector<GenericIndexParser<FunctionIndex>>(stream));
  1110. for (auto& index : indices) {
  1111. Vector<Instruction> instructions { Instruction(Instructions::ref_func, index) };
  1112. items.empend(move(instructions));
  1113. }
  1114. } else {
  1115. items = TRY(parse_vector<Expression>(stream));
  1116. }
  1117. return Element { type, move(items), move(mode) };
  1118. }
  1119. ParseResult<ElementSection> ElementSection::parse(Stream& stream)
  1120. {
  1121. ScopeLogger<WASM_BINPARSER_DEBUG> logger("ElementSection"sv);
  1122. auto result = TRY(parse_vector<Element>(stream));
  1123. return ElementSection { result };
  1124. }
  1125. ParseResult<Locals> Locals::parse(Stream& stream)
  1126. {
  1127. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Locals"sv);
  1128. auto count_or_error = stream.read_value<LEB128<u32>>();
  1129. if (count_or_error.is_error())
  1130. return with_eof_check(stream, ParseError::InvalidSize);
  1131. size_t count = count_or_error.release_value();
  1132. if (count > Constants::max_allowed_function_locals_per_type)
  1133. return with_eof_check(stream, ParseError::HugeAllocationRequested);
  1134. auto type = TRY(ValueType::parse(stream));
  1135. return Locals { static_cast<u32>(count), type };
  1136. }
  1137. ParseResult<CodeSection::Func> CodeSection::Func::parse(Stream& stream, size_t size_hint)
  1138. {
  1139. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Func"sv);
  1140. auto locals = TRY(parse_vector<Locals>(stream));
  1141. auto body = TRY(Expression::parse(stream, size_hint));
  1142. return Func { move(locals), move(body) };
  1143. }
  1144. ParseResult<CodeSection::Code> CodeSection::Code::parse(Stream& stream)
  1145. {
  1146. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Code"sv);
  1147. auto size_or_error = stream.read_value<LEB128<u32>>();
  1148. if (size_or_error.is_error())
  1149. return with_eof_check(stream, ParseError::InvalidSize);
  1150. size_t size = size_or_error.release_value();
  1151. // Emprically, if there are `size` bytes to be read, then there's around
  1152. // `size / 2` instructions, so we pass that as our size hint.
  1153. auto func = TRY(Func::parse(stream, size / 2));
  1154. return Code { static_cast<u32>(size), move(func) };
  1155. }
  1156. ParseResult<CodeSection> CodeSection::parse(Stream& stream)
  1157. {
  1158. ScopeLogger<WASM_BINPARSER_DEBUG> logger("CodeSection"sv);
  1159. auto result = TRY(parse_vector<Code>(stream));
  1160. return CodeSection { move(result) };
  1161. }
  1162. ParseResult<DataSection::Data> DataSection::Data::parse(Stream& stream)
  1163. {
  1164. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Data"sv);
  1165. auto tag_or_error = stream.read_value<LEB128<u32>>();
  1166. if (tag_or_error.is_error())
  1167. return with_eof_check(stream, ParseError::ExpectedKindTag);
  1168. auto tag = tag_or_error.release_value();
  1169. if (tag > 0x02)
  1170. return with_eof_check(stream, ParseError::InvalidTag);
  1171. if (tag == 0x00) {
  1172. auto expr = TRY(Expression::parse(stream));
  1173. auto init = TRY(parse_vector<u8>(stream));
  1174. return Data { Active { init, { 0 }, expr } };
  1175. }
  1176. if (tag == 0x01) {
  1177. auto init = TRY(parse_vector<u8>(stream));
  1178. return Data { Passive { init } };
  1179. }
  1180. if (tag == 0x02) {
  1181. auto index = TRY(GenericIndexParser<MemoryIndex>::parse(stream));
  1182. auto expr = TRY(Expression::parse(stream));
  1183. auto init = TRY(parse_vector<u8>(stream));
  1184. return Data { Active { init, index, expr } };
  1185. }
  1186. VERIFY_NOT_REACHED();
  1187. }
  1188. ParseResult<DataSection> DataSection::parse(Stream& stream)
  1189. {
  1190. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataSection"sv);
  1191. auto data = TRY(parse_vector<Data>(stream));
  1192. return DataSection { data };
  1193. }
  1194. ParseResult<DataCountSection> DataCountSection::parse([[maybe_unused]] Stream& stream)
  1195. {
  1196. ScopeLogger<WASM_BINPARSER_DEBUG> logger("DataCountSection"sv);
  1197. auto value_or_error = stream.read_value<LEB128<u32>>();
  1198. if (value_or_error.is_error()) {
  1199. if (stream.is_eof()) {
  1200. // The section simply didn't contain anything.
  1201. return DataCountSection { {} };
  1202. }
  1203. return ParseError::ExpectedSize;
  1204. }
  1205. u32 value = value_or_error.release_value();
  1206. return DataCountSection { value };
  1207. }
  1208. ParseResult<Module> Module::parse(Stream& stream)
  1209. {
  1210. ScopeLogger<WASM_BINPARSER_DEBUG> logger("Module"sv);
  1211. u8 buf[4];
  1212. if (stream.read_until_filled({ buf, 4 }).is_error())
  1213. return with_eof_check(stream, ParseError::InvalidInput);
  1214. if (Bytes { buf, 4 } != wasm_magic.span())
  1215. return with_eof_check(stream, ParseError::InvalidModuleMagic);
  1216. if (stream.read_until_filled({ buf, 4 }).is_error())
  1217. return with_eof_check(stream, ParseError::InvalidInput);
  1218. if (Bytes { buf, 4 } != wasm_version.span())
  1219. return with_eof_check(stream, ParseError::InvalidModuleVersion);
  1220. Vector<AnySection> sections;
  1221. while (!stream.is_eof()) {
  1222. auto section_id_or_error = stream.read_value<u8>();
  1223. if (section_id_or_error.is_error())
  1224. return with_eof_check(stream, ParseError::ExpectedIndex);
  1225. auto section_id = section_id_or_error.release_value();
  1226. auto section_size_or_error = stream.read_value<LEB128<u32>>();
  1227. if (section_size_or_error.is_error())
  1228. return with_eof_check(stream, ParseError::ExpectedSize);
  1229. size_t section_size = section_size_or_error.release_value();
  1230. auto section_stream = ConstrainedStream { MaybeOwned<Stream>(stream), section_size };
  1231. switch (section_id) {
  1232. case CustomSection::section_id:
  1233. sections.append(TRY(CustomSection::parse(section_stream)));
  1234. break;
  1235. case TypeSection::section_id:
  1236. sections.append(TRY(TypeSection::parse(section_stream)));
  1237. break;
  1238. case ImportSection::section_id:
  1239. sections.append(TRY(ImportSection::parse(section_stream)));
  1240. break;
  1241. case FunctionSection::section_id:
  1242. sections.append(TRY(FunctionSection::parse(section_stream)));
  1243. break;
  1244. case TableSection::section_id:
  1245. sections.append(TRY(TableSection::parse(section_stream)));
  1246. break;
  1247. case MemorySection::section_id:
  1248. sections.append(TRY(MemorySection::parse(section_stream)));
  1249. break;
  1250. case GlobalSection::section_id:
  1251. sections.append(TRY(GlobalSection::parse(section_stream)));
  1252. break;
  1253. case ExportSection::section_id:
  1254. sections.append(TRY(ExportSection::parse(section_stream)));
  1255. break;
  1256. case StartSection::section_id:
  1257. sections.append(TRY(StartSection::parse(section_stream)));
  1258. break;
  1259. case ElementSection::section_id:
  1260. sections.append(TRY(ElementSection::parse(section_stream)));
  1261. break;
  1262. case CodeSection::section_id:
  1263. sections.append(TRY(CodeSection::parse(section_stream)));
  1264. break;
  1265. case DataSection::section_id:
  1266. sections.append(TRY(DataSection::parse(section_stream)));
  1267. break;
  1268. case DataCountSection::section_id:
  1269. sections.append(TRY(DataCountSection::parse(section_stream)));
  1270. break;
  1271. default:
  1272. return with_eof_check(stream, ParseError::InvalidIndex);
  1273. }
  1274. if (section_stream.remaining() != 0)
  1275. return ParseError::SectionSizeMismatch;
  1276. }
  1277. return Module { move(sections) };
  1278. }
  1279. ByteString parse_error_to_byte_string(ParseError error)
  1280. {
  1281. switch (error) {
  1282. case ParseError::UnexpectedEof:
  1283. return "Unexpected end-of-file";
  1284. case ParseError::ExpectedIndex:
  1285. return "Expected a valid index value";
  1286. case ParseError::ExpectedKindTag:
  1287. return "Expected a valid kind tag";
  1288. case ParseError::ExpectedSize:
  1289. return "Expected a valid LEB128-encoded size";
  1290. case ParseError::ExpectedValueOrTerminator:
  1291. return "Expected either a terminator or a value";
  1292. case ParseError::InvalidIndex:
  1293. return "An index parsed was semantically invalid";
  1294. case ParseError::InvalidInput:
  1295. return "Input data contained invalid bytes";
  1296. case ParseError::InvalidModuleMagic:
  1297. return "Incorrect module magic (did not match \\0asm)";
  1298. case ParseError::InvalidModuleVersion:
  1299. return "Incorrect module version";
  1300. case ParseError::InvalidSize:
  1301. return "A parsed size did not make sense in context";
  1302. case ParseError::InvalidTag:
  1303. return "A parsed tag did not make sense in context";
  1304. case ParseError::InvalidType:
  1305. return "A parsed type did not make sense in context";
  1306. case ParseError::NotImplemented:
  1307. return "The parser encountered an unimplemented feature";
  1308. case ParseError::HugeAllocationRequested:
  1309. return "Parsing caused an attempt to allocate a very big chunk of memory, likely malformed data";
  1310. case ParseError::OutOfMemory:
  1311. return "The parser hit an OOM condition";
  1312. case ParseError::ExpectedFloatingImmediate:
  1313. return "Expected a floating point immediate";
  1314. case ParseError::ExpectedSignedImmediate:
  1315. return "Expected a signed integer immediate";
  1316. case ParseError::InvalidImmediate:
  1317. return "A parsed instruction immediate was invalid for the instruction it was used for";
  1318. case ParseError::SectionSizeMismatch:
  1319. return "A parsed section did not fulfill its expected size";
  1320. case ParseError::InvalidUtf8:
  1321. return "A parsed string was not valid UTF-8";
  1322. case ParseError::UnknownInstruction:
  1323. return "A parsed instruction was not known to this parser";
  1324. }
  1325. return "Unknown error";
  1326. }
  1327. }