1 /*
2     util.h - utility functions
3     Copyright (C) 2016-2020, 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 <stddef.h>       /* size_t, ptrdiff_t */
34 #include <stdlib.h>       /* malloc */
35 #include <string.h>       /* strlen, strncpy */
36 #include <stdio.h>        /* fprintf, fileno */
37 #include <assert.h>
38 #include <sys/types.h>    /* stat, utime */
39 #include <sys/stat.h>     /* stat */
40 #if defined(_WIN32)
41 #  include <sys/utime.h>  /* utime */
42 #  include <io.h>         /* _chmod */
43 #else
44 #  include <unistd.h>     /* chown, stat */
45 # if PLATFORM_POSIX_VERSION < 200809L
46 #  include <utime.h>      /* utime */
47 # else
48 #  include <fcntl.h>      /* AT_FDCWD */
49 #  include <sys/stat.h>   /* for utimensat */
50 # endif
51 #endif
52 #include <time.h>         /* time */
53 #include <limits.h>       /* INT_MAX */
54 #include <errno.h>
55 
56 
57 
58 /*-**************************************************************
59 *  Basic Types
60 *****************************************************************/
61 #if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
62 # include <stdint.h>
63   typedef  uint8_t BYTE;
64   typedef uint16_t U16;
65   typedef  int16_t S16;
66   typedef uint32_t U32;
67   typedef  int32_t S32;
68   typedef uint64_t U64;
69   typedef  int64_t S64;
70 #else
71   typedef unsigned char       BYTE;
72   typedef unsigned short      U16;
73   typedef   signed short      S16;
74   typedef unsigned int        U32;
75   typedef   signed int        S32;
76   typedef unsigned long long  U64;
77   typedef   signed long long  S64;
78 #endif
79 
80 
81 /* ************************************************************
82 * Avoid fseek()'s 2GiB barrier with MSVC, MacOS, *BSD, MinGW
83 ***************************************************************/
84 #if defined(_MSC_VER) && (_MSC_VER >= 1400)
85 #   define UTIL_fseek _fseeki64
86 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
87 #  define UTIL_fseek fseeko
88 #elif defined(__MINGW32__) && defined(__MSVCRT__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS)
89 #   define UTIL_fseek fseeko64
90 #else
91 #   define UTIL_fseek fseek
92 #endif
93 
94 
95 /*-****************************************
96 *  Sleep functions: Windows - Posix - others
97 ******************************************/
98 #if defined(_WIN32)
99 #  include <windows.h>
100 #  define SET_REALTIME_PRIORITY SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)
101 #  define UTIL_sleep(s) Sleep(1000*s)
102 #  define UTIL_sleepMilli(milli) Sleep(milli)
103 #elif PLATFORM_POSIX_VERSION >= 0 /* Unix-like operating system */
104 #  include <unistd.h>
105 #  include <sys/resource.h> /* setpriority */
106 #  include <time.h>         /* clock_t, nanosleep, clock, CLOCKS_PER_SEC */
107 #  if defined(PRIO_PROCESS)
108 #    define SET_REALTIME_PRIORITY setpriority(PRIO_PROCESS, 0, -20)
109 #  else
110 #    define SET_REALTIME_PRIORITY /* disabled */
111 #  endif
112 #  define UTIL_sleep(s) sleep(s)
113 #  if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 199309L)) || (PLATFORM_POSIX_VERSION >= 200112L)  /* nanosleep requires POSIX.1-2001 */
114 #      define UTIL_sleepMilli(milli) { struct timespec t; t.tv_sec=0; t.tv_nsec=milli*1000000ULL; nanosleep(&t, NULL); }
115 #  else
116 #      define UTIL_sleepMilli(milli) /* disabled */
117 #  endif
118 #else
119 #  define SET_REALTIME_PRIORITY      /* disabled */
120 #  define UTIL_sleep(s)          /* disabled */
121 #  define UTIL_sleepMilli(milli) /* disabled */
122 #endif
123 
124 
125 /*-****************************************
126 *  stat() functions
127 ******************************************/
128 #if defined(_MSC_VER)
129 #  define UTIL_TYPE_stat __stat64
130 #  define UTIL_stat _stat64
131 #  define UTIL_fstat _fstat64
132 #  define UTIL_STAT_MODE_ISREG(st_mode) ((st_mode) & S_IFREG)
133 #elif   defined(__MINGW32__) && defined (__MSVCRT__)
134 #  define UTIL_TYPE_stat _stati64
135 #  define UTIL_stat _stati64
136 #  define UTIL_fstat _fstati64
137 #  define UTIL_STAT_MODE_ISREG(st_mode) ((st_mode) & S_IFREG)
138 #else
139 #  define UTIL_TYPE_stat stat
140 #  define UTIL_stat stat
141 #  define UTIL_fstat fstat
142 #  define UTIL_STAT_MODE_ISREG(st_mode) (S_ISREG(st_mode))
143 #endif
144 
145 
146 /*-****************************************
147 *  fileno() function
148 ******************************************/
149 #if defined(_MSC_VER)
150 #  define UTIL_fileno _fileno
151 #else
152 #  define UTIL_fileno fileno
153 #endif
154 
155 /* *************************************
156 *  Constants
157 ***************************************/
158 #define LIST_SIZE_INCREASE   (8*1024)
159 
160 
161 /*-****************************************
162 *  Compiler specifics
163 ******************************************/
164 #if defined(__INTEL_COMPILER)
165 #  pragma warning(disable : 177)    /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */
166 #endif
167 #if defined(__GNUC__)
168 #  define UTIL_STATIC static __attribute__((unused))
169 #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
170 #  define UTIL_STATIC static inline
171 #elif defined(_MSC_VER)
172 #  define UTIL_STATIC static __inline
173 #else
174 #  define UTIL_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
175 #endif
176 
177 
178 /*-****************************************
179 *  Time functions
180 ******************************************/
181 #if defined(_WIN32)   /* Windows */
182 
183     typedef LARGE_INTEGER UTIL_time_t;
UTIL_getTime(void)184     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
UTIL_getSpanTimeMicro(UTIL_time_t clockStart,UTIL_time_t clockEnd)185     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
186     {
187         static LARGE_INTEGER ticksPerSecond;
188         static int init = 0;
189         if (!init) {
190             if (!QueryPerformanceFrequency(&ticksPerSecond))
191                 fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
192             init = 1;
193         }
194         return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
195     }
UTIL_getSpanTimeNano(UTIL_time_t clockStart,UTIL_time_t clockEnd)196     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
197     {
198         static LARGE_INTEGER ticksPerSecond;
199         static int init = 0;
200         if (!init) {
201             if (!QueryPerformanceFrequency(&ticksPerSecond))
202                 fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
203             init = 1;
204         }
205         return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
206     }
207 
208 #elif defined(__APPLE__) && defined(__MACH__)
209 
210     #include <mach/mach_time.h>
211     typedef U64 UTIL_time_t;
UTIL_getTime(void)212     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
UTIL_getSpanTimeMicro(UTIL_time_t clockStart,UTIL_time_t clockEnd)213     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
214     {
215         static mach_timebase_info_data_t rate;
216         static int init = 0;
217         if (!init) {
218             mach_timebase_info(&rate);
219             init = 1;
220         }
221         return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom)) / 1000ULL;
222     }
UTIL_getSpanTimeNano(UTIL_time_t clockStart,UTIL_time_t clockEnd)223     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
224     {
225         static mach_timebase_info_data_t rate;
226         static int init = 0;
227         if (!init) {
228             mach_timebase_info(&rate);
229             init = 1;
230         }
231         return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
232     }
233 
234 #elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || (defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2) ) )
235 
236     #include <time.h>
237     typedef struct timespec UTIL_time_t;
UTIL_getTime(void)238     UTIL_STATIC UTIL_time_t UTIL_getTime(void)
239     {
240         UTIL_time_t now;
241         if (clock_gettime(CLOCK_MONOTONIC, &now))
242             fprintf(stderr, "ERROR: Failed to get time\n");   /* we could also exit() */
243         return now;
244     }
UTIL_getSpanTime(UTIL_time_t begin,UTIL_time_t end)245     UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
246     {
247         UTIL_time_t diff;
248         if (end.tv_nsec < begin.tv_nsec) {
249             diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
250             diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
251         } else {
252             diff.tv_sec = end.tv_sec - begin.tv_sec;
253             diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
254         }
255         return diff;
256     }
UTIL_getSpanTimeMicro(UTIL_time_t begin,UTIL_time_t end)257     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
258     {
259         UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
260         U64 micro = 0;
261         micro += 1000000ULL * diff.tv_sec;
262         micro += diff.tv_nsec / 1000ULL;
263         return micro;
264     }
UTIL_getSpanTimeNano(UTIL_time_t begin,UTIL_time_t end)265     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
266     {
267         UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
268         U64 nano = 0;
269         nano += 1000000000ULL * diff.tv_sec;
270         nano += diff.tv_nsec;
271         return nano;
272     }
273 
274 #else   /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
275 
276     typedef clock_t UTIL_time_t;
UTIL_getTime(void)277     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
UTIL_getSpanTimeMicro(UTIL_time_t clockStart,UTIL_time_t clockEnd)278     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
UTIL_getSpanTimeNano(UTIL_time_t clockStart,UTIL_time_t clockEnd)279     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
280 #endif
281 
282 
283 /* returns time span in microseconds */
UTIL_clockSpanMicro(UTIL_time_t clockStart)284 UTIL_STATIC U64 UTIL_clockSpanMicro(UTIL_time_t clockStart)
285 {
286     UTIL_time_t const clockEnd = UTIL_getTime();
287     return UTIL_getSpanTimeMicro(clockStart, clockEnd);
288 }
289 
290 /* returns time span in nanoseconds */
UTIL_clockSpanNano(UTIL_time_t clockStart)291 UTIL_STATIC U64 UTIL_clockSpanNano(UTIL_time_t clockStart)
292 {
293     UTIL_time_t const clockEnd = UTIL_getTime();
294     return UTIL_getSpanTimeNano(clockStart, clockEnd);
295 }
296 
UTIL_waitForNextTick(void)297 UTIL_STATIC void UTIL_waitForNextTick(void)
298 {
299     UTIL_time_t const clockStart = UTIL_getTime();
300     UTIL_time_t clockEnd;
301     do {
302         clockEnd = UTIL_getTime();
303     } while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
304 }
305 
306 
307 
308 /*-****************************************
309 *  File functions
310 ******************************************/
311 #if defined(_MSC_VER)
312     #define chmod _chmod
313     typedef struct __stat64 stat_t;
314 #else
315     typedef struct stat stat_t;
316 #endif
317 
318 
319 UTIL_STATIC int UTIL_isRegFile(const char* infilename);
320 
321 
UTIL_setFileStat(const char * filename,stat_t * statbuf)322 UTIL_STATIC int UTIL_setFileStat(const char *filename, stat_t *statbuf)
323 {
324     int res = 0;
325 
326     if (!UTIL_isRegFile(filename))
327         return -1;
328 
329     {
330 #if defined(_WIN32) || (PLATFORM_POSIX_VERSION < 200809L)
331         struct utimbuf timebuf;
332         timebuf.actime = time(NULL);
333         timebuf.modtime = statbuf->st_mtime;
334         res += utime(filename, &timebuf);  /* set access and modification times */
335 #else
336         struct timespec timebuf[2];
337         memset(timebuf, 0, sizeof(timebuf));
338         timebuf[0].tv_nsec = UTIME_NOW;
339         timebuf[1].tv_sec = statbuf->st_mtime;
340         res += utimensat(AT_FDCWD, filename, timebuf, 0);  /* set access and modification times */
341 #endif
342     }
343 
344 #if !defined(_WIN32)
345     res += chown(filename, statbuf->st_uid, statbuf->st_gid);  /* Copy ownership */
346 #endif
347 
348     res += chmod(filename, statbuf->st_mode & 07777);  /* Copy file permissions */
349 
350     errno = 0;
351     return -res; /* number of errors is returned */
352 }
353 
354 
UTIL_getFileStat(const char * infilename,stat_t * statbuf)355 UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
356 {
357     int r;
358 #if defined(_MSC_VER)
359     r = _stat64(infilename, statbuf);
360     if (r || !(statbuf->st_mode & S_IFREG)) return 0;   /* No good... */
361 #else
362     r = stat(infilename, statbuf);
363     if (r || !S_ISREG(statbuf->st_mode)) return 0;   /* No good... */
364 #endif
365     return 1;
366 }
367 
368 
UTIL_isRegFile(const char * infilename)369 UTIL_STATIC int UTIL_isRegFile(const char* infilename)
370 {
371     stat_t statbuf;
372     return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
373 }
374 
375 
UTIL_isDirectory(const char * infilename)376 UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
377 {
378     int r;
379     stat_t statbuf;
380 #if defined(_MSC_VER)
381     r = _stat64(infilename, &statbuf);
382     if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
383 #else
384     r = stat(infilename, &statbuf);
385     if (!r && S_ISDIR(statbuf.st_mode)) return 1;
386 #endif
387     return 0;
388 }
389 
390 
UTIL_getOpenFileSize(FILE * file)391 UTIL_STATIC U64 UTIL_getOpenFileSize(FILE* file)
392 {
393     int r;
394     int fd;
395     struct UTIL_TYPE_stat statbuf;
396 
397     fd = UTIL_fileno(file);
398     if (fd < 0) {
399         perror("fileno");
400         exit(1);
401     }
402     r = UTIL_fstat(fd, &statbuf);
403     if (r || !UTIL_STAT_MODE_ISREG(statbuf.st_mode)) return 0;   /* No good... */
404     return (U64)statbuf.st_size;
405 }
406 
407 
UTIL_getFileSize(const char * infilename)408 UTIL_STATIC U64 UTIL_getFileSize(const char* infilename)
409 {
410     int r;
411     struct UTIL_TYPE_stat statbuf;
412 
413     r = UTIL_stat(infilename, &statbuf);
414     if (r || !UTIL_STAT_MODE_ISREG(statbuf.st_mode)) return 0;   /* No good... */
415     return (U64)statbuf.st_size;
416 }
417 
418 
UTIL_getTotalFileSize(const char ** fileNamesTable,unsigned nbFiles)419 UTIL_STATIC U64 UTIL_getTotalFileSize(const char** fileNamesTable, unsigned nbFiles)
420 {
421     U64 total = 0;
422     unsigned n;
423     for (n=0; n<nbFiles; n++)
424         total += UTIL_getFileSize(fileNamesTable[n]);
425     return total;
426 }
427 
428 
429 /*
430  * A modified version of realloc().
431  * If UTIL_realloc() fails the original block is freed.
432 */
UTIL_realloc(void * ptr,size_t size)433 UTIL_STATIC void* UTIL_realloc(void* ptr, size_t size)
434 {
435     void* const newptr = realloc(ptr, size);
436     if (newptr) return newptr;
437     free(ptr);
438     return NULL;
439 }
440 
441 
442 #ifdef _WIN32
443 #  define UTIL_HAS_CREATEFILELIST
444 
UTIL_prepareFileList(const char * dirName,char ** bufStart,size_t * pos,char ** bufEnd)445 UTIL_STATIC int UTIL_prepareFileList(const char* dirName, char** bufStart, size_t* pos, char** bufEnd)
446 {
447     char* path;
448     size_t dirLength, nbFiles = 0;
449     WIN32_FIND_DATAA cFile;
450     HANDLE hFile;
451 
452     dirLength = strlen(dirName);
453     path = (char*) malloc(dirLength + 3);
454     if (!path) return 0;
455 
456     memcpy(path, dirName, dirLength);
457     path[dirLength] = '\\';
458     path[dirLength+1] = '*';
459     path[dirLength+2] = 0;
460 
461     hFile=FindFirstFileA(path, &cFile);
462     if (hFile == INVALID_HANDLE_VALUE) {
463         fprintf(stderr, "Cannot open directory '%s'\n", dirName);
464         return 0;
465     }
466     free(path);
467 
468     do {
469         size_t pathLength;
470         int const fnameLength = (int)strlen(cFile.cFileName);
471         path = (char*) malloc(dirLength + fnameLength + 2);
472         if (!path) { FindClose(hFile); return 0; }
473         memcpy(path, dirName, dirLength);
474         path[dirLength] = '\\';
475         memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
476         pathLength = dirLength+1+fnameLength;
477         path[pathLength] = 0;
478         if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
479             if (strcmp (cFile.cFileName, "..") == 0 ||
480                 strcmp (cFile.cFileName, ".") == 0) continue;
481 
482             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd);  /* Recursively call "UTIL_prepareFileList" with the new path. */
483             if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
484         }
485         else if ((cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)) {
486             if (*bufStart + *pos + pathLength >= *bufEnd) {
487                 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
488                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
489                 *bufEnd = *bufStart + newListSize;
490                 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
491             }
492             if (*bufStart + *pos + pathLength < *bufEnd) {
493                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
494                 *pos += pathLength + 1;
495                 nbFiles++;
496             }
497         }
498         free(path);
499     } while (FindNextFileA(hFile, &cFile));
500 
501     FindClose(hFile);
502     assert(nbFiles < INT_MAX);
503     return (int)nbFiles;
504 }
505 
506 #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L)  /* opendir, readdir require POSIX.1-2001 */
507 #  define UTIL_HAS_CREATEFILELIST
508 #  include <dirent.h>       /* opendir, readdir */
509 #  include <string.h>       /* strerror, memcpy */
510 
UTIL_prepareFileList(const char * dirName,char ** bufStart,size_t * pos,char ** bufEnd)511 UTIL_STATIC int UTIL_prepareFileList(const char* dirName, char** bufStart, size_t* pos, char** bufEnd)
512 {
513     DIR* dir;
514     struct dirent * entry;
515     size_t dirLength;
516     int nbFiles = 0;
517 
518     if (!(dir = opendir(dirName))) {
519         fprintf(stderr, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
520         return 0;
521     }
522 
523     dirLength = strlen(dirName);
524     errno = 0;
525     while ((entry = readdir(dir)) != NULL) {
526         char* path;
527         size_t fnameLength, pathLength;
528         if (strcmp (entry->d_name, "..") == 0 ||
529             strcmp (entry->d_name, ".") == 0) continue;
530         fnameLength = strlen(entry->d_name);
531         path = (char*)malloc(dirLength + fnameLength + 2);
532         if (!path) { closedir(dir); return 0; }
533         memcpy(path, dirName, dirLength);
534         path[dirLength] = '/';
535         memcpy(path+dirLength+1, entry->d_name, fnameLength);
536         pathLength = dirLength+1+fnameLength;
537         path[pathLength] = 0;
538 
539         if (UTIL_isDirectory(path)) {
540             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd);  /* Recursively call "UTIL_prepareFileList" with the new path. */
541             if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
542         } else {
543             if (*bufStart + *pos + pathLength >= *bufEnd) {
544                 size_t const newListSize = (size_t)(*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
545                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
546                 *bufEnd = *bufStart + newListSize;
547                 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
548             }
549             if (*bufStart + *pos + pathLength < *bufEnd) {
550                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
551                 *pos += pathLength + 1;
552                 nbFiles++;
553             }
554         }
555         free(path);
556         errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
557     }
558 
559     if (errno != 0) {
560         fprintf(stderr, "readdir(%s) error: %s\n", dirName, strerror(errno));
561         free(*bufStart);
562         *bufStart = NULL;
563     }
564     closedir(dir);
565     return nbFiles;
566 }
567 
568 #else
569 
UTIL_prepareFileList(const char * dirName,char ** bufStart,size_t * pos,char ** bufEnd)570 UTIL_STATIC int UTIL_prepareFileList(const char* dirName, char** bufStart, size_t* pos, char** bufEnd)
571 {
572     (void)bufStart; (void)bufEnd; (void)pos;
573     fprintf(stderr, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
574     return 0;
575 }
576 
577 #endif /* #ifdef _WIN32 */
578 
579 /*
580  * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
581  *                       and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
582  * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
583  * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
584  */
585 UTIL_STATIC const char**
UTIL_createFileList(const char ** inputNames,unsigned inputNamesNb,char ** allocatedBuffer,unsigned * allocatedNamesNb)586 UTIL_createFileList(const char** inputNames, unsigned inputNamesNb,
587                     char** allocatedBuffer, unsigned* allocatedNamesNb)
588 {
589     size_t pos;
590     unsigned i, nbFiles;
591     char* buf = (char*)malloc(LIST_SIZE_INCREASE);
592     size_t bufSize = LIST_SIZE_INCREASE;
593     const char** fileTable;
594 
595     if (!buf) return NULL;
596 
597     for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
598         if (!UTIL_isDirectory(inputNames[i])) {
599             size_t const len = strlen(inputNames[i]) + 1;  /* include nul char */
600             if (pos + len >= bufSize) {
601                 while (pos + len >= bufSize) bufSize += LIST_SIZE_INCREASE;
602                 buf = (char*)UTIL_realloc(buf, bufSize);
603                 if (!buf) return NULL;
604             }
605             assert(pos + len < bufSize);
606             memcpy(buf + pos, inputNames[i], len);
607             pos += len;
608             nbFiles++;
609         } else {
610             char* bufend = buf + bufSize;
611             nbFiles += (unsigned)UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend);
612             if (buf == NULL) return NULL;
613             assert(bufend > buf);
614             bufSize = (size_t)(bufend - buf);
615     }   }
616 
617     if (nbFiles == 0) { free(buf); return NULL; }
618 
619     fileTable = (const char**)malloc(((size_t)nbFiles+1) * sizeof(const char*));
620     if (!fileTable) { free(buf); return NULL; }
621 
622     for (i=0, pos=0; i<nbFiles; i++) {
623         fileTable[i] = buf + pos;
624         pos += strlen(fileTable[i]) + 1;
625     }
626 
627     if (pos > bufSize) {
628         free(buf);
629         free((void*)fileTable);
630         return NULL;
631     }   /* can this happen ? */
632 
633     *allocatedBuffer = buf;
634     *allocatedNamesNb = nbFiles;
635 
636     return fileTable;
637 }
638 
639 
640 UTIL_STATIC void
UTIL_freeFileList(const char ** filenameTable,char * allocatedBuffer)641 UTIL_freeFileList(const char** filenameTable, char* allocatedBuffer)
642 {
643     if (allocatedBuffer) free(allocatedBuffer);
644     if (filenameTable) free((void*)filenameTable);
645 }
646 
647 
648 #if defined (__cplusplus)
649 }
650 #endif
651 
652 #endif /* UTIL_H_MODULE */
653