Debian Codegraph @

allocator/nonmoving_windows.go

raw symbols SCIP
1 //go:build windows
2
3 package allocator
4
5 import (
6 "fmt"
7 "math"
8 "unsafe"
9
10 "github.com/tetratelabs/wazero/experimental"
11 "golang.org/x/sys/windows"
12 )
13
14 var pageSize = uint64(windows.Getpagesize())
15
16 func alloc(_, max uint64) experimental.LinearMemory {
17 // Round up to the page size because recommitting must be page-aligned.
18 // In practice, the WebAssembly page size should be a multiple of the system
19 // page size on most if not all platforms and rounding will never happen.
20 rnd := pageSize - 1
21 res := (max + rnd) &^ rnd
22
23 if res > math.MaxInt {
24 // This ensures uintptr(max) overflows to a large value,
25 // and windows.VirtualAlloc returns an error.
26 res = math.MaxUint64
27 }
28
29 // Reserve max bytes of address space, to ensure we won't need to move it.
30 // This does not commit memory.
31 r, err := windows.VirtualAlloc(0, uintptr(res), windows.MEM_RESERVE, windows.PAGE_READWRITE)
32 if err != nil {
33 panic(fmt.Errorf("allocator_windows: failed to reserve memory: %w", err))
34 }
35
36 buf := unsafe.Slice((*byte)(unsafe.Pointer(r)), int(res))
37 return &virtualMemory{buf: buf[:0], addr: r}
38 }
39
40 // The slice covers the entire mmapped memory:
41 // - len(buf) is the already committed memory,
42 // - cap(buf) is the reserved address space, which is max rounded up to a page.
43 type virtualMemory struct {
44 buf []byte
45 addr uintptr
46 }
47
48 func (m *virtualMemory) Reallocate(size uint64) []byte {
49 com := uint64(len(m.buf))
50 res := uint64(cap(m.buf))
51
52 if com < size && size <= res {
53 // Round up to the page size.
54 rnd := pageSize - 1
55 newCap := (size + rnd) &^ rnd
56
57 // Commit additional memory up to new bytes.
58 _, err := windows.VirtualAlloc(m.addr, uintptr(newCap), windows.MEM_COMMIT, windows.PAGE_READWRITE)
59 if err != nil {
60 return nil
61 }
62
63 // Update committed memory.
64 m.buf = m.buf[:newCap]
65 }
66 // Limit returned capacity because bytes beyond
67 // len(m.buf) have not yet been committed.
68 return m.buf[:size:len(m.buf)]
69 }
70
71 func (m *virtualMemory) Free() {
72 err := windows.VirtualFree(m.addr, 0, windows.MEM_RELEASE)
73 if err != nil {
74 panic(fmt.Errorf("allocator_windows: failed to release memory: %w", err))
75 }
76 m.addr = 0
77 }