Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

66 lines
2.3 KiB

  1. #ifndef RANGECHECK_H
  2. #define RANGECHECK_H
  3. #include <stddef.h>
  4. /* return 0 for range error / overflow, 1 for ok */
  5. #if defined(__GNUC__) && defined(__OPTIMIZE__)
  6. #define __static extern
  7. #else
  8. #define __static static
  9. #endif
  10. /* does ptr point to one of buf[0], buf[1], ... buf[len-1]? */
  11. __static inline int range_ptrinbuf(const void* buf,size_t len,const void* ptr) {
  12. register const char* c=(const char*)buf; /* no pointer arithmetic on void* */
  13. return (c && /* is buf non-NULL? */
  14. #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 1)
  15. ((size_t)c)+len>(size_t)c && /* gcc 4.1 miscompiles this test */
  16. #else
  17. c+len>c && /* catch integer overflows and fail if buffer is 0 bytes long */
  18. /* because then ptr can't point _in_ the buffer */
  19. #endif
  20. (size_t)((const char*)ptr-c)<len); /* this one is a little tricky.
  21. "ptr-c" checks the offset of ptr in the buffer is inside the buffer size.
  22. Now, ptr-c can underflow; say it is -1. When we cast it to size_t, it becomes
  23. a very large number. */
  24. }
  25. /* Is this a plausible buffer?
  26. * Check whether buf is NULL, and whether buf+len overflows.
  27. * Does NOT check whether buf has a non-zero length! */
  28. __static inline int range_validbuf(const void* buf,size_t len) {
  29. #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 1)
  30. return (buf && (size_t)buf+len>=(size_t)buf); /* gcc 4.1 miscompiles this test */
  31. #else
  32. return (buf && (const char*)buf+len>=(const char*)buf);
  33. #endif
  34. }
  35. /* is buf2[0..len2-1] inside buf1[0..len-1]? */
  36. __static inline int range_bufinbuf(const void* buf1,size_t len1,const void* buf2,size_t len2) {
  37. return range_validbuf(buf1,len1) &&
  38. range_validbuf(buf2,len2) &&
  39. buf1<=buf2 &&
  40. (ptrdiff_t)buf1+len1>=(ptrdiff_t)buf2+len2;
  41. }
  42. /* does an array of "elements" members of size "membersize" starting at
  43. * "arraystart" lie inside buf1[0..len-1]? */
  44. int range_arrayinbuf(const void* buf1,size_t len,
  45. const void* arraystart,size_t elements,size_t membersize);
  46. /* does an ASCIIZ string starting at "ptr" lie in buf[0..len-1]? */
  47. int range_strinbuf(const void* buf,size_t len,const void* stringstart);
  48. /* does an UTF-16 string starting at "ptr" lie in buf[0..len-1]? */
  49. int range_str2inbuf(const void* buf,size_t len,const void* stringstart);
  50. /* does an UTF-32 string starting at "ptr" lie in buf[0..len-1]? */
  51. int range_str4inbuf(const void* buf,size_t len,const void* stringstart);
  52. #undef __static
  53. #endif