/src/zstd/programs/util.c
Line | Count | Source |
1 | | /* |
2 | | * Copyright (c) Meta Platforms, Inc. and affiliates. |
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 | | /*-**************************************** |
12 | | * Dependencies |
13 | | ******************************************/ |
14 | | #include "util.h" /* note : ensure that platform.h is included first ! */ |
15 | | #include <stdlib.h> /* malloc, realloc, free */ |
16 | | #include <stdio.h> /* fprintf */ |
17 | | #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC, nanosleep */ |
18 | | #include <errno.h> |
19 | | #include <assert.h> |
20 | | |
21 | | #if defined(__FreeBSD__) |
22 | | #include <sys/param.h> /* __FreeBSD_version */ |
23 | | #endif /* #ifdef __FreeBSD__ */ |
24 | | |
25 | | #if defined(_WIN32) |
26 | | # include <sys/utime.h> /* utime */ |
27 | | # include <io.h> /* _chmod */ |
28 | | # define ZSTD_USE_UTIMENSAT 0 |
29 | | #else |
30 | | # include <unistd.h> /* chown, stat */ |
31 | | # include <sys/stat.h> /* utimensat, st_mtime */ |
32 | | # if (PLATFORM_POSIX_VERSION >= 200809L && defined(st_mtime)) \ |
33 | | || (defined(__FreeBSD__) && __FreeBSD_version >= 1100056) |
34 | | # define ZSTD_USE_UTIMENSAT 1 |
35 | | # else |
36 | | # define ZSTD_USE_UTIMENSAT 0 |
37 | | # endif |
38 | | # if ZSTD_USE_UTIMENSAT |
39 | | # include <fcntl.h> /* AT_FDCWD */ |
40 | | # else |
41 | | # include <utime.h> /* utime */ |
42 | | # endif |
43 | | #endif |
44 | | |
45 | | #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__) |
46 | | #include <direct.h> /* needed for _mkdir in windows */ |
47 | | #endif |
48 | | |
49 | | #if defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */ |
50 | | # include <dirent.h> /* opendir, readdir */ |
51 | | # include <string.h> /* strerror, memcpy */ |
52 | | #endif /* #ifdef _WIN32 */ |
53 | | |
54 | | /*-**************************************** |
55 | | * Internal Macros |
56 | | ******************************************/ |
57 | | |
58 | | /* CONTROL is almost like an assert(), but is never disabled. |
59 | | * It's designed for failures that may happen rarely, |
60 | | * but we don't want to maintain a specific error code path for them, |
61 | | * such as a malloc() returning NULL for example. |
62 | | * Since it's always active, this macro can trigger side effects. |
63 | | */ |
64 | 0 | #define CONTROL(c) { \ |
65 | 0 | if (!(c)) { \ |
66 | 0 | UTIL_DISPLAYLEVEL(1, "Error : %s, %i : %s", \ |
67 | 0 | __FILE__, __LINE__, #c); \ |
68 | 0 | exit(1); \ |
69 | 0 | } } |
70 | | |
71 | | /* console log */ |
72 | 0 | #define UTIL_DISPLAY(...) fprintf(stderr, __VA_ARGS__) |
73 | 0 | #define UTIL_DISPLAYLEVEL(l, ...) { if (g_utilDisplayLevel>=l) { UTIL_DISPLAY(__VA_ARGS__); } } |
74 | | |
75 | | static int g_traceDepth = 0; |
76 | | int g_traceFileStat = 0; |
77 | | |
78 | | #define UTIL_TRACE_CALL(...) \ |
79 | 0 | { \ |
80 | 0 | if (g_traceFileStat) { \ |
81 | 0 | UTIL_DISPLAY("Trace:FileStat: %*s> ", g_traceDepth, ""); \ |
82 | 0 | UTIL_DISPLAY(__VA_ARGS__); \ |
83 | 0 | UTIL_DISPLAY("\n"); \ |
84 | 0 | ++g_traceDepth; \ |
85 | 0 | } \ |
86 | 0 | } |
87 | | |
88 | | #define UTIL_TRACE_RET(ret) \ |
89 | 0 | { \ |
90 | 0 | if (g_traceFileStat) { \ |
91 | 0 | --g_traceDepth; \ |
92 | 0 | UTIL_DISPLAY("Trace:FileStat: %*s< %d\n", g_traceDepth, "", (ret)); \ |
93 | 0 | } \ |
94 | 0 | } |
95 | | |
96 | | /* A modified version of realloc(). |
97 | | * If UTIL_realloc() fails the original block is freed. |
98 | | */ |
99 | | UTIL_STATIC void* UTIL_realloc(void *ptr, size_t size) |
100 | 0 | { |
101 | 0 | void *newptr = realloc(ptr, size); |
102 | 0 | if (newptr) return newptr; |
103 | 0 | free(ptr); |
104 | 0 | return NULL; |
105 | 0 | } |
106 | | |
107 | | #if defined(_MSC_VER) |
108 | | #define chmod _chmod |
109 | | #endif |
110 | | |
111 | | #ifndef ZSTD_HAVE_FCHMOD |
112 | | #if PLATFORM_POSIX_VERSION >= 199309L |
113 | | #define ZSTD_HAVE_FCHMOD |
114 | | #endif |
115 | | #endif |
116 | | |
117 | | #ifndef ZSTD_HAVE_FCHOWN |
118 | | #if PLATFORM_POSIX_VERSION >= 200809L |
119 | | #define ZSTD_HAVE_FCHOWN |
120 | | #endif |
121 | | #endif |
122 | | |
123 | | /*-**************************************** |
124 | | * Console log |
125 | | ******************************************/ |
126 | | int g_utilDisplayLevel; |
127 | | |
128 | | int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg, |
129 | 0 | const char* acceptableLetters, int hasStdinInput) { |
130 | 0 | int ch, result; |
131 | |
|
132 | 0 | if (hasStdinInput) { |
133 | 0 | UTIL_DISPLAY("stdin is an input - not proceeding.\n"); |
134 | 0 | return 1; |
135 | 0 | } |
136 | | |
137 | 0 | UTIL_DISPLAY("%s", prompt); |
138 | 0 | ch = getchar(); |
139 | 0 | result = 0; |
140 | 0 | if (strchr(acceptableLetters, ch) == NULL) { |
141 | 0 | UTIL_DISPLAY("%s \n", abortMsg); |
142 | 0 | result = 1; |
143 | 0 | } |
144 | | /* flush the rest */ |
145 | 0 | while ((ch!=EOF) && (ch!='\n')) |
146 | 0 | ch = getchar(); |
147 | 0 | return result; |
148 | 0 | } |
149 | | |
150 | | |
151 | | /*-************************************* |
152 | | * Constants |
153 | | ***************************************/ |
154 | 0 | #define KB * (1 << 10) |
155 | 0 | #define LIST_SIZE_INCREASE (8 KB) |
156 | 0 | #define MAX_FILE_OF_FILE_NAMES_SIZE (1<<20)*50 |
157 | | |
158 | | |
159 | | /*-************************************* |
160 | | * Functions |
161 | | ***************************************/ |
162 | | |
163 | | void UTIL_traceFileStat(void) |
164 | 0 | { |
165 | 0 | g_traceFileStat = 1; |
166 | 0 | } |
167 | | |
168 | | int UTIL_fstat(const int fd, const char* filename, stat_t* statbuf) |
169 | 0 | { |
170 | 0 | int ret; |
171 | 0 | UTIL_TRACE_CALL("UTIL_stat(%d, %s)", fd, filename); |
172 | | #if defined(_MSC_VER) |
173 | | if (fd >= 0) { |
174 | | ret = !_fstat64(fd, statbuf); |
175 | | } else { |
176 | | ret = !_stat64(filename, statbuf); |
177 | | } |
178 | | #elif defined(__MINGW32__) && defined (__MSVCRT__) |
179 | | if (fd >= 0) { |
180 | | ret = !_fstati64(fd, statbuf); |
181 | | } else { |
182 | | ret = !_stati64(filename, statbuf); |
183 | | } |
184 | | #else |
185 | 0 | if (fd >= 0) { |
186 | 0 | ret = !fstat(fd, statbuf); |
187 | 0 | } else { |
188 | 0 | ret = !stat(filename, statbuf); |
189 | 0 | } |
190 | 0 | #endif |
191 | 0 | UTIL_TRACE_RET(ret); |
192 | 0 | return ret; |
193 | 0 | } |
194 | | |
195 | | int UTIL_stat(const char* filename, stat_t* statbuf) |
196 | 0 | { |
197 | 0 | return UTIL_fstat(-1, filename, statbuf); |
198 | 0 | } |
199 | | |
200 | | int UTIL_isFdRegularFile(int fd) |
201 | 0 | { |
202 | 0 | stat_t statbuf; |
203 | 0 | int ret; |
204 | 0 | UTIL_TRACE_CALL("UTIL_isFdRegularFile(%d)", fd); |
205 | 0 | ret = fd >= 0 && UTIL_fstat(fd, "", &statbuf) && UTIL_isRegularFileStat(&statbuf); |
206 | 0 | UTIL_TRACE_RET(ret); |
207 | 0 | return ret; |
208 | 0 | } |
209 | | |
210 | | int UTIL_isRegularFile(const char* infilename) |
211 | 0 | { |
212 | 0 | stat_t statbuf; |
213 | 0 | int ret; |
214 | 0 | UTIL_TRACE_CALL("UTIL_isRegularFile(%s)", infilename); |
215 | 0 | ret = UTIL_stat(infilename, &statbuf) && UTIL_isRegularFileStat(&statbuf); |
216 | 0 | UTIL_TRACE_RET(ret); |
217 | 0 | return ret; |
218 | 0 | } |
219 | | |
220 | | int UTIL_isRegularFileStat(const stat_t* statbuf) |
221 | 0 | { |
222 | | #if defined(_MSC_VER) |
223 | | return (statbuf->st_mode & S_IFREG) != 0; |
224 | | #else |
225 | 0 | return S_ISREG(statbuf->st_mode) != 0; |
226 | 0 | #endif |
227 | 0 | } |
228 | | |
229 | | /* like chmod, but avoid changing permission of /dev/null */ |
230 | | int UTIL_chmod(char const* filename, const stat_t* statbuf, mode_t permissions) |
231 | 0 | { |
232 | 0 | return UTIL_fchmod(-1, filename, statbuf, permissions); |
233 | 0 | } |
234 | | |
235 | | int UTIL_fchmod(const int fd, char const* filename, const stat_t* statbuf, mode_t permissions) |
236 | 0 | { |
237 | 0 | stat_t localStatBuf; |
238 | 0 | UTIL_TRACE_CALL("UTIL_chmod(%s, %#4o)", filename, (unsigned)permissions); |
239 | 0 | if (statbuf == NULL) { |
240 | 0 | if (!UTIL_fstat(fd, filename, &localStatBuf)) { |
241 | 0 | UTIL_TRACE_RET(0); |
242 | 0 | return 0; |
243 | 0 | } |
244 | 0 | statbuf = &localStatBuf; |
245 | 0 | } |
246 | 0 | if (!UTIL_isRegularFileStat(statbuf)) { |
247 | 0 | UTIL_TRACE_RET(0); |
248 | 0 | return 0; /* pretend success, but don't change anything */ |
249 | 0 | } |
250 | 0 | #ifdef ZSTD_HAVE_FCHMOD |
251 | 0 | if (fd >= 0) { |
252 | 0 | int ret; |
253 | 0 | UTIL_TRACE_CALL("fchmod"); |
254 | 0 | ret = fchmod(fd, permissions); |
255 | 0 | UTIL_TRACE_RET(ret); |
256 | 0 | UTIL_TRACE_RET(ret); |
257 | 0 | return ret; |
258 | 0 | } else |
259 | 0 | #endif |
260 | 0 | { |
261 | 0 | int ret; |
262 | 0 | UTIL_TRACE_CALL("chmod"); |
263 | 0 | ret = chmod(filename, permissions); |
264 | 0 | UTIL_TRACE_RET(ret); |
265 | 0 | UTIL_TRACE_RET(ret); |
266 | 0 | return ret; |
267 | 0 | } |
268 | 0 | } |
269 | | |
270 | | /* set access and modification times */ |
271 | | int UTIL_utime(const char* filename, const stat_t *statbuf) |
272 | 0 | { |
273 | 0 | int ret; |
274 | 0 | UTIL_TRACE_CALL("UTIL_utime(%s)", filename); |
275 | | /* We check that st_mtime is a macro here in order to give us confidence |
276 | | * that struct stat has a struct timespec st_mtim member. We need this |
277 | | * check because there are some platforms that claim to be POSIX 2008 |
278 | | * compliant but which do not have st_mtim... */ |
279 | | /* FreeBSD has implemented POSIX 2008 for a long time but still only |
280 | | * advertises support for POSIX 2001. They have a version macro that |
281 | | * lets us safely gate them in. |
282 | | * See https://docs.freebsd.org/en/books/porters-handbook/versions/. |
283 | | */ |
284 | 0 | #if ZSTD_USE_UTIMENSAT |
285 | 0 | { |
286 | | /* (atime, mtime) */ |
287 | 0 | struct timespec timebuf[2] = { {0, UTIME_NOW} }; |
288 | 0 | timebuf[1] = statbuf->st_mtim; |
289 | 0 | ret = utimensat(AT_FDCWD, filename, timebuf, 0); |
290 | 0 | } |
291 | | #else |
292 | | { |
293 | | struct utimbuf timebuf; |
294 | | timebuf.actime = time(NULL); |
295 | | timebuf.modtime = statbuf->st_mtime; |
296 | | ret = utime(filename, &timebuf); |
297 | | } |
298 | | #endif |
299 | 0 | errno = 0; |
300 | 0 | UTIL_TRACE_RET(ret); |
301 | 0 | return ret; |
302 | 0 | } |
303 | | |
304 | | int UTIL_setFileStat(const char *filename, const stat_t *statbuf) |
305 | 0 | { |
306 | 0 | return UTIL_setFDStat(-1, filename, statbuf); |
307 | 0 | } |
308 | | |
309 | | int UTIL_setFDStat(const int fd, const char *filename, const stat_t *statbuf) |
310 | 0 | { |
311 | 0 | int res = 0; |
312 | 0 | stat_t curStatBuf; |
313 | 0 | UTIL_TRACE_CALL("UTIL_setFileStat(%d, %s)", fd, filename); |
314 | |
|
315 | 0 | if (!UTIL_fstat(fd, filename, &curStatBuf) || !UTIL_isRegularFileStat(&curStatBuf)) { |
316 | 0 | UTIL_TRACE_RET(-1); |
317 | 0 | return -1; |
318 | 0 | } |
319 | | |
320 | | /* Mimic gzip's behavior: |
321 | | * |
322 | | * "Change the group first, then the permissions, then the owner. |
323 | | * That way, the permissions will be correct on systems that allow |
324 | | * users to give away files, without introducing a security hole. |
325 | | * Security depends on permissions not containing the setuid or |
326 | | * setgid bits." */ |
327 | | |
328 | 0 | #if !defined(_WIN32) |
329 | 0 | #ifdef ZSTD_HAVE_FCHOWN |
330 | 0 | if (fd >= 0) { |
331 | 0 | res += fchown(fd, -1, statbuf->st_gid); /* Apply group ownership */ |
332 | 0 | } else |
333 | 0 | #endif |
334 | 0 | { |
335 | 0 | res += chown(filename, -1, statbuf->st_gid); /* Apply group ownership */ |
336 | 0 | } |
337 | 0 | #endif |
338 | |
|
339 | 0 | res += UTIL_fchmod(fd, filename, &curStatBuf, statbuf->st_mode & 0777); /* Copy file permissions */ |
340 | |
|
341 | 0 | #if !defined(_WIN32) |
342 | 0 | #ifdef ZSTD_HAVE_FCHOWN |
343 | 0 | if (fd >= 0) { |
344 | 0 | res += fchown(fd, statbuf->st_uid, -1); /* Apply user ownership */ |
345 | 0 | } else |
346 | 0 | #endif |
347 | 0 | { |
348 | 0 | res += chown(filename, statbuf->st_uid, -1); /* Apply user ownership */ |
349 | 0 | } |
350 | 0 | #endif |
351 | |
|
352 | 0 | errno = 0; |
353 | 0 | UTIL_TRACE_RET(-res); |
354 | 0 | return -res; /* number of errors is returned */ |
355 | 0 | } |
356 | | |
357 | | int UTIL_isDirectory(const char* infilename) |
358 | 0 | { |
359 | 0 | stat_t statbuf; |
360 | 0 | int ret; |
361 | 0 | UTIL_TRACE_CALL("UTIL_isDirectory(%s)", infilename); |
362 | 0 | ret = UTIL_stat(infilename, &statbuf) && UTIL_isDirectoryStat(&statbuf); |
363 | 0 | UTIL_TRACE_RET(ret); |
364 | 0 | return ret; |
365 | 0 | } |
366 | | |
367 | | int UTIL_isDirectoryStat(const stat_t* statbuf) |
368 | 0 | { |
369 | 0 | int ret; |
370 | 0 | UTIL_TRACE_CALL("UTIL_isDirectoryStat()"); |
371 | | #if defined(_MSC_VER) |
372 | | ret = (statbuf->st_mode & _S_IFDIR) != 0; |
373 | | #else |
374 | 0 | ret = S_ISDIR(statbuf->st_mode) != 0; |
375 | 0 | #endif |
376 | 0 | UTIL_TRACE_RET(ret); |
377 | 0 | return ret; |
378 | 0 | } |
379 | | |
380 | 0 | int UTIL_compareStr(const void *p1, const void *p2) { |
381 | 0 | return strcmp(* (char * const *) p1, * (char * const *) p2); |
382 | 0 | } |
383 | | |
384 | | int UTIL_isSameFile(const char* fName1, const char* fName2) |
385 | 0 | { |
386 | 0 | int ret; |
387 | 0 | assert(fName1 != NULL); assert(fName2 != NULL); |
388 | 0 | UTIL_TRACE_CALL("UTIL_isSameFile(%s, %s)", fName1, fName2); |
389 | | #if defined(_MSC_VER) || defined(_WIN32) |
390 | | /* note : Visual does not support file identification by inode. |
391 | | * inode does not work on Windows, even with a posix layer, like msys2. |
392 | | * The following work-around is limited to detecting exact name repetition only, |
393 | | * aka `filename` is considered different from `subdir/../filename` */ |
394 | | ret = !strcmp(fName1, fName2); |
395 | | #else |
396 | 0 | { stat_t file1Stat; |
397 | 0 | stat_t file2Stat; |
398 | 0 | ret = UTIL_stat(fName1, &file1Stat) |
399 | 0 | && UTIL_stat(fName2, &file2Stat) |
400 | 0 | && UTIL_isSameFileStat(fName1, fName2, &file1Stat, &file2Stat); |
401 | 0 | } |
402 | 0 | #endif |
403 | 0 | UTIL_TRACE_RET(ret); |
404 | 0 | return ret; |
405 | 0 | } |
406 | | |
407 | | int UTIL_isSameFileStat( |
408 | | const char* fName1, const char* fName2, |
409 | | const stat_t* file1Stat, const stat_t* file2Stat) |
410 | 0 | { |
411 | 0 | int ret; |
412 | 0 | assert(fName1 != NULL); assert(fName2 != NULL); |
413 | 0 | UTIL_TRACE_CALL("UTIL_isSameFileStat(%s, %s)", fName1, fName2); |
414 | | #if defined(_MSC_VER) || defined(_WIN32) |
415 | | /* note : Visual does not support file identification by inode. |
416 | | * inode does not work on Windows, even with a posix layer, like msys2. |
417 | | * The following work-around is limited to detecting exact name repetition only, |
418 | | * aka `filename` is considered different from `subdir/../filename` */ |
419 | | (void)file1Stat; |
420 | | (void)file2Stat; |
421 | | ret = !strcmp(fName1, fName2); |
422 | | #else |
423 | 0 | { |
424 | 0 | ret = (file1Stat->st_dev == file2Stat->st_dev) |
425 | 0 | && (file1Stat->st_ino == file2Stat->st_ino); |
426 | 0 | } |
427 | 0 | #endif |
428 | 0 | UTIL_TRACE_RET(ret); |
429 | 0 | return ret; |
430 | 0 | } |
431 | | |
432 | | /* UTIL_isFIFO : distinguish named pipes */ |
433 | | int UTIL_isFIFO(const char* infilename) |
434 | 0 | { |
435 | 0 | UTIL_TRACE_CALL("UTIL_isFIFO(%s)", infilename); |
436 | | /* macro guards, as defined in : https://linux.die.net/man/2/lstat */ |
437 | 0 | #if PLATFORM_POSIX_VERSION >= 200112L |
438 | 0 | { |
439 | 0 | stat_t statbuf; |
440 | 0 | if (UTIL_stat(infilename, &statbuf) && UTIL_isFIFOStat(&statbuf)) { |
441 | 0 | UTIL_TRACE_RET(1); |
442 | 0 | return 1; |
443 | 0 | } |
444 | 0 | } |
445 | 0 | #endif |
446 | 0 | (void)infilename; |
447 | 0 | UTIL_TRACE_RET(0); |
448 | 0 | return 0; |
449 | 0 | } |
450 | | |
451 | | /* UTIL_isFIFO : distinguish named pipes */ |
452 | | int UTIL_isFIFOStat(const stat_t* statbuf) |
453 | 0 | { |
454 | | /* macro guards, as defined in : https://linux.die.net/man/2/lstat */ |
455 | 0 | #if PLATFORM_POSIX_VERSION >= 200112L |
456 | 0 | if (S_ISFIFO(statbuf->st_mode)) return 1; |
457 | 0 | #endif |
458 | 0 | (void)statbuf; |
459 | 0 | return 0; |
460 | 0 | } |
461 | | |
462 | | /* process substitution */ |
463 | | int UTIL_isFileDescriptorPipe(const char* filename) |
464 | 0 | { |
465 | 0 | UTIL_TRACE_CALL("UTIL_isFileDescriptorPipe(%s)", filename); |
466 | | /* Check if the filename is a /dev/fd/ path which indicates a file descriptor */ |
467 | 0 | if (filename[0] == '/' && strncmp(filename, "/dev/fd/", 8) == 0) { |
468 | 0 | UTIL_TRACE_RET(1); |
469 | 0 | return 1; |
470 | 0 | } |
471 | | |
472 | | /* Check for alternative process substitution formats on different systems */ |
473 | 0 | if (filename[0] == '/' && strncmp(filename, "/proc/self/fd/", 14) == 0) { |
474 | 0 | UTIL_TRACE_RET(1); |
475 | 0 | return 1; |
476 | 0 | } |
477 | | |
478 | 0 | UTIL_TRACE_RET(0); |
479 | 0 | return 0; /* Not recognized as a file descriptor pipe */ |
480 | 0 | } |
481 | | |
482 | | /* UTIL_isBlockDevStat : distinguish named pipes */ |
483 | | int UTIL_isBlockDevStat(const stat_t* statbuf) |
484 | 0 | { |
485 | | /* macro guards, as defined in : https://linux.die.net/man/2/lstat */ |
486 | 0 | #if PLATFORM_POSIX_VERSION >= 200112L |
487 | 0 | if (S_ISBLK(statbuf->st_mode)) return 1; |
488 | 0 | #endif |
489 | 0 | (void)statbuf; |
490 | 0 | return 0; |
491 | 0 | } |
492 | | |
493 | | #if defined(_WIN32) |
494 | | /* Symbolic links and junctions are "name surrogate" reparse points. |
495 | | * Other reparse points (OneDrive placeholders, deduplicated files, ...) |
496 | | * are regular files and directories : they must not be treated as links. */ |
497 | | static int UTIL_isNameSurrogate(DWORD attributes, DWORD reparseTag) |
498 | | { |
499 | | return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) |
500 | | && IsReparseTagNameSurrogate(reparseTag); |
501 | | } |
502 | | #endif |
503 | | |
504 | | int UTIL_isLink(const char* infilename) |
505 | 0 | { |
506 | 0 | UTIL_TRACE_CALL("UTIL_isLink(%s)", infilename); |
507 | | /* macro guards, as defined in : https://linux.die.net/man/2/lstat */ |
508 | 0 | #if PLATFORM_POSIX_VERSION >= 200112L |
509 | 0 | { |
510 | 0 | stat_t statbuf; |
511 | 0 | int const r = lstat(infilename, &statbuf); |
512 | 0 | if (!r && S_ISLNK(statbuf.st_mode)) { |
513 | 0 | UTIL_TRACE_RET(1); |
514 | 0 | return 1; |
515 | 0 | } |
516 | 0 | } |
517 | | #elif defined(_WIN32) |
518 | | { |
519 | | DWORD const attributes = GetFileAttributesA(infilename); |
520 | | if ( attributes != INVALID_FILE_ATTRIBUTES |
521 | | && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) ) { |
522 | | /* GetFileAttributes() does not report the reparse tag, FindFirstFile() does */ |
523 | | WIN32_FIND_DATAA findData; |
524 | | HANDLE const hFind = FindFirstFileA(infilename, &findData); |
525 | | if (hFind != INVALID_HANDLE_VALUE) { |
526 | | int const isLink = UTIL_isNameSurrogate(findData.dwFileAttributes, findData.dwReserved0); |
527 | | FindClose(hFind); |
528 | | if (isLink) { |
529 | | UTIL_TRACE_RET(1); |
530 | | return 1; |
531 | | } |
532 | | } |
533 | | } |
534 | | } |
535 | | #endif |
536 | 0 | (void)infilename; |
537 | 0 | UTIL_TRACE_RET(0); |
538 | 0 | return 0; |
539 | 0 | } |
540 | | |
541 | | static int g_fakeStdinIsConsole = 0; |
542 | | static int g_fakeStderrIsConsole = 0; |
543 | | static int g_fakeStdoutIsConsole = 0; |
544 | | |
545 | | int UTIL_isConsole(FILE* file) |
546 | 0 | { |
547 | 0 | int ret; |
548 | 0 | UTIL_TRACE_CALL("UTIL_isConsole(%d)", fileno(file)); |
549 | 0 | if (file == stdin && g_fakeStdinIsConsole) |
550 | 0 | ret = 1; |
551 | 0 | else if (file == stderr && g_fakeStderrIsConsole) |
552 | 0 | ret = 1; |
553 | 0 | else if (file == stdout && g_fakeStdoutIsConsole) |
554 | 0 | ret = 1; |
555 | 0 | else |
556 | 0 | ret = IS_CONSOLE(file); |
557 | 0 | UTIL_TRACE_RET(ret); |
558 | 0 | return ret; |
559 | 0 | } |
560 | | |
561 | | void UTIL_fakeStdinIsConsole(void) |
562 | 0 | { |
563 | 0 | g_fakeStdinIsConsole = 1; |
564 | 0 | } |
565 | | void UTIL_fakeStdoutIsConsole(void) |
566 | 0 | { |
567 | 0 | g_fakeStdoutIsConsole = 1; |
568 | 0 | } |
569 | | void UTIL_fakeStderrIsConsole(void) |
570 | 0 | { |
571 | 0 | g_fakeStderrIsConsole = 1; |
572 | 0 | } |
573 | | |
574 | | U64 UTIL_getFileSize(const char* infilename) |
575 | 0 | { |
576 | 0 | stat_t statbuf; |
577 | 0 | UTIL_TRACE_CALL("UTIL_getFileSize(%s)", infilename); |
578 | 0 | if (!UTIL_stat(infilename, &statbuf)) { |
579 | 0 | UTIL_TRACE_RET(-1); |
580 | 0 | return UTIL_FILESIZE_UNKNOWN; |
581 | 0 | } |
582 | 0 | { |
583 | 0 | U64 const size = UTIL_getFileSizeStat(&statbuf); |
584 | 0 | UTIL_TRACE_RET((int)size); |
585 | 0 | return size; |
586 | 0 | } |
587 | 0 | } |
588 | | |
589 | | U64 UTIL_getFileSizeStat(const stat_t* statbuf) |
590 | 0 | { |
591 | 0 | if (!UTIL_isRegularFileStat(statbuf)) return UTIL_FILESIZE_UNKNOWN; |
592 | | #if defined(_MSC_VER) |
593 | | if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN; |
594 | | #elif defined(__MINGW32__) && defined (__MSVCRT__) |
595 | | if (!(statbuf->st_mode & S_IFREG)) return UTIL_FILESIZE_UNKNOWN; |
596 | | #else |
597 | 0 | if (!S_ISREG(statbuf->st_mode)) return UTIL_FILESIZE_UNKNOWN; |
598 | 0 | #endif |
599 | 0 | return (U64)statbuf->st_size; |
600 | 0 | } |
601 | | |
602 | | UTIL_HumanReadableSize_t UTIL_makeHumanReadableSize(U64 size) |
603 | 0 | { |
604 | 0 | UTIL_HumanReadableSize_t hrs; |
605 | |
|
606 | 0 | if (g_utilDisplayLevel > 3) { |
607 | | /* In verbose mode, do not scale sizes down, except in the case of |
608 | | * values that exceed the integral precision of a double. */ |
609 | 0 | if (size >= (1ull << 53)) { |
610 | 0 | hrs.value = (double)size / (1ull << 20); |
611 | 0 | hrs.suffix = " MiB"; |
612 | | /* At worst, a double representation of a maximal size will be |
613 | | * accurate to better than tens of kilobytes. */ |
614 | 0 | hrs.precision = 2; |
615 | 0 | } else { |
616 | 0 | hrs.value = (double)size; |
617 | 0 | hrs.suffix = " B"; |
618 | 0 | hrs.precision = 0; |
619 | 0 | } |
620 | 0 | } else { |
621 | | /* In regular mode, scale sizes down and use suffixes. */ |
622 | 0 | if (size >= (1ull << 60)) { |
623 | 0 | hrs.value = (double)size / (1ull << 60); |
624 | 0 | hrs.suffix = " EiB"; |
625 | 0 | } else if (size >= (1ull << 50)) { |
626 | 0 | hrs.value = (double)size / (1ull << 50); |
627 | 0 | hrs.suffix = " PiB"; |
628 | 0 | } else if (size >= (1ull << 40)) { |
629 | 0 | hrs.value = (double)size / (1ull << 40); |
630 | 0 | hrs.suffix = " TiB"; |
631 | 0 | } else if (size >= (1ull << 30)) { |
632 | 0 | hrs.value = (double)size / (1ull << 30); |
633 | 0 | hrs.suffix = " GiB"; |
634 | 0 | } else if (size >= (1ull << 20)) { |
635 | 0 | hrs.value = (double)size / (1ull << 20); |
636 | 0 | hrs.suffix = " MiB"; |
637 | 0 | } else if (size >= (1ull << 10)) { |
638 | 0 | hrs.value = (double)size / (1ull << 10); |
639 | 0 | hrs.suffix = " KiB"; |
640 | 0 | } else { |
641 | 0 | hrs.value = (double)size; |
642 | 0 | hrs.suffix = " B"; |
643 | 0 | } |
644 | |
|
645 | 0 | if (hrs.value >= 100 || (U64)hrs.value == size) { |
646 | 0 | hrs.precision = 0; |
647 | 0 | } else if (hrs.value >= 10) { |
648 | 0 | hrs.precision = 1; |
649 | 0 | } else if (hrs.value > 1) { |
650 | 0 | hrs.precision = 2; |
651 | 0 | } else { |
652 | 0 | hrs.precision = 3; |
653 | 0 | } |
654 | 0 | } |
655 | |
|
656 | 0 | return hrs; |
657 | 0 | } |
658 | | |
659 | | U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles) |
660 | 0 | { |
661 | 0 | U64 total = 0; |
662 | 0 | unsigned n; |
663 | 0 | UTIL_TRACE_CALL("UTIL_getTotalFileSize(%u)", nbFiles); |
664 | 0 | for (n=0; n<nbFiles; n++) { |
665 | 0 | U64 const size = UTIL_getFileSize(fileNamesTable[n]); |
666 | 0 | if (size == UTIL_FILESIZE_UNKNOWN) { |
667 | 0 | UTIL_TRACE_RET(-1); |
668 | 0 | return UTIL_FILESIZE_UNKNOWN; |
669 | 0 | } |
670 | 0 | total += size; |
671 | 0 | } |
672 | 0 | UTIL_TRACE_RET((int)total); |
673 | 0 | return total; |
674 | 0 | } |
675 | | |
676 | | |
677 | | /* Read the entire content of a file into a buffer with progressive resizing */ |
678 | | static char* UTIL_readFileContent(FILE* inFile, size_t* totalReadPtr) |
679 | 0 | { |
680 | 0 | size_t bufSize = 64 KB; /* Start with a reasonable buffer size */ |
681 | 0 | size_t totalRead = 0; |
682 | 0 | size_t bytesRead = 0; |
683 | 0 | char* buf = (char*)malloc(bufSize); |
684 | 0 | if (buf == NULL) return NULL; |
685 | | |
686 | | |
687 | | /* Read the file incrementally */ |
688 | 0 | while ((bytesRead = fread(buf + totalRead, 1, bufSize - totalRead - 1, inFile)) > 0) { |
689 | 0 | totalRead += bytesRead; |
690 | | |
691 | | /* If buffer is nearly full, expand it */ |
692 | 0 | if (bufSize - totalRead < 1 KB) { |
693 | 0 | if (bufSize >= MAX_FILE_OF_FILE_NAMES_SIZE) { |
694 | | /* Too large, abort */ |
695 | 0 | free(buf); |
696 | 0 | return NULL; |
697 | 0 | } |
698 | | |
699 | 0 | { size_t newBufSize = bufSize * 2; |
700 | 0 | if (newBufSize > MAX_FILE_OF_FILE_NAMES_SIZE) |
701 | 0 | newBufSize = MAX_FILE_OF_FILE_NAMES_SIZE; |
702 | |
|
703 | 0 | { char* newBuf = (char*)realloc(buf, newBufSize); |
704 | 0 | if (newBuf == NULL) { |
705 | 0 | free(buf); |
706 | 0 | return NULL; |
707 | 0 | } |
708 | | |
709 | 0 | buf = newBuf; |
710 | 0 | bufSize = newBufSize; |
711 | 0 | } } } |
712 | 0 | } |
713 | | |
714 | | /* Add null terminator to the end */ |
715 | 0 | buf[totalRead] = '\0'; |
716 | 0 | *totalReadPtr = totalRead; |
717 | |
|
718 | 0 | return buf; |
719 | 0 | } |
720 | | |
721 | | /* Process a buffer containing multiple lines and count the number of lines */ |
722 | | static size_t UTIL_processLines(char* buffer, size_t bufferSize) |
723 | 0 | { |
724 | 0 | size_t lineCount = 0; |
725 | 0 | size_t i = 0; |
726 | | |
727 | | /* Convert newlines to null terminators and count lines */ |
728 | 0 | while (i < bufferSize) { |
729 | 0 | if (buffer[i] == '\n') { |
730 | 0 | buffer[i] = '\0'; /* Replace newlines with null terminators */ |
731 | 0 | lineCount++; |
732 | 0 | } |
733 | 0 | i++; |
734 | 0 | } |
735 | | |
736 | | /* Count the last line if it doesn't end with a newline */ |
737 | 0 | if (bufferSize > 0 && (i == 0 || buffer[i-1] != '\0')) { |
738 | 0 | lineCount++; |
739 | 0 | } |
740 | |
|
741 | 0 | return lineCount; |
742 | 0 | } |
743 | | |
744 | | /* Create an array of pointers to the lines in a buffer */ |
745 | | static const char** UTIL_createLinePointers(char* buffer, size_t numLines, size_t bufferSize) |
746 | 0 | { |
747 | 0 | size_t lineIndex = 0; |
748 | 0 | size_t pos = 0; |
749 | 0 | void* const bufferPtrs = malloc(numLines * sizeof(const char**)); |
750 | 0 | const char** const linePointers = (const char**)bufferPtrs; |
751 | 0 | if (bufferPtrs == NULL) return NULL; |
752 | | |
753 | 0 | while (lineIndex < numLines && pos < bufferSize) { |
754 | 0 | size_t len = 0; |
755 | 0 | linePointers[lineIndex++] = buffer+pos; |
756 | | |
757 | | /* Find the next null terminator, being careful not to go past the buffer */ |
758 | 0 | while ((pos + len < bufferSize) && buffer[pos + len] != '\0') { |
759 | 0 | len++; |
760 | 0 | } |
761 | | |
762 | | /* Move past this string and its null terminator */ |
763 | 0 | pos += len; |
764 | 0 | if (pos < bufferSize) pos++; /* Skip the null terminator if we're not at buffer end */ |
765 | 0 | } |
766 | | |
767 | | /* Verify we processed the expected number of lines */ |
768 | 0 | if (lineIndex != numLines) { |
769 | | /* Something went wrong - we didn't find as many lines as expected */ |
770 | 0 | free(bufferPtrs); |
771 | 0 | return NULL; |
772 | 0 | } |
773 | | |
774 | 0 | return linePointers; |
775 | 0 | } |
776 | | |
777 | | FileNamesTable* |
778 | | UTIL_createFileNamesTable_fromFileList(const char* fileList) |
779 | 0 | { |
780 | 0 | stat_t statbuf; |
781 | 0 | char* buffer = NULL; |
782 | 0 | size_t numLines = 0; |
783 | 0 | size_t bufferSize = 0; |
784 | | |
785 | | /* Check if the input is a valid file */ |
786 | 0 | if (!UTIL_stat(fileList, &statbuf)) { |
787 | 0 | return NULL; |
788 | 0 | } |
789 | | |
790 | | /* Check if the input is a supported type */ |
791 | 0 | if (!UTIL_isRegularFileStat(&statbuf) && |
792 | 0 | !UTIL_isFIFOStat(&statbuf) && |
793 | 0 | !UTIL_isFileDescriptorPipe(fileList)) { |
794 | 0 | return NULL; |
795 | 0 | } |
796 | | |
797 | | /* Open the input file */ |
798 | 0 | { FILE* const inFile = fopen(fileList, "rb"); |
799 | 0 | if (inFile == NULL) return NULL; |
800 | | |
801 | | /* Read the file content */ |
802 | 0 | buffer = UTIL_readFileContent(inFile, &bufferSize); |
803 | 0 | fclose(inFile); |
804 | 0 | } |
805 | | |
806 | 0 | if (buffer == NULL) return NULL; |
807 | | |
808 | | /* Process lines */ |
809 | 0 | numLines = UTIL_processLines(buffer, bufferSize); |
810 | 0 | if (numLines == 0) { |
811 | 0 | free(buffer); |
812 | 0 | return NULL; |
813 | 0 | } |
814 | | |
815 | | /* Create line pointers */ |
816 | 0 | { const char** linePointers = UTIL_createLinePointers(buffer, numLines, bufferSize); |
817 | 0 | if (linePointers == NULL) { |
818 | 0 | free(buffer); |
819 | 0 | return NULL; |
820 | 0 | } |
821 | | |
822 | | /* Create the final table */ |
823 | 0 | return UTIL_assembleFileNamesTable(linePointers, numLines, buffer); |
824 | 0 | } |
825 | 0 | } |
826 | | |
827 | | |
828 | | static FileNamesTable* |
829 | | UTIL_assembleFileNamesTable2(const char** filenames, size_t tableSize, size_t tableCapacity, char* buf) |
830 | 0 | { |
831 | 0 | FileNamesTable* const table = (FileNamesTable*) malloc(sizeof(*table)); |
832 | 0 | CONTROL(table != NULL); |
833 | 0 | table->fileNames = filenames; |
834 | 0 | table->buf = buf; |
835 | 0 | table->tableSize = tableSize; |
836 | 0 | table->tableCapacity = tableCapacity; |
837 | 0 | return table; |
838 | 0 | } |
839 | | |
840 | | FileNamesTable* |
841 | | UTIL_assembleFileNamesTable(const char** filenames, size_t tableSize, char* buf) |
842 | 0 | { |
843 | 0 | return UTIL_assembleFileNamesTable2(filenames, tableSize, tableSize, buf); |
844 | 0 | } |
845 | | |
846 | | void UTIL_freeFileNamesTable(FileNamesTable* table) |
847 | 0 | { |
848 | 0 | if (table==NULL) return; |
849 | 0 | free((void*)table->fileNames); |
850 | 0 | free(table->buf); |
851 | 0 | free(table); |
852 | 0 | } |
853 | | |
854 | | FileNamesTable* UTIL_allocateFileNamesTable(size_t tableSize) |
855 | 0 | { |
856 | 0 | const char** const fnTable = (const char**)malloc(tableSize * sizeof(*fnTable)); |
857 | 0 | FileNamesTable* fnt; |
858 | 0 | if (fnTable==NULL) return NULL; |
859 | 0 | fnt = UTIL_assembleFileNamesTable(fnTable, tableSize, NULL); |
860 | 0 | fnt->tableSize = 0; /* the table is empty */ |
861 | 0 | return fnt; |
862 | 0 | } |
863 | | |
864 | 0 | int UTIL_searchFileNamesTable(FileNamesTable* table, char const* name) { |
865 | 0 | size_t i; |
866 | 0 | for(i=0 ;i < table->tableSize; i++) { |
867 | 0 | if(!strcmp(table->fileNames[i], name)) { |
868 | 0 | return (int)i; |
869 | 0 | } |
870 | 0 | } |
871 | 0 | return -1; |
872 | 0 | } |
873 | | |
874 | | void UTIL_refFilename(FileNamesTable* fnt, const char* filename) |
875 | 0 | { |
876 | 0 | assert(fnt->tableSize < fnt->tableCapacity); |
877 | 0 | fnt->fileNames[fnt->tableSize] = filename; |
878 | 0 | fnt->tableSize++; |
879 | 0 | } |
880 | | |
881 | | static size_t getTotalTableSize(FileNamesTable* table) |
882 | 0 | { |
883 | 0 | size_t fnb, totalSize = 0; |
884 | 0 | for(fnb = 0 ; fnb < table->tableSize && table->fileNames[fnb] ; ++fnb) { |
885 | 0 | totalSize += strlen(table->fileNames[fnb]) + 1; /* +1 to add '\0' at the end of each fileName */ |
886 | 0 | } |
887 | 0 | return totalSize; |
888 | 0 | } |
889 | | |
890 | | FileNamesTable* |
891 | | UTIL_mergeFileNamesTable(FileNamesTable* table1, FileNamesTable* table2) |
892 | 0 | { |
893 | 0 | unsigned newTableIdx = 0; |
894 | 0 | size_t pos = 0; |
895 | 0 | size_t newTotalTableSize; |
896 | 0 | char* buf; |
897 | |
|
898 | 0 | FileNamesTable* const newTable = UTIL_assembleFileNamesTable(NULL, 0, NULL); |
899 | 0 | CONTROL( newTable != NULL ); |
900 | |
|
901 | 0 | newTotalTableSize = getTotalTableSize(table1) + getTotalTableSize(table2); |
902 | |
|
903 | 0 | buf = (char*) calloc(newTotalTableSize, sizeof(*buf)); |
904 | 0 | CONTROL ( buf != NULL ); |
905 | |
|
906 | 0 | newTable->buf = buf; |
907 | 0 | newTable->tableSize = table1->tableSize + table2->tableSize; |
908 | 0 | newTable->fileNames = (const char **) calloc(newTable->tableSize, sizeof(*(newTable->fileNames))); |
909 | 0 | CONTROL ( newTable->fileNames != NULL ); |
910 | |
|
911 | 0 | { unsigned idx1; |
912 | 0 | for( idx1=0 ; (idx1 < table1->tableSize) && table1->fileNames[idx1] && (pos < newTotalTableSize); ++idx1, ++newTableIdx) { |
913 | 0 | size_t const curLen = strlen(table1->fileNames[idx1]); |
914 | 0 | memcpy(buf+pos, table1->fileNames[idx1], curLen); |
915 | 0 | assert(newTableIdx <= newTable->tableSize); |
916 | 0 | newTable->fileNames[newTableIdx] = buf+pos; |
917 | 0 | pos += curLen+1; |
918 | 0 | } } |
919 | |
|
920 | 0 | { unsigned idx2; |
921 | 0 | for( idx2=0 ; (idx2 < table2->tableSize) && table2->fileNames[idx2] && (pos < newTotalTableSize) ; ++idx2, ++newTableIdx) { |
922 | 0 | size_t const curLen = strlen(table2->fileNames[idx2]); |
923 | 0 | memcpy(buf+pos, table2->fileNames[idx2], curLen); |
924 | 0 | assert(newTableIdx < newTable->tableSize); |
925 | 0 | newTable->fileNames[newTableIdx] = buf+pos; |
926 | 0 | pos += curLen+1; |
927 | 0 | } } |
928 | 0 | assert(pos <= newTotalTableSize); |
929 | 0 | newTable->tableSize = newTableIdx; |
930 | |
|
931 | 0 | UTIL_freeFileNamesTable(table1); |
932 | 0 | UTIL_freeFileNamesTable(table2); |
933 | |
|
934 | 0 | return newTable; |
935 | 0 | } |
936 | | |
937 | | #ifdef _WIN32 |
938 | | static int UTIL_prepareFileList(const char* dirName, |
939 | | char** bufStart, size_t* pos, |
940 | | char** bufEnd, int followLinks) |
941 | | { |
942 | | char* path; |
943 | | size_t dirLength, pathLength; |
944 | | int nbFiles = 0; |
945 | | WIN32_FIND_DATAA cFile; |
946 | | HANDLE hFile; |
947 | | |
948 | | dirLength = strlen(dirName); |
949 | | path = (char*) malloc(dirLength + 3); |
950 | | if (!path) return 0; |
951 | | |
952 | | memcpy(path, dirName, dirLength); |
953 | | path[dirLength] = '\\'; |
954 | | path[dirLength+1] = '*'; |
955 | | path[dirLength+2] = 0; |
956 | | |
957 | | hFile=FindFirstFileA(path, &cFile); |
958 | | if (hFile == INVALID_HANDLE_VALUE) { |
959 | | UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName); |
960 | | free(path); |
961 | | return 0; |
962 | | } |
963 | | free(path); |
964 | | |
965 | | do { |
966 | | size_t const fnameLength = strlen(cFile.cFileName); |
967 | | path = (char*) malloc(dirLength + fnameLength + 2); |
968 | | if (!path) { FindClose(hFile); return 0; } |
969 | | memcpy(path, dirName, dirLength); |
970 | | path[dirLength] = '\\'; |
971 | | memcpy(path+dirLength+1, cFile.cFileName, fnameLength); |
972 | | pathLength = dirLength+1+fnameLength; |
973 | | path[pathLength] = 0; |
974 | | if (!followLinks && UTIL_isNameSurrogate(cFile.dwFileAttributes, cFile.dwReserved0)) { |
975 | | UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path); |
976 | | free(path); |
977 | | continue; |
978 | | } |
979 | | if (cFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { |
980 | | if ( strcmp (cFile.cFileName, "..") == 0 |
981 | | || strcmp (cFile.cFileName, ".") == 0 ) |
982 | | continue; |
983 | | /* Recursively call "UTIL_prepareFileList" with the new path. */ |
984 | | nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); |
985 | | if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; } |
986 | | } else if ( (cFile.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) |
987 | | || (cFile.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) |
988 | | || (cFile.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED) ) { |
989 | | if (*bufStart + *pos + pathLength >= *bufEnd) { |
990 | | ptrdiff_t const newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE; |
991 | | *bufStart = (char*)UTIL_realloc(*bufStart, newListSize); |
992 | | if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; } |
993 | | *bufEnd = *bufStart + newListSize; |
994 | | } |
995 | | if (*bufStart + *pos + pathLength < *bufEnd) { |
996 | | memcpy(*bufStart + *pos, path, pathLength+1 /* include final \0 */); |
997 | | *pos += pathLength + 1; |
998 | | nbFiles++; |
999 | | } } |
1000 | | free(path); |
1001 | | } while (FindNextFileA(hFile, &cFile)); |
1002 | | |
1003 | | FindClose(hFile); |
1004 | | return nbFiles; |
1005 | | } |
1006 | | |
1007 | | #elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */ |
1008 | | |
1009 | | static int UTIL_prepareFileList(const char *dirName, |
1010 | | char** bufStart, size_t* pos, |
1011 | | char** bufEnd, int followLinks) |
1012 | 0 | { |
1013 | 0 | DIR* dir; |
1014 | 0 | struct dirent * entry; |
1015 | 0 | size_t dirLength; |
1016 | 0 | int nbFiles = 0; |
1017 | |
|
1018 | 0 | if (!(dir = opendir(dirName))) { |
1019 | 0 | UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s': %s\n", dirName, strerror(errno)); |
1020 | 0 | return 0; |
1021 | 0 | } |
1022 | | |
1023 | 0 | dirLength = strlen(dirName); |
1024 | 0 | errno = 0; |
1025 | 0 | while ((entry = readdir(dir)) != NULL) { |
1026 | 0 | char* path; |
1027 | 0 | size_t fnameLength, pathLength; |
1028 | 0 | if (strcmp (entry->d_name, "..") == 0 || |
1029 | 0 | strcmp (entry->d_name, ".") == 0) continue; |
1030 | 0 | fnameLength = strlen(entry->d_name); |
1031 | 0 | path = (char*) malloc(dirLength + fnameLength + 2); |
1032 | 0 | if (!path) { closedir(dir); return 0; } |
1033 | 0 | memcpy(path, dirName, dirLength); |
1034 | |
|
1035 | 0 | path[dirLength] = '/'; |
1036 | 0 | memcpy(path+dirLength+1, entry->d_name, fnameLength); |
1037 | 0 | pathLength = dirLength+1+fnameLength; |
1038 | 0 | path[pathLength] = 0; |
1039 | |
|
1040 | 0 | if (!followLinks && UTIL_isLink(path)) { |
1041 | 0 | UTIL_DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring\n", path); |
1042 | 0 | free(path); |
1043 | 0 | continue; |
1044 | 0 | } |
1045 | | |
1046 | 0 | if (UTIL_isDirectory(path)) { |
1047 | 0 | nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd, followLinks); /* Recursively call "UTIL_prepareFileList" with the new path. */ |
1048 | 0 | if (*bufStart == NULL) { free(path); closedir(dir); return 0; } |
1049 | 0 | } else { |
1050 | 0 | if (*bufStart + *pos + pathLength >= *bufEnd) { |
1051 | 0 | ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE; |
1052 | 0 | assert(newListSize >= 0); |
1053 | 0 | *bufStart = (char*)UTIL_realloc(*bufStart, (size_t)newListSize); |
1054 | 0 | if (*bufStart != NULL) { |
1055 | 0 | *bufEnd = *bufStart + newListSize; |
1056 | 0 | } else { |
1057 | 0 | free(path); closedir(dir); return 0; |
1058 | 0 | } |
1059 | 0 | } |
1060 | 0 | if (*bufStart + *pos + pathLength < *bufEnd) { |
1061 | 0 | memcpy(*bufStart + *pos, path, pathLength + 1); /* with final \0 */ |
1062 | 0 | *pos += pathLength + 1; |
1063 | 0 | nbFiles++; |
1064 | 0 | } } |
1065 | 0 | free(path); |
1066 | 0 | errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */ |
1067 | 0 | } |
1068 | | |
1069 | 0 | if (errno != 0) { |
1070 | 0 | UTIL_DISPLAYLEVEL(1, "readdir(%s) error: %s \n", dirName, strerror(errno)); |
1071 | 0 | free(*bufStart); |
1072 | 0 | *bufStart = NULL; |
1073 | 0 | } |
1074 | 0 | closedir(dir); |
1075 | 0 | return nbFiles; |
1076 | 0 | } |
1077 | | |
1078 | | #else |
1079 | | |
1080 | | static int UTIL_prepareFileList(const char *dirName, |
1081 | | char** bufStart, size_t* pos, |
1082 | | char** bufEnd, int followLinks) |
1083 | | { |
1084 | | (void)bufStart; (void)bufEnd; (void)pos; (void)followLinks; |
1085 | | UTIL_DISPLAYLEVEL(1, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE) \n", dirName); |
1086 | | return 0; |
1087 | | } |
1088 | | |
1089 | | #endif /* #ifdef _WIN32 */ |
1090 | | |
1091 | | int UTIL_isCompressedFile(const char *inputName, const char *extensionList[]) |
1092 | 0 | { |
1093 | 0 | const char* ext = UTIL_getFileExtension(inputName); |
1094 | 0 | while(*extensionList!=NULL) |
1095 | 0 | { |
1096 | 0 | const int isCompressedExtension = strcmp(ext,*extensionList); |
1097 | 0 | if(isCompressedExtension==0) |
1098 | 0 | return 1; |
1099 | 0 | ++extensionList; |
1100 | 0 | } |
1101 | 0 | return 0; |
1102 | 0 | } |
1103 | | |
1104 | | /*Utility function to get file extension from file */ |
1105 | | const char* UTIL_getFileExtension(const char* infilename) |
1106 | 0 | { |
1107 | 0 | const char* extension = strrchr(infilename, '.'); |
1108 | 0 | if(!extension || extension==infilename) return ""; |
1109 | 0 | return extension; |
1110 | 0 | } |
1111 | | |
1112 | | static int pathnameHas2Dots(const char *pathname) |
1113 | 0 | { |
1114 | | /* We need to figure out whether any ".." present in the path is a whole |
1115 | | * path token, which is the case if it is bordered on both sides by either |
1116 | | * the beginning/end of the path or by a directory separator. |
1117 | | */ |
1118 | 0 | const char *needle = pathname; |
1119 | 0 | while (1) { |
1120 | 0 | needle = strstr(needle, ".."); |
1121 | |
|
1122 | 0 | if (needle == NULL) { |
1123 | 0 | return 0; |
1124 | 0 | } |
1125 | | |
1126 | 0 | if ((needle == pathname || needle[-1] == PATH_SEP) |
1127 | 0 | && (needle[2] == '\0' || needle[2] == PATH_SEP)) { |
1128 | 0 | return 1; |
1129 | 0 | } |
1130 | | |
1131 | | /* increment so we search for the next match */ |
1132 | 0 | needle++; |
1133 | 0 | }; |
1134 | 0 | return 0; |
1135 | 0 | } |
1136 | | |
1137 | | static int isFileNameValidForMirroredOutput(const char *filename) |
1138 | 0 | { |
1139 | 0 | return !pathnameHas2Dots(filename); |
1140 | 0 | } |
1141 | | |
1142 | | |
1143 | 0 | #define DIR_DEFAULT_MODE 0755 |
1144 | | static mode_t getDirMode(const char *dirName) |
1145 | 0 | { |
1146 | 0 | stat_t st; |
1147 | 0 | if (!UTIL_stat(dirName, &st)) { |
1148 | 0 | UTIL_DISPLAY("zstd: failed to get DIR stats %s: %s\n", dirName, strerror(errno)); |
1149 | 0 | return DIR_DEFAULT_MODE; |
1150 | 0 | } |
1151 | 0 | if (!UTIL_isDirectoryStat(&st)) { |
1152 | 0 | UTIL_DISPLAY("zstd: expected directory: %s\n", dirName); |
1153 | 0 | return DIR_DEFAULT_MODE; |
1154 | 0 | } |
1155 | 0 | return st.st_mode; |
1156 | 0 | } |
1157 | | |
1158 | | static int makeDir(const char *dir, mode_t mode) |
1159 | 0 | { |
1160 | | #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__) |
1161 | | int ret = _mkdir(dir); |
1162 | | (void) mode; |
1163 | | #else |
1164 | 0 | int ret = mkdir(dir, mode); |
1165 | 0 | #endif |
1166 | 0 | if (ret != 0) { |
1167 | 0 | if (errno == EEXIST) |
1168 | 0 | return 0; |
1169 | 0 | UTIL_DISPLAY("zstd: failed to create DIR %s: %s\n", dir, strerror(errno)); |
1170 | 0 | } |
1171 | 0 | return ret; |
1172 | 0 | } |
1173 | | |
1174 | | /* this function requires a mutable input string */ |
1175 | | static void convertPathnameToDirName(char *pathname) |
1176 | 0 | { |
1177 | 0 | size_t len = 0; |
1178 | 0 | char* pos = NULL; |
1179 | | /* get dir name from pathname similar to 'dirname()' */ |
1180 | 0 | assert(pathname != NULL); |
1181 | | |
1182 | | /* remove trailing '/' chars */ |
1183 | 0 | len = strlen(pathname); |
1184 | 0 | assert(len > 0); |
1185 | 0 | while (pathname[len] == PATH_SEP) { |
1186 | 0 | pathname[len] = '\0'; |
1187 | 0 | len--; |
1188 | 0 | } |
1189 | 0 | if (len == 0) return; |
1190 | | |
1191 | | /* if input is a single file, return '.' instead. i.e. |
1192 | | * "xyz/abc/file.txt" => "xyz/abc" |
1193 | | "./file.txt" => "." |
1194 | | "file.txt" => "." |
1195 | | */ |
1196 | 0 | pos = strrchr(pathname, PATH_SEP); |
1197 | 0 | if (pos == NULL) { |
1198 | 0 | pathname[0] = '.'; |
1199 | 0 | pathname[1] = '\0'; |
1200 | 0 | } else { |
1201 | 0 | *pos = '\0'; |
1202 | 0 | } |
1203 | 0 | } |
1204 | | |
1205 | | /* pathname must be valid */ |
1206 | | static const char* trimLeadingRootChar(const char *pathname) |
1207 | 0 | { |
1208 | 0 | assert(pathname != NULL); |
1209 | 0 | if (pathname[0] == PATH_SEP) |
1210 | 0 | return pathname + 1; |
1211 | 0 | return pathname; |
1212 | 0 | } |
1213 | | |
1214 | | /* pathname must be valid */ |
1215 | | static const char* trimLeadingCurrentDirConst(const char *pathname) |
1216 | 0 | { |
1217 | 0 | assert(pathname != NULL); |
1218 | 0 | if ((pathname[0] == '.') && (pathname[1] == PATH_SEP)) |
1219 | 0 | return pathname + 2; |
1220 | 0 | return pathname; |
1221 | 0 | } |
1222 | | |
1223 | | static char* |
1224 | | trimLeadingCurrentDir(char *pathname) |
1225 | 0 | { |
1226 | | /* 'union charunion' can do const-cast without compiler warning */ |
1227 | 0 | union charunion { |
1228 | 0 | char *chr; |
1229 | 0 | const char* cchr; |
1230 | 0 | } ptr; |
1231 | 0 | ptr.cchr = trimLeadingCurrentDirConst(pathname); |
1232 | 0 | return ptr.chr; |
1233 | 0 | } |
1234 | | |
1235 | | /* remove leading './' or '/' chars here */ |
1236 | | static const char * trimPath(const char *pathname) |
1237 | 0 | { |
1238 | 0 | return trimLeadingRootChar( |
1239 | 0 | trimLeadingCurrentDirConst(pathname)); |
1240 | 0 | } |
1241 | | |
1242 | | static char* mallocAndJoin2Dir(const char *dir1, const char *dir2) |
1243 | 0 | { |
1244 | 0 | assert(dir1 != NULL && dir2 != NULL); |
1245 | 0 | { const size_t dir1Size = strlen(dir1); |
1246 | 0 | const size_t dir2Size = strlen(dir2); |
1247 | 0 | char *outDirBuffer, *buffer; |
1248 | |
|
1249 | 0 | outDirBuffer = (char *) malloc(dir1Size + dir2Size + 2); |
1250 | 0 | CONTROL(outDirBuffer != NULL); |
1251 | |
|
1252 | 0 | memcpy(outDirBuffer, dir1, dir1Size); |
1253 | 0 | outDirBuffer[dir1Size] = '\0'; |
1254 | |
|
1255 | 0 | buffer = outDirBuffer + dir1Size; |
1256 | 0 | if (dir1Size > 0 && *(buffer - 1) != PATH_SEP) { |
1257 | 0 | *buffer = PATH_SEP; |
1258 | 0 | buffer++; |
1259 | 0 | } |
1260 | 0 | memcpy(buffer, dir2, dir2Size); |
1261 | 0 | buffer[dir2Size] = '\0'; |
1262 | |
|
1263 | 0 | return outDirBuffer; |
1264 | 0 | } |
1265 | 0 | } |
1266 | | |
1267 | | /* this function will return NULL if input srcFileName is not valid name for mirrored output path */ |
1268 | | char* UTIL_createMirroredDestDirName(const char* srcFileName, const char* outDirRootName) |
1269 | 0 | { |
1270 | 0 | char* pathname = NULL; |
1271 | 0 | if (!isFileNameValidForMirroredOutput(srcFileName)) |
1272 | 0 | return NULL; |
1273 | | |
1274 | 0 | pathname = mallocAndJoin2Dir(outDirRootName, trimPath(srcFileName)); |
1275 | |
|
1276 | 0 | convertPathnameToDirName(pathname); |
1277 | 0 | return pathname; |
1278 | 0 | } |
1279 | | |
1280 | | static int |
1281 | | mirrorSrcDir(char* srcDirName, const char* outDirName) |
1282 | 0 | { |
1283 | 0 | mode_t srcMode; |
1284 | 0 | int status = 0; |
1285 | 0 | char* newDir = mallocAndJoin2Dir(outDirName, trimPath(srcDirName)); |
1286 | 0 | if (!newDir) |
1287 | 0 | return -ENOMEM; |
1288 | | |
1289 | 0 | srcMode = getDirMode(srcDirName); |
1290 | 0 | status = makeDir(newDir, srcMode); |
1291 | 0 | free(newDir); |
1292 | 0 | return status; |
1293 | 0 | } |
1294 | | |
1295 | | static int |
1296 | | mirrorSrcDirRecursive(char* srcDirName, const char* outDirName) |
1297 | 0 | { |
1298 | 0 | int status = 0; |
1299 | 0 | char* pp = trimLeadingCurrentDir(srcDirName); |
1300 | 0 | char* sp = NULL; |
1301 | |
|
1302 | 0 | while ((sp = strchr(pp, PATH_SEP)) != NULL) { |
1303 | 0 | if (sp != pp) { |
1304 | 0 | *sp = '\0'; |
1305 | 0 | status = mirrorSrcDir(srcDirName, outDirName); |
1306 | 0 | if (status != 0) |
1307 | 0 | return status; |
1308 | 0 | *sp = PATH_SEP; |
1309 | 0 | } |
1310 | 0 | pp = sp + 1; |
1311 | 0 | } |
1312 | 0 | status = mirrorSrcDir(srcDirName, outDirName); |
1313 | 0 | return status; |
1314 | 0 | } |
1315 | | |
1316 | | static void |
1317 | | makeMirroredDestDirsWithSameSrcDirMode(char** srcDirNames, unsigned nbFile, const char* outDirName) |
1318 | 0 | { |
1319 | 0 | unsigned int i = 0; |
1320 | 0 | for (i = 0; i < nbFile; i++) |
1321 | 0 | mirrorSrcDirRecursive(srcDirNames[i], outDirName); |
1322 | 0 | } |
1323 | | |
1324 | | static int |
1325 | | firstIsParentOrSameDirOfSecond(const char* firstDir, const char* secondDir) |
1326 | 0 | { |
1327 | 0 | size_t firstDirLen = strlen(firstDir), |
1328 | 0 | secondDirLen = strlen(secondDir); |
1329 | 0 | return firstDirLen <= secondDirLen && |
1330 | 0 | (secondDir[firstDirLen] == PATH_SEP || secondDir[firstDirLen] == '\0') && |
1331 | 0 | 0 == strncmp(firstDir, secondDir, firstDirLen); |
1332 | 0 | } |
1333 | | |
1334 | 0 | static int compareDir(const void* pathname1, const void* pathname2) { |
1335 | | /* sort it after remove the leading '/' or './'*/ |
1336 | 0 | const char* s1 = trimPath(*(char * const *) pathname1); |
1337 | 0 | const char* s2 = trimPath(*(char * const *) pathname2); |
1338 | 0 | return strcmp(s1, s2); |
1339 | 0 | } |
1340 | | |
1341 | | static void |
1342 | | makeUniqueMirroredDestDirs(char** srcDirNames, unsigned nbFile, const char* outDirName) |
1343 | 0 | { |
1344 | 0 | unsigned int i = 0, uniqueDirNr = 0; |
1345 | 0 | char** uniqueDirNames = NULL; |
1346 | |
|
1347 | 0 | if (nbFile == 0) |
1348 | 0 | return; |
1349 | | |
1350 | 0 | uniqueDirNames = (char** ) malloc(nbFile * sizeof (char *)); |
1351 | 0 | CONTROL(uniqueDirNames != NULL); |
1352 | | |
1353 | | /* if dirs is "a/b/c" and "a/b/c/d", we only need call: |
1354 | | * we just need "a/b/c/d" */ |
1355 | 0 | qsort((void *)srcDirNames, nbFile, sizeof(char*), compareDir); |
1356 | |
|
1357 | 0 | uniqueDirNr = 1; |
1358 | 0 | uniqueDirNames[uniqueDirNr - 1] = srcDirNames[0]; |
1359 | 0 | for (i = 1; i < nbFile; i++) { |
1360 | 0 | char* prevDirName = srcDirNames[i - 1]; |
1361 | 0 | char* currDirName = srcDirNames[i]; |
1362 | | |
1363 | | /* note: we always compare trimmed path, i.e.: |
1364 | | * src dir of "./foo" and "/foo" will be both saved into: |
1365 | | * "outDirName/foo/" */ |
1366 | 0 | if (!firstIsParentOrSameDirOfSecond(trimPath(prevDirName), |
1367 | 0 | trimPath(currDirName))) |
1368 | 0 | uniqueDirNr++; |
1369 | | |
1370 | | /* we need to maintain original src dir name instead of trimmed |
1371 | | * dir, so we can retrieve the original src dir's mode_t */ |
1372 | 0 | uniqueDirNames[uniqueDirNr - 1] = currDirName; |
1373 | 0 | } |
1374 | |
|
1375 | 0 | makeMirroredDestDirsWithSameSrcDirMode(uniqueDirNames, uniqueDirNr, outDirName); |
1376 | |
|
1377 | 0 | free(uniqueDirNames); |
1378 | 0 | } |
1379 | | |
1380 | | static void |
1381 | | makeMirroredDestDirs(char** srcFileNames, unsigned nbFile, const char* outDirName) |
1382 | 0 | { |
1383 | 0 | unsigned int i = 0; |
1384 | 0 | for (i = 0; i < nbFile; ++i) |
1385 | 0 | convertPathnameToDirName(srcFileNames[i]); |
1386 | 0 | makeUniqueMirroredDestDirs(srcFileNames, nbFile, outDirName); |
1387 | 0 | } |
1388 | | |
1389 | | void UTIL_mirrorSourceFilesDirectories(const char** inFileNames, unsigned int nbFile, const char* outDirName) |
1390 | 0 | { |
1391 | 0 | unsigned int i = 0, validFilenamesNr = 0; |
1392 | 0 | char** srcFileNames = (char **) malloc(nbFile * sizeof (char *)); |
1393 | 0 | CONTROL(srcFileNames != NULL); |
1394 | | |
1395 | | /* check input filenames is valid */ |
1396 | 0 | for (i = 0; i < nbFile; ++i) { |
1397 | 0 | if (isFileNameValidForMirroredOutput(inFileNames[i])) { |
1398 | 0 | char* fname = STRDUP(inFileNames[i]); |
1399 | 0 | CONTROL(fname != NULL); |
1400 | 0 | srcFileNames[validFilenamesNr++] = fname; |
1401 | 0 | } |
1402 | 0 | } |
1403 | | |
1404 | 0 | if (validFilenamesNr > 0) { |
1405 | 0 | makeDir(outDirName, DIR_DEFAULT_MODE); |
1406 | 0 | makeMirroredDestDirs(srcFileNames, validFilenamesNr, outDirName); |
1407 | 0 | } |
1408 | |
|
1409 | 0 | for (i = 0; i < validFilenamesNr; i++) |
1410 | 0 | free(srcFileNames[i]); |
1411 | 0 | free(srcFileNames); |
1412 | 0 | } |
1413 | | |
1414 | | FileNamesTable* |
1415 | | UTIL_createExpandedFNT(const char* const* inputNames, size_t nbIfns, int followLinks) |
1416 | 0 | { |
1417 | 0 | unsigned nbFiles; |
1418 | 0 | char* buf = (char*)malloc(LIST_SIZE_INCREASE); |
1419 | 0 | char* bufend = buf + LIST_SIZE_INCREASE; |
1420 | |
|
1421 | 0 | if (!buf) return NULL; |
1422 | | |
1423 | 0 | { size_t ifnNb, pos; |
1424 | 0 | for (ifnNb=0, pos=0, nbFiles=0; ifnNb<nbIfns; ifnNb++) { |
1425 | 0 | if (!UTIL_isDirectory(inputNames[ifnNb])) { |
1426 | 0 | size_t const len = strlen(inputNames[ifnNb]); |
1427 | 0 | if (buf + pos + len >= bufend) { |
1428 | 0 | ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE; |
1429 | 0 | assert(newListSize >= 0); |
1430 | 0 | buf = (char*)UTIL_realloc(buf, (size_t)newListSize); |
1431 | 0 | if (!buf) return NULL; |
1432 | 0 | bufend = buf + newListSize; |
1433 | 0 | } |
1434 | 0 | if (buf + pos + len < bufend) { |
1435 | 0 | memcpy(buf+pos, inputNames[ifnNb], len+1); /* including final \0 */ |
1436 | 0 | pos += len + 1; |
1437 | 0 | nbFiles++; |
1438 | 0 | } |
1439 | 0 | } else { |
1440 | 0 | nbFiles += (unsigned)UTIL_prepareFileList(inputNames[ifnNb], &buf, &pos, &bufend, followLinks); |
1441 | 0 | if (buf == NULL) return NULL; |
1442 | 0 | } } } |
1443 | | |
1444 | | /* note : even if nbFiles==0, function returns a valid, though empty, FileNamesTable* object */ |
1445 | | |
1446 | 0 | { size_t ifnNb, pos; |
1447 | 0 | size_t const fntCapacity = nbFiles + 1; /* minimum 1, allows adding one reference, typically stdin */ |
1448 | 0 | const char** const fileNamesTable = (const char**)malloc(fntCapacity * sizeof(*fileNamesTable)); |
1449 | 0 | if (!fileNamesTable) { free(buf); return NULL; } |
1450 | | |
1451 | 0 | for (ifnNb = 0, pos = 0; ifnNb < nbFiles; ifnNb++) { |
1452 | 0 | fileNamesTable[ifnNb] = buf + pos; |
1453 | 0 | if (buf + pos > bufend) { free(buf); free((void*)fileNamesTable); return NULL; } |
1454 | 0 | pos += strlen(fileNamesTable[ifnNb]) + 1; |
1455 | 0 | } |
1456 | 0 | return UTIL_assembleFileNamesTable2(fileNamesTable, nbFiles, fntCapacity, buf); |
1457 | 0 | } |
1458 | 0 | } |
1459 | | |
1460 | | |
1461 | | void UTIL_expandFNT(FileNamesTable** fnt, int followLinks) |
1462 | 0 | { |
1463 | 0 | FileNamesTable* const newFNT = UTIL_createExpandedFNT((*fnt)->fileNames, (*fnt)->tableSize, followLinks); |
1464 | 0 | CONTROL(newFNT != NULL); |
1465 | 0 | UTIL_freeFileNamesTable(*fnt); |
1466 | 0 | *fnt = newFNT; |
1467 | 0 | } |
1468 | | |
1469 | | FileNamesTable* UTIL_createFNT_fromROTable(const char** filenames, size_t nbFilenames) |
1470 | 0 | { |
1471 | 0 | size_t const sizeof_FNTable = nbFilenames * sizeof(*filenames); |
1472 | 0 | const char** const newFNTable = (const char**)malloc(sizeof_FNTable); |
1473 | 0 | if (newFNTable==NULL) return NULL; |
1474 | 0 | memcpy((void*)newFNTable, filenames, sizeof_FNTable); /* void* : mitigate a Visual compiler bug or limitation */ |
1475 | 0 | return UTIL_assembleFileNamesTable(newFNTable, nbFilenames, NULL); |
1476 | 0 | } |
1477 | | |
1478 | | |
1479 | | /*-**************************************** |
1480 | | * count the number of cores |
1481 | | ******************************************/ |
1482 | | |
1483 | | #if defined(_WIN32) || defined(WIN32) |
1484 | | |
1485 | | #include <windows.h> |
1486 | | |
1487 | | typedef BOOL(WINAPI* LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); |
1488 | | |
1489 | | DWORD CountSetBits(ULONG_PTR bitMask) |
1490 | | { |
1491 | | DWORD LSHIFT = sizeof(ULONG_PTR)*8 - 1; |
1492 | | DWORD bitSetCount = 0; |
1493 | | ULONG_PTR bitTest = (ULONG_PTR)1 << LSHIFT; |
1494 | | DWORD i; |
1495 | | |
1496 | | for (i = 0; i <= LSHIFT; ++i) |
1497 | | { |
1498 | | bitSetCount += ((bitMask & bitTest)?1:0); |
1499 | | bitTest/=2; |
1500 | | } |
1501 | | |
1502 | | return bitSetCount; |
1503 | | } |
1504 | | |
1505 | | int UTIL_countCores(int logical) |
1506 | | { |
1507 | | static int numCores = 0; |
1508 | | if (numCores != 0) return numCores; |
1509 | | |
1510 | | { LPFN_GLPI glpi; |
1511 | | BOOL done = FALSE; |
1512 | | PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL; |
1513 | | PSYSTEM_LOGICAL_PROCESSOR_INFORMATION ptr = NULL; |
1514 | | DWORD returnLength = 0; |
1515 | | size_t byteOffset = 0; |
1516 | | |
1517 | | #if defined(_MSC_VER) |
1518 | | /* Visual Studio does not like the following cast */ |
1519 | | # pragma warning( disable : 4054 ) /* conversion from function ptr to data ptr */ |
1520 | | # pragma warning( disable : 4055 ) /* conversion from data ptr to function ptr */ |
1521 | | #endif |
1522 | | glpi = (LPFN_GLPI)(void*)GetProcAddress(GetModuleHandle(TEXT("kernel32")), |
1523 | | "GetLogicalProcessorInformation"); |
1524 | | |
1525 | | if (glpi == NULL) { |
1526 | | goto failed; |
1527 | | } |
1528 | | |
1529 | | while(!done) { |
1530 | | DWORD rc = glpi(buffer, &returnLength); |
1531 | | if (FALSE == rc) { |
1532 | | if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { |
1533 | | if (buffer) |
1534 | | free(buffer); |
1535 | | buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)malloc(returnLength); |
1536 | | |
1537 | | if (buffer == NULL) { |
1538 | | perror("zstd"); |
1539 | | exit(1); |
1540 | | } |
1541 | | } else { |
1542 | | /* some other error */ |
1543 | | goto failed; |
1544 | | } |
1545 | | } else { |
1546 | | done = TRUE; |
1547 | | } } |
1548 | | |
1549 | | ptr = buffer; |
1550 | | |
1551 | | while (byteOffset + sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) <= returnLength) { |
1552 | | |
1553 | | if (ptr->Relationship == RelationProcessorCore) { |
1554 | | if (logical) |
1555 | | numCores += CountSetBits(ptr->ProcessorMask); |
1556 | | else |
1557 | | numCores++; |
1558 | | } |
1559 | | |
1560 | | ptr++; |
1561 | | byteOffset += sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); |
1562 | | } |
1563 | | |
1564 | | free(buffer); |
1565 | | |
1566 | | return numCores; |
1567 | | } |
1568 | | |
1569 | | failed: |
1570 | | /* try to fall back on GetSystemInfo */ |
1571 | | { SYSTEM_INFO sysinfo; |
1572 | | GetSystemInfo(&sysinfo); |
1573 | | numCores = sysinfo.dwNumberOfProcessors; |
1574 | | if (numCores == 0) numCores = 1; /* just in case */ |
1575 | | } |
1576 | | return numCores; |
1577 | | } |
1578 | | |
1579 | | #elif defined(__APPLE__) |
1580 | | |
1581 | | #include <sys/sysctl.h> |
1582 | | |
1583 | | /* Use apple-provided syscall |
1584 | | * see: man 3 sysctl */ |
1585 | | int UTIL_countCores(int logical) |
1586 | | { |
1587 | | static S32 numCores = 0; /* apple specifies int32_t */ |
1588 | | if (numCores != 0) return numCores; |
1589 | | |
1590 | | { size_t size = sizeof(S32); |
1591 | | int const ret = sysctlbyname(logical ? "hw.logicalcpu" : "hw.physicalcpu", &numCores, &size, NULL, 0); |
1592 | | if (ret != 0) { |
1593 | | if (errno == ENOENT) { |
1594 | | /* entry not present, fall back on 1 */ |
1595 | | numCores = 1; |
1596 | | } else { |
1597 | | perror("zstd: can't get number of cpus"); |
1598 | | exit(1); |
1599 | | } |
1600 | | } |
1601 | | |
1602 | | return numCores; |
1603 | | } |
1604 | | } |
1605 | | |
1606 | | #elif defined(__linux__) |
1607 | | |
1608 | | /* parse /proc/cpuinfo |
1609 | | * siblings / cpu cores should give hyperthreading ratio |
1610 | | * otherwise fall back on sysconf */ |
1611 | | int UTIL_countCores(int logical) |
1612 | 0 | { |
1613 | 0 | static int numCores = 0; |
1614 | |
|
1615 | 0 | if (numCores != 0) return numCores; |
1616 | | |
1617 | 0 | numCores = (int)sysconf(_SC_NPROCESSORS_ONLN); |
1618 | 0 | if (numCores == -1) { |
1619 | | /* value not queryable, fall back on 1 */ |
1620 | 0 | return numCores = 1; |
1621 | 0 | } |
1622 | | |
1623 | | /* try to determine if there's hyperthreading */ |
1624 | 0 | { FILE* const cpuinfo = fopen("/proc/cpuinfo", "r"); |
1625 | 0 | #define BUF_SIZE 80 |
1626 | 0 | char buff[BUF_SIZE]; |
1627 | |
|
1628 | 0 | int siblings = 0; |
1629 | 0 | int cpu_cores = 0; |
1630 | 0 | int ratio = 1; |
1631 | |
|
1632 | 0 | if (cpuinfo == NULL) { |
1633 | | /* fall back on the sysconf value */ |
1634 | 0 | return numCores; |
1635 | 0 | } |
1636 | | |
1637 | | /* assume the cpu cores/siblings values will be constant across all |
1638 | | * present processors */ |
1639 | 0 | while (!feof(cpuinfo)) { |
1640 | 0 | if (fgets(buff, BUF_SIZE, cpuinfo) != NULL) { |
1641 | 0 | if (strncmp(buff, "siblings", 8) == 0) { |
1642 | 0 | const char* const sep = strchr(buff, ':'); |
1643 | 0 | if (sep == NULL || *sep == '\0') { |
1644 | | /* formatting was broken? */ |
1645 | 0 | goto failed; |
1646 | 0 | } |
1647 | | |
1648 | 0 | siblings = atoi(sep + 1); |
1649 | 0 | } |
1650 | 0 | if (strncmp(buff, "cpu cores", 9) == 0) { |
1651 | 0 | const char* const sep = strchr(buff, ':'); |
1652 | 0 | if (sep == NULL || *sep == '\0') { |
1653 | | /* formatting was broken? */ |
1654 | 0 | goto failed; |
1655 | 0 | } |
1656 | | |
1657 | 0 | cpu_cores = atoi(sep + 1); |
1658 | 0 | } |
1659 | 0 | } else if (ferror(cpuinfo)) { |
1660 | | /* fall back on the sysconf value */ |
1661 | 0 | goto failed; |
1662 | 0 | } } |
1663 | 0 | if (siblings && cpu_cores && siblings > cpu_cores) { |
1664 | 0 | ratio = siblings / cpu_cores; |
1665 | 0 | } |
1666 | |
|
1667 | 0 | if (ratio && numCores > ratio && !logical) { |
1668 | 0 | numCores = numCores / ratio; |
1669 | 0 | } |
1670 | |
|
1671 | 0 | failed: |
1672 | 0 | fclose(cpuinfo); |
1673 | 0 | return numCores; |
1674 | 0 | } |
1675 | 0 | } |
1676 | | |
1677 | | #elif defined(__FreeBSD__) |
1678 | | |
1679 | | #include <sys/sysctl.h> |
1680 | | |
1681 | | /* Use physical core sysctl when available |
1682 | | * see: man 4 smp, man 3 sysctl */ |
1683 | | int UTIL_countCores(int logical) |
1684 | | { |
1685 | | static int numCores = 0; /* freebsd sysctl is native int sized */ |
1686 | | #if __FreeBSD_version >= 1300008 |
1687 | | static int perCore = 1; |
1688 | | #endif |
1689 | | if (numCores != 0) return numCores; |
1690 | | |
1691 | | #if __FreeBSD_version >= 1300008 |
1692 | | { size_t size = sizeof(numCores); |
1693 | | int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0); |
1694 | | if (ret == 0) { |
1695 | | if (logical) { |
1696 | | ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0); |
1697 | | /* default to physical cores if logical cannot be read */ |
1698 | | if (ret == 0) |
1699 | | numCores *= perCore; |
1700 | | } |
1701 | | |
1702 | | return numCores; |
1703 | | } |
1704 | | if (errno != ENOENT) { |
1705 | | perror("zstd: can't get number of cpus"); |
1706 | | exit(1); |
1707 | | } |
1708 | | /* sysctl not present, fall through to older sysconf method */ |
1709 | | } |
1710 | | #else |
1711 | | /* suppress unused parameter warning */ |
1712 | | (void) logical; |
1713 | | #endif |
1714 | | |
1715 | | numCores = (int)sysconf(_SC_NPROCESSORS_ONLN); |
1716 | | if (numCores == -1) { |
1717 | | /* value not queryable, fall back on 1 */ |
1718 | | numCores = 1; |
1719 | | } |
1720 | | return numCores; |
1721 | | } |
1722 | | |
1723 | | #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__) |
1724 | | |
1725 | | /* Use POSIX sysconf |
1726 | | * see: man 3 sysconf */ |
1727 | | int UTIL_countCores(int logical) |
1728 | | { |
1729 | | static int numCores = 0; |
1730 | | |
1731 | | /* suppress unused parameter warning */ |
1732 | | (void)logical; |
1733 | | |
1734 | | if (numCores != 0) return numCores; |
1735 | | |
1736 | | numCores = (int)sysconf(_SC_NPROCESSORS_ONLN); |
1737 | | if (numCores == -1) { |
1738 | | /* value not queryable, fall back on 1 */ |
1739 | | return numCores = 1; |
1740 | | } |
1741 | | return numCores; |
1742 | | } |
1743 | | |
1744 | | #else |
1745 | | |
1746 | | int UTIL_countCores(int logical) |
1747 | | { |
1748 | | /* suppress unused parameter warning */ |
1749 | | (void)logical; |
1750 | | |
1751 | | /* assume 1 */ |
1752 | | return 1; |
1753 | | } |
1754 | | |
1755 | | #endif |
1756 | | |
1757 | | int UTIL_countPhysicalCores(void) |
1758 | 0 | { |
1759 | 0 | return UTIL_countCores(0); |
1760 | 0 | } |
1761 | | |
1762 | | int UTIL_countLogicalCores(void) |
1763 | 0 | { |
1764 | 0 | return UTIL_countCores(1); |
1765 | 0 | } |