Search code examples
clinuxmemorylinux-kernelxnu

About accessing userspace memory from kernel


I'm doing kext development at XNU kernel, there is KPI function called copyin and its friends, similar to copy_from_user at Linux kernel

So I'm using copyin at most time, it's more secure processing data at kernelspace rather than relatively volatile userspace, but sometime i need process a quite large amount of memory(eg 2MB) from userspace, and i only need to read, could that be a excuse for directly access userspace memory ? (could that cause unexpected problem?)

The data from userspace has entries, so i only need read at least each time, besides I don't need to do any write on this memory neither from userspace process, I list three ways that just i could think about, hope someone could give me advice, i am really appreciate that!

  1. Alloc enough size pageable memory (IOMallocPageable) at kernel space, and calling copyin to copy the whole data from userspace
  2. Alloc also alloc pageable memory, and size is enough for one entry, use copyin to read and process then read again to same memory
  3. Use stac disable smap, directly read from userspace

First way, if i don't do writing, could that be mapping to same physical map, so doesn't need waster memory? Which way is more efficiency?


Solution

  • If you have the userspace address you can remap it to kernel - use IOMemoryDescriptor::withAddressRange with the relevant task (process task) and map it to kernel with IOMemoryDescriptor::createMappingInTask.

    Make sure the permissions are correct.

    Just a friendly tip - the stac/clac instructions are overwritten by the context switch code handler and you will have to make sure it's not being called during your copying phase. Done it - not very fun.