From 30da6d49f435b7ef317b059113ec1fab21d72d00 Mon Sep 17 00:00:00 2001 From: Benjamin Feng Date: Wed, 4 Dec 2019 22:43:02 -0600 Subject: [PATCH] Fix freeing memory across bounds --- lib/std/heap.zig | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/std/heap.zig b/lib/std/heap.zig index 25580a974b..fcc9420cf7 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -379,8 +379,11 @@ const WasmPageAllocator = struct { } if (free_start < extendedOffset()) { - conventional.recycle(free_start, free_end - free_start); - } else { + const clamped_end = std.math.min(extendedOffset(), free_end); + conventional.recycle(free_start, clamped_end - free_start); + } + + if (free_end > extendedOffset()) { if (extended.totalPages() == 0) { // Steal the last page from the memory currently being recycled // TODO: would it be better if we use the first page instead? @@ -390,7 +393,8 @@ const WasmPageAllocator = struct { // Since this is the first page being freed and we consume it, assume *nothing* is free. std.mem.set(u8, extended.bytes, FreeBlock.used); } - extended.recycle(free_start - extendedOffset(), free_end - free_start); + const clamped_start = std.math.max(extendedOffset(), free_start); + extended.recycle(clamped_start - extendedOffset(), free_end - clamped_start); } }