Skip to content

Commit 5bad8a5

Browse files
committed
Implement mprotect function for Windows.
Fixes go-qml#79.
1 parent 364da65 commit 5bad8a5

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

all.cpp

+4
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,7 @@
66
#include "cpp/connector.cpp"
77

88
#include "cpp/moc_all.cpp"
9+
10+
#ifdef _WIN32
11+
#include "cpp/mmemwin.cpp"
12+
#endif

cpp/mmemwin.cpp

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <windows.h>
2+
3+
#define protREAD 1
4+
#define protWRITE 2
5+
#define protEXEC 4
6+
7+
extern "C" {
8+
9+
int mprotect(void *addr, size_t len, int prot)
10+
{
11+
DWORD wprot = 0;
12+
if (prot & protWRITE) {
13+
wprot = PAGE_READWRITE;
14+
} else if (prot & protREAD) {
15+
wprot = PAGE_READ;
16+
}
17+
if (prot & protEXEC) {
18+
wprot <<= 4;
19+
}
20+
DWORD oldwprot;
21+
if (!VirtualProtect(addr, len, wprot, &oldwprot)) {
22+
return -1;
23+
}
24+
return 0;
25+
}
26+
27+
} // extern "C"

testing.go

+10-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package qml
22

3-
// #include <sys/mman.h>
3+
// #include <stdlib.h>
4+
// int mprotect(void *addr, size_t len, int prot);
45
import "C"
56

67
import (
@@ -27,6 +28,12 @@ func SetupTesting() {
2728
fset(ptr(tmain), ptr(tstub), mmain)
2829
}
2930

31+
const (
32+
protREAD = 1
33+
protWRITE = 2
34+
protEXEC = 4
35+
)
36+
3037
func fset(target, old, new uintptr) {
3138
pageOffset := target % pageSize
3239
pageAddr := target - pageOffset
@@ -44,8 +51,8 @@ func fset(target, old, new uintptr) {
4451
binary.LittleEndian.PutUint64(newAddr, uint64(new))
4552

4653
// BSD's syscall package misses Mprotect. Use cgo instead.
47-
C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), C.PROT_EXEC|C.PROT_READ|C.PROT_WRITE)
48-
defer C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), C.PROT_EXEC|C.PROT_READ)
54+
C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), protEXEC|protREAD|protWRITE)
55+
defer C.mprotect(unsafe.Pointer(pageAddr), C.size_t(len(mem)), protEXEC|protREAD)
4956

5057
delta := make([]byte, 4)
5158
for i, c := range mem[pageOffset:] {

0 commit comments

Comments
 (0)