Debian Codegraph @

internal/wasm/memory/mem_windows.go

raw symbols SCIP
1 package memory
2
3 import (
4 "math"
5 "reflect"
6 "sync"
7 "unsafe"
8
9 "golang.org/x/sys/windows"
10 )
11
12 type Memory struct {
13 Buf []byte
14 Max int64
15 com int
16 ptr uintptr
17 mu sync.Mutex
18 }
19
20 func (m *Memory) Slice() *[]byte {
21 return &m.Buf
22 }
23
24 func (m *Memory) Grow(delta, _ int64) int64 {
25 m.mu.Lock()
26 defer m.mu.Unlock()
27
28 if m.Buf == nil {
29 m.allocate(uint64(m.Max) << 16)
30 }
31
32 len := len(m.Buf)
33 old := int64(len >> 16)
34 if delta == 0 {
35 return old
36 }
37 new := old + delta
38 if new > m.Max {
39 return -1
40 }
41 m.reallocate(uint64(new) << 16)
42 return old
43 }
44
45 func (m *Memory) allocate(max uint64) {
46 // Round up to the page size.
47 rnd := uint64(windows.Getpagesize() - 1)
48 res := (max + rnd) &^ rnd
49
50 if res > math.MaxInt {
51 // This ensures uintptr(res) overflows to a large value,
52 // and windows.VirtualAlloc returns an error.
53 res = math.MaxUint64
54 }
55
56 // Reserve res bytes of address space, to ensure we won't need to move it.
57 r, err := windows.VirtualAlloc(0, uintptr(res), windows.MEM_RESERVE, windows.PAGE_READWRITE)
58 if err != nil {
59 panic(err)
60 }
61 m.ptr = r
62
63 // SliceHeader, although deprecated, avoids a go vet warning.
64 sh := (*reflect.SliceHeader)(unsafe.Pointer(&m.Buf))
65 sh.Data = r
66 sh.Len = 0
67 sh.Cap = int(res)
68 }
69
70 func (m *Memory) reallocate(size uint64) {
71 com := uint64(m.com)
72 res := uint64(cap(m.Buf))
73 if com < size && size <= res {
74 // Grow geometrically, round up to the page size.
75 rnd := uint64(windows.Getpagesize() - 1)
76 new := com + com>>3
77 new = min(max(size, new), res)
78 new = (new + rnd) &^ rnd
79
80 // Commit additional memory up to new bytes.
81 _, err := windows.VirtualAlloc(m.ptr, uintptr(new), windows.MEM_COMMIT, windows.PAGE_READWRITE)
82 if err != nil {
83 panic(err)
84 }
85 m.com = int(new)
86 }
87 buf := m.Buf[:size]
88 atomicStoreSliceLen(&m.Buf, len(buf))
89 }
90
91 func (m *Memory) Close() error {
92 err := windows.VirtualFree(m.ptr, 0, windows.MEM_RELEASE)
93 m.Buf = nil
94 m.com = 0
95 m.ptr = 0
96 return err
97 }