diff options
| author | sin | 2015-01-29 20:31:30 +0000 |
|---|---|---|
| committer | sin | 2015-01-29 20:31:49 +0000 |
| commit | 647c25ad9c482eeacc30f89feef49dfe265b3055 (patch) | |
| tree | 271a95bcf083dce098be896a7e56b170085ceb54 | |
| parent | 0784beab029ba53201ef93a601cb8c10d6aaca7f (diff) | |
Add read()/write() checks
| -rw-r--r-- | include/unistd.h | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/include/unistd.h b/include/unistd.h new file mode 100644 index 0000000..df74dc0 --- /dev/null +++ b/include/unistd.h | |||
| @@ -0,0 +1,49 @@ | |||
| 1 | /* See LICENSE file for copyright and license details. */ | ||
| 2 | #ifndef FORTIFY_UNISTD_H_ | ||
| 3 | #define FORTIFY_UNISTD_H_ | ||
| 4 | |||
| 5 | #include_next <unistd.h> | ||
| 6 | |||
| 7 | #if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0 && defined(__OPTIMIZE__) && __OPTIMIZE__ > 0 | ||
| 8 | |||
| 9 | #define __errordecl(name, msg) extern void name(void) __attribute__((__error__(msg))) | ||
| 10 | |||
| 11 | __errordecl(__read_error, "read: buffer overflow detected"); | ||
| 12 | static inline __attribute__ ((always_inline)) | ||
| 13 | ssize_t | ||
| 14 | __fortify_read(int fd, void *buf, size_t n) | ||
| 15 | { | ||
| 16 | size_t bos = __builtin_object_size(buf, 0); | ||
| 17 | |||
| 18 | if (__builtin_constant_p(n) && n > bos) | ||
| 19 | __read_error(); | ||
| 20 | |||
| 21 | if (n > bos) | ||
| 22 | __builtin_trap(); | ||
| 23 | return read(fd, buf, n); | ||
| 24 | } | ||
| 25 | |||
| 26 | __errordecl(__write_error, "write: buffer overflow detected"); | ||
| 27 | static inline __attribute__ ((always_inline)) | ||
| 28 | ssize_t | ||
| 29 | __fortify_write(int fd, void *buf, size_t n) | ||
| 30 | { | ||
| 31 | size_t bos = __builtin_object_size(buf, 0); | ||
| 32 | |||
| 33 | if (__builtin_constant_p(n) && n > bos) | ||
| 34 | __write_error(); | ||
| 35 | |||
| 36 | if (n > bos) | ||
| 37 | __builtin_trap(); | ||
| 38 | return write(fd, buf, n); | ||
| 39 | } | ||
| 40 | |||
| 41 | #undef read | ||
| 42 | #define read(fd, buf, n) __fortify_read(fd, buf, n) | ||
| 43 | |||
| 44 | #undef write | ||
| 45 | #define write(fd, buf, n) __fortify_write(fd, buf, n) | ||
| 46 | |||
| 47 | #endif | ||
| 48 | |||
| 49 | #endif | ||
