/* * Created by yuuta on 7/19/22. */ #include "win32.h" #include "helpers.h" #include "log.h" #include "common.h" #include #include #include #include #ifdef _WIN32 #include #endif int alloc(void *existing, unsigned int count, unsigned int bytes, bool zero_out, void **out) { const unsigned int size = count * bytes; void *ptr; if (!(ptr = realloc(existing, size))) { const int e = errno; LOGEV("Cannot %sallocate %d bytes of memory: %s (%d).", existing ? "re" : "", size, strerror2(e), e); return AC_E_MEMORY_ALLOCATION; } if (!existing && zero_out) { memset(ptr, 0, size); } *out = ptr; return AC_E_OK; } int strdup2(const char *str, char **out) { char *str2; if (!(str2 = strdup(str))) { const int e = errno; LOGEV("Cannot duplicate string '%s': %s (%d).", str, strerror2(e), e); return AC_E_MEMORY_ALLOCATION; } *out = str2; return AC_E_OK; } #ifdef _WIN32 static _Thread_local LPTSTR err_buf = NULL; #else static _Thread_local char err_buf[1024]; #endif char *strerror2(int errnum) { #ifdef _WIN32 if (err_buf) { LocalFree(err_buf); err_buf = NULL; } FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errnum, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err_buf, 0, NULL); if (!err_buf) { return "Unknown error"; } #else int r; if ((r = strerror_r(errnum, err_buf, sizeof(err_buf) / sizeof(char)))) { snprintf(err_buf, 1024, "%d (%d)", errnum, r); } #endif return err_buf; } void helpers_cleanup(void) { #ifdef _WIN32 if (err_buf) { LocalFree(err_buf); err_buf = NULL; } #endif }