Home | History | Annotate | Download | only in programs
      1 /*
      2     util.h - utility functions
      3     Copyright (C) 2016-present, Przemyslaw Skibinski, Yann Collet
      4 
      5     This program is free software; you can redistribute it and/or modify
      6     it under the terms of the GNU General Public License as published by
      7     the Free Software Foundation; either version 2 of the License, or
      8     (at your option) any later version.
      9 
     10     This program is distributed in the hope that it will be useful,
     11     but WITHOUT ANY WARRANTY; without even the implied warranty of
     12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13     GNU General Public License for more details.
     14 
     15     You should have received a copy of the GNU General Public License along
     16     with this program; if not, write to the Free Software Foundation, Inc.,
     17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
     18 */
     19 
     20 #ifndef UTIL_H_MODULE
     21 #define UTIL_H_MODULE
     22 
     23 #if defined (__cplusplus)
     24 extern "C" {
     25 #endif
     26 
     27 
     28 
     29 /*-****************************************
     30 *  Dependencies
     31 ******************************************/
     32 #include "platform.h"     /* PLATFORM_POSIX_VERSION */
     33 #include <stdlib.h>       /* malloc */
     34 #include <stddef.h>       /* size_t, ptrdiff_t */
     35 #include <stdio.h>        /* fprintf */
     36 #include <sys/types.h>    /* stat, utime */
     37 #include <sys/stat.h>     /* stat */
     38 #if defined(_MSC_VER)
     39 #  include <sys/utime.h>  /* utime */
     40 #  include <io.h>         /* _chmod */
     41 #else
     42 #  include <unistd.h>     /* chown, stat */
     43 #  include <utime.h>      /* utime */
     44 #endif
     45 #include <time.h>         /* time */
     46 #include <errno.h>
     47 
     48 
     49 
     50 /*-**************************************************************
     51 *  Basic Types
     52 *****************************************************************/
     53 #if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
     54 # include <stdint.h>
     55   typedef  uint8_t BYTE;
     56   typedef uint16_t U16;
     57   typedef  int16_t S16;
     58   typedef uint32_t U32;
     59   typedef  int32_t S32;
     60   typedef uint64_t U64;
     61   typedef  int64_t S64;
     62 #else
     63   typedef unsigned char       BYTE;
     64   typedef unsigned short      U16;
     65   typedef   signed short      S16;
     66   typedef unsigned int        U32;
     67   typedef   signed int        S32;
     68   typedef unsigned long long  U64;
     69   typedef   signed long long  S64;
     70 #endif
     71 
     72 
     73 /*-****************************************
     74 *  Sleep functions: Windows - Posix - others
     75 ******************************************/
     76 #if defined(_WIN32)
     77 #  include <windows.h>
     78 #  define SET_HIGH_PRIORITY SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)
     79 #  define UTIL_sleep(s) Sleep(1000*s)
     80 #  define UTIL_sleepMilli(milli) Sleep(milli)
     81 #elif PLATFORM_POSIX_VERSION >= 0 /* Unix-like operating system */
     82 #  include <unistd.h>
     83 #  include <sys/resource.h> /* setpriority */
     84 #  include <time.h>         /* clock_t, nanosleep, clock, CLOCKS_PER_SEC */
     85 #  if defined(PRIO_PROCESS)
     86 #    define SET_HIGH_PRIORITY setpriority(PRIO_PROCESS, 0, -20)
     87 #  else
     88 #    define SET_HIGH_PRIORITY /* disabled */
     89 #  endif
     90 #  define UTIL_sleep(s) sleep(s)
     91 #  if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 199309L)) || (PLATFORM_POSIX_VERSION >= 200112L)  /* nanosleep requires POSIX.1-2001 */
     92 #      define UTIL_sleepMilli(milli) { struct timespec t; t.tv_sec=0; t.tv_nsec=milli*1000000ULL; nanosleep(&t, NULL); }
     93 #  else
     94 #      define UTIL_sleepMilli(milli) /* disabled */
     95 #  endif
     96 #else
     97 #  define SET_HIGH_PRIORITY      /* disabled */
     98 #  define UTIL_sleep(s)          /* disabled */
     99 #  define UTIL_sleepMilli(milli) /* disabled */
    100 #endif
    101 
    102 
    103 /* *************************************
    104 *  Constants
    105 ***************************************/
    106 #define LIST_SIZE_INCREASE   (8*1024)
    107 
    108 
    109 /*-****************************************
    110 *  Compiler specifics
    111 ******************************************/
    112 #if defined(__INTEL_COMPILER)
    113 #  pragma warning(disable : 177)    /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */
    114 #endif
    115 #if defined(__GNUC__)
    116 #  define UTIL_STATIC static __attribute__((unused))
    117 #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
    118 #  define UTIL_STATIC static inline
    119 #elif defined(_MSC_VER)
    120 #  define UTIL_STATIC static __inline
    121 #else
    122 #  define UTIL_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
    123 #endif
    124 
    125 
    126 /*-****************************************
    127 *  Time functions
    128 ******************************************/
    129 #if !defined(_WIN32)
    130    typedef clock_t UTIL_time_t;
    131    UTIL_STATIC void UTIL_initTimer(UTIL_time_t* ticksPerSecond) { *ticksPerSecond=0; }
    132    UTIL_STATIC void UTIL_getTime(UTIL_time_t* x) { *x = clock(); }
    133    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { (void)ticksPerSecond; return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
    134    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { (void)ticksPerSecond; return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
    135 #else
    136    typedef LARGE_INTEGER UTIL_time_t;
    137    UTIL_STATIC void UTIL_initTimer(UTIL_time_t* ticksPerSecond) { if (!QueryPerformanceFrequency(ticksPerSecond)) fprintf(stderr, "ERROR: QueryPerformance not present\n"); }
    138    UTIL_STATIC void UTIL_getTime(UTIL_time_t* x) { QueryPerformanceCounter(x); }
    139    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart; }
    140    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart; }
    141 #endif
    142 
    143 
    144 /* returns time span in microseconds */
    145 UTIL_STATIC U64 UTIL_clockSpanMicro( UTIL_time_t clockStart, UTIL_time_t ticksPerSecond )
    146 {
    147     UTIL_time_t clockEnd;
    148     UTIL_getTime(&clockEnd);
    149     return UTIL_getSpanTimeMicro(ticksPerSecond, clockStart, clockEnd);
    150 }
    151 
    152 
    153 UTIL_STATIC void UTIL_waitForNextTick(UTIL_time_t ticksPerSecond)
    154 {
    155     UTIL_time_t clockStart, clockEnd;
    156     UTIL_getTime(&clockStart);
    157     do {
    158         UTIL_getTime(&clockEnd);
    159     } while (UTIL_getSpanTimeNano(ticksPerSecond, clockStart, clockEnd) == 0);
    160 }
    161 
    162 
    163 
    164 /*-****************************************
    165 *  File functions
    166 ******************************************/
    167 #if defined(_MSC_VER)
    168 	#define chmod _chmod
    169 	typedef struct _stat64 stat_t;
    170 #else
    171     typedef struct stat stat_t;
    172 #endif
    173 
    174 
    175 UTIL_STATIC int UTIL_setFileStat(const char *filename, stat_t *statbuf)
    176 {
    177     int res = 0;
    178     struct utimbuf timebuf;
    179 
    180 	timebuf.actime = time(NULL);
    181 	timebuf.modtime = statbuf->st_mtime;
    182 	res += utime(filename, &timebuf);  /* set access and modification times */
    183 
    184 #if !defined(_WIN32)
    185     res += chown(filename, statbuf->st_uid, statbuf->st_gid);  /* Copy ownership */
    186 #endif
    187 
    188     res += chmod(filename, statbuf->st_mode & 07777);  /* Copy file permissions */
    189 
    190     errno = 0;
    191     return -res; /* number of errors is returned */
    192 }
    193 
    194 
    195 UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
    196 {
    197     int r;
    198 #if defined(_MSC_VER)
    199     r = _stat64(infilename, statbuf);
    200     if (r || !(statbuf->st_mode & S_IFREG)) return 0;   /* No good... */
    201 #else
    202     r = stat(infilename, statbuf);
    203     if (r || !S_ISREG(statbuf->st_mode)) return 0;   /* No good... */
    204 #endif
    205     return 1;
    206 }
    207 
    208 
    209 UTIL_STATIC U64 UTIL_getFileSize(const char* infilename)
    210 {
    211     int r;
    212 #if defined(_MSC_VER)
    213     struct _stat64 statbuf;
    214     r = _stat64(infilename, &statbuf);
    215     if (r || !(statbuf.st_mode & S_IFREG)) return 0;   /* No good... */
    216 #else
    217     struct stat statbuf;
    218     r = stat(infilename, &statbuf);
    219     if (r || !S_ISREG(statbuf.st_mode)) return 0;   /* No good... */
    220 #endif
    221     return (U64)statbuf.st_size;
    222 }
    223 
    224 
    225 UTIL_STATIC U64 UTIL_getTotalFileSize(const char** fileNamesTable, unsigned nbFiles)
    226 {
    227     U64 total = 0;
    228     unsigned n;
    229     for (n=0; n<nbFiles; n++)
    230         total += UTIL_getFileSize(fileNamesTable[n]);
    231     return total;
    232 }
    233 
    234 
    235 UTIL_STATIC int UTIL_doesFileExists(const char* infilename)
    236 {
    237     int r;
    238 #if defined(_MSC_VER)
    239     struct _stat64 statbuf;
    240     r = _stat64(infilename, &statbuf);
    241     if (r || !(statbuf.st_mode & S_IFREG)) return 0;   /* No good... */
    242 #else
    243     struct stat statbuf;
    244     r = stat(infilename, &statbuf);
    245     if (r || !S_ISREG(statbuf.st_mode)) return 0;   /* No good... */
    246 #endif
    247     return 1;
    248 }
    249 
    250 
    251 UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
    252 {
    253     int r;
    254 #if defined(_MSC_VER)
    255     struct _stat64 statbuf;
    256     r = _stat64(infilename, &statbuf);
    257     if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
    258 #else
    259     struct stat statbuf;
    260     r = stat(infilename, &statbuf);
    261     if (!r && S_ISDIR(statbuf.st_mode)) return 1;
    262 #endif
    263     return 0;
    264 }
    265 
    266 /*
    267  * A modified version of realloc().
    268  * If UTIL_realloc() fails the original block is freed.
    269 */
    270 UTIL_STATIC void *UTIL_realloc(void *ptr, size_t size)
    271 {
    272     void *newptr = realloc(ptr, size);
    273     if (newptr) return newptr;
    274     free(ptr);
    275     return NULL;
    276 }
    277 
    278 
    279 #ifdef _WIN32
    280 #  define UTIL_HAS_CREATEFILELIST
    281 
    282 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd)
    283 {
    284     char* path;
    285     int dirLength, fnameLength, pathLength, nbFiles = 0;
    286     WIN32_FIND_DATAA cFile;
    287     HANDLE hFile;
    288 
    289     dirLength = (int)strlen(dirName);
    290     path = (char*) malloc(dirLength + 3);
    291     if (!path) return 0;
    292 
    293     memcpy(path, dirName, dirLength);
    294     path[dirLength] = '\\';
    295     path[dirLength+1] = '*';
    296     path[dirLength+2] = 0;
    297 
    298     hFile=FindFirstFileA(path, &cFile);
    299     if (hFile == INVALID_HANDLE_VALUE) {
    300         fprintf(stderr, "Cannot open directory '%s'\n", dirName);
    301         return 0;
    302     }
    303     free(path);
    304 
    305     do {
    306         fnameLength = (int)strlen(cFile.cFileName);
    307         path = (char*) malloc(dirLength + fnameLength + 2);
    308         if (!path) { FindClose(hFile); return 0; }
    309         memcpy(path, dirName, dirLength);
    310         path[dirLength] = '\\';
    311         memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
    312         pathLength = dirLength+1+fnameLength;
    313         path[pathLength] = 0;
    314         if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
    315             if (strcmp (cFile.cFileName, "..") == 0 ||
    316                 strcmp (cFile.cFileName, ".") == 0) continue;
    317 
    318             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd);  /* Recursively call "UTIL_prepareFileList" with the new path. */
    319             if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
    320         }
    321         else if ((cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)) {
    322             if (*bufStart + *pos + pathLength >= *bufEnd) {
    323                 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
    324                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
    325                 *bufEnd = *bufStart + newListSize;
    326                 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
    327             }
    328             if (*bufStart + *pos + pathLength < *bufEnd) {
    329                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
    330                 *pos += pathLength + 1;
    331                 nbFiles++;
    332             }
    333         }
    334         free(path);
    335     } while (FindNextFileA(hFile, &cFile));
    336 
    337     FindClose(hFile);
    338     return nbFiles;
    339 }
    340 
    341 #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L)  /* opendir, readdir require POSIX.1-2001 */
    342 #  define UTIL_HAS_CREATEFILELIST
    343 #  include <dirent.h>       /* opendir, readdir */
    344 #  include <string.h>       /* strerror, memcpy */
    345 
    346 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd)
    347 {
    348     DIR *dir;
    349     struct dirent *entry;
    350     char* path;
    351     int dirLength, fnameLength, pathLength, nbFiles = 0;
    352 
    353     if (!(dir = opendir(dirName))) {
    354         fprintf(stderr, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
    355         return 0;
    356     }
    357 
    358     dirLength = (int)strlen(dirName);
    359     errno = 0;
    360     while ((entry = readdir(dir)) != NULL) {
    361         if (strcmp (entry->d_name, "..") == 0 ||
    362             strcmp (entry->d_name, ".") == 0) continue;
    363         fnameLength = (int)strlen(entry->d_name);
    364         path = (char*) malloc(dirLength + fnameLength + 2);
    365         if (!path) { closedir(dir); return 0; }
    366         memcpy(path, dirName, dirLength);
    367         path[dirLength] = '/';
    368         memcpy(path+dirLength+1, entry->d_name, fnameLength);
    369         pathLength = dirLength+1+fnameLength;
    370         path[pathLength] = 0;
    371 
    372         if (UTIL_isDirectory(path)) {
    373             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd);  /* Recursively call "UTIL_prepareFileList" with the new path. */
    374             if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
    375         } else {
    376             if (*bufStart + *pos + pathLength >= *bufEnd) {
    377                 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
    378                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
    379                 *bufEnd = *bufStart + newListSize;
    380                 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
    381             }
    382             if (*bufStart + *pos + pathLength < *bufEnd) {
    383                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
    384                 *pos += pathLength + 1;
    385                 nbFiles++;
    386             }
    387         }
    388         free(path);
    389         errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
    390     }
    391 
    392     if (errno != 0) {
    393         fprintf(stderr, "readdir(%s) error: %s\n", dirName, strerror(errno));
    394         free(*bufStart);
    395         *bufStart = NULL;
    396     }
    397     closedir(dir);
    398     return nbFiles;
    399 }
    400 
    401 #else
    402 
    403 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd)
    404 {
    405     (void)bufStart; (void)bufEnd; (void)pos;
    406     fprintf(stderr, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
    407     return 0;
    408 }
    409 
    410 #endif /* #ifdef _WIN32 */
    411 
    412 /*
    413  * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
    414  *                       and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
    415  * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
    416  * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
    417  */
    418 UTIL_STATIC const char** UTIL_createFileList(const char **inputNames, unsigned inputNamesNb, char** allocatedBuffer, unsigned* allocatedNamesNb)
    419 {
    420     size_t pos;
    421     unsigned i, nbFiles;
    422     char* buf = (char*)malloc(LIST_SIZE_INCREASE);
    423     char* bufend = buf + LIST_SIZE_INCREASE;
    424     const char** fileTable;
    425 
    426     if (!buf) return NULL;
    427 
    428     for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
    429         if (!UTIL_isDirectory(inputNames[i])) {
    430             size_t const len = strlen(inputNames[i]);
    431             if (buf + pos + len >= bufend) {
    432                 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
    433                 buf = (char*)UTIL_realloc(buf, newListSize);
    434                 bufend = buf + newListSize;
    435                 if (!buf) return NULL;
    436             }
    437             if (buf + pos + len < bufend) {
    438                 strncpy(buf + pos, inputNames[i], bufend - (buf + pos));
    439                 pos += len + 1;
    440                 nbFiles++;
    441             }
    442         } else {
    443             nbFiles += UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend);
    444             if (buf == NULL) return NULL;
    445     }   }
    446 
    447     if (nbFiles == 0) { free(buf); return NULL; }
    448 
    449     fileTable = (const char**)malloc((nbFiles+1) * sizeof(const char*));
    450     if (!fileTable) { free(buf); return NULL; }
    451 
    452     for (i=0, pos=0; i<nbFiles; i++) {
    453         fileTable[i] = buf + pos;
    454         pos += strlen(fileTable[i]) + 1;
    455     }
    456 
    457     if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
    458 
    459     *allocatedBuffer = buf;
    460     *allocatedNamesNb = nbFiles;
    461 
    462     return fileTable;
    463 }
    464 
    465 
    466 UTIL_STATIC void UTIL_freeFileList(const char** filenameTable, char* allocatedBuffer)
    467 {
    468     if (allocatedBuffer) free(allocatedBuffer);
    469     if (filenameTable) free((void*)filenameTable);
    470 }
    471 
    472 
    473 #if defined (__cplusplus)
    474 }
    475 #endif
    476 
    477 #endif /* UTIL_H_MODULE */
    478