Coverage Report

Created: 2024-09-08 06:27

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