| 1 |
|
| 2 |
|
| 3 |
package allocator |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"math" |
| 8 |
|
| 9 |
"github.com/tetratelabs/wazero/experimental" |
| 10 |
"golang.org/x/sys/unix" |
| 11 |
) |
| 12 |
|
| 13 |
var pageSize = uint64(unix.Getpagesize()) |
| 14 |
|
| 15 |
func alloc(_, max uint64) experimental.LinearMemory { |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
rnd := pageSize - 1 |
| 20 |
res := (max + rnd) &^ rnd |
| 21 |
|
| 22 |
if res > math.MaxInt { |
| 23 |
|
| 24 |
|
| 25 |
res = math.MaxUint64 |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
b, err := unix.Mmap(-1, 0, int(res), unix.PROT_NONE, unix.MAP_PRIVATE|unix.MAP_ANON) |
| 31 |
if err != nil { |
| 32 |
panic(fmt.Errorf("allocator_unix: failed to reserve memory: %w", err)) |
| 33 |
} |
| 34 |
return &mmappedMemory{buf: b[:0]} |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
type mmappedMemory struct { |
| 41 |
buf []byte |
| 42 |
} |
| 43 |
|
| 44 |
func (m *mmappedMemory) Reallocate(size uint64) []byte { |
| 45 |
com := uint64(len(m.buf)) |
| 46 |
res := uint64(cap(m.buf)) |
| 47 |
|
| 48 |
if com < size && size <= res { |
| 49 |
|
| 50 |
rnd := pageSize - 1 |
| 51 |
newCap := (size + rnd) &^ rnd |
| 52 |
|
| 53 |
|
| 54 |
err := unix.Mprotect(m.buf[com:newCap], unix.PROT_READ|unix.PROT_WRITE) |
| 55 |
if err != nil { |
| 56 |
return nil |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
m.buf = m.buf[:newCap] |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
return m.buf[:size:len(m.buf)] |
| 65 |
} |
| 66 |
|
| 67 |
func (m *mmappedMemory) Free() { |
| 68 |
err := unix.Munmap(m.buf[:cap(m.buf)]) |
| 69 |
if err != nil { |
| 70 |
panic(fmt.Errorf("allocator_unix: failed to release memory: %w", err)) |
| 71 |
} |
| 72 |
m.buf = nil |
| 73 |
} |