mach_vm_write与(os / kern)无效地址失败

时间:2018-04-02 19:17:36

标签: c macos kernel

我已经创建了一些代码来将内存写入系统上的另一个进程,但是mach_vm_write()失败了"(os / kern)无效地址"错误,尽管地址看似有效。我的代码如下。

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));

1 个答案:

答案 0 :(得分:1)

原来,mach_vm_write()失败的原因是我的mach_vm_protect()调用正在设置最大保护。 电话应该是这样的:

mach_vm_protect(task, address_1, 6, FALSE, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE)