Coverage Report

Created: 2026-12-01 06:39

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