Reputation: 41
I've created some code to write memory to another process on the system, but mach_vm_write() fails with the "(os/kern) invalid address" error, despite the address seemingly being valid. My code is below.
if ((kret = task_for_pid(mach_task_self(), pid, &task)) == KERN_SUCCESS)
{
//this succeeds with the correct value.
if ((kret = get_task_base(task, &base)) == KERN_SUCCESS)
{
char patch_1[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
mach_vm_address_t address_1 = base + 0x77777;
//this also succeeds
if ((kret = mach_vm_protect(task, address_1, 6, TRUE, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)) == KERN_SUCCESS)
{
//fails with "(os/kern) invalid address" despite using the same value as the previous mach_vm_protect() call.
if ((kret = mach_vm_write(task, address_1, (vm_offset_t)&patch_1, 6)) == KERN_SUCCESS)
{
}
else printf("mach_vm_write failed w/ error %d: %s\n", kret, mach_error_string(kret));
}
else printf("mach_vm_protect failed w/ error %d: %s\n", kret, mach_error_string(kret));
}
else printf("mach_vm_region_recurse failed w/ error %d: %s\n", kret, mach_error_string(kret));
}
else printf("task_for_pid failed w/ error %d: %s\n", kret, mach_error_string(kret));
Upvotes: 2
Views: 1435
Reputation: 41
Turns out the reason mach_vm_write() was failing was that my mach_vm_protect() call was setting the maximum protection. The call should have looked like this:
mach_vm_protect(task, address_1, 6, FALSE, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)
Upvotes: 2