Debian Codegraph @

internal/buffer/buffer_mmap.go

raw
1 //go:build !purego && (aix || android || darwin || dragonfly || freebsd || illumos || ios || linux || netbsd || openbsd || plan9 || solaris)
2 // +build !purego
3 // +build aix android darwin dragonfly freebsd illumos ios linux netbsd openbsd plan9 solaris
4
5 // TODO: replace the above with go:build unix once Go 1.19 is the lowest
6 // supported version
7
8 package buffer
9
10 import (
11 "golang.org/x/sys/unix"
12 )
13
14 type Buffer struct {
15 n int
16 pg int
17 mmap []byte
18 }
19
20 func New(n int) (Buffer, error) {
21 pg := unix.Getpagesize()
22 full := ((n+(pg-1))/pg + 2) * pg
23
24 b, err := unix.Mmap(-1, 0, full, unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
25 if err != nil {
26 return Buffer{}, err
27 }
28
29 if n > 0 {
30 err = unix.Mprotect(b[pg:full-pg], unix.PROT_READ|unix.PROT_WRITE)
31 if err != nil {
32 unix.Munmap(b)
33 return Buffer{}, err
34 }
35 }
36
37 return Buffer{
38 n: n,
39 pg: pg,
40 mmap: b,
41 }, nil
42 }
43
44 func (a *Buffer) ProtectHead() []byte {
45 head := a.pg
46 return a.mmap[head : head+a.n : head+a.n]
47 }
48
49 func (a *Buffer) ProtectTail() []byte {
50 tail := len(a.mmap) - a.pg - a.n
51 return a.mmap[tail : tail+a.n : tail+a.n]
52 }
53
54 func (a *Buffer) Release() {
55 unix.Munmap(a.mmap)
56 }