agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.93k stars 179 forks source link

panic: permission denied #48

Closed dgofman closed 2 years ago

dgofman commented 3 years ago

I have implemented monkey_arm64.go jmpToFunctionValue. Now trying to compile and execute my code on a Mac M1. I am getting an exception when making a call to syscall.Mprotect (syscall.PROT_WRITE). Do you know how to fix this problem?

func mprotectCrossPage(addr uintptr, length int, prot int) {
    pageSize := syscall.Getpagesize()
    for p := pageStart(addr); p < addr+uintptr(length); p += uintptr(pageSize) {
        page := rawMemoryAccess(p, pageSize)

            err := syscall.Mprotect(page, prot) //syscall.PROT_READ|syscall.PROT_WRITE|syscall.PROT_EXEC

        if err != nil {
            panic(err)
        }
    }
}
func jmpToFunctionValue(to uintptr) []byte {
    /*return []byte{
        0x48, 0xBA,
        byte(to),
        byte(to >> 8),
        byte(to >> 16),
        byte(to >> 24),
        byte(to >> 32),
        byte(to >> 40),
        byte(to >> 48),
        byte(to >> 56), // movabs rdx,to
        0xFF, 0x22,     // jmp QWORD PTR [rdx]
    }*/
    raw := []uint32{
        uint32((((to) & 0xffff) << 5) | 0xD2800000),       // MOVZ X0, <bytes 0,1>
        uint32((((to >> 16) & 0xffff) << 5) | 0xF2A00000), // MOVK X0, <bytes 2,4>, LSL 16
        uint32((((to >> 32) & 0xffff) << 5) | 0xF2C00000), // MOVK X0, <bytes 4,5>, LSL 32
        uint32((((to >> 48) & 0xffff) << 5) | 0xF2E00000), // MOVK X0, <bytes 6,7>, LSL 48
        0xD63F0000, // BLR X0
    }

    // Get the slice header
    header := *(*reflect.SliceHeader)(unsafe.Pointer(&raw))

    header.Len *= 4 // 4 bytes in uint32
    header.Cap *= 4 // 4 bytes in uint32

    // Convert slice header to an []byte
    data := *(*[]byte)(unsafe.Pointer(&header))
    return data
}
dgofman commented 3 years ago

It looks like this is a bug

https://developer.apple.com/forums/thread/672804

https://gitlab.com/qemu-project/qemu/-/commit/c118881ee607dcac

https://github.com/zherczeg/sljit/issues/99

agiledragon commented 3 years ago

Please refer to this issue that has been closed, https://github.com/agiledragon/gomonkey/issues/10.

agiledragon commented 2 years ago

Arm64 is fully supported in the v2.2.0.