From 45b09c03877119fb32df0594ab70cf43259b5877 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Holm?= Date: Sat, 5 Aug 2017 00:03:09 +0200 Subject: [PATCH] Avoid array-out-of-bounds when building in sourcedir subdir. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The type of errors avoided looks like this. ../src/common.c:2250:9: bemærk: in expansion of macro »ILOG« ILOG("Ignoring %d bytes of 0x%02x at end of file\n", num_empty, erased_pattern); ^~~~ --- CMakeLists.txt | 3 ++- include/stlink/logging.h | 2 +- src/logging.c | 25 +++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 46790de91..ecf64e358 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,7 +48,6 @@ endif() # fixup __FILE__ absolute paths in logging module # see: https://cmake.org/pipermail/cmake-developers/2015-January/024202.html string(LENGTH "${CMAKE_SOURCE_DIR}/" CMAKE_SOURCE_DIR_LENGTH) -add_definitions(-DCMAKE_SOURCE_DIR_LENGTH=${CMAKE_SOURCE_DIR_LENGTH}) set(STLINK_HEADERS include/stlink.h @@ -69,6 +68,8 @@ set(STLINK_SOURCE src/flash_loader.c ) +set_source_files_properties( src/logging.c PROPERTIES COMPILE_FLAGS "-DCMAKE_SOURCE_DIR=\"${CMAKE_SOURCE_DIR}\" -DCMAKE_BINARY_DIR=\"${CMAKE_BINARY_DIR}\"") + if (WIN32 OR MSYS OR MINGW) set (STLINK_SOURCE "${STLINK_SOURCE};src/mmap.c;src/mingw/mingw.c") endif () diff --git a/include/stlink/logging.h b/include/stlink/logging.h index 9a98a6bc5..7a5443ac6 100644 --- a/include/stlink/logging.h +++ b/include/stlink/logging.h @@ -23,7 +23,7 @@ int ugly_log(int level, const char *tag, const char *format, ...); #ifndef CMAKE_SOURCE_DIR_LENGTH #define CMAKE_SOURCE_DIR_LENGTH 0 #endif -#define UGLY_LOG_FILE (__FILE__+CMAKE_SOURCE_DIR_LENGTH) +#define UGLY_LOG_FILE __FILE__ /** @todo we need to write this in a more generic way, for now this should compile on visual studio (See http://stackoverflow.com/a/8673872/1836746) */ diff --git a/src/logging.c b/src/logging.c index 1f51900b5..5025fa3c5 100644 --- a/src/logging.c +++ b/src/logging.c @@ -8,13 +8,37 @@ #include #include #include +#include #include "stlink/logging.h" static int max_level = UINFO; +#define TOSTR(s) #s +#define STR(s) TOSTR(s) + +static const char* source_dir = STR(CMAKE_SOURCE_DIR); +static const char* build_dir = STR(CMAKE_BINARY_DIR); +static int tagskip = 0; + int ugly_init(int maximum_threshold) { max_level = maximum_threshold; + tagskip = 0; + + // If build_dir is a subdir of source_dir + if (strstr(build_dir, source_dir) != 0) { + int len = strlen(source_dir); + if (build_dir[len] == '/') { + for (unsigned idx=len; idx max_level) { return 0; } + tag += tagskip; va_list args; va_start(args, format); time_t mytt = time(NULL);