Skip to content

Commit

Permalink
Mprotect
Browse files Browse the repository at this point in the history
  • Loading branch information
lemon-mint committed Oct 14, 2021
1 parent 2c6a1bc commit 72278ba
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
21 changes: 21 additions & 0 deletions memory/mprotect_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris

package memory

import "syscall"

func mprotect(addr uintptr, len uintptr, prot int) (err error) {
var data reflect.SliceHeader
data.Data = addr
data.Len = int(size)
data.Cap = int(size)
var byteslice []byte = *(*[]byte)(unsafe.Pointer(&data))
err = syscall.Mprotect(byteslice, prot)
return
}

var ReadOnly = syscall.PROT_READ
var ReadWrite = syscall.PROT_READ | syscall.PROT_WRITE
var Execute = syscall.PROT_EXEC
var ExecuteRead = syscall.PROT_EXEC | syscall.PROT_READ
var ExecuteReadWrite = syscall.PROT_EXEC | syscall.PROT_READ | syscall.PROT_WRITE
35 changes: 35 additions & 0 deletions memory/mprotect_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//go:build windows

package memory

import (
"fmt"
"syscall"
"unsafe"
)

var kernel32 = syscall.NewLazyDLL("kernel32.dll")
var procVirtualProtect = kernel32.NewProc("VirtualProtect")

var ErrVirtualProtect = fmt.Errorf("virtualprotect failed")

func mprotect(addr uintptr, size uintptr, prot int) (err error) {
var oldprot uint32

ret, _, _ := procVirtualProtect.Call(
uintptr(addr),
uintptr(size),
uintptr(prot),
uintptr(unsafe.Pointer(&oldprot)),
)
if ret > 0 {
return nil
}
return ErrVirtualProtect
}

var ReadOnly = 0x02
var ReadWrite = 0x04
var Execute = 0x10
var ExecuteRead = 0x20
var ExecuteReadWrite = 0x40
17 changes: 17 additions & 0 deletions memory/page.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package memory

import "syscall"

var pagesize uintptr = uintptr(syscall.Getpagesize())

func GetPageHead(ptr uintptr) uintptr {
return pagesize * (ptr / pagesize)
}

func NextPageHead(curpage uintptr) uintptr {
return curpage + pagesize
}

func Mprotect(ptr uintptr, size uintptr, prot int) error {
return mprotect(ptr, size, prot)
}

0 comments on commit 72278ba

Please sign in to comment.