|
| 1 | +package alloc // import "github.com/ncruces/go-sqlite3/internal/alloc" |
| 2 | + |
| 3 | +import ( |
| 4 | + "math" |
| 5 | + "unsafe" |
| 6 | + |
| 7 | + "github.com/tetratelabs/wazero/experimental" |
| 8 | + "golang.org/x/sys/windows" |
| 9 | +) |
| 10 | + |
| 11 | +func NewMemory(cap, max uint64) experimental.LinearMemory { |
| 12 | + // Round up to the page size. |
| 13 | + rnd := uint64(windows.Getpagesize() - 1) |
| 14 | + res := (max + rnd) &^ rnd |
| 15 | + |
| 16 | + if res > math.MaxInt { |
| 17 | + // This ensures uintptr(res) overflows to a large value, |
| 18 | + // and windows.VirtualAlloc returns an error. |
| 19 | + res = math.MaxUint64 |
| 20 | + } |
| 21 | + |
| 22 | + com := res |
| 23 | + kind := windows.MEM_COMMIT |
| 24 | + if cap < max { // Commit memory only if cap=max. |
| 25 | + com = 0 |
| 26 | + kind = windows.MEM_RESERVE |
| 27 | + } |
| 28 | + |
| 29 | + // Reserve res bytes of address space, to ensure we won't need to move it. |
| 30 | + r, err := windows.VirtualAlloc(0, uintptr(res), uint32(kind), windows.PAGE_READWRITE) |
| 31 | + if err != nil { |
| 32 | + panic(err) |
| 33 | + } |
| 34 | + buf := unsafe.Slice((*byte)(unsafe.Pointer(r)), int(max)) |
| 35 | + mem := virtualMemory{addr: r, buf: buf[:com:res]} |
| 36 | + return &mem |
| 37 | +} |
| 38 | + |
| 39 | +// The slice covers the entire mmapped memory: |
| 40 | +// - len(buf) is the already committed memory, |
| 41 | +// - cap(buf) is the reserved address space. |
| 42 | +type virtualMemory struct { |
| 43 | + buf []byte |
| 44 | + addr uintptr |
| 45 | +} |
| 46 | + |
| 47 | +func (m *virtualMemory) Reallocate(size uint64) []byte { |
| 48 | + com := uint64(len(m.buf)) |
| 49 | + res := uint64(cap(m.buf)) |
| 50 | + if com < size && size <= res { |
| 51 | + // Grow geometrically, round up to the page size. |
| 52 | + rnd := uint64(windows.Getpagesize() - 1) |
| 53 | + new := com + com>>3 |
| 54 | + new = min(max(size, new), res) |
| 55 | + new = (new + rnd) &^ rnd |
| 56 | + |
| 57 | + // Commit additional memory up to new bytes. |
| 58 | + _, err := windows.VirtualAlloc(m.addr, uintptr(new), windows.MEM_COMMIT, windows.PAGE_READWRITE) |
| 59 | + if err != nil { |
| 60 | + return nil |
| 61 | + } |
| 62 | + |
| 63 | + m.buf = m.buf[:new] // Update committed memory. |
| 64 | + } |
| 65 | + // Limit returned capacity because bytes beyond |
| 66 | + // len(m.buf) have not yet been committed. |
| 67 | + return m.buf[:size:len(m.buf)] |
| 68 | +} |
| 69 | + |
| 70 | +func (m *virtualMemory) Free() { |
| 71 | + err := windows.VirtualFree(m.addr, 0, windows.MEM_RELEASE) |
| 72 | + if err != nil { |
| 73 | + panic(err) |
| 74 | + } |
| 75 | + m.addr = 0 |
| 76 | +} |
0 commit comments