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