From 91a08b6abbcfdd02d523b3f0b6fa5e8a1c8b8364 Mon Sep 17 00:00:00 2001 From: Tau Date: Wed, 7 Nov 2018 16:38:24 -0500 Subject: [PATCH] util/dprintf.c: Add debug printf --- util/dprintf.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ util/dprintf.h | 22 +++++++++++++++++ util/meson.build | 2 ++ 3 files changed, 87 insertions(+) create mode 100644 util/dprintf.c create mode 100644 util/dprintf.h diff --git a/util/dprintf.c b/util/dprintf.c new file mode 100644 index 0000000..34941f7 --- /dev/null +++ b/util/dprintf.c @@ -0,0 +1,63 @@ +#ifndef NDEBUG + +#include + +#include +#include +#include +#include + +#include "util/dprintf.h" + +static char dbg_buf[16384]; +static size_t dbg_buf_pos; + +void dprintf(const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + dprintfv(fmt, ap); + va_end(ap); +} + +void dprintfv(const char *fmt, va_list ap) +{ + dbg_buf_pos += vsnprintf_s( + dbg_buf + dbg_buf_pos, + sizeof(dbg_buf) - dbg_buf_pos, + sizeof(dbg_buf) - dbg_buf_pos - 1, + fmt, + ap); + + if (dbg_buf_pos + 1 > sizeof(dbg_buf)) { + abort(); + } + + if (strchr(dbg_buf, '\n') == NULL) { + return; + } + + OutputDebugStringA(dbg_buf); + dbg_buf_pos = 0; + dbg_buf[0] = '\0'; +} + +void dwprintf(const wchar_t *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + dwprintfv(fmt, ap); + va_end(ap); +} + +void dwprintfv(const wchar_t *fmt, va_list ap) +{ + wchar_t msg[512]; + + _vsnwprintf_s(msg, _countof(msg), _countof(msg) - 1, fmt, ap); + OutputDebugStringW(msg); +} + +#endif diff --git a/util/dprintf.h b/util/dprintf.h new file mode 100644 index 0000000..af071b1 --- /dev/null +++ b/util/dprintf.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +#ifdef __GNUC__ +#define DPRINTF_CHK __attribute__(( format(printf, 1, 2) )) +#else +#define DPRINTF_CHK +#endif + +#ifndef NDEBUG +void dprintf(const char *fmt, ...) DPRINTF_CHK; +void dprintfv(const char *fmt, va_list ap); +void dwprintf(const wchar_t *fmt, ...); +void dwprintfv(const wchar_t *fmt, va_list ap); +#else +#define dprintf(...) +#define dprintfv(fmt, ap) +#define dwprintf(...) +#define dwprintfv(fmt, ap) +#endif diff --git a/util/meson.build b/util/meson.build index ed0929d..0cedae5 100644 --- a/util/meson.build +++ b/util/meson.build @@ -7,5 +7,7 @@ util_lib = static_library( capnhook.get_variable('hook_dep'), ], sources : [ + 'dprintf.c', + 'dprintf.h', ], )