mmap_unix.go

 1//go:build (linux || darwin || freebsd || netbsd || dragonfly || solaris) && !tinygo
 2
 3package platform
 4
 5import (
 6	"syscall"
 7)
 8
 9const (
10	mmapProtAMD64 = syscall.PROT_READ | syscall.PROT_WRITE | syscall.PROT_EXEC
11	mmapProtARM64 = syscall.PROT_READ | syscall.PROT_WRITE
12)
13
14func munmapCodeSegment(code []byte) error {
15	return syscall.Munmap(code)
16}
17
18// mmapCodeSegmentAMD64 gives all read-write-exec permission to the mmap region
19// to enter the function. Otherwise, segmentation fault exception is raised.
20func mmapCodeSegmentAMD64(size int) ([]byte, error) {
21	// The region must be RWX: RW for writing native codes, X for executing the region.
22	return mmapCodeSegment(size, mmapProtAMD64)
23}
24
25// mmapCodeSegmentARM64 cannot give all read-write-exec permission to the mmap region.
26// Otherwise, the mmap systemcall would raise an error. Here we give read-write
27// to the region so that we can write contents at call-sites. Callers are responsible to
28// execute MprotectRX on the returned buffer.
29func mmapCodeSegmentARM64(size int) ([]byte, error) {
30	// The region must be RW: RW for writing native codes.
31	return mmapCodeSegment(size, mmapProtARM64)
32}