blob: de25bc2327f0bab4c3e055254304b506916fa889 [file] [log] [blame]
Rohit Jainf881ee82018-10-11 12:52:19 -07001/*
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#if defined (__cplusplus)
12extern "C" {
13#endif
14
15
16/*-****************************************
17* Dependencies
18******************************************/
Yann Colletffba1422018-12-20 14:30:30 -080019#include "util.h" /* note : ensure that platform.h is included first ! */
Yann Collet173ef9d2018-12-19 18:30:57 -080020#include <errno.h>
Yann Collet72dbf1b2018-12-20 12:27:12 -080021#include <assert.h>
Yann Collet173ef9d2018-12-19 18:30:57 -080022
Sen Huang62616c42019-09-06 13:20:50 -070023#if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
24#include <direct.h> /* needed for _mkdir in windows */
25#endif
Rohit Jainf881ee82018-10-11 12:52:19 -070026
Yann Collet173ef9d2018-12-19 18:30:57 -080027int UTIL_fileExist(const char* filename)
28{
29 stat_t statbuf;
Yann Collet105fa952018-12-20 09:16:40 -080030#if defined(_MSC_VER)
31 int const stat_error = _stat64(filename, &statbuf);
32#else
33 int const stat_error = stat(filename, &statbuf);
34#endif
35 return !stat_error;
Yann Collet173ef9d2018-12-19 18:30:57 -080036}
37
Rohit Jaind6d240f2018-10-11 15:07:12 -070038int UTIL_isRegularFile(const char* infilename)
39{
40 stat_t statbuf;
41 return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
42}
43
44int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
45{
46 int r;
47#if defined(_MSC_VER)
48 r = _stat64(infilename, statbuf);
49 if (r || !(statbuf->st_mode & S_IFREG)) return 0; /* No good... */
50#else
51 r = stat(infilename, statbuf);
52 if (r || !S_ISREG(statbuf->st_mode)) return 0; /* No good... */
53#endif
54 return 1;
55}
56
57int UTIL_setFileStat(const char *filename, stat_t *statbuf)
58{
59 int res = 0;
Rohit Jaind6d240f2018-10-11 15:07:12 -070060
61 if (!UTIL_isRegularFile(filename))
62 return -1;
63
W. Felix Handtee1ec8002019-09-12 16:27:05 -040064 /* set access and modification times */
Rosen Penev41e90652019-07-30 17:17:07 -070065#if defined(_WIN32) || (PLATFORM_POSIX_VERSION < 200809L)
W. Felix Handtee1ec8002019-09-12 16:27:05 -040066 {
67 struct utimbuf timebuf;
68 timebuf.actime = time(NULL);
69 timebuf.modtime = statbuf->st_mtime;
70 res += utime(filename, &timebuf);
71 }
Rosen Penev41e90652019-07-30 17:17:07 -070072#else
W. Felix Handtee1ec8002019-09-12 16:27:05 -040073 {
74 /* (atime, mtime) */
Yann Collete0d413d2019-10-04 15:09:52 -070075 struct timespec timebuf[2] = { {0, UTIME_NOW} };
76 timebuf[1] = statbuf->st_mtim;
W. Felix Handtee1ec8002019-09-12 16:27:05 -040077 res += utimensat(AT_FDCWD, filename, timebuf, 0);
78 }
Rosen Penev41e90652019-07-30 17:17:07 -070079#endif
Rohit Jaind6d240f2018-10-11 15:07:12 -070080
81#if !defined(_WIN32)
82 res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */
83#endif
84
85 res += chmod(filename, statbuf->st_mode & 07777); /* Copy file permissions */
86
87 errno = 0;
88 return -res; /* number of errors is returned */
89}
Rohit Jainf881ee82018-10-11 12:52:19 -070090
91U32 UTIL_isDirectory(const char* infilename)
92{
93 int r;
94 stat_t statbuf;
95#if defined(_MSC_VER)
96 r = _stat64(infilename, &statbuf);
97 if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
98#else
99 r = stat(infilename, &statbuf);
100 if (!r && S_ISDIR(statbuf.st_mode)) return 1;
101#endif
102 return 0;
103}
104
Sen Huangf80437c2019-10-02 11:08:20 -0400105int UTIL_compareStr(const void *p1, const void *p2) {
106 return strcmp(* (char * const *) p1, * (char * const *) p2);
107}
Sen Huanga9c807a2019-09-06 10:17:04 -0700108
Yann Collet00040432019-10-17 10:56:14 -0700109int UTIL_isSameFile(const char* fName1, const char* fName2)
shakeelraoe5811e52019-03-23 19:04:56 -0700110{
Yann Collet00040432019-10-17 10:56:14 -0700111 assert(fName1 != NULL); assert(fName2 != NULL);
112#if defined(_MSC_VER) || defined(_WIN32)
shakeelraoe5811e52019-03-23 19:04:56 -0700113 /* note : Visual does not support file identification by inode.
Yann Collet00040432019-10-17 10:56:14 -0700114 * inode does not work on Windows, even with a posix layer, like msys2.
shakeelraoe5811e52019-03-23 19:04:56 -0700115 * The following work-around is limited to detecting exact name repetition only,
116 * aka `filename` is considered different from `subdir/../filename` */
Yann Collet157479a2019-10-17 14:31:42 -0700117 return !strcmp(fName1, fName2);
shakeelraoe5811e52019-03-23 19:04:56 -0700118#else
Yann Collet00040432019-10-17 10:56:14 -0700119 { stat_t file1Stat;
120 stat_t file2Stat;
121 return UTIL_getFileStat(fName1, &file1Stat)
122 && UTIL_getFileStat(fName2, &file2Stat)
123 && (file1Stat.st_dev == file2Stat.st_dev)
124 && (file1Stat.st_ino == file2Stat.st_ino);
125 }
shakeelraoe5811e52019-03-23 19:04:56 -0700126#endif
127}
128
Rohit Jainf881ee82018-10-11 12:52:19 -0700129U32 UTIL_isLink(const char* infilename)
130{
131/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
W. Felix Handted2c48042019-06-07 15:31:33 -0400132#if PLATFORM_POSIX_VERSION >= 200112L
Rohit Jainf881ee82018-10-11 12:52:19 -0700133 int r;
134 stat_t statbuf;
135 r = lstat(infilename, &statbuf);
136 if (!r && S_ISLNK(statbuf.st_mode)) return 1;
137#endif
Rohit Jainf881ee82018-10-11 12:52:19 -0700138 (void)infilename;
139 return 0;
140}
141
142U64 UTIL_getFileSize(const char* infilename)
143{
144 if (!UTIL_isRegularFile(infilename)) return UTIL_FILESIZE_UNKNOWN;
145 { int r;
146#if defined(_MSC_VER)
147 struct __stat64 statbuf;
148 r = _stat64(infilename, &statbuf);
149 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
150#elif defined(__MINGW32__) && defined (__MSVCRT__)
151 struct _stati64 statbuf;
152 r = _stati64(infilename, &statbuf);
153 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
154#else
155 struct stat statbuf;
156 r = stat(infilename, &statbuf);
157 if (r || !S_ISREG(statbuf.st_mode)) return UTIL_FILESIZE_UNKNOWN;
158#endif
159 return (U64)statbuf.st_size;
160 }
161}
162
163
164U64 UTIL_getTotalFileSize(const char* const * const fileNamesTable, unsigned nbFiles)
165{
166 U64 total = 0;
167 int error = 0;
168 unsigned n;
169 for (n=0; n<nbFiles; n++) {
170 U64 const size = UTIL_getFileSize(fileNamesTable[n]);
171 error |= (size == UTIL_FILESIZE_UNKNOWN);
172 total += size;
173 }
174 return error ? UTIL_FILESIZE_UNKNOWN : total;
175}
176
Rohit Jainc7251e52018-10-11 18:05:15 -0700177#ifdef _WIN32
Rohit Jain705e0b12018-10-11 15:51:57 -0700178int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
179{
180 char* path;
181 int dirLength, fnameLength, pathLength, nbFiles = 0;
182 WIN32_FIND_DATAA cFile;
183 HANDLE hFile;
184
185 dirLength = (int)strlen(dirName);
186 path = (char*) malloc(dirLength + 3);
187 if (!path) return 0;
188
189 memcpy(path, dirName, dirLength);
190 path[dirLength] = '\\';
191 path[dirLength+1] = '*';
192 path[dirLength+2] = 0;
193
194 hFile=FindFirstFileA(path, &cFile);
195 if (hFile == INVALID_HANDLE_VALUE) {
196 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
197 return 0;
198 }
199 free(path);
200
201 do {
202 fnameLength = (int)strlen(cFile.cFileName);
203 path = (char*) malloc(dirLength + fnameLength + 2);
204 if (!path) { FindClose(hFile); return 0; }
205 memcpy(path, dirName, dirLength);
206 path[dirLength] = '\\';
207 memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
208 pathLength = dirLength+1+fnameLength;
209 path[pathLength] = 0;
210 if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800211 if ( strcmp (cFile.cFileName, "..") == 0
212 || strcmp (cFile.cFileName, ".") == 0 )
213 continue;
214 /* Recursively call "UTIL_prepareFileList" with the new path. */
215 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);
Rohit Jain705e0b12018-10-11 15:51:57 -0700216 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800217 } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
218 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
219 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) {
Rohit Jain705e0b12018-10-11 15:51:57 -0700220 if (*bufStart + *pos + pathLength >= *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800221 ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
Rohit Jain705e0b12018-10-11 15:51:57 -0700222 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700223 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800224 *bufEnd = *bufStart + newListSize;
Rohit Jain705e0b12018-10-11 15:51:57 -0700225 }
226 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800227 memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */);
Rohit Jain705e0b12018-10-11 15:51:57 -0700228 *pos += pathLength + 1;
229 nbFiles++;
230 }
231 }
232 free(path);
233 } while (FindNextFileA(hFile, &cFile));
234
235 FindClose(hFile);
236 return nbFiles;
237}
238
239#elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
240
241int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
242{
243 DIR *dir;
244 struct dirent *entry;
245 char* path;
Yann Colleta71256a2019-10-17 11:01:20 -0700246 size_t dirLength, fnameLength, pathLength;
247 int nbFiles = 0;
Rohit Jain705e0b12018-10-11 15:51:57 -0700248
249 if (!(dir = opendir(dirName))) {
250 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
251 return 0;
252 }
253
Yann Colleta71256a2019-10-17 11:01:20 -0700254 dirLength = strlen(dirName);
Rohit Jain705e0b12018-10-11 15:51:57 -0700255 errno = 0;
256 while ((entry = readdir(dir)) != NULL) {
257 if (strcmp (entry->d_name, "..") == 0 ||
258 strcmp (entry->d_name, ".") == 0) continue;
Yann Colleta71256a2019-10-17 11:01:20 -0700259 fnameLength = strlen(entry->d_name);
Rohit Jain705e0b12018-10-11 15:51:57 -0700260 path = (char*) malloc(dirLength + fnameLength + 2);
261 if (!path) { closedir(dir); return 0; }
262 memcpy(path, dirName, dirLength);
263
264 path[dirLength] = '/';
265 memcpy(path+dirLength+1, entry->d_name, fnameLength);
266 pathLength = dirLength+1+fnameLength;
267 path[pathLength] = 0;
268
269 if (!followLinks && UTIL_isLink(path)) {
270 UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
LeeYoung624793b94b2019-07-25 21:07:57 +0800271 free(path);
Rohit Jain705e0b12018-10-11 15:51:57 -0700272 continue;
273 }
274
275 if (UTIL_isDirectory(path)) {
276 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
277 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
278 } else {
279 if (*bufStart + *pos + pathLength >= *bufEnd) {
280 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
Yann Colleta71256a2019-10-17 11:01:20 -0700281 assert(newListSize >= 0);
282 *bufStart = (char*)UTIL_realloc(*bufStart, (size_t)newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700283 *bufEnd = *bufStart + newListSize;
284 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
285 }
286 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800287 memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */
Rohit Jain705e0b12018-10-11 15:51:57 -0700288 *pos += pathLength + 1;
289 nbFiles++;
290 }
291 }
292 free(path);
293 errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
294 }
295
296 if (errno != 0) {
297 UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s\n", dirName, strerror(errno));
298 free(*bufStart);
299 *bufStart = NULL;
300 }
301 closedir(dir);
302 return nbFiles;
303}
304
305#else
306
307int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
308{
309 (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks;
310 UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
311 return 0;
312}
313
314#endif /* #ifdef _WIN32 */
315
316/*
317 * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
318 * and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
319 * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
320 * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
321 */
322const char**
323UTIL_createFileList(const char **inputNames, unsigned inputNamesNb,
324 char** allocatedBuffer, unsigned* allocatedNamesNb,
325 int followLinks)
326{
327 size_t pos;
328 unsigned i, nbFiles;
329 char* buf = (char*)malloc(LIST_SIZE_INCREASE);
330 char* bufend = buf + LIST_SIZE_INCREASE;
Rohit Jain705e0b12018-10-11 15:51:57 -0700331
332 if (!buf) return NULL;
333
334 for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
335 if (!UTIL_isDirectory(inputNames[i])) {
336 size_t const len = strlen(inputNames[i]);
337 if (buf + pos + len >= bufend) {
338 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
Yann Colleta71256a2019-10-17 11:01:20 -0700339 assert(newListSize >= 0);
340 buf = (char*)UTIL_realloc(buf, (size_t)newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700341 bufend = buf + newListSize;
342 if (!buf) return NULL;
343 }
344 if (buf + pos + len < bufend) {
Yann Collet29e46ed2019-10-18 14:28:34 -0700345 memcpy(buf+pos, inputNames[i], len+1); /* including final \0 */
Rohit Jain705e0b12018-10-11 15:51:57 -0700346 pos += len + 1;
347 nbFiles++;
348 }
349 } else {
Yann Colleta71256a2019-10-17 11:01:20 -0700350 nbFiles += (unsigned)UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend, followLinks);
Rohit Jain705e0b12018-10-11 15:51:57 -0700351 if (buf == NULL) return NULL;
352 } }
353
354 if (nbFiles == 0) { free(buf); return NULL; }
355
Yann Collet29e46ed2019-10-18 14:28:34 -0700356 { const char** const fileTable = (const char**)malloc((nbFiles + 1) * sizeof(*fileTable));
357 if (!fileTable) { free(buf); return NULL; }
Rohit Jain705e0b12018-10-11 15:51:57 -0700358
Yann Collet29e46ed2019-10-18 14:28:34 -0700359 for (i = 0, pos = 0; i < nbFiles; i++) {
360 fileTable[i] = buf + pos;
361 if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
362 pos += strlen(fileTable[i]) + 1;
363 }
364
365 *allocatedBuffer = buf;
366 *allocatedNamesNb = nbFiles;
367
368 return fileTable;
Rohit Jain705e0b12018-10-11 15:51:57 -0700369 }
Rohit Jain705e0b12018-10-11 15:51:57 -0700370}
371
Yann Collet59a71162019-04-10 12:37:03 -0700372
Rohit Jaind6d240f2018-10-11 15:07:12 -0700373/*-****************************************
Rohit Jaina47f6e62018-10-11 16:51:29 -0700374* Console log
375******************************************/
376int g_utilDisplayLevel;
377
Yann Collet72dbf1b2018-12-20 12:27:12 -0800378
Yann Collet59a71162019-04-10 12:37:03 -0700379
Rohit Jaina47f6e62018-10-11 16:51:29 -0700380/*-****************************************
Yann Collet59a71162019-04-10 12:37:03 -0700381* count the number of physical cores
Rohit Jaind6d240f2018-10-11 15:07:12 -0700382******************************************/
Rohit Jainc7251e52018-10-11 18:05:15 -0700383
Rohit Jain91b2fed2018-10-11 17:34:47 -0700384#if defined(_WIN32) || defined(WIN32)
385
386#include <windows.h>
387
388typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
389
390int UTIL_countPhysicalCores(void)
391{
392 static int numPhysicalCores = 0;
393 if (numPhysicalCores != 0) return numPhysicalCores;
394
395 { LPFN_GLPI glpi;
396 BOOL done = FALSE;
397 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
398 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
399 DWORD returnLength = 0;
400 size_t byteOffset = 0;
401
Yann Colletf3796372019-10-18 17:05:42 -0700402#ifdef (_MSC_VER)
403/* Visual Studio does not like the following cast */
404# pragma warning( disable : 4054 ) /* conversion from function ptr to data ptr */
405# pragma warning( disable : 4055 ) /* conversion from data ptr to function ptr */
406#endif
Yann Collet1bd6c152019-10-18 15:45:31 -0700407 glpi = (LPFN_GLPI)(void*)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
408 "GetLogicalProcessorInformation");
Rohit Jain91b2fed2018-10-11 17:34:47 -0700409
410 if (glpi == NULL) {
411 goto failed;
412 }
413
414 while(!done) {
415 DWORD rc = glpi(buffer, &returnLength);
416 if (FALSE == rc) {
417 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
418 if (buffer)
419 free(buffer);
420 buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
421
422 if (buffer == NULL) {
423 perror("zstd");
424 exit(1);
425 }
426 } else {
427 /* some other error */
428 goto failed;
429 }
430 } else {
431 done = TRUE;
432 }
433 }
434
435 ptr = buffer;
436
437 while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
438
439 if (ptr->Relationship == RelationProcessorCore) {
440 numPhysicalCores++;
441 }
442
443 ptr++;
444 byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
445 }
446
447 free(buffer);
448
449 return numPhysicalCores;
450 }
451
452failed:
453 /* try to fall back on GetSystemInfo */
454 { SYSTEM_INFO sysinfo;
455 GetSystemInfo(&sysinfo);
456 numPhysicalCores = sysinfo.dwNumberOfProcessors;
457 if (numPhysicalCores == 0) numPhysicalCores = 1; /* just in case */
458 }
459 return numPhysicalCores;
460}
461
462#elif defined(__APPLE__)
463
464#include <sys/sysctl.h>
465
466/* Use apple-provided syscall
467 * see: man 3 sysctl */
468int UTIL_countPhysicalCores(void)
469{
470 static S32 numPhysicalCores = 0; /* apple specifies int32_t */
471 if (numPhysicalCores != 0) return numPhysicalCores;
472
473 { size_t size = sizeof(S32);
474 int const ret = sysctlbyname("hw.physicalcpu", &numPhysicalCores, &size, NULL, 0);
475 if (ret != 0) {
476 if (errno == ENOENT) {
477 /* entry not present, fall back on 1 */
478 numPhysicalCores = 1;
479 } else {
480 perror("zstd: can't get number of physical cpus");
481 exit(1);
482 }
483 }
484
485 return numPhysicalCores;
486 }
487}
488
489#elif defined(__linux__)
490
491/* parse /proc/cpuinfo
492 * siblings / cpu cores should give hyperthreading ratio
493 * otherwise fall back on sysconf */
494int UTIL_countPhysicalCores(void)
495{
496 static int numPhysicalCores = 0;
497
498 if (numPhysicalCores != 0) return numPhysicalCores;
499
500 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
501 if (numPhysicalCores == -1) {
502 /* value not queryable, fall back on 1 */
503 return numPhysicalCores = 1;
504 }
505
506 /* try to determine if there's hyperthreading */
507 { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
508#define BUF_SIZE 80
509 char buff[BUF_SIZE];
510
511 int siblings = 0;
512 int cpu_cores = 0;
513 int ratio = 1;
514
515 if (cpuinfo == NULL) {
516 /* fall back on the sysconf value */
517 return numPhysicalCores;
518 }
519
520 /* assume the cpu cores/siblings values will be constant across all
521 * present processors */
522 while (!feof(cpuinfo)) {
523 if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
524 if (strncmp(buff, "siblings", 8) == 0) {
525 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +0800526 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -0700527 /* formatting was broken? */
528 goto failed;
529 }
530
531 siblings = atoi(sep + 1);
532 }
533 if (strncmp(buff, "cpu cores", 9) == 0) {
534 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +0800535 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -0700536 /* formatting was broken? */
537 goto failed;
538 }
539
540 cpu_cores = atoi(sep + 1);
541 }
542 } else if (ferror(cpuinfo)) {
543 /* fall back on the sysconf value */
544 goto failed;
545 }
546 }
547 if (siblings && cpu_cores) {
548 ratio = siblings / cpu_cores;
549 }
550failed:
551 fclose(cpuinfo);
552 return numPhysicalCores = numPhysicalCores / ratio;
553 }
554}
555
Conrad Meyerfe826372019-01-04 11:57:12 -0800556#elif defined(__FreeBSD__)
Rohit Jain91b2fed2018-10-11 17:34:47 -0700557
Conrad Meyerfe826372019-01-04 11:57:12 -0800558#include <sys/param.h>
559#include <sys/sysctl.h>
560
561/* Use physical core sysctl when available
562 * see: man 4 smp, man 3 sysctl */
563int UTIL_countPhysicalCores(void)
564{
565 static int numPhysicalCores = 0; /* freebsd sysctl is native int sized */
566 if (numPhysicalCores != 0) return numPhysicalCores;
567
568#if __FreeBSD_version >= 1300008
569 { size_t size = sizeof(numPhysicalCores);
570 int ret = sysctlbyname("kern.smp.cores", &numPhysicalCores, &size, NULL, 0);
571 if (ret == 0) return numPhysicalCores;
572 if (errno != ENOENT) {
573 perror("zstd: can't get number of physical cpus");
574 exit(1);
575 }
576 /* sysctl not present, fall through to older sysconf method */
577 }
578#endif
579
580 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
581 if (numPhysicalCores == -1) {
582 /* value not queryable, fall back on 1 */
583 numPhysicalCores = 1;
584 }
585 return numPhysicalCores;
586}
587
588#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
589
590/* Use POSIX sysconf
591 * see: man 3 sysconf */
Rohit Jain91b2fed2018-10-11 17:34:47 -0700592int UTIL_countPhysicalCores(void)
593{
594 static int numPhysicalCores = 0;
595
596 if (numPhysicalCores != 0) return numPhysicalCores;
597
598 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
599 if (numPhysicalCores == -1) {
600 /* value not queryable, fall back on 1 */
601 return numPhysicalCores = 1;
602 }
603 return numPhysicalCores;
604}
605
606#else
607
608int UTIL_countPhysicalCores(void)
609{
610 /* assume 1 */
611 return 1;
612}
613
614#endif
615
Rohit Jainf881ee82018-10-11 12:52:19 -0700616#if defined (__cplusplus)
617}
618#endif