blob: 920601fba29ee3f3f329602eba2ffde651fb2879 [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;
60 struct utimbuf timebuf;
61
62 if (!UTIL_isRegularFile(filename))
63 return -1;
64
65 timebuf.actime = time(NULL);
66 timebuf.modtime = statbuf->st_mtime;
67 res += utime(filename, &timebuf); /* set access and modification times */
68
69#if !defined(_WIN32)
70 res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */
71#endif
72
73 res += chmod(filename, statbuf->st_mode & 07777); /* Copy file permissions */
74
75 errno = 0;
76 return -res; /* number of errors is returned */
77}
Rohit Jainf881ee82018-10-11 12:52:19 -070078
79U32 UTIL_isDirectory(const char* infilename)
80{
81 int r;
82 stat_t statbuf;
83#if defined(_MSC_VER)
84 r = _stat64(infilename, &statbuf);
85 if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
86#else
87 r = stat(infilename, &statbuf);
88 if (!r && S_ISDIR(statbuf.st_mode)) return 1;
89#endif
90 return 0;
91}
92
Sen Huanga9c807a2019-09-06 10:17:04 -070093int UTIL_createDir(const char* outDirName)
94{
Sen Huang7f98b462019-09-05 16:03:35 -070095 int r;
Sen Huanga9c807a2019-09-06 10:17:04 -070096 if (UTIL_isDirectory(outDirName))
97 return 0; /* no need to create if directory already exists */
98
Sen Huang62616c42019-09-06 13:20:50 -070099#if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
Sen Huang7f98b462019-09-05 16:03:35 -0700100 r = _mkdir(outDirName);
101 if (r || !UTIL_isDirectory(outDirName)) return 1;
102#else
103 r = mkdir(outDirName, S_IRWXU | S_IRWXG | S_IRWXO); /* dir has all permissions */
104 if (r || !UTIL_isDirectory(outDirName)) return 1;
105#endif
106 return 0;
107}
108
109void UTIL_createDestinationDirTable(const char** filenameTable, unsigned nbFiles,
110 const char* outDirName, char** dstFilenameTable)
111{
112 unsigned u;
113 char c;
114 c = '/';
115
116 /* duplicate source file table */
117 for (u = 0; u < nbFiles; ++u) {
Sen Huang62616c42019-09-06 13:20:50 -0700118 const char* filename;
Sen Huang7f98b462019-09-05 16:03:35 -0700119 size_t finalPathLen;
120 finalPathLen = strlen(outDirName);
121 filename = strrchr(filenameTable[u], c); /* filename is the last bit of string after '/' */
122 finalPathLen += strlen(filename);
Sen Huanga9c807a2019-09-06 10:17:04 -0700123 dstFilenameTable[u] = (char*) malloc((finalPathLen+5) * sizeof(char)); /* extra 1 bit for \0, extra 4 for .zst if compressing*/
Sen Huang7f98b462019-09-05 16:03:35 -0700124 strcpy(dstFilenameTable[u], outDirName);
125 strcat(dstFilenameTable[u], filename);
126 }
127}
128
Sen Huang30bff502019-09-06 11:10:53 -0700129void UTIL_processMultipleFilenameDestinationDir(char** dstFilenameTable,
130 const char** filenameTable, unsigned filenameIdx,
131 const char* outFileName, const char* outDirName) {
132 int dirResult;
133 dirResult = UTIL_createDir(outDirName);
134 if (dirResult)
135 UTIL_DISPLAYLEVEL(1, "Directory creation unsuccessful\n");
136
137 UTIL_createDestinationDirTable(filenameTable, filenameIdx, outDirName, dstFilenameTable);
138 if (outFileName) {
139 outFileName = dstFilenameTable[0]; /* in case -O is called with single file */
140 }
141}
142
Sen Huang7f98b462019-09-05 16:03:35 -0700143void UTIL_freeDestinationFilenameTable(char** dstDirTable, unsigned nbFiles) {
144 unsigned u;
Sen Huang6beb3c02019-09-05 17:56:24 -0700145 for (u = 0; u < nbFiles; ++u) {
146 if (dstDirTable[u] != NULL)
147 free(dstDirTable[u]);
148 }
149 if (dstDirTable != NULL) free((void*)dstDirTable);
Sen Huang7f98b462019-09-05 16:03:35 -0700150}
151
shakeelraoe5811e52019-03-23 19:04:56 -0700152int UTIL_isSameFile(const char* file1, const char* file2)
153{
154#if defined(_MSC_VER)
155 /* note : Visual does not support file identification by inode.
156 * The following work-around is limited to detecting exact name repetition only,
157 * aka `filename` is considered different from `subdir/../filename` */
158 return !strcmp(file1, file2);
159#else
160 stat_t file1Stat;
161 stat_t file2Stat;
162 return UTIL_getFileStat(file1, &file1Stat)
163 && UTIL_getFileStat(file2, &file2Stat)
164 && (file1Stat.st_dev == file2Stat.st_dev)
165 && (file1Stat.st_ino == file2Stat.st_ino);
166#endif
167}
168
Rohit Jainf881ee82018-10-11 12:52:19 -0700169U32 UTIL_isLink(const char* infilename)
170{
171/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
W. Felix Handted2c48042019-06-07 15:31:33 -0400172#if PLATFORM_POSIX_VERSION >= 200112L
Rohit Jainf881ee82018-10-11 12:52:19 -0700173 int r;
174 stat_t statbuf;
175 r = lstat(infilename, &statbuf);
176 if (!r && S_ISLNK(statbuf.st_mode)) return 1;
177#endif
Rohit Jainf881ee82018-10-11 12:52:19 -0700178 (void)infilename;
179 return 0;
180}
181
182U64 UTIL_getFileSize(const char* infilename)
183{
184 if (!UTIL_isRegularFile(infilename)) return UTIL_FILESIZE_UNKNOWN;
185 { int r;
186#if defined(_MSC_VER)
187 struct __stat64 statbuf;
188 r = _stat64(infilename, &statbuf);
189 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
190#elif defined(__MINGW32__) && defined (__MSVCRT__)
191 struct _stati64 statbuf;
192 r = _stati64(infilename, &statbuf);
193 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
194#else
195 struct stat statbuf;
196 r = stat(infilename, &statbuf);
197 if (r || !S_ISREG(statbuf.st_mode)) return UTIL_FILESIZE_UNKNOWN;
198#endif
199 return (U64)statbuf.st_size;
200 }
201}
202
203
204U64 UTIL_getTotalFileSize(const char* const * const fileNamesTable, unsigned nbFiles)
205{
206 U64 total = 0;
207 int error = 0;
208 unsigned n;
209 for (n=0; n<nbFiles; n++) {
210 U64 const size = UTIL_getFileSize(fileNamesTable[n]);
211 error |= (size == UTIL_FILESIZE_UNKNOWN);
212 total += size;
213 }
214 return error ? UTIL_FILESIZE_UNKNOWN : total;
215}
216
Rohit Jainc7251e52018-10-11 18:05:15 -0700217#ifdef _WIN32
Rohit Jain705e0b12018-10-11 15:51:57 -0700218int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
219{
220 char* path;
221 int dirLength, fnameLength, pathLength, nbFiles = 0;
222 WIN32_FIND_DATAA cFile;
223 HANDLE hFile;
224
225 dirLength = (int)strlen(dirName);
226 path = (char*) malloc(dirLength + 3);
227 if (!path) return 0;
228
229 memcpy(path, dirName, dirLength);
230 path[dirLength] = '\\';
231 path[dirLength+1] = '*';
232 path[dirLength+2] = 0;
233
234 hFile=FindFirstFileA(path, &cFile);
235 if (hFile == INVALID_HANDLE_VALUE) {
236 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
237 return 0;
238 }
239 free(path);
240
241 do {
242 fnameLength = (int)strlen(cFile.cFileName);
243 path = (char*) malloc(dirLength + fnameLength + 2);
244 if (!path) { FindClose(hFile); return 0; }
245 memcpy(path, dirName, dirLength);
246 path[dirLength] = '\\';
247 memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
248 pathLength = dirLength+1+fnameLength;
249 path[pathLength] = 0;
250 if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800251 if ( strcmp (cFile.cFileName, "..") == 0
252 || strcmp (cFile.cFileName, ".") == 0 )
253 continue;
254 /* Recursively call "UTIL_prepareFileList" with the new path. */
255 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);
Rohit Jain705e0b12018-10-11 15:51:57 -0700256 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800257 } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
258 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
259 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) {
Rohit Jain705e0b12018-10-11 15:51:57 -0700260 if (*bufStart + *pos + pathLength >= *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800261 ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
Rohit Jain705e0b12018-10-11 15:51:57 -0700262 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700263 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800264 *bufEnd = *bufStart + newListSize;
Rohit Jain705e0b12018-10-11 15:51:57 -0700265 }
266 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800267 memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */);
Rohit Jain705e0b12018-10-11 15:51:57 -0700268 *pos += pathLength + 1;
269 nbFiles++;
270 }
271 }
272 free(path);
273 } while (FindNextFileA(hFile, &cFile));
274
275 FindClose(hFile);
276 return nbFiles;
277}
278
279#elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
280
281int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
282{
283 DIR *dir;
284 struct dirent *entry;
285 char* path;
286 int dirLength, fnameLength, pathLength, nbFiles = 0;
287
288 if (!(dir = opendir(dirName))) {
289 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
290 return 0;
291 }
292
293 dirLength = (int)strlen(dirName);
294 errno = 0;
295 while ((entry = readdir(dir)) != NULL) {
296 if (strcmp (entry->d_name, "..") == 0 ||
297 strcmp (entry->d_name, ".") == 0) continue;
298 fnameLength = (int)strlen(entry->d_name);
299 path = (char*) malloc(dirLength + fnameLength + 2);
300 if (!path) { closedir(dir); return 0; }
301 memcpy(path, dirName, dirLength);
302
303 path[dirLength] = '/';
304 memcpy(path+dirLength+1, entry->d_name, fnameLength);
305 pathLength = dirLength+1+fnameLength;
306 path[pathLength] = 0;
307
308 if (!followLinks && UTIL_isLink(path)) {
309 UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
LeeYoung624793b94b2019-07-25 21:07:57 +0800310 free(path);
Rohit Jain705e0b12018-10-11 15:51:57 -0700311 continue;
312 }
313
314 if (UTIL_isDirectory(path)) {
315 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
316 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
317 } else {
318 if (*bufStart + *pos + pathLength >= *bufEnd) {
319 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
320 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
321 *bufEnd = *bufStart + newListSize;
322 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
323 }
324 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800325 memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */
Rohit Jain705e0b12018-10-11 15:51:57 -0700326 *pos += pathLength + 1;
327 nbFiles++;
328 }
329 }
330 free(path);
331 errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
332 }
333
334 if (errno != 0) {
335 UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s\n", dirName, strerror(errno));
336 free(*bufStart);
337 *bufStart = NULL;
338 }
339 closedir(dir);
340 return nbFiles;
341}
342
343#else
344
345int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
346{
347 (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks;
348 UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
349 return 0;
350}
351
352#endif /* #ifdef _WIN32 */
353
354/*
355 * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
356 * and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
357 * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
358 * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
359 */
360const char**
361UTIL_createFileList(const char **inputNames, unsigned inputNamesNb,
362 char** allocatedBuffer, unsigned* allocatedNamesNb,
363 int followLinks)
364{
365 size_t pos;
366 unsigned i, nbFiles;
367 char* buf = (char*)malloc(LIST_SIZE_INCREASE);
368 char* bufend = buf + LIST_SIZE_INCREASE;
369 const char** fileTable;
370
371 if (!buf) return NULL;
372
373 for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
374 if (!UTIL_isDirectory(inputNames[i])) {
375 size_t const len = strlen(inputNames[i]);
376 if (buf + pos + len >= bufend) {
377 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
378 buf = (char*)UTIL_realloc(buf, newListSize);
379 bufend = buf + newListSize;
380 if (!buf) return NULL;
381 }
382 if (buf + pos + len < bufend) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800383 memcpy(buf+pos, inputNames[i], len+1); /* with final \0 */
Rohit Jain705e0b12018-10-11 15:51:57 -0700384 pos += len + 1;
385 nbFiles++;
386 }
387 } else {
388 nbFiles += UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend, followLinks);
389 if (buf == NULL) return NULL;
390 } }
391
392 if (nbFiles == 0) { free(buf); return NULL; }
393
394 fileTable = (const char**)malloc((nbFiles+1) * sizeof(const char*));
395 if (!fileTable) { free(buf); return NULL; }
396
397 for (i=0, pos=0; i<nbFiles; i++) {
398 fileTable[i] = buf + pos;
399 pos += strlen(fileTable[i]) + 1;
400 }
401
402 if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
403
404 *allocatedBuffer = buf;
405 *allocatedNamesNb = nbFiles;
406
407 return fileTable;
408}
409
Yann Collet59a71162019-04-10 12:37:03 -0700410
Rohit Jaind6d240f2018-10-11 15:07:12 -0700411/*-****************************************
Rohit Jaina47f6e62018-10-11 16:51:29 -0700412* Console log
413******************************************/
414int g_utilDisplayLevel;
415
Yann Collet72dbf1b2018-12-20 12:27:12 -0800416
Yann Collet59a71162019-04-10 12:37:03 -0700417
Rohit Jaina47f6e62018-10-11 16:51:29 -0700418/*-****************************************
Yann Collet59a71162019-04-10 12:37:03 -0700419* count the number of physical cores
Rohit Jaind6d240f2018-10-11 15:07:12 -0700420******************************************/
Rohit Jainc7251e52018-10-11 18:05:15 -0700421
Rohit Jain91b2fed2018-10-11 17:34:47 -0700422#if defined(_WIN32) || defined(WIN32)
423
424#include <windows.h>
425
426typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
427
428int UTIL_countPhysicalCores(void)
429{
430 static int numPhysicalCores = 0;
431 if (numPhysicalCores != 0) return numPhysicalCores;
432
433 { LPFN_GLPI glpi;
434 BOOL done = FALSE;
435 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
436 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
437 DWORD returnLength = 0;
438 size_t byteOffset = 0;
439
440 glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
441 "GetLogicalProcessorInformation");
442
443 if (glpi == NULL) {
444 goto failed;
445 }
446
447 while(!done) {
448 DWORD rc = glpi(buffer, &returnLength);
449 if (FALSE == rc) {
450 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
451 if (buffer)
452 free(buffer);
453 buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
454
455 if (buffer == NULL) {
456 perror("zstd");
457 exit(1);
458 }
459 } else {
460 /* some other error */
461 goto failed;
462 }
463 } else {
464 done = TRUE;
465 }
466 }
467
468 ptr = buffer;
469
470 while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
471
472 if (ptr->Relationship == RelationProcessorCore) {
473 numPhysicalCores++;
474 }
475
476 ptr++;
477 byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
478 }
479
480 free(buffer);
481
482 return numPhysicalCores;
483 }
484
485failed:
486 /* try to fall back on GetSystemInfo */
487 { SYSTEM_INFO sysinfo;
488 GetSystemInfo(&sysinfo);
489 numPhysicalCores = sysinfo.dwNumberOfProcessors;
490 if (numPhysicalCores == 0) numPhysicalCores = 1; /* just in case */
491 }
492 return numPhysicalCores;
493}
494
495#elif defined(__APPLE__)
496
497#include <sys/sysctl.h>
498
499/* Use apple-provided syscall
500 * see: man 3 sysctl */
501int UTIL_countPhysicalCores(void)
502{
503 static S32 numPhysicalCores = 0; /* apple specifies int32_t */
504 if (numPhysicalCores != 0) return numPhysicalCores;
505
506 { size_t size = sizeof(S32);
507 int const ret = sysctlbyname("hw.physicalcpu", &numPhysicalCores, &size, NULL, 0);
508 if (ret != 0) {
509 if (errno == ENOENT) {
510 /* entry not present, fall back on 1 */
511 numPhysicalCores = 1;
512 } else {
513 perror("zstd: can't get number of physical cpus");
514 exit(1);
515 }
516 }
517
518 return numPhysicalCores;
519 }
520}
521
522#elif defined(__linux__)
523
524/* parse /proc/cpuinfo
525 * siblings / cpu cores should give hyperthreading ratio
526 * otherwise fall back on sysconf */
527int UTIL_countPhysicalCores(void)
528{
529 static int numPhysicalCores = 0;
530
531 if (numPhysicalCores != 0) return numPhysicalCores;
532
533 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
534 if (numPhysicalCores == -1) {
535 /* value not queryable, fall back on 1 */
536 return numPhysicalCores = 1;
537 }
538
539 /* try to determine if there's hyperthreading */
540 { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
541#define BUF_SIZE 80
542 char buff[BUF_SIZE];
543
544 int siblings = 0;
545 int cpu_cores = 0;
546 int ratio = 1;
547
548 if (cpuinfo == NULL) {
549 /* fall back on the sysconf value */
550 return numPhysicalCores;
551 }
552
553 /* assume the cpu cores/siblings values will be constant across all
554 * present processors */
555 while (!feof(cpuinfo)) {
556 if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
557 if (strncmp(buff, "siblings", 8) == 0) {
558 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +0800559 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -0700560 /* formatting was broken? */
561 goto failed;
562 }
563
564 siblings = atoi(sep + 1);
565 }
566 if (strncmp(buff, "cpu cores", 9) == 0) {
567 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +0800568 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -0700569 /* formatting was broken? */
570 goto failed;
571 }
572
573 cpu_cores = atoi(sep + 1);
574 }
575 } else if (ferror(cpuinfo)) {
576 /* fall back on the sysconf value */
577 goto failed;
578 }
579 }
580 if (siblings && cpu_cores) {
581 ratio = siblings / cpu_cores;
582 }
583failed:
584 fclose(cpuinfo);
585 return numPhysicalCores = numPhysicalCores / ratio;
586 }
587}
588
Conrad Meyerfe826372019-01-04 11:57:12 -0800589#elif defined(__FreeBSD__)
Rohit Jain91b2fed2018-10-11 17:34:47 -0700590
Conrad Meyerfe826372019-01-04 11:57:12 -0800591#include <sys/param.h>
592#include <sys/sysctl.h>
593
594/* Use physical core sysctl when available
595 * see: man 4 smp, man 3 sysctl */
596int UTIL_countPhysicalCores(void)
597{
598 static int numPhysicalCores = 0; /* freebsd sysctl is native int sized */
599 if (numPhysicalCores != 0) return numPhysicalCores;
600
601#if __FreeBSD_version >= 1300008
602 { size_t size = sizeof(numPhysicalCores);
603 int ret = sysctlbyname("kern.smp.cores", &numPhysicalCores, &size, NULL, 0);
604 if (ret == 0) return numPhysicalCores;
605 if (errno != ENOENT) {
606 perror("zstd: can't get number of physical cpus");
607 exit(1);
608 }
609 /* sysctl not present, fall through to older sysconf method */
610 }
611#endif
612
613 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
614 if (numPhysicalCores == -1) {
615 /* value not queryable, fall back on 1 */
616 numPhysicalCores = 1;
617 }
618 return numPhysicalCores;
619}
620
621#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
622
623/* Use POSIX sysconf
624 * see: man 3 sysconf */
Rohit Jain91b2fed2018-10-11 17:34:47 -0700625int UTIL_countPhysicalCores(void)
626{
627 static int numPhysicalCores = 0;
628
629 if (numPhysicalCores != 0) return numPhysicalCores;
630
631 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
632 if (numPhysicalCores == -1) {
633 /* value not queryable, fall back on 1 */
634 return numPhysicalCores = 1;
635 }
636 return numPhysicalCores;
637}
638
639#else
640
641int UTIL_countPhysicalCores(void)
642{
643 /* assume 1 */
644 return 1;
645}
646
647#endif
648
Rohit Jainf881ee82018-10-11 12:52:19 -0700649#if defined (__cplusplus)
650}
651#endif