From e05e9ff1431e048f9918903b3340552727dc9ce3 Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Fri, 7 Feb 2020 13:41:14 +0100 Subject: [PATCH] sys: implement lol::sys::getenv() for safety. --- src/base/features.cpp | 3 +-- src/base/log.cpp | 3 +-- src/lol/sys/init.h | 19 +++++++++++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/base/features.cpp b/src/base/features.cpp index e5f178e7..f4b87d5c 100644 --- a/src/base/features.cpp +++ b/src/base/features.cpp @@ -17,8 +17,7 @@ namespace lol bool has_threads() { - static char const *var = getenv("LOL_NOTHREADS"); - static bool const disable_threads = var && var[0]; + static bool const disable_threads = sys::getenv("LOL_NOTHREADS").size() > 0; #if defined __EMSCRIPTEN__ && !defined __EMSCRIPTEN_PTHREADS__ // For some reason hardware_concurrency() will return the actual number // of threads/cores even though the system cannot spawn threads. diff --git a/src/base/log.cpp b/src/base/log.cpp index 415096c0..b9cdf7c4 100644 --- a/src/base/log.cpp +++ b/src/base/log.cpp @@ -80,8 +80,7 @@ void msg::helper(message_type type, char const *fmt, va_list ap) #if !defined LOL_BUILD_DEBUG && !_DEBUG if (type == message_type::debug) { - static char const *var = getenv("LOL_DEBUG"); - static bool const disable_debug = !var || !var[0]; + static bool const disable_debug = sys::getenv("LOL_DEBUG").size() > 0; if (disable_debug) return; } diff --git a/src/lol/sys/init.h b/src/lol/sys/init.h index 8571bb34..8da3efa0 100644 --- a/src/lol/sys/init.h +++ b/src/lol/sys/init.h @@ -19,6 +19,7 @@ #include #include +#include namespace lol { @@ -56,6 +57,24 @@ extern void init(int argc, char *argv[], extern void add_data_dir(std::string const &dir); extern array get_path_list(std::string const &file); +static inline std::string getenv(std::string const &var) +{ +#if _MSC_VER + char *buf = nullptr; + size_t count = 0; + if (_dupenv_s(&buf, &count, var.c_str()) == 0 && buf) + { + std::string ret(buf); + free(buf); + return ret; + } +#else + if (auto var = std::getenv(var.c_str())) + return std::string(var); +#endif + return std::string(); +} + } /* namespace sys */ } /* namespace lol */