forked from portalgun-io/mmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmap_unix.go
88 lines (70 loc) · 1.37 KB
/
mmap_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// +build darwin linux
package mmap
import (
"unsafe"
"golang.org/x/sys/unix"
)
var (
errEAGAIN error = unix.EAGAIN
errEINVAL error = unix.EINVAL
errENOENT error = unix.ENOENT
)
func errnoErr(e unix.Errno) error {
switch e {
case 0:
return nil
case unix.EAGAIN:
return errEAGAIN
case unix.EINVAL:
return errEINVAL
case unix.ENOENT:
return errENOENT
default:
return e
}
}
func mmap(fd uintptr, size int, write bool) ([]byte, error) {
if size <= 0 {
return nil, errEINVAL
}
var (
prot = unix.PROT_READ
flag = unix.MAP_SHARED
)
if write {
prot = prot | unix.PROT_WRITE
}
r0, _, e1 := unix.Syscall6(unix.SYS_MMAP, 0, uintptr(size), uintptr(prot), uintptr(flag), fd, 0)
if e1 != 0 {
return nil, errnoErr(e1)
}
addr := uintptr(r0)
slice := struct {
addr uintptr
len int
cap int
}{addr, size, size}
data := *(*[]byte)(unsafe.Pointer(&slice))
return data, nil
}
func munmap(data []byte) error {
if len(data) == 0 || len(data) != cap(data) {
return errEINVAL
}
addr := uintptr(unsafe.Pointer(&data[0]))
size := uintptr(len(data))
_, _, e1 := unix.Syscall(unix.SYS_MUNMAP, addr, size, 0)
if e1 != 0 {
return errnoErr(e1)
}
return nil
}
func msync(data []byte, wait bool) error {
flags := unix.MS_INVALIDATE
if wait {
flags = flags | unix.MS_SYNC
} else {
flags = flags | unix.MS_ASYNC
}
return unix.Msync(data, flags)
}