Commit a7282d0910

Jacob Young <jacobly0@users.noreply.github.com>
2024-03-23 03:38:51
WasmAllocator: fix safety panic during OOM
1 parent ff7ca4b
Changed files (1)
lib
lib/std/heap/WasmAllocator.zig
@@ -55,7 +55,7 @@ fn alloc(ctx: *anyopaque, len: usize, log2_align: u8, return_address: usize) ?[*
         const addr = a: {
             const top_free_ptr = frees[class];
             if (top_free_ptr != 0) {
-                const node = @as(*usize, @ptrFromInt(top_free_ptr + (slot_size - @sizeOf(usize))));
+                const node: *usize = @ptrFromInt(top_free_ptr + (slot_size - @sizeOf(usize)));
                 frees[class] = node.*;
                 break :a top_free_ptr;
             }
@@ -74,11 +74,10 @@ fn alloc(ctx: *anyopaque, len: usize, log2_align: u8, return_address: usize) ?[*
                 break :a next_addr;
             }
         };
-        return @as([*]u8, @ptrFromInt(addr));
+        return @ptrFromInt(addr);
     }
     const bigpages_needed = bigPagesNeeded(actual_len);
-    const addr = allocBigPages(bigpages_needed);
-    return @as([*]u8, @ptrFromInt(addr));
+    return @ptrFromInt(allocBigPages(bigpages_needed));
 }
 
 fn resize(
@@ -123,14 +122,14 @@ fn free(
     const class = math.log2(slot_size) - min_class;
     const addr = @intFromPtr(buf.ptr);
     if (class < size_class_count) {
-        const node = @as(*usize, @ptrFromInt(addr + (slot_size - @sizeOf(usize))));
+        const node: *usize = @ptrFromInt(addr + (slot_size - @sizeOf(usize)));
         node.* = frees[class];
         frees[class] = addr;
     } else {
         const bigpages_needed = bigPagesNeeded(actual_len);
         const pow2_pages = math.ceilPowerOfTwoAssert(usize, bigpages_needed);
         const big_slot_size_bytes = pow2_pages * bigpage_size;
-        const node = @as(*usize, @ptrFromInt(addr + (big_slot_size_bytes - @sizeOf(usize))));
+        const node: *usize = @ptrFromInt(addr + (big_slot_size_bytes - @sizeOf(usize)));
         const big_class = math.log2(pow2_pages);
         node.* = big_frees[big_class];
         big_frees[big_class] = addr;
@@ -148,15 +147,14 @@ fn allocBigPages(n: usize) usize {
 
     const top_free_ptr = big_frees[class];
     if (top_free_ptr != 0) {
-        const node = @as(*usize, @ptrFromInt(top_free_ptr + (slot_size_bytes - @sizeOf(usize))));
+        const node: *usize = @ptrFromInt(top_free_ptr + (slot_size_bytes - @sizeOf(usize)));
         big_frees[class] = node.*;
         return top_free_ptr;
     }
 
     const page_index = @wasmMemoryGrow(0, pow2_pages * pages_per_bigpage);
-    if (page_index <= 0) return 0;
-    const addr = @as(u32, @intCast(page_index)) * wasm.page_size;
-    return addr;
+    if (page_index == -1) return 0;
+    return @as(usize, @intCast(page_index)) * wasm.page_size;
 }
 
 const test_ally = Allocator{