Skip to content

Commit

Permalink
Merge pull request #844 from wasmx/metering
Browse files Browse the repository at this point in the history
Support metering cost for memory pages
  • Loading branch information
axic committed Mar 3, 2023
2 parents 6b39221 + a5e1e4e commit b9e1c18
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/fizzy/execute.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -898,8 +898,15 @@ ExecutionResult execute(
}
case Instr::memory_grow:
{
stack.top() =
grow_memory(*memory, stack.top().as<uint32_t>(), instance.memory_pages_limit);
const auto delta_pages = stack.top().as<uint32_t>();

if constexpr (MeteringEnabled)
{
if ((ctx.ticks -= get_grow_memory_cost(delta_pages)) < 0)
goto trap;
}

stack.top() = grow_memory(*memory, delta_pages, instance.memory_pages_limit);
break;
}
case Instr::i32_const:
Expand Down
6 changes: 6 additions & 0 deletions lib/fizzy/instructions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ const uint8_t* get_instruction_max_align_table() noexcept;
/// execution metering.
const int16_t* get_instruction_cost_table() noexcept;

/// Calculates the cost of memory expansion. Currently set at 65536 per page (1 per byte).
inline constexpr auto get_grow_memory_cost(uint32_t delta_pages) noexcept
{
return delta_pages * 65536;
}

} // namespace fizzy
23 changes: 23 additions & 0 deletions test/unittests/execute_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1101,3 +1101,26 @@ TEST(execute, metering)
ctx.ticks = 0;
EXPECT_THAT(execute(*instance, 0, {}, ctx), Traps());
}

TEST(execute, metering_memory)
{
/* wat2wasm
(memory 0 1)
(func (result i32)
i32.const 1
memory.grow
)
*/
const auto wasm =
from_hex("0061736d010000000105016000017f030201000504010100010a08010600410140000b");
auto instance = instantiate(parse(wasm));

ExecutionContext ctx;
ctx.metering_enabled = true;
ctx.ticks = 100000;
EXPECT_THAT(execute(*instance, 0, {}, ctx), Result(0));
EXPECT_EQ(ctx.ticks, 34461);

ctx.ticks = 65536;
EXPECT_THAT(execute(*instance, 0, {}, ctx), Traps());
}

0 comments on commit b9e1c18

Please sign in to comment.