Debian Codegraph @

allocator/nonmoving_unix.go

raw symbols SCIP
1 //go:build unix
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 // Round up to the page size because recommitting must be page-aligned.
17 // In practice, the WebAssembly page size should be a multiple of the system
18 // page size on most if not all platforms and rounding will never happen.
19 rnd := pageSize - 1
20 res := (max + rnd) &^ rnd
21
22 if res > math.MaxInt {
23 // This ensures int(max) overflows to a negative value,
24 // and unix.Mmap returns EINVAL.
25 res = math.MaxUint64
26 }
27
28 // Reserve max bytes of address space, to ensure we won't need to move it.
29 // A protected, private, anonymous mapping should not commit memory.
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 // The slice covers the entire mmapped memory:
38 // - len(buf) is the already committed memory,
39 // - cap(buf) is the reserved address space, which is max rounded up to a page.
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 // Round up to the page size.
50 rnd := pageSize - 1
51 newCap := (size + rnd) &^ rnd
52
53 // Commit additional memory up to new bytes.
54 err := unix.Mprotect(m.buf[com:newCap], unix.PROT_READ|unix.PROT_WRITE)
55 if err != nil {
56 return nil
57 }
58
59 // Update committed memory.
60 m.buf = m.buf[:newCap]
61 }
62 // Limit returned capacity because bytes beyond
63 // len(m.buf) have not yet been committed.
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 }