Re: IsBadReadPtr for Linux?



John Reiser <jreiser@xxxxxxxxxxxx> writes:

Ok, I want to check if a pointer addresses a readable area of memory.

write(fd, ptr, sizeof(*ptr))

will work on any UNIX-like system, provided fd is a valid
filedescriptor that is open for writing. If the value returned is
sizeof(*ptr), then the pointer is valid for reading. If the value
returned is -1, then check 'errno'; if EFAULT, then the pointer is a
bad read pointer. If not EFAULT, then some other error is
preventing a valid analysis of *ptr.

Not quite - if the file descriptor is opened against /dev/null, then
one can pass bad pointers to write(2) and get no error. The same is
true of /dev/zero, /dev/full, all the "trivial" char devices, at least
in the Linux 2.6 kernels I've dealt with; none behaves any differently
for an invalid input address. This result is slightly nonobvious from
the man pages and standards text I've seen, so I for one was surpised.

Last time I needed this, I needed to do it in a signal handler and
without using a temporary file (which arguably shouldn't be necessary
for this). I ended up calling msync on the appropriately page
address. This does reliably return ENOMEM for pages that aren't.
With the async flag, it had no side effects to speak of, since the
process was about to dump core anyway...


--
Grant Taylor
Embedded Linux Consultant
http://www.picante.com/
.