我正在嘗試動態分配記憶體并使其可以通過 mach_vm_protect 執行;但是,每當我嘗試執行應用程式崩潰的代碼時。但是 mach_vm_protect 成功了,這是我不明白的。
#include <stdio.h>
#include <unistd.h>
#include <mach/mach_init.h>
#include <mach/vm_map.h>
#include <mach/mach_vm.h>
int test(int x, int y){
return x y;
}
typedef int (*test_mach_copy)(int,int);
#define CODE_SIZE 0x17
int main()
{
mach_vm_address_t remoteCode64 = (vm_address_t) NULL;
mach_vm_address_t testvmaddr = (vm_address_t)&test;
task_t remotetask;
task_for_pid(mach_task_self(), getpid(), &remotetask);
if (mach_vm_protect(remotetask, testvmaddr, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
return 1;
}
if(mach_vm_allocate(remotetask,&remoteCode64,CODE_SIZE,VM_FLAGS_ANYWHERE)!=KERN_SUCCESS){
return 1;
}
if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) {
return 1;
}
mach_vm_copy(remotetask, testvmaddr, CODE_SIZE, remoteCode64);
test_mach_copy tmc = (test_mach_copy)remoteCode64;
int x = tmc(10,20);
printf("%d\n",x);
return 0;
}
x017 大小是否正確 sizeof(test())
uj5u.com熱心網友回復:
問題可能是您使用VM_PROT_READ|VM_PROT_EXECUTE|VM_PROT_WRITE|VM_PROT_COPY. 現代作業系統和架構試圖強制執行W^X權限。也就是說,記憶體范圍要么是可執行的,要么是可寫的,但絕不是兩者兼而有之。
mach_vm_protect由于您的呼叫正在回傳,因此內核中可能存在錯誤KERN_SUCCESS。
mach_vm_protect我只需連續兩次呼叫即可使您的代碼正常作業:
int main()
{
mach_vm_address_t remoteCode64 = (vm_address_t) NULL;
mach_vm_address_t testvmaddr = (vm_address_t)&test;
task_t remotetask;
task_for_pid(mach_task_self(), getpid(), &remotetask);
if (mach_vm_protect(remotetask, testvmaddr, CODE_SIZE, 1, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
return 1;
}
if(mach_vm_allocate(remotetask,&remoteCode64,CODE_SIZE,VM_FLAGS_ANYWHERE)!=KERN_SUCCESS){
return 1;
}
if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 0, VM_PROT_READ|VM_PROT_WRITE|VM_PROT_COPY)!=KERN_SUCCESS) {
return 1;
}
if (mach_vm_copy(remotetask, testvmaddr, CODE_SIZE, remoteCode64) != KERN_SUCCESS) {
return 1;
}
if (mach_vm_protect(remotetask, remoteCode64, CODE_SIZE, 0, VM_PROT_READ|VM_PROT_EXECUTE)!=KERN_SUCCESS) {
return 1;
}
test_mach_copy tmc = (test_mach_copy)remoteCode64;
int x = tmc(10,20);
printf("%d\n",x);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431174.html
