From d23bdcd225527d8782b6dfc8888f5ed82f87a61b Mon Sep 17 00:00:00 2001 From: Nuno Cruces Date: Mon, 20 May 2024 09:33:34 +0100 Subject: [PATCH] Commiting memory not needed. --- internal/util/alloc_unix.go | 10 ++-------- internal/util/alloc_windows.go | 10 ++-------- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/internal/util/alloc_unix.go b/internal/util/alloc_unix.go index f7a1c03..7f1a379 100644 --- a/internal/util/alloc_unix.go +++ b/internal/util/alloc_unix.go @@ -13,26 +13,20 @@ func newAllocator(cap, max uint64) experimental.LinearMemory { // Round up to the page size. rnd := uint64(unix.Getpagesize() - 1) max = (max + rnd) &^ rnd - cap = (cap + rnd) &^ rnd if max > math.MaxInt { // This ensures int(max) overflows to a negative value, // and unix.Mmap returns EINVAL. max = math.MaxUint64 } + // Reserve max bytes of address space, to ensure we won't need to move it. // A protected, private, anonymous mapping should not commit memory. b, err := unix.Mmap(-1, 0, int(max), unix.PROT_NONE, unix.MAP_PRIVATE|unix.MAP_ANON) if err != nil { panic(err) } - // Commit the initial cap bytes of memory. - err = unix.Mprotect(b[:cap], unix.PROT_READ|unix.PROT_WRITE) - if err != nil { - unix.Munmap(b) - panic(err) - } - return &mmappedMemory{buf: b[:cap]} + return &mmappedMemory{buf: b[:0]} } // The slice covers the entire mmapped memory: diff --git a/internal/util/alloc_windows.go b/internal/util/alloc_windows.go index 482689f..a898489 100644 --- a/internal/util/alloc_windows.go +++ b/internal/util/alloc_windows.go @@ -15,29 +15,23 @@ func newAllocator(cap, max uint64) experimental.LinearMemory { // Round up to the page size. rnd := uint64(windows.Getpagesize() - 1) max = (max + rnd) &^ rnd - cap = (cap + rnd) &^ rnd if max > math.MaxInt { // This ensures uintptr(max) overflows to a large value, // and windows.VirtualAlloc returns an error. max = math.MaxUint64 } + // Reserve max bytes of address space, to ensure we won't need to move it. // This does not commit memory. r, err := windows.VirtualAlloc(0, uintptr(max), windows.MEM_RESERVE, windows.PAGE_READWRITE) if err != nil { panic(err) } - // Commit the initial cap bytes of memory. - _, err = windows.VirtualAlloc(r, uintptr(cap), windows.MEM_COMMIT, windows.PAGE_READWRITE) - if err != nil { - windows.VirtualFree(r, 0, windows.MEM_RELEASE) - panic(err) - } + mem := virtualMemory{addr: r} // SliceHeader, although deprecated, avoids a go vet warning. sh := (*reflect.SliceHeader)(unsafe.Pointer(&mem.buf)) - sh.Len = int(cap) // Not a bug. sh.Cap = int(max) // Not a bug. sh.Data = r return &mem