summaryrefslogtreecommitdiff
path: root/src/console
diff options
context:
space:
mode:
Diffstat (limited to 'src/console')
-rw-r--r--src/console/vsprintf.c36
1 files changed, 28 insertions, 8 deletions
diff --git a/src/console/vsprintf.c b/src/console/vsprintf.c
index 321ce81490..b1b6d475be 100644
--- a/src/console/vsprintf.c
+++ b/src/console/vsprintf.c
@@ -23,28 +23,34 @@
#include <console/vtxprintf.h>
#include <trace.h>
-struct vsprintf_context
+struct vsnprintf_context
{
char *str_buf;
+ size_t buf_limit;
};
static void str_tx_byte(unsigned char byte, void *data)
{
- struct vsprintf_context *ctx = data;
- *ctx->str_buf = byte;
- ctx->str_buf++;
+ struct vsnprintf_context *ctx = data;
+ if (ctx->buf_limit) {
+ *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;
- struct vsprintf_context ctx;
+ struct vsnprintf_context ctx;
DISABLE_TRACE;
ctx.str_buf = buf;
+ ctx.buf_limit = size ? size - 1 : 0;
i = vtxdprintf(str_tx_byte, fmt, args, &ctx);
- *ctx.str_buf = '\0';
+ if (size)
+ *ctx.str_buf = '\0';
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;