Types.h 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Badge.h>
  8. #include <AK/ByteString.h>
  9. #include <AK/DistinctNumeric.h>
  10. #include <AK/LEB128.h>
  11. #include <AK/Result.h>
  12. #include <AK/String.h>
  13. #include <AK/UFixedBigInt.h>
  14. #include <AK/Variant.h>
  15. #include <LibWasm/Constants.h>
  16. #include <LibWasm/Forward.h>
  17. #include <LibWasm/Opcode.h>
  18. namespace Wasm {
  19. template<size_t M>
  20. using NativeIntegralType = Conditional<M == 8, u8, Conditional<M == 16, u16, Conditional<M == 32, u32, Conditional<M == 64, u64, void>>>>;
  21. template<size_t M>
  22. using NativeFloatingType = Conditional<M == 32, f32, Conditional<M == 64, f64, void>>;
  23. template<size_t M, size_t N, template<typename> typename SetSign, typename ElementType = SetSign<NativeIntegralType<M>>>
  24. using NativeVectorType __attribute__((vector_size(N * sizeof(ElementType)))) = ElementType;
  25. template<size_t M, size_t N, typename ElementType = NativeFloatingType<M>>
  26. using NativeFloatingVectorType __attribute__((vector_size(N * sizeof(ElementType)))) = ElementType;
  27. template<typename T, template<typename> typename SetSign>
  28. using Native128ByteVectorOf = NativeVectorType<sizeof(T) * 8, 16 / sizeof(T), SetSign, T>;
  29. enum class ParseError {
  30. UnexpectedEof,
  31. UnknownInstruction,
  32. ExpectedFloatingImmediate,
  33. ExpectedIndex,
  34. ExpectedKindTag,
  35. ExpectedSignedImmediate,
  36. ExpectedSize,
  37. ExpectedValueOrTerminator,
  38. InvalidImmediate,
  39. InvalidIndex,
  40. InvalidInput,
  41. InvalidModuleMagic,
  42. InvalidModuleVersion,
  43. InvalidSize,
  44. InvalidTag,
  45. InvalidType,
  46. HugeAllocationRequested,
  47. OutOfMemory,
  48. SectionSizeMismatch,
  49. InvalidUtf8,
  50. // FIXME: This should not exist!
  51. NotImplemented,
  52. };
  53. ByteString parse_error_to_byte_string(ParseError);
  54. template<typename T>
  55. using ParseResult = ErrorOr<T, ParseError>;
  56. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, TypeIndex);
  57. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, FunctionIndex);
  58. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, TableIndex);
  59. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, ElementIndex);
  60. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, MemoryIndex);
  61. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, LocalIndex);
  62. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, GlobalIndex);
  63. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, LabelIndex);
  64. AK_TYPEDEF_DISTINCT_ORDERED_ID(size_t, DataIndex);
  65. AK_TYPEDEF_DISTINCT_NUMERIC_GENERAL(u64, InstructionPointer, Arithmetic, Comparison, Flags, Increment);
  66. ParseError with_eof_check(Stream const& stream, ParseError error_if_not_eof);
  67. template<typename T>
  68. struct GenericIndexParser {
  69. static ParseResult<T> parse(Stream& stream)
  70. {
  71. auto value_or_error = stream.read_value<LEB128<u32>>();
  72. if (value_or_error.is_error())
  73. return with_eof_check(stream, ParseError::ExpectedIndex);
  74. size_t value = value_or_error.release_value();
  75. return T { value };
  76. }
  77. };
  78. class ReconsumableStream : public Stream {
  79. public:
  80. explicit ReconsumableStream(Stream& stream)
  81. : m_stream(stream)
  82. {
  83. }
  84. void unread(ReadonlyBytes data) { m_buffer.append(data.data(), data.size()); }
  85. private:
  86. virtual ErrorOr<Bytes> read_some(Bytes bytes) override
  87. {
  88. auto original_bytes = bytes;
  89. size_t bytes_read_from_buffer = 0;
  90. if (!m_buffer.is_empty()) {
  91. auto read_size = min(bytes.size(), m_buffer.size());
  92. m_buffer.span().slice(0, read_size).copy_to(bytes);
  93. bytes = bytes.slice(read_size);
  94. for (size_t i = 0; i < read_size; ++i)
  95. m_buffer.take_first();
  96. bytes_read_from_buffer = read_size;
  97. }
  98. return original_bytes.trim(TRY(m_stream.read_some(bytes)).size() + bytes_read_from_buffer);
  99. }
  100. virtual bool is_eof() const override
  101. {
  102. return m_buffer.is_empty() && m_stream.is_eof();
  103. }
  104. virtual ErrorOr<void> discard(size_t count) override
  105. {
  106. size_t bytes_discarded_from_buffer = 0;
  107. if (!m_buffer.is_empty()) {
  108. auto read_size = min(count, m_buffer.size());
  109. for (size_t i = 0; i < read_size; ++i)
  110. m_buffer.take_first();
  111. bytes_discarded_from_buffer = read_size;
  112. }
  113. return m_stream.discard(count - bytes_discarded_from_buffer);
  114. }
  115. virtual ErrorOr<size_t> write_some(ReadonlyBytes) override
  116. {
  117. return Error::from_errno(EBADF);
  118. }
  119. virtual bool is_open() const override
  120. {
  121. return m_stream.is_open();
  122. }
  123. virtual void close() override
  124. {
  125. m_stream.close();
  126. }
  127. Stream& m_stream;
  128. Vector<u8, 8> m_buffer;
  129. };
  130. // https://webassembly.github.io/spec/core/bikeshed/#value-types%E2%91%A2
  131. class ValueType {
  132. public:
  133. enum Kind {
  134. I32,
  135. I64,
  136. F32,
  137. F64,
  138. V128,
  139. FunctionReference,
  140. ExternReference,
  141. };
  142. explicit ValueType(Kind kind)
  143. : m_kind(kind)
  144. {
  145. }
  146. bool operator==(ValueType const&) const = default;
  147. auto is_reference() const { return m_kind == ExternReference || m_kind == FunctionReference; }
  148. auto is_vector() const { return m_kind == V128; }
  149. auto is_numeric() const { return !is_reference() && !is_vector(); }
  150. auto kind() const { return m_kind; }
  151. static ParseResult<ValueType> parse(Stream& stream);
  152. static ByteString kind_name(Kind kind)
  153. {
  154. switch (kind) {
  155. case I32:
  156. return "i32";
  157. case I64:
  158. return "i64";
  159. case F32:
  160. return "f32";
  161. case F64:
  162. return "f64";
  163. case V128:
  164. return "v128";
  165. case FunctionReference:
  166. return "funcref";
  167. case ExternReference:
  168. return "externref";
  169. }
  170. VERIFY_NOT_REACHED();
  171. }
  172. private:
  173. Kind m_kind;
  174. };
  175. // https://webassembly.github.io/spec/core/bikeshed/#result-types%E2%91%A2
  176. class ResultType {
  177. public:
  178. explicit ResultType(Vector<ValueType> types)
  179. : m_types(move(types))
  180. {
  181. }
  182. auto const& types() const { return m_types; }
  183. static ParseResult<ResultType> parse(Stream& stream);
  184. private:
  185. Vector<ValueType> m_types;
  186. };
  187. // https://webassembly.github.io/spec/core/bikeshed/#function-types%E2%91%A4
  188. class FunctionType {
  189. public:
  190. FunctionType(Vector<ValueType> parameters, Vector<ValueType> results)
  191. : m_parameters(move(parameters))
  192. , m_results(move(results))
  193. {
  194. }
  195. auto& parameters() const { return m_parameters; }
  196. auto& results() const { return m_results; }
  197. static ParseResult<FunctionType> parse(Stream& stream);
  198. private:
  199. Vector<ValueType> m_parameters;
  200. Vector<ValueType> m_results;
  201. };
  202. // https://webassembly.github.io/spec/core/bikeshed/#limits%E2%91%A5
  203. class Limits {
  204. public:
  205. explicit Limits(u32 min, Optional<u32> max = {})
  206. : m_min(min)
  207. , m_max(move(max))
  208. {
  209. }
  210. auto min() const { return m_min; }
  211. auto& max() const { return m_max; }
  212. bool is_subset_of(Limits other) const
  213. {
  214. return m_min >= other.min()
  215. && (!other.max().has_value() || (m_max.has_value() && *m_max <= *other.max()));
  216. }
  217. static ParseResult<Limits> parse(Stream& stream);
  218. private:
  219. u32 m_min { 0 };
  220. Optional<u32> m_max;
  221. };
  222. // https://webassembly.github.io/spec/core/bikeshed/#memory-types%E2%91%A4
  223. class MemoryType {
  224. public:
  225. explicit MemoryType(Limits limits)
  226. : m_limits(move(limits))
  227. {
  228. }
  229. auto& limits() const { return m_limits; }
  230. static ParseResult<MemoryType> parse(Stream& stream);
  231. private:
  232. Limits m_limits;
  233. };
  234. // https://webassembly.github.io/spec/core/bikeshed/#table-types%E2%91%A4
  235. class TableType {
  236. public:
  237. explicit TableType(ValueType element_type, Limits limits)
  238. : m_element_type(element_type)
  239. , m_limits(move(limits))
  240. {
  241. VERIFY(m_element_type.is_reference());
  242. }
  243. auto& limits() const { return m_limits; }
  244. auto& element_type() const { return m_element_type; }
  245. static ParseResult<TableType> parse(Stream& stream);
  246. private:
  247. ValueType m_element_type;
  248. Limits m_limits;
  249. };
  250. // https://webassembly.github.io/spec/core/bikeshed/#global-types%E2%91%A4
  251. class GlobalType {
  252. public:
  253. GlobalType(ValueType type, bool is_mutable)
  254. : m_type(type)
  255. , m_is_mutable(is_mutable)
  256. {
  257. }
  258. auto& type() const { return m_type; }
  259. auto is_mutable() const { return m_is_mutable; }
  260. static ParseResult<GlobalType> parse(Stream& stream);
  261. private:
  262. ValueType m_type;
  263. bool m_is_mutable { false };
  264. };
  265. // https://webassembly.github.io/spec/core/bikeshed/#binary-blocktype
  266. class BlockType {
  267. public:
  268. enum Kind {
  269. Empty,
  270. Type,
  271. Index,
  272. };
  273. BlockType()
  274. : m_kind(Empty)
  275. , m_empty(0)
  276. {
  277. }
  278. explicit BlockType(ValueType type)
  279. : m_kind(Type)
  280. , m_value_type(type)
  281. {
  282. }
  283. explicit BlockType(TypeIndex index)
  284. : m_kind(Index)
  285. , m_type_index(index)
  286. {
  287. }
  288. auto kind() const { return m_kind; }
  289. auto& value_type() const
  290. {
  291. VERIFY(kind() == Type);
  292. return m_value_type;
  293. }
  294. auto& type_index() const
  295. {
  296. VERIFY(kind() == Index);
  297. return m_type_index;
  298. }
  299. static ParseResult<BlockType> parse(Stream& stream);
  300. private:
  301. Kind m_kind { Empty };
  302. union {
  303. ValueType m_value_type;
  304. TypeIndex m_type_index;
  305. u8 m_empty;
  306. };
  307. };
  308. // https://webassembly.github.io/spec/core/bikeshed/#binary-instr
  309. // https://webassembly.github.io/spec/core/bikeshed/#reference-instructions%E2%91%A6
  310. // https://webassembly.github.io/spec/core/bikeshed/#parametric-instructions%E2%91%A6
  311. // https://webassembly.github.io/spec/core/bikeshed/#variable-instructions%E2%91%A6
  312. // https://webassembly.github.io/spec/core/bikeshed/#table-instructions%E2%91%A6
  313. // https://webassembly.github.io/spec/core/bikeshed/#memory-instructions%E2%91%A6
  314. // https://webassembly.github.io/spec/core/bikeshed/#numeric-instructions%E2%91%A6
  315. class Instruction {
  316. public:
  317. explicit Instruction(OpCode opcode)
  318. : m_opcode(opcode)
  319. , m_arguments(static_cast<u8>(0))
  320. {
  321. }
  322. struct TableElementArgs {
  323. ElementIndex element_index;
  324. TableIndex table_index;
  325. };
  326. struct TableTableArgs {
  327. TableIndex lhs;
  328. TableIndex rhs;
  329. };
  330. struct StructuredInstructionArgs {
  331. BlockType block_type;
  332. InstructionPointer end_ip;
  333. Optional<InstructionPointer> else_ip;
  334. };
  335. struct TableBranchArgs {
  336. Vector<LabelIndex> labels;
  337. LabelIndex default_;
  338. };
  339. struct IndirectCallArgs {
  340. TypeIndex type;
  341. TableIndex table;
  342. };
  343. struct MemoryArgument {
  344. u32 align;
  345. u32 offset;
  346. MemoryIndex memory_index { 0 };
  347. };
  348. struct MemoryAndLaneArgument {
  349. MemoryArgument memory;
  350. u8 lane;
  351. };
  352. struct LaneIndex {
  353. u8 lane;
  354. };
  355. // Proposal "multi-memory"
  356. struct MemoryCopyArgs {
  357. MemoryIndex src_index;
  358. MemoryIndex dst_index;
  359. };
  360. struct MemoryInitArgs {
  361. DataIndex data_index;
  362. MemoryIndex memory_index;
  363. };
  364. struct MemoryIndexArgument {
  365. MemoryIndex memory_index;
  366. };
  367. struct ShuffleArgument {
  368. explicit ShuffleArgument(u8 (&lanes)[16])
  369. : lanes {
  370. lanes[0], lanes[1], lanes[2], lanes[3], lanes[4], lanes[5], lanes[6], lanes[7],
  371. lanes[8], lanes[9], lanes[10], lanes[11], lanes[12], lanes[13], lanes[14], lanes[15]
  372. }
  373. {
  374. }
  375. u8 lanes[16];
  376. };
  377. template<typename T>
  378. explicit Instruction(OpCode opcode, T argument)
  379. : m_opcode(opcode)
  380. , m_arguments(move(argument))
  381. {
  382. }
  383. static ParseResult<Instruction> parse(Stream& stream);
  384. auto& opcode() const { return m_opcode; }
  385. auto& arguments() const { return m_arguments; }
  386. auto& arguments() { return m_arguments; }
  387. private:
  388. OpCode m_opcode { 0 };
  389. Variant<
  390. BlockType,
  391. DataIndex,
  392. ElementIndex,
  393. FunctionIndex,
  394. GlobalIndex,
  395. IndirectCallArgs,
  396. LabelIndex,
  397. LaneIndex,
  398. LocalIndex,
  399. MemoryArgument,
  400. MemoryAndLaneArgument,
  401. MemoryCopyArgs,
  402. MemoryIndexArgument,
  403. MemoryInitArgs,
  404. StructuredInstructionArgs,
  405. ShuffleArgument,
  406. TableBranchArgs,
  407. TableElementArgs,
  408. TableIndex,
  409. TableTableArgs,
  410. ValueType,
  411. Vector<ValueType>,
  412. double,
  413. float,
  414. i32,
  415. i64,
  416. u128,
  417. u8> // Empty state
  418. m_arguments;
  419. };
  420. class CustomSection {
  421. public:
  422. static constexpr u8 section_id = 0;
  423. CustomSection(ByteString name, ByteBuffer contents)
  424. : m_name(move(name))
  425. , m_contents(move(contents))
  426. {
  427. }
  428. auto& name() const { return m_name; }
  429. auto& contents() const { return m_contents; }
  430. static ParseResult<CustomSection> parse(Stream& stream);
  431. private:
  432. ByteString m_name;
  433. ByteBuffer m_contents;
  434. };
  435. class TypeSection {
  436. public:
  437. static constexpr u8 section_id = 1;
  438. explicit TypeSection(Vector<FunctionType> types)
  439. : m_types(move(types))
  440. {
  441. }
  442. auto& types() const { return m_types; }
  443. static ParseResult<TypeSection> parse(Stream& stream);
  444. private:
  445. Vector<FunctionType> m_types;
  446. };
  447. class ImportSection {
  448. public:
  449. class Import {
  450. public:
  451. using ImportDesc = Variant<TypeIndex, TableType, MemoryType, GlobalType, FunctionType>;
  452. Import(ByteString module, ByteString name, ImportDesc description)
  453. : m_module(move(module))
  454. , m_name(move(name))
  455. , m_description(move(description))
  456. {
  457. }
  458. auto& module() const { return m_module; }
  459. auto& name() const { return m_name; }
  460. auto& description() const { return m_description; }
  461. static ParseResult<Import> parse(Stream& stream);
  462. private:
  463. template<typename T>
  464. static ParseResult<Import> parse_with_type(auto&& stream, auto&& module, auto&& name)
  465. {
  466. auto result = TRY(T::parse(stream));
  467. return Import { module, name, result };
  468. }
  469. ByteString m_module;
  470. ByteString m_name;
  471. ImportDesc m_description;
  472. };
  473. public:
  474. static constexpr u8 section_id = 2;
  475. explicit ImportSection(Vector<Import> imports)
  476. : m_imports(move(imports))
  477. {
  478. }
  479. auto& imports() const { return m_imports; }
  480. static ParseResult<ImportSection> parse(Stream& stream);
  481. private:
  482. Vector<Import> m_imports;
  483. };
  484. class FunctionSection {
  485. public:
  486. static constexpr u8 section_id = 3;
  487. explicit FunctionSection(Vector<TypeIndex> types)
  488. : m_types(move(types))
  489. {
  490. }
  491. auto& types() const { return m_types; }
  492. static ParseResult<FunctionSection> parse(Stream& stream);
  493. private:
  494. Vector<TypeIndex> m_types;
  495. };
  496. class TableSection {
  497. public:
  498. class Table {
  499. public:
  500. explicit Table(TableType type)
  501. : m_type(move(type))
  502. {
  503. }
  504. auto& type() const { return m_type; }
  505. static ParseResult<Table> parse(Stream& stream);
  506. private:
  507. TableType m_type;
  508. };
  509. public:
  510. static constexpr u8 section_id = 4;
  511. explicit TableSection(Vector<Table> tables)
  512. : m_tables(move(tables))
  513. {
  514. }
  515. auto& tables() const { return m_tables; }
  516. static ParseResult<TableSection> parse(Stream& stream);
  517. private:
  518. Vector<Table> m_tables;
  519. };
  520. class MemorySection {
  521. public:
  522. class Memory {
  523. public:
  524. explicit Memory(MemoryType type)
  525. : m_type(move(type))
  526. {
  527. }
  528. auto& type() const { return m_type; }
  529. static ParseResult<Memory> parse(Stream& stream);
  530. private:
  531. MemoryType m_type;
  532. };
  533. public:
  534. static constexpr u8 section_id = 5;
  535. explicit MemorySection(Vector<Memory> memories)
  536. : m_memories(move(memories))
  537. {
  538. }
  539. auto& memories() const { return m_memories; }
  540. static ParseResult<MemorySection> parse(Stream& stream);
  541. private:
  542. Vector<Memory> m_memories;
  543. };
  544. class Expression {
  545. public:
  546. explicit Expression(Vector<Instruction> instructions)
  547. : m_instructions(move(instructions))
  548. {
  549. }
  550. auto& instructions() const { return m_instructions; }
  551. static ParseResult<Expression> parse(Stream& stream, Optional<size_t> size_hint = {});
  552. private:
  553. Vector<Instruction> m_instructions;
  554. };
  555. class GlobalSection {
  556. public:
  557. class Global {
  558. public:
  559. explicit Global(GlobalType type, Expression expression)
  560. : m_type(move(type))
  561. , m_expression(move(expression))
  562. {
  563. }
  564. auto& type() const { return m_type; }
  565. auto& expression() const { return m_expression; }
  566. static ParseResult<Global> parse(Stream& stream);
  567. private:
  568. GlobalType m_type;
  569. Expression m_expression;
  570. };
  571. public:
  572. static constexpr u8 section_id = 6;
  573. explicit GlobalSection(Vector<Global> entries)
  574. : m_entries(move(entries))
  575. {
  576. }
  577. auto& entries() const { return m_entries; }
  578. static ParseResult<GlobalSection> parse(Stream& stream);
  579. private:
  580. Vector<Global> m_entries;
  581. };
  582. class ExportSection {
  583. private:
  584. using ExportDesc = Variant<FunctionIndex, TableIndex, MemoryIndex, GlobalIndex>;
  585. public:
  586. class Export {
  587. public:
  588. explicit Export(ByteString name, ExportDesc description)
  589. : m_name(move(name))
  590. , m_description(move(description))
  591. {
  592. }
  593. auto& name() const { return m_name; }
  594. auto& description() const { return m_description; }
  595. static ParseResult<Export> parse(Stream& stream);
  596. private:
  597. ByteString m_name;
  598. ExportDesc m_description;
  599. };
  600. static constexpr u8 section_id = 7;
  601. explicit ExportSection(Vector<Export> entries)
  602. : m_entries(move(entries))
  603. {
  604. }
  605. auto& entries() const { return m_entries; }
  606. static ParseResult<ExportSection> parse(Stream& stream);
  607. private:
  608. Vector<Export> m_entries;
  609. };
  610. class StartSection {
  611. public:
  612. class StartFunction {
  613. public:
  614. explicit StartFunction(FunctionIndex index)
  615. : m_index(index)
  616. {
  617. }
  618. auto& index() const { return m_index; }
  619. static ParseResult<StartFunction> parse(Stream& stream);
  620. private:
  621. FunctionIndex m_index;
  622. };
  623. static constexpr u8 section_id = 8;
  624. explicit StartSection(StartFunction func)
  625. : m_function(move(func))
  626. {
  627. }
  628. auto& function() const { return m_function; }
  629. static ParseResult<StartSection> parse(Stream& stream);
  630. private:
  631. StartFunction m_function;
  632. };
  633. class ElementSection {
  634. public:
  635. struct Active {
  636. TableIndex index;
  637. Expression expression;
  638. };
  639. struct Declarative {
  640. };
  641. struct Passive {
  642. };
  643. struct Element {
  644. static ParseResult<Element> parse(Stream&);
  645. ValueType type;
  646. Vector<Expression> init;
  647. Variant<Active, Passive, Declarative> mode;
  648. };
  649. static constexpr u8 section_id = 9;
  650. explicit ElementSection(Vector<Element> segs)
  651. : m_segments(move(segs))
  652. {
  653. }
  654. auto& segments() const { return m_segments; }
  655. static ParseResult<ElementSection> parse(Stream& stream);
  656. private:
  657. Vector<Element> m_segments;
  658. };
  659. class Locals {
  660. public:
  661. explicit Locals(u32 n, ValueType type)
  662. : m_n(n)
  663. , m_type(type)
  664. {
  665. }
  666. // Yikes...
  667. auto n() const { return m_n; }
  668. auto& type() const { return m_type; }
  669. static ParseResult<Locals> parse(Stream& stream);
  670. private:
  671. u32 m_n { 0 };
  672. ValueType m_type;
  673. };
  674. class CodeSection {
  675. public:
  676. // https://webassembly.github.io/spec/core/bikeshed/#binary-func
  677. class Func {
  678. public:
  679. explicit Func(Vector<Locals> locals, Expression body)
  680. : m_locals(move(locals))
  681. , m_body(move(body))
  682. {
  683. }
  684. auto& locals() const { return m_locals; }
  685. auto& body() const { return m_body; }
  686. static ParseResult<Func> parse(Stream& stream, size_t size_hint);
  687. private:
  688. Vector<Locals> m_locals;
  689. Expression m_body;
  690. };
  691. class Code {
  692. public:
  693. explicit Code(u32 size, Func func)
  694. : m_size(size)
  695. , m_func(move(func))
  696. {
  697. }
  698. auto size() const { return m_size; }
  699. auto& func() const { return m_func; }
  700. static ParseResult<Code> parse(Stream& stream);
  701. private:
  702. u32 m_size { 0 };
  703. Func m_func;
  704. };
  705. static constexpr u8 section_id = 10;
  706. explicit CodeSection(Vector<Code> funcs)
  707. : m_functions(move(funcs))
  708. {
  709. }
  710. auto& functions() const { return m_functions; }
  711. static ParseResult<CodeSection> parse(Stream& stream);
  712. private:
  713. Vector<Code> m_functions;
  714. };
  715. class DataSection {
  716. public:
  717. class Data {
  718. public:
  719. struct Passive {
  720. Vector<u8> init;
  721. };
  722. struct Active {
  723. Vector<u8> init;
  724. MemoryIndex index;
  725. Expression offset;
  726. };
  727. using Value = Variant<Passive, Active>;
  728. explicit Data(Value value)
  729. : m_value(move(value))
  730. {
  731. }
  732. auto& value() const { return m_value; }
  733. static ParseResult<Data> parse(Stream& stream);
  734. private:
  735. Value m_value;
  736. };
  737. static constexpr u8 section_id = 11;
  738. explicit DataSection(Vector<Data> data)
  739. : m_data(move(data))
  740. {
  741. }
  742. auto& data() const { return m_data; }
  743. static ParseResult<DataSection> parse(Stream& stream);
  744. private:
  745. Vector<Data> m_data;
  746. };
  747. class DataCountSection {
  748. public:
  749. static constexpr u8 section_id = 12;
  750. explicit DataCountSection(Optional<u32> count)
  751. : m_count(move(count))
  752. {
  753. }
  754. auto& count() const { return m_count; }
  755. static ParseResult<DataCountSection> parse(Stream& stream);
  756. private:
  757. Optional<u32> m_count;
  758. };
  759. class Module {
  760. public:
  761. enum class ValidationStatus {
  762. Unchecked,
  763. Invalid,
  764. Valid,
  765. };
  766. using AnySection = Variant<
  767. CustomSection,
  768. TypeSection,
  769. ImportSection,
  770. FunctionSection,
  771. TableSection,
  772. MemorySection,
  773. GlobalSection,
  774. ExportSection,
  775. StartSection,
  776. ElementSection,
  777. CodeSection,
  778. DataSection,
  779. DataCountSection>;
  780. static constexpr Array<u8, 4> wasm_magic { 0, 'a', 's', 'm' };
  781. static constexpr Array<u8, 4> wasm_version { 1, 0, 0, 0 };
  782. explicit Module(Vector<AnySection> sections)
  783. : m_sections(move(sections))
  784. {
  785. }
  786. auto& sections() const { return m_sections; }
  787. auto& type(TypeIndex index) const
  788. {
  789. FunctionType const* type = nullptr;
  790. for_each_section_of_type<TypeSection>([&](TypeSection const& section) {
  791. type = &section.types().at(index.value());
  792. });
  793. VERIFY(type != nullptr);
  794. return *type;
  795. }
  796. template<typename T, typename Callback>
  797. void for_each_section_of_type(Callback&& callback) const
  798. {
  799. for (auto& section : m_sections) {
  800. if (auto ptr = section.get_pointer<T>())
  801. callback(*ptr);
  802. }
  803. }
  804. template<typename T, typename Callback>
  805. void for_each_section_of_type(Callback&& callback)
  806. {
  807. for (auto& section : m_sections) {
  808. if (auto ptr = section.get_pointer<T>())
  809. callback(*ptr);
  810. }
  811. }
  812. void set_validation_status(ValidationStatus status, Badge<Validator>) { set_validation_status(status); }
  813. ValidationStatus validation_status() const { return m_validation_status; }
  814. StringView validation_error() const { return *m_validation_error; }
  815. void set_validation_error(ByteString error) { m_validation_error = move(error); }
  816. static ParseResult<Module> parse(Stream& stream);
  817. private:
  818. void set_validation_status(ValidationStatus status) { m_validation_status = status; }
  819. Vector<AnySection> m_sections;
  820. ValidationStatus m_validation_status { ValidationStatus::Unchecked };
  821. Optional<ByteString> m_validation_error;
  822. };
  823. }