2 * Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
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.
14 #if defined (__cplusplus)
20 /*-****************************************
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 */
31 # include <sys/utime.h> /* utime */
32 # include <io.h> /* _chmod */
34 # include <unistd.h> /* chown, stat */
35 # include <utime.h> /* utime */
37 #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC, nanosleep */
39 #include "mem.h" /* U32, U64 */
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
52 # define UTIL_fseek fseek
56 /*-****************************************
57 * Sleep functions: Windows - Posix - others
58 ******************************************/
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 */
66 # include <sys/resource.h> /* setpriority */
67 # if defined(PRIO_PROCESS)
68 # define SET_REALTIME_PRIORITY setpriority(PRIO_PROCESS, 0, -20)
70 # define SET_REALTIME_PRIORITY /* disabled */
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); }
76 # define UTIL_sleepMilli(milli) /* disabled */
79 # define SET_REALTIME_PRIORITY /* disabled */
80 # define UTIL_sleep(s) /* disabled */
81 # define UTIL_sleepMilli(milli) /* disabled */
85 /* *************************************
87 ***************************************/
88 #define LIST_SIZE_INCREASE (8*1024)
91 /*-****************************************
93 ******************************************/
94 #if defined(__INTEL_COMPILER)
95 # pragma warning(disable : 177) /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */
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
104 # define UTIL_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
108 /*-****************************************
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__); } }
116 /*-****************************************
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)
125 static LARGE_INTEGER ticksPerSecond;
128 if (!QueryPerformanceFrequency(&ticksPerSecond))
129 UTIL_DISPLAYLEVEL(1, "ERROR: QueryPerformanceFrequency() failure\n");
132 return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
134 UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
136 static LARGE_INTEGER ticksPerSecond;
139 if (!QueryPerformanceFrequency(&ticksPerSecond))
140 UTIL_DISPLAYLEVEL(1, "ERROR: QueryPerformanceFrequency() failure\n");
143 return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
146 #elif defined(__APPLE__) && defined(__MACH__)
148 #include <mach/mach_time.h>
149 #define UTIL_TIME_INITIALIZER 0
150 typedef U64 UTIL_time_t;
151 UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
152 UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
154 static mach_timebase_info_data_t rate;
157 mach_timebase_info(&rate);
160 return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom))/1000ULL;
162 UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
164 static mach_timebase_info_data_t rate;
167 mach_timebase_info(&rate);
170 return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
173 #elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2))
175 #define UTIL_TIME_INITIALIZER { 0, 0 }
176 typedef struct timespec UTIL_freq_t;
177 typedef struct timespec UTIL_time_t;
178 UTIL_STATIC UTIL_time_t UTIL_getTime(void)
181 if (clock_gettime(CLOCK_MONOTONIC, &time))
182 UTIL_DISPLAYLEVEL(1, "ERROR: Failed to get time\n"); /* we could also exit() */
185 UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
188 if (end.tv_nsec < begin.tv_nsec) {
189 diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
190 diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
192 diff.tv_sec = end.tv_sec - begin.tv_sec;
193 diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
197 UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
199 UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
201 micro += 1000000ULL * diff.tv_sec;
202 micro += diff.tv_nsec / 1000ULL;
205 UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
207 UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
209 nano += 1000000000ULL * diff.tv_sec;
210 nano += diff.tv_nsec;
213 #else /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
214 typedef clock_t UTIL_time_t;
215 #define UTIL_TIME_INITIALIZER 0
216 UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
217 UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
218 UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
221 #define SEC_TO_MICRO 1000000
223 /* returns time span in microseconds */
224 UTIL_STATIC U64 UTIL_clockSpanMicro(UTIL_time_t clockStart )
226 UTIL_time_t const clockEnd = UTIL_getTime();
227 return UTIL_getSpanTimeMicro(clockStart, clockEnd);
230 /* returns time span in microseconds */
231 UTIL_STATIC U64 UTIL_clockSpanNano(UTIL_time_t clockStart )
233 UTIL_time_t const clockEnd = UTIL_getTime();
234 return UTIL_getSpanTimeNano(clockStart, clockEnd);
237 UTIL_STATIC void UTIL_waitForNextTick(void)
239 UTIL_time_t const clockStart = UTIL_getTime();
240 UTIL_time_t clockEnd;
242 clockEnd = UTIL_getTime();
243 } while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
248 /*-****************************************
250 ******************************************/
251 #if defined(_MSC_VER)
253 typedef struct __stat64 stat_t;
255 typedef struct stat stat_t;
259 UTIL_STATIC int UTIL_isRegularFile(const char* infilename);
262 UTIL_STATIC int UTIL_setFileStat(const char *filename, stat_t *statbuf)
265 struct utimbuf timebuf;
267 if (!UTIL_isRegularFile(filename))
270 timebuf.actime = time(NULL);
271 timebuf.modtime = statbuf->st_mtime;
272 res += utime(filename, &timebuf); /* set access and modification times */
275 res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */
278 res += chmod(filename, statbuf->st_mode & 07777); /* Copy file permissions */
281 return -res; /* number of errors is returned */
285 UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
288 #if defined(_MSC_VER)
289 r = _stat64(infilename, statbuf);
290 if (r || !(statbuf->st_mode & S_IFREG)) return 0; /* No good... */
292 r = stat(infilename, statbuf);
293 if (r || !S_ISREG(statbuf->st_mode)) return 0; /* No good... */
299 UTIL_STATIC int UTIL_isRegularFile(const char* infilename)
302 return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
306 UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
310 #if defined(_MSC_VER)
311 r = _stat64(infilename, &statbuf);
312 if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
314 r = stat(infilename, &statbuf);
315 if (!r && S_ISDIR(statbuf.st_mode)) return 1;
320 UTIL_STATIC U32 UTIL_isLink(const char* infilename)
323 /* no symlinks on windows */
328 r = lstat(infilename, &statbuf);
329 if (!r && S_ISLNK(statbuf.st_mode)) return 1;
335 #define UTIL_FILESIZE_UNKNOWN ((U64)(-1))
336 UTIL_STATIC U64 UTIL_getFileSize(const char* infilename)
338 if (!UTIL_isRegularFile(infilename)) return UTIL_FILESIZE_UNKNOWN;
340 #if defined(_MSC_VER)
341 struct __stat64 statbuf;
342 r = _stat64(infilename, &statbuf);
343 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
344 #elif defined(__MINGW32__) && defined (__MSVCRT__)
345 struct _stati64 statbuf;
346 r = _stati64(infilename, &statbuf);
347 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
350 r = stat(infilename, &statbuf);
351 if (r || !S_ISREG(statbuf.st_mode)) return UTIL_FILESIZE_UNKNOWN;
353 return (U64)statbuf.st_size;
358 UTIL_STATIC U64 UTIL_getTotalFileSize(const char* const * const fileNamesTable, unsigned nbFiles)
363 for (n=0; n<nbFiles; n++) {
364 U64 const size = UTIL_getFileSize(fileNamesTable[n]);
365 error |= (size == UTIL_FILESIZE_UNKNOWN);
368 return error ? UTIL_FILESIZE_UNKNOWN : total;
373 * A modified version of realloc().
374 * If UTIL_realloc() fails the original block is freed.
376 UTIL_STATIC void *UTIL_realloc(void *ptr, size_t size)
378 void *newptr = realloc(ptr, size);
379 if (newptr) return newptr;
385 # define UTIL_HAS_CREATEFILELIST
387 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
390 int dirLength, fnameLength, pathLength, nbFiles = 0;
391 WIN32_FIND_DATAA cFile;
394 dirLength = (int)strlen(dirName);
395 path = (char*) malloc(dirLength + 3);
398 memcpy(path, dirName, dirLength);
399 path[dirLength] = '\\';
400 path[dirLength+1] = '*';
401 path[dirLength+2] = 0;
403 hFile=FindFirstFileA(path, &cFile);
404 if (hFile == INVALID_HANDLE_VALUE) {
405 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
411 fnameLength = (int)strlen(cFile.cFileName);
412 path = (char*) malloc(dirLength + fnameLength + 2);
413 if (!path) { FindClose(hFile); return 0; }
414 memcpy(path, dirName, dirLength);
415 path[dirLength] = '\\';
416 memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
417 pathLength = dirLength+1+fnameLength;
418 path[pathLength] = 0;
419 if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
420 if (strcmp (cFile.cFileName, "..") == 0 ||
421 strcmp (cFile.cFileName, ".") == 0) continue;
423 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
424 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
426 else if ((cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)) {
427 if (*bufStart + *pos + pathLength >= *bufEnd) {
428 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
429 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
430 *bufEnd = *bufStart + newListSize;
431 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
433 if (*bufStart + *pos + pathLength < *bufEnd) {
434 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
435 *pos += pathLength + 1;
440 } while (FindNextFileA(hFile, &cFile));
446 #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
447 # define UTIL_HAS_CREATEFILELIST
448 # include <dirent.h> /* opendir, readdir */
449 # include <string.h> /* strerror, memcpy */
451 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
454 struct dirent *entry;
456 int dirLength, fnameLength, pathLength, nbFiles = 0;
458 if (!(dir = opendir(dirName))) {
459 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
463 dirLength = (int)strlen(dirName);
465 while ((entry = readdir(dir)) != NULL) {
466 if (strcmp (entry->d_name, "..") == 0 ||
467 strcmp (entry->d_name, ".") == 0) continue;
468 fnameLength = (int)strlen(entry->d_name);
469 path = (char*) malloc(dirLength + fnameLength + 2);
470 if (!path) { closedir(dir); return 0; }
471 memcpy(path, dirName, dirLength);
473 path[dirLength] = '/';
474 memcpy(path+dirLength+1, entry->d_name, fnameLength);
475 pathLength = dirLength+1+fnameLength;
476 path[pathLength] = 0;
478 if (!followLinks && UTIL_isLink(path)) {
479 UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
483 if (UTIL_isDirectory(path)) {
484 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
485 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
487 if (*bufStart + *pos + pathLength >= *bufEnd) {
488 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
489 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
490 *bufEnd = *bufStart + newListSize;
491 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
493 if (*bufStart + *pos + pathLength < *bufEnd) {
494 strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos));
495 *pos += pathLength + 1;
500 errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
504 UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s\n", dirName, strerror(errno));
514 UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
516 (void)bufStart; (void)bufEnd; (void)pos;
517 UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
521 #endif /* #ifdef _WIN32 */
524 * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
525 * and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
526 * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
527 * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
529 UTIL_STATIC const char** UTIL_createFileList(const char **inputNames, unsigned inputNamesNb, char** allocatedBuffer, unsigned* allocatedNamesNb, int followLinks)
533 char* buf = (char*)malloc(LIST_SIZE_INCREASE);
534 char* bufend = buf + LIST_SIZE_INCREASE;
535 const char** fileTable;
537 if (!buf) return NULL;
539 for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
540 if (!UTIL_isDirectory(inputNames[i])) {
541 size_t const len = strlen(inputNames[i]);
542 if (buf + pos + len >= bufend) {
543 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
544 buf = (char*)UTIL_realloc(buf, newListSize);
545 bufend = buf + newListSize;
546 if (!buf) return NULL;
548 if (buf + pos + len < bufend) {
549 strncpy(buf + pos, inputNames[i], bufend - (buf + pos));
554 nbFiles += UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend, followLinks);
555 if (buf == NULL) return NULL;
558 if (nbFiles == 0) { free(buf); return NULL; }
560 fileTable = (const char**)malloc((nbFiles+1) * sizeof(const char*));
561 if (!fileTable) { free(buf); return NULL; }
563 for (i=0, pos=0; i<nbFiles; i++) {
564 fileTable[i] = buf + pos;
565 pos += strlen(fileTable[i]) + 1;
568 if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
570 *allocatedBuffer = buf;
571 *allocatedNamesNb = nbFiles;
577 UTIL_STATIC void UTIL_freeFileList(const char** filenameTable, char* allocatedBuffer)
579 if (allocatedBuffer) free(allocatedBuffer);
580 if (filenameTable) free((void*)filenameTable);
583 /* count the number of physical cores */
584 #if defined(_WIN32) || defined(WIN32)
588 typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
590 UTIL_STATIC int UTIL_countPhysicalCores(void)
592 static int numPhysicalCores = 0;
593 if (numPhysicalCores != 0) return numPhysicalCores;
597 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
598 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
599 DWORD returnLength = 0;
600 size_t byteOffset = 0;
602 glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
603 "GetLogicalProcessorInformation");
610 DWORD rc = glpi(buffer, &returnLength);
612 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
615 buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
617 if (buffer == NULL) {
622 /* some other error */
632 while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
634 if (ptr->Relationship == RelationProcessorCore) {
639 byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
644 return numPhysicalCores;
648 /* try to fall back on GetSystemInfo */
649 { SYSTEM_INFO sysinfo;
650 GetSystemInfo(&sysinfo);
651 numPhysicalCores = sysinfo.dwNumberOfProcessors;
652 if (numPhysicalCores == 0) numPhysicalCores = 1; /* just in case */
654 return numPhysicalCores;
657 #elif defined(__APPLE__)
659 #include <sys/sysctl.h>
661 /* Use apple-provided syscall
662 * see: man 3 sysctl */
663 UTIL_STATIC int UTIL_countPhysicalCores(void)
665 static S32 numPhysicalCores = 0; /* apple specifies int32_t */
666 if (numPhysicalCores != 0) return numPhysicalCores;
668 { size_t size = sizeof(S32);
669 int const ret = sysctlbyname("hw.physicalcpu", &numPhysicalCores, &size, NULL, 0);
671 if (errno == ENOENT) {
672 /* entry not present, fall back on 1 */
673 numPhysicalCores = 1;
675 perror("zstd: can't get number of physical cpus");
680 return numPhysicalCores;
684 #elif defined(__linux__)
686 /* parse /proc/cpuinfo
687 * siblings / cpu cores should give hyperthreading ratio
688 * otherwise fall back on sysconf */
689 UTIL_STATIC int UTIL_countPhysicalCores(void)
691 static int numPhysicalCores = 0;
693 if (numPhysicalCores != 0) return numPhysicalCores;
695 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
696 if (numPhysicalCores == -1) {
697 /* value not queryable, fall back on 1 */
698 return numPhysicalCores = 1;
701 /* try to determine if there's hyperthreading */
702 { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
710 if (cpuinfo == NULL) {
711 /* fall back on the sysconf value */
712 return numPhysicalCores;
715 /* assume the cpu cores/siblings values will be constant across all
716 * present processors */
717 while (!feof(cpuinfo)) {
718 if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
719 if (strncmp(buff, "siblings", 8) == 0) {
720 const char* const sep = strchr(buff, ':');
722 /* formatting was broken? */
726 siblings = atoi(sep + 1);
728 if (strncmp(buff, "cpu cores", 9) == 0) {
729 const char* const sep = strchr(buff, ':');
731 /* formatting was broken? */
735 cpu_cores = atoi(sep + 1);
737 } else if (ferror(cpuinfo)) {
738 /* fall back on the sysconf value */
742 if (siblings && cpu_cores) {
743 ratio = siblings / cpu_cores;
747 return numPhysicalCores = numPhysicalCores / ratio;
751 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
753 /* Use apple-provided syscall
754 * see: man 3 sysctl */
755 UTIL_STATIC int UTIL_countPhysicalCores(void)
757 static int numPhysicalCores = 0;
759 if (numPhysicalCores != 0) return numPhysicalCores;
761 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
762 if (numPhysicalCores == -1) {
763 /* value not queryable, fall back on 1 */
764 return numPhysicalCores = 1;
766 return numPhysicalCores;
771 UTIL_STATIC int UTIL_countPhysicalCores(void)
779 #if defined (__cplusplus)
783 #endif /* UTIL_H_MODULE */