xref: /freebsd/sys/contrib/zstd/programs/util.h (revision 60fde7ce5d7bf5d94290720ea53db5701ab406a8)
1 /*
2  * Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10 
11 #ifndef UTIL_H_MODULE
12 #define UTIL_H_MODULE
13 
14 #if defined (__cplusplus)
15 extern "C" {
16 #endif
17 
18 
19 
20 /*-****************************************
21 *  Dependencies
22 ******************************************/
23 #include "platform.h"     /* PLATFORM_POSIX_VERSION */
24 #include <stdlib.h>       /* malloc */
25 #include <stddef.h>       /* size_t, ptrdiff_t */
26 #include <stdio.h>        /* fprintf */
27 #include <string.h>       /* strncmp */
28 #include <sys/types.h>    /* stat, utime */
29 #include <sys/stat.h>     /* stat */
30 #if defined(_MSC_VER)
31 #  include <sys/utime.h>  /* utime */
32 #  include <io.h>         /* _chmod */
33 #else
34 #  include <unistd.h>     /* chown, stat */
35 #  include <utime.h>      /* utime */
36 #endif
37 #include <time.h>         /* clock_t, clock, CLOCKS_PER_SEC, nanosleep */
38 #include <errno.h>
39 #include "mem.h"          /* U32, U64 */
40 
41 
42 /* ************************************************************
43 * Avoid fseek()'s 2GiB barrier with MSVC, MacOS, *BSD, MinGW
44 ***************************************************************/
45 #if defined(_MSC_VER) && (_MSC_VER >= 1400)
46 #   define UTIL_fseek _fseeki64
47 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
48 #  define UTIL_fseek fseeko
49 #elif defined(__MINGW32__) && defined(__MSVCRT__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS)
50 #   define UTIL_fseek fseeko64
51 #else
52 #   define UTIL_fseek fseek
53 #endif
54 
55 
56 /*-****************************************
57 *  Sleep functions: Windows - Posix - others
58 ******************************************/
59 #if defined(_WIN32)
60 #  include <windows.h>
61 #  define SET_REALTIME_PRIORITY SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS)
62 #  define UTIL_sleep(s) Sleep(1000*s)
63 #  define UTIL_sleepMilli(milli) Sleep(milli)
64 #elif PLATFORM_POSIX_VERSION >= 0 /* Unix-like operating system */
65 #  include <unistd.h>
66 #  include <sys/resource.h> /* setpriority */
67 #  if defined(PRIO_PROCESS)
68 #    define SET_REALTIME_PRIORITY setpriority(PRIO_PROCESS, 0, -20)
69 #  else
70 #    define SET_REALTIME_PRIORITY /* disabled */
71 #  endif
72 #  define UTIL_sleep(s) sleep(s)
73 #  if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 199309L)) || (PLATFORM_POSIX_VERSION >= 200112L)  /* nanosleep requires POSIX.1-2001 */
74 #      define UTIL_sleepMilli(milli) { struct timespec t; t.tv_sec=0; t.tv_nsec=milli*1000000ULL; nanosleep(&t, NULL); }
75 #  else
76 #      define UTIL_sleepMilli(milli) /* disabled */
77 #  endif
78 #else
79 #  define SET_REALTIME_PRIORITY      /* disabled */
80 #  define UTIL_sleep(s)          /* disabled */
81 #  define UTIL_sleepMilli(milli) /* disabled */
82 #endif
83 
84 
85 /* *************************************
86 *  Constants
87 ***************************************/
88 #define LIST_SIZE_INCREASE   (8*1024)
89 
90 
91 /*-****************************************
92 *  Compiler specifics
93 ******************************************/
94 #if defined(__INTEL_COMPILER)
95 #  pragma warning(disable : 177)    /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */
96 #endif
97 #if defined(__GNUC__)
98 #  define UTIL_STATIC static __attribute__((unused))
99 #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
100 #  define UTIL_STATIC static inline
101 #elif defined(_MSC_VER)
102 #  define UTIL_STATIC static __inline
103 #else
104 #  define UTIL_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
105 #endif
106 
107 
108 /*-****************************************
109 *  Console log
110 ******************************************/
111 static int g_utilDisplayLevel;
112 #define UTIL_DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
113 #define UTIL_DISPLAYLEVEL(l, ...) { if (g_utilDisplayLevel>=l) { UTIL_DISPLAY(__VA_ARGS__); } }
114 
115 
116 /*-****************************************
117 *  Time functions
118 ******************************************/
119 #if defined(_WIN32)   /* Windows */
120     #define UTIL_TIME_INITIALIZER { { 0, 0 } }
121     typedef LARGE_INTEGER UTIL_time_t;
122     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
123     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
124     {
125         static LARGE_INTEGER ticksPerSecond;
126         static int init = 0;
127         if (!init) {
128             if (!QueryPerformanceFrequency(&ticksPerSecond))
129                 UTIL_DISPLAYLEVEL(1, "ERROR: QueryPerformanceFrequency() failure\n");
130             init = 1;
131         }
132         return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
133     }
134     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
135     {
136         static LARGE_INTEGER ticksPerSecond;
137         static int init = 0;
138         if (!init) {
139             if (!QueryPerformanceFrequency(&ticksPerSecond))
140                 UTIL_DISPLAYLEVEL(1, "ERROR: QueryPerformanceFrequency() failure\n");
141             init = 1;
142         }
143         return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
144     }
145 #elif defined(__APPLE__) && defined(__MACH__)
146     #include <mach/mach_time.h>
147     #define UTIL_TIME_INITIALIZER 0
148     typedef U64 UTIL_time_t;
149     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
150     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
151     {
152         static mach_timebase_info_data_t rate;
153         static int init = 0;
154         if (!init) {
155             mach_timebase_info(&rate);
156             init = 1;
157         }
158         return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom))/1000ULL;
159     }
160     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
161     {
162         static mach_timebase_info_data_t rate;
163         static int init = 0;
164         if (!init) {
165             mach_timebase_info(&rate);
166             init = 1;
167         }
168         return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
169     }
170 #elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2))
171     #define UTIL_TIME_INITIALIZER { 0, 0 }
172     typedef struct timespec UTIL_freq_t;
173     typedef struct timespec UTIL_time_t;
174     UTIL_STATIC UTIL_time_t UTIL_getTime(void)
175     {
176         UTIL_time_t time;
177         if (clock_gettime(CLOCK_MONOTONIC, &time))
178             UTIL_DISPLAYLEVEL(1, "ERROR: Failed to get time\n");   /* we could also exit() */
179         return time;
180     }
181     UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
182     {
183         UTIL_time_t diff;
184         if (end.tv_nsec < begin.tv_nsec) {
185             diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
186             diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
187         } else {
188             diff.tv_sec = end.tv_sec - begin.tv_sec;
189             diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
190         }
191         return diff;
192     }
193     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
194     {
195         UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
196         U64 micro = 0;
197         micro += 1000000ULL * diff.tv_sec;
198         micro += diff.tv_nsec / 1000ULL;
199         return micro;
200     }
201     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
202     {
203         UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
204         U64 nano = 0;
205         nano += 1000000000ULL * diff.tv_sec;
206         nano += diff.tv_nsec;
207         return nano;
208     }
209 #else   /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
210     typedef clock_t UTIL_time_t;
211     #define UTIL_TIME_INITIALIZER 0
212     UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
213     UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
214     UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
215 #endif
216 
217 #define SEC_TO_MICRO 1000000
218 
219 /* returns time span in microseconds */
220 UTIL_STATIC U64 UTIL_clockSpanMicro( UTIL_time_t clockStart )
221 {
222     UTIL_time_t const clockEnd = UTIL_getTime();
223     return UTIL_getSpanTimeMicro(clockStart, clockEnd);
224 }
225 
226 
227 UTIL_STATIC void UTIL_waitForNextTick(void)
228 {
229     UTIL_time_t const clockStart = UTIL_getTime();
230     UTIL_time_t clockEnd;
231     do {
232         clockEnd = UTIL_getTime();
233     } while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
234 }
235 
236 
237 
238 /*-****************************************
239 *  File functions
240 ******************************************/
241 #if defined(_MSC_VER)
242     #define chmod _chmod
243     typedef struct __stat64 stat_t;
244 #else
245     typedef struct stat stat_t;
246 #endif
247 
248 
249 UTIL_STATIC int UTIL_setFileStat(const char *filename, stat_t *statbuf)
250 {
251     int res = 0;
252     struct utimbuf timebuf;
253 
254     timebuf.actime = time(NULL);
255     timebuf.modtime = statbuf->st_mtime;
256     res += utime(filename, &timebuf);  /* set access and modification times */
257 
258 #if !defined(_WIN32)
259     res += chown(filename, statbuf->st_uid, statbuf->st_gid);  /* Copy ownership */
260 #endif
261 
262     res += chmod(filename, statbuf->st_mode & 07777);  /* Copy file permissions */
263 
264     errno = 0;
265     return -res; /* number of errors is returned */
266 }
267 
268 
269 UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
270 {
271     int r;
272 #if defined(_MSC_VER)
273     r = _stat64(infilename, statbuf);
274     if (r || !(statbuf->st_mode & S_IFREG)) return 0;   /* No good... */
275 #else
276     r = stat(infilename, statbuf);
277     if (r || !S_ISREG(statbuf->st_mode)) return 0;   /* No good... */
278 #endif
279     return 1;
280 }
281 
282 
283 UTIL_STATIC int UTIL_isRegularFile(const char* infilename)
284 {
285     stat_t statbuf;
286     return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
287 }
288 
289 
290 UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
291 {
292     int r;
293     stat_t statbuf;
294 #if defined(_MSC_VER)
295     r = _stat64(infilename, &statbuf);
296     if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
297 #else
298     r = stat(infilename, &statbuf);
299     if (!r && S_ISDIR(statbuf.st_mode)) return 1;
300 #endif
301     return 0;
302 }
303 
304 UTIL_STATIC U32 UTIL_isLink(const char* infilename)
305 {
306 #if defined(_WIN32)
307     /* no symlinks on windows */
308     (void)infilename;
309 #else
310     int r;
311     stat_t statbuf;
312     r = lstat(infilename, &statbuf);
313     if (!r && S_ISLNK(statbuf.st_mode)) return 1;
314 #endif
315     return 0;
316 }
317 
318 
319 #define UTIL_FILESIZE_UNKNOWN  ((U64)(-1))
320 UTIL_STATIC U64 UTIL_getFileSize(const char* infilename)
321 {
322     if (!UTIL_isRegularFile(infilename)) return UTIL_FILESIZE_UNKNOWN;
323     {   int r;
324 #if defined(_MSC_VER)
325         struct __stat64 statbuf;
326         r = _stat64(infilename, &statbuf);
327         if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
328 #elif defined(__MINGW32__) && defined (__MSVCRT__)
329         struct _stati64 statbuf;
330         r = _stati64(infilename, &statbuf);
331         if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
332 #else
333         struct stat statbuf;
334         r = stat(infilename, &statbuf);
335         if (r || !S_ISREG(statbuf.st_mode)) return UTIL_FILESIZE_UNKNOWN;
336 #endif
337         return (U64)statbuf.st_size;
338     }
339 }
340 
341 
342 UTIL_STATIC U64 UTIL_getTotalFileSize(const char* const * const fileNamesTable, unsigned nbFiles)
343 {
344     U64 total = 0;
345     int error = 0;
346     unsigned n;
347     for (n=0; n<nbFiles; n++) {
348         U64 const size = UTIL_getFileSize(fileNamesTable[n]);
349         error |= (size == UTIL_FILESIZE_UNKNOWN);
350         total += size;
351     }
352     return error ? UTIL_FILESIZE_UNKNOWN : total;
353 }
354 
355 
356 /*
357  * A modified version of realloc().
358  * If UTIL_realloc() fails the original block is freed.
359 */
360 UTIL_STATIC void *UTIL_realloc(void *ptr, size_t size)
361 {
362     void *newptr = realloc(ptr, size);
363     if (newptr) return newptr;
364     free(ptr);
365     return NULL;
366 }
367 
368 #ifdef _WIN32
369 #  define UTIL_HAS_CREATEFILELIST
370 
371 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
372 {
373     char* path;
374     int dirLength, fnameLength, pathLength, nbFiles = 0;
375     WIN32_FIND_DATAA cFile;
376     HANDLE hFile;
377 
378     dirLength = (int)strlen(dirName);
379     path = (char*) malloc(dirLength + 3);
380     if (!path) return 0;
381 
382     memcpy(path, dirName, dirLength);
383     path[dirLength] = '\\';
384     path[dirLength+1] = '*';
385     path[dirLength+2] = 0;
386 
387     hFile=FindFirstFileA(path, &cFile);
388     if (hFile == INVALID_HANDLE_VALUE) {
389         UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
390         return 0;
391     }
392     free(path);
393 
394     do {
395         fnameLength = (int)strlen(cFile.cFileName);
396         path = (char*) malloc(dirLength + fnameLength + 2);
397         if (!path) { FindClose(hFile); return 0; }
398         memcpy(path, dirName, dirLength);
399         path[dirLength] = '\\';
400         memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
401         pathLength = dirLength+1+fnameLength;
402         path[pathLength] = 0;
403         if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
404             if (strcmp (cFile.cFileName, "..") == 0 ||
405                 strcmp (cFile.cFileName, ".") == 0) continue;
406 
407             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);  /* Recursively call "UTIL_prepareFileList" with the new path. */
408             if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
409         }
410         else if ((cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)) {
411             if (*bufStart + *pos + pathLength >= *bufEnd) {
412                 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
413                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
414                 *bufEnd = *bufStart + newListSize;
415                 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
416             }
417             if (*bufStart + *pos + pathLength < *bufEnd) {
418                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
419                 *pos += pathLength + 1;
420                 nbFiles++;
421             }
422         }
423         free(path);
424     } while (FindNextFileA(hFile, &cFile));
425 
426     FindClose(hFile);
427     return nbFiles;
428 }
429 
430 #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L)  /* opendir, readdir require POSIX.1-2001 */
431 #  define UTIL_HAS_CREATEFILELIST
432 #  include <dirent.h>       /* opendir, readdir */
433 #  include <string.h>       /* strerror, memcpy */
434 
435 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
436 {
437     DIR *dir;
438     struct dirent *entry;
439     char* path;
440     int dirLength, fnameLength, pathLength, nbFiles = 0;
441 
442     if (!(dir = opendir(dirName))) {
443         UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
444         return 0;
445     }
446 
447     dirLength = (int)strlen(dirName);
448     errno = 0;
449     while ((entry = readdir(dir)) != NULL) {
450         if (strcmp (entry->d_name, "..") == 0 ||
451             strcmp (entry->d_name, ".") == 0) continue;
452         fnameLength = (int)strlen(entry->d_name);
453         path = (char*) malloc(dirLength + fnameLength + 2);
454         if (!path) { closedir(dir); return 0; }
455         memcpy(path, dirName, dirLength);
456 
457         path[dirLength] = '/';
458         memcpy(path+dirLength+1, entry->d_name, fnameLength);
459         pathLength = dirLength+1+fnameLength;
460         path[pathLength] = 0;
461 
462         if (!followLinks && UTIL_isLink(path)) {
463             UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
464             continue;
465         }
466 
467         if (UTIL_isDirectory(path)) {
468             nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);  /* Recursively call "UTIL_prepareFileList" with the new path. */
469             if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
470         } else {
471             if (*bufStart + *pos + pathLength >= *bufEnd) {
472                 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
473                 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
474                 *bufEnd = *bufStart + newListSize;
475                 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
476             }
477             if (*bufStart + *pos + pathLength < *bufEnd) {
478                 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
479                 *pos += pathLength + 1;
480                 nbFiles++;
481             }
482         }
483         free(path);
484         errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
485     }
486 
487     if (errno != 0) {
488         UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s\n", dirName, strerror(errno));
489         free(*bufStart);
490         *bufStart = NULL;
491     }
492     closedir(dir);
493     return nbFiles;
494 }
495 
496 #else
497 
498 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
499 {
500     (void)bufStart; (void)bufEnd; (void)pos;
501     UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
502     return 0;
503 }
504 
505 #endif /* #ifdef _WIN32 */
506 
507 /*
508  * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
509  *                       and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
510  * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
511  * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
512  */
513 UTIL_STATIC const char** UTIL_createFileList(const char **inputNames, unsigned inputNamesNb, char** allocatedBuffer, unsigned* allocatedNamesNb, int followLinks)
514 {
515     size_t pos;
516     unsigned i, nbFiles;
517     char* buf = (char*)malloc(LIST_SIZE_INCREASE);
518     char* bufend = buf + LIST_SIZE_INCREASE;
519     const char** fileTable;
520 
521     if (!buf) return NULL;
522 
523     for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
524         if (!UTIL_isDirectory(inputNames[i])) {
525             size_t const len = strlen(inputNames[i]);
526             if (buf + pos + len >= bufend) {
527                 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
528                 buf = (char*)UTIL_realloc(buf, newListSize);
529                 bufend = buf + newListSize;
530                 if (!buf) return NULL;
531             }
532             if (buf + pos + len < bufend) {
533                 strncpy(buf + pos, inputNames[i], bufend - (buf + pos));
534                 pos += len + 1;
535                 nbFiles++;
536             }
537         } else {
538             nbFiles += UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend, followLinks);
539             if (buf == NULL) return NULL;
540     }   }
541 
542     if (nbFiles == 0) { free(buf); return NULL; }
543 
544     fileTable = (const char**)malloc((nbFiles+1) * sizeof(const char*));
545     if (!fileTable) { free(buf); return NULL; }
546 
547     for (i=0, pos=0; i<nbFiles; i++) {
548         fileTable[i] = buf + pos;
549         pos += strlen(fileTable[i]) + 1;
550     }
551 
552     if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
553 
554     *allocatedBuffer = buf;
555     *allocatedNamesNb = nbFiles;
556 
557     return fileTable;
558 }
559 
560 
561 UTIL_STATIC void UTIL_freeFileList(const char** filenameTable, char* allocatedBuffer)
562 {
563     if (allocatedBuffer) free(allocatedBuffer);
564     if (filenameTable) free((void*)filenameTable);
565 }
566 
567 /* count the number of physical cores */
568 #if defined(_WIN32) || defined(WIN32)
569 
570 #include <windows.h>
571 
572 typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
573 
574 UTIL_STATIC int UTIL_countPhysicalCores(void)
575 {
576     static int numPhysicalCores = 0;
577     if (numPhysicalCores != 0) return numPhysicalCores;
578 
579     {   LPFN_GLPI glpi;
580         BOOL done = FALSE;
581         PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
582         PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
583         DWORD returnLength = 0;
584         size_t byteOffset = 0;
585 
586         glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
587                                          "GetLogicalProcessorInformation");
588 
589         if (glpi == NULL) {
590             goto failed;
591         }
592 
593         while(!done) {
594             DWORD rc = glpi(buffer, &returnLength);
595             if (FALSE == rc) {
596                 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
597                     if (buffer)
598                         free(buffer);
599                     buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
600 
601                     if (buffer == NULL) {
602                         perror("zstd");
603                         exit(1);
604                     }
605                 } else {
606                     /* some other error */
607                     goto failed;
608                 }
609             } else {
610                 done = TRUE;
611             }
612         }
613 
614         ptr = buffer;
615 
616         while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
617 
618             if (ptr->Relationship == RelationProcessorCore) {
619                 numPhysicalCores++;
620             }
621 
622             ptr++;
623             byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
624         }
625 
626         free(buffer);
627 
628         return numPhysicalCores;
629     }
630 
631 failed:
632     /* try to fall back on GetSystemInfo */
633     {   SYSTEM_INFO sysinfo;
634         GetSystemInfo(&sysinfo);
635         numPhysicalCores = sysinfo.dwNumberOfProcessors;
636         if (numPhysicalCores == 0) numPhysicalCores = 1; /* just in case */
637     }
638     return numPhysicalCores;
639 }
640 
641 #elif defined(__APPLE__)
642 
643 #include <sys/sysctl.h>
644 
645 /* Use apple-provided syscall
646  * see: man 3 sysctl */
647 UTIL_STATIC int UTIL_countPhysicalCores(void)
648 {
649     static S32 numPhysicalCores = 0; /* apple specifies int32_t */
650     if (numPhysicalCores != 0) return numPhysicalCores;
651 
652     {   size_t size = sizeof(S32);
653         int const ret = sysctlbyname("hw.physicalcpu", &numPhysicalCores, &size, NULL, 0);
654         if (ret != 0) {
655             if (errno == ENOENT) {
656                 /* entry not present, fall back on 1 */
657                 numPhysicalCores = 1;
658             } else {
659                 perror("zstd: can't get number of physical cpus");
660                 exit(1);
661             }
662         }
663 
664         return numPhysicalCores;
665     }
666 }
667 
668 #elif defined(__linux__)
669 
670 /* parse /proc/cpuinfo
671  * siblings / cpu cores should give hyperthreading ratio
672  * otherwise fall back on sysconf */
673 UTIL_STATIC int UTIL_countPhysicalCores(void)
674 {
675     static int numPhysicalCores = 0;
676 
677     if (numPhysicalCores != 0) return numPhysicalCores;
678 
679     numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
680     if (numPhysicalCores == -1) {
681         /* value not queryable, fall back on 1 */
682         return numPhysicalCores = 1;
683     }
684 
685     /* try to determine if there's hyperthreading */
686     {   FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
687 #define BUF_SIZE 80
688         char buff[BUF_SIZE];
689 
690         int siblings = 0;
691         int cpu_cores = 0;
692         int ratio = 1;
693 
694         if (cpuinfo == NULL) {
695             /* fall back on the sysconf value */
696             return numPhysicalCores;
697         }
698 
699         /* assume the cpu cores/siblings values will be constant across all
700          * present processors */
701         while (!feof(cpuinfo)) {
702             if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
703                 if (strncmp(buff, "siblings", 8) == 0) {
704                     const char* const sep = strchr(buff, ':');
705                     if (*sep == '\0') {
706                         /* formatting was broken? */
707                         goto failed;
708                     }
709 
710                     siblings = atoi(sep + 1);
711                 }
712                 if (strncmp(buff, "cpu cores", 9) == 0) {
713                     const char* const sep = strchr(buff, ':');
714                     if (*sep == '\0') {
715                         /* formatting was broken? */
716                         goto failed;
717                     }
718 
719                     cpu_cores = atoi(sep + 1);
720                 }
721             } else if (ferror(cpuinfo)) {
722                 /* fall back on the sysconf value */
723                 goto failed;
724             }
725         }
726         if (siblings && cpu_cores) {
727             ratio = siblings / cpu_cores;
728         }
729 failed:
730         fclose(cpuinfo);
731         return numPhysicalCores = numPhysicalCores / ratio;
732     }
733 }
734 
735 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
736 
737 /* Use apple-provided syscall
738  * see: man 3 sysctl */
739 UTIL_STATIC int UTIL_countPhysicalCores(void)
740 {
741     static int numPhysicalCores = 0;
742 
743     if (numPhysicalCores != 0) return numPhysicalCores;
744 
745     numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
746     if (numPhysicalCores == -1) {
747         /* value not queryable, fall back on 1 */
748         return numPhysicalCores = 1;
749     }
750     return numPhysicalCores;
751 }
752 
753 #else
754 
755 UTIL_STATIC int UTIL_countPhysicalCores(void)
756 {
757     /* assume 1 */
758     return 1;
759 }
760 
761 #endif
762 
763 #if defined (__cplusplus)
764 }
765 #endif
766 
767 #endif /* UTIL_H_MODULE */
768