Vladimir Serbinenko (phcoder@gmail.com) just uploaded a new patch set to gerrit, which you can find at http://review.coreboot.org/4278
-gerrit
commit 9f872cccfd6fe85552a9a3e2ccb3b99dfa137957 Author: Vladimir Serbinenko phcoder@gmail.com Date: Tue Nov 26 02:20:32 2013 +0100
console/vsprintf: Implement snprintf
snprintf is a safe variant of sprintf. To avoid buffer overflows we shouldn't use sprintf at all. But for now let's start by implementing snprintf in first place.
Change-Id: Ic17d94b8cd91b72f66b84b0589a06b8abef5e5c9 Signed-off-by: Vladimir Serbinenko phcoder@gmail.com --- src/console/vsprintf.c | 30 +++++++++++++++++++++++++----- src/include/string.h | 1 + 2 files changed, 26 insertions(+), 5 deletions(-)
diff --git a/src/console/vsprintf.c b/src/console/vsprintf.c index 435401b..3d085e9 100644 --- a/src/console/vsprintf.c +++ b/src/console/vsprintf.c @@ -27,14 +27,18 @@ DECLARE_SPIN_LOCK(vsprintf_lock)
static char *str_buf; +static size_t buf_limit;
static void str_tx_byte(unsigned char byte) { - *str_buf = byte; - str_buf++; + if (buf_limit) { + *str_buf = byte; + str_buf++; + buf_limit--; + } }
-static int vsprintf(char *buf, const char *fmt, va_list args) +static int vsnprintf(char *buf, size_t size, const char *fmt, va_list args) { int i;
@@ -42,8 +46,10 @@ static int vsprintf(char *buf, const char *fmt, va_list args) spin_lock(&vsprintf_lock);
str_buf = buf; + buf_limit = size ? size - 1 : 0; i = vtxprintf(str_tx_byte, fmt, args); - *str_buf = '\0'; + if (size) + *str_buf = '\0';
spin_unlock(&vsprintf_lock); ENABLE_TRACE; @@ -57,7 +63,21 @@ int sprintf(char *buf, const char *fmt, ...) int i;
va_start(args, fmt); - i = vsprintf(buf, fmt, args); + /* A trick: we have at most (size_t)-1 adressable space anyway, so + if we output so much we'll crash anyway. */ + i = vsnprintf(buf, -1, fmt, args); + va_end(args); + + return i; +} + +int snprintf(char *buf, size_t size, const char *fmt, ...) +{ + va_list args; + int i; + + va_start(args, fmt); + i = vsnprintf(buf, size, fmt, args); va_end(args);
return i; diff --git a/src/include/string.h b/src/include/string.h index 77985e1..dc125e1 100644 --- a/src/include/string.h +++ b/src/include/string.h @@ -17,6 +17,7 @@ int memcmp(const void *s1, const void *s2, size_t n); void *memchr(const void *s, int c, size_t n); #if !defined(__PRE_RAM__) int sprintf(char * buf, const char *fmt, ...); +int snprintf(char * buf, size_t size, const char *fmt, ...); #endif
// simple string functions