This patch is intended as a companion to the “Adding buffer overflow detection to string functions” blog post: It is relative to libbsd 0.8.3 (commit 9bed430ee30e677d8774e4feba8707507979d62b). diff --git a/include/bsd/string.h b/include/bsd/string.h index ee2f953..987abb7 100644 --- a/include/bsd/string.h +++ b/include/bsd/string.h @@ -43,6 +43,18 @@ char *strnstr(const char *str, const char *find, size_t str_len); void strmode(mode_t mode, char *str); void explicit_bzero(void *buf, size_t len); + +#if defined(__GNUC__) && defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0 +size_t libbsd_strlcpy_chk(char *dst, const char *src, + size_t siz, size_t dstsiz); +extern __inline__ __attribute__((__always_inline__, __artificial__)) +size_t +strlcpy(char *dst, const char *src, size_t siz) +{ + return libbsd_strlcpy_chk(dst, src, siz, __builtin_object_size(dst, 1)); +} +#endif + __END_DECLS #endif diff --git a/src/Makefile.am b/src/Makefile.am index ad83dbf..7ed20ee 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -86,8 +86,10 @@ libbsd_la_SOURCES = \ heapsort.c \ humanize_number.c \ inet_net_pton.c \ + libbsd_strlcpy_chk.c \ local-elf.h \ local-link.h \ + local-string.h \ merge.c \ nlist.c \ pidfile.c \ diff --git a/src/libbsd.map b/src/libbsd.map index 2b9a3db..5016f50 100644 --- a/src/libbsd.map +++ b/src/libbsd.map @@ -136,3 +136,7 @@ LIBBSD_0.7 { LIBBSD_0.8 { explicit_bzero; } LIBBSD_0.7; + +LIBBSD_0.9 { + libbsd_strlcpy_chk; +} LIBBSD_0.8; diff --git a/src/libbsd_strlcpy_chk.c b/src/libbsd_strlcpy_chk.c new file mode 100644 index 0000000..588f5a0 --- /dev/null +++ b/src/libbsd_strlcpy_chk.c @@ -0,0 +1,10 @@ +#include "local-string.h" +#include + +size_t +libbsd_strlcpy_chk(char *dst, const char *src, size_t siz, size_t dstsiz) +{ + if (siz > dstsiz) + abort(); + return libbsd_strlcpy_local(dst, src, siz); +} diff --git a/src/local-string.h b/src/local-string.h new file mode 100644 index 0000000..ee381d2 --- /dev/null +++ b/src/local-string.h @@ -0,0 +1,9 @@ +#ifndef LIBBSD_LOCAL_STRING_H +#define LIBBSD_LOCAL_STRING_H + +#include + +size_t libbsd_strlcpy_local(char *dst, const char *src, size_t siz) + __attribute__ ((visibility ("hidden"))); + +#endif diff --git a/src/strlcpy.c b/src/strlcpy.c index 1719d35..048765a 100644 --- a/src/strlcpy.c +++ b/src/strlcpy.c @@ -17,15 +17,15 @@ */ #include -#include +#include "local-string.h" /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ -size_t -strlcpy(char *dst, const char *src, size_t siz) +size_t __attribute__ ((alias("strlcpy"))) +libbsd_strlcpy_local(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; @@ -49,3 +49,6 @@ strlcpy(char *dst, const char *src, size_t siz) return(s - src - 1); /* count does not include NUL */ } + +size_t strlcpy(char *dst, const char *src, size_t siz) + __attribute__ ((alias("libbsd_strlcpy_local")));