diff --git a/Userland/Libraries/LibWasm/Parser/Parser.cpp b/Userland/Libraries/LibWasm/Parser/Parser.cpp index 3a4b18f5367..de838ed978e 100644 --- a/Userland/Libraries/LibWasm/Parser/Parser.cpp +++ b/Userland/Libraries/LibWasm/Parser/Parser.cpp @@ -1049,13 +1049,15 @@ ParseResult MemorySection::parse(Stream& stream) return MemorySection { memories }; } -ParseResult Expression::parse(Stream& stream) +ParseResult Expression::parse(Stream& stream, Optional size_hint) { ScopeLogger logger("Expression"sv); InstructionPointer ip { 0 }; Vector stack; Vector instructions; + if (size_hint.has_value()) + instructions.ensure_capacity(size_hint.release_value()); while (true) { auto instruction = TRY(Instruction::parse(stream)); switch (instruction.opcode().value()) { @@ -1239,11 +1241,11 @@ ParseResult Locals::parse(Stream& stream) return Locals { static_cast(count), type }; } -ParseResult CodeSection::Func::parse(Stream& stream) +ParseResult CodeSection::Func::parse(Stream& stream, size_t size_hint) { ScopeLogger logger("Func"sv); auto locals = TRY(parse_vector(stream)); - auto body = TRY(Expression::parse(stream)); + auto body = TRY(Expression::parse(stream, size_hint)); return Func { locals, body }; } @@ -1257,7 +1259,9 @@ ParseResult CodeSection::Code::parse(Stream& stream) auto constrained_stream = ConstrainedStream { MaybeOwned(stream), size }; - auto func = TRY(Func::parse(constrained_stream)); + // Emprically, if there are `size` bytes to be read, then there's around + // `size / 2` instructions, so we pass that as our size hint. + auto func = TRY(Func::parse(constrained_stream, size / 2)); return Code { static_cast(size), func }; } diff --git a/Userland/Libraries/LibWasm/Types.h b/Userland/Libraries/LibWasm/Types.h index 1e5ec6e6d41..c742bffa0ef 100644 --- a/Userland/Libraries/LibWasm/Types.h +++ b/Userland/Libraries/LibWasm/Types.h @@ -676,7 +676,7 @@ public: auto& instructions() const { return m_instructions; } - static ParseResult parse(Stream& stream); + static ParseResult parse(Stream& stream, Optional size_hint = {}); private: Vector m_instructions; @@ -855,7 +855,7 @@ public: auto& locals() const { return m_locals; } auto& body() const { return m_body; } - static ParseResult parse(Stream& stream); + static ParseResult parse(Stream& stream, size_t size_hint); private: Vector m_locals;