Shared memory between kernel and user mode. How to

2020-06-23 09:43发布

问题:

I am trying to use shared memory between user process and kernel.

Option one - to let kernel to create section and let user mode app to open memory by name "Global\my_mem". It's working only in read-only mode. When I am trying to open section with FILE_MAP_WRITE it gives access denied(5). Not sure how to grant access or modify DACL.

Option two - pass handle back via IOCTL. This one is questionable since handle to section opened in KERNEL is 0xFFFFFFFF80001234. My understanding that handles that have any of upper bits set can not be used in user mode. Especially if app will be 32-bit :) Initially I expected that section handle will be somewhat similar to kernel file handle and I will be able to use it.

What would be the correct approach to establish shared memory channel between kernel and user mode?

回答1:

For option 1, you can specify the security descriptor assigned to the newly created object via the SecurityDescriptor member of the OBJECT_ATTRIBUTES structure.

For option 2, you would need to create an additional handle as a user handle, which you do by not specifying the OBJ_KERNEL_HANDLE flag in the OBJECT_ATTRIBUTES structure. This will only work if you open the new handle while running in the context of a thread belonging to the user application's process, e.g., while processing an IOCTL received from the user application.

Another option is for the kernel driver to map the section into the user-mode application's address space itself, using ZwMapViewOfSection.

One issue with using a section is that the driver itself can only safely access it from a system thread. If that is a problem, you can share memory directly rather than via a section. If you allocate the memory in kernel mode, you can map it into the user-mode application's address space using MmMapLockedPagesSpecifyCache.

Yet another option is for the driver to access a memory buffer allocated by the user-mode process.

The downside to either of these approaches is that the buffer (or the part of it being shared) must be locked in memory, whereas using a section allows the buffer to be pageable.



回答2:

Since you referred to 32bit app, I assume it is between a user process and a device driver - I would go with IOCTL - METHOD_IN_DIRECT (receives data in the buffer) and METHOD_OUT_DIRECT (write data into the buffer).

If shared memory is between multiple user processes and one or more device drivers - using shared Memory Object method is recommended .