blob: d69b72a37ca6102d20eb9af80da5a38de007d919 [file] [log] [blame]
Rohit Jainf881ee82018-10-11 12:52:19 -07001/*
Nick Terrella4943082021-03-29 14:23:36 -07002 * Copyright (c) Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
Rohit Jainf881ee82018-10-11 12:52:19 -07003 * 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 Colleta684b822019-11-26 15:16:53 -080020#include <stdlib.h> /* malloc, realloc, free */
Yann Colletaaab6182019-11-26 15:25:32 -080021#include <stdio.h> /* fprintf */
Yann Colleta684b822019-11-26 15:16:53 -080022#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC, nanosleep */
Yann Collet173ef9d2018-12-19 18:30:57 -080023#include <errno.h>
Yann Collet72dbf1b2018-12-20 12:27:12 -080024#include <assert.h>
Yann Collet173ef9d2018-12-19 18:30:57 -080025
Yann Colleta684b822019-11-26 15:16:53 -080026#if defined(_WIN32)
27# include <sys/utime.h> /* utime */
28# include <io.h> /* _chmod */
29#else
30# include <unistd.h> /* chown, stat */
Fabrice Fontaine26d01bd2020-07-15 21:19:14 +020031# if PLATFORM_POSIX_VERSION < 200809L || !defined(st_mtime)
Yann Colleta684b822019-11-26 15:16:53 -080032# include <utime.h> /* utime */
33# else
34# include <fcntl.h> /* AT_FDCWD */
35# include <sys/stat.h> /* utimensat */
36# endif
37#endif
38
Sen Huang62616c42019-09-06 13:20:50 -070039#if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
40#include <direct.h> /* needed for _mkdir in windows */
41#endif
Rohit Jainf881ee82018-10-11 12:52:19 -070042
Yann Collet76b9e422019-11-05 14:59:45 -080043#if defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
44# include <dirent.h> /* opendir, readdir */
45# include <string.h> /* strerror, memcpy */
46#endif /* #ifdef _WIN32 */
47
Yann Collet1ead0c52019-10-25 16:36:59 -070048/*-****************************************
49* Internal Macros
50******************************************/
51
Yann Collet7543cd02019-11-26 15:21:58 -080052/* CONTROL is almost like an assert(), but is never disabled.
53 * It's designed for failures that may happen rarely,
54 * but we don't want to maintain a specific error code path for them,
55 * such as a malloc() returning NULL for example.
56 * Since it's always active, this macro can trigger side effects.
Yann Collet1ead0c52019-10-25 16:36:59 -070057 */
58#define CONTROL(c) { \
59 if (!(c)) { \
60 UTIL_DISPLAYLEVEL(1, "Error : %s, %i : %s", \
61 __FILE__, __LINE__, #c); \
Yann Collet3e5c81e2019-10-26 00:01:11 -070062 exit(1); \
Yann Collet1ead0c52019-10-25 16:36:59 -070063} }
64
Yann Collet7543cd02019-11-26 15:21:58 -080065/* console log */
66#define UTIL_DISPLAY(...) fprintf(stderr, __VA_ARGS__)
67#define UTIL_DISPLAYLEVEL(l, ...) { if (g_utilDisplayLevel>=l) { UTIL_DISPLAY(__VA_ARGS__); } }
68
69/* A modified version of realloc().
Yann Collet76b9e422019-11-05 14:59:45 -080070 * If UTIL_realloc() fails the original block is freed.
71 */
72UTIL_STATIC void* UTIL_realloc(void *ptr, size_t size)
73{
74 void *newptr = realloc(ptr, size);
75 if (newptr) return newptr;
76 free(ptr);
77 return NULL;
78}
79
Yann Collet9a221402019-11-25 13:45:22 -080080#if defined(_MSC_VER)
81 #define chmod _chmod
82#endif
83
Yann Collet76b9e422019-11-05 14:59:45 -080084
Yann Collet1ead0c52019-10-25 16:36:59 -070085/*-****************************************
86* Console log
87******************************************/
88int g_utilDisplayLevel;
89
senhuang427991c552020-08-26 16:50:20 -040090int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg,
senhuang4293d63ea2020-09-24 15:58:06 -040091 const char* acceptableLetters, int hasStdinInput) {
senhuang427991c552020-08-26 16:50:20 -040092 int ch, result;
senhuang427aa3da12020-09-22 14:15:52 -040093
senhuang4288f44102020-09-24 16:29:12 -040094 if (hasStdinInput) {
senhuang4202422db2020-09-25 11:51:35 -040095 UTIL_DISPLAY("stdin is an input - not proceeding.\n");
senhuang4293d63ea2020-09-24 15:58:06 -040096 return 1;
senhuang4288f44102020-09-24 16:29:12 -040097 }
senhuang4293d63ea2020-09-24 15:58:06 -040098
senhuang42aab11ce2020-08-25 11:25:49 -040099 UTIL_DISPLAY("%s", prompt);
100 ch = getchar();
senhuang427991c552020-08-26 16:50:20 -0400101 result = 0;
senhuang42aab11ce2020-08-25 11:25:49 -0400102 if (strchr(acceptableLetters, ch) == NULL) {
103 UTIL_DISPLAY("%s", abortMsg);
senhuang427991c552020-08-26 16:50:20 -0400104 result = 1;
senhuang42aab11ce2020-08-25 11:25:49 -0400105 }
106 /* flush the rest */
107 while ((ch!=EOF) && (ch!='\n'))
108 ch = getchar();
senhuang427991c552020-08-26 16:50:20 -0400109 return result;
senhuang42aab11ce2020-08-25 11:25:49 -0400110}
111
Yann Collet1ead0c52019-10-25 16:36:59 -0700112
Yann Collet9a221402019-11-25 13:45:22 -0800113/*-*************************************
114* Constants
115***************************************/
116#define LIST_SIZE_INCREASE (8*1024)
Yann Colletc71bd452019-11-26 11:20:26 -0800117#define MAX_FILE_OF_FILE_NAMES_SIZE (1<<20)*50
Yann Collet9a221402019-11-25 13:45:22 -0800118
119
120/*-*************************************
121* Functions
122***************************************/
Yann Collet1ead0c52019-10-25 16:36:59 -0700123
W. Felix Handteb11bea52020-08-05 00:09:29 -0400124int UTIL_stat(const char* filename, stat_t* statbuf)
125{
126#if defined(_MSC_VER)
127 return !_stat64(filename, statbuf);
128#elif defined(__MINGW32__) && defined (__MSVCRT__)
129 return !_stati64(filename, statbuf);
130#else
131 return !stat(filename, statbuf);
132#endif
133}
134
Rohit Jaind6d240f2018-10-11 15:07:12 -0700135int UTIL_isRegularFile(const char* infilename)
136{
137 stat_t statbuf;
W. Felix Handte51ac0202020-08-10 15:28:02 -0400138 return UTIL_stat(infilename, &statbuf) && UTIL_isRegularFileStat(&statbuf);
Rohit Jaind6d240f2018-10-11 15:07:12 -0700139}
140
W. Felix Handte44fa0522020-08-05 01:00:06 -0400141int UTIL_isRegularFileStat(const stat_t* statbuf)
142{
143#if defined(_MSC_VER)
144 return (statbuf->st_mode & S_IFREG) != 0;
145#else
146 return S_ISREG(statbuf->st_mode) != 0;
147#endif
148}
149
Yann Collet9a221402019-11-25 13:45:22 -0800150/* like chmod, but avoid changing permission of /dev/null */
W. Felix Handte0a8aacb2020-08-05 12:00:12 -0400151int UTIL_chmod(char const* filename, const stat_t* statbuf, mode_t permissions)
Yann Collet9a221402019-11-25 13:45:22 -0800152{
W. Felix Handte0a8aacb2020-08-05 12:00:12 -0400153 stat_t localStatBuf;
154 if (statbuf == NULL) {
155 if (!UTIL_stat(filename, &localStatBuf)) return 0;
156 statbuf = &localStatBuf;
157 }
158 if (!UTIL_isRegularFileStat(statbuf)) return 0; /* pretend success, but don't change anything */
Yann Collet9a221402019-11-25 13:45:22 -0800159 return chmod(filename, permissions);
160}
161
W. Felix Handtea719edb2021-08-04 14:49:00 -0400162/* set access and modification times */
163int UTIL_utime(const char* filename, const stat_t *statbuf)
164{
165 int ret;
166 /* We check that st_mtime is a macro here in order to give us confidence
167 * that struct stat has a struct timespec st_mtim member. We need this
168 * check because there are some platforms that claim to be POSIX 2008
169 * compliant but which do not have st_mtim... */
170#if (PLATFORM_POSIX_VERSION >= 200809L) && defined(st_mtime)
171 /* (atime, mtime) */
172 struct timespec timebuf[2] = { {0, UTIME_NOW} };
173 timebuf[1] = statbuf->st_mtim;
174 ret = utimensat(AT_FDCWD, filename, timebuf, 0);
175#else
176 struct utimbuf timebuf;
177 timebuf.actime = time(NULL);
178 timebuf.modtime = statbuf->st_mtime;
179 ret = utime(filename, &timebuf);
180#endif
181 errno = 0;
182 return ret;
183}
184
W. Felix Handte1a1003f2020-08-05 00:35:21 -0400185int UTIL_setFileStat(const char *filename, const stat_t *statbuf)
Rohit Jaind6d240f2018-10-11 15:07:12 -0700186{
187 int res = 0;
Rohit Jaind6d240f2018-10-11 15:07:12 -0700188
W. Felix Handtec1449142020-08-05 12:10:42 -0400189 stat_t curStatBuf;
190 if (!UTIL_stat(filename, &curStatBuf) || !UTIL_isRegularFileStat(&curStatBuf))
Rohit Jaind6d240f2018-10-11 15:07:12 -0700191 return -1;
192
W. Felix Handtee1ec8002019-09-12 16:27:05 -0400193 /* set access and modification times */
W. Felix Handtea719edb2021-08-04 14:49:00 -0400194 res += UTIL_utime(filename, statbuf);
Rohit Jaind6d240f2018-10-11 15:07:12 -0700195
196#if !defined(_WIN32)
197 res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */
198#endif
199
W. Felix Handtec1449142020-08-05 12:10:42 -0400200 res += UTIL_chmod(filename, &curStatBuf, statbuf->st_mode & 07777); /* Copy file permissions */
Rohit Jaind6d240f2018-10-11 15:07:12 -0700201
202 errno = 0;
203 return -res; /* number of errors is returned */
204}
Rohit Jainf881ee82018-10-11 12:52:19 -0700205
Yann Collet9a221402019-11-25 13:45:22 -0800206int UTIL_isDirectory(const char* infilename)
Rohit Jainf881ee82018-10-11 12:52:19 -0700207{
Rohit Jainf881ee82018-10-11 12:52:19 -0700208 stat_t statbuf;
W. Felix Handte51ac0202020-08-10 15:28:02 -0400209 return UTIL_stat(infilename, &statbuf) && UTIL_isDirectoryStat(&statbuf);
Rohit Jainf881ee82018-10-11 12:52:19 -0700210}
211
W. Felix Handte44fa0522020-08-05 01:00:06 -0400212int UTIL_isDirectoryStat(const stat_t* statbuf)
213{
214#if defined(_MSC_VER)
215 return (statbuf->st_mode & _S_IFDIR) != 0;
216#else
217 return S_ISDIR(statbuf->st_mode) != 0;
218#endif
219}
220
Sen Huangf80437c2019-10-02 11:08:20 -0400221int UTIL_compareStr(const void *p1, const void *p2) {
222 return strcmp(* (char * const *) p1, * (char * const *) p2);
223}
Sen Huanga9c807a2019-09-06 10:17:04 -0700224
Yann Collet00040432019-10-17 10:56:14 -0700225int UTIL_isSameFile(const char* fName1, const char* fName2)
shakeelraoe5811e52019-03-23 19:04:56 -0700226{
Yann Collet00040432019-10-17 10:56:14 -0700227 assert(fName1 != NULL); assert(fName2 != NULL);
228#if defined(_MSC_VER) || defined(_WIN32)
shakeelraoe5811e52019-03-23 19:04:56 -0700229 /* note : Visual does not support file identification by inode.
Yann Collet00040432019-10-17 10:56:14 -0700230 * inode does not work on Windows, even with a posix layer, like msys2.
shakeelraoe5811e52019-03-23 19:04:56 -0700231 * The following work-around is limited to detecting exact name repetition only,
232 * aka `filename` is considered different from `subdir/../filename` */
Yann Collet157479a2019-10-17 14:31:42 -0700233 return !strcmp(fName1, fName2);
shakeelraoe5811e52019-03-23 19:04:56 -0700234#else
Yann Collet00040432019-10-17 10:56:14 -0700235 { stat_t file1Stat;
236 stat_t file2Stat;
W. Felix Handte5fbc6ad2020-08-05 00:31:48 -0400237 return UTIL_stat(fName1, &file1Stat)
238 && UTIL_stat(fName2, &file2Stat)
Yann Collet00040432019-10-17 10:56:14 -0700239 && (file1Stat.st_dev == file2Stat.st_dev)
240 && (file1Stat.st_ino == file2Stat.st_ino);
241 }
shakeelraoe5811e52019-03-23 19:04:56 -0700242#endif
243}
244
Yann Collet9a221402019-11-25 13:45:22 -0800245/* UTIL_isFIFO : distinguish named pipes */
246int UTIL_isFIFO(const char* infilename)
Bimba Shrestha8a397482019-10-22 15:23:22 -0700247{
248/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
249#if PLATFORM_POSIX_VERSION >= 200112L
250 stat_t statbuf;
W. Felix Handte44fa0522020-08-05 01:00:06 -0400251 if (UTIL_stat(infilename, &statbuf) && UTIL_isFIFOStat(&statbuf)) return 1;
Bimba Shrestha8a397482019-10-22 15:23:22 -0700252#endif
253 (void)infilename;
254 return 0;
255}
Bimba Shrestha8a397482019-10-22 15:23:22 -0700256
W. Felix Handte44fa0522020-08-05 01:00:06 -0400257/* UTIL_isFIFO : distinguish named pipes */
258int UTIL_isFIFOStat(const stat_t* statbuf)
259{
260/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
261#if PLATFORM_POSIX_VERSION >= 200112L
262 if (S_ISFIFO(statbuf->st_mode)) return 1;
263#endif
264 (void)statbuf;
265 return 0;
266}
267
W. Felix Handte33f3e292021-05-04 16:24:46 -0400268/* UTIL_isBlockDevStat : distinguish named pipes */
269int UTIL_isBlockDevStat(const stat_t* statbuf)
270{
271/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
272#if PLATFORM_POSIX_VERSION >= 200112L
273 if (S_ISBLK(statbuf->st_mode)) return 1;
274#endif
275 (void)statbuf;
276 return 0;
277}
278
Yann Collet9a221402019-11-25 13:45:22 -0800279int UTIL_isLink(const char* infilename)
Rohit Jainf881ee82018-10-11 12:52:19 -0700280{
281/* macro guards, as defined in : https://linux.die.net/man/2/lstat */
W. Felix Handted2c48042019-06-07 15:31:33 -0400282#if PLATFORM_POSIX_VERSION >= 200112L
Rohit Jainf881ee82018-10-11 12:52:19 -0700283 stat_t statbuf;
Yann Collet9a221402019-11-25 13:45:22 -0800284 int const r = lstat(infilename, &statbuf);
Rohit Jainf881ee82018-10-11 12:52:19 -0700285 if (!r && S_ISLNK(statbuf.st_mode)) return 1;
286#endif
Rohit Jainf881ee82018-10-11 12:52:19 -0700287 (void)infilename;
288 return 0;
289}
290
291U64 UTIL_getFileSize(const char* infilename)
292{
W. Felix Handte69cb9e72020-08-05 00:21:41 -0400293 stat_t statbuf;
294 if (!UTIL_stat(infilename, &statbuf)) return UTIL_FILESIZE_UNKNOWN;
W. Felix Handte44fa0522020-08-05 01:00:06 -0400295 return UTIL_getFileSizeStat(&statbuf);
296}
297
298U64 UTIL_getFileSizeStat(const stat_t* statbuf)
299{
300 if (!UTIL_isRegularFileStat(statbuf)) return UTIL_FILESIZE_UNKNOWN;
Rohit Jainf881ee82018-10-11 12:52:19 -0700301#if defined(_MSC_VER)
W. Felix Handte44fa0522020-08-05 01:00:06 -0400302 if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
Rohit Jainf881ee82018-10-11 12:52:19 -0700303#elif defined(__MINGW32__) && defined (__MSVCRT__)
W. Felix Handte44fa0522020-08-05 01:00:06 -0400304 if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN;
Rohit Jainf881ee82018-10-11 12:52:19 -0700305#else
W. Felix Handte44fa0522020-08-05 01:00:06 -0400306 if (!S_ISREG(statbuf->st_mode)) return UTIL_FILESIZE_UNKNOWN;
Rohit Jainf881ee82018-10-11 12:52:19 -0700307#endif
W. Felix Handte44fa0522020-08-05 01:00:06 -0400308 return (U64)statbuf->st_size;
Rohit Jainf881ee82018-10-11 12:52:19 -0700309}
310
Yann Colleteab69222021-09-03 12:51:02 -0700311UTIL_HumanReadableSize_t UTIL_makeHumanReadableSize(U64 size)
312{
W. Felix Handtebbb81c82021-06-09 13:05:44 -0400313 UTIL_HumanReadableSize_t hrs;
W. Felix Handtebbb81c82021-06-09 13:05:44 -0400314
W. Felix Handte9c340ce2021-06-09 16:13:00 -0400315 if (g_utilDisplayLevel > 3) {
W. Felix Handte464bfb02021-06-09 15:22:59 -0400316 /* In verbose mode, do not scale sizes down, except in the case of
317 * values that exceed the integral precision of a double. */
318 if (size >= (1ull << 53)) {
319 hrs.value = (double)size / (1ull << 20);
W. Felix Handte2af36872021-06-10 12:06:51 -0400320 hrs.suffix = " MiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400321 /* At worst, a double representation of a maximal size will be
322 * accurate to better than tens of kilobytes. */
323 hrs.precision = 2;
324 } else {
325 hrs.value = (double)size;
W. Felix Handte93bb3682021-06-09 15:26:16 -0400326 hrs.suffix = " B";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400327 hrs.precision = 0;
328 }
W. Felix Handtebbb81c82021-06-09 13:05:44 -0400329 } else {
W. Felix Handte464bfb02021-06-09 15:22:59 -0400330 /* In regular mode, scale sizes down and use suffixes. */
331 if (size >= (1ull << 60)) {
332 hrs.value = (double)size / (1ull << 60);
W. Felix Handte2af36872021-06-10 12:06:51 -0400333 hrs.suffix = " EiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400334 } else if (size >= (1ull << 50)) {
335 hrs.value = (double)size / (1ull << 50);
W. Felix Handte2af36872021-06-10 12:06:51 -0400336 hrs.suffix = " PiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400337 } else if (size >= (1ull << 40)) {
338 hrs.value = (double)size / (1ull << 40);
W. Felix Handte2af36872021-06-10 12:06:51 -0400339 hrs.suffix = " TiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400340 } else if (size >= (1ull << 30)) {
341 hrs.value = (double)size / (1ull << 30);
W. Felix Handte2af36872021-06-10 12:06:51 -0400342 hrs.suffix = " GiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400343 } else if (size >= (1ull << 20)) {
344 hrs.value = (double)size / (1ull << 20);
W. Felix Handte2af36872021-06-10 12:06:51 -0400345 hrs.suffix = " MiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400346 } else if (size >= (1ull << 10)) {
347 hrs.value = (double)size / (1ull << 10);
W. Felix Handte2af36872021-06-10 12:06:51 -0400348 hrs.suffix = " KiB";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400349 } else {
350 hrs.value = (double)size;
W. Felix Handte93bb3682021-06-09 15:26:16 -0400351 hrs.suffix = " B";
W. Felix Handte464bfb02021-06-09 15:22:59 -0400352 }
353
354 if (hrs.value >= 100 || (U64)hrs.value == size) {
355 hrs.precision = 0;
356 } else if (hrs.value >= 10) {
357 hrs.precision = 1;
358 } else if (hrs.value > 1) {
359 hrs.precision = 2;
360 } else {
361 hrs.precision = 3;
362 }
W. Felix Handtebbb81c82021-06-09 13:05:44 -0400363 }
364
365 return hrs;
366}
Rohit Jainf881ee82018-10-11 12:52:19 -0700367
Yann Collet5fb84ca2019-10-25 17:34:29 -0700368U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles)
Rohit Jainf881ee82018-10-11 12:52:19 -0700369{
370 U64 total = 0;
Rohit Jainf881ee82018-10-11 12:52:19 -0700371 unsigned n;
372 for (n=0; n<nbFiles; n++) {
373 U64 const size = UTIL_getFileSize(fileNamesTable[n]);
Yann Collet5fb84ca2019-10-25 17:34:29 -0700374 if (size == UTIL_FILESIZE_UNKNOWN) return UTIL_FILESIZE_UNKNOWN;
Rohit Jainf881ee82018-10-11 12:52:19 -0700375 total += size;
376 }
Yann Collet5fb84ca2019-10-25 17:34:29 -0700377 return total;
Rohit Jainf881ee82018-10-11 12:52:19 -0700378}
379
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100380
Yann Collet1ead0c52019-10-25 16:36:59 -0700381/* condition : @file must be valid, and not have reached its end.
Yann Colletd9c634e2019-10-28 15:03:32 -0700382 * @return : length of line written into @buf, ended with `\0` instead of '\n',
Yann Collet1ead0c52019-10-25 16:36:59 -0700383 * or 0, if there is no new line */
384static size_t readLineFromFile(char* buf, size_t len, FILE* file)
385{
Yann Collet1ead0c52019-10-25 16:36:59 -0700386 assert(!feof(file));
Yann Colletdf05b2b2021-05-05 18:01:55 -0700387 if ( fgets(buf, (int) len, file) == NULL ) return 0;
Yann Colletd9c634e2019-10-28 15:03:32 -0700388 { size_t linelen = strlen(buf);
389 if (strlen(buf)==0) return 0;
390 if (buf[linelen-1] == '\n') linelen--;
391 buf[linelen] = '\0';
392 return linelen+1;
393 }
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100394}
395
Yann Collet1ead0c52019-10-25 16:36:59 -0700396/* Conditions :
397 * size of @inputFileName file must be < @dstCapacity
398 * @dst must be initialized
399 * @return : nb of lines
400 * or -1 if there's an error
401 */
402static int
403readLinesFromFile(void* dst, size_t dstCapacity,
404 const char* inputFileName)
405{
406 int nbFiles = 0;
Yann Collet3e5c81e2019-10-26 00:01:11 -0700407 size_t pos = 0;
Yann Collet1ead0c52019-10-25 16:36:59 -0700408 char* const buf = (char*)dst;
409 FILE* const inputFile = fopen(inputFileName, "r");
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100410
Yann Collet1ead0c52019-10-25 16:36:59 -0700411 assert(dst != NULL);
Ahmed Abdellahaefa18e2019-10-24 10:12:51 +0100412
Yann Collet1ead0c52019-10-25 16:36:59 -0700413 if(!inputFile) {
414 if (g_utilDisplayLevel >= 1) perror("zstd:util:readLinesFromFile");
415 return -1;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100416 }
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100417
Yann Collet1ead0c52019-10-25 16:36:59 -0700418 while ( !feof(inputFile) ) {
419 size_t const lineLength = readLineFromFile(buf+pos, dstCapacity-pos, inputFile);
420 if (lineLength == 0) break;
421 assert(pos + lineLength < dstCapacity);
Yann Colletd9c634e2019-10-28 15:03:32 -0700422 pos += lineLength;
Yann Collet1ead0c52019-10-25 16:36:59 -0700423 ++nbFiles;
Yann Collet1ead0c52019-10-25 16:36:59 -0700424 }
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100425
Yann Collet1ead0c52019-10-25 16:36:59 -0700426 CONTROL( fclose(inputFile) == 0 );
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100427
Yann Collet1ead0c52019-10-25 16:36:59 -0700428 return nbFiles;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100429}
430
431/*Note: buf is not freed in case function successfully created table because filesTable->fileNames[0] = buf*/
432FileNamesTable*
Yann Collet1ead0c52019-10-25 16:36:59 -0700433UTIL_createFileNamesTable_fromFileName(const char* inputFileName)
434{
435 size_t nbFiles = 0;
436 char* buf;
437 size_t bufSize;
438 size_t pos = 0;
W. Felix Handte7238cca2020-08-05 01:08:34 -0400439 stat_t statbuf;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100440
W. Felix Handte7238cca2020-08-05 01:08:34 -0400441 if (!UTIL_stat(inputFileName, &statbuf) || !UTIL_isRegularFileStat(&statbuf))
Yann Collet1ead0c52019-10-25 16:36:59 -0700442 return NULL;
Ahmed Abdellah47712c92019-10-24 10:30:05 +0100443
W. Felix Handte7238cca2020-08-05 01:08:34 -0400444 { U64 const inputFileSize = UTIL_getFileSizeStat(&statbuf);
Yann Collet1ead0c52019-10-25 16:36:59 -0700445 if(inputFileSize > MAX_FILE_OF_FILE_NAMES_SIZE)
446 return NULL;
Yann Collet12efa1e2019-10-26 00:27:32 -0700447 bufSize = (size_t)(inputFileSize + 1); /* (+1) to add '\0' at the end of last filename */
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100448 }
449
Yann Collet1ead0c52019-10-25 16:36:59 -0700450 buf = (char*) malloc(bufSize);
451 CONTROL( buf != NULL );
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100452
Yann Collet1ead0c52019-10-25 16:36:59 -0700453 { int const ret_nbFiles = readLinesFromFile(buf, bufSize, inputFileName);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100454
Yann Collet1ead0c52019-10-25 16:36:59 -0700455 if (ret_nbFiles <= 0) {
456 free(buf);
457 return NULL;
458 }
459 nbFiles = (size_t)ret_nbFiles;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100460 }
461
Yann Collet1ead0c52019-10-25 16:36:59 -0700462 { const char** filenamesTable = (const char**) malloc(nbFiles * sizeof(*filenamesTable));
463 CONTROL(filenamesTable != NULL);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100464
Yann Collet1ead0c52019-10-25 16:36:59 -0700465 { size_t fnb;
466 for (fnb = 0, pos = 0; fnb < nbFiles; fnb++) {
467 filenamesTable[fnb] = buf+pos;
468 pos += strlen(buf+pos)+1; /* +1 for the finishing `\0` */
469 } }
470 assert(pos <= bufSize);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100471
Yann Collet9a3de0a2019-11-25 15:34:55 -0800472 return UTIL_assembleFileNamesTable(filenamesTable, nbFiles, buf);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100473 }
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100474}
475
Yann Colleta49417b2019-12-02 14:28:18 -0800476static FileNamesTable*
477UTIL_assembleFileNamesTable2(const char** filenames, size_t tableSize, size_t tableCapacity, char* buf)
Yann Collet1ead0c52019-10-25 16:36:59 -0700478{
479 FileNamesTable* const table = (FileNamesTable*) malloc(sizeof(*table));
Yann Collet96ee2072019-11-26 15:44:33 -0800480 CONTROL(table != NULL);
Yann Collet1ead0c52019-10-25 16:36:59 -0700481 table->fileNames = filenames;
482 table->buf = buf;
483 table->tableSize = tableSize;
Yann Colleta49417b2019-12-02 14:28:18 -0800484 table->tableCapacity = tableCapacity;
Yann Collet1ead0c52019-10-25 16:36:59 -0700485 return table;
Ahmed Abdellahcddb05e2019-10-24 14:42:37 +0100486}
487
Yann Colleta49417b2019-12-02 14:28:18 -0800488FileNamesTable*
489UTIL_assembleFileNamesTable(const char** filenames, size_t tableSize, char* buf)
490{
491 return UTIL_assembleFileNamesTable2(filenames, tableSize, tableSize, buf);
492}
493
Yann Collet1ead0c52019-10-25 16:36:59 -0700494void UTIL_freeFileNamesTable(FileNamesTable* table)
495{
496 if (table==NULL) return;
497 free((void*)table->fileNames);
498 free(table->buf);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100499 free(table);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100500}
501
Yann Colletb09f5932019-11-05 17:02:43 -0800502FileNamesTable* UTIL_allocateFileNamesTable(size_t tableSize)
503{
504 const char** const fnTable = (const char**)malloc(tableSize * sizeof(*fnTable));
505 FileNamesTable* fnt;
506 if (fnTable==NULL) return NULL;
Yann Collet9a3de0a2019-11-25 15:34:55 -0800507 fnt = UTIL_assembleFileNamesTable(fnTable, tableSize, NULL);
Yann Colletb09f5932019-11-05 17:02:43 -0800508 fnt->tableSize = 0; /* the table is empty */
509 return fnt;
510}
511
512void UTIL_refFilename(FileNamesTable* fnt, const char* filename)
513{
Yann Colletf622c0a2019-11-26 14:48:23 -0800514 assert(fnt->tableSize < fnt->tableCapacity);
Yann Colletb09f5932019-11-05 17:02:43 -0800515 fnt->fileNames[fnt->tableSize] = filename;
516 fnt->tableSize++;
517}
518
Yann Collet1ead0c52019-10-25 16:36:59 -0700519static size_t getTotalTableSize(FileNamesTable* table)
520{
521 size_t fnb = 0, totalSize = 0;
522 for(fnb = 0 ; fnb < table->tableSize && table->fileNames[fnb] ; ++fnb) {
523 totalSize += strlen(table->fileNames[fnb]) + 1; /* +1 to add '\0' at the end of each fileName */
524 }
525 return totalSize;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100526}
527
528FileNamesTable*
Yann Collet31a0abb2019-11-06 09:10:05 -0800529UTIL_mergeFileNamesTable(FileNamesTable* table1, FileNamesTable* table2)
Yann Collet1ead0c52019-10-25 16:36:59 -0700530{
531 unsigned newTableIdx = 0;
532 size_t pos = 0;
533 size_t newTotalTableSize;
534 char* buf;
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100535
Yann Collet9a3de0a2019-11-25 15:34:55 -0800536 FileNamesTable* const newTable = UTIL_assembleFileNamesTable(NULL, 0, NULL);
Yann Collet1ead0c52019-10-25 16:36:59 -0700537 CONTROL( newTable != NULL );
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100538
Ahmed Abdellahaefa18e2019-10-24 10:12:51 +0100539 newTotalTableSize = getTotalTableSize(table1) + getTotalTableSize(table2);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100540
Yann Collet1ead0c52019-10-25 16:36:59 -0700541 buf = (char*) calloc(newTotalTableSize, sizeof(*buf));
542 CONTROL ( buf != NULL );
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100543
Ahmed Abdellahaefa18e2019-10-24 10:12:51 +0100544 newTable->buf = buf;
Yann Collet1ead0c52019-10-25 16:36:59 -0700545 newTable->tableSize = table1->tableSize + table2->tableSize;
546 newTable->fileNames = (const char **) calloc(newTable->tableSize, sizeof(*(newTable->fileNames)));
547 CONTROL ( newTable->fileNames != NULL );
548
549 { unsigned idx1;
550 for( idx1=0 ; (idx1 < table1->tableSize) && table1->fileNames[idx1] && (pos < newTotalTableSize); ++idx1, ++newTableIdx) {
551 size_t const curLen = strlen(table1->fileNames[idx1]);
552 memcpy(buf+pos, table1->fileNames[idx1], curLen);
553 assert(newTableIdx <= newTable->tableSize);
554 newTable->fileNames[newTableIdx] = buf+pos;
555 pos += curLen+1;
556 } }
557
558 { unsigned idx2;
559 for( idx2=0 ; (idx2 < table2->tableSize) && table2->fileNames[idx2] && (pos < newTotalTableSize) ; ++idx2, ++newTableIdx) {
560 size_t const curLen = strlen(table2->fileNames[idx2]);
561 memcpy(buf+pos, table2->fileNames[idx2], curLen);
562 assert(newTableIdx <= newTable->tableSize);
563 newTable->fileNames[newTableIdx] = buf+pos;
564 pos += curLen+1;
565 } }
566 assert(pos <= newTotalTableSize);
Yann Collet1ead0c52019-10-25 16:36:59 -0700567 newTable->tableSize = newTableIdx;
Ahmed Abdellahaefa18e2019-10-24 10:12:51 +0100568
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100569 UTIL_freeFileNamesTable(table1);
570 UTIL_freeFileNamesTable(table2);
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100571
Ahmed Abdellah779ea722019-10-15 07:49:13 +0100572 return newTable;
573}
574
Rohit Jainc7251e52018-10-11 18:05:15 -0700575#ifdef _WIN32
Yann Collet76b9e422019-11-05 14:59:45 -0800576static int UTIL_prepareFileList(const char* dirName,
577 char** bufStart, size_t* pos,
578 char** bufEnd, int followLinks)
Rohit Jain705e0b12018-10-11 15:51:57 -0700579{
580 char* path;
Yann Collet74d872e2019-10-25 18:26:30 -0700581 size_t dirLength, pathLength;
582 int nbFiles = 0;
Rohit Jain705e0b12018-10-11 15:51:57 -0700583 WIN32_FIND_DATAA cFile;
584 HANDLE hFile;
585
Yann Collet1ead0c52019-10-25 16:36:59 -0700586 dirLength = strlen(dirName);
Rohit Jain705e0b12018-10-11 15:51:57 -0700587 path = (char*) malloc(dirLength + 3);
588 if (!path) return 0;
589
590 memcpy(path, dirName, dirLength);
591 path[dirLength] = '\\';
592 path[dirLength+1] = '*';
593 path[dirLength+2] = 0;
594
595 hFile=FindFirstFileA(path, &cFile);
596 if (hFile == INVALID_HANDLE_VALUE) {
597 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName);
598 return 0;
599 }
600 free(path);
601
602 do {
Yann Collet1ead0c52019-10-25 16:36:59 -0700603 size_t const fnameLength = strlen(cFile.cFileName);
Rohit Jain705e0b12018-10-11 15:51:57 -0700604 path = (char*) malloc(dirLength + fnameLength + 2);
605 if (!path) { FindClose(hFile); return 0; }
606 memcpy(path, dirName, dirLength);
607 path[dirLength] = '\\';
608 memcpy(path+dirLength+1, cFile.cFileName, fnameLength);
609 pathLength = dirLength+1+fnameLength;
610 path[pathLength] = 0;
611 if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800612 if ( strcmp (cFile.cFileName, "..") == 0
613 || strcmp (cFile.cFileName, ".") == 0 )
614 continue;
615 /* Recursively call "UTIL_prepareFileList" with the new path. */
616 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks);
Rohit Jain705e0b12018-10-11 15:51:57 -0700617 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800618 } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL)
619 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
620 || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) {
Rohit Jain705e0b12018-10-11 15:51:57 -0700621 if (*bufStart + *pos + pathLength >= *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800622 ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
Rohit Jain705e0b12018-10-11 15:51:57 -0700623 *bufStart = (char*)UTIL_realloc(*bufStart, newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700624 if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; }
Yann Collet72dbf1b2018-12-20 12:27:12 -0800625 *bufEnd = *bufStart + newListSize;
Rohit Jain705e0b12018-10-11 15:51:57 -0700626 }
627 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800628 memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */);
Rohit Jain705e0b12018-10-11 15:51:57 -0700629 *pos += pathLength + 1;
630 nbFiles++;
Yann Collet1ead0c52019-10-25 16:36:59 -0700631 } }
Rohit Jain705e0b12018-10-11 15:51:57 -0700632 free(path);
633 } while (FindNextFileA(hFile, &cFile));
634
635 FindClose(hFile);
636 return nbFiles;
637}
638
639#elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */
640
Yann Collet76b9e422019-11-05 14:59:45 -0800641static int UTIL_prepareFileList(const char *dirName,
642 char** bufStart, size_t* pos,
643 char** bufEnd, int followLinks)
Rohit Jain705e0b12018-10-11 15:51:57 -0700644{
Yann Collet1ead0c52019-10-25 16:36:59 -0700645 DIR* dir;
646 struct dirent * entry;
647 size_t dirLength;
Yann Colleta71256a2019-10-17 11:01:20 -0700648 int nbFiles = 0;
Rohit Jain705e0b12018-10-11 15:51:57 -0700649
650 if (!(dir = opendir(dirName))) {
651 UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno));
652 return 0;
653 }
654
Yann Colleta71256a2019-10-17 11:01:20 -0700655 dirLength = strlen(dirName);
Rohit Jain705e0b12018-10-11 15:51:57 -0700656 errno = 0;
657 while ((entry = readdir(dir)) != NULL) {
Yann Collet1ead0c52019-10-25 16:36:59 -0700658 char* path;
659 size_t fnameLength, pathLength;
Rohit Jain705e0b12018-10-11 15:51:57 -0700660 if (strcmp (entry->d_name, "..") == 0 ||
661 strcmp (entry->d_name, ".") == 0) continue;
Yann Colleta71256a2019-10-17 11:01:20 -0700662 fnameLength = strlen(entry->d_name);
Rohit Jain705e0b12018-10-11 15:51:57 -0700663 path = (char*) malloc(dirLength + fnameLength + 2);
664 if (!path) { closedir(dir); return 0; }
665 memcpy(path, dirName, dirLength);
666
667 path[dirLength] = '/';
668 memcpy(path+dirLength+1, entry->d_name, fnameLength);
669 pathLength = dirLength+1+fnameLength;
670 path[pathLength] = 0;
671
672 if (!followLinks && UTIL_isLink(path)) {
673 UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path);
LeeYoung624793b94b2019-07-25 21:07:57 +0800674 free(path);
Rohit Jain705e0b12018-10-11 15:51:57 -0700675 continue;
676 }
677
678 if (UTIL_isDirectory(path)) {
679 nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */
680 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
681 } else {
682 if (*bufStart + *pos + pathLength >= *bufEnd) {
683 ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE;
Yann Colleta71256a2019-10-17 11:01:20 -0700684 assert(newListSize >= 0);
685 *bufStart = (char*)UTIL_realloc(*bufStart, (size_t)newListSize);
Rohit Jain705e0b12018-10-11 15:51:57 -0700686 *bufEnd = *bufStart + newListSize;
687 if (*bufStart == NULL) { free(path); closedir(dir); return 0; }
688 }
689 if (*bufStart + *pos + pathLength < *bufEnd) {
Yann Collet72dbf1b2018-12-20 12:27:12 -0800690 memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */
Rohit Jain705e0b12018-10-11 15:51:57 -0700691 *pos += pathLength + 1;
692 nbFiles++;
Yann Collet1ead0c52019-10-25 16:36:59 -0700693 } }
Rohit Jain705e0b12018-10-11 15:51:57 -0700694 free(path);
695 errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */
696 }
697
698 if (errno != 0) {
Yann Collet96ee2072019-11-26 15:44:33 -0800699 UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s \n", dirName, strerror(errno));
Rohit Jain705e0b12018-10-11 15:51:57 -0700700 free(*bufStart);
701 *bufStart = NULL;
702 }
703 closedir(dir);
704 return nbFiles;
705}
706
707#else
708
Yann Collet76b9e422019-11-05 14:59:45 -0800709static int UTIL_prepareFileList(const char *dirName,
710 char** bufStart, size_t* pos,
711 char** bufEnd, int followLinks)
Rohit Jain705e0b12018-10-11 15:51:57 -0700712{
713 (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks;
Yann Collet96ee2072019-11-26 15:44:33 -0800714 UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE) \n", dirName);
Rohit Jain705e0b12018-10-11 15:51:57 -0700715 return 0;
716}
717
718#endif /* #ifdef _WIN32 */
719
Shashank Tavildar0f2bff22019-10-28 18:21:47 -0700720int UTIL_isCompressedFile(const char *inputName, const char *extensionList[])
Shashank Tavildar48f85662019-10-25 15:49:11 -0700721{
Shashank Tavildar9ab6a742019-10-29 12:27:54 -0700722 const char* ext = UTIL_getFileExtension(inputName);
Shashank Tavildar3c1649f2019-10-29 15:59:20 -0700723 while(*extensionList!=NULL)
Shashank Tavildarc5060992019-10-29 12:56:04 -0700724 {
Shashank Tavildar3c1649f2019-10-29 15:59:20 -0700725 const int isCompressedExtension = strcmp(ext,*extensionList);
726 if(isCompressedExtension==0)
727 return 1;
728 ++extensionList;
Shashank Tavildarc5060992019-10-29 12:56:04 -0700729 }
Shashank Tavildar02433e02019-10-28 14:54:54 -0700730 return 0;
Shashank Tavildar48f85662019-10-25 15:49:11 -0700731}
Shashank Tavildar0f2bff22019-10-28 18:21:47 -0700732
Shashank Tavildar9ab6a742019-10-29 12:27:54 -0700733/*Utility function to get file extension from file */
734const char* UTIL_getFileExtension(const char* infilename)
735{
736 const char* extension = strrchr(infilename, '.');
737 if(!extension || extension==infilename) return "";
738 return extension;
739}
740
Xin Xie9a8ccd42020-06-19 19:35:51 -0700741static int pathnameHas2Dots(const char *pathname)
742{
W. Felix Handte61db5902021-02-26 12:29:42 -0500743 /* We need to figure out whether any ".." present in the path is a whole
744 * path token, which is the case if it is bordered on both sides by either
745 * the beginning/end of the path or by a directory separator.
746 */
747 const char *needle = pathname;
748 while (1) {
749 needle = strstr(needle, "..");
750
751 if (needle == NULL) {
752 return 0;
753 }
754
755 if ((needle == pathname || needle[-1] == PATH_SEP)
756 && (needle[2] == '\0' || needle[2] == PATH_SEP)) {
757 return 1;
758 }
759
760 /* increment so we search for the next match */
761 needle++;
762 };
763 return 0;
Xin Xie9a8ccd42020-06-19 19:35:51 -0700764}
765
766static int isFileNameValidForMirroredOutput(const char *filename)
767{
768 return !pathnameHas2Dots(filename);
769}
770
771
772#define DIR_DEFAULT_MODE 0755
773static mode_t getDirMode(const char *dirName)
774{
775 stat_t st;
W. Felix Handte51ac0202020-08-10 15:28:02 -0400776 if (!UTIL_stat(dirName, &st)) {
Xin Xie9a8ccd42020-06-19 19:35:51 -0700777 UTIL_DISPLAY("zstd: failed to get DIR stats %s: %s\n", dirName, strerror(errno));
778 return DIR_DEFAULT_MODE;
779 }
W. Felix Handte51ac0202020-08-10 15:28:02 -0400780 if (!UTIL_isDirectoryStat(&st)) {
781 UTIL_DISPLAY("zstd: expected directory: %s\n", dirName);
782 return DIR_DEFAULT_MODE;
783 }
Xin Xie9a8ccd42020-06-19 19:35:51 -0700784 return st.st_mode;
785}
786
787static int makeDir(const char *dir, mode_t mode)
788{
789#if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__)
790 int ret = _mkdir(dir);
791 (void) mode;
792#else
793 int ret = mkdir(dir, mode);
794#endif
795 if (ret != 0) {
796 if (errno == EEXIST)
797 return 0;
798 UTIL_DISPLAY("zstd: failed to create DIR %s: %s\n", dir, strerror(errno));
799 }
800 return ret;
801}
802
803/* this function requires a mutable input string */
804static void convertPathnameToDirName(char *pathname)
805{
806 size_t len = 0;
807 char* pos = NULL;
808 /* get dir name from pathname similar to 'dirname()' */
809 assert(pathname != NULL);
810
811 /* remove trailing '/' chars */
812 len = strlen(pathname);
813 assert(len > 0);
814 while (pathname[len] == PATH_SEP) {
815 pathname[len] = '\0';
816 len--;
817 }
818 if (len == 0) return;
819
820 /* if input is a single file, return '.' instead. i.e.
821 * "xyz/abc/file.txt" => "xyz/abc"
822 "./file.txt" => "."
823 "file.txt" => "."
824 */
825 pos = strrchr(pathname, PATH_SEP);
826 if (pos == NULL) {
827 pathname[0] = '.';
828 pathname[1] = '\0';
829 } else {
830 *pos = '\0';
831 }
832}
833
834/* pathname must be valid */
835static const char* trimLeadingRootChar(const char *pathname)
836{
837 assert(pathname != NULL);
838 if (pathname[0] == PATH_SEP)
839 return pathname + 1;
840 return pathname;
841}
842
843/* pathname must be valid */
844static const char* trimLeadingCurrentDirConst(const char *pathname)
845{
846 assert(pathname != NULL);
847 if ((pathname[0] == '.') && (pathname[1] == PATH_SEP))
848 return pathname + 2;
849 return pathname;
850}
851
852static char*
853trimLeadingCurrentDir(char *pathname)
854{
855 /* 'union charunion' can do const-cast without compiler warning */
856 union charunion {
857 char *chr;
858 const char* cchr;
859 } ptr;
860 ptr.cchr = trimLeadingCurrentDirConst(pathname);
861 return ptr.chr;
862}
863
864/* remove leading './' or '/' chars here */
865static const char * trimPath(const char *pathname)
866{
867 return trimLeadingRootChar(
868 trimLeadingCurrentDirConst(pathname));
869}
870
871static char* mallocAndJoin2Dir(const char *dir1, const char *dir2)
872{
873 const size_t dir1Size = strlen(dir1);
874 const size_t dir2Size = strlen(dir2);
875 char *outDirBuffer, *buffer, trailingChar;
876
877 assert(dir1 != NULL && dir2 != NULL);
878 outDirBuffer = (char *) malloc(dir1Size + dir2Size + 2);
879 CONTROL(outDirBuffer != NULL);
880
Yann Colletfed1c622020-11-30 04:44:37 -0800881 memcpy(outDirBuffer, dir1, dir1Size);
Xin Xie9a8ccd42020-06-19 19:35:51 -0700882 outDirBuffer[dir1Size] = '\0';
883
884 if (dir2[0] == '.')
885 return outDirBuffer;
886
887 buffer = outDirBuffer + dir1Size;
888 trailingChar = *(buffer - 1);
889 if (trailingChar != PATH_SEP) {
890 *buffer = PATH_SEP;
891 buffer++;
892 }
Yann Colletfed1c622020-11-30 04:44:37 -0800893 memcpy(buffer, dir2, dir2Size);
Xin Xie9a8ccd42020-06-19 19:35:51 -0700894 buffer[dir2Size] = '\0';
895
896 return outDirBuffer;
897}
898
899/* this function will return NULL if input srcFileName is not valid name for mirrored output path */
900char* UTIL_createMirroredDestDirName(const char* srcFileName, const char* outDirRootName)
901{
902 char* pathname = NULL;
903 if (!isFileNameValidForMirroredOutput(srcFileName))
904 return NULL;
905
906 pathname = mallocAndJoin2Dir(outDirRootName, trimPath(srcFileName));
907
908 convertPathnameToDirName(pathname);
909 return pathname;
910}
911
912static int
913mirrorSrcDir(char* srcDirName, const char* outDirName)
914{
915 mode_t srcMode;
916 int status = 0;
917 char* newDir = mallocAndJoin2Dir(outDirName, trimPath(srcDirName));
918 if (!newDir)
919 return -ENOMEM;
920
921 srcMode = getDirMode(srcDirName);
922 status = makeDir(newDir, srcMode);
923 free(newDir);
924 return status;
925}
926
927static int
928mirrorSrcDirRecursive(char* srcDirName, const char* outDirName)
929{
930 int status = 0;
931 char* pp = trimLeadingCurrentDir(srcDirName);
932 char* sp = NULL;
933
934 while ((sp = strchr(pp, PATH_SEP)) != NULL) {
935 if (sp != pp) {
936 *sp = '\0';
937 status = mirrorSrcDir(srcDirName, outDirName);
938 if (status != 0)
939 return status;
940 *sp = PATH_SEP;
941 }
942 pp = sp + 1;
943 }
944 status = mirrorSrcDir(srcDirName, outDirName);
945 return status;
946}
947
948static void
949makeMirroredDestDirsWithSameSrcDirMode(char** srcDirNames, unsigned nbFile, const char* outDirName)
950{
951 unsigned int i = 0;
952 for (i = 0; i < nbFile; i++)
953 mirrorSrcDirRecursive(srcDirNames[i], outDirName);
954}
955
956static int
957firstIsParentOrSameDirOfSecond(const char* firstDir, const char* secondDir)
958{
959 size_t firstDirLen = strlen(firstDir),
960 secondDirLen = strlen(secondDir);
961 return firstDirLen <= secondDirLen &&
962 (secondDir[firstDirLen] == PATH_SEP || secondDir[firstDirLen] == '\0') &&
963 0 == strncmp(firstDir, secondDir, firstDirLen);
964}
965
966static int compareDir(const void* pathname1, const void* pathname2) {
967 /* sort it after remove the leading '/' or './'*/
968 const char* s1 = trimPath(*(char * const *) pathname1);
969 const char* s2 = trimPath(*(char * const *) pathname2);
970 return strcmp(s1, s2);
971}
972
973static void
974makeUniqueMirroredDestDirs(char** srcDirNames, unsigned nbFile, const char* outDirName)
975{
976 unsigned int i = 0, uniqueDirNr = 0;
977 char** uniqueDirNames = NULL;
978
979 if (nbFile == 0)
980 return;
981
982 uniqueDirNames = (char** ) malloc(nbFile * sizeof (char *));
983 CONTROL(uniqueDirNames != NULL);
984
985 /* if dirs is "a/b/c" and "a/b/c/d", we only need call:
986 * we just need "a/b/c/d" */
987 qsort((void *)srcDirNames, nbFile, sizeof(char*), compareDir);
988
989 uniqueDirNr = 1;
990 uniqueDirNames[uniqueDirNr - 1] = srcDirNames[0];
991 for (i = 1; i < nbFile; i++) {
992 char* prevDirName = srcDirNames[i - 1];
993 char* currDirName = srcDirNames[i];
994
Dimitris Apostolouebbd6752021-11-13 10:04:04 +0200995 /* note: we always compare trimmed path, i.e.:
Xin Xie9a8ccd42020-06-19 19:35:51 -0700996 * src dir of "./foo" and "/foo" will be both saved into:
997 * "outDirName/foo/" */
998 if (!firstIsParentOrSameDirOfSecond(trimPath(prevDirName),
999 trimPath(currDirName)))
1000 uniqueDirNr++;
1001
1002 /* we need maintain original src dir name instead of trimmed
Dimitris Apostolouebbd6752021-11-13 10:04:04 +02001003 * dir, so we can retrieve the original src dir's mode_t */
Xin Xie9a8ccd42020-06-19 19:35:51 -07001004 uniqueDirNames[uniqueDirNr - 1] = currDirName;
1005 }
1006
1007 makeMirroredDestDirsWithSameSrcDirMode(uniqueDirNames, uniqueDirNr, outDirName);
1008
1009 free(uniqueDirNames);
1010}
1011
1012static void
1013makeMirroredDestDirs(char** srcFileNames, unsigned nbFile, const char* outDirName)
1014{
1015 unsigned int i = 0;
1016 for (i = 0; i < nbFile; ++i)
1017 convertPathnameToDirName(srcFileNames[i]);
1018 makeUniqueMirroredDestDirs(srcFileNames, nbFile, outDirName);
1019}
1020
1021void UTIL_mirrorSourceFilesDirectories(const char** inFileNames, unsigned int nbFile, const char* outDirName)
1022{
1023 unsigned int i = 0, validFilenamesNr = 0;
1024 char** srcFileNames = (char **) malloc(nbFile * sizeof (char *));
1025 CONTROL(srcFileNames != NULL);
1026
1027 /* check input filenames is valid */
1028 for (i = 0; i < nbFile; ++i) {
1029 if (isFileNameValidForMirroredOutput(inFileNames[i])) {
1030 char* fname = STRDUP(inFileNames[i]);
1031 CONTROL(fname != NULL);
1032 srcFileNames[validFilenamesNr++] = fname;
1033 }
1034 }
1035
1036 if (validFilenamesNr > 0) {
1037 makeDir(outDirName, DIR_DEFAULT_MODE);
1038 makeMirroredDestDirs(srcFileNames, validFilenamesNr, outDirName);
1039 }
1040
1041 for (i = 0; i < validFilenamesNr; i++)
1042 free(srcFileNames[i]);
1043 free(srcFileNames);
1044}
Yann Colletb09f5932019-11-05 17:02:43 -08001045
Yann Collet31a0abb2019-11-06 09:10:05 -08001046FileNamesTable*
Sen Huangf27e3262021-03-25 10:38:56 -07001047UTIL_createExpandedFNT(const char* const* inputNames, size_t nbIfns, int followLinks)
Rohit Jain705e0b12018-10-11 15:51:57 -07001048{
Yann Colletb09f5932019-11-05 17:02:43 -08001049 unsigned nbFiles;
Rohit Jain705e0b12018-10-11 15:51:57 -07001050 char* buf = (char*)malloc(LIST_SIZE_INCREASE);
1051 char* bufend = buf + LIST_SIZE_INCREASE;
Rohit Jain705e0b12018-10-11 15:51:57 -07001052
1053 if (!buf) return NULL;
1054
Yann Colletd5b4a7e2019-11-26 17:46:57 -08001055 { size_t ifnNb, pos;
Yann Colletb09f5932019-11-05 17:02:43 -08001056 for (ifnNb=0, pos=0, nbFiles=0; ifnNb<nbIfns; ifnNb++) {
1057 if (!UTIL_isDirectory(inputNames[ifnNb])) {
1058 size_t const len = strlen(inputNames[ifnNb]);
1059 if (buf + pos + len >= bufend) {
1060 ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE;
1061 assert(newListSize >= 0);
1062 buf = (char*)UTIL_realloc(buf, (size_t)newListSize);
Yann Colletb09f5932019-11-05 17:02:43 -08001063 if (!buf) return NULL;
Yann Colletd5b4a7e2019-11-26 17:46:57 -08001064 bufend = buf + newListSize;
Yann Colletb09f5932019-11-05 17:02:43 -08001065 }
1066 if (buf + pos + len < bufend) {
1067 memcpy(buf+pos, inputNames[ifnNb], len+1); /* including final \0 */
1068 pos += len + 1;
1069 nbFiles++;
1070 }
1071 } else {
1072 nbFiles += (unsigned)UTIL_prepareFileList(inputNames[ifnNb], &buf, &pos, &bufend, followLinks);
1073 if (buf == NULL) return NULL;
1074 } } }
Rohit Jain705e0b12018-10-11 15:51:57 -07001075
Yann Colleta49417b2019-12-02 14:28:18 -08001076 /* note : even if nbFiles==0, function returns a valid, though empty, FileNamesTable* object */
Rohit Jain705e0b12018-10-11 15:51:57 -07001077
Yann Colletd5b4a7e2019-11-26 17:46:57 -08001078 { size_t ifnNb, pos;
Yann Colleta49417b2019-12-02 14:28:18 -08001079 size_t const fntCapacity = nbFiles + 1; /* minimum 1, allows adding one reference, typically stdin */
1080 const char** const fileNamesTable = (const char**)malloc(fntCapacity * sizeof(*fileNamesTable));
Yann Colletb09f5932019-11-05 17:02:43 -08001081 if (!fileNamesTable) { free(buf); return NULL; }
Rohit Jain705e0b12018-10-11 15:51:57 -07001082
Yann Colletb09f5932019-11-05 17:02:43 -08001083 for (ifnNb = 0, pos = 0; ifnNb < nbFiles; ifnNb++) {
1084 fileNamesTable[ifnNb] = buf + pos;
1085 if (buf + pos > bufend) { free(buf); free((void*)fileNamesTable); return NULL; }
1086 pos += strlen(fileNamesTable[ifnNb]) + 1;
Yann Collet29e46ed2019-10-18 14:28:34 -07001087 }
Yann Colleta49417b2019-12-02 14:28:18 -08001088 return UTIL_assembleFileNamesTable2(fileNamesTable, nbFiles, fntCapacity, buf);
Rohit Jain705e0b12018-10-11 15:51:57 -07001089 }
Rohit Jain705e0b12018-10-11 15:51:57 -07001090}
1091
Yann Collet59a71162019-04-10 12:37:03 -07001092
Yann Collet31a0abb2019-11-06 09:10:05 -08001093void UTIL_expandFNT(FileNamesTable** fnt, int followLinks)
Yann Collet76b9e422019-11-05 14:59:45 -08001094{
Yann Collet31a0abb2019-11-06 09:10:05 -08001095 FileNamesTable* const newFNT = UTIL_createExpandedFNT((*fnt)->fileNames, (*fnt)->tableSize, followLinks);
Yann Colleta49417b2019-12-02 14:28:18 -08001096 CONTROL(newFNT != NULL);
Yann Collet31a0abb2019-11-06 09:10:05 -08001097 UTIL_freeFileNamesTable(*fnt);
1098 *fnt = newFNT;
Yann Collet76b9e422019-11-05 14:59:45 -08001099}
1100
Yann Colleta7e33e32019-11-06 14:42:13 -08001101FileNamesTable* UTIL_createFNT_fromROTable(const char** filenames, size_t nbFilenames)
1102{
1103 size_t const sizeof_FNTable = nbFilenames * sizeof(*filenames);
1104 const char** const newFNTable = (const char**)malloc(sizeof_FNTable);
1105 if (newFNTable==NULL) return NULL;
Yann Collet9df49dc2019-11-06 15:23:44 -08001106 memcpy((void*)newFNTable, filenames, sizeof_FNTable); /* void* : mitigate a Visual compiler bug or limitation */
Yann Colletd5b4a7e2019-11-26 17:46:57 -08001107 return UTIL_assembleFileNamesTable(newFNTable, nbFilenames, NULL);
Yann Colleta7e33e32019-11-06 14:42:13 -08001108}
1109
Yann Collet72dbf1b2018-12-20 12:27:12 -08001110
Rohit Jaina47f6e62018-10-11 16:51:29 -07001111/*-****************************************
Binh Vo6a46e382021-06-16 09:38:43 -04001112* count the number of cores
Rohit Jaind6d240f2018-10-11 15:07:12 -07001113******************************************/
Rohit Jainc7251e52018-10-11 18:05:15 -07001114
Rohit Jain91b2fed2018-10-11 17:34:47 -07001115#if defined(_WIN32) || defined(WIN32)
1116
1117#include <windows.h>
1118
1119typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
1120
Binh Vo6a46e382021-06-16 09:38:43 -04001121DWORD CountSetBits(ULONG_PTR bitMask)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001122{
Binh Vo6a46e382021-06-16 09:38:43 -04001123 DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1;
1124 DWORD bitSetCount = 0;
Yann Colleteab69222021-09-03 12:51:02 -07001125 ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT;
Binh Vo6a46e382021-06-16 09:38:43 -04001126 DWORD i;
Yann Colleteab69222021-09-03 12:51:02 -07001127
Binh Vo6a46e382021-06-16 09:38:43 -04001128 for (i = 0; i <= LSHIFT; ++i)
1129 {
1130 bitSetCount += ((bitMask & bitTest)?1:0);
1131 bitTest/=2;
1132 }
1133
1134 return bitSetCount;
1135}
1136
1137int UTIL_countCores(int logical)
1138{
1139 static int numCores = 0;
1140 if (numCores != 0) return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001141
1142 { LPFN_GLPI glpi;
1143 BOOL done = FALSE;
1144 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
1145 PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL;
1146 DWORD returnLength = 0;
1147 size_t byteOffset = 0;
1148
Yann Collet0492c572019-10-18 17:08:52 -07001149#if defined(_MSC_VER)
Yann Colletf3796372019-10-18 17:05:42 -07001150/* Visual Studio does not like the following cast */
1151# pragma warning( disable : 4054 ) /* conversion from function ptr to data ptr */
1152# pragma warning( disable : 4055 ) /* conversion from data ptr to function ptr */
1153#endif
Yann Collet1bd6c152019-10-18 15:45:31 -07001154 glpi = (LPFN_GLPI)(void*)GetProcAddress(GetModuleHandle(TEXT("kernel32")),
1155 "GetLogicalProcessorInformation");
Rohit Jain91b2fed2018-10-11 17:34:47 -07001156
1157 if (glpi == NULL) {
1158 goto failed;
1159 }
1160
1161 while(!done) {
1162 DWORD rc = glpi(buffer, &returnLength);
1163 if (FALSE == rc) {
1164 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
1165 if (buffer)
1166 free(buffer);
1167 buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength);
1168
1169 if (buffer == NULL) {
1170 perror("zstd");
1171 exit(1);
1172 }
1173 } else {
1174 /* some other error */
1175 goto failed;
1176 }
1177 } else {
1178 done = TRUE;
Yann Collet96ee2072019-11-26 15:44:33 -08001179 } }
Rohit Jain91b2fed2018-10-11 17:34:47 -07001180
1181 ptr = buffer;
1182
1183 while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) {
1184
1185 if (ptr->Relationship == RelationProcessorCore) {
Binh Vo6a46e382021-06-16 09:38:43 -04001186 if (logical)
1187 numCores += CountSetBits(ptr->ProcessorMask);
1188 else
1189 numCores++;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001190 }
1191
1192 ptr++;
1193 byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
1194 }
1195
1196 free(buffer);
1197
Binh Vo6a46e382021-06-16 09:38:43 -04001198 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001199 }
1200
1201failed:
1202 /* try to fall back on GetSystemInfo */
1203 { SYSTEM_INFO sysinfo;
1204 GetSystemInfo(&sysinfo);
Binh Vo6a46e382021-06-16 09:38:43 -04001205 numCores = sysinfo.dwNumberOfProcessors;
1206 if (numCores == 0) numCores = 1; /* just in case */
Rohit Jain91b2fed2018-10-11 17:34:47 -07001207 }
Binh Vo6a46e382021-06-16 09:38:43 -04001208 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001209}
1210
1211#elif defined(__APPLE__)
1212
1213#include <sys/sysctl.h>
1214
1215/* Use apple-provided syscall
1216 * see: man 3 sysctl */
Binh Vo6a46e382021-06-16 09:38:43 -04001217int UTIL_countCores(int logical)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001218{
Binh Vo6a46e382021-06-16 09:38:43 -04001219 static S32 numCores = 0; /* apple specifies int32_t */
1220 if (numCores != 0) return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001221
1222 { size_t size = sizeof(S32);
Binh Vo6a46e382021-06-16 09:38:43 -04001223 int const ret = sysctlbyname(logical ? "hw.logicalcpu" : "hw.physicalcpu", &numCores, &size, NULL, 0);
Rohit Jain91b2fed2018-10-11 17:34:47 -07001224 if (ret != 0) {
1225 if (errno == ENOENT) {
1226 /* entry not present, fall back on 1 */
Binh Vo6a46e382021-06-16 09:38:43 -04001227 numCores = 1;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001228 } else {
Binh Vo6a46e382021-06-16 09:38:43 -04001229 perror("zstd: can't get number of cpus");
Rohit Jain91b2fed2018-10-11 17:34:47 -07001230 exit(1);
1231 }
1232 }
1233
Binh Vo6a46e382021-06-16 09:38:43 -04001234 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001235 }
1236}
1237
1238#elif defined(__linux__)
1239
1240/* parse /proc/cpuinfo
1241 * siblings / cpu cores should give hyperthreading ratio
1242 * otherwise fall back on sysconf */
Binh Vo6a46e382021-06-16 09:38:43 -04001243int UTIL_countCores(int logical)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001244{
Binh Vo6a46e382021-06-16 09:38:43 -04001245 static int numCores = 0;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001246
Binh Vo6a46e382021-06-16 09:38:43 -04001247 if (numCores != 0) return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001248
Binh Vo6a46e382021-06-16 09:38:43 -04001249 numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
1250 if (numCores == -1) {
Rohit Jain91b2fed2018-10-11 17:34:47 -07001251 /* value not queryable, fall back on 1 */
Binh Vo6a46e382021-06-16 09:38:43 -04001252 return numCores = 1;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001253 }
1254
1255 /* try to determine if there's hyperthreading */
1256 { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r");
1257#define BUF_SIZE 80
1258 char buff[BUF_SIZE];
1259
1260 int siblings = 0;
1261 int cpu_cores = 0;
1262 int ratio = 1;
1263
1264 if (cpuinfo == NULL) {
1265 /* fall back on the sysconf value */
Binh Vo6a46e382021-06-16 09:38:43 -04001266 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001267 }
1268
1269 /* assume the cpu cores/siblings values will be constant across all
1270 * present processors */
1271 while (!feof(cpuinfo)) {
1272 if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) {
1273 if (strncmp(buff, "siblings", 8) == 0) {
1274 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +08001275 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -07001276 /* formatting was broken? */
1277 goto failed;
1278 }
1279
1280 siblings = atoi(sep + 1);
1281 }
1282 if (strncmp(buff, "cpu cores", 9) == 0) {
1283 const char* const sep = strchr(buff, ':');
LeeYoung624c5caaf52019-07-29 17:05:50 +08001284 if (sep == NULL || *sep == '\0') {
Rohit Jain91b2fed2018-10-11 17:34:47 -07001285 /* formatting was broken? */
1286 goto failed;
1287 }
1288
1289 cpu_cores = atoi(sep + 1);
1290 }
1291 } else if (ferror(cpuinfo)) {
1292 /* fall back on the sysconf value */
1293 goto failed;
Yann Collet96ee2072019-11-26 15:44:33 -08001294 } }
Paul Bone4d6c78f2021-03-02 20:31:23 +11001295 if (siblings && cpu_cores && siblings > cpu_cores) {
Rohit Jain91b2fed2018-10-11 17:34:47 -07001296 ratio = siblings / cpu_cores;
1297 }
Paul Boneeb1a09d2021-03-02 20:13:51 +11001298
Binh Vo6a46e382021-06-16 09:38:43 -04001299 if (ratio && numCores > ratio && !logical) {
1300 numCores = numCores / ratio;
Paul Bone4d6c78f2021-03-02 20:31:23 +11001301 }
Paul Boneeb1a09d2021-03-02 20:13:51 +11001302
Rohit Jain91b2fed2018-10-11 17:34:47 -07001303failed:
1304 fclose(cpuinfo);
Binh Vo6a46e382021-06-16 09:38:43 -04001305 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001306 }
1307}
1308
Conrad Meyerfe826372019-01-04 11:57:12 -08001309#elif defined(__FreeBSD__)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001310
Conrad Meyerfe826372019-01-04 11:57:12 -08001311#include <sys/param.h>
1312#include <sys/sysctl.h>
1313
1314/* Use physical core sysctl when available
1315 * see: man 4 smp, man 3 sysctl */
Binh Vo6a46e382021-06-16 09:38:43 -04001316int UTIL_countCores(int logical)
Conrad Meyerfe826372019-01-04 11:57:12 -08001317{
Binh Vo6a46e382021-06-16 09:38:43 -04001318 static int numCores = 0; /* freebsd sysctl is native int sized */
1319#if __FreeBSD_version >= 1300008
1320 static int perCore = 1;
1321#endif
1322 if (numCores != 0) return numCores;
Conrad Meyerfe826372019-01-04 11:57:12 -08001323
1324#if __FreeBSD_version >= 1300008
Binh Vo6a46e382021-06-16 09:38:43 -04001325 { size_t size = sizeof(numCores);
1326 int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0);
1327 if (ret == 0) {
1328 if (logical) {
1329 ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0);
1330 /* default to physical cores if logical cannot be read */
1331 if (ret == 0)
1332 numCores *= perCore;
1333 }
1334
1335 return numCores;
1336 }
Conrad Meyerfe826372019-01-04 11:57:12 -08001337 if (errno != ENOENT) {
Binh Vo6a46e382021-06-16 09:38:43 -04001338 perror("zstd: can't get number of cpus");
Conrad Meyerfe826372019-01-04 11:57:12 -08001339 exit(1);
1340 }
1341 /* sysctl not present, fall through to older sysconf method */
1342 }
Binh Vo6a46e382021-06-16 09:38:43 -04001343#else
1344 /* suppress unused parameter warning */
1345 (void) logical;
Conrad Meyerfe826372019-01-04 11:57:12 -08001346#endif
1347
Binh Vo6a46e382021-06-16 09:38:43 -04001348 numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
1349 if (numCores == -1) {
Conrad Meyerfe826372019-01-04 11:57:12 -08001350 /* value not queryable, fall back on 1 */
Binh Vo6a46e382021-06-16 09:38:43 -04001351 numCores = 1;
Conrad Meyerfe826372019-01-04 11:57:12 -08001352 }
Binh Vo6a46e382021-06-16 09:38:43 -04001353 return numCores;
Conrad Meyerfe826372019-01-04 11:57:12 -08001354}
1355
Christoph Reiterd0dcaf52020-01-08 00:48:26 +01001356#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
Conrad Meyerfe826372019-01-04 11:57:12 -08001357
1358/* Use POSIX sysconf
1359 * see: man 3 sysconf */
Binh Vo6a46e382021-06-16 09:38:43 -04001360int UTIL_countCores(int logical)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001361{
Binh Vo6a46e382021-06-16 09:38:43 -04001362 static int numCores = 0;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001363
binhdvod7e17362021-11-29 14:11:39 -05001364 /* suppress unused parameter warning */
1365 (void)logical;
1366
Binh Vo6a46e382021-06-16 09:38:43 -04001367 if (numCores != 0) return numCores;
1368
1369 numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
1370 if (numCores == -1) {
Rohit Jain91b2fed2018-10-11 17:34:47 -07001371 /* value not queryable, fall back on 1 */
Binh Vo6a46e382021-06-16 09:38:43 -04001372 return numCores = 1;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001373 }
Binh Vo6a46e382021-06-16 09:38:43 -04001374 return numCores;
Rohit Jain91b2fed2018-10-11 17:34:47 -07001375}
1376
1377#else
1378
Binh Vo6a46e382021-06-16 09:38:43 -04001379int UTIL_countCores(int logical)
Rohit Jain91b2fed2018-10-11 17:34:47 -07001380{
1381 /* assume 1 */
1382 return 1;
1383}
1384
1385#endif
1386
Binh Vo6a46e382021-06-16 09:38:43 -04001387int UTIL_countPhysicalCores(void)
1388{
1389 return UTIL_countCores(0);
1390}
1391
1392int UTIL_countLogicalCores(void)
1393{
1394 return UTIL_countCores(1);
1395}
1396
Rohit Jainf881ee82018-10-11 12:52:19 -07001397#if defined (__cplusplus)
1398}
1399#endif