For debugging purposes I need to test a pointer to see if it points to a valid readable page. Currently I am parsing /proc/[pid]/maps to see if the address is mapped ok, but this seems a bit long-winded. Is there a better way? Thanks.
Asked
Active
Viewed 6,541 times
22
-
1I'm doing it parsing `/proc/self/maps` as well – Gregory Pakosz Aug 20 '11 at 21:04
-
@GregoryPakosz: For that to be a generic & reliable solution, wouldn't it require reloading and reparsing the map on every check to account for things like a growing heap or newly mapped-in memory segments? – etherice Apr 20 '13 at 18:07
-
@etherice: No because /proc is self-refreshing; every time you access a /proc file(s), kernel code runs that regenerates it's "content". – kaiwan Oct 10 '16 at 04:27
-
@etherice I believe that is correct. Any solution to this will be fundamentally unreliable in the presence of parallelism, interrupts or faulty hardware. There is a time-of-check to time-of-use race window ([CWE-367](https://cwe.mitre.org/data/definitions/367.html)). The memory pointed to by the address can be unmapped, protected or poisoned between checking the address and using it. – Richard Palethorpe Sep 28 '21 at 14:00
-
check this article: https://renatocunha.com/2015/12/msync-pointer-validity/ – TingQian LI Apr 20 '23 at 00:26
1 Answers
20
The canonical way is to use the write()
system call to read from the page (writing to a dummy pipe()
file descriptor). Instead of faulting, it will return -1
with errno == EFAULT
if the buffer passed to write()
is unreadable.

caf
- 233,326
- 40
- 323
- 462
-
7Warning: Have seen at least one other SO solution suggest using /dev/null for this purpose (http://stackoverflow.com/questions/4611776/isbadreadptr-analogue-on-unix), but newer kernels (I tested on 3.8.7) return success for /dev/null write() even if 'buf' is NULL. So while this test might work with /dev/null on whichever system you're testing on, it's definitely not a portable solution. Using some other fd (like a dummy pipe or posix shm object) would not be as fast but it would definitely be safer and more portable. – etherice Apr 20 '13 at 18:25