Changed from localtime to the more secure localtime_r and localtime_s functions.

This commit is contained in:
Leon Styhre 2020-12-29 13:44:13 +01:00
parent eadeb88ece
commit c747416071
2 changed files with 20 additions and 3 deletions

View file

@ -54,7 +54,15 @@ void Log::open()
std::ostringstream& Log::get(LogLevel level) std::ostringstream& Log::get(LogLevel level)
{ {
time_t t = time(nullptr); time_t t = time(nullptr);
os << std::put_time(localtime(&t), "%b %d %T ") << logLevelMap[level] << ":\t"; struct tm tm;
#if defined(_WIN64)
// Of course Windows does not follow standards and puts the parameters the other way
// around compared to POSIX.
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
os << std::put_time(&tm, "%b %d %T ") << logLevelMap[level] << ":\t";
messageLevel = level; messageLevel = level;
return os; return os;

View file

@ -44,7 +44,11 @@ namespace Utils
void DateTime::setTime(const time_t& _time) void DateTime::setTime(const time_t& _time)
{ {
mTime = (_time < 0) ? 0 : _time; mTime = (_time < 0) ? 0 : _time;
mTimeStruct = *localtime(&mTime); #if defined(_WIN64)
localtime_s(&mTimeStruct, &mTime);
#else
localtime_r(&mTime, &mTimeStruct);
#endif
mIsoString = timeToString(mTime); mIsoString = timeToString(mTime);
} }
@ -171,7 +175,12 @@ namespace Utils
std::string timeToString(const time_t& _time, const std::string& _format) std::string timeToString(const time_t& _time, const std::string& _format)
{ {
const char* f = _format.c_str(); const char* f = _format.c_str();
const tm timeStruct = *localtime(&_time); tm timeStruct;
#if defined(_WIN64)
localtime_s(&timeStruct, &_time);
#else
localtime_r(&_time, &timeStruct);
#endif
char buf[256] = { '\0' }; char buf[256] = { '\0' };
char* s = buf; char* s = buf;