diff --git a/include/verilatedos.h b/include/verilatedos.h index e4e2baab1..1d3b0c90e 100644 --- a/include/verilatedos.h +++ b/include/verilatedos.h @@ -614,8 +614,13 @@ static inline double VL_ROUND(double n) { //========================================================================= // Time and performance +#include + namespace VlOs { +/// Get environment variable +extern std::string getenvStr(const std::string& envvar, + const std::string& defaultValue) VL_MT_SAFE; extern uint64_t memUsageBytes() VL_MT_SAFE; ///< Return memory usage in bytes, or 0 if unknown // Internal: Record CPU time, starting point on construction, and current delta from that diff --git a/include/verilatedos_c.h b/include/verilatedos_c.h index dc7778e34..a568e53fa 100644 --- a/include/verilatedos_c.h +++ b/include/verilatedos_c.h @@ -99,5 +99,31 @@ uint64_t memUsageBytes() VL_MT_SAFE { #endif } +//========================================================================= +// VlOs::getenvStr implementation + +std::string getenvStr(const std::string& envvar, const std::string& defaultValue) VL_MT_SAFE { + std::string ret; +#if defined(_MSC_VER) + // Note: MinGW does not offer _dupenv_s + const char* envvalue = nullptr; + _dupenv_s((char**)&envvalue, nullptr, envvar.c_str()); + if (envvalue != nullptr) { + const std::string result{envvalue}; + free((void*)envvalue); + ret = result; + } else { + ret = defaultValue; + } +#else + if (const char* const envvalue = getenv(envvar.c_str())) { + ret = envvalue; + } else { + ret = defaultValue; + } +#endif + return ret; +} + //========================================================================= } //namespace VlOs diff --git a/src/V3Os.cpp b/src/V3Os.cpp index 41508f43b..99661201d 100644 --- a/src/V3Os.cpp +++ b/src/V3Os.cpp @@ -86,26 +86,7 @@ VL_DEFINE_DEBUG_FUNCTIONS; // Environment string V3Os::getenvStr(const string& envvar, const string& defaultValue) { - string ret = ""; -#if defined(_MSC_VER) - // Note: MinGW does not offer _dupenv_s - const char* envvalue = nullptr; - _dupenv_s((char**)&envvalue, nullptr, envvar.c_str()); - if (envvalue != nullptr) { - const std::string result{envvalue}; - free((void*)envvalue); - ret = result; - } else { - ret = defaultValue; - } -#else - if (const char* const envvalue = getenv(envvar.c_str())) { - ret = envvalue; - } else { - ret = defaultValue; - } -#endif - return VString::escapeStringForPath(ret); + return VString::escapeStringForPath(VlOs::getenvStr(envvar, defaultValue)); } void V3Os::setenvStr(const string& envvar, const string& value, const string& why) { @@ -122,7 +103,7 @@ void V3Os::setenvStr(const string& envvar, const string& value, const string& wh // setenv() replaced by putenv() in Solaris environment. Prototype is different // putenv() requires NAME=VALUE format const string vareq = envvar + "=" + value; - putenv(const_cast(vareq.c_str())); + putenv(strdup(vareq.c_str())); // will leak if setting the same variable again #endif }