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>
Reviewed-on: http://review.coreboot.org/4278
Tested-by: build bot (Jenkins)
Reviewed-by: Peter Stuge <peter@stuge.se>
This commit is contained in:
Vladimir Serbinenko
2013-11-26 22:07:47 +01:00
committed by Peter Stuge
parent 697c1ed1ff
commit 4b5012a4a2
2 changed files with 29 additions and 8 deletions

View File

@ -23,28 +23,34 @@
#include <console/vtxprintf.h> #include <console/vtxprintf.h>
#include <trace.h> #include <trace.h>
struct vsprintf_context struct vsnprintf_context
{ {
char *str_buf; char *str_buf;
size_t buf_limit;
}; };
static void str_tx_byte(unsigned char byte, void *data) static void str_tx_byte(unsigned char byte, void *data)
{ {
struct vsprintf_context *ctx = data; struct vsnprintf_context *ctx = data;
*ctx->str_buf = byte; if (ctx->buf_limit) {
ctx->str_buf++; *ctx->str_buf = byte;
ctx->str_buf++;
ctx->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; int i;
struct vsprintf_context ctx; struct vsnprintf_context ctx;
DISABLE_TRACE; DISABLE_TRACE;
ctx.str_buf = buf; ctx.str_buf = buf;
ctx.buf_limit = size ? size - 1 : 0;
i = vtxdprintf(str_tx_byte, fmt, args, &ctx); i = vtxdprintf(str_tx_byte, fmt, args, &ctx);
*ctx.str_buf = '\0'; if (size)
*ctx.str_buf = '\0';
ENABLE_TRACE; ENABLE_TRACE;
@ -57,7 +63,21 @@ int sprintf(char *buf, const char *fmt, ...)
int i; int i;
va_start(args, fmt); 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); va_end(args);
return i; return i;

View File

@ -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); void *memchr(const void *s, int c, size_t n);
#if !defined(__PRE_RAM__) #if !defined(__PRE_RAM__)
int sprintf(char * buf, const char *fmt, ...); int sprintf(char * buf, const char *fmt, ...);
int snprintf(char * buf, size_t size, const char *fmt, ...);
#endif #endif
// simple string functions // simple string functions