Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a memory mapped device in C in userspace

I wish to mock a memory mapped device in C in order to do effective unit testing of a device wrapping library (in Linux).

Now, I know I can mmap a file descriptor into userspace which could in principle represent a mock of said device.

So, AFAICT, my question comes down to this: Is it possible in userspace to create a file descriptor on which mmap can act, with the reading and writing being handled by suitable callbacks?

Alternatively, perhaps this is a solved problem and there is a known kernel driver that can be hooked into?

like image 634
Henry Gomersall Avatar asked Oct 25 '25 05:10

Henry Gomersall


1 Answers

Considering it's a Linux system, you can implement a very simple FUSE filesystem with just one file on it. The kernel can handle it from there.

The main issue is that you can expect the kernel to not flush every write. There's a msync() call to flush all outstanding writes, though, but your System Under Test isn't going to call that. However, I think you can get away with opening the file descriptor using O_DIRECT | O_DSYNC

like image 54
MSalters Avatar answered Oct 26 '25 20:10

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!