Commit 3f3003097c

Andrew Kelley <andrew@ziglang.org>
2022-10-31 00:10:20
std.heap.PageAllocator: add check for large allocation
Instead of making the memory alignment functions more complicated, I added more API documentation for their existing semantics. closes #12118 closes #12135
1 parent 9b54c9d
Changed files (3)
lib/std/heap/general_purpose_allocator.zig
@@ -971,6 +971,14 @@ test "large allocations" {
     allocator.free(ptr2);
 }
 
+test "very large allocation" {
+    var gpa = GeneralPurposeAllocator(test_config){};
+    defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
+    const allocator = gpa.allocator();
+
+    try std.testing.expectError(error.OutOfMemory, allocator.alloc(u8, math.maxInt(usize)));
+}
+
 test "realloc" {
     var gpa = GeneralPurposeAllocator(test_config){};
     defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
lib/std/heap.zig
@@ -260,6 +260,9 @@ const PageAllocator = struct {
     fn alloc(_: *anyopaque, n: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 {
         _ = ra;
         assert(n > 0);
+        if (n > maxInt(usize) - (mem.page_size - 1)) {
+            return error.OutOfMemory;
+        }
         const aligned_len = mem.alignForward(n, mem.page_size);
 
         if (builtin.os.tag == .windows) {
lib/std/mem.zig
@@ -3551,12 +3551,14 @@ test "sliceAsBytes preserves pointer attributes" {
 
 /// Round an address up to the next (or current) aligned address.
 /// The alignment must be a power of 2 and greater than 0.
+/// Asserts that rounding up the address does not cause integer overflow.
 pub fn alignForward(addr: usize, alignment: usize) usize {
     return alignForwardGeneric(usize, addr, alignment);
 }
 
 /// Round an address up to the next (or current) aligned address.
 /// The alignment must be a power of 2 and greater than 0.
+/// Asserts that rounding up the address does not cause integer overflow.
 pub fn alignForwardGeneric(comptime T: type, addr: T, alignment: T) T {
     return alignBackwardGeneric(T, addr + (alignment - 1), alignment);
 }