From 4d8cc8d7649a8c7b39bb20b6c4a4558705a1cf3d Mon Sep 17 00:00:00 2001 From: Wenzel Jakob Date: Tue, 7 Sep 2010 22:24:48 +0200 Subject: [PATCH] nicer snprintf() behavior --- src/libcore/logger.cpp | 17 ++++++++++++++--- src/libcore/util.cpp | 20 ++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/libcore/logger.cpp b/src/libcore/logger.cpp index 9acdcd06..b4d1565e 100644 --- a/src/libcore/logger.cpp +++ b/src/libcore/logger.cpp @@ -48,19 +48,30 @@ void Logger::log(ELogLevel level, const Class *theClass, if (level < m_logLevel) return; - char tmp[2048]; + char tmp[512], *msg = tmp; va_list iterator; va_start(iterator, fmt); - vsnprintf(tmp, 2048, fmt, iterator); + size_t size = vsnprintf(tmp, sizeof(tmp), fmt, iterator); va_end(iterator); + if (size >= sizeof(tmp)) { + /* Overflow! -- dynamically allocate memory */ + msg = new char[size+1]; + va_start(iterator, fmt); + vsnprintf(msg, size+1, fmt, iterator); + va_end(iterator); + } + if (m_formatter == NULL) { std::cerr << "PANIC: Logging has not been properly initialized!" << std::endl; exit(-1); } std::string text = m_formatter->format(level, theClass, - Thread::getThread(), tmp, file, line); + Thread::getThread(), msg, file, line); + + if (msg != tmp) + delete[] msg; if (level < EError) { m_mutex->lock(); diff --git a/src/libcore/util.cpp b/src/libcore/util.cpp index 6c25f4d9..134e074c 100644 --- a/src/libcore/util.cpp +++ b/src/libcore/util.cpp @@ -311,14 +311,26 @@ Float log2(Float value) { return std::log(value) * invLn2; } -std::string formatString(const char *pFmt, ...) { - char tmp[2048]; /* Limited to 2k */ +std::string formatString(const char *fmt, ...) { + char tmp[512]; va_list iterator; - va_start(iterator, pFmt); - vsnprintf(tmp, 2048, pFmt, iterator); + va_start(iterator, fmt); + size_t size = vsnprintf(tmp, sizeof(tmp), fmt, iterator); va_end(iterator); + if (size >= sizeof(tmp)) { + /* Overflow! -- dynamically allocate memory */ + char *dest = new char[size+1]; + va_start(iterator, fmt); + vsnprintf(dest, size+1, fmt, iterator); + va_end(iterator); + + std::string result(dest); + delete[] dest; + return result; + } + return std::string(tmp); }