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.
11 #if defined (__cplusplus)
16 /*-****************************************
18 ******************************************/
19 #include "util.h" /* note : ensure that platform.h is included first ! */
23 #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
24 #include <direct.h> /* needed for _mkdir in windows */
27 int UTIL_fileExist(const char* filename)
31 int const stat_error = _stat64(filename, &statbuf);
33 int const stat_error = stat(filename, &statbuf);
38 int UTIL_isRegularFile(const char* infilename)
41 return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
44 int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
48 r = _stat64(infilename, statbuf);
49 if (r || !(statbuf->st_mode & S_IFREG)) return 0; /* No good... */
51 r = stat(infilename, statbuf);
52 if (r || !S_ISREG(statbuf->st_mode)) return 0; /* No good... */
57 int UTIL_setFileStat(const char *filename, stat_t *statbuf)
61 if (!UTIL_isRegularFile(filename))
64 /* set access and modification times */
65 #if defined(_WIN32) || (PLATFORM_POSIX_VERSION < 200809L)
67 struct utimbuf timebuf;
68 timebuf.actime = time(NULL);
69 timebuf.modtime = statbuf->st_mtime;
70 res += utime(filename, &timebuf);
75 struct timespec timebuf[2] = { {0, UTIME_NOW} };
76 timebuf[1] = statbuf->st_mtim;
77 res += utimensat(AT_FDCWD, filename, timebuf, 0);
82 res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */
85 res += chmod(filename, statbuf->st_mode & 07777); /* Copy file permissions */
88 return -res; /* number of errors is returned */
91 U32 UTIL_isDirectory(const char* infilename)
96 r = _stat64(infilename, &statbuf);
97 if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
99 r = stat(infilename, &statbuf);
100 if (!r && S_ISDIR(statbuf.st_mode)) return 1;
105 int UTIL_compareStr(const void *p1, const void *p2) {
106 return strcmp(* (char * const *) p1, * (char * const *) p2);
109 int UTIL_isSameFile(const char* fName1, const char* fName2)
111 assert(fName1 != NULL); assert(fName2 != NULL);
112 #if defined(_MSC_VER) || defined(_WIN32)
113 /* note : Visual does not support file identification by inode.
114 * inode does not work on Windows, even with a posix layer, like msys2.
115 * The following work-around is limited to detecting exact name repetition only,
116 * aka `filename` is considered different from `subdir/../filename` */
117 return !strcmp(fName1, fName2);
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);
130 /* Using this to distinguish named pipes */
131 U32 UTIL_isFIFO(const char* infilename)
133 /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
134 #if PLATFORM_POSIX_VERSION >= 200112L
136 int r = UTIL_getFileStat(infilename, &statbuf);
137 if (!r && S_ISFIFO(statbuf.st_mode)) return 1;
144 U32 UTIL_isLink(const char* infilename)
146 /* macro guards, as defined in : https://linux.die.net/man/2/lstat */
147 #if PLATFORM_POSIX_VERSION >= 200112L
150 r = lstat(infilename, &statbuf);
151 if (!r && S_ISLNK(statbuf.st_mode)) return 1;
157 U64 UTIL_getFileSize(const char* infilename)
159 if (!UTIL_isRegularFile(infilename)) return UTIL_FILESIZE_UNKNOWN;
161 #if defined(_MSC_VER)
162 struct __stat64 statbuf;
163 r = _stat64(infilename, &statbuf);
164 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
165 #elif defined(__MINGW32__) && defined (__MSVCRT__)
166 struct _stati64 statbuf;
167 r = _stati64(infilename, &statbuf);
168 if (r || !(statbuf.st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
171 r = stat(infilename, &statbuf);
172 if (r || !S_ISREG(statbuf.st_mode)) return UTIL_FILESIZE_UNKNOWN;
174 return (U64)statbuf.st_size;
179 U64 UTIL_getTotalFileSize(const char* const * const fileNamesTable, unsigned nbFiles)
184 for (n=0; n<nbFiles; n++) {
185 U64 const size = UTIL_getFileSize(fileNamesTable[n]);
186 error |= (size == UTIL_FILESIZE_UNKNOWN);
189 return error ? UTIL_FILESIZE_UNKNOWN : total;
193 int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
196 int dirLength, fnameLength, pathLength, nbFiles = 0;
197 WIN32_FIND_DATAA cFile;
200 dirLength = (int)strlen(dirName);
201 path = (char*) malloc(dirLength + 3);
204 memcpy(path, dirName, dirLength);
205 path[dirLength] = '\\';
206 path[dirLength+1] = '*';
207 path[dirLength+2] = 0;
209 hFile=FindFirstFileA(path, &cFile);
210 if (hFile == INVALID_HANDLE_VALUE) {
211 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
217 fnameLength = (int)strlen(cFile.cFileName);
218 path = (char*) malloc(dirLength + fnameLength + 2);
219 if (!path) { FindClose(hFile); return 0; }
220 memcpy(path, dirName, dirLength);
221 path[dirLength] = '\\';
222 memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
223 pathLength = dirLength+1+fnameLength;
224 path[pathLength] = 0;
225 if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
226 if ( strcmp (cFile.cFileName, "..") == 0
227 || strcmp (cFile.cFileName, ".") == 0 )
229 /* Recursively call "UTIL_prepareFileList" with the new path. */
230 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);
231 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
232 } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
233 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
234 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) {
235 if (*bufStart + *pos + pathLength >= *bufEnd) {
236 ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
237 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
238 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
239 *bufEnd = *bufStart + newListSize;
241 if (*bufStart + *pos + pathLength < *bufEnd) {
242 memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */);
243 *pos += pathLength + 1;
248 } while (FindNextFileA(hFile, &cFile));
254 #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
256 int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
259 struct dirent *entry;
261 size_t dirLength, fnameLength, pathLength;
264 if (!(dir = opendir(dirName))) {
265 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
269 dirLength = strlen(dirName);
271 while ((entry = readdir(dir)) != NULL) {
272 if (strcmp (entry->d_name, "..") == 0 ||
273 strcmp (entry->d_name, ".") == 0) continue;
274 fnameLength = strlen(entry->d_name);
275 path = (char*) malloc(dirLength + fnameLength + 2);
276 if (!path) { closedir(dir); return 0; }
277 memcpy(path, dirName, dirLength);
279 path[dirLength] = '/';
280 memcpy(path+dirLength+1, entry->d_name, fnameLength);
281 pathLength = dirLength+1+fnameLength;
282 path[pathLength] = 0;
284 if (!followLinks && UTIL_isLink(path)) {
285 UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
290 if (UTIL_isDirectory(path)) {
291 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
292 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
294 if (*bufStart + *pos + pathLength >= *bufEnd) {
295 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
296 assert(newListSize >= 0);
297 *bufStart = (char*)UTIL_realloc(*bufStart, (size_t)newListSize);
298 *bufEnd = *bufStart + newListSize;
299 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
301 if (*bufStart + *pos + pathLength < *bufEnd) {
302 memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */
303 *pos += pathLength + 1;
308 errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
312 UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s\n", dirName, strerror(errno));
322 int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd, int followLinks)
324 (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks;
325 UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName);
329 #endif /* #ifdef _WIN32 */
331 int UTIL_isCompressedFile(const char *inputName, const char *extensionList[])
333 const char* ext = UTIL_getFileExtension(inputName);
334 while(*extensionList!=NULL)
336 const int isCompressedExtension = strcmp(ext,*extensionList);
337 if(isCompressedExtension==0)
344 /*Utility function to get file extension from file */
345 const char* UTIL_getFileExtension(const char* infilename)
347 const char* extension = strrchr(infilename, '.');
348 if(!extension || extension==infilename) return "";
353 * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories,
354 * and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb).
355 * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer)
356 * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called.
359 UTIL_createFileList(const char **inputNames, unsigned inputNamesNb,
360 char** allocatedBuffer, unsigned* allocatedNamesNb,
365 char* buf = (char*)malloc(LIST_SIZE_INCREASE);
366 char* bufend = buf + LIST_SIZE_INCREASE;
368 if (!buf) return NULL;
370 for (i=0, pos=0, nbFiles=0; i<inputNamesNb; i++) {
371 if (!UTIL_isDirectory(inputNames[i])) {
372 size_t const len = strlen(inputNames[i]);
373 if (buf + pos + len >= bufend) {
374 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
375 assert(newListSize >= 0);
376 buf = (char*)UTIL_realloc(buf, (size_t)newListSize);
377 bufend = buf + newListSize;
378 if (!buf) return NULL;
380 if (buf + pos + len < bufend) {
381 memcpy(buf+pos, inputNames[i], len+1); /* including final \0 */
386 nbFiles += (unsigned)UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend, followLinks);
387 if (buf == NULL) return NULL;
390 if (nbFiles == 0) { free(buf); return NULL; }
392 { const char** const fileTable = (const char**)malloc((nbFiles + 1) * sizeof(*fileTable));
393 if (!fileTable) { free(buf); return NULL; }
395 for (i = 0, pos = 0; i < nbFiles; i++) {
396 fileTable[i] = buf + pos;
397 if (buf + pos > bufend) { free(buf); free((void*)fileTable); return NULL; }
398 pos += strlen(fileTable[i]) + 1;
401 *allocatedBuffer = buf;
402 *allocatedNamesNb = nbFiles;
409 /*-****************************************
411 ******************************************/
412 int g_utilDisplayLevel;
416 /*-****************************************
417 * count the number of physical cores
418 ******************************************/
420 #if defined(_WIN32) || defined(WIN32)
424 typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
426 int UTIL_countPhysicalCores(void)
428 static int numPhysicalCores = 0;
429 if (numPhysicalCores != 0) return numPhysicalCores;
433 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
434 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
435 DWORD returnLength = 0;
436 size_t byteOffset = 0;
438 #if defined(_MSC_VER)
439 /* Visual Studio does not like the following cast */
440 # pragma warning( disable : 4054 ) /* conversion from function ptr to data ptr */
441 # pragma warning( disable : 4055 ) /* conversion from data ptr to function ptr */
443 glpi = (LPFN_GLPI)(void*)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
444 "GetLogicalProcessorInformation");
451 DWORD rc = glpi(buffer, &returnLength);
453 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
456 buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
458 if (buffer == NULL) {
463 /* some other error */
473 while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
475 if (ptr->Relationship == RelationProcessorCore) {
480 byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
485 return numPhysicalCores;
489 /* try to fall back on GetSystemInfo */
490 { SYSTEM_INFO sysinfo;
491 GetSystemInfo(&sysinfo);
492 numPhysicalCores = sysinfo.dwNumberOfProcessors;
493 if (numPhysicalCores == 0) numPhysicalCores = 1; /* just in case */
495 return numPhysicalCores;
498 #elif defined(__APPLE__)
500 #include <sys/sysctl.h>
502 /* Use apple-provided syscall
503 * see: man 3 sysctl */
504 int UTIL_countPhysicalCores(void)
506 static S32 numPhysicalCores = 0; /* apple specifies int32_t */
507 if (numPhysicalCores != 0) return numPhysicalCores;
509 { size_t size = sizeof(S32);
510 int const ret = sysctlbyname("hw.physicalcpu", &numPhysicalCores, &size, NULL, 0);
512 if (errno == ENOENT) {
513 /* entry not present, fall back on 1 */
514 numPhysicalCores = 1;
516 perror("zstd: can't get number of physical cpus");
521 return numPhysicalCores;
525 #elif defined(__linux__)
527 /* parse /proc/cpuinfo
528 * siblings / cpu cores should give hyperthreading ratio
529 * otherwise fall back on sysconf */
530 int UTIL_countPhysicalCores(void)
532 static int numPhysicalCores = 0;
534 if (numPhysicalCores != 0) return numPhysicalCores;
536 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
537 if (numPhysicalCores == -1) {
538 /* value not queryable, fall back on 1 */
539 return numPhysicalCores = 1;
542 /* try to determine if there's hyperthreading */
543 { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
551 if (cpuinfo == NULL) {
552 /* fall back on the sysconf value */
553 return numPhysicalCores;
556 /* assume the cpu cores/siblings values will be constant across all
557 * present processors */
558 while (!feof(cpuinfo)) {
559 if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
560 if (strncmp(buff, "siblings", 8) == 0) {
561 const char* const sep = strchr(buff, ':');
562 if (sep == NULL || *sep == '\0') {
563 /* formatting was broken? */
567 siblings = atoi(sep + 1);
569 if (strncmp(buff, "cpu cores", 9) == 0) {
570 const char* const sep = strchr(buff, ':');
571 if (sep == NULL || *sep == '\0') {
572 /* formatting was broken? */
576 cpu_cores = atoi(sep + 1);
578 } else if (ferror(cpuinfo)) {
579 /* fall back on the sysconf value */
583 if (siblings && cpu_cores) {
584 ratio = siblings / cpu_cores;
588 return numPhysicalCores = numPhysicalCores / ratio;
592 #elif defined(__FreeBSD__)
594 #include <sys/param.h>
595 #include <sys/sysctl.h>
597 /* Use physical core sysctl when available
598 * see: man 4 smp, man 3 sysctl */
599 int UTIL_countPhysicalCores(void)
601 static int numPhysicalCores = 0; /* freebsd sysctl is native int sized */
602 if (numPhysicalCores != 0) return numPhysicalCores;
604 #if __FreeBSD_version >= 1300008
605 { size_t size = sizeof(numPhysicalCores);
606 int ret = sysctlbyname("kern.smp.cores", &numPhysicalCores, &size, NULL, 0);
607 if (ret == 0) return numPhysicalCores;
608 if (errno != ENOENT) {
609 perror("zstd: can't get number of physical cpus");
612 /* sysctl not present, fall through to older sysconf method */
616 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
617 if (numPhysicalCores == -1) {
618 /* value not queryable, fall back on 1 */
619 numPhysicalCores = 1;
621 return numPhysicalCores;
624 #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
627 * see: man 3 sysconf */
628 int UTIL_countPhysicalCores(void)
630 static int numPhysicalCores = 0;
632 if (numPhysicalCores != 0) return numPhysicalCores;
634 numPhysicalCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
635 if (numPhysicalCores == -1) {
636 /* value not queryable, fall back on 1 */
637 return numPhysicalCores = 1;
639 return numPhysicalCores;
644 int UTIL_countPhysicalCores(void)
652 #if defined (__cplusplus)