| 1 |
|
| 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 |
|
| 18 |
|
| 19 |
|
| 20 |
rnd := pageSize - 1 |
| 21 |
res := (max + rnd) &^ rnd |
| 22 |
|
| 23 |
if res > math.MaxInt { |
| 24 |
|
| 25 |
|
| 26 |
res = math.MaxUint64 |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 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 |
|
| 41 |
|
| 42 |
|
| 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 |
|
| 54 |
rnd := pageSize - 1 |
| 55 |
newCap := (size + rnd) &^ rnd |
| 56 |
|
| 57 |
|
| 58 |
_, err := windows.VirtualAlloc(m.addr, uintptr(newCap), windows.MEM_COMMIT, windows.PAGE_READWRITE) |
| 59 |
if err != nil { |
| 60 |
return nil |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
m.buf = m.buf[:newCap] |
| 65 |
} |
| 66 |
|
| 67 |
|
| 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 |
} |