#ifndef UTILITY_H
#define UTILITY_H
#ifdef __cplusplus
extern "C" {
#endif
// standard C includes
#include <stdint.h>
#include <time.h>
// bring TLS support to antique compilers
#ifndef thread_local
#ifdef _MSC_VER
#define thread_local __declspec(thread) // the thread_local keyword wasn't defined before C++11 and C23
#else // a saner compiler
#define thread_local _Thread_local // the thread_local keyword wasn't defined before C++11 and C23
#endif // _MSC_VER
#endif // !thread_local
// Microsoft-specific shims
#ifdef _MSC_VER
#include <stdarg.h>
#include <io.h>
#include <direct.h>
#if defined(_M_AMD64)
#define __x86_64__ 1
#elif defined(_M_ARM64) || defined(_M_ARM64EC)
#define __aarch64__ 1
#endif // native platform identification
static inline char *sane_strerror (int errnum) { thread_local static char errorstr[256]; strerror_s (errorstr, sizeof (errorstr), errnum); return (errorstr); } // non-complaining strerror() implementation for MSVC. Note that strerror() is unsafe IF AND ONLY IF the locale is changed during program execution AND a string pointer returned by strerror is saved and reused by the program. Guess the odds it will happen here...
#define strerror(n) sane_strerror ((n)) // STFU Microsoft
static inline char *sane_getenv (const char *varname) { extern char **environ; size_t i, len = strlen (varname); for (i = 0; environ[i] != NULL; i++) if ((strncmp (environ[i], varname, len) == 0) && ((environ[i])[len] == '=')) return (&(environ[i])[len + 1]); return (NULL); } // non-complaining getenv() implementation for MSVC. Note that getenv_s() access _environ too as per Microsoft docs, so this is perfectly legit. Nuff said.
#define getenv(v) sane_getenv ((v)) // STFU Microsoft
static struct tm *sane_localtime (const time_t *clock) { thread_local static struct tm localtime_tm; if (localtime_s (&localtime_tm, clock) != 0) return (NULL); return (&localtime_tm); } // non-complaining localtime() implementation for MSVC. Uses TLS.
#define localtime(t) sane_localtime ((t)) // STFU Microsoft
static inline char *sane_asctime (const struct tm *tm_time) { thread_local static char asctimestr[64]; if (asctime_s (asctimestr, sizeof (asctimestr), tm_time) != 0) return (NULL); return (asctimestr); } // non-complaining asctime() implementation for MSVC. Uses TLS.
#define asctime(t) sane_asctime ((t)) // STFU Microsoft
static inline int vasprintf (char **out_string, const char *fmt, va_list va_args) { int retval; va_list ap; va_copy (ap, va_args); retval = _vsnprintf_s (NULL, 0, 0, fmt, ap); va_end (ap); if (retval == -1) return (-1); *out_string = malloc ((size_t) retval + 1); if (*out_string == NULL) return (-1); va_copy (ap, va_args); retval = _vsnprintf_s (*out_string, (size_t) retval + 1, (size_t) retval + 1, fmt, va_args); va_end (ap); return (retval); } // vasprintf() implementation for Windows
static inline int asprintf (char **out_string, const char *fmt, ...) { int r; va_list ap; va_start (ap, fmt); r = vasprintf (out_string, fmt, ap); va_end (ap); return (r); } // asprintf() implementation for Windows
#define strcasecmp(s1,s2) _stricmp ((s1), (s2))
#define __builtin_bswap16(x) _byteswap_ushort ((unsigned short) (x))
#define __builtin_bswap32(x) _byteswap_ulong ((unsigned long) (x))
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ // all Windows machines are little-endian
#define S_IFIFO 0x1000
#define S_IFLNK 0xa000
#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#define major(rdev) ((int) (((rdev) >> 10) & 0x3f)) // on Windows assume a QNX-compatible makedev(). Node is zero (local host).
#define minor(rdev) ((int) (((rdev) >> 0) & 0x3ff)) // on Windows assume a QNX-compatible makedev(). Node is zero (local host).
#define makedev(maj,min) ((dev_t) (((maj) << 10) | (min))) // on Windows assume a QNX-compatible makedev(). Node is zero (local host).
#define strdup(s) _strdup ((s))
#define strcasecmp(s1,s2) _stricmp ((s1), (s2))
#define strtok_r(s,delim,ctx) strtok_s ((s), (delim), (ctx))
#define mkdir(pathname,mode) _mkdir ((pathname))
#define utimbuf __utimbuf32
#define utime(p,t) _utime32 ((p), (t))
#define access(pathname,accmode) _access ((pathname), (accmode))
#define unlink(pathname) _unlink ((pathname))
#define ftello(fp) _ftelli64 ((fp))
#define fileno(fp) _fileno ((fp))
#define ftruncate(fd,size) _chsize_s ((fd), (size))
#define readlink(pathname,buf,maxsize) ((*_errno () = 129 /*ENOTSUP*/), -1) // readlink() not supported on Windows
#define stat _stat64
#define getcwd(buf,maxsize) _getcwd ((buf), (maxsize))
#define chdir(pathname) _chdir ((pathname))
#define putenv(v) _putenv ((v))
#define MAXPATHLEN 1024
struct dirent { unsigned char d_namlen; char *d_name; }; // bring struct dirent/opendir() support to Windows
typedef struct DIR { intptr_t handle; struct __finddata64_t info; struct dirent result; char *pathname; char *search_pattern; } DIR;
static inline DIR *opendir (const char *name) // UNIX-like opendir() implementation for Windows
{
DIR *dir; size_t base_length, all_length; const char *suffix;
dir = (DIR *) malloc (sizeof (DIR)); if (dir == NULL) { /*errno already set*/ return (NULL); }
dir->pathname = _fullpath (NULL, name, 0); // system will mallocate, caller frees
if (dir->pathname == NULL) { free (dir); *_errno () = 12 /*ENOMEM*/; return (NULL); }
base_length = strlen (name);
suffix = ((name[base_length - 1] == '\\') || (name[base_length - 1] == '/') ? "*" : "/*"); // search pattern must end with suitable wildcard
all_length = base_length + strlen (suffix) + 1;
dir->search_pattern = (char *) malloc (all_length); if (dir->search_pattern == NULL) { free (dir->pathname); free (dir); *_errno () = 12 /*ENOMEM*/; return (NULL); }
strcpy_s (dir->search_pattern, all_length, name); strcat_s (dir->search_pattern, all_length, suffix);
dir->handle = _findfirst64 (dir->search_pattern, &dir->info); if (dir->handle == -1) { free (dir->search_pattern); free (dir->pathname); free (dir); return (NULL); }
dir->result.d_namlen = 0; dir->result.d_name = NULL; // first-time initialization
return (dir);
}
static inline int closedir (DIR *dir) // UNIX-like closedir() implementation for Windows
{
int result = -1;
if (dir == NULL) { *_errno () = 9 /*EBADF*/; return (-1); }
if (dir->handle != -1) result = _findclose (dir->handle);
if (dir->search_pattern != NULL) free (dir->search_pattern);
if (dir->pathname != NULL) free (dir->pathname);
free (dir);
if (result == -1) *_errno () = 9 /*EBADF*/; // map all errors to EBADF
return (result);
}
static inline struct dirent *readdir (DIR *dir) // UNIX-like readdir() implementation for Windows
{
struct dirent *result = NULL;
if ((dir == NULL) || (dir->handle == -1)) { *_errno () = 9 /*EBADF*/; return (NULL); }
if ((dir->result.d_name == NULL) || (_findnext64 (dir->handle, &dir->info) != -1)) {
result = &dir->result;
result->d_name = dir->info.name;
result->d_namlen = (unsigned char) strlen (dir->info.name);
}
return (result);
}
static inline void rewinddir (DIR *dir) // UNIX-like rewinddir() implementation for Windows
{
if ((dir == NULL) || (dir->handle == -1)) { *_errno () = 9 /*EBADF*/; return; }
_findclose (dir->handle);
dir->handle = (long) _findfirst64 (dir->search_pattern, &dir->info);
dir->result.d_namlen = 0; dir->result.d_name = NULL; // first-time initialization
}
#else // !_MSC_VER
#define strcpy_s(s1,s1size,s2) strcpy ((s1), (s2))
#define strcat_s(s1,s1size,s2) strcat ((s1), (s2))
#define sprintf_s(s1,s1size,...) sprintf ((s1), __VA_ARGS__)
#define fopen_s(fp,pathname,mode) *(fp) = fopen ((pathname), (mode))
#endif // _MSC_VER
// handy macros that generate a version number in the format "YYYYMMDD" corresponding to the build date. Usage: printf ("version " VERSION_FMT_YYYYMMDD "\n", VERSION_ARG_YYYYMMDD);
#ifndef VERSION_ARG_YYYYMMDD
#define BUILDDATE_YEAR (&__DATE__[7]) // compiler will optimize this into a const string, e.g. "2021"
#define BUILDDATE_MONTH ( \
*((uint32_t *) __DATE__) == *((uint32_t *) "Jan ") ? "01" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Feb ") ? "02" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Mar ") ? "03" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Apr ") ? "04" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "May ") ? "05" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Jun ") ? "06" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Jul ") ? "07" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Aug ") ? "08" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Sep ") ? "09" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Oct ") ? "10" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Nov ") ? "11" : \
*((uint32_t *) __DATE__) == *((uint32_t *) "Dec ") ? "12" : \
"XX" \
) // compiler will optimize this into a const string, e.g. "11"
#define BUILDDATE_DAY ( \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 1 ") ? "01" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 2 ") ? "02" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 3 ") ? "03" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 4 ") ? "04" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 5 ") ? "05" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 6 ") ? "06" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 7 ") ? "07" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 8 ") ? "08" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 9 ") ? "09" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 10 ") ? "10" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 11 ") ? "11" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 12 ") ? "12" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 13 ") ? "13" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 14 ") ? "14" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 15 ") ? "15" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 16 ") ? "16" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 17 ") ? "17" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 18 ") ? "18" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 19 ") ? "19" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 20 ") ? "20" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 21 ") ? "21" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 22 ") ? "22" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 23 ") ? "23" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 24 ") ? "24" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 25 ") ? "25" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 26 ") ? "26" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 27 ") ? "27" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 28 ") ? "28" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 29 ") ? "29" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 30 ") ? "30" : \
*((uint32_t *) &__DATE__[3]) == *((uint32_t *) " 31 ") ? "31" : \
"XX" \
) // compiler will optimize this into a const string, e.g. "14"
#define VERSION_FMT_YYYYMMDD "%s%s%s"
#define VERSION_ARG_YYYYMMDD BUILDDATE_YEAR, BUILDDATE_MONTH, BUILDDATE_DAY
#endif // !VERSION_ARG_YYYYMMDD
// macro to bring __FILE_NAME__ support to moronic compilers
#ifndef __FILE_NAME__ // Clang 9+ has the macro, GCC 12+ added it too in 2021, MSVC obviously won't do it. Heh.
#define __FILE_NAME__ ( \
(sizeof (__FILE__) > 2) && ((__FILE__[sizeof (__FILE__) - 2] == '/') || (__FILE__[sizeof (__FILE__) - 2] == '\\')) ? &__FILE__[sizeof (__FILE__) - 1] : \
(sizeof (__FILE__) > 3) && ((__FILE__[sizeof (__FILE__) - 3] == '/') || (__FILE__[sizeof (__FILE__) - 3] == '\\')) ? &__FILE__[sizeof (__FILE__) - 2] : \
(sizeof (__FILE__) > 4) && ((__FILE__[sizeof (__FILE__) - 4] == '/') || (__FILE__[sizeof (__FILE__) - 4] == '\\')) ? &__FILE__[sizeof (__FILE__) - 3] : \
(sizeof (__FILE__) > 5) && ((__FILE__[sizeof (__FILE__) - 5] == '/') || (__FILE__[sizeof (__FILE__) - 5] == '\\')) ? &__FILE__[sizeof (__FILE__) - 4] : \
(sizeof (__FILE__) > 6) && ((__FILE__[sizeof (__FILE__) - 6] == '/') || (__FILE__[sizeof (__FILE__) - 6] == '\\')) ? &__FILE__[sizeof (__FILE__) - 5] : \
(sizeof (__FILE__) > 7) && ((__FILE__[sizeof (__FILE__) - 7] == '/') || (__FILE__[sizeof (__FILE__) - 7] == '\\')) ? &__FILE__[sizeof (__FILE__) - 6] : \
(sizeof (__FILE__) > 8) && ((__FILE__[sizeof (__FILE__) - 8] == '/') || (__FILE__[sizeof (__FILE__) - 8] == '\\')) ? &__FILE__[sizeof (__FILE__) - 7] : \
(sizeof (__FILE__) > 9) && ((__FILE__[sizeof (__FILE__) - 9] == '/') || (__FILE__[sizeof (__FILE__) - 9] == '\\')) ? &__FILE__[sizeof (__FILE__) - 8] : \
(sizeof (__FILE__) > 10) && ((__FILE__[sizeof (__FILE__) - 10] == '/') || (__FILE__[sizeof (__FILE__) - 10] == '\\')) ? &__FILE__[sizeof (__FILE__) - 9] : \
(sizeof (__FILE__) > 11) && ((__FILE__[sizeof (__FILE__) - 11] == '/') || (__FILE__[sizeof (__FILE__) - 11] == '\\')) ? &__FILE__[sizeof (__FILE__) - 10] : \
(sizeof (__FILE__) > 12) && ((__FILE__[sizeof (__FILE__) - 12] == '/') || (__FILE__[sizeof (__FILE__) - 12] == '\\')) ? &__FILE__[sizeof (__FILE__) - 11] : \
(sizeof (__FILE__) > 13) && ((__FILE__[sizeof (__FILE__) - 13] == '/') || (__FILE__[sizeof (__FILE__) - 13] == '\\')) ? &__FILE__[sizeof (__FILE__) - 12] : \
(sizeof (__FILE__) > 14) && ((__FILE__[sizeof (__FILE__) - 14] == '/') || (__FILE__[sizeof (__FILE__) - 14] == '\\')) ? &__FILE__[sizeof (__FILE__) - 13] : \
(sizeof (__FILE__) > 15) && ((__FILE__[sizeof (__FILE__) - 15] == '/') || (__FILE__[sizeof (__FILE__) - 15] == '\\')) ? &__FILE__[sizeof (__FILE__) - 14] : \
(sizeof (__FILE__) > 16) && ((__FILE__[sizeof (__FILE__) - 16] == '/') || (__FILE__[sizeof (__FILE__) - 16] == '\\')) ? &__FILE__[sizeof (__FILE__) - 15] : \
(sizeof (__FILE__) > 17) && ((__FILE__[sizeof (__FILE__) - 17] == '/') || (__FILE__[sizeof (__FILE__) - 17] == '\\')) ? &__FILE__[sizeof (__FILE__) - 16] : \
(sizeof (__FILE__) > 18) && ((__FILE__[sizeof (__FILE__) - 18] == '/') || (__FILE__[sizeof (__FILE__) - 18] == '\\')) ? &__FILE__[sizeof (__FILE__) - 17] : \
(sizeof (__FILE__) > 19) && ((__FILE__[sizeof (__FILE__) - 19] == '/') || (__FILE__[sizeof (__FILE__) - 19] == '\\')) ? &__FILE__[sizeof (__FILE__) - 18] : \
(sizeof (__FILE__) > 20) && ((__FILE__[sizeof (__FILE__) - 20] == '/') || (__FILE__[sizeof (__FILE__) - 20] == '\\')) ? &__FILE__[sizeof (__FILE__) - 19] : \
(sizeof (__FILE__) > 21) && ((__FILE__[sizeof (__FILE__) - 21] == '/') || (__FILE__[sizeof (__FILE__) - 21] == '\\')) ? &__FILE__[sizeof (__FILE__) - 20] : \
(sizeof (__FILE__) > 22) && ((__FILE__[sizeof (__FILE__) - 22] == '/') || (__FILE__[sizeof (__FILE__) - 22] == '\\')) ? &__FILE__[sizeof (__FILE__) - 21] : \
(sizeof (__FILE__) > 23) && ((__FILE__[sizeof (__FILE__) - 23] == '/') || (__FILE__[sizeof (__FILE__) - 23] == '\\')) ? &__FILE__[sizeof (__FILE__) - 22] : \
(sizeof (__FILE__) > 24) && ((__FILE__[sizeof (__FILE__) - 24] == '/') || (__FILE__[sizeof (__FILE__) - 24] == '\\')) ? &__FILE__[sizeof (__FILE__) - 23] : \
(sizeof (__FILE__) > 25) && ((__FILE__[sizeof (__FILE__) - 25] == '/') || (__FILE__[sizeof (__FILE__) - 25] == '\\')) ? &__FILE__[sizeof (__FILE__) - 24] : \
(sizeof (__FILE__) > 26) && ((__FILE__[sizeof (__FILE__) - 26] == '/') || (__FILE__[sizeof (__FILE__) - 26] == '\\')) ? &__FILE__[sizeof (__FILE__) - 25] : \
(sizeof (__FILE__) > 27) && ((__FILE__[sizeof (__FILE__) - 27] == '/') || (__FILE__[sizeof (__FILE__) - 27] == '\\')) ? &__FILE__[sizeof (__FILE__) - 26] : \
(sizeof (__FILE__) > 28) && ((__FILE__[sizeof (__FILE__) - 28] == '/') || (__FILE__[sizeof (__FILE__) - 28] == '\\')) ? &__FILE__[sizeof (__FILE__) - 27] : \
(sizeof (__FILE__) > 29) && ((__FILE__[sizeof (__FILE__) - 29] == '/') || (__FILE__[sizeof (__FILE__) - 29] == '\\')) ? &__FILE__[sizeof (__FILE__) - 28] : \
(sizeof (__FILE__) > 30) && ((__FILE__[sizeof (__FILE__) - 30] == '/') || (__FILE__[sizeof (__FILE__) - 30] == '\\')) ? &__FILE__[sizeof (__FILE__) - 29] : \
(sizeof (__FILE__) > 31) && ((__FILE__[sizeof (__FILE__) - 31] == '/') || (__FILE__[sizeof (__FILE__) - 31] == '\\')) ? &__FILE__[sizeof (__FILE__) - 30] : \
(sizeof (__FILE__) > 32) && ((__FILE__[sizeof (__FILE__) - 32] == '/') || (__FILE__[sizeof (__FILE__) - 32] == '\\')) ? &__FILE__[sizeof (__FILE__) - 31] : \
(sizeof (__FILE__) > 33) && ((__FILE__[sizeof (__FILE__) - 33] == '/') || (__FILE__[sizeof (__FILE__) - 33] == '\\')) ? &__FILE__[sizeof (__FILE__) - 32] : \
__FILE__) // this *COMPILE-TIME* macro complements the __FILE__ macro defined by the C standard by returning just the filename portion of the full path. Supports filenames up to 32 chars. Expand as necessary.
#endif // !__FILE_NAME__
// logging macros
#define LOG(type,lvl,...) do { if ((lvl) <= verbose_level) { fprintf (stderr, "ifstool: %s: ", (type)); if (verbose_level > 1) fprintf (stderr, "%s:%d:%s(): ", __FILE_NAME__, __LINE__, __func__); fprintf (stderr, __VA_ARGS__); fputc ('\n', stderr); } } while (0)
#define LOG_ERROR(...) LOG ("error", 0, __VA_ARGS__)
#define LOG_WARNING(...) LOG ("warning", 1, __VA_ARGS__)
#define LOG_INFO(...) LOG ("info", 2, __VA_ARGS__)
#define LOG_DEBUG(...) LOG ("debug", 3, __VA_ARGS__)
// macro to gently exit with an error message
#define DIE_WITH_EXITCODE(exitcode,...) do { LOG_ERROR (__VA_ARGS__); exit ((exitcode)); } while (0)
// macro to exit less brutally than with abort() if something doesn't go the way we'd like to
#define ASSERT(is_it_true,...) do { if (!(is_it_true)) { LOG ("fatal error", 0, "consistency check failed:"); LOG ("fatal error", 0, #is_it_true); LOG ("fatal error", 0, __VA_ARGS__); exit (1); } } while (0)
#define ASSERT_WITH_ERRNO(is_it_true) ASSERT ((is_it_true), "%s", strerror (errno))
#ifdef __cplusplus
}
#endif
#endif // UTILITY_H