xref: /f-stack/freebsd/contrib/zstd/programs/fileio.c (revision 22ce4aff)
1*22ce4affSfengbojiang /*
2*22ce4affSfengbojiang  * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
3*22ce4affSfengbojiang  * All rights reserved.
4*22ce4affSfengbojiang  *
5*22ce4affSfengbojiang  * This source code is licensed under both the BSD-style license (found in the
6*22ce4affSfengbojiang  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*22ce4affSfengbojiang  * in the COPYING file in the root directory of this source tree).
8*22ce4affSfengbojiang  * You may select, at your option, one of the above-listed licenses.
9*22ce4affSfengbojiang  */
10*22ce4affSfengbojiang 
11*22ce4affSfengbojiang 
12*22ce4affSfengbojiang /* *************************************
13*22ce4affSfengbojiang *  Compiler Options
14*22ce4affSfengbojiang ***************************************/
15*22ce4affSfengbojiang #ifdef _MSC_VER   /* Visual */
16*22ce4affSfengbojiang #  pragma warning(disable : 4127)  /* disable: C4127: conditional expression is constant */
17*22ce4affSfengbojiang #  pragma warning(disable : 4204)  /* non-constant aggregate initializer */
18*22ce4affSfengbojiang #endif
19*22ce4affSfengbojiang #if defined(__MINGW32__) && !defined(_POSIX_SOURCE)
20*22ce4affSfengbojiang #  define _POSIX_SOURCE 1          /* disable %llu warnings with MinGW on Windows */
21*22ce4affSfengbojiang #endif
22*22ce4affSfengbojiang 
23*22ce4affSfengbojiang /*-*************************************
24*22ce4affSfengbojiang *  Includes
25*22ce4affSfengbojiang ***************************************/
26*22ce4affSfengbojiang #include "platform.h"   /* Large Files support, SET_BINARY_MODE */
27*22ce4affSfengbojiang #include "util.h"       /* UTIL_getFileSize, UTIL_isRegularFile, UTIL_isSameFile */
28*22ce4affSfengbojiang #include <stdio.h>      /* fprintf, fopen, fread, _fileno, stdin, stdout */
29*22ce4affSfengbojiang #include <stdlib.h>     /* malloc, free */
30*22ce4affSfengbojiang #include <string.h>     /* strcmp, strlen */
31*22ce4affSfengbojiang #include <assert.h>
32*22ce4affSfengbojiang #include <errno.h>      /* errno */
33*22ce4affSfengbojiang #include <limits.h>     /* INT_MAX */
34*22ce4affSfengbojiang #include <signal.h>
35*22ce4affSfengbojiang #include "timefn.h"     /* UTIL_getTime, UTIL_clockSpanMicro */
36*22ce4affSfengbojiang 
37*22ce4affSfengbojiang #if defined (_MSC_VER)
38*22ce4affSfengbojiang #  include <sys/stat.h>
39*22ce4affSfengbojiang #  include <io.h>
40*22ce4affSfengbojiang #endif
41*22ce4affSfengbojiang 
42*22ce4affSfengbojiang #include "../lib/common/mem.h"     /* U32, U64 */
43*22ce4affSfengbojiang #include "fileio.h"
44*22ce4affSfengbojiang 
45*22ce4affSfengbojiang #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_magicNumber, ZSTD_frameHeaderSize_max */
46*22ce4affSfengbojiang #include "../lib/zstd.h"
47*22ce4affSfengbojiang #include "../lib/common/zstd_errors.h"  /* ZSTD_error_frameParameter_windowTooLarge */
48*22ce4affSfengbojiang #include "../lib/compress/zstd_compress_internal.h"
49*22ce4affSfengbojiang 
50*22ce4affSfengbojiang #if defined(ZSTD_GZCOMPRESS) || defined(ZSTD_GZDECOMPRESS)
51*22ce4affSfengbojiang #  include <zlib.h>
52*22ce4affSfengbojiang #  if !defined(z_const)
53*22ce4affSfengbojiang #    define z_const
54*22ce4affSfengbojiang #  endif
55*22ce4affSfengbojiang #endif
56*22ce4affSfengbojiang 
57*22ce4affSfengbojiang #if defined(ZSTD_LZMACOMPRESS) || defined(ZSTD_LZMADECOMPRESS)
58*22ce4affSfengbojiang #  include <lzma.h>
59*22ce4affSfengbojiang #endif
60*22ce4affSfengbojiang 
61*22ce4affSfengbojiang #define LZ4_MAGICNUMBER 0x184D2204
62*22ce4affSfengbojiang #if defined(ZSTD_LZ4COMPRESS) || defined(ZSTD_LZ4DECOMPRESS)
63*22ce4affSfengbojiang #  define LZ4F_ENABLE_OBSOLETE_ENUMS
64*22ce4affSfengbojiang #  include <lz4frame.h>
65*22ce4affSfengbojiang #  include <lz4.h>
66*22ce4affSfengbojiang #endif
67*22ce4affSfengbojiang 
68*22ce4affSfengbojiang 
69*22ce4affSfengbojiang /*-*************************************
70*22ce4affSfengbojiang *  Constants
71*22ce4affSfengbojiang ***************************************/
72*22ce4affSfengbojiang #define ADAPT_WINDOWLOG_DEFAULT 23   /* 8 MB */
73*22ce4affSfengbojiang #define DICTSIZE_MAX (32 MB)   /* protection against large input (attack scenario) */
74*22ce4affSfengbojiang 
75*22ce4affSfengbojiang #define FNSPACE 30
76*22ce4affSfengbojiang 
77*22ce4affSfengbojiang /*-*************************************
78*22ce4affSfengbojiang *  Macros
79*22ce4affSfengbojiang ***************************************/
80*22ce4affSfengbojiang 
81*22ce4affSfengbojiang struct FIO_display_prefs_s {
82*22ce4affSfengbojiang     int displayLevel;   /* 0 : no display;  1: errors;  2: + result + interaction + warnings;  3: + progression;  4: + information */
83*22ce4affSfengbojiang     U32 noProgress;
84*22ce4affSfengbojiang };
85*22ce4affSfengbojiang 
86*22ce4affSfengbojiang static FIO_display_prefs_t g_display_prefs = {2, 0};
87*22ce4affSfengbojiang 
88*22ce4affSfengbojiang #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
89*22ce4affSfengbojiang #define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
90*22ce4affSfengbojiang #define DISPLAYLEVEL(l, ...) { if (g_display_prefs.displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
91*22ce4affSfengbojiang 
92*22ce4affSfengbojiang static const U64 g_refreshRate = SEC_TO_MICRO / 6;
93*22ce4affSfengbojiang static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
94*22ce4affSfengbojiang 
95*22ce4affSfengbojiang #define READY_FOR_UPDATE() (!g_display_prefs.noProgress && UTIL_clockSpanMicro(g_displayClock) > g_refreshRate)
96*22ce4affSfengbojiang #define DELAY_NEXT_UPDATE() { g_displayClock = UTIL_getTime(); }
97*22ce4affSfengbojiang #define DISPLAYUPDATE(l, ...) {                              \
98*22ce4affSfengbojiang         if (g_display_prefs.displayLevel>=l && !g_display_prefs.noProgress) { \
99*22ce4affSfengbojiang             if (READY_FOR_UPDATE() || (g_display_prefs.displayLevel>=4)) { \
100*22ce4affSfengbojiang                 DELAY_NEXT_UPDATE();                         \
101*22ce4affSfengbojiang                 DISPLAY(__VA_ARGS__);                        \
102*22ce4affSfengbojiang                 if (g_display_prefs.displayLevel>=4) fflush(stderr);       \
103*22ce4affSfengbojiang     }   }   }
104*22ce4affSfengbojiang 
105*22ce4affSfengbojiang #undef MIN  /* in case it would be already defined */
106*22ce4affSfengbojiang #define MIN(a,b)    ((a) < (b) ? (a) : (b))
107*22ce4affSfengbojiang 
108*22ce4affSfengbojiang 
109*22ce4affSfengbojiang #define EXM_THROW(error, ...)                                             \
110*22ce4affSfengbojiang {                                                                         \
111*22ce4affSfengbojiang     DISPLAYLEVEL(1, "zstd: ");                                            \
112*22ce4affSfengbojiang     DISPLAYLEVEL(5, "Error defined at %s, line %i : \n", __FILE__, __LINE__); \
113*22ce4affSfengbojiang     DISPLAYLEVEL(1, "error %i : ", error);                                \
114*22ce4affSfengbojiang     DISPLAYLEVEL(1, __VA_ARGS__);                                         \
115*22ce4affSfengbojiang     DISPLAYLEVEL(1, " \n");                                               \
116*22ce4affSfengbojiang     exit(error);                                                          \
117*22ce4affSfengbojiang }
118*22ce4affSfengbojiang 
119*22ce4affSfengbojiang #define CHECK_V(v, f)                                \
120*22ce4affSfengbojiang     v = f;                                           \
121*22ce4affSfengbojiang     if (ZSTD_isError(v)) {                           \
122*22ce4affSfengbojiang         DISPLAYLEVEL(5, "%s \n", #f);                \
123*22ce4affSfengbojiang         EXM_THROW(11, "%s", ZSTD_getErrorName(v));   \
124*22ce4affSfengbojiang     }
125*22ce4affSfengbojiang #define CHECK(f) { size_t err; CHECK_V(err, f); }
126*22ce4affSfengbojiang 
127*22ce4affSfengbojiang 
128*22ce4affSfengbojiang /*-************************************
129*22ce4affSfengbojiang *  Signal (Ctrl-C trapping)
130*22ce4affSfengbojiang **************************************/
131*22ce4affSfengbojiang static const char* g_artefact = NULL;
INThandler(int sig)132*22ce4affSfengbojiang static void INThandler(int sig)
133*22ce4affSfengbojiang {
134*22ce4affSfengbojiang     assert(sig==SIGINT); (void)sig;
135*22ce4affSfengbojiang #if !defined(_MSC_VER)
136*22ce4affSfengbojiang     signal(sig, SIG_IGN);  /* this invocation generates a buggy warning in Visual Studio */
137*22ce4affSfengbojiang #endif
138*22ce4affSfengbojiang     if (g_artefact) {
139*22ce4affSfengbojiang         assert(UTIL_isRegularFile(g_artefact));
140*22ce4affSfengbojiang         remove(g_artefact);
141*22ce4affSfengbojiang     }
142*22ce4affSfengbojiang     DISPLAY("\n");
143*22ce4affSfengbojiang     exit(2);
144*22ce4affSfengbojiang }
addHandler(char const * dstFileName)145*22ce4affSfengbojiang static void addHandler(char const* dstFileName)
146*22ce4affSfengbojiang {
147*22ce4affSfengbojiang     if (UTIL_isRegularFile(dstFileName)) {
148*22ce4affSfengbojiang         g_artefact = dstFileName;
149*22ce4affSfengbojiang         signal(SIGINT, INThandler);
150*22ce4affSfengbojiang     } else {
151*22ce4affSfengbojiang         g_artefact = NULL;
152*22ce4affSfengbojiang     }
153*22ce4affSfengbojiang }
154*22ce4affSfengbojiang /* Idempotent */
clearHandler(void)155*22ce4affSfengbojiang static void clearHandler(void)
156*22ce4affSfengbojiang {
157*22ce4affSfengbojiang     if (g_artefact) signal(SIGINT, SIG_DFL);
158*22ce4affSfengbojiang     g_artefact = NULL;
159*22ce4affSfengbojiang }
160*22ce4affSfengbojiang 
161*22ce4affSfengbojiang 
162*22ce4affSfengbojiang /*-*********************************************************
163*22ce4affSfengbojiang *  Termination signal trapping (Print debug stack trace)
164*22ce4affSfengbojiang ***********************************************************/
165*22ce4affSfengbojiang #if defined(__has_feature) && !defined(BACKTRACE_ENABLE) /* Clang compiler */
166*22ce4affSfengbojiang #  if (__has_feature(address_sanitizer))
167*22ce4affSfengbojiang #    define BACKTRACE_ENABLE 0
168*22ce4affSfengbojiang #  endif /* __has_feature(address_sanitizer) */
169*22ce4affSfengbojiang #elif defined(__SANITIZE_ADDRESS__) && !defined(BACKTRACE_ENABLE) /* GCC compiler */
170*22ce4affSfengbojiang #  define BACKTRACE_ENABLE 0
171*22ce4affSfengbojiang #endif
172*22ce4affSfengbojiang 
173*22ce4affSfengbojiang #if !defined(BACKTRACE_ENABLE)
174*22ce4affSfengbojiang /* automatic detector : backtrace enabled by default on linux+glibc and osx */
175*22ce4affSfengbojiang #  if (defined(__linux__) && (defined(__GLIBC__) && !defined(__UCLIBC__))) \
176*22ce4affSfengbojiang      || (defined(__APPLE__) && defined(__MACH__))
177*22ce4affSfengbojiang #    define BACKTRACE_ENABLE 1
178*22ce4affSfengbojiang #  else
179*22ce4affSfengbojiang #    define BACKTRACE_ENABLE 0
180*22ce4affSfengbojiang #  endif
181*22ce4affSfengbojiang #endif
182*22ce4affSfengbojiang 
183*22ce4affSfengbojiang /* note : after this point, BACKTRACE_ENABLE is necessarily defined */
184*22ce4affSfengbojiang 
185*22ce4affSfengbojiang 
186*22ce4affSfengbojiang #if BACKTRACE_ENABLE
187*22ce4affSfengbojiang 
188*22ce4affSfengbojiang #include <execinfo.h>   /* backtrace, backtrace_symbols */
189*22ce4affSfengbojiang 
190*22ce4affSfengbojiang #define MAX_STACK_FRAMES    50
191*22ce4affSfengbojiang 
ABRThandler(int sig)192*22ce4affSfengbojiang static void ABRThandler(int sig) {
193*22ce4affSfengbojiang     const char* name;
194*22ce4affSfengbojiang     void* addrlist[MAX_STACK_FRAMES];
195*22ce4affSfengbojiang     char** symbollist;
196*22ce4affSfengbojiang     int addrlen, i;
197*22ce4affSfengbojiang 
198*22ce4affSfengbojiang     switch (sig) {
199*22ce4affSfengbojiang         case SIGABRT: name = "SIGABRT"; break;
200*22ce4affSfengbojiang         case SIGFPE: name = "SIGFPE"; break;
201*22ce4affSfengbojiang         case SIGILL: name = "SIGILL"; break;
202*22ce4affSfengbojiang         case SIGINT: name = "SIGINT"; break;
203*22ce4affSfengbojiang         case SIGSEGV: name = "SIGSEGV"; break;
204*22ce4affSfengbojiang         default: name = "UNKNOWN";
205*22ce4affSfengbojiang     }
206*22ce4affSfengbojiang 
207*22ce4affSfengbojiang     DISPLAY("Caught %s signal, printing stack:\n", name);
208*22ce4affSfengbojiang     /* Retrieve current stack addresses. */
209*22ce4affSfengbojiang     addrlen = backtrace(addrlist, MAX_STACK_FRAMES);
210*22ce4affSfengbojiang     if (addrlen == 0) {
211*22ce4affSfengbojiang         DISPLAY("\n");
212*22ce4affSfengbojiang         return;
213*22ce4affSfengbojiang     }
214*22ce4affSfengbojiang     /* Create readable strings to each frame. */
215*22ce4affSfengbojiang     symbollist = backtrace_symbols(addrlist, addrlen);
216*22ce4affSfengbojiang     /* Print the stack trace, excluding calls handling the signal. */
217*22ce4affSfengbojiang     for (i = ZSTD_START_SYMBOLLIST_FRAME; i < addrlen; i++) {
218*22ce4affSfengbojiang         DISPLAY("%s\n", symbollist[i]);
219*22ce4affSfengbojiang     }
220*22ce4affSfengbojiang     free(symbollist);
221*22ce4affSfengbojiang     /* Reset and raise the signal so default handler runs. */
222*22ce4affSfengbojiang     signal(sig, SIG_DFL);
223*22ce4affSfengbojiang     raise(sig);
224*22ce4affSfengbojiang }
225*22ce4affSfengbojiang #endif
226*22ce4affSfengbojiang 
FIO_addAbortHandler()227*22ce4affSfengbojiang void FIO_addAbortHandler()
228*22ce4affSfengbojiang {
229*22ce4affSfengbojiang #if BACKTRACE_ENABLE
230*22ce4affSfengbojiang     signal(SIGABRT, ABRThandler);
231*22ce4affSfengbojiang     signal(SIGFPE, ABRThandler);
232*22ce4affSfengbojiang     signal(SIGILL, ABRThandler);
233*22ce4affSfengbojiang     signal(SIGSEGV, ABRThandler);
234*22ce4affSfengbojiang     signal(SIGBUS, ABRThandler);
235*22ce4affSfengbojiang #endif
236*22ce4affSfengbojiang }
237*22ce4affSfengbojiang 
238*22ce4affSfengbojiang 
239*22ce4affSfengbojiang /*-************************************************************
240*22ce4affSfengbojiang * Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
241*22ce4affSfengbojiang ***************************************************************/
242*22ce4affSfengbojiang #if defined(_MSC_VER) && _MSC_VER >= 1400
243*22ce4affSfengbojiang #   define LONG_SEEK _fseeki64
244*22ce4affSfengbojiang #   define LONG_TELL _ftelli64
245*22ce4affSfengbojiang #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
246*22ce4affSfengbojiang #  define LONG_SEEK fseeko
247*22ce4affSfengbojiang #  define LONG_TELL ftello
248*22ce4affSfengbojiang #elif defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)
249*22ce4affSfengbojiang #   define LONG_SEEK fseeko64
250*22ce4affSfengbojiang #   define LONG_TELL ftello64
251*22ce4affSfengbojiang #elif defined(_WIN32) && !defined(__DJGPP__)
252*22ce4affSfengbojiang #   include <windows.h>
LONG_SEEK(FILE * file,__int64 offset,int origin)253*22ce4affSfengbojiang     static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
254*22ce4affSfengbojiang         LARGE_INTEGER off;
255*22ce4affSfengbojiang         DWORD method;
256*22ce4affSfengbojiang         off.QuadPart = offset;
257*22ce4affSfengbojiang         if (origin == SEEK_END)
258*22ce4affSfengbojiang             method = FILE_END;
259*22ce4affSfengbojiang         else if (origin == SEEK_CUR)
260*22ce4affSfengbojiang             method = FILE_CURRENT;
261*22ce4affSfengbojiang         else
262*22ce4affSfengbojiang             method = FILE_BEGIN;
263*22ce4affSfengbojiang 
264*22ce4affSfengbojiang         if (SetFilePointerEx((HANDLE) _get_osfhandle(_fileno(file)), off, NULL, method))
265*22ce4affSfengbojiang             return 0;
266*22ce4affSfengbojiang         else
267*22ce4affSfengbojiang             return -1;
268*22ce4affSfengbojiang     }
LONG_TELL(FILE * file)269*22ce4affSfengbojiang     static __int64 LONG_TELL(FILE* file) {
270*22ce4affSfengbojiang         LARGE_INTEGER off, newOff;
271*22ce4affSfengbojiang         off.QuadPart = 0;
272*22ce4affSfengbojiang         newOff.QuadPart = 0;
273*22ce4affSfengbojiang         SetFilePointerEx((HANDLE) _get_osfhandle(_fileno(file)), off, &newOff, FILE_CURRENT);
274*22ce4affSfengbojiang         return newOff.QuadPart;
275*22ce4affSfengbojiang     }
276*22ce4affSfengbojiang #else
277*22ce4affSfengbojiang #   define LONG_SEEK fseek
278*22ce4affSfengbojiang #   define LONG_TELL ftell
279*22ce4affSfengbojiang #endif
280*22ce4affSfengbojiang 
281*22ce4affSfengbojiang 
282*22ce4affSfengbojiang /*-*************************************
283*22ce4affSfengbojiang *  Parameters: FIO_prefs_t
284*22ce4affSfengbojiang ***************************************/
285*22ce4affSfengbojiang 
286*22ce4affSfengbojiang /* typedef'd to FIO_prefs_t within fileio.h */
287*22ce4affSfengbojiang struct FIO_prefs_s {
288*22ce4affSfengbojiang 
289*22ce4affSfengbojiang     /* Algorithm preferences */
290*22ce4affSfengbojiang     FIO_compressionType_t compressionType;
291*22ce4affSfengbojiang     U32 sparseFileSupport;   /* 0: no sparse allowed; 1: auto (file yes, stdout no); 2: force sparse */
292*22ce4affSfengbojiang     int dictIDFlag;
293*22ce4affSfengbojiang     int checksumFlag;
294*22ce4affSfengbojiang     int blockSize;
295*22ce4affSfengbojiang     int overlapLog;
296*22ce4affSfengbojiang     U32 adaptiveMode;
297*22ce4affSfengbojiang     int rsyncable;
298*22ce4affSfengbojiang     int minAdaptLevel;
299*22ce4affSfengbojiang     int maxAdaptLevel;
300*22ce4affSfengbojiang     int ldmFlag;
301*22ce4affSfengbojiang     int ldmHashLog;
302*22ce4affSfengbojiang     int ldmMinMatch;
303*22ce4affSfengbojiang     int ldmBucketSizeLog;
304*22ce4affSfengbojiang     int ldmHashRateLog;
305*22ce4affSfengbojiang     size_t streamSrcSize;
306*22ce4affSfengbojiang     size_t targetCBlockSize;
307*22ce4affSfengbojiang     int srcSizeHint;
308*22ce4affSfengbojiang     int testMode;
309*22ce4affSfengbojiang     ZSTD_literalCompressionMode_e literalCompressionMode;
310*22ce4affSfengbojiang 
311*22ce4affSfengbojiang     /* IO preferences */
312*22ce4affSfengbojiang     U32 removeSrcFile;
313*22ce4affSfengbojiang     U32 overwrite;
314*22ce4affSfengbojiang 
315*22ce4affSfengbojiang     /* Computation resources preferences */
316*22ce4affSfengbojiang     unsigned memLimit;
317*22ce4affSfengbojiang     int nbWorkers;
318*22ce4affSfengbojiang 
319*22ce4affSfengbojiang     int excludeCompressedFiles;
320*22ce4affSfengbojiang     int patchFromMode;
321*22ce4affSfengbojiang     int contentSize;
322*22ce4affSfengbojiang };
323*22ce4affSfengbojiang 
324*22ce4affSfengbojiang /*-*************************************
325*22ce4affSfengbojiang *  Parameters: FIO_ctx_t
326*22ce4affSfengbojiang ***************************************/
327*22ce4affSfengbojiang 
328*22ce4affSfengbojiang /* typedef'd to FIO_ctx_t within fileio.h */
329*22ce4affSfengbojiang struct FIO_ctx_s {
330*22ce4affSfengbojiang 
331*22ce4affSfengbojiang     /* file i/o info */
332*22ce4affSfengbojiang     int nbFilesTotal;
333*22ce4affSfengbojiang     int hasStdinInput;
334*22ce4affSfengbojiang     int hasStdoutOutput;
335*22ce4affSfengbojiang 
336*22ce4affSfengbojiang     /* file i/o state */
337*22ce4affSfengbojiang     int currFileIdx;
338*22ce4affSfengbojiang     int nbFilesProcessed;
339*22ce4affSfengbojiang     size_t totalBytesInput;
340*22ce4affSfengbojiang     size_t totalBytesOutput;
341*22ce4affSfengbojiang };
342*22ce4affSfengbojiang 
343*22ce4affSfengbojiang 
344*22ce4affSfengbojiang /*-*************************************
345*22ce4affSfengbojiang *  Parameters: Initialization
346*22ce4affSfengbojiang ***************************************/
347*22ce4affSfengbojiang 
348*22ce4affSfengbojiang #define FIO_OVERLAP_LOG_NOTSET 9999
349*22ce4affSfengbojiang #define FIO_LDM_PARAM_NOTSET 9999
350*22ce4affSfengbojiang 
351*22ce4affSfengbojiang 
FIO_createPreferences(void)352*22ce4affSfengbojiang FIO_prefs_t* FIO_createPreferences(void)
353*22ce4affSfengbojiang {
354*22ce4affSfengbojiang     FIO_prefs_t* const ret = (FIO_prefs_t*)malloc(sizeof(FIO_prefs_t));
355*22ce4affSfengbojiang     if (!ret) EXM_THROW(21, "Allocation error : not enough memory");
356*22ce4affSfengbojiang 
357*22ce4affSfengbojiang     ret->compressionType = FIO_zstdCompression;
358*22ce4affSfengbojiang     ret->overwrite = 0;
359*22ce4affSfengbojiang     ret->sparseFileSupport = ZSTD_SPARSE_DEFAULT;
360*22ce4affSfengbojiang     ret->dictIDFlag = 1;
361*22ce4affSfengbojiang     ret->checksumFlag = 1;
362*22ce4affSfengbojiang     ret->removeSrcFile = 0;
363*22ce4affSfengbojiang     ret->memLimit = 0;
364*22ce4affSfengbojiang     ret->nbWorkers = 1;
365*22ce4affSfengbojiang     ret->blockSize = 0;
366*22ce4affSfengbojiang     ret->overlapLog = FIO_OVERLAP_LOG_NOTSET;
367*22ce4affSfengbojiang     ret->adaptiveMode = 0;
368*22ce4affSfengbojiang     ret->rsyncable = 0;
369*22ce4affSfengbojiang     ret->minAdaptLevel = -50;   /* initializing this value requires a constant, so ZSTD_minCLevel() doesn't work */
370*22ce4affSfengbojiang     ret->maxAdaptLevel = 22;   /* initializing this value requires a constant, so ZSTD_maxCLevel() doesn't work */
371*22ce4affSfengbojiang     ret->ldmFlag = 0;
372*22ce4affSfengbojiang     ret->ldmHashLog = 0;
373*22ce4affSfengbojiang     ret->ldmMinMatch = 0;
374*22ce4affSfengbojiang     ret->ldmBucketSizeLog = FIO_LDM_PARAM_NOTSET;
375*22ce4affSfengbojiang     ret->ldmHashRateLog = FIO_LDM_PARAM_NOTSET;
376*22ce4affSfengbojiang     ret->streamSrcSize = 0;
377*22ce4affSfengbojiang     ret->targetCBlockSize = 0;
378*22ce4affSfengbojiang     ret->srcSizeHint = 0;
379*22ce4affSfengbojiang     ret->testMode = 0;
380*22ce4affSfengbojiang     ret->literalCompressionMode = ZSTD_lcm_auto;
381*22ce4affSfengbojiang     ret->excludeCompressedFiles = 0;
382*22ce4affSfengbojiang     return ret;
383*22ce4affSfengbojiang }
384*22ce4affSfengbojiang 
FIO_createContext(void)385*22ce4affSfengbojiang FIO_ctx_t* FIO_createContext(void)
386*22ce4affSfengbojiang {
387*22ce4affSfengbojiang     FIO_ctx_t* const ret = (FIO_ctx_t*)malloc(sizeof(FIO_ctx_t));
388*22ce4affSfengbojiang     if (!ret) EXM_THROW(21, "Allocation error : not enough memory");
389*22ce4affSfengbojiang 
390*22ce4affSfengbojiang     ret->currFileIdx = 0;
391*22ce4affSfengbojiang     ret->hasStdinInput = 0;
392*22ce4affSfengbojiang     ret->hasStdoutOutput = 0;
393*22ce4affSfengbojiang     ret->nbFilesTotal = 1;
394*22ce4affSfengbojiang     ret->nbFilesProcessed = 0;
395*22ce4affSfengbojiang     ret->totalBytesInput = 0;
396*22ce4affSfengbojiang     ret->totalBytesOutput = 0;
397*22ce4affSfengbojiang     return ret;
398*22ce4affSfengbojiang }
399*22ce4affSfengbojiang 
FIO_freePreferences(FIO_prefs_t * const prefs)400*22ce4affSfengbojiang void FIO_freePreferences(FIO_prefs_t* const prefs)
401*22ce4affSfengbojiang {
402*22ce4affSfengbojiang     free(prefs);
403*22ce4affSfengbojiang }
404*22ce4affSfengbojiang 
FIO_freeContext(FIO_ctx_t * const fCtx)405*22ce4affSfengbojiang void FIO_freeContext(FIO_ctx_t* const fCtx)
406*22ce4affSfengbojiang {
407*22ce4affSfengbojiang     free(fCtx);
408*22ce4affSfengbojiang }
409*22ce4affSfengbojiang 
410*22ce4affSfengbojiang 
411*22ce4affSfengbojiang /*-*************************************
412*22ce4affSfengbojiang *  Parameters: Display Options
413*22ce4affSfengbojiang ***************************************/
414*22ce4affSfengbojiang 
FIO_setNotificationLevel(int level)415*22ce4affSfengbojiang void FIO_setNotificationLevel(int level) { g_display_prefs.displayLevel=level; }
416*22ce4affSfengbojiang 
FIO_setNoProgress(unsigned noProgress)417*22ce4affSfengbojiang void FIO_setNoProgress(unsigned noProgress) { g_display_prefs.noProgress = noProgress; }
418*22ce4affSfengbojiang 
419*22ce4affSfengbojiang 
420*22ce4affSfengbojiang /*-*************************************
421*22ce4affSfengbojiang *  Parameters: Setters
422*22ce4affSfengbojiang ***************************************/
423*22ce4affSfengbojiang 
424*22ce4affSfengbojiang /* FIO_prefs_t functions */
425*22ce4affSfengbojiang 
FIO_setCompressionType(FIO_prefs_t * const prefs,FIO_compressionType_t compressionType)426*22ce4affSfengbojiang void FIO_setCompressionType(FIO_prefs_t* const prefs, FIO_compressionType_t compressionType) { prefs->compressionType = compressionType; }
427*22ce4affSfengbojiang 
FIO_overwriteMode(FIO_prefs_t * const prefs)428*22ce4affSfengbojiang void FIO_overwriteMode(FIO_prefs_t* const prefs) { prefs->overwrite = 1; }
429*22ce4affSfengbojiang 
FIO_setSparseWrite(FIO_prefs_t * const prefs,unsigned sparse)430*22ce4affSfengbojiang void FIO_setSparseWrite(FIO_prefs_t* const prefs, unsigned sparse) { prefs->sparseFileSupport = sparse; }
431*22ce4affSfengbojiang 
FIO_setDictIDFlag(FIO_prefs_t * const prefs,int dictIDFlag)432*22ce4affSfengbojiang void FIO_setDictIDFlag(FIO_prefs_t* const prefs, int dictIDFlag) { prefs->dictIDFlag = dictIDFlag; }
433*22ce4affSfengbojiang 
FIO_setChecksumFlag(FIO_prefs_t * const prefs,int checksumFlag)434*22ce4affSfengbojiang void FIO_setChecksumFlag(FIO_prefs_t* const prefs, int checksumFlag) { prefs->checksumFlag = checksumFlag; }
435*22ce4affSfengbojiang 
FIO_setRemoveSrcFile(FIO_prefs_t * const prefs,unsigned flag)436*22ce4affSfengbojiang void FIO_setRemoveSrcFile(FIO_prefs_t* const prefs, unsigned flag) { prefs->removeSrcFile = (flag>0); }
437*22ce4affSfengbojiang 
FIO_setMemLimit(FIO_prefs_t * const prefs,unsigned memLimit)438*22ce4affSfengbojiang void FIO_setMemLimit(FIO_prefs_t* const prefs, unsigned memLimit) { prefs->memLimit = memLimit; }
439*22ce4affSfengbojiang 
FIO_setNbWorkers(FIO_prefs_t * const prefs,int nbWorkers)440*22ce4affSfengbojiang void FIO_setNbWorkers(FIO_prefs_t* const prefs, int nbWorkers) {
441*22ce4affSfengbojiang #ifndef ZSTD_MULTITHREAD
442*22ce4affSfengbojiang     if (nbWorkers > 0) DISPLAYLEVEL(2, "Note : multi-threading is disabled \n");
443*22ce4affSfengbojiang #endif
444*22ce4affSfengbojiang     prefs->nbWorkers = nbWorkers;
445*22ce4affSfengbojiang }
446*22ce4affSfengbojiang 
FIO_setExcludeCompressedFile(FIO_prefs_t * const prefs,int excludeCompressedFiles)447*22ce4affSfengbojiang void FIO_setExcludeCompressedFile(FIO_prefs_t* const prefs, int excludeCompressedFiles) { prefs->excludeCompressedFiles = excludeCompressedFiles; }
448*22ce4affSfengbojiang 
FIO_setBlockSize(FIO_prefs_t * const prefs,int blockSize)449*22ce4affSfengbojiang void FIO_setBlockSize(FIO_prefs_t* const prefs, int blockSize) {
450*22ce4affSfengbojiang     if (blockSize && prefs->nbWorkers==0)
451*22ce4affSfengbojiang         DISPLAYLEVEL(2, "Setting block size is useless in single-thread mode \n");
452*22ce4affSfengbojiang     prefs->blockSize = blockSize;
453*22ce4affSfengbojiang }
454*22ce4affSfengbojiang 
FIO_setOverlapLog(FIO_prefs_t * const prefs,int overlapLog)455*22ce4affSfengbojiang void FIO_setOverlapLog(FIO_prefs_t* const prefs, int overlapLog){
456*22ce4affSfengbojiang     if (overlapLog && prefs->nbWorkers==0)
457*22ce4affSfengbojiang         DISPLAYLEVEL(2, "Setting overlapLog is useless in single-thread mode \n");
458*22ce4affSfengbojiang     prefs->overlapLog = overlapLog;
459*22ce4affSfengbojiang }
460*22ce4affSfengbojiang 
FIO_setAdaptiveMode(FIO_prefs_t * const prefs,unsigned adapt)461*22ce4affSfengbojiang void FIO_setAdaptiveMode(FIO_prefs_t* const prefs, unsigned adapt) {
462*22ce4affSfengbojiang     if ((adapt>0) && (prefs->nbWorkers==0))
463*22ce4affSfengbojiang         EXM_THROW(1, "Adaptive mode is not compatible with single thread mode \n");
464*22ce4affSfengbojiang     prefs->adaptiveMode = adapt;
465*22ce4affSfengbojiang }
466*22ce4affSfengbojiang 
FIO_setRsyncable(FIO_prefs_t * const prefs,int rsyncable)467*22ce4affSfengbojiang void FIO_setRsyncable(FIO_prefs_t* const prefs, int rsyncable) {
468*22ce4affSfengbojiang     if ((rsyncable>0) && (prefs->nbWorkers==0))
469*22ce4affSfengbojiang         EXM_THROW(1, "Rsyncable mode is not compatible with single thread mode \n");
470*22ce4affSfengbojiang     prefs->rsyncable = rsyncable;
471*22ce4affSfengbojiang }
472*22ce4affSfengbojiang 
FIO_setStreamSrcSize(FIO_prefs_t * const prefs,size_t streamSrcSize)473*22ce4affSfengbojiang void FIO_setStreamSrcSize(FIO_prefs_t* const prefs, size_t streamSrcSize) {
474*22ce4affSfengbojiang     prefs->streamSrcSize = streamSrcSize;
475*22ce4affSfengbojiang }
476*22ce4affSfengbojiang 
FIO_setTargetCBlockSize(FIO_prefs_t * const prefs,size_t targetCBlockSize)477*22ce4affSfengbojiang void FIO_setTargetCBlockSize(FIO_prefs_t* const prefs, size_t targetCBlockSize) {
478*22ce4affSfengbojiang     prefs->targetCBlockSize = targetCBlockSize;
479*22ce4affSfengbojiang }
480*22ce4affSfengbojiang 
FIO_setSrcSizeHint(FIO_prefs_t * const prefs,size_t srcSizeHint)481*22ce4affSfengbojiang void FIO_setSrcSizeHint(FIO_prefs_t* const prefs, size_t srcSizeHint) {
482*22ce4affSfengbojiang     prefs->srcSizeHint = (int)MIN((size_t)INT_MAX, srcSizeHint);
483*22ce4affSfengbojiang }
484*22ce4affSfengbojiang 
FIO_setTestMode(FIO_prefs_t * const prefs,int testMode)485*22ce4affSfengbojiang void FIO_setTestMode(FIO_prefs_t* const prefs, int testMode) {
486*22ce4affSfengbojiang     prefs->testMode = (testMode!=0);
487*22ce4affSfengbojiang }
488*22ce4affSfengbojiang 
FIO_setLiteralCompressionMode(FIO_prefs_t * const prefs,ZSTD_literalCompressionMode_e mode)489*22ce4affSfengbojiang void FIO_setLiteralCompressionMode(
490*22ce4affSfengbojiang         FIO_prefs_t* const prefs,
491*22ce4affSfengbojiang         ZSTD_literalCompressionMode_e mode) {
492*22ce4affSfengbojiang     prefs->literalCompressionMode = mode;
493*22ce4affSfengbojiang }
494*22ce4affSfengbojiang 
FIO_setAdaptMin(FIO_prefs_t * const prefs,int minCLevel)495*22ce4affSfengbojiang void FIO_setAdaptMin(FIO_prefs_t* const prefs, int minCLevel)
496*22ce4affSfengbojiang {
497*22ce4affSfengbojiang #ifndef ZSTD_NOCOMPRESS
498*22ce4affSfengbojiang     assert(minCLevel >= ZSTD_minCLevel());
499*22ce4affSfengbojiang #endif
500*22ce4affSfengbojiang     prefs->minAdaptLevel = minCLevel;
501*22ce4affSfengbojiang }
502*22ce4affSfengbojiang 
FIO_setAdaptMax(FIO_prefs_t * const prefs,int maxCLevel)503*22ce4affSfengbojiang void FIO_setAdaptMax(FIO_prefs_t* const prefs, int maxCLevel)
504*22ce4affSfengbojiang {
505*22ce4affSfengbojiang     prefs->maxAdaptLevel = maxCLevel;
506*22ce4affSfengbojiang }
507*22ce4affSfengbojiang 
FIO_setLdmFlag(FIO_prefs_t * const prefs,unsigned ldmFlag)508*22ce4affSfengbojiang void FIO_setLdmFlag(FIO_prefs_t* const prefs, unsigned ldmFlag) {
509*22ce4affSfengbojiang     prefs->ldmFlag = (ldmFlag>0);
510*22ce4affSfengbojiang }
511*22ce4affSfengbojiang 
FIO_setLdmHashLog(FIO_prefs_t * const prefs,int ldmHashLog)512*22ce4affSfengbojiang void FIO_setLdmHashLog(FIO_prefs_t* const prefs, int ldmHashLog) {
513*22ce4affSfengbojiang     prefs->ldmHashLog = ldmHashLog;
514*22ce4affSfengbojiang }
515*22ce4affSfengbojiang 
FIO_setLdmMinMatch(FIO_prefs_t * const prefs,int ldmMinMatch)516*22ce4affSfengbojiang void FIO_setLdmMinMatch(FIO_prefs_t* const prefs, int ldmMinMatch) {
517*22ce4affSfengbojiang     prefs->ldmMinMatch = ldmMinMatch;
518*22ce4affSfengbojiang }
519*22ce4affSfengbojiang 
FIO_setLdmBucketSizeLog(FIO_prefs_t * const prefs,int ldmBucketSizeLog)520*22ce4affSfengbojiang void FIO_setLdmBucketSizeLog(FIO_prefs_t* const prefs, int ldmBucketSizeLog) {
521*22ce4affSfengbojiang     prefs->ldmBucketSizeLog = ldmBucketSizeLog;
522*22ce4affSfengbojiang }
523*22ce4affSfengbojiang 
524*22ce4affSfengbojiang 
FIO_setLdmHashRateLog(FIO_prefs_t * const prefs,int ldmHashRateLog)525*22ce4affSfengbojiang void FIO_setLdmHashRateLog(FIO_prefs_t* const prefs, int ldmHashRateLog) {
526*22ce4affSfengbojiang     prefs->ldmHashRateLog = ldmHashRateLog;
527*22ce4affSfengbojiang }
528*22ce4affSfengbojiang 
FIO_setPatchFromMode(FIO_prefs_t * const prefs,int value)529*22ce4affSfengbojiang void FIO_setPatchFromMode(FIO_prefs_t* const prefs, int value)
530*22ce4affSfengbojiang {
531*22ce4affSfengbojiang     prefs->patchFromMode = value != 0;
532*22ce4affSfengbojiang }
533*22ce4affSfengbojiang 
FIO_setContentSize(FIO_prefs_t * const prefs,int value)534*22ce4affSfengbojiang void FIO_setContentSize(FIO_prefs_t* const prefs, int value)
535*22ce4affSfengbojiang {
536*22ce4affSfengbojiang     prefs->contentSize = value != 0;
537*22ce4affSfengbojiang }
538*22ce4affSfengbojiang 
539*22ce4affSfengbojiang /* FIO_ctx_t functions */
540*22ce4affSfengbojiang 
FIO_setHasStdoutOutput(FIO_ctx_t * const fCtx,int value)541*22ce4affSfengbojiang void FIO_setHasStdoutOutput(FIO_ctx_t* const fCtx, int value) {
542*22ce4affSfengbojiang     fCtx->hasStdoutOutput = value;
543*22ce4affSfengbojiang }
544*22ce4affSfengbojiang 
FIO_setNbFilesTotal(FIO_ctx_t * const fCtx,int value)545*22ce4affSfengbojiang void FIO_setNbFilesTotal(FIO_ctx_t* const fCtx, int value)
546*22ce4affSfengbojiang {
547*22ce4affSfengbojiang     fCtx->nbFilesTotal = value;
548*22ce4affSfengbojiang }
549*22ce4affSfengbojiang 
FIO_determineHasStdinInput(FIO_ctx_t * const fCtx,const FileNamesTable * const filenames)550*22ce4affSfengbojiang void FIO_determineHasStdinInput(FIO_ctx_t* const fCtx, const FileNamesTable* const filenames) {
551*22ce4affSfengbojiang     size_t i = 0;
552*22ce4affSfengbojiang     for ( ; i < filenames->tableSize; ++i) {
553*22ce4affSfengbojiang         if (!strcmp(stdinmark, filenames->fileNames[i])) {
554*22ce4affSfengbojiang             fCtx->hasStdinInput = 1;
555*22ce4affSfengbojiang             return;
556*22ce4affSfengbojiang         }
557*22ce4affSfengbojiang     }
558*22ce4affSfengbojiang }
559*22ce4affSfengbojiang 
560*22ce4affSfengbojiang /*-*************************************
561*22ce4affSfengbojiang *  Functions
562*22ce4affSfengbojiang ***************************************/
563*22ce4affSfengbojiang /** FIO_removeFile() :
564*22ce4affSfengbojiang  * @result : Unlink `fileName`, even if it's read-only */
FIO_removeFile(const char * path)565*22ce4affSfengbojiang static int FIO_removeFile(const char* path)
566*22ce4affSfengbojiang {
567*22ce4affSfengbojiang     stat_t statbuf;
568*22ce4affSfengbojiang     if (!UTIL_stat(path, &statbuf)) {
569*22ce4affSfengbojiang         DISPLAYLEVEL(2, "zstd: Failed to stat %s while trying to remove it\n", path);
570*22ce4affSfengbojiang         return 0;
571*22ce4affSfengbojiang     }
572*22ce4affSfengbojiang     if (!UTIL_isRegularFileStat(&statbuf)) {
573*22ce4affSfengbojiang         DISPLAYLEVEL(2, "zstd: Refusing to remove non-regular file %s\n", path);
574*22ce4affSfengbojiang         return 0;
575*22ce4affSfengbojiang     }
576*22ce4affSfengbojiang #if defined(_WIN32) || defined(WIN32)
577*22ce4affSfengbojiang     /* windows doesn't allow remove read-only files,
578*22ce4affSfengbojiang      * so try to make it writable first */
579*22ce4affSfengbojiang     if (!(statbuf.st_mode & _S_IWRITE)) {
580*22ce4affSfengbojiang         UTIL_chmod(path, &statbuf, _S_IWRITE);
581*22ce4affSfengbojiang     }
582*22ce4affSfengbojiang #endif
583*22ce4affSfengbojiang     return remove(path);
584*22ce4affSfengbojiang }
585*22ce4affSfengbojiang 
586*22ce4affSfengbojiang /** FIO_openSrcFile() :
587*22ce4affSfengbojiang  *  condition : `srcFileName` must be non-NULL.
588*22ce4affSfengbojiang  * @result : FILE* to `srcFileName`, or NULL if it fails */
FIO_openSrcFile(const char * srcFileName)589*22ce4affSfengbojiang static FILE* FIO_openSrcFile(const char* srcFileName)
590*22ce4affSfengbojiang {
591*22ce4affSfengbojiang     stat_t statbuf;
592*22ce4affSfengbojiang     assert(srcFileName != NULL);
593*22ce4affSfengbojiang     if (!strcmp (srcFileName, stdinmark)) {
594*22ce4affSfengbojiang         DISPLAYLEVEL(4,"Using stdin for input \n");
595*22ce4affSfengbojiang         SET_BINARY_MODE(stdin);
596*22ce4affSfengbojiang         return stdin;
597*22ce4affSfengbojiang     }
598*22ce4affSfengbojiang 
599*22ce4affSfengbojiang     if (!UTIL_stat(srcFileName, &statbuf)) {
600*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: can't stat %s : %s -- ignored \n",
601*22ce4affSfengbojiang                         srcFileName, strerror(errno));
602*22ce4affSfengbojiang         return NULL;
603*22ce4affSfengbojiang     }
604*22ce4affSfengbojiang 
605*22ce4affSfengbojiang     if (!UTIL_isRegularFileStat(&statbuf)
606*22ce4affSfengbojiang      && !UTIL_isFIFOStat(&statbuf)
607*22ce4affSfengbojiang     ) {
608*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s is not a regular file -- ignored \n",
609*22ce4affSfengbojiang                         srcFileName);
610*22ce4affSfengbojiang         return NULL;
611*22ce4affSfengbojiang     }
612*22ce4affSfengbojiang 
613*22ce4affSfengbojiang     {   FILE* const f = fopen(srcFileName, "rb");
614*22ce4affSfengbojiang         if (f == NULL)
615*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));
616*22ce4affSfengbojiang         return f;
617*22ce4affSfengbojiang     }
618*22ce4affSfengbojiang }
619*22ce4affSfengbojiang 
620*22ce4affSfengbojiang /** FIO_openDstFile() :
621*22ce4affSfengbojiang  *  condition : `dstFileName` must be non-NULL.
622*22ce4affSfengbojiang  * @result : FILE* to `dstFileName`, or NULL if it fails */
623*22ce4affSfengbojiang static FILE*
FIO_openDstFile(FIO_ctx_t * fCtx,FIO_prefs_t * const prefs,const char * srcFileName,const char * dstFileName)624*22ce4affSfengbojiang FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs,
625*22ce4affSfengbojiang                 const char* srcFileName, const char* dstFileName)
626*22ce4affSfengbojiang {
627*22ce4affSfengbojiang     if (prefs->testMode) return NULL;  /* do not open file in test mode */
628*22ce4affSfengbojiang 
629*22ce4affSfengbojiang     assert(dstFileName != NULL);
630*22ce4affSfengbojiang     if (!strcmp (dstFileName, stdoutmark)) {
631*22ce4affSfengbojiang         DISPLAYLEVEL(4,"Using stdout for output \n");
632*22ce4affSfengbojiang         SET_BINARY_MODE(stdout);
633*22ce4affSfengbojiang         if (prefs->sparseFileSupport == 1) {
634*22ce4affSfengbojiang             prefs->sparseFileSupport = 0;
635*22ce4affSfengbojiang             DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n");
636*22ce4affSfengbojiang         }
637*22ce4affSfengbojiang         return stdout;
638*22ce4affSfengbojiang     }
639*22ce4affSfengbojiang 
640*22ce4affSfengbojiang     /* ensure dst is not the same as src */
641*22ce4affSfengbojiang     if (srcFileName != NULL && UTIL_isSameFile(srcFileName, dstFileName)) {
642*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: Refusing to open an output file which will overwrite the input file \n");
643*22ce4affSfengbojiang         return NULL;
644*22ce4affSfengbojiang     }
645*22ce4affSfengbojiang 
646*22ce4affSfengbojiang     if (prefs->sparseFileSupport == 1) {
647*22ce4affSfengbojiang         prefs->sparseFileSupport = ZSTD_SPARSE_DEFAULT;
648*22ce4affSfengbojiang     }
649*22ce4affSfengbojiang 
650*22ce4affSfengbojiang     if (UTIL_isRegularFile(dstFileName)) {
651*22ce4affSfengbojiang         /* Check if destination file already exists */
652*22ce4affSfengbojiang         FILE* const fCheck = fopen( dstFileName, "rb" );
653*22ce4affSfengbojiang #if !defined(_WIN32)
654*22ce4affSfengbojiang         /* this test does not work on Windows :
655*22ce4affSfengbojiang          * `NUL` and `nul` are detected as regular files */
656*22ce4affSfengbojiang         if (!strcmp(dstFileName, nulmark)) {
657*22ce4affSfengbojiang             EXM_THROW(40, "%s is unexpectedly categorized as a regular file",
658*22ce4affSfengbojiang                         dstFileName);
659*22ce4affSfengbojiang         }
660*22ce4affSfengbojiang #endif
661*22ce4affSfengbojiang         if (fCheck != NULL) {  /* dst file exists, authorization prompt */
662*22ce4affSfengbojiang             fclose(fCheck);
663*22ce4affSfengbojiang             if (!prefs->overwrite) {
664*22ce4affSfengbojiang                 if (g_display_prefs.displayLevel <= 1) {
665*22ce4affSfengbojiang                     /* No interaction possible */
666*22ce4affSfengbojiang                     DISPLAY("zstd: %s already exists; not overwritten  \n",
667*22ce4affSfengbojiang                             dstFileName);
668*22ce4affSfengbojiang                     return NULL;
669*22ce4affSfengbojiang                 }
670*22ce4affSfengbojiang                 DISPLAY("zstd: %s already exists; ", dstFileName);
671*22ce4affSfengbojiang                 if (UTIL_requireUserConfirmation("overwrite (y/n) ? ", "Not overwritten  \n", "yY", fCtx->hasStdinInput))
672*22ce4affSfengbojiang                     return NULL;
673*22ce4affSfengbojiang             }
674*22ce4affSfengbojiang             /* need to unlink */
675*22ce4affSfengbojiang             FIO_removeFile(dstFileName);
676*22ce4affSfengbojiang     }   }
677*22ce4affSfengbojiang 
678*22ce4affSfengbojiang     {   FILE* const f = fopen( dstFileName, "wb" );
679*22ce4affSfengbojiang         if (f == NULL) {
680*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno));
681*22ce4affSfengbojiang         } else if (srcFileName != NULL
682*22ce4affSfengbojiang                && strcmp (srcFileName, stdinmark)
683*22ce4affSfengbojiang                && strcmp(dstFileName, nulmark) ) {
684*22ce4affSfengbojiang             /* reduce rights on newly created dst file while compression is ongoing */
685*22ce4affSfengbojiang             UTIL_chmod(dstFileName, NULL, 00600);
686*22ce4affSfengbojiang         }
687*22ce4affSfengbojiang         return f;
688*22ce4affSfengbojiang     }
689*22ce4affSfengbojiang }
690*22ce4affSfengbojiang 
691*22ce4affSfengbojiang /*! FIO_createDictBuffer() :
692*22ce4affSfengbojiang  *  creates a buffer, pointed by `*bufferPtr`,
693*22ce4affSfengbojiang  *  loads `filename` content into it, up to DICTSIZE_MAX bytes.
694*22ce4affSfengbojiang  * @return : loaded size
695*22ce4affSfengbojiang  *  if fileName==NULL, returns 0 and a NULL pointer
696*22ce4affSfengbojiang  */
FIO_createDictBuffer(void ** bufferPtr,const char * fileName,FIO_prefs_t * const prefs)697*22ce4affSfengbojiang static size_t FIO_createDictBuffer(void** bufferPtr, const char* fileName, FIO_prefs_t* const prefs)
698*22ce4affSfengbojiang {
699*22ce4affSfengbojiang     FILE* fileHandle;
700*22ce4affSfengbojiang     U64 fileSize;
701*22ce4affSfengbojiang 
702*22ce4affSfengbojiang     assert(bufferPtr != NULL);
703*22ce4affSfengbojiang     *bufferPtr = NULL;
704*22ce4affSfengbojiang     if (fileName == NULL) return 0;
705*22ce4affSfengbojiang 
706*22ce4affSfengbojiang     DISPLAYLEVEL(4,"Loading %s as dictionary \n", fileName);
707*22ce4affSfengbojiang     fileHandle = fopen(fileName, "rb");
708*22ce4affSfengbojiang     if (fileHandle==NULL) EXM_THROW(31, "%s: %s", fileName, strerror(errno));
709*22ce4affSfengbojiang 
710*22ce4affSfengbojiang     fileSize = UTIL_getFileSize(fileName);
711*22ce4affSfengbojiang     {
712*22ce4affSfengbojiang         size_t const dictSizeMax = prefs->patchFromMode ? prefs->memLimit : DICTSIZE_MAX;
713*22ce4affSfengbojiang         if (fileSize >  dictSizeMax) {
714*22ce4affSfengbojiang             EXM_THROW(32, "Dictionary file %s is too large (> %u bytes)",
715*22ce4affSfengbojiang                             fileName,  (unsigned)dictSizeMax);   /* avoid extreme cases */
716*22ce4affSfengbojiang         }
717*22ce4affSfengbojiang     }
718*22ce4affSfengbojiang     *bufferPtr = malloc((size_t)fileSize);
719*22ce4affSfengbojiang     if (*bufferPtr==NULL) EXM_THROW(34, "%s", strerror(errno));
720*22ce4affSfengbojiang     {   size_t const readSize = fread(*bufferPtr, 1, (size_t)fileSize, fileHandle);
721*22ce4affSfengbojiang         if (readSize != fileSize)
722*22ce4affSfengbojiang             EXM_THROW(35, "Error reading dictionary file %s : %s",
723*22ce4affSfengbojiang                     fileName, strerror(errno));
724*22ce4affSfengbojiang     }
725*22ce4affSfengbojiang     fclose(fileHandle);
726*22ce4affSfengbojiang     return (size_t)fileSize;
727*22ce4affSfengbojiang }
728*22ce4affSfengbojiang 
729*22ce4affSfengbojiang 
730*22ce4affSfengbojiang 
731*22ce4affSfengbojiang /* FIO_checkFilenameCollisions() :
732*22ce4affSfengbojiang  * Checks for and warns if there are any files that would have the same output path
733*22ce4affSfengbojiang  */
FIO_checkFilenameCollisions(const char ** filenameTable,unsigned nbFiles)734*22ce4affSfengbojiang int FIO_checkFilenameCollisions(const char** filenameTable, unsigned nbFiles) {
735*22ce4affSfengbojiang     const char **filenameTableSorted, *prevElem, *filename;
736*22ce4affSfengbojiang     unsigned u;
737*22ce4affSfengbojiang 
738*22ce4affSfengbojiang     filenameTableSorted = (const char**) malloc(sizeof(char*) * nbFiles);
739*22ce4affSfengbojiang     if (!filenameTableSorted) {
740*22ce4affSfengbojiang         DISPLAY("Unable to malloc new str array, not checking for name collisions\n");
741*22ce4affSfengbojiang         return 1;
742*22ce4affSfengbojiang     }
743*22ce4affSfengbojiang 
744*22ce4affSfengbojiang     for (u = 0; u < nbFiles; ++u) {
745*22ce4affSfengbojiang         filename = strrchr(filenameTable[u], PATH_SEP);
746*22ce4affSfengbojiang         if (filename == NULL) {
747*22ce4affSfengbojiang             filenameTableSorted[u] = filenameTable[u];
748*22ce4affSfengbojiang         } else {
749*22ce4affSfengbojiang             filenameTableSorted[u] = filename+1;
750*22ce4affSfengbojiang         }
751*22ce4affSfengbojiang     }
752*22ce4affSfengbojiang 
753*22ce4affSfengbojiang     qsort((void*)filenameTableSorted, nbFiles, sizeof(char*), UTIL_compareStr);
754*22ce4affSfengbojiang     prevElem = filenameTableSorted[0];
755*22ce4affSfengbojiang     for (u = 1; u < nbFiles; ++u) {
756*22ce4affSfengbojiang         if (strcmp(prevElem, filenameTableSorted[u]) == 0) {
757*22ce4affSfengbojiang             DISPLAY("WARNING: Two files have same filename: %s\n", prevElem);
758*22ce4affSfengbojiang         }
759*22ce4affSfengbojiang         prevElem = filenameTableSorted[u];
760*22ce4affSfengbojiang     }
761*22ce4affSfengbojiang 
762*22ce4affSfengbojiang     free((void*)filenameTableSorted);
763*22ce4affSfengbojiang     return 0;
764*22ce4affSfengbojiang }
765*22ce4affSfengbojiang 
766*22ce4affSfengbojiang static const char*
extractFilename(const char * path,char separator)767*22ce4affSfengbojiang extractFilename(const char* path, char separator)
768*22ce4affSfengbojiang {
769*22ce4affSfengbojiang     const char* search = strrchr(path, separator);
770*22ce4affSfengbojiang     if (search == NULL) return path;
771*22ce4affSfengbojiang     return search+1;
772*22ce4affSfengbojiang }
773*22ce4affSfengbojiang 
774*22ce4affSfengbojiang /* FIO_createFilename_fromOutDir() :
775*22ce4affSfengbojiang  * Takes a source file name and specified output directory, and
776*22ce4affSfengbojiang  * allocates memory for and returns a pointer to final path.
777*22ce4affSfengbojiang  * This function never returns an error (it may abort() in case of pb)
778*22ce4affSfengbojiang  */
779*22ce4affSfengbojiang static char*
FIO_createFilename_fromOutDir(const char * path,const char * outDirName,const size_t suffixLen)780*22ce4affSfengbojiang FIO_createFilename_fromOutDir(const char* path, const char* outDirName, const size_t suffixLen)
781*22ce4affSfengbojiang {
782*22ce4affSfengbojiang     const char* filenameStart;
783*22ce4affSfengbojiang     char separator;
784*22ce4affSfengbojiang     char* result;
785*22ce4affSfengbojiang 
786*22ce4affSfengbojiang #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__) /* windows support */
787*22ce4affSfengbojiang     separator = '\\';
788*22ce4affSfengbojiang #else
789*22ce4affSfengbojiang     separator = '/';
790*22ce4affSfengbojiang #endif
791*22ce4affSfengbojiang 
792*22ce4affSfengbojiang     filenameStart = extractFilename(path, separator);
793*22ce4affSfengbojiang #if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__) /* windows support */
794*22ce4affSfengbojiang     filenameStart = extractFilename(filenameStart, '/');  /* sometimes, '/' separator is also used on Windows (mingw+msys2) */
795*22ce4affSfengbojiang #endif
796*22ce4affSfengbojiang 
797*22ce4affSfengbojiang     result = (char*) calloc(1, strlen(outDirName) + 1 + strlen(filenameStart) + suffixLen + 1);
798*22ce4affSfengbojiang     if (!result) {
799*22ce4affSfengbojiang         EXM_THROW(30, "zstd: FIO_createFilename_fromOutDir: %s", strerror(errno));
800*22ce4affSfengbojiang     }
801*22ce4affSfengbojiang 
802*22ce4affSfengbojiang     memcpy(result, outDirName, strlen(outDirName));
803*22ce4affSfengbojiang     if (outDirName[strlen(outDirName)-1] == separator) {
804*22ce4affSfengbojiang         memcpy(result + strlen(outDirName), filenameStart, strlen(filenameStart));
805*22ce4affSfengbojiang     } else {
806*22ce4affSfengbojiang         memcpy(result + strlen(outDirName), &separator, 1);
807*22ce4affSfengbojiang         memcpy(result + strlen(outDirName) + 1, filenameStart, strlen(filenameStart));
808*22ce4affSfengbojiang     }
809*22ce4affSfengbojiang 
810*22ce4affSfengbojiang     return result;
811*22ce4affSfengbojiang }
812*22ce4affSfengbojiang 
813*22ce4affSfengbojiang /* FIO_highbit64() :
814*22ce4affSfengbojiang  * gives position of highest bit.
815*22ce4affSfengbojiang  * note : only works for v > 0 !
816*22ce4affSfengbojiang  */
FIO_highbit64(unsigned long long v)817*22ce4affSfengbojiang static unsigned FIO_highbit64(unsigned long long v)
818*22ce4affSfengbojiang {
819*22ce4affSfengbojiang     unsigned count = 0;
820*22ce4affSfengbojiang     assert(v != 0);
821*22ce4affSfengbojiang     v >>= 1;
822*22ce4affSfengbojiang     while (v) { v >>= 1; count++; }
823*22ce4affSfengbojiang     return count;
824*22ce4affSfengbojiang }
825*22ce4affSfengbojiang 
FIO_adjustMemLimitForPatchFromMode(FIO_prefs_t * const prefs,unsigned long long const dictSize,unsigned long long const maxSrcFileSize)826*22ce4affSfengbojiang static void FIO_adjustMemLimitForPatchFromMode(FIO_prefs_t* const prefs,
827*22ce4affSfengbojiang                                     unsigned long long const dictSize,
828*22ce4affSfengbojiang                                     unsigned long long const maxSrcFileSize)
829*22ce4affSfengbojiang {
830*22ce4affSfengbojiang     unsigned long long maxSize = MAX(prefs->memLimit, MAX(dictSize, maxSrcFileSize));
831*22ce4affSfengbojiang     unsigned const maxWindowSize = (1U << ZSTD_WINDOWLOG_MAX);
832*22ce4affSfengbojiang     if (maxSize == UTIL_FILESIZE_UNKNOWN)
833*22ce4affSfengbojiang         EXM_THROW(42, "Using --patch-from with stdin requires --stream-size");
834*22ce4affSfengbojiang     assert(maxSize != UTIL_FILESIZE_UNKNOWN);
835*22ce4affSfengbojiang     if (maxSize > maxWindowSize)
836*22ce4affSfengbojiang         EXM_THROW(42, "Can't handle files larger than %u GB\n", maxWindowSize/(1 GB));
837*22ce4affSfengbojiang     FIO_setMemLimit(prefs, (unsigned)maxSize);
838*22ce4affSfengbojiang }
839*22ce4affSfengbojiang 
840*22ce4affSfengbojiang /* FIO_removeMultiFilesWarning() :
841*22ce4affSfengbojiang  * Returns 1 if the console should abort, 0 if console should proceed.
842*22ce4affSfengbojiang  * This function handles logic when processing multiple files with -o, displaying the appropriate warnings/prompts.
843*22ce4affSfengbojiang  *
844*22ce4affSfengbojiang  * If -f is specified, or there is just 1 file, zstd will always proceed as usual.
845*22ce4affSfengbojiang  * If --rm is specified, there will be a prompt asking for user confirmation.
846*22ce4affSfengbojiang  *         If -f is specified with --rm, zstd will proceed as usual
847*22ce4affSfengbojiang  *         If -q is specified with --rm, zstd will abort pre-emptively
848*22ce4affSfengbojiang  *         If neither flag is specified, zstd will prompt the user for confirmation to proceed.
849*22ce4affSfengbojiang  * If --rm is not specified, then zstd will print a warning to the user (which can be silenced with -q).
850*22ce4affSfengbojiang  * However, if the output is stdout, we will always abort rather than displaying the warning prompt.
851*22ce4affSfengbojiang  */
FIO_removeMultiFilesWarning(FIO_ctx_t * const fCtx,const FIO_prefs_t * const prefs,const char * outFileName,int displayLevelCutoff)852*22ce4affSfengbojiang static int FIO_removeMultiFilesWarning(FIO_ctx_t* const fCtx, const FIO_prefs_t* const prefs, const char* outFileName, int displayLevelCutoff)
853*22ce4affSfengbojiang {
854*22ce4affSfengbojiang     int error = 0;
855*22ce4affSfengbojiang     if (fCtx->nbFilesTotal > 1 && !prefs->overwrite) {
856*22ce4affSfengbojiang         if (g_display_prefs.displayLevel <= displayLevelCutoff) {
857*22ce4affSfengbojiang             if (prefs->removeSrcFile) {
858*22ce4affSfengbojiang                 DISPLAYLEVEL(1, "zstd: Aborting... not deleting files and processing into dst: %s", outFileName);
859*22ce4affSfengbojiang                 error =  1;
860*22ce4affSfengbojiang             }
861*22ce4affSfengbojiang         } else {
862*22ce4affSfengbojiang             if (!strcmp(outFileName, stdoutmark)) {
863*22ce4affSfengbojiang                 DISPLAYLEVEL(2, "zstd: WARNING: all input files will be processed and concatenated into stdout. ");
864*22ce4affSfengbojiang             } else {
865*22ce4affSfengbojiang                 DISPLAYLEVEL(2, "zstd: WARNING: all input files will be processed and concatenated into a single output file: %s ", outFileName);
866*22ce4affSfengbojiang             }
867*22ce4affSfengbojiang             DISPLAYLEVEL(2, "\nThe concatenated output CANNOT regenerate the original directory tree. ")
868*22ce4affSfengbojiang             if (prefs->removeSrcFile) {
869*22ce4affSfengbojiang                 if (fCtx->hasStdoutOutput) {
870*22ce4affSfengbojiang                     DISPLAYLEVEL(1, "\nAborting. Use -f if you really want to delete the files and output to stdout");
871*22ce4affSfengbojiang                     error = 1;
872*22ce4affSfengbojiang                 } else {
873*22ce4affSfengbojiang                     error = g_display_prefs.displayLevel > displayLevelCutoff && UTIL_requireUserConfirmation("This is a destructive operation. Proceed? (y/n): ", "Aborting...", "yY", fCtx->hasStdinInput);
874*22ce4affSfengbojiang                 }
875*22ce4affSfengbojiang             }
876*22ce4affSfengbojiang         }
877*22ce4affSfengbojiang         DISPLAY("\n");
878*22ce4affSfengbojiang     }
879*22ce4affSfengbojiang     return error;
880*22ce4affSfengbojiang }
881*22ce4affSfengbojiang 
882*22ce4affSfengbojiang #ifndef ZSTD_NOCOMPRESS
883*22ce4affSfengbojiang 
884*22ce4affSfengbojiang /* **********************************************************************
885*22ce4affSfengbojiang  *  Compression
886*22ce4affSfengbojiang  ************************************************************************/
887*22ce4affSfengbojiang typedef struct {
888*22ce4affSfengbojiang     FILE* srcFile;
889*22ce4affSfengbojiang     FILE* dstFile;
890*22ce4affSfengbojiang     void*  srcBuffer;
891*22ce4affSfengbojiang     size_t srcBufferSize;
892*22ce4affSfengbojiang     void*  dstBuffer;
893*22ce4affSfengbojiang     size_t dstBufferSize;
894*22ce4affSfengbojiang     void* dictBuffer;
895*22ce4affSfengbojiang     size_t dictBufferSize;
896*22ce4affSfengbojiang     const char* dictFileName;
897*22ce4affSfengbojiang     ZSTD_CStream* cctx;
898*22ce4affSfengbojiang } cRess_t;
899*22ce4affSfengbojiang 
FIO_adjustParamsForPatchFromMode(FIO_prefs_t * const prefs,ZSTD_compressionParameters * comprParams,unsigned long long const dictSize,unsigned long long const maxSrcFileSize,int cLevel)900*22ce4affSfengbojiang static void FIO_adjustParamsForPatchFromMode(FIO_prefs_t* const prefs,
901*22ce4affSfengbojiang                                     ZSTD_compressionParameters* comprParams,
902*22ce4affSfengbojiang                                     unsigned long long const dictSize,
903*22ce4affSfengbojiang                                     unsigned long long const maxSrcFileSize,
904*22ce4affSfengbojiang                                     int cLevel)
905*22ce4affSfengbojiang {
906*22ce4affSfengbojiang     unsigned const fileWindowLog = FIO_highbit64(maxSrcFileSize) + 1;
907*22ce4affSfengbojiang     ZSTD_compressionParameters const cParams = ZSTD_getCParams(cLevel, (size_t)maxSrcFileSize, (size_t)dictSize);
908*22ce4affSfengbojiang     FIO_adjustMemLimitForPatchFromMode(prefs, dictSize, maxSrcFileSize);
909*22ce4affSfengbojiang     if (fileWindowLog > ZSTD_WINDOWLOG_MAX)
910*22ce4affSfengbojiang         DISPLAYLEVEL(1, "Max window log exceeded by file (compression ratio will suffer)\n");
911*22ce4affSfengbojiang     comprParams->windowLog = MIN(ZSTD_WINDOWLOG_MAX, fileWindowLog);
912*22ce4affSfengbojiang     if (fileWindowLog > ZSTD_cycleLog(cParams.chainLog, cParams.strategy)) {
913*22ce4affSfengbojiang         if (!prefs->ldmFlag)
914*22ce4affSfengbojiang             DISPLAYLEVEL(1, "long mode automatically triggered\n");
915*22ce4affSfengbojiang         FIO_setLdmFlag(prefs, 1);
916*22ce4affSfengbojiang     }
917*22ce4affSfengbojiang     if (cParams.strategy >= ZSTD_btopt) {
918*22ce4affSfengbojiang         DISPLAYLEVEL(1, "[Optimal parser notes] Consider the following to improve patch size at the cost of speed:\n");
919*22ce4affSfengbojiang         DISPLAYLEVEL(1, "- Use --single-thread mode in the zstd cli\n");
920*22ce4affSfengbojiang         DISPLAYLEVEL(1, "- Set a larger targetLength (eg. --zstd=targetLength=4096)\n");
921*22ce4affSfengbojiang         DISPLAYLEVEL(1, "- Set a larger chainLog (eg. --zstd=chainLog=%u)\n", ZSTD_CHAINLOG_MAX);
922*22ce4affSfengbojiang         DISPLAYLEVEL(1, "Also consdier playing around with searchLog and hashLog\n");
923*22ce4affSfengbojiang     }
924*22ce4affSfengbojiang }
925*22ce4affSfengbojiang 
FIO_createCResources(FIO_prefs_t * const prefs,const char * dictFileName,unsigned long long const maxSrcFileSize,int cLevel,ZSTD_compressionParameters comprParams)926*22ce4affSfengbojiang static cRess_t FIO_createCResources(FIO_prefs_t* const prefs,
927*22ce4affSfengbojiang                                     const char* dictFileName, unsigned long long const maxSrcFileSize,
928*22ce4affSfengbojiang                                     int cLevel, ZSTD_compressionParameters comprParams) {
929*22ce4affSfengbojiang     cRess_t ress;
930*22ce4affSfengbojiang     memset(&ress, 0, sizeof(ress));
931*22ce4affSfengbojiang 
932*22ce4affSfengbojiang     DISPLAYLEVEL(6, "FIO_createCResources \n");
933*22ce4affSfengbojiang     ress.cctx = ZSTD_createCCtx();
934*22ce4affSfengbojiang     if (ress.cctx == NULL)
935*22ce4affSfengbojiang         EXM_THROW(30, "allocation error (%s): can't create ZSTD_CCtx",
936*22ce4affSfengbojiang                     strerror(errno));
937*22ce4affSfengbojiang     ress.srcBufferSize = ZSTD_CStreamInSize();
938*22ce4affSfengbojiang     ress.srcBuffer = malloc(ress.srcBufferSize);
939*22ce4affSfengbojiang     ress.dstBufferSize = ZSTD_CStreamOutSize();
940*22ce4affSfengbojiang 
941*22ce4affSfengbojiang     /* need to update memLimit before calling createDictBuffer
942*22ce4affSfengbojiang      * because of memLimit check inside it */
943*22ce4affSfengbojiang     if (prefs->patchFromMode) {
944*22ce4affSfengbojiang         unsigned long long const ssSize = (unsigned long long)prefs->streamSrcSize;
945*22ce4affSfengbojiang         FIO_adjustParamsForPatchFromMode(prefs, &comprParams, UTIL_getFileSize(dictFileName), ssSize > 0 ? ssSize : maxSrcFileSize, cLevel);
946*22ce4affSfengbojiang     }
947*22ce4affSfengbojiang     ress.dstBuffer = malloc(ress.dstBufferSize);
948*22ce4affSfengbojiang     ress.dictBufferSize = FIO_createDictBuffer(&ress.dictBuffer, dictFileName, prefs);   /* works with dictFileName==NULL */
949*22ce4affSfengbojiang     if (!ress.srcBuffer || !ress.dstBuffer)
950*22ce4affSfengbojiang         EXM_THROW(31, "allocation error : not enough memory");
951*22ce4affSfengbojiang 
952*22ce4affSfengbojiang     /* Advanced parameters, including dictionary */
953*22ce4affSfengbojiang     if (dictFileName && (ress.dictBuffer==NULL))
954*22ce4affSfengbojiang         EXM_THROW(32, "allocation error : can't create dictBuffer");
955*22ce4affSfengbojiang     ress.dictFileName = dictFileName;
956*22ce4affSfengbojiang 
957*22ce4affSfengbojiang     if (prefs->adaptiveMode && !prefs->ldmFlag && !comprParams.windowLog)
958*22ce4affSfengbojiang         comprParams.windowLog = ADAPT_WINDOWLOG_DEFAULT;
959*22ce4affSfengbojiang 
960*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_contentSizeFlag, prefs->contentSize) );  /* always enable content size when available (note: supposed to be default) */
961*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_dictIDFlag, prefs->dictIDFlag) );
962*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_checksumFlag, prefs->checksumFlag) );
963*22ce4affSfengbojiang     /* compression level */
964*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_compressionLevel, cLevel) );
965*22ce4affSfengbojiang     /* max compressed block size */
966*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_targetCBlockSize, (int)prefs->targetCBlockSize) );
967*22ce4affSfengbojiang     /* source size hint */
968*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_srcSizeHint, (int)prefs->srcSizeHint) );
969*22ce4affSfengbojiang     /* long distance matching */
970*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_enableLongDistanceMatching, prefs->ldmFlag) );
971*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_ldmHashLog, prefs->ldmHashLog) );
972*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_ldmMinMatch, prefs->ldmMinMatch) );
973*22ce4affSfengbojiang     if (prefs->ldmBucketSizeLog != FIO_LDM_PARAM_NOTSET) {
974*22ce4affSfengbojiang         CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_ldmBucketSizeLog, prefs->ldmBucketSizeLog) );
975*22ce4affSfengbojiang     }
976*22ce4affSfengbojiang     if (prefs->ldmHashRateLog != FIO_LDM_PARAM_NOTSET) {
977*22ce4affSfengbojiang         CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_ldmHashRateLog, prefs->ldmHashRateLog) );
978*22ce4affSfengbojiang     }
979*22ce4affSfengbojiang     /* compression parameters */
980*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_windowLog, (int)comprParams.windowLog) );
981*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_chainLog, (int)comprParams.chainLog) );
982*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_hashLog, (int)comprParams.hashLog) );
983*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_searchLog, (int)comprParams.searchLog) );
984*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_minMatch, (int)comprParams.minMatch) );
985*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_targetLength, (int)comprParams.targetLength) );
986*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_strategy, comprParams.strategy) );
987*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_literalCompressionMode, (int)prefs->literalCompressionMode) );
988*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_enableDedicatedDictSearch, 1) );
989*22ce4affSfengbojiang     /* multi-threading */
990*22ce4affSfengbojiang #ifdef ZSTD_MULTITHREAD
991*22ce4affSfengbojiang     DISPLAYLEVEL(5,"set nb workers = %u \n", prefs->nbWorkers);
992*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_nbWorkers, prefs->nbWorkers) );
993*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_jobSize, prefs->blockSize) );
994*22ce4affSfengbojiang     if (prefs->overlapLog != FIO_OVERLAP_LOG_NOTSET) {
995*22ce4affSfengbojiang         DISPLAYLEVEL(3,"set overlapLog = %u \n", prefs->overlapLog);
996*22ce4affSfengbojiang         CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_overlapLog, prefs->overlapLog) );
997*22ce4affSfengbojiang     }
998*22ce4affSfengbojiang     CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_rsyncable, prefs->rsyncable) );
999*22ce4affSfengbojiang #endif
1000*22ce4affSfengbojiang     /* dictionary */
1001*22ce4affSfengbojiang     if (prefs->patchFromMode) {
1002*22ce4affSfengbojiang         CHECK( ZSTD_CCtx_refPrefix(ress.cctx, ress.dictBuffer, ress.dictBufferSize) );
1003*22ce4affSfengbojiang     } else {
1004*22ce4affSfengbojiang         CHECK( ZSTD_CCtx_loadDictionary(ress.cctx, ress.dictBuffer, ress.dictBufferSize) );
1005*22ce4affSfengbojiang     }
1006*22ce4affSfengbojiang 
1007*22ce4affSfengbojiang     return ress;
1008*22ce4affSfengbojiang }
1009*22ce4affSfengbojiang 
FIO_freeCResources(const cRess_t * const ress)1010*22ce4affSfengbojiang static void FIO_freeCResources(const cRess_t* const ress)
1011*22ce4affSfengbojiang {
1012*22ce4affSfengbojiang     free(ress->srcBuffer);
1013*22ce4affSfengbojiang     free(ress->dstBuffer);
1014*22ce4affSfengbojiang     free(ress->dictBuffer);
1015*22ce4affSfengbojiang     ZSTD_freeCStream(ress->cctx);   /* never fails */
1016*22ce4affSfengbojiang }
1017*22ce4affSfengbojiang 
1018*22ce4affSfengbojiang 
1019*22ce4affSfengbojiang #ifdef ZSTD_GZCOMPRESS
1020*22ce4affSfengbojiang static unsigned long long
FIO_compressGzFrame(const cRess_t * ress,const char * srcFileName,U64 const srcFileSize,int compressionLevel,U64 * readsize)1021*22ce4affSfengbojiang FIO_compressGzFrame(const cRess_t* ress,  /* buffers & handlers are used, but not changed */
1022*22ce4affSfengbojiang                     const char* srcFileName, U64 const srcFileSize,
1023*22ce4affSfengbojiang                     int compressionLevel, U64* readsize)
1024*22ce4affSfengbojiang {
1025*22ce4affSfengbojiang     unsigned long long inFileSize = 0, outFileSize = 0;
1026*22ce4affSfengbojiang     z_stream strm;
1027*22ce4affSfengbojiang 
1028*22ce4affSfengbojiang     if (compressionLevel > Z_BEST_COMPRESSION)
1029*22ce4affSfengbojiang         compressionLevel = Z_BEST_COMPRESSION;
1030*22ce4affSfengbojiang 
1031*22ce4affSfengbojiang     strm.zalloc = Z_NULL;
1032*22ce4affSfengbojiang     strm.zfree = Z_NULL;
1033*22ce4affSfengbojiang     strm.opaque = Z_NULL;
1034*22ce4affSfengbojiang 
1035*22ce4affSfengbojiang     {   int const ret = deflateInit2(&strm, compressionLevel, Z_DEFLATED,
1036*22ce4affSfengbojiang                         15 /* maxWindowLogSize */ + 16 /* gzip only */,
1037*22ce4affSfengbojiang                         8, Z_DEFAULT_STRATEGY); /* see http://www.zlib.net/manual.html */
1038*22ce4affSfengbojiang         if (ret != Z_OK) {
1039*22ce4affSfengbojiang             EXM_THROW(71, "zstd: %s: deflateInit2 error %d \n", srcFileName, ret);
1040*22ce4affSfengbojiang     }   }
1041*22ce4affSfengbojiang 
1042*22ce4affSfengbojiang     strm.next_in = 0;
1043*22ce4affSfengbojiang     strm.avail_in = 0;
1044*22ce4affSfengbojiang     strm.next_out = (Bytef*)ress->dstBuffer;
1045*22ce4affSfengbojiang     strm.avail_out = (uInt)ress->dstBufferSize;
1046*22ce4affSfengbojiang 
1047*22ce4affSfengbojiang     while (1) {
1048*22ce4affSfengbojiang         int ret;
1049*22ce4affSfengbojiang         if (strm.avail_in == 0) {
1050*22ce4affSfengbojiang             size_t const inSize = fread(ress->srcBuffer, 1, ress->srcBufferSize, ress->srcFile);
1051*22ce4affSfengbojiang             if (inSize == 0) break;
1052*22ce4affSfengbojiang             inFileSize += inSize;
1053*22ce4affSfengbojiang             strm.next_in = (z_const unsigned char*)ress->srcBuffer;
1054*22ce4affSfengbojiang             strm.avail_in = (uInt)inSize;
1055*22ce4affSfengbojiang         }
1056*22ce4affSfengbojiang         ret = deflate(&strm, Z_NO_FLUSH);
1057*22ce4affSfengbojiang         if (ret != Z_OK)
1058*22ce4affSfengbojiang             EXM_THROW(72, "zstd: %s: deflate error %d \n", srcFileName, ret);
1059*22ce4affSfengbojiang         {   size_t const cSize = ress->dstBufferSize - strm.avail_out;
1060*22ce4affSfengbojiang             if (cSize) {
1061*22ce4affSfengbojiang                 if (fwrite(ress->dstBuffer, 1, cSize, ress->dstFile) != cSize)
1062*22ce4affSfengbojiang                     EXM_THROW(73, "Write error : cannot write to output file : %s ", strerror(errno));
1063*22ce4affSfengbojiang                 outFileSize += cSize;
1064*22ce4affSfengbojiang                 strm.next_out = (Bytef*)ress->dstBuffer;
1065*22ce4affSfengbojiang                 strm.avail_out = (uInt)ress->dstBufferSize;
1066*22ce4affSfengbojiang         }   }
1067*22ce4affSfengbojiang         if (srcFileSize == UTIL_FILESIZE_UNKNOWN) {
1068*22ce4affSfengbojiang             DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ",
1069*22ce4affSfengbojiang                             (unsigned)(inFileSize>>20),
1070*22ce4affSfengbojiang                             (double)outFileSize/inFileSize*100)
1071*22ce4affSfengbojiang         } else {
1072*22ce4affSfengbojiang             DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%% ",
1073*22ce4affSfengbojiang                             (unsigned)(inFileSize>>20), (unsigned)(srcFileSize>>20),
1074*22ce4affSfengbojiang                             (double)outFileSize/inFileSize*100);
1075*22ce4affSfengbojiang     }   }
1076*22ce4affSfengbojiang 
1077*22ce4affSfengbojiang     while (1) {
1078*22ce4affSfengbojiang         int const ret = deflate(&strm, Z_FINISH);
1079*22ce4affSfengbojiang         {   size_t const cSize = ress->dstBufferSize - strm.avail_out;
1080*22ce4affSfengbojiang             if (cSize) {
1081*22ce4affSfengbojiang                 if (fwrite(ress->dstBuffer, 1, cSize, ress->dstFile) != cSize)
1082*22ce4affSfengbojiang                     EXM_THROW(75, "Write error : %s ", strerror(errno));
1083*22ce4affSfengbojiang                 outFileSize += cSize;
1084*22ce4affSfengbojiang                 strm.next_out = (Bytef*)ress->dstBuffer;
1085*22ce4affSfengbojiang                 strm.avail_out = (uInt)ress->dstBufferSize;
1086*22ce4affSfengbojiang         }   }
1087*22ce4affSfengbojiang         if (ret == Z_STREAM_END) break;
1088*22ce4affSfengbojiang         if (ret != Z_BUF_ERROR)
1089*22ce4affSfengbojiang             EXM_THROW(77, "zstd: %s: deflate error %d \n", srcFileName, ret);
1090*22ce4affSfengbojiang     }
1091*22ce4affSfengbojiang 
1092*22ce4affSfengbojiang     {   int const ret = deflateEnd(&strm);
1093*22ce4affSfengbojiang         if (ret != Z_OK) {
1094*22ce4affSfengbojiang             EXM_THROW(79, "zstd: %s: deflateEnd error %d \n", srcFileName, ret);
1095*22ce4affSfengbojiang     }   }
1096*22ce4affSfengbojiang     *readsize = inFileSize;
1097*22ce4affSfengbojiang     return outFileSize;
1098*22ce4affSfengbojiang }
1099*22ce4affSfengbojiang #endif
1100*22ce4affSfengbojiang 
1101*22ce4affSfengbojiang 
1102*22ce4affSfengbojiang #ifdef ZSTD_LZMACOMPRESS
1103*22ce4affSfengbojiang static unsigned long long
FIO_compressLzmaFrame(cRess_t * ress,const char * srcFileName,U64 const srcFileSize,int compressionLevel,U64 * readsize,int plain_lzma)1104*22ce4affSfengbojiang FIO_compressLzmaFrame(cRess_t* ress,
1105*22ce4affSfengbojiang                       const char* srcFileName, U64 const srcFileSize,
1106*22ce4affSfengbojiang                       int compressionLevel, U64* readsize, int plain_lzma)
1107*22ce4affSfengbojiang {
1108*22ce4affSfengbojiang     unsigned long long inFileSize = 0, outFileSize = 0;
1109*22ce4affSfengbojiang     lzma_stream strm = LZMA_STREAM_INIT;
1110*22ce4affSfengbojiang     lzma_action action = LZMA_RUN;
1111*22ce4affSfengbojiang     lzma_ret ret;
1112*22ce4affSfengbojiang 
1113*22ce4affSfengbojiang     if (compressionLevel < 0) compressionLevel = 0;
1114*22ce4affSfengbojiang     if (compressionLevel > 9) compressionLevel = 9;
1115*22ce4affSfengbojiang 
1116*22ce4affSfengbojiang     if (plain_lzma) {
1117*22ce4affSfengbojiang         lzma_options_lzma opt_lzma;
1118*22ce4affSfengbojiang         if (lzma_lzma_preset(&opt_lzma, compressionLevel))
1119*22ce4affSfengbojiang             EXM_THROW(81, "zstd: %s: lzma_lzma_preset error", srcFileName);
1120*22ce4affSfengbojiang         ret = lzma_alone_encoder(&strm, &opt_lzma); /* LZMA */
1121*22ce4affSfengbojiang         if (ret != LZMA_OK)
1122*22ce4affSfengbojiang             EXM_THROW(82, "zstd: %s: lzma_alone_encoder error %d", srcFileName, ret);
1123*22ce4affSfengbojiang     } else {
1124*22ce4affSfengbojiang         ret = lzma_easy_encoder(&strm, compressionLevel, LZMA_CHECK_CRC64); /* XZ */
1125*22ce4affSfengbojiang         if (ret != LZMA_OK)
1126*22ce4affSfengbojiang             EXM_THROW(83, "zstd: %s: lzma_easy_encoder error %d", srcFileName, ret);
1127*22ce4affSfengbojiang     }
1128*22ce4affSfengbojiang 
1129*22ce4affSfengbojiang     strm.next_in = 0;
1130*22ce4affSfengbojiang     strm.avail_in = 0;
1131*22ce4affSfengbojiang     strm.next_out = (BYTE*)ress->dstBuffer;
1132*22ce4affSfengbojiang     strm.avail_out = ress->dstBufferSize;
1133*22ce4affSfengbojiang 
1134*22ce4affSfengbojiang     while (1) {
1135*22ce4affSfengbojiang         if (strm.avail_in == 0) {
1136*22ce4affSfengbojiang             size_t const inSize = fread(ress->srcBuffer, 1, ress->srcBufferSize, ress->srcFile);
1137*22ce4affSfengbojiang             if (inSize == 0) action = LZMA_FINISH;
1138*22ce4affSfengbojiang             inFileSize += inSize;
1139*22ce4affSfengbojiang             strm.next_in = (BYTE const*)ress->srcBuffer;
1140*22ce4affSfengbojiang             strm.avail_in = inSize;
1141*22ce4affSfengbojiang         }
1142*22ce4affSfengbojiang 
1143*22ce4affSfengbojiang         ret = lzma_code(&strm, action);
1144*22ce4affSfengbojiang 
1145*22ce4affSfengbojiang         if (ret != LZMA_OK && ret != LZMA_STREAM_END)
1146*22ce4affSfengbojiang             EXM_THROW(84, "zstd: %s: lzma_code encoding error %d", srcFileName, ret);
1147*22ce4affSfengbojiang         {   size_t const compBytes = ress->dstBufferSize - strm.avail_out;
1148*22ce4affSfengbojiang             if (compBytes) {
1149*22ce4affSfengbojiang                 if (fwrite(ress->dstBuffer, 1, compBytes, ress->dstFile) != compBytes)
1150*22ce4affSfengbojiang                     EXM_THROW(85, "Write error : %s", strerror(errno));
1151*22ce4affSfengbojiang                 outFileSize += compBytes;
1152*22ce4affSfengbojiang                 strm.next_out = (BYTE*)ress->dstBuffer;
1153*22ce4affSfengbojiang                 strm.avail_out = ress->dstBufferSize;
1154*22ce4affSfengbojiang         }   }
1155*22ce4affSfengbojiang         if (srcFileSize == UTIL_FILESIZE_UNKNOWN)
1156*22ce4affSfengbojiang             DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%%",
1157*22ce4affSfengbojiang                             (unsigned)(inFileSize>>20),
1158*22ce4affSfengbojiang                             (double)outFileSize/inFileSize*100)
1159*22ce4affSfengbojiang         else
1160*22ce4affSfengbojiang             DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%%",
1161*22ce4affSfengbojiang                             (unsigned)(inFileSize>>20), (unsigned)(srcFileSize>>20),
1162*22ce4affSfengbojiang                             (double)outFileSize/inFileSize*100);
1163*22ce4affSfengbojiang         if (ret == LZMA_STREAM_END) break;
1164*22ce4affSfengbojiang     }
1165*22ce4affSfengbojiang 
1166*22ce4affSfengbojiang     lzma_end(&strm);
1167*22ce4affSfengbojiang     *readsize = inFileSize;
1168*22ce4affSfengbojiang 
1169*22ce4affSfengbojiang     return outFileSize;
1170*22ce4affSfengbojiang }
1171*22ce4affSfengbojiang #endif
1172*22ce4affSfengbojiang 
1173*22ce4affSfengbojiang #ifdef ZSTD_LZ4COMPRESS
1174*22ce4affSfengbojiang 
1175*22ce4affSfengbojiang #if LZ4_VERSION_NUMBER <= 10600
1176*22ce4affSfengbojiang #define LZ4F_blockLinked blockLinked
1177*22ce4affSfengbojiang #define LZ4F_max64KB max64KB
1178*22ce4affSfengbojiang #endif
1179*22ce4affSfengbojiang 
FIO_LZ4_GetBlockSize_FromBlockId(int id)1180*22ce4affSfengbojiang static int FIO_LZ4_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); }
1181*22ce4affSfengbojiang 
1182*22ce4affSfengbojiang static unsigned long long
FIO_compressLz4Frame(cRess_t * ress,const char * srcFileName,U64 const srcFileSize,int compressionLevel,int checksumFlag,U64 * readsize)1183*22ce4affSfengbojiang FIO_compressLz4Frame(cRess_t* ress,
1184*22ce4affSfengbojiang                      const char* srcFileName, U64 const srcFileSize,
1185*22ce4affSfengbojiang                      int compressionLevel, int checksumFlag,
1186*22ce4affSfengbojiang                      U64* readsize)
1187*22ce4affSfengbojiang {
1188*22ce4affSfengbojiang     const size_t blockSize = FIO_LZ4_GetBlockSize_FromBlockId(LZ4F_max64KB);
1189*22ce4affSfengbojiang     unsigned long long inFileSize = 0, outFileSize = 0;
1190*22ce4affSfengbojiang 
1191*22ce4affSfengbojiang     LZ4F_preferences_t prefs;
1192*22ce4affSfengbojiang     LZ4F_compressionContext_t ctx;
1193*22ce4affSfengbojiang 
1194*22ce4affSfengbojiang     LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
1195*22ce4affSfengbojiang     if (LZ4F_isError(errorCode))
1196*22ce4affSfengbojiang         EXM_THROW(31, "zstd: failed to create lz4 compression context");
1197*22ce4affSfengbojiang 
1198*22ce4affSfengbojiang     memset(&prefs, 0, sizeof(prefs));
1199*22ce4affSfengbojiang 
1200*22ce4affSfengbojiang     assert(blockSize <= ress->srcBufferSize);
1201*22ce4affSfengbojiang 
1202*22ce4affSfengbojiang     prefs.autoFlush = 1;
1203*22ce4affSfengbojiang     prefs.compressionLevel = compressionLevel;
1204*22ce4affSfengbojiang     prefs.frameInfo.blockMode = LZ4F_blockLinked;
1205*22ce4affSfengbojiang     prefs.frameInfo.blockSizeID = LZ4F_max64KB;
1206*22ce4affSfengbojiang     prefs.frameInfo.contentChecksumFlag = (contentChecksum_t)checksumFlag;
1207*22ce4affSfengbojiang #if LZ4_VERSION_NUMBER >= 10600
1208*22ce4affSfengbojiang     prefs.frameInfo.contentSize = (srcFileSize==UTIL_FILESIZE_UNKNOWN) ? 0 : srcFileSize;
1209*22ce4affSfengbojiang #endif
1210*22ce4affSfengbojiang     assert(LZ4F_compressBound(blockSize, &prefs) <= ress->dstBufferSize);
1211*22ce4affSfengbojiang 
1212*22ce4affSfengbojiang     {
1213*22ce4affSfengbojiang         size_t readSize;
1214*22ce4affSfengbojiang         size_t headerSize = LZ4F_compressBegin(ctx, ress->dstBuffer, ress->dstBufferSize, &prefs);
1215*22ce4affSfengbojiang         if (LZ4F_isError(headerSize))
1216*22ce4affSfengbojiang             EXM_THROW(33, "File header generation failed : %s",
1217*22ce4affSfengbojiang                             LZ4F_getErrorName(headerSize));
1218*22ce4affSfengbojiang         if (fwrite(ress->dstBuffer, 1, headerSize, ress->dstFile) != headerSize)
1219*22ce4affSfengbojiang             EXM_THROW(34, "Write error : %s (cannot write header)", strerror(errno));
1220*22ce4affSfengbojiang         outFileSize += headerSize;
1221*22ce4affSfengbojiang 
1222*22ce4affSfengbojiang         /* Read first block */
1223*22ce4affSfengbojiang         readSize  = fread(ress->srcBuffer, (size_t)1, (size_t)blockSize, ress->srcFile);
1224*22ce4affSfengbojiang         inFileSize += readSize;
1225*22ce4affSfengbojiang 
1226*22ce4affSfengbojiang         /* Main Loop */
1227*22ce4affSfengbojiang         while (readSize>0) {
1228*22ce4affSfengbojiang             size_t const outSize = LZ4F_compressUpdate(ctx,
1229*22ce4affSfengbojiang                                         ress->dstBuffer, ress->dstBufferSize,
1230*22ce4affSfengbojiang                                         ress->srcBuffer, readSize, NULL);
1231*22ce4affSfengbojiang             if (LZ4F_isError(outSize))
1232*22ce4affSfengbojiang                 EXM_THROW(35, "zstd: %s: lz4 compression failed : %s",
1233*22ce4affSfengbojiang                             srcFileName, LZ4F_getErrorName(outSize));
1234*22ce4affSfengbojiang             outFileSize += outSize;
1235*22ce4affSfengbojiang             if (srcFileSize == UTIL_FILESIZE_UNKNOWN) {
1236*22ce4affSfengbojiang                 DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%%",
1237*22ce4affSfengbojiang                                 (unsigned)(inFileSize>>20),
1238*22ce4affSfengbojiang                                 (double)outFileSize/inFileSize*100)
1239*22ce4affSfengbojiang             } else {
1240*22ce4affSfengbojiang                 DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%%",
1241*22ce4affSfengbojiang                                 (unsigned)(inFileSize>>20), (unsigned)(srcFileSize>>20),
1242*22ce4affSfengbojiang                                 (double)outFileSize/inFileSize*100);
1243*22ce4affSfengbojiang             }
1244*22ce4affSfengbojiang 
1245*22ce4affSfengbojiang             /* Write Block */
1246*22ce4affSfengbojiang             {   size_t const sizeCheck = fwrite(ress->dstBuffer, 1, outSize, ress->dstFile);
1247*22ce4affSfengbojiang                 if (sizeCheck != outSize)
1248*22ce4affSfengbojiang                     EXM_THROW(36, "Write error : %s", strerror(errno));
1249*22ce4affSfengbojiang             }
1250*22ce4affSfengbojiang 
1251*22ce4affSfengbojiang             /* Read next block */
1252*22ce4affSfengbojiang             readSize  = fread(ress->srcBuffer, (size_t)1, (size_t)blockSize, ress->srcFile);
1253*22ce4affSfengbojiang             inFileSize += readSize;
1254*22ce4affSfengbojiang         }
1255*22ce4affSfengbojiang         if (ferror(ress->srcFile)) EXM_THROW(37, "Error reading %s ", srcFileName);
1256*22ce4affSfengbojiang 
1257*22ce4affSfengbojiang         /* End of Stream mark */
1258*22ce4affSfengbojiang         headerSize = LZ4F_compressEnd(ctx, ress->dstBuffer, ress->dstBufferSize, NULL);
1259*22ce4affSfengbojiang         if (LZ4F_isError(headerSize))
1260*22ce4affSfengbojiang             EXM_THROW(38, "zstd: %s: lz4 end of file generation failed : %s",
1261*22ce4affSfengbojiang                         srcFileName, LZ4F_getErrorName(headerSize));
1262*22ce4affSfengbojiang 
1263*22ce4affSfengbojiang         {   size_t const sizeCheck = fwrite(ress->dstBuffer, 1, headerSize, ress->dstFile);
1264*22ce4affSfengbojiang             if (sizeCheck != headerSize)
1265*22ce4affSfengbojiang                 EXM_THROW(39, "Write error : %s (cannot write end of stream)",
1266*22ce4affSfengbojiang                             strerror(errno));
1267*22ce4affSfengbojiang         }
1268*22ce4affSfengbojiang         outFileSize += headerSize;
1269*22ce4affSfengbojiang     }
1270*22ce4affSfengbojiang 
1271*22ce4affSfengbojiang     *readsize = inFileSize;
1272*22ce4affSfengbojiang     LZ4F_freeCompressionContext(ctx);
1273*22ce4affSfengbojiang 
1274*22ce4affSfengbojiang     return outFileSize;
1275*22ce4affSfengbojiang }
1276*22ce4affSfengbojiang #endif
1277*22ce4affSfengbojiang 
1278*22ce4affSfengbojiang 
1279*22ce4affSfengbojiang static unsigned long long
FIO_compressZstdFrame(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,const cRess_t * ressPtr,const char * srcFileName,U64 fileSize,int compressionLevel,U64 * readsize)1280*22ce4affSfengbojiang FIO_compressZstdFrame(FIO_ctx_t* const fCtx,
1281*22ce4affSfengbojiang                       FIO_prefs_t* const prefs,
1282*22ce4affSfengbojiang                       const cRess_t* ressPtr,
1283*22ce4affSfengbojiang                       const char* srcFileName, U64 fileSize,
1284*22ce4affSfengbojiang                       int compressionLevel, U64* readsize)
1285*22ce4affSfengbojiang {
1286*22ce4affSfengbojiang     cRess_t const ress = *ressPtr;
1287*22ce4affSfengbojiang     FILE* const srcFile = ress.srcFile;
1288*22ce4affSfengbojiang     FILE* const dstFile = ress.dstFile;
1289*22ce4affSfengbojiang     U64 compressedfilesize = 0;
1290*22ce4affSfengbojiang     ZSTD_EndDirective directive = ZSTD_e_continue;
1291*22ce4affSfengbojiang 
1292*22ce4affSfengbojiang     /* stats */
1293*22ce4affSfengbojiang     ZSTD_frameProgression previous_zfp_update = { 0, 0, 0, 0, 0, 0 };
1294*22ce4affSfengbojiang     ZSTD_frameProgression previous_zfp_correction = { 0, 0, 0, 0, 0, 0 };
1295*22ce4affSfengbojiang     typedef enum { noChange, slower, faster } speedChange_e;
1296*22ce4affSfengbojiang     speedChange_e speedChange = noChange;
1297*22ce4affSfengbojiang     unsigned flushWaiting = 0;
1298*22ce4affSfengbojiang     unsigned inputPresented = 0;
1299*22ce4affSfengbojiang     unsigned inputBlocked = 0;
1300*22ce4affSfengbojiang     unsigned lastJobID = 0;
1301*22ce4affSfengbojiang 
1302*22ce4affSfengbojiang     DISPLAYLEVEL(6, "compression using zstd format \n");
1303*22ce4affSfengbojiang 
1304*22ce4affSfengbojiang     /* init */
1305*22ce4affSfengbojiang     if (fileSize != UTIL_FILESIZE_UNKNOWN) {
1306*22ce4affSfengbojiang         CHECK(ZSTD_CCtx_setPledgedSrcSize(ress.cctx, fileSize));
1307*22ce4affSfengbojiang     } else if (prefs->streamSrcSize > 0) {
1308*22ce4affSfengbojiang       /* unknown source size; use the declared stream size */
1309*22ce4affSfengbojiang       CHECK( ZSTD_CCtx_setPledgedSrcSize(ress.cctx, prefs->streamSrcSize) );
1310*22ce4affSfengbojiang     }
1311*22ce4affSfengbojiang     (void)srcFileName;
1312*22ce4affSfengbojiang 
1313*22ce4affSfengbojiang     /* Main compression loop */
1314*22ce4affSfengbojiang     do {
1315*22ce4affSfengbojiang         size_t stillToFlush;
1316*22ce4affSfengbojiang         /* Fill input Buffer */
1317*22ce4affSfengbojiang         size_t const inSize = fread(ress.srcBuffer, (size_t)1, ress.srcBufferSize, srcFile);
1318*22ce4affSfengbojiang         ZSTD_inBuffer inBuff = { ress.srcBuffer, inSize, 0 };
1319*22ce4affSfengbojiang         DISPLAYLEVEL(6, "fread %u bytes from source \n", (unsigned)inSize);
1320*22ce4affSfengbojiang         *readsize += inSize;
1321*22ce4affSfengbojiang 
1322*22ce4affSfengbojiang         if ((inSize == 0) || (*readsize == fileSize))
1323*22ce4affSfengbojiang             directive = ZSTD_e_end;
1324*22ce4affSfengbojiang 
1325*22ce4affSfengbojiang         stillToFlush = 1;
1326*22ce4affSfengbojiang         while ((inBuff.pos != inBuff.size)   /* input buffer must be entirely ingested */
1327*22ce4affSfengbojiang             || (directive == ZSTD_e_end && stillToFlush != 0) ) {
1328*22ce4affSfengbojiang 
1329*22ce4affSfengbojiang             size_t const oldIPos = inBuff.pos;
1330*22ce4affSfengbojiang             ZSTD_outBuffer outBuff = { ress.dstBuffer, ress.dstBufferSize, 0 };
1331*22ce4affSfengbojiang             size_t const toFlushNow = ZSTD_toFlushNow(ress.cctx);
1332*22ce4affSfengbojiang             CHECK_V(stillToFlush, ZSTD_compressStream2(ress.cctx, &outBuff, &inBuff, directive));
1333*22ce4affSfengbojiang 
1334*22ce4affSfengbojiang             /* count stats */
1335*22ce4affSfengbojiang             inputPresented++;
1336*22ce4affSfengbojiang             if (oldIPos == inBuff.pos) inputBlocked++;  /* input buffer is full and can't take any more : input speed is faster than consumption rate */
1337*22ce4affSfengbojiang             if (!toFlushNow) flushWaiting = 1;
1338*22ce4affSfengbojiang 
1339*22ce4affSfengbojiang             /* Write compressed stream */
1340*22ce4affSfengbojiang             DISPLAYLEVEL(6, "ZSTD_compress_generic(end:%u) => input pos(%u)<=(%u)size ; output generated %u bytes \n",
1341*22ce4affSfengbojiang                             (unsigned)directive, (unsigned)inBuff.pos, (unsigned)inBuff.size, (unsigned)outBuff.pos);
1342*22ce4affSfengbojiang             if (outBuff.pos) {
1343*22ce4affSfengbojiang                 size_t const sizeCheck = fwrite(ress.dstBuffer, 1, outBuff.pos, dstFile);
1344*22ce4affSfengbojiang                 if (sizeCheck != outBuff.pos)
1345*22ce4affSfengbojiang                     EXM_THROW(25, "Write error : %s (cannot write compressed block)",
1346*22ce4affSfengbojiang                                     strerror(errno));
1347*22ce4affSfengbojiang                 compressedfilesize += outBuff.pos;
1348*22ce4affSfengbojiang             }
1349*22ce4affSfengbojiang 
1350*22ce4affSfengbojiang             /* display notification; and adapt compression level */
1351*22ce4affSfengbojiang             if (READY_FOR_UPDATE()) {
1352*22ce4affSfengbojiang                 ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress.cctx);
1353*22ce4affSfengbojiang                 double const cShare = (double)zfp.produced / (zfp.consumed + !zfp.consumed/*avoid div0*/) * 100;
1354*22ce4affSfengbojiang 
1355*22ce4affSfengbojiang                 /* display progress notifications */
1356*22ce4affSfengbojiang                 if (g_display_prefs.displayLevel >= 3) {
1357*22ce4affSfengbojiang                     DISPLAYUPDATE(3, "\r(L%i) Buffered :%4u MB - Consumed :%4u MB - Compressed :%4u MB => %.2f%% ",
1358*22ce4affSfengbojiang                                 compressionLevel,
1359*22ce4affSfengbojiang                                 (unsigned)((zfp.ingested - zfp.consumed) >> 20),
1360*22ce4affSfengbojiang                                 (unsigned)(zfp.consumed >> 20),
1361*22ce4affSfengbojiang                                 (unsigned)(zfp.produced >> 20),
1362*22ce4affSfengbojiang                                 cShare );
1363*22ce4affSfengbojiang                 } else {   /* summarized notifications if == 2 */
1364*22ce4affSfengbojiang                     DISPLAYLEVEL(2, "\r%79s\r", "");    /* Clear out the current displayed line */
1365*22ce4affSfengbojiang                     if (fCtx->nbFilesTotal > 1) {
1366*22ce4affSfengbojiang                         size_t srcFileNameSize = strlen(srcFileName);
1367*22ce4affSfengbojiang                         /* Ensure that the string we print is roughly the same size each time */
1368*22ce4affSfengbojiang                         if (srcFileNameSize > 18) {
1369*22ce4affSfengbojiang                             const char* truncatedSrcFileName = srcFileName + srcFileNameSize - 15;
1370*22ce4affSfengbojiang                             DISPLAYLEVEL(2, "Compress: %u/%u files. Current: ...%s ",
1371*22ce4affSfengbojiang                                          fCtx->currFileIdx+1, fCtx->nbFilesTotal, truncatedSrcFileName);
1372*22ce4affSfengbojiang                         } else {
1373*22ce4affSfengbojiang                             DISPLAYLEVEL(2, "Compress: %u/%u files. Current: %*s ",
1374*22ce4affSfengbojiang                                          fCtx->currFileIdx+1, fCtx->nbFilesTotal, (int)(18-srcFileNameSize), srcFileName);
1375*22ce4affSfengbojiang                         }
1376*22ce4affSfengbojiang                     }
1377*22ce4affSfengbojiang                     DISPLAYLEVEL(2, "Read : %2u ", (unsigned)(zfp.consumed >> 20));
1378*22ce4affSfengbojiang                     if (fileSize != UTIL_FILESIZE_UNKNOWN)
1379*22ce4affSfengbojiang                         DISPLAYLEVEL(2, "/ %2u ", (unsigned)(fileSize >> 20));
1380*22ce4affSfengbojiang                     DISPLAYLEVEL(2, "MB ==> %2.f%%", cShare);
1381*22ce4affSfengbojiang                     DELAY_NEXT_UPDATE();
1382*22ce4affSfengbojiang                 }
1383*22ce4affSfengbojiang 
1384*22ce4affSfengbojiang                 /* adaptive mode : statistics measurement and speed correction */
1385*22ce4affSfengbojiang                 if (prefs->adaptiveMode) {
1386*22ce4affSfengbojiang 
1387*22ce4affSfengbojiang                     /* check output speed */
1388*22ce4affSfengbojiang                     if (zfp.currentJobID > 1) {  /* only possible if nbWorkers >= 1 */
1389*22ce4affSfengbojiang 
1390*22ce4affSfengbojiang                         unsigned long long newlyProduced = zfp.produced - previous_zfp_update.produced;
1391*22ce4affSfengbojiang                         unsigned long long newlyFlushed = zfp.flushed - previous_zfp_update.flushed;
1392*22ce4affSfengbojiang                         assert(zfp.produced >= previous_zfp_update.produced);
1393*22ce4affSfengbojiang                         assert(prefs->nbWorkers >= 1);
1394*22ce4affSfengbojiang 
1395*22ce4affSfengbojiang                         /* test if compression is blocked
1396*22ce4affSfengbojiang                          * either because output is slow and all buffers are full
1397*22ce4affSfengbojiang                          * or because input is slow and no job can start while waiting for at least one buffer to be filled.
1398*22ce4affSfengbojiang                          * note : exclude starting part, since currentJobID > 1 */
1399*22ce4affSfengbojiang                         if ( (zfp.consumed == previous_zfp_update.consumed)   /* no data compressed : no data available, or no more buffer to compress to, OR compression is really slow (compression of a single block is slower than update rate)*/
1400*22ce4affSfengbojiang                           && (zfp.nbActiveWorkers == 0)                       /* confirmed : no compression ongoing */
1401*22ce4affSfengbojiang                           ) {
1402*22ce4affSfengbojiang                             DISPLAYLEVEL(6, "all buffers full : compression stopped => slow down \n")
1403*22ce4affSfengbojiang                             speedChange = slower;
1404*22ce4affSfengbojiang                         }
1405*22ce4affSfengbojiang 
1406*22ce4affSfengbojiang                         previous_zfp_update = zfp;
1407*22ce4affSfengbojiang 
1408*22ce4affSfengbojiang                         if ( (newlyProduced > (newlyFlushed * 9 / 8))   /* compression produces more data than output can flush (though production can be spiky, due to work unit : (N==4)*block sizes) */
1409*22ce4affSfengbojiang                           && (flushWaiting == 0)                        /* flush speed was never slowed by lack of production, so it's operating at max capacity */
1410*22ce4affSfengbojiang                           ) {
1411*22ce4affSfengbojiang                             DISPLAYLEVEL(6, "compression faster than flush (%llu > %llu), and flushed was never slowed down by lack of production => slow down \n", newlyProduced, newlyFlushed);
1412*22ce4affSfengbojiang                             speedChange = slower;
1413*22ce4affSfengbojiang                         }
1414*22ce4affSfengbojiang                         flushWaiting = 0;
1415*22ce4affSfengbojiang                     }
1416*22ce4affSfengbojiang 
1417*22ce4affSfengbojiang                     /* course correct only if there is at least one new job completed */
1418*22ce4affSfengbojiang                     if (zfp.currentJobID > lastJobID) {
1419*22ce4affSfengbojiang                         DISPLAYLEVEL(6, "compression level adaptation check \n")
1420*22ce4affSfengbojiang 
1421*22ce4affSfengbojiang                         /* check input speed */
1422*22ce4affSfengbojiang                         if (zfp.currentJobID > (unsigned)(prefs->nbWorkers+1)) {   /* warm up period, to fill all workers */
1423*22ce4affSfengbojiang                             if (inputBlocked <= 0) {
1424*22ce4affSfengbojiang                                 DISPLAYLEVEL(6, "input is never blocked => input is slower than ingestion \n");
1425*22ce4affSfengbojiang                                 speedChange = slower;
1426*22ce4affSfengbojiang                             } else if (speedChange == noChange) {
1427*22ce4affSfengbojiang                                 unsigned long long newlyIngested = zfp.ingested - previous_zfp_correction.ingested;
1428*22ce4affSfengbojiang                                 unsigned long long newlyConsumed = zfp.consumed - previous_zfp_correction.consumed;
1429*22ce4affSfengbojiang                                 unsigned long long newlyProduced = zfp.produced - previous_zfp_correction.produced;
1430*22ce4affSfengbojiang                                 unsigned long long newlyFlushed  = zfp.flushed  - previous_zfp_correction.flushed;
1431*22ce4affSfengbojiang                                 previous_zfp_correction = zfp;
1432*22ce4affSfengbojiang                                 assert(inputPresented > 0);
1433*22ce4affSfengbojiang                                 DISPLAYLEVEL(6, "input blocked %u/%u(%.2f) - ingested:%u vs %u:consumed - flushed:%u vs %u:produced \n",
1434*22ce4affSfengbojiang                                                 inputBlocked, inputPresented, (double)inputBlocked/inputPresented*100,
1435*22ce4affSfengbojiang                                                 (unsigned)newlyIngested, (unsigned)newlyConsumed,
1436*22ce4affSfengbojiang                                                 (unsigned)newlyFlushed, (unsigned)newlyProduced);
1437*22ce4affSfengbojiang                                 if ( (inputBlocked > inputPresented / 8)     /* input is waiting often, because input buffers is full : compression or output too slow */
1438*22ce4affSfengbojiang                                   && (newlyFlushed * 33 / 32 > newlyProduced)  /* flush everything that is produced */
1439*22ce4affSfengbojiang                                   && (newlyIngested * 33 / 32 > newlyConsumed) /* input speed as fast or faster than compression speed */
1440*22ce4affSfengbojiang                                 ) {
1441*22ce4affSfengbojiang                                     DISPLAYLEVEL(6, "recommend faster as in(%llu) >= (%llu)comp(%llu) <= out(%llu) \n",
1442*22ce4affSfengbojiang                                                     newlyIngested, newlyConsumed, newlyProduced, newlyFlushed);
1443*22ce4affSfengbojiang                                     speedChange = faster;
1444*22ce4affSfengbojiang                                 }
1445*22ce4affSfengbojiang                             }
1446*22ce4affSfengbojiang                             inputBlocked = 0;
1447*22ce4affSfengbojiang                             inputPresented = 0;
1448*22ce4affSfengbojiang                         }
1449*22ce4affSfengbojiang 
1450*22ce4affSfengbojiang                         if (speedChange == slower) {
1451*22ce4affSfengbojiang                             DISPLAYLEVEL(6, "slower speed , higher compression \n")
1452*22ce4affSfengbojiang                             compressionLevel ++;
1453*22ce4affSfengbojiang                             if (compressionLevel > ZSTD_maxCLevel()) compressionLevel = ZSTD_maxCLevel();
1454*22ce4affSfengbojiang                             if (compressionLevel > prefs->maxAdaptLevel) compressionLevel = prefs->maxAdaptLevel;
1455*22ce4affSfengbojiang                             compressionLevel += (compressionLevel == 0);   /* skip 0 */
1456*22ce4affSfengbojiang                             ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_compressionLevel, compressionLevel);
1457*22ce4affSfengbojiang                         }
1458*22ce4affSfengbojiang                         if (speedChange == faster) {
1459*22ce4affSfengbojiang                             DISPLAYLEVEL(6, "faster speed , lighter compression \n")
1460*22ce4affSfengbojiang                             compressionLevel --;
1461*22ce4affSfengbojiang                             if (compressionLevel < prefs->minAdaptLevel) compressionLevel = prefs->minAdaptLevel;
1462*22ce4affSfengbojiang                             compressionLevel -= (compressionLevel == 0);   /* skip 0 */
1463*22ce4affSfengbojiang                             ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_compressionLevel, compressionLevel);
1464*22ce4affSfengbojiang                         }
1465*22ce4affSfengbojiang                         speedChange = noChange;
1466*22ce4affSfengbojiang 
1467*22ce4affSfengbojiang                         lastJobID = zfp.currentJobID;
1468*22ce4affSfengbojiang                     }  /* if (zfp.currentJobID > lastJobID) */
1469*22ce4affSfengbojiang                 }  /* if (g_adaptiveMode) */
1470*22ce4affSfengbojiang             }  /* if (READY_FOR_UPDATE()) */
1471*22ce4affSfengbojiang         }  /* while ((inBuff.pos != inBuff.size) */
1472*22ce4affSfengbojiang     } while (directive != ZSTD_e_end);
1473*22ce4affSfengbojiang 
1474*22ce4affSfengbojiang     if (ferror(srcFile)) {
1475*22ce4affSfengbojiang         EXM_THROW(26, "Read error : I/O error");
1476*22ce4affSfengbojiang     }
1477*22ce4affSfengbojiang     if (fileSize != UTIL_FILESIZE_UNKNOWN && *readsize != fileSize) {
1478*22ce4affSfengbojiang         EXM_THROW(27, "Read error : Incomplete read : %llu / %llu B",
1479*22ce4affSfengbojiang                 (unsigned long long)*readsize, (unsigned long long)fileSize);
1480*22ce4affSfengbojiang     }
1481*22ce4affSfengbojiang 
1482*22ce4affSfengbojiang     return compressedfilesize;
1483*22ce4affSfengbojiang }
1484*22ce4affSfengbojiang 
1485*22ce4affSfengbojiang /*! FIO_compressFilename_internal() :
1486*22ce4affSfengbojiang  *  same as FIO_compressFilename_extRess(), with `ress.desFile` already opened.
1487*22ce4affSfengbojiang  *  @return : 0 : compression completed correctly,
1488*22ce4affSfengbojiang  *            1 : missing or pb opening srcFileName
1489*22ce4affSfengbojiang  */
1490*22ce4affSfengbojiang static int
FIO_compressFilename_internal(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,cRess_t ress,const char * dstFileName,const char * srcFileName,int compressionLevel)1491*22ce4affSfengbojiang FIO_compressFilename_internal(FIO_ctx_t* const fCtx,
1492*22ce4affSfengbojiang                               FIO_prefs_t* const prefs,
1493*22ce4affSfengbojiang                               cRess_t ress,
1494*22ce4affSfengbojiang                               const char* dstFileName, const char* srcFileName,
1495*22ce4affSfengbojiang                               int compressionLevel)
1496*22ce4affSfengbojiang {
1497*22ce4affSfengbojiang     UTIL_time_t const timeStart = UTIL_getTime();
1498*22ce4affSfengbojiang     clock_t const cpuStart = clock();
1499*22ce4affSfengbojiang     U64 readsize = 0;
1500*22ce4affSfengbojiang     U64 compressedfilesize = 0;
1501*22ce4affSfengbojiang     U64 const fileSize = UTIL_getFileSize(srcFileName);
1502*22ce4affSfengbojiang     DISPLAYLEVEL(5, "%s: %u bytes \n", srcFileName, (unsigned)fileSize);
1503*22ce4affSfengbojiang 
1504*22ce4affSfengbojiang     /* compression format selection */
1505*22ce4affSfengbojiang     switch (prefs->compressionType) {
1506*22ce4affSfengbojiang         default:
1507*22ce4affSfengbojiang         case FIO_zstdCompression:
1508*22ce4affSfengbojiang             compressedfilesize = FIO_compressZstdFrame(fCtx, prefs, &ress, srcFileName, fileSize, compressionLevel, &readsize);
1509*22ce4affSfengbojiang             break;
1510*22ce4affSfengbojiang 
1511*22ce4affSfengbojiang         case FIO_gzipCompression:
1512*22ce4affSfengbojiang #ifdef ZSTD_GZCOMPRESS
1513*22ce4affSfengbojiang             compressedfilesize = FIO_compressGzFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize);
1514*22ce4affSfengbojiang #else
1515*22ce4affSfengbojiang             (void)compressionLevel;
1516*22ce4affSfengbojiang             EXM_THROW(20, "zstd: %s: file cannot be compressed as gzip (zstd compiled without ZSTD_GZCOMPRESS) -- ignored \n",
1517*22ce4affSfengbojiang                             srcFileName);
1518*22ce4affSfengbojiang #endif
1519*22ce4affSfengbojiang             break;
1520*22ce4affSfengbojiang 
1521*22ce4affSfengbojiang         case FIO_xzCompression:
1522*22ce4affSfengbojiang         case FIO_lzmaCompression:
1523*22ce4affSfengbojiang #ifdef ZSTD_LZMACOMPRESS
1524*22ce4affSfengbojiang             compressedfilesize = FIO_compressLzmaFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize, prefs->compressionType==FIO_lzmaCompression);
1525*22ce4affSfengbojiang #else
1526*22ce4affSfengbojiang             (void)compressionLevel;
1527*22ce4affSfengbojiang             EXM_THROW(20, "zstd: %s: file cannot be compressed as xz/lzma (zstd compiled without ZSTD_LZMACOMPRESS) -- ignored \n",
1528*22ce4affSfengbojiang                             srcFileName);
1529*22ce4affSfengbojiang #endif
1530*22ce4affSfengbojiang             break;
1531*22ce4affSfengbojiang 
1532*22ce4affSfengbojiang         case FIO_lz4Compression:
1533*22ce4affSfengbojiang #ifdef ZSTD_LZ4COMPRESS
1534*22ce4affSfengbojiang             compressedfilesize = FIO_compressLz4Frame(&ress, srcFileName, fileSize, compressionLevel, prefs->checksumFlag, &readsize);
1535*22ce4affSfengbojiang #else
1536*22ce4affSfengbojiang             (void)compressionLevel;
1537*22ce4affSfengbojiang             EXM_THROW(20, "zstd: %s: file cannot be compressed as lz4 (zstd compiled without ZSTD_LZ4COMPRESS) -- ignored \n",
1538*22ce4affSfengbojiang                             srcFileName);
1539*22ce4affSfengbojiang #endif
1540*22ce4affSfengbojiang             break;
1541*22ce4affSfengbojiang     }
1542*22ce4affSfengbojiang 
1543*22ce4affSfengbojiang     /* Status */
1544*22ce4affSfengbojiang     fCtx->totalBytesInput += (size_t)readsize;
1545*22ce4affSfengbojiang     fCtx->totalBytesOutput += (size_t)compressedfilesize;
1546*22ce4affSfengbojiang     DISPLAYLEVEL(2, "\r%79s\r", "");
1547*22ce4affSfengbojiang     if (g_display_prefs.displayLevel >= 2 &&
1548*22ce4affSfengbojiang         !fCtx->hasStdoutOutput &&
1549*22ce4affSfengbojiang         (g_display_prefs.displayLevel >= 3 || fCtx->nbFilesTotal <= 1)) {
1550*22ce4affSfengbojiang         if (readsize == 0) {
1551*22ce4affSfengbojiang             DISPLAYLEVEL(2,"%-20s :  (%6llu => %6llu bytes, %s) \n",
1552*22ce4affSfengbojiang                 srcFileName,
1553*22ce4affSfengbojiang                 (unsigned long long)readsize, (unsigned long long) compressedfilesize,
1554*22ce4affSfengbojiang                 dstFileName);
1555*22ce4affSfengbojiang         } else {
1556*22ce4affSfengbojiang             DISPLAYLEVEL(2,"%-20s :%6.2f%%   (%6llu => %6llu bytes, %s) \n",
1557*22ce4affSfengbojiang                 srcFileName,
1558*22ce4affSfengbojiang                 (double)compressedfilesize / readsize * 100,
1559*22ce4affSfengbojiang                 (unsigned long long)readsize, (unsigned long long) compressedfilesize,
1560*22ce4affSfengbojiang                 dstFileName);
1561*22ce4affSfengbojiang         }
1562*22ce4affSfengbojiang     }
1563*22ce4affSfengbojiang 
1564*22ce4affSfengbojiang     /* Elapsed Time and CPU Load */
1565*22ce4affSfengbojiang     {   clock_t const cpuEnd = clock();
1566*22ce4affSfengbojiang         double const cpuLoad_s = (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC;
1567*22ce4affSfengbojiang         U64 const timeLength_ns = UTIL_clockSpanNano(timeStart);
1568*22ce4affSfengbojiang         double const timeLength_s = (double)timeLength_ns / 1000000000;
1569*22ce4affSfengbojiang         double const cpuLoad_pct = (cpuLoad_s / timeLength_s) * 100;
1570*22ce4affSfengbojiang         DISPLAYLEVEL(4, "%-20s : Completed in %.2f sec  (cpu load : %.0f%%)\n",
1571*22ce4affSfengbojiang                         srcFileName, timeLength_s, cpuLoad_pct);
1572*22ce4affSfengbojiang     }
1573*22ce4affSfengbojiang     return 0;
1574*22ce4affSfengbojiang }
1575*22ce4affSfengbojiang 
1576*22ce4affSfengbojiang 
1577*22ce4affSfengbojiang /*! FIO_compressFilename_dstFile() :
1578*22ce4affSfengbojiang  *  open dstFileName, or pass-through if ress.dstFile != NULL,
1579*22ce4affSfengbojiang  *  then start compression with FIO_compressFilename_internal().
1580*22ce4affSfengbojiang  *  Manages source removal (--rm) and file permissions transfer.
1581*22ce4affSfengbojiang  *  note : ress.srcFile must be != NULL,
1582*22ce4affSfengbojiang  *  so reach this function through FIO_compressFilename_srcFile().
1583*22ce4affSfengbojiang  *  @return : 0 : compression completed correctly,
1584*22ce4affSfengbojiang  *            1 : pb
1585*22ce4affSfengbojiang  */
FIO_compressFilename_dstFile(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,cRess_t ress,const char * dstFileName,const char * srcFileName,int compressionLevel)1586*22ce4affSfengbojiang static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx,
1587*22ce4affSfengbojiang                                         FIO_prefs_t* const prefs,
1588*22ce4affSfengbojiang                                         cRess_t ress,
1589*22ce4affSfengbojiang                                         const char* dstFileName,
1590*22ce4affSfengbojiang                                         const char* srcFileName,
1591*22ce4affSfengbojiang                                         int compressionLevel)
1592*22ce4affSfengbojiang {
1593*22ce4affSfengbojiang     int closeDstFile = 0;
1594*22ce4affSfengbojiang     int result;
1595*22ce4affSfengbojiang     stat_t statbuf;
1596*22ce4affSfengbojiang     int transfer_permissions = 0;
1597*22ce4affSfengbojiang     assert(ress.srcFile != NULL);
1598*22ce4affSfengbojiang     if (ress.dstFile == NULL) {
1599*22ce4affSfengbojiang         closeDstFile = 1;
1600*22ce4affSfengbojiang         DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: opening dst: %s \n", dstFileName);
1601*22ce4affSfengbojiang         ress.dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName);
1602*22ce4affSfengbojiang         if (ress.dstFile==NULL) return 1;  /* could not open dstFileName */
1603*22ce4affSfengbojiang         /* Must only be added after FIO_openDstFile() succeeds.
1604*22ce4affSfengbojiang          * Otherwise we may delete the destination file if it already exists,
1605*22ce4affSfengbojiang          * and the user presses Ctrl-C when asked if they wish to overwrite.
1606*22ce4affSfengbojiang          */
1607*22ce4affSfengbojiang         addHandler(dstFileName);
1608*22ce4affSfengbojiang 
1609*22ce4affSfengbojiang         if ( strcmp (srcFileName, stdinmark)
1610*22ce4affSfengbojiang           && UTIL_stat(srcFileName, &statbuf)
1611*22ce4affSfengbojiang           && UTIL_isRegularFileStat(&statbuf) )
1612*22ce4affSfengbojiang             transfer_permissions = 1;
1613*22ce4affSfengbojiang     }
1614*22ce4affSfengbojiang 
1615*22ce4affSfengbojiang     result = FIO_compressFilename_internal(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel);
1616*22ce4affSfengbojiang 
1617*22ce4affSfengbojiang     if (closeDstFile) {
1618*22ce4affSfengbojiang         FILE* const dstFile = ress.dstFile;
1619*22ce4affSfengbojiang         ress.dstFile = NULL;
1620*22ce4affSfengbojiang 
1621*22ce4affSfengbojiang         clearHandler();
1622*22ce4affSfengbojiang 
1623*22ce4affSfengbojiang         DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: closing dst: %s \n", dstFileName);
1624*22ce4affSfengbojiang         if (fclose(dstFile)) { /* error closing dstFile */
1625*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno));
1626*22ce4affSfengbojiang             result=1;
1627*22ce4affSfengbojiang         }
1628*22ce4affSfengbojiang         if ( (result != 0)  /* operation failure */
1629*22ce4affSfengbojiang           && strcmp(dstFileName, stdoutmark)  /* special case : don't remove() stdout */
1630*22ce4affSfengbojiang           ) {
1631*22ce4affSfengbojiang             FIO_removeFile(dstFileName); /* remove compression artefact; note don't do anything special if remove() fails */
1632*22ce4affSfengbojiang         } else if (transfer_permissions) {
1633*22ce4affSfengbojiang             DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: transferring permissions into dst: %s \n", dstFileName);
1634*22ce4affSfengbojiang             UTIL_setFileStat(dstFileName, &statbuf);
1635*22ce4affSfengbojiang         } else {
1636*22ce4affSfengbojiang             DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: do not transfer permissions into dst: %s \n", dstFileName);
1637*22ce4affSfengbojiang         }
1638*22ce4affSfengbojiang     }
1639*22ce4affSfengbojiang 
1640*22ce4affSfengbojiang     return result;
1641*22ce4affSfengbojiang }
1642*22ce4affSfengbojiang 
1643*22ce4affSfengbojiang /* List used to compare file extensions (used with --exclude-compressed flag)
1644*22ce4affSfengbojiang * Different from the suffixList and should only apply to ZSTD compress operationResult
1645*22ce4affSfengbojiang */
1646*22ce4affSfengbojiang static const char *compressedFileExtensions[] = {
1647*22ce4affSfengbojiang     ZSTD_EXTENSION,
1648*22ce4affSfengbojiang     TZSTD_EXTENSION,
1649*22ce4affSfengbojiang     GZ_EXTENSION,
1650*22ce4affSfengbojiang     TGZ_EXTENSION,
1651*22ce4affSfengbojiang     LZMA_EXTENSION,
1652*22ce4affSfengbojiang     XZ_EXTENSION,
1653*22ce4affSfengbojiang     TXZ_EXTENSION,
1654*22ce4affSfengbojiang     LZ4_EXTENSION,
1655*22ce4affSfengbojiang     TLZ4_EXTENSION,
1656*22ce4affSfengbojiang     NULL
1657*22ce4affSfengbojiang };
1658*22ce4affSfengbojiang 
1659*22ce4affSfengbojiang /*! FIO_compressFilename_srcFile() :
1660*22ce4affSfengbojiang  *  @return : 0 : compression completed correctly,
1661*22ce4affSfengbojiang  *            1 : missing or pb opening srcFileName
1662*22ce4affSfengbojiang  */
1663*22ce4affSfengbojiang static int
FIO_compressFilename_srcFile(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,cRess_t ress,const char * dstFileName,const char * srcFileName,int compressionLevel)1664*22ce4affSfengbojiang FIO_compressFilename_srcFile(FIO_ctx_t* const fCtx,
1665*22ce4affSfengbojiang                              FIO_prefs_t* const prefs,
1666*22ce4affSfengbojiang                              cRess_t ress,
1667*22ce4affSfengbojiang                              const char* dstFileName,
1668*22ce4affSfengbojiang                              const char* srcFileName,
1669*22ce4affSfengbojiang                              int compressionLevel)
1670*22ce4affSfengbojiang {
1671*22ce4affSfengbojiang     int result;
1672*22ce4affSfengbojiang     DISPLAYLEVEL(6, "FIO_compressFilename_srcFile: %s \n", srcFileName);
1673*22ce4affSfengbojiang 
1674*22ce4affSfengbojiang     /* ensure src is not a directory */
1675*22ce4affSfengbojiang     if (UTIL_isDirectory(srcFileName)) {
1676*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
1677*22ce4affSfengbojiang         return 1;
1678*22ce4affSfengbojiang     }
1679*22ce4affSfengbojiang 
1680*22ce4affSfengbojiang     /* ensure src is not the same as dict (if present) */
1681*22ce4affSfengbojiang     if (ress.dictFileName != NULL && UTIL_isSameFile(srcFileName, ress.dictFileName)) {
1682*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: cannot use %s as an input file and dictionary \n", srcFileName);
1683*22ce4affSfengbojiang         return 1;
1684*22ce4affSfengbojiang     }
1685*22ce4affSfengbojiang 
1686*22ce4affSfengbojiang     /* Check if "srcFile" is compressed. Only done if --exclude-compressed flag is used
1687*22ce4affSfengbojiang     * YES => ZSTD will skip compression of the file and will return 0.
1688*22ce4affSfengbojiang     * NO => ZSTD will resume with compress operation.
1689*22ce4affSfengbojiang     */
1690*22ce4affSfengbojiang     if (prefs->excludeCompressedFiles == 1 && UTIL_isCompressedFile(srcFileName, compressedFileExtensions)) {
1691*22ce4affSfengbojiang         DISPLAYLEVEL(4, "File is already compressed : %s \n", srcFileName);
1692*22ce4affSfengbojiang         return 0;
1693*22ce4affSfengbojiang     }
1694*22ce4affSfengbojiang 
1695*22ce4affSfengbojiang     ress.srcFile = FIO_openSrcFile(srcFileName);
1696*22ce4affSfengbojiang     if (ress.srcFile == NULL) return 1;   /* srcFile could not be opened */
1697*22ce4affSfengbojiang 
1698*22ce4affSfengbojiang     result = FIO_compressFilename_dstFile(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel);
1699*22ce4affSfengbojiang 
1700*22ce4affSfengbojiang     fclose(ress.srcFile);
1701*22ce4affSfengbojiang     ress.srcFile = NULL;
1702*22ce4affSfengbojiang     if ( prefs->removeSrcFile   /* --rm */
1703*22ce4affSfengbojiang       && result == 0       /* success */
1704*22ce4affSfengbojiang       && strcmp(srcFileName, stdinmark)   /* exception : don't erase stdin */
1705*22ce4affSfengbojiang       ) {
1706*22ce4affSfengbojiang         /* We must clear the handler, since after this point calling it would
1707*22ce4affSfengbojiang          * delete both the source and destination files.
1708*22ce4affSfengbojiang          */
1709*22ce4affSfengbojiang         clearHandler();
1710*22ce4affSfengbojiang         if (FIO_removeFile(srcFileName))
1711*22ce4affSfengbojiang             EXM_THROW(1, "zstd: %s: %s", srcFileName, strerror(errno));
1712*22ce4affSfengbojiang     }
1713*22ce4affSfengbojiang     return result;
1714*22ce4affSfengbojiang }
1715*22ce4affSfengbojiang 
FIO_compressFilename(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,const char * dstFileName,const char * srcFileName,const char * dictFileName,int compressionLevel,ZSTD_compressionParameters comprParams)1716*22ce4affSfengbojiang int FIO_compressFilename(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, const char* dstFileName,
1717*22ce4affSfengbojiang                          const char* srcFileName, const char* dictFileName,
1718*22ce4affSfengbojiang                          int compressionLevel, ZSTD_compressionParameters comprParams)
1719*22ce4affSfengbojiang {
1720*22ce4affSfengbojiang     cRess_t const ress = FIO_createCResources(prefs, dictFileName, UTIL_getFileSize(srcFileName), compressionLevel, comprParams);
1721*22ce4affSfengbojiang     int const result = FIO_compressFilename_srcFile(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel);
1722*22ce4affSfengbojiang 
1723*22ce4affSfengbojiang #define DISPLAY_LEVEL_DEFAULT 2
1724*22ce4affSfengbojiang 
1725*22ce4affSfengbojiang     FIO_freeCResources(&ress);
1726*22ce4affSfengbojiang     return result;
1727*22ce4affSfengbojiang }
1728*22ce4affSfengbojiang 
1729*22ce4affSfengbojiang /* FIO_determineCompressedName() :
1730*22ce4affSfengbojiang  * create a destination filename for compressed srcFileName.
1731*22ce4affSfengbojiang  * @return a pointer to it.
1732*22ce4affSfengbojiang  * This function never returns an error (it may abort() in case of pb)
1733*22ce4affSfengbojiang  */
1734*22ce4affSfengbojiang static const char*
FIO_determineCompressedName(const char * srcFileName,const char * outDirName,const char * suffix)1735*22ce4affSfengbojiang FIO_determineCompressedName(const char* srcFileName, const char* outDirName, const char* suffix)
1736*22ce4affSfengbojiang {
1737*22ce4affSfengbojiang     static size_t dfnbCapacity = 0;
1738*22ce4affSfengbojiang     static char* dstFileNameBuffer = NULL;   /* using static allocation : this function cannot be multi-threaded */
1739*22ce4affSfengbojiang     char* outDirFilename = NULL;
1740*22ce4affSfengbojiang     size_t sfnSize = strlen(srcFileName);
1741*22ce4affSfengbojiang     size_t const srcSuffixLen = strlen(suffix);
1742*22ce4affSfengbojiang     if (outDirName) {
1743*22ce4affSfengbojiang         outDirFilename = FIO_createFilename_fromOutDir(srcFileName, outDirName, srcSuffixLen);
1744*22ce4affSfengbojiang         sfnSize = strlen(outDirFilename);
1745*22ce4affSfengbojiang         assert(outDirFilename != NULL);
1746*22ce4affSfengbojiang     }
1747*22ce4affSfengbojiang 
1748*22ce4affSfengbojiang     if (dfnbCapacity <= sfnSize+srcSuffixLen+1) {
1749*22ce4affSfengbojiang         /* resize buffer for dstName */
1750*22ce4affSfengbojiang         free(dstFileNameBuffer);
1751*22ce4affSfengbojiang         dfnbCapacity = sfnSize + srcSuffixLen + 30;
1752*22ce4affSfengbojiang         dstFileNameBuffer = (char*)malloc(dfnbCapacity);
1753*22ce4affSfengbojiang         if (!dstFileNameBuffer) {
1754*22ce4affSfengbojiang             EXM_THROW(30, "zstd: %s", strerror(errno));
1755*22ce4affSfengbojiang         }
1756*22ce4affSfengbojiang     }
1757*22ce4affSfengbojiang     assert(dstFileNameBuffer != NULL);
1758*22ce4affSfengbojiang 
1759*22ce4affSfengbojiang     if (outDirFilename) {
1760*22ce4affSfengbojiang         memcpy(dstFileNameBuffer, outDirFilename, sfnSize);
1761*22ce4affSfengbojiang         free(outDirFilename);
1762*22ce4affSfengbojiang     } else {
1763*22ce4affSfengbojiang         memcpy(dstFileNameBuffer, srcFileName, sfnSize);
1764*22ce4affSfengbojiang     }
1765*22ce4affSfengbojiang     memcpy(dstFileNameBuffer+sfnSize, suffix, srcSuffixLen+1 /* Include terminating null */);
1766*22ce4affSfengbojiang     return dstFileNameBuffer;
1767*22ce4affSfengbojiang }
1768*22ce4affSfengbojiang 
FIO_getLargestFileSize(const char ** inFileNames,unsigned nbFiles)1769*22ce4affSfengbojiang static unsigned long long FIO_getLargestFileSize(const char** inFileNames, unsigned nbFiles)
1770*22ce4affSfengbojiang {
1771*22ce4affSfengbojiang     size_t i;
1772*22ce4affSfengbojiang     unsigned long long fileSize, maxFileSize = 0;
1773*22ce4affSfengbojiang     for (i = 0; i < nbFiles; i++) {
1774*22ce4affSfengbojiang         fileSize = UTIL_getFileSize(inFileNames[i]);
1775*22ce4affSfengbojiang         maxFileSize = fileSize > maxFileSize ? fileSize : maxFileSize;
1776*22ce4affSfengbojiang     }
1777*22ce4affSfengbojiang     return maxFileSize;
1778*22ce4affSfengbojiang }
1779*22ce4affSfengbojiang 
1780*22ce4affSfengbojiang /* FIO_compressMultipleFilenames() :
1781*22ce4affSfengbojiang  * compress nbFiles files
1782*22ce4affSfengbojiang  * into either one destination (outFileName),
1783*22ce4affSfengbojiang  * or into one file each (outFileName == NULL, but suffix != NULL),
1784*22ce4affSfengbojiang  * or into a destination folder (specified with -O)
1785*22ce4affSfengbojiang  */
FIO_compressMultipleFilenames(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,const char ** inFileNamesTable,const char * outMirroredRootDirName,const char * outDirName,const char * outFileName,const char * suffix,const char * dictFileName,int compressionLevel,ZSTD_compressionParameters comprParams)1786*22ce4affSfengbojiang int FIO_compressMultipleFilenames(FIO_ctx_t* const fCtx,
1787*22ce4affSfengbojiang                                   FIO_prefs_t* const prefs,
1788*22ce4affSfengbojiang                                   const char** inFileNamesTable,
1789*22ce4affSfengbojiang                                   const char* outMirroredRootDirName,
1790*22ce4affSfengbojiang                                   const char* outDirName,
1791*22ce4affSfengbojiang                                   const char* outFileName, const char* suffix,
1792*22ce4affSfengbojiang                                   const char* dictFileName, int compressionLevel,
1793*22ce4affSfengbojiang                                   ZSTD_compressionParameters comprParams)
1794*22ce4affSfengbojiang {
1795*22ce4affSfengbojiang     int status;
1796*22ce4affSfengbojiang     int error = 0;
1797*22ce4affSfengbojiang     cRess_t ress = FIO_createCResources(prefs, dictFileName,
1798*22ce4affSfengbojiang         FIO_getLargestFileSize(inFileNamesTable, fCtx->nbFilesTotal),
1799*22ce4affSfengbojiang         compressionLevel, comprParams);
1800*22ce4affSfengbojiang 
1801*22ce4affSfengbojiang     /* init */
1802*22ce4affSfengbojiang     assert(outFileName != NULL || suffix != NULL);
1803*22ce4affSfengbojiang     if (outFileName != NULL) {   /* output into a single destination (stdout typically) */
1804*22ce4affSfengbojiang         if (FIO_removeMultiFilesWarning(fCtx, prefs, outFileName, 1 /* displayLevelCutoff */)) {
1805*22ce4affSfengbojiang             FIO_freeCResources(&ress);
1806*22ce4affSfengbojiang             return 1;
1807*22ce4affSfengbojiang         }
1808*22ce4affSfengbojiang         ress.dstFile = FIO_openDstFile(fCtx, prefs, NULL, outFileName);
1809*22ce4affSfengbojiang         if (ress.dstFile == NULL) {  /* could not open outFileName */
1810*22ce4affSfengbojiang             error = 1;
1811*22ce4affSfengbojiang         } else {
1812*22ce4affSfengbojiang             for (; fCtx->currFileIdx < fCtx->nbFilesTotal; ++fCtx->currFileIdx) {
1813*22ce4affSfengbojiang                 status = FIO_compressFilename_srcFile(fCtx, prefs, ress, outFileName, inFileNamesTable[fCtx->currFileIdx], compressionLevel);
1814*22ce4affSfengbojiang                 if (!status) fCtx->nbFilesProcessed++;
1815*22ce4affSfengbojiang                 error |= status;
1816*22ce4affSfengbojiang             }
1817*22ce4affSfengbojiang             if (fclose(ress.dstFile))
1818*22ce4affSfengbojiang                 EXM_THROW(29, "Write error (%s) : cannot properly close %s",
1819*22ce4affSfengbojiang                             strerror(errno), outFileName);
1820*22ce4affSfengbojiang             ress.dstFile = NULL;
1821*22ce4affSfengbojiang         }
1822*22ce4affSfengbojiang     } else {
1823*22ce4affSfengbojiang         if (outMirroredRootDirName)
1824*22ce4affSfengbojiang             UTIL_mirrorSourceFilesDirectories(inFileNamesTable, fCtx->nbFilesTotal, outMirroredRootDirName);
1825*22ce4affSfengbojiang 
1826*22ce4affSfengbojiang         for (; fCtx->currFileIdx < fCtx->nbFilesTotal; ++fCtx->currFileIdx) {
1827*22ce4affSfengbojiang             const char* const srcFileName = inFileNamesTable[fCtx->currFileIdx];
1828*22ce4affSfengbojiang             const char* dstFileName = NULL;
1829*22ce4affSfengbojiang             if (outMirroredRootDirName) {
1830*22ce4affSfengbojiang                 char* validMirroredDirName = UTIL_createMirroredDestDirName(srcFileName, outMirroredRootDirName);
1831*22ce4affSfengbojiang                 if (validMirroredDirName) {
1832*22ce4affSfengbojiang                     dstFileName = FIO_determineCompressedName(srcFileName, validMirroredDirName, suffix);
1833*22ce4affSfengbojiang                     free(validMirroredDirName);
1834*22ce4affSfengbojiang                 } else {
1835*22ce4affSfengbojiang                     DISPLAYLEVEL(2, "zstd: --output-dir-mirror cannot compress '%s' into '%s' \n", srcFileName, outMirroredRootDirName);
1836*22ce4affSfengbojiang                     error=1;
1837*22ce4affSfengbojiang                     continue;
1838*22ce4affSfengbojiang                 }
1839*22ce4affSfengbojiang             } else {
1840*22ce4affSfengbojiang                 dstFileName = FIO_determineCompressedName(srcFileName, outDirName, suffix);  /* cannot fail */
1841*22ce4affSfengbojiang             }
1842*22ce4affSfengbojiang             status = FIO_compressFilename_srcFile(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel);
1843*22ce4affSfengbojiang             if (!status) fCtx->nbFilesProcessed++;
1844*22ce4affSfengbojiang             error |= status;
1845*22ce4affSfengbojiang         }
1846*22ce4affSfengbojiang 
1847*22ce4affSfengbojiang         if (outDirName)
1848*22ce4affSfengbojiang             FIO_checkFilenameCollisions(inFileNamesTable , fCtx->nbFilesTotal);
1849*22ce4affSfengbojiang     }
1850*22ce4affSfengbojiang 
1851*22ce4affSfengbojiang     if (fCtx->nbFilesProcessed >= 1 && fCtx->nbFilesTotal > 1 && fCtx->totalBytesInput != 0) {
1852*22ce4affSfengbojiang         DISPLAYLEVEL(2, "\r%79s\r", "");
1853*22ce4affSfengbojiang         DISPLAYLEVEL(2, "%d files compressed : %.2f%%  (%6zu => %6zu bytes)\n", fCtx->nbFilesProcessed,
1854*22ce4affSfengbojiang                         (double)fCtx->totalBytesOutput/((double)fCtx->totalBytesInput)*100,
1855*22ce4affSfengbojiang                         fCtx->totalBytesInput, fCtx->totalBytesOutput);
1856*22ce4affSfengbojiang     }
1857*22ce4affSfengbojiang 
1858*22ce4affSfengbojiang     FIO_freeCResources(&ress);
1859*22ce4affSfengbojiang     return error;
1860*22ce4affSfengbojiang }
1861*22ce4affSfengbojiang 
1862*22ce4affSfengbojiang #endif /* #ifndef ZSTD_NOCOMPRESS */
1863*22ce4affSfengbojiang 
1864*22ce4affSfengbojiang 
1865*22ce4affSfengbojiang 
1866*22ce4affSfengbojiang #ifndef ZSTD_NODECOMPRESS
1867*22ce4affSfengbojiang 
1868*22ce4affSfengbojiang /* **************************************************************************
1869*22ce4affSfengbojiang  *  Decompression
1870*22ce4affSfengbojiang  ***************************************************************************/
1871*22ce4affSfengbojiang typedef struct {
1872*22ce4affSfengbojiang     void*  srcBuffer;
1873*22ce4affSfengbojiang     size_t srcBufferSize;
1874*22ce4affSfengbojiang     size_t srcBufferLoaded;
1875*22ce4affSfengbojiang     void*  dstBuffer;
1876*22ce4affSfengbojiang     size_t dstBufferSize;
1877*22ce4affSfengbojiang     ZSTD_DStream* dctx;
1878*22ce4affSfengbojiang     FILE*  dstFile;
1879*22ce4affSfengbojiang } dRess_t;
1880*22ce4affSfengbojiang 
FIO_createDResources(FIO_prefs_t * const prefs,const char * dictFileName)1881*22ce4affSfengbojiang static dRess_t FIO_createDResources(FIO_prefs_t* const prefs, const char* dictFileName)
1882*22ce4affSfengbojiang {
1883*22ce4affSfengbojiang     dRess_t ress;
1884*22ce4affSfengbojiang     memset(&ress, 0, sizeof(ress));
1885*22ce4affSfengbojiang 
1886*22ce4affSfengbojiang     if (prefs->patchFromMode)
1887*22ce4affSfengbojiang         FIO_adjustMemLimitForPatchFromMode(prefs, UTIL_getFileSize(dictFileName), 0 /* just use the dict size */);
1888*22ce4affSfengbojiang 
1889*22ce4affSfengbojiang     /* Allocation */
1890*22ce4affSfengbojiang     ress.dctx = ZSTD_createDStream();
1891*22ce4affSfengbojiang     if (ress.dctx==NULL)
1892*22ce4affSfengbojiang         EXM_THROW(60, "Error: %s : can't create ZSTD_DStream", strerror(errno));
1893*22ce4affSfengbojiang     CHECK( ZSTD_DCtx_setMaxWindowSize(ress.dctx, prefs->memLimit) );
1894*22ce4affSfengbojiang     CHECK( ZSTD_DCtx_setParameter(ress.dctx, ZSTD_d_forceIgnoreChecksum, !prefs->checksumFlag));
1895*22ce4affSfengbojiang 
1896*22ce4affSfengbojiang     ress.srcBufferSize = ZSTD_DStreamInSize();
1897*22ce4affSfengbojiang     ress.srcBuffer = malloc(ress.srcBufferSize);
1898*22ce4affSfengbojiang     ress.dstBufferSize = ZSTD_DStreamOutSize();
1899*22ce4affSfengbojiang     ress.dstBuffer = malloc(ress.dstBufferSize);
1900*22ce4affSfengbojiang     if (!ress.srcBuffer || !ress.dstBuffer)
1901*22ce4affSfengbojiang         EXM_THROW(61, "Allocation error : not enough memory");
1902*22ce4affSfengbojiang 
1903*22ce4affSfengbojiang     /* dictionary */
1904*22ce4affSfengbojiang     {   void* dictBuffer;
1905*22ce4affSfengbojiang         size_t const dictBufferSize = FIO_createDictBuffer(&dictBuffer, dictFileName, prefs);
1906*22ce4affSfengbojiang         CHECK( ZSTD_initDStream_usingDict(ress.dctx, dictBuffer, dictBufferSize) );
1907*22ce4affSfengbojiang         free(dictBuffer);
1908*22ce4affSfengbojiang     }
1909*22ce4affSfengbojiang 
1910*22ce4affSfengbojiang     return ress;
1911*22ce4affSfengbojiang }
1912*22ce4affSfengbojiang 
FIO_freeDResources(dRess_t ress)1913*22ce4affSfengbojiang static void FIO_freeDResources(dRess_t ress)
1914*22ce4affSfengbojiang {
1915*22ce4affSfengbojiang     CHECK( ZSTD_freeDStream(ress.dctx) );
1916*22ce4affSfengbojiang     free(ress.srcBuffer);
1917*22ce4affSfengbojiang     free(ress.dstBuffer);
1918*22ce4affSfengbojiang }
1919*22ce4affSfengbojiang 
1920*22ce4affSfengbojiang 
1921*22ce4affSfengbojiang /** FIO_fwriteSparse() :
1922*22ce4affSfengbojiang *  @return : storedSkips,
1923*22ce4affSfengbojiang *            argument for next call to FIO_fwriteSparse() or FIO_fwriteSparseEnd() */
1924*22ce4affSfengbojiang static unsigned
FIO_fwriteSparse(FILE * file,const void * buffer,size_t bufferSize,const FIO_prefs_t * const prefs,unsigned storedSkips)1925*22ce4affSfengbojiang FIO_fwriteSparse(FILE* file,
1926*22ce4affSfengbojiang                  const void* buffer, size_t bufferSize,
1927*22ce4affSfengbojiang                  const FIO_prefs_t* const prefs,
1928*22ce4affSfengbojiang                  unsigned storedSkips)
1929*22ce4affSfengbojiang {
1930*22ce4affSfengbojiang     const size_t* const bufferT = (const size_t*)buffer;   /* Buffer is supposed malloc'ed, hence aligned on size_t */
1931*22ce4affSfengbojiang     size_t bufferSizeT = bufferSize / sizeof(size_t);
1932*22ce4affSfengbojiang     const size_t* const bufferTEnd = bufferT + bufferSizeT;
1933*22ce4affSfengbojiang     const size_t* ptrT = bufferT;
1934*22ce4affSfengbojiang     static const size_t segmentSizeT = (32 KB) / sizeof(size_t);   /* check every 32 KB */
1935*22ce4affSfengbojiang 
1936*22ce4affSfengbojiang     if (prefs->testMode) return 0;  /* do not output anything in test mode */
1937*22ce4affSfengbojiang 
1938*22ce4affSfengbojiang     if (!prefs->sparseFileSupport) {  /* normal write */
1939*22ce4affSfengbojiang         size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file);
1940*22ce4affSfengbojiang         if (sizeCheck != bufferSize)
1941*22ce4affSfengbojiang             EXM_THROW(70, "Write error : cannot write decoded block : %s",
1942*22ce4affSfengbojiang                             strerror(errno));
1943*22ce4affSfengbojiang         return 0;
1944*22ce4affSfengbojiang     }
1945*22ce4affSfengbojiang 
1946*22ce4affSfengbojiang     /* avoid int overflow */
1947*22ce4affSfengbojiang     if (storedSkips > 1 GB) {
1948*22ce4affSfengbojiang         if (LONG_SEEK(file, 1 GB, SEEK_CUR) != 0)
1949*22ce4affSfengbojiang             EXM_THROW(91, "1 GB skip error (sparse file support)");
1950*22ce4affSfengbojiang         storedSkips -= 1 GB;
1951*22ce4affSfengbojiang     }
1952*22ce4affSfengbojiang 
1953*22ce4affSfengbojiang     while (ptrT < bufferTEnd) {
1954*22ce4affSfengbojiang         size_t nb0T;
1955*22ce4affSfengbojiang 
1956*22ce4affSfengbojiang         /* adjust last segment if < 32 KB */
1957*22ce4affSfengbojiang         size_t seg0SizeT = segmentSizeT;
1958*22ce4affSfengbojiang         if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT;
1959*22ce4affSfengbojiang         bufferSizeT -= seg0SizeT;
1960*22ce4affSfengbojiang 
1961*22ce4affSfengbojiang         /* count leading zeroes */
1962*22ce4affSfengbojiang         for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ;
1963*22ce4affSfengbojiang         storedSkips += (unsigned)(nb0T * sizeof(size_t));
1964*22ce4affSfengbojiang 
1965*22ce4affSfengbojiang         if (nb0T != seg0SizeT) {   /* not all 0s */
1966*22ce4affSfengbojiang             size_t const nbNon0ST = seg0SizeT - nb0T;
1967*22ce4affSfengbojiang             /* skip leading zeros */
1968*22ce4affSfengbojiang             if (LONG_SEEK(file, storedSkips, SEEK_CUR) != 0)
1969*22ce4affSfengbojiang                 EXM_THROW(92, "Sparse skip error ; try --no-sparse");
1970*22ce4affSfengbojiang             storedSkips = 0;
1971*22ce4affSfengbojiang             /* write the rest */
1972*22ce4affSfengbojiang             if (fwrite(ptrT + nb0T, sizeof(size_t), nbNon0ST, file) != nbNon0ST)
1973*22ce4affSfengbojiang                 EXM_THROW(93, "Write error : cannot write decoded block : %s",
1974*22ce4affSfengbojiang                             strerror(errno));
1975*22ce4affSfengbojiang         }
1976*22ce4affSfengbojiang         ptrT += seg0SizeT;
1977*22ce4affSfengbojiang     }
1978*22ce4affSfengbojiang 
1979*22ce4affSfengbojiang     {   static size_t const maskT = sizeof(size_t)-1;
1980*22ce4affSfengbojiang         if (bufferSize & maskT) {
1981*22ce4affSfengbojiang             /* size not multiple of sizeof(size_t) : implies end of block */
1982*22ce4affSfengbojiang             const char* const restStart = (const char*)bufferTEnd;
1983*22ce4affSfengbojiang             const char* restPtr = restStart;
1984*22ce4affSfengbojiang             const char* const restEnd = (const char*)buffer + bufferSize;
1985*22ce4affSfengbojiang             assert(restEnd > restStart && restEnd < restStart + sizeof(size_t));
1986*22ce4affSfengbojiang             for ( ; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ;
1987*22ce4affSfengbojiang             storedSkips += (unsigned) (restPtr - restStart);
1988*22ce4affSfengbojiang             if (restPtr != restEnd) {
1989*22ce4affSfengbojiang                 /* not all remaining bytes are 0 */
1990*22ce4affSfengbojiang                 size_t const restSize = (size_t)(restEnd - restPtr);
1991*22ce4affSfengbojiang                 if (LONG_SEEK(file, storedSkips, SEEK_CUR) != 0)
1992*22ce4affSfengbojiang                     EXM_THROW(92, "Sparse skip error ; try --no-sparse");
1993*22ce4affSfengbojiang                 if (fwrite(restPtr, 1, restSize, file) != restSize)
1994*22ce4affSfengbojiang                     EXM_THROW(95, "Write error : cannot write end of decoded block : %s",
1995*22ce4affSfengbojiang                         strerror(errno));
1996*22ce4affSfengbojiang                 storedSkips = 0;
1997*22ce4affSfengbojiang     }   }   }
1998*22ce4affSfengbojiang 
1999*22ce4affSfengbojiang     return storedSkips;
2000*22ce4affSfengbojiang }
2001*22ce4affSfengbojiang 
2002*22ce4affSfengbojiang static void
FIO_fwriteSparseEnd(const FIO_prefs_t * const prefs,FILE * file,unsigned storedSkips)2003*22ce4affSfengbojiang FIO_fwriteSparseEnd(const FIO_prefs_t* const prefs, FILE* file, unsigned storedSkips)
2004*22ce4affSfengbojiang {
2005*22ce4affSfengbojiang     if (prefs->testMode) assert(storedSkips == 0);
2006*22ce4affSfengbojiang     if (storedSkips>0) {
2007*22ce4affSfengbojiang         assert(prefs->sparseFileSupport > 0);  /* storedSkips>0 implies sparse support is enabled */
2008*22ce4affSfengbojiang         (void)prefs;   /* assert can be disabled, in which case prefs becomes unused */
2009*22ce4affSfengbojiang         if (LONG_SEEK(file, storedSkips-1, SEEK_CUR) != 0)
2010*22ce4affSfengbojiang             EXM_THROW(69, "Final skip error (sparse file support)");
2011*22ce4affSfengbojiang         /* last zero must be explicitly written,
2012*22ce4affSfengbojiang          * so that skipped ones get implicitly translated as zero by FS */
2013*22ce4affSfengbojiang         {   const char lastZeroByte[1] = { 0 };
2014*22ce4affSfengbojiang             if (fwrite(lastZeroByte, 1, 1, file) != 1)
2015*22ce4affSfengbojiang                 EXM_THROW(69, "Write error : cannot write last zero : %s", strerror(errno));
2016*22ce4affSfengbojiang     }   }
2017*22ce4affSfengbojiang }
2018*22ce4affSfengbojiang 
2019*22ce4affSfengbojiang 
2020*22ce4affSfengbojiang /** FIO_passThrough() : just copy input into output, for compatibility with gzip -df mode
2021*22ce4affSfengbojiang     @return : 0 (no error) */
FIO_passThrough(const FIO_prefs_t * const prefs,FILE * foutput,FILE * finput,void * buffer,size_t bufferSize,size_t alreadyLoaded)2022*22ce4affSfengbojiang static int FIO_passThrough(const FIO_prefs_t* const prefs,
2023*22ce4affSfengbojiang                            FILE* foutput, FILE* finput,
2024*22ce4affSfengbojiang                            void* buffer, size_t bufferSize,
2025*22ce4affSfengbojiang                            size_t alreadyLoaded)
2026*22ce4affSfengbojiang {
2027*22ce4affSfengbojiang     size_t const blockSize = MIN(64 KB, bufferSize);
2028*22ce4affSfengbojiang     size_t readFromInput;
2029*22ce4affSfengbojiang     unsigned storedSkips = 0;
2030*22ce4affSfengbojiang 
2031*22ce4affSfengbojiang     /* assumption : ress->srcBufferLoaded bytes already loaded and stored within buffer */
2032*22ce4affSfengbojiang     {   size_t const sizeCheck = fwrite(buffer, 1, alreadyLoaded, foutput);
2033*22ce4affSfengbojiang         if (sizeCheck != alreadyLoaded) {
2034*22ce4affSfengbojiang             DISPLAYLEVEL(1, "Pass-through write error : %s\n", strerror(errno));
2035*22ce4affSfengbojiang             return 1;
2036*22ce4affSfengbojiang     }   }
2037*22ce4affSfengbojiang 
2038*22ce4affSfengbojiang     do {
2039*22ce4affSfengbojiang         readFromInput = fread(buffer, 1, blockSize, finput);
2040*22ce4affSfengbojiang         storedSkips = FIO_fwriteSparse(foutput, buffer, readFromInput, prefs, storedSkips);
2041*22ce4affSfengbojiang     } while (readFromInput == blockSize);
2042*22ce4affSfengbojiang     if (ferror(finput)) {
2043*22ce4affSfengbojiang         DISPLAYLEVEL(1, "Pass-through read error : %s\n", strerror(errno));
2044*22ce4affSfengbojiang         return 1;
2045*22ce4affSfengbojiang     }
2046*22ce4affSfengbojiang     assert(feof(finput));
2047*22ce4affSfengbojiang 
2048*22ce4affSfengbojiang     FIO_fwriteSparseEnd(prefs, foutput, storedSkips);
2049*22ce4affSfengbojiang     return 0;
2050*22ce4affSfengbojiang }
2051*22ce4affSfengbojiang 
2052*22ce4affSfengbojiang /* FIO_zstdErrorHelp() :
2053*22ce4affSfengbojiang  * detailed error message when requested window size is too large */
2054*22ce4affSfengbojiang static void
FIO_zstdErrorHelp(const FIO_prefs_t * const prefs,const dRess_t * ress,size_t err,const char * srcFileName)2055*22ce4affSfengbojiang FIO_zstdErrorHelp(const FIO_prefs_t* const prefs,
2056*22ce4affSfengbojiang                   const dRess_t* ress,
2057*22ce4affSfengbojiang                   size_t err, const char* srcFileName)
2058*22ce4affSfengbojiang {
2059*22ce4affSfengbojiang     ZSTD_frameHeader header;
2060*22ce4affSfengbojiang 
2061*22ce4affSfengbojiang     /* Help message only for one specific error */
2062*22ce4affSfengbojiang     if (ZSTD_getErrorCode(err) != ZSTD_error_frameParameter_windowTooLarge)
2063*22ce4affSfengbojiang         return;
2064*22ce4affSfengbojiang 
2065*22ce4affSfengbojiang     /* Try to decode the frame header */
2066*22ce4affSfengbojiang     err = ZSTD_getFrameHeader(&header, ress->srcBuffer, ress->srcBufferLoaded);
2067*22ce4affSfengbojiang     if (err == 0) {
2068*22ce4affSfengbojiang         unsigned long long const windowSize = header.windowSize;
2069*22ce4affSfengbojiang         unsigned const windowLog = FIO_highbit64(windowSize) + ((windowSize & (windowSize - 1)) != 0);
2070*22ce4affSfengbojiang         assert(prefs->memLimit > 0);
2071*22ce4affSfengbojiang         DISPLAYLEVEL(1, "%s : Window size larger than maximum : %llu > %u \n",
2072*22ce4affSfengbojiang                         srcFileName, windowSize, prefs->memLimit);
2073*22ce4affSfengbojiang         if (windowLog <= ZSTD_WINDOWLOG_MAX) {
2074*22ce4affSfengbojiang             unsigned const windowMB = (unsigned)((windowSize >> 20) + ((windowSize & ((1 MB) - 1)) != 0));
2075*22ce4affSfengbojiang             assert(windowSize < (U64)(1ULL << 52));   /* ensure now overflow for windowMB */
2076*22ce4affSfengbojiang             DISPLAYLEVEL(1, "%s : Use --long=%u or --memory=%uMB \n",
2077*22ce4affSfengbojiang                             srcFileName, windowLog, windowMB);
2078*22ce4affSfengbojiang             return;
2079*22ce4affSfengbojiang     }   }
2080*22ce4affSfengbojiang     DISPLAYLEVEL(1, "%s : Window log larger than ZSTD_WINDOWLOG_MAX=%u; not supported \n",
2081*22ce4affSfengbojiang                     srcFileName, ZSTD_WINDOWLOG_MAX);
2082*22ce4affSfengbojiang }
2083*22ce4affSfengbojiang 
2084*22ce4affSfengbojiang /** FIO_decompressFrame() :
2085*22ce4affSfengbojiang  *  @return : size of decoded zstd frame, or an error code
2086*22ce4affSfengbojiang  */
2087*22ce4affSfengbojiang #define FIO_ERROR_FRAME_DECODING   ((unsigned long long)(-2))
2088*22ce4affSfengbojiang static unsigned long long
FIO_decompressZstdFrame(FIO_ctx_t * const fCtx,dRess_t * ress,FILE * finput,const FIO_prefs_t * const prefs,const char * srcFileName,U64 alreadyDecoded)2089*22ce4affSfengbojiang FIO_decompressZstdFrame(FIO_ctx_t* const fCtx, dRess_t* ress, FILE* finput,
2090*22ce4affSfengbojiang                         const FIO_prefs_t* const prefs,
2091*22ce4affSfengbojiang                         const char* srcFileName,
2092*22ce4affSfengbojiang                         U64 alreadyDecoded)  /* for multi-frames streams */
2093*22ce4affSfengbojiang {
2094*22ce4affSfengbojiang     U64 frameSize = 0;
2095*22ce4affSfengbojiang     U32 storedSkips = 0;
2096*22ce4affSfengbojiang 
2097*22ce4affSfengbojiang     /* display last 20 characters only */
2098*22ce4affSfengbojiang     {   size_t const srcFileLength = strlen(srcFileName);
2099*22ce4affSfengbojiang         if (srcFileLength>20) srcFileName += srcFileLength-20;
2100*22ce4affSfengbojiang     }
2101*22ce4affSfengbojiang 
2102*22ce4affSfengbojiang     ZSTD_resetDStream(ress->dctx);
2103*22ce4affSfengbojiang 
2104*22ce4affSfengbojiang     /* Header loading : ensures ZSTD_getFrameHeader() will succeed */
2105*22ce4affSfengbojiang     {   size_t const toDecode = ZSTD_FRAMEHEADERSIZE_MAX;
2106*22ce4affSfengbojiang         if (ress->srcBufferLoaded < toDecode) {
2107*22ce4affSfengbojiang             size_t const toRead = toDecode - ress->srcBufferLoaded;
2108*22ce4affSfengbojiang             void* const startPosition = (char*)ress->srcBuffer + ress->srcBufferLoaded;
2109*22ce4affSfengbojiang             ress->srcBufferLoaded += fread(startPosition, 1, toRead, finput);
2110*22ce4affSfengbojiang     }   }
2111*22ce4affSfengbojiang 
2112*22ce4affSfengbojiang     /* Main decompression Loop */
2113*22ce4affSfengbojiang     while (1) {
2114*22ce4affSfengbojiang         ZSTD_inBuffer  inBuff = { ress->srcBuffer, ress->srcBufferLoaded, 0 };
2115*22ce4affSfengbojiang         ZSTD_outBuffer outBuff= { ress->dstBuffer, ress->dstBufferSize, 0 };
2116*22ce4affSfengbojiang         size_t const readSizeHint = ZSTD_decompressStream(ress->dctx, &outBuff, &inBuff);
2117*22ce4affSfengbojiang         if (ZSTD_isError(readSizeHint)) {
2118*22ce4affSfengbojiang             DISPLAYLEVEL(1, "%s : Decoding error (36) : %s \n",
2119*22ce4affSfengbojiang                             srcFileName, ZSTD_getErrorName(readSizeHint));
2120*22ce4affSfengbojiang             FIO_zstdErrorHelp(prefs, ress, readSizeHint, srcFileName);
2121*22ce4affSfengbojiang             return FIO_ERROR_FRAME_DECODING;
2122*22ce4affSfengbojiang         }
2123*22ce4affSfengbojiang 
2124*22ce4affSfengbojiang         /* Write block */
2125*22ce4affSfengbojiang         storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, outBuff.pos, prefs, storedSkips);
2126*22ce4affSfengbojiang         frameSize += outBuff.pos;
2127*22ce4affSfengbojiang         if (!fCtx->hasStdoutOutput) {
2128*22ce4affSfengbojiang             if (fCtx->nbFilesTotal > 1) {
2129*22ce4affSfengbojiang                 size_t srcFileNameSize = strlen(srcFileName);
2130*22ce4affSfengbojiang                 if (srcFileNameSize > 18) {
2131*22ce4affSfengbojiang                     const char* truncatedSrcFileName = srcFileName + srcFileNameSize - 15;
2132*22ce4affSfengbojiang                     DISPLAYUPDATE(2, "\rDecompress: %2u/%2u files. Current: ...%s : %u MB...    ",
2133*22ce4affSfengbojiang                                     fCtx->currFileIdx+1, fCtx->nbFilesTotal, truncatedSrcFileName, (unsigned)((alreadyDecoded+frameSize)>>20) );
2134*22ce4affSfengbojiang                 } else {
2135*22ce4affSfengbojiang                     DISPLAYUPDATE(2, "\rDecompress: %2u/%2u files. Current: %s : %u MB...    ",
2136*22ce4affSfengbojiang                                 fCtx->currFileIdx+1, fCtx->nbFilesTotal, srcFileName, (unsigned)((alreadyDecoded+frameSize)>>20) );
2137*22ce4affSfengbojiang                 }
2138*22ce4affSfengbojiang             } else {
2139*22ce4affSfengbojiang                 DISPLAYUPDATE(2, "\r%-20.20s : %u MB...     ",
2140*22ce4affSfengbojiang                                 srcFileName, (unsigned)((alreadyDecoded+frameSize)>>20) );
2141*22ce4affSfengbojiang             }
2142*22ce4affSfengbojiang         }
2143*22ce4affSfengbojiang 
2144*22ce4affSfengbojiang         if (inBuff.pos > 0) {
2145*22ce4affSfengbojiang             memmove(ress->srcBuffer, (char*)ress->srcBuffer + inBuff.pos, inBuff.size - inBuff.pos);
2146*22ce4affSfengbojiang             ress->srcBufferLoaded -= inBuff.pos;
2147*22ce4affSfengbojiang         }
2148*22ce4affSfengbojiang 
2149*22ce4affSfengbojiang         if (readSizeHint == 0) break;   /* end of frame */
2150*22ce4affSfengbojiang 
2151*22ce4affSfengbojiang         /* Fill input buffer */
2152*22ce4affSfengbojiang         {   size_t const toDecode = MIN(readSizeHint, ress->srcBufferSize);  /* support large skippable frames */
2153*22ce4affSfengbojiang             if (ress->srcBufferLoaded < toDecode) {
2154*22ce4affSfengbojiang                 size_t const toRead = toDecode - ress->srcBufferLoaded;   /* > 0 */
2155*22ce4affSfengbojiang                 void* const startPosition = (char*)ress->srcBuffer + ress->srcBufferLoaded;
2156*22ce4affSfengbojiang                 size_t const readSize = fread(startPosition, 1, toRead, finput);
2157*22ce4affSfengbojiang                 if (readSize==0) {
2158*22ce4affSfengbojiang                     DISPLAYLEVEL(1, "%s : Read error (39) : premature end \n",
2159*22ce4affSfengbojiang                                     srcFileName);
2160*22ce4affSfengbojiang                     return FIO_ERROR_FRAME_DECODING;
2161*22ce4affSfengbojiang                 }
2162*22ce4affSfengbojiang                 ress->srcBufferLoaded += readSize;
2163*22ce4affSfengbojiang     }   }   }
2164*22ce4affSfengbojiang 
2165*22ce4affSfengbojiang     FIO_fwriteSparseEnd(prefs, ress->dstFile, storedSkips);
2166*22ce4affSfengbojiang 
2167*22ce4affSfengbojiang     return frameSize;
2168*22ce4affSfengbojiang }
2169*22ce4affSfengbojiang 
2170*22ce4affSfengbojiang 
2171*22ce4affSfengbojiang #ifdef ZSTD_GZDECOMPRESS
2172*22ce4affSfengbojiang static unsigned long long
FIO_decompressGzFrame(dRess_t * ress,FILE * srcFile,const FIO_prefs_t * const prefs,const char * srcFileName)2173*22ce4affSfengbojiang FIO_decompressGzFrame(dRess_t* ress, FILE* srcFile,
2174*22ce4affSfengbojiang                       const FIO_prefs_t* const prefs,
2175*22ce4affSfengbojiang                       const char* srcFileName)
2176*22ce4affSfengbojiang {
2177*22ce4affSfengbojiang     unsigned long long outFileSize = 0;
2178*22ce4affSfengbojiang     z_stream strm;
2179*22ce4affSfengbojiang     int flush = Z_NO_FLUSH;
2180*22ce4affSfengbojiang     int decodingError = 0;
2181*22ce4affSfengbojiang     unsigned storedSkips = 0;
2182*22ce4affSfengbojiang 
2183*22ce4affSfengbojiang     strm.zalloc = Z_NULL;
2184*22ce4affSfengbojiang     strm.zfree = Z_NULL;
2185*22ce4affSfengbojiang     strm.opaque = Z_NULL;
2186*22ce4affSfengbojiang     strm.next_in = 0;
2187*22ce4affSfengbojiang     strm.avail_in = 0;
2188*22ce4affSfengbojiang     /* see http://www.zlib.net/manual.html */
2189*22ce4affSfengbojiang     if (inflateInit2(&strm, 15 /* maxWindowLogSize */ + 16 /* gzip only */) != Z_OK)
2190*22ce4affSfengbojiang         return FIO_ERROR_FRAME_DECODING;
2191*22ce4affSfengbojiang 
2192*22ce4affSfengbojiang     strm.next_out = (Bytef*)ress->dstBuffer;
2193*22ce4affSfengbojiang     strm.avail_out = (uInt)ress->dstBufferSize;
2194*22ce4affSfengbojiang     strm.avail_in = (uInt)ress->srcBufferLoaded;
2195*22ce4affSfengbojiang     strm.next_in = (z_const unsigned char*)ress->srcBuffer;
2196*22ce4affSfengbojiang 
2197*22ce4affSfengbojiang     for ( ; ; ) {
2198*22ce4affSfengbojiang         int ret;
2199*22ce4affSfengbojiang         if (strm.avail_in == 0) {
2200*22ce4affSfengbojiang             ress->srcBufferLoaded = fread(ress->srcBuffer, 1, ress->srcBufferSize, srcFile);
2201*22ce4affSfengbojiang             if (ress->srcBufferLoaded == 0) flush = Z_FINISH;
2202*22ce4affSfengbojiang             strm.next_in = (z_const unsigned char*)ress->srcBuffer;
2203*22ce4affSfengbojiang             strm.avail_in = (uInt)ress->srcBufferLoaded;
2204*22ce4affSfengbojiang         }
2205*22ce4affSfengbojiang         ret = inflate(&strm, flush);
2206*22ce4affSfengbojiang         if (ret == Z_BUF_ERROR) {
2207*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: premature gz end \n", srcFileName);
2208*22ce4affSfengbojiang             decodingError = 1; break;
2209*22ce4affSfengbojiang         }
2210*22ce4affSfengbojiang         if (ret != Z_OK && ret != Z_STREAM_END) {
2211*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: inflate error %d \n", srcFileName, ret);
2212*22ce4affSfengbojiang             decodingError = 1; break;
2213*22ce4affSfengbojiang         }
2214*22ce4affSfengbojiang         {   size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
2215*22ce4affSfengbojiang             if (decompBytes) {
2216*22ce4affSfengbojiang                 storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, decompBytes, prefs, storedSkips);
2217*22ce4affSfengbojiang                 outFileSize += decompBytes;
2218*22ce4affSfengbojiang                 strm.next_out = (Bytef*)ress->dstBuffer;
2219*22ce4affSfengbojiang                 strm.avail_out = (uInt)ress->dstBufferSize;
2220*22ce4affSfengbojiang             }
2221*22ce4affSfengbojiang         }
2222*22ce4affSfengbojiang         if (ret == Z_STREAM_END) break;
2223*22ce4affSfengbojiang     }
2224*22ce4affSfengbojiang 
2225*22ce4affSfengbojiang     if (strm.avail_in > 0)
2226*22ce4affSfengbojiang         memmove(ress->srcBuffer, strm.next_in, strm.avail_in);
2227*22ce4affSfengbojiang     ress->srcBufferLoaded = strm.avail_in;
2228*22ce4affSfengbojiang     if ( (inflateEnd(&strm) != Z_OK)  /* release resources ; error detected */
2229*22ce4affSfengbojiang       && (decodingError==0) ) {
2230*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s: inflateEnd error \n", srcFileName);
2231*22ce4affSfengbojiang         decodingError = 1;
2232*22ce4affSfengbojiang     }
2233*22ce4affSfengbojiang     FIO_fwriteSparseEnd(prefs, ress->dstFile, storedSkips);
2234*22ce4affSfengbojiang     return decodingError ? FIO_ERROR_FRAME_DECODING : outFileSize;
2235*22ce4affSfengbojiang }
2236*22ce4affSfengbojiang #endif
2237*22ce4affSfengbojiang 
2238*22ce4affSfengbojiang 
2239*22ce4affSfengbojiang #ifdef ZSTD_LZMADECOMPRESS
2240*22ce4affSfengbojiang static unsigned long long
FIO_decompressLzmaFrame(dRess_t * ress,FILE * srcFile,const FIO_prefs_t * const prefs,const char * srcFileName,int plain_lzma)2241*22ce4affSfengbojiang FIO_decompressLzmaFrame(dRess_t* ress, FILE* srcFile,
2242*22ce4affSfengbojiang                         const FIO_prefs_t* const prefs,
2243*22ce4affSfengbojiang                         const char* srcFileName, int plain_lzma)
2244*22ce4affSfengbojiang {
2245*22ce4affSfengbojiang     unsigned long long outFileSize = 0;
2246*22ce4affSfengbojiang     lzma_stream strm = LZMA_STREAM_INIT;
2247*22ce4affSfengbojiang     lzma_action action = LZMA_RUN;
2248*22ce4affSfengbojiang     lzma_ret initRet;
2249*22ce4affSfengbojiang     int decodingError = 0;
2250*22ce4affSfengbojiang     unsigned storedSkips = 0;
2251*22ce4affSfengbojiang 
2252*22ce4affSfengbojiang     strm.next_in = 0;
2253*22ce4affSfengbojiang     strm.avail_in = 0;
2254*22ce4affSfengbojiang     if (plain_lzma) {
2255*22ce4affSfengbojiang         initRet = lzma_alone_decoder(&strm, UINT64_MAX); /* LZMA */
2256*22ce4affSfengbojiang     } else {
2257*22ce4affSfengbojiang         initRet = lzma_stream_decoder(&strm, UINT64_MAX, 0); /* XZ */
2258*22ce4affSfengbojiang     }
2259*22ce4affSfengbojiang 
2260*22ce4affSfengbojiang     if (initRet != LZMA_OK) {
2261*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s: %s error %d \n",
2262*22ce4affSfengbojiang                         plain_lzma ? "lzma_alone_decoder" : "lzma_stream_decoder",
2263*22ce4affSfengbojiang                         srcFileName, initRet);
2264*22ce4affSfengbojiang         return FIO_ERROR_FRAME_DECODING;
2265*22ce4affSfengbojiang     }
2266*22ce4affSfengbojiang 
2267*22ce4affSfengbojiang     strm.next_out = (BYTE*)ress->dstBuffer;
2268*22ce4affSfengbojiang     strm.avail_out = ress->dstBufferSize;
2269*22ce4affSfengbojiang     strm.next_in = (BYTE const*)ress->srcBuffer;
2270*22ce4affSfengbojiang     strm.avail_in = ress->srcBufferLoaded;
2271*22ce4affSfengbojiang 
2272*22ce4affSfengbojiang     for ( ; ; ) {
2273*22ce4affSfengbojiang         lzma_ret ret;
2274*22ce4affSfengbojiang         if (strm.avail_in == 0) {
2275*22ce4affSfengbojiang             ress->srcBufferLoaded = fread(ress->srcBuffer, 1, ress->srcBufferSize, srcFile);
2276*22ce4affSfengbojiang             if (ress->srcBufferLoaded == 0) action = LZMA_FINISH;
2277*22ce4affSfengbojiang             strm.next_in = (BYTE const*)ress->srcBuffer;
2278*22ce4affSfengbojiang             strm.avail_in = ress->srcBufferLoaded;
2279*22ce4affSfengbojiang         }
2280*22ce4affSfengbojiang         ret = lzma_code(&strm, action);
2281*22ce4affSfengbojiang 
2282*22ce4affSfengbojiang         if (ret == LZMA_BUF_ERROR) {
2283*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: premature lzma end \n", srcFileName);
2284*22ce4affSfengbojiang             decodingError = 1; break;
2285*22ce4affSfengbojiang         }
2286*22ce4affSfengbojiang         if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
2287*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: lzma_code decoding error %d \n",
2288*22ce4affSfengbojiang                             srcFileName, ret);
2289*22ce4affSfengbojiang             decodingError = 1; break;
2290*22ce4affSfengbojiang         }
2291*22ce4affSfengbojiang         {   size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
2292*22ce4affSfengbojiang             if (decompBytes) {
2293*22ce4affSfengbojiang                 storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, decompBytes, prefs, storedSkips);
2294*22ce4affSfengbojiang                 outFileSize += decompBytes;
2295*22ce4affSfengbojiang                 strm.next_out = (BYTE*)ress->dstBuffer;
2296*22ce4affSfengbojiang                 strm.avail_out = ress->dstBufferSize;
2297*22ce4affSfengbojiang         }   }
2298*22ce4affSfengbojiang         if (ret == LZMA_STREAM_END) break;
2299*22ce4affSfengbojiang     }
2300*22ce4affSfengbojiang 
2301*22ce4affSfengbojiang     if (strm.avail_in > 0)
2302*22ce4affSfengbojiang         memmove(ress->srcBuffer, strm.next_in, strm.avail_in);
2303*22ce4affSfengbojiang     ress->srcBufferLoaded = strm.avail_in;
2304*22ce4affSfengbojiang     lzma_end(&strm);
2305*22ce4affSfengbojiang     FIO_fwriteSparseEnd(prefs, ress->dstFile, storedSkips);
2306*22ce4affSfengbojiang     return decodingError ? FIO_ERROR_FRAME_DECODING : outFileSize;
2307*22ce4affSfengbojiang }
2308*22ce4affSfengbojiang #endif
2309*22ce4affSfengbojiang 
2310*22ce4affSfengbojiang #ifdef ZSTD_LZ4DECOMPRESS
2311*22ce4affSfengbojiang static unsigned long long
FIO_decompressLz4Frame(dRess_t * ress,FILE * srcFile,const FIO_prefs_t * const prefs,const char * srcFileName)2312*22ce4affSfengbojiang FIO_decompressLz4Frame(dRess_t* ress, FILE* srcFile,
2313*22ce4affSfengbojiang                        const FIO_prefs_t* const prefs,
2314*22ce4affSfengbojiang                        const char* srcFileName)
2315*22ce4affSfengbojiang {
2316*22ce4affSfengbojiang     unsigned long long filesize = 0;
2317*22ce4affSfengbojiang     LZ4F_errorCode_t nextToLoad;
2318*22ce4affSfengbojiang     LZ4F_decompressionContext_t dCtx;
2319*22ce4affSfengbojiang     LZ4F_errorCode_t const errorCode = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
2320*22ce4affSfengbojiang     int decodingError = 0;
2321*22ce4affSfengbojiang     unsigned storedSkips = 0;
2322*22ce4affSfengbojiang 
2323*22ce4affSfengbojiang     if (LZ4F_isError(errorCode)) {
2324*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: failed to create lz4 decompression context \n");
2325*22ce4affSfengbojiang         return FIO_ERROR_FRAME_DECODING;
2326*22ce4affSfengbojiang     }
2327*22ce4affSfengbojiang 
2328*22ce4affSfengbojiang     /* Init feed with magic number (already consumed from FILE* sFile) */
2329*22ce4affSfengbojiang     {   size_t inSize = 4;
2330*22ce4affSfengbojiang         size_t outSize= 0;
2331*22ce4affSfengbojiang         MEM_writeLE32(ress->srcBuffer, LZ4_MAGICNUMBER);
2332*22ce4affSfengbojiang         nextToLoad = LZ4F_decompress(dCtx, ress->dstBuffer, &outSize, ress->srcBuffer, &inSize, NULL);
2333*22ce4affSfengbojiang         if (LZ4F_isError(nextToLoad)) {
2334*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: lz4 header error : %s \n",
2335*22ce4affSfengbojiang                             srcFileName, LZ4F_getErrorName(nextToLoad));
2336*22ce4affSfengbojiang             LZ4F_freeDecompressionContext(dCtx);
2337*22ce4affSfengbojiang             return FIO_ERROR_FRAME_DECODING;
2338*22ce4affSfengbojiang     }   }
2339*22ce4affSfengbojiang 
2340*22ce4affSfengbojiang     /* Main Loop */
2341*22ce4affSfengbojiang     for (;nextToLoad;) {
2342*22ce4affSfengbojiang         size_t readSize;
2343*22ce4affSfengbojiang         size_t pos = 0;
2344*22ce4affSfengbojiang         size_t decodedBytes = ress->dstBufferSize;
2345*22ce4affSfengbojiang 
2346*22ce4affSfengbojiang         /* Read input */
2347*22ce4affSfengbojiang         if (nextToLoad > ress->srcBufferSize) nextToLoad = ress->srcBufferSize;
2348*22ce4affSfengbojiang         readSize = fread(ress->srcBuffer, 1, nextToLoad, srcFile);
2349*22ce4affSfengbojiang         if (!readSize) break;   /* reached end of file or stream */
2350*22ce4affSfengbojiang 
2351*22ce4affSfengbojiang         while ((pos < readSize) || (decodedBytes == ress->dstBufferSize)) {  /* still to read, or still to flush */
2352*22ce4affSfengbojiang             /* Decode Input (at least partially) */
2353*22ce4affSfengbojiang             size_t remaining = readSize - pos;
2354*22ce4affSfengbojiang             decodedBytes = ress->dstBufferSize;
2355*22ce4affSfengbojiang             nextToLoad = LZ4F_decompress(dCtx, ress->dstBuffer, &decodedBytes, (char*)(ress->srcBuffer)+pos, &remaining, NULL);
2356*22ce4affSfengbojiang             if (LZ4F_isError(nextToLoad)) {
2357*22ce4affSfengbojiang                 DISPLAYLEVEL(1, "zstd: %s: lz4 decompression error : %s \n",
2358*22ce4affSfengbojiang                                 srcFileName, LZ4F_getErrorName(nextToLoad));
2359*22ce4affSfengbojiang                 decodingError = 1; nextToLoad = 0; break;
2360*22ce4affSfengbojiang             }
2361*22ce4affSfengbojiang             pos += remaining;
2362*22ce4affSfengbojiang 
2363*22ce4affSfengbojiang             /* Write Block */
2364*22ce4affSfengbojiang             if (decodedBytes) {
2365*22ce4affSfengbojiang                 storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, decodedBytes, prefs, storedSkips);
2366*22ce4affSfengbojiang                 filesize += decodedBytes;
2367*22ce4affSfengbojiang                 DISPLAYUPDATE(2, "\rDecompressed : %u MB  ", (unsigned)(filesize>>20));
2368*22ce4affSfengbojiang             }
2369*22ce4affSfengbojiang 
2370*22ce4affSfengbojiang             if (!nextToLoad) break;
2371*22ce4affSfengbojiang         }
2372*22ce4affSfengbojiang     }
2373*22ce4affSfengbojiang     /* can be out because readSize == 0, which could be an fread() error */
2374*22ce4affSfengbojiang     if (ferror(srcFile)) {
2375*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s: read error \n", srcFileName);
2376*22ce4affSfengbojiang         decodingError=1;
2377*22ce4affSfengbojiang     }
2378*22ce4affSfengbojiang 
2379*22ce4affSfengbojiang     if (nextToLoad!=0) {
2380*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s: unfinished lz4 stream \n", srcFileName);
2381*22ce4affSfengbojiang         decodingError=1;
2382*22ce4affSfengbojiang     }
2383*22ce4affSfengbojiang 
2384*22ce4affSfengbojiang     LZ4F_freeDecompressionContext(dCtx);
2385*22ce4affSfengbojiang     ress->srcBufferLoaded = 0; /* LZ4F will reach exact frame boundary */
2386*22ce4affSfengbojiang     FIO_fwriteSparseEnd(prefs, ress->dstFile, storedSkips);
2387*22ce4affSfengbojiang 
2388*22ce4affSfengbojiang     return decodingError ? FIO_ERROR_FRAME_DECODING : filesize;
2389*22ce4affSfengbojiang }
2390*22ce4affSfengbojiang #endif
2391*22ce4affSfengbojiang 
2392*22ce4affSfengbojiang 
2393*22ce4affSfengbojiang 
2394*22ce4affSfengbojiang /** FIO_decompressFrames() :
2395*22ce4affSfengbojiang  *  Find and decode frames inside srcFile
2396*22ce4affSfengbojiang  *  srcFile presumed opened and valid
2397*22ce4affSfengbojiang  * @return : 0 : OK
2398*22ce4affSfengbojiang  *           1 : error
2399*22ce4affSfengbojiang  */
FIO_decompressFrames(FIO_ctx_t * const fCtx,dRess_t ress,FILE * srcFile,const FIO_prefs_t * const prefs,const char * dstFileName,const char * srcFileName)2400*22ce4affSfengbojiang static int FIO_decompressFrames(FIO_ctx_t* const fCtx,
2401*22ce4affSfengbojiang                           dRess_t ress, FILE* srcFile,
2402*22ce4affSfengbojiang                           const FIO_prefs_t* const prefs,
2403*22ce4affSfengbojiang                           const char* dstFileName, const char* srcFileName)
2404*22ce4affSfengbojiang {
2405*22ce4affSfengbojiang     unsigned readSomething = 0;
2406*22ce4affSfengbojiang     unsigned long long filesize = 0;
2407*22ce4affSfengbojiang     assert(srcFile != NULL);
2408*22ce4affSfengbojiang 
2409*22ce4affSfengbojiang     /* for each frame */
2410*22ce4affSfengbojiang     for ( ; ; ) {
2411*22ce4affSfengbojiang         /* check magic number -> version */
2412*22ce4affSfengbojiang         size_t const toRead = 4;
2413*22ce4affSfengbojiang         const BYTE* const buf = (const BYTE*)ress.srcBuffer;
2414*22ce4affSfengbojiang         if (ress.srcBufferLoaded < toRead)  /* load up to 4 bytes for header */
2415*22ce4affSfengbojiang             ress.srcBufferLoaded += fread((char*)ress.srcBuffer + ress.srcBufferLoaded,
2416*22ce4affSfengbojiang                                           (size_t)1, toRead - ress.srcBufferLoaded, srcFile);
2417*22ce4affSfengbojiang         if (ress.srcBufferLoaded==0) {
2418*22ce4affSfengbojiang             if (readSomething==0) {  /* srcFile is empty (which is invalid) */
2419*22ce4affSfengbojiang                 DISPLAYLEVEL(1, "zstd: %s: unexpected end of file \n", srcFileName);
2420*22ce4affSfengbojiang                 return 1;
2421*22ce4affSfengbojiang             }  /* else, just reached frame boundary */
2422*22ce4affSfengbojiang             break;   /* no more input */
2423*22ce4affSfengbojiang         }
2424*22ce4affSfengbojiang         readSomething = 1;   /* there is at least 1 byte in srcFile */
2425*22ce4affSfengbojiang         if (ress.srcBufferLoaded < toRead) {
2426*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: unknown header \n", srcFileName);
2427*22ce4affSfengbojiang             return 1;
2428*22ce4affSfengbojiang         }
2429*22ce4affSfengbojiang         if (ZSTD_isFrame(buf, ress.srcBufferLoaded)) {
2430*22ce4affSfengbojiang             unsigned long long const frameSize = FIO_decompressZstdFrame(fCtx, &ress, srcFile, prefs, srcFileName, filesize);
2431*22ce4affSfengbojiang             if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
2432*22ce4affSfengbojiang             filesize += frameSize;
2433*22ce4affSfengbojiang         } else if (buf[0] == 31 && buf[1] == 139) { /* gz magic number */
2434*22ce4affSfengbojiang #ifdef ZSTD_GZDECOMPRESS
2435*22ce4affSfengbojiang             unsigned long long const frameSize = FIO_decompressGzFrame(&ress, srcFile, prefs, srcFileName);
2436*22ce4affSfengbojiang             if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
2437*22ce4affSfengbojiang             filesize += frameSize;
2438*22ce4affSfengbojiang #else
2439*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: gzip file cannot be uncompressed (zstd compiled without HAVE_ZLIB) -- ignored \n", srcFileName);
2440*22ce4affSfengbojiang             return 1;
2441*22ce4affSfengbojiang #endif
2442*22ce4affSfengbojiang         } else if ((buf[0] == 0xFD && buf[1] == 0x37)  /* xz magic number */
2443*22ce4affSfengbojiang                 || (buf[0] == 0x5D && buf[1] == 0x00)) { /* lzma header (no magic number) */
2444*22ce4affSfengbojiang #ifdef ZSTD_LZMADECOMPRESS
2445*22ce4affSfengbojiang             unsigned long long const frameSize = FIO_decompressLzmaFrame(&ress, srcFile, prefs, srcFileName, buf[0] != 0xFD);
2446*22ce4affSfengbojiang             if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
2447*22ce4affSfengbojiang             filesize += frameSize;
2448*22ce4affSfengbojiang #else
2449*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: xz/lzma file cannot be uncompressed (zstd compiled without HAVE_LZMA) -- ignored \n", srcFileName);
2450*22ce4affSfengbojiang             return 1;
2451*22ce4affSfengbojiang #endif
2452*22ce4affSfengbojiang         } else if (MEM_readLE32(buf) == LZ4_MAGICNUMBER) {
2453*22ce4affSfengbojiang #ifdef ZSTD_LZ4DECOMPRESS
2454*22ce4affSfengbojiang             unsigned long long const frameSize = FIO_decompressLz4Frame(&ress, srcFile, prefs, srcFileName);
2455*22ce4affSfengbojiang             if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
2456*22ce4affSfengbojiang             filesize += frameSize;
2457*22ce4affSfengbojiang #else
2458*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: lz4 file cannot be uncompressed (zstd compiled without HAVE_LZ4) -- ignored \n", srcFileName);
2459*22ce4affSfengbojiang             return 1;
2460*22ce4affSfengbojiang #endif
2461*22ce4affSfengbojiang         } else if ((prefs->overwrite) && !strcmp (dstFileName, stdoutmark)) {  /* pass-through mode */
2462*22ce4affSfengbojiang             return FIO_passThrough(prefs,
2463*22ce4affSfengbojiang                                    ress.dstFile, srcFile,
2464*22ce4affSfengbojiang                                    ress.srcBuffer, ress.srcBufferSize,
2465*22ce4affSfengbojiang                                    ress.srcBufferLoaded);
2466*22ce4affSfengbojiang         } else {
2467*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: unsupported format \n", srcFileName);
2468*22ce4affSfengbojiang             return 1;
2469*22ce4affSfengbojiang     }   }  /* for each frame */
2470*22ce4affSfengbojiang 
2471*22ce4affSfengbojiang     /* Final Status */
2472*22ce4affSfengbojiang     fCtx->totalBytesOutput += (size_t)filesize;
2473*22ce4affSfengbojiang     DISPLAYLEVEL(2, "\r%79s\r", "");
2474*22ce4affSfengbojiang     /* No status message in pipe mode (stdin - stdout) or multi-files mode */
2475*22ce4affSfengbojiang     if (g_display_prefs.displayLevel >= 2) {
2476*22ce4affSfengbojiang         if (fCtx->nbFilesTotal <= 1 || g_display_prefs.displayLevel >= 3) {
2477*22ce4affSfengbojiang             DISPLAYLEVEL(2, "%-20s: %llu bytes \n", srcFileName, filesize);
2478*22ce4affSfengbojiang         }
2479*22ce4affSfengbojiang     }
2480*22ce4affSfengbojiang 
2481*22ce4affSfengbojiang     return 0;
2482*22ce4affSfengbojiang }
2483*22ce4affSfengbojiang 
2484*22ce4affSfengbojiang /** FIO_decompressDstFile() :
2485*22ce4affSfengbojiang     open `dstFileName`,
2486*22ce4affSfengbojiang     or path-through if ress.dstFile is already != 0,
2487*22ce4affSfengbojiang     then start decompression process (FIO_decompressFrames()).
2488*22ce4affSfengbojiang     @return : 0 : OK
2489*22ce4affSfengbojiang               1 : operation aborted
2490*22ce4affSfengbojiang */
FIO_decompressDstFile(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,dRess_t ress,FILE * srcFile,const char * dstFileName,const char * srcFileName)2491*22ce4affSfengbojiang static int FIO_decompressDstFile(FIO_ctx_t* const fCtx,
2492*22ce4affSfengbojiang                                  FIO_prefs_t* const prefs,
2493*22ce4affSfengbojiang                                  dRess_t ress, FILE* srcFile,
2494*22ce4affSfengbojiang                                  const char* dstFileName, const char* srcFileName)
2495*22ce4affSfengbojiang {
2496*22ce4affSfengbojiang     int result;
2497*22ce4affSfengbojiang     stat_t statbuf;
2498*22ce4affSfengbojiang     int transfer_permissions = 0;
2499*22ce4affSfengbojiang     int releaseDstFile = 0;
2500*22ce4affSfengbojiang 
2501*22ce4affSfengbojiang     if ((ress.dstFile == NULL) && (prefs->testMode==0)) {
2502*22ce4affSfengbojiang         releaseDstFile = 1;
2503*22ce4affSfengbojiang 
2504*22ce4affSfengbojiang         ress.dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName);
2505*22ce4affSfengbojiang         if (ress.dstFile==NULL) return 1;
2506*22ce4affSfengbojiang 
2507*22ce4affSfengbojiang         /* Must only be added after FIO_openDstFile() succeeds.
2508*22ce4affSfengbojiang          * Otherwise we may delete the destination file if it already exists,
2509*22ce4affSfengbojiang          * and the user presses Ctrl-C when asked if they wish to overwrite.
2510*22ce4affSfengbojiang          */
2511*22ce4affSfengbojiang         addHandler(dstFileName);
2512*22ce4affSfengbojiang 
2513*22ce4affSfengbojiang         if ( strcmp(srcFileName, stdinmark)   /* special case : don't transfer permissions from stdin */
2514*22ce4affSfengbojiang           && UTIL_stat(srcFileName, &statbuf)
2515*22ce4affSfengbojiang           && UTIL_isRegularFileStat(&statbuf) )
2516*22ce4affSfengbojiang             transfer_permissions = 1;
2517*22ce4affSfengbojiang     }
2518*22ce4affSfengbojiang 
2519*22ce4affSfengbojiang     result = FIO_decompressFrames(fCtx, ress, srcFile, prefs, dstFileName, srcFileName);
2520*22ce4affSfengbojiang 
2521*22ce4affSfengbojiang     if (releaseDstFile) {
2522*22ce4affSfengbojiang         FILE* const dstFile = ress.dstFile;
2523*22ce4affSfengbojiang         clearHandler();
2524*22ce4affSfengbojiang         ress.dstFile = NULL;
2525*22ce4affSfengbojiang         if (fclose(dstFile)) {
2526*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno));
2527*22ce4affSfengbojiang             result = 1;
2528*22ce4affSfengbojiang         }
2529*22ce4affSfengbojiang 
2530*22ce4affSfengbojiang         if ( (result != 0)  /* operation failure */
2531*22ce4affSfengbojiang           && strcmp(dstFileName, stdoutmark)  /* special case : don't remove() stdout */
2532*22ce4affSfengbojiang           ) {
2533*22ce4affSfengbojiang             FIO_removeFile(dstFileName);  /* remove decompression artefact; note: don't do anything special if remove() fails */
2534*22ce4affSfengbojiang         } else if ( transfer_permissions /* file permissions correctly extracted from src */ ) {
2535*22ce4affSfengbojiang             UTIL_setFileStat(dstFileName, &statbuf);  /* transfer file permissions from src into dst */
2536*22ce4affSfengbojiang         }
2537*22ce4affSfengbojiang     }
2538*22ce4affSfengbojiang 
2539*22ce4affSfengbojiang     return result;
2540*22ce4affSfengbojiang }
2541*22ce4affSfengbojiang 
2542*22ce4affSfengbojiang 
2543*22ce4affSfengbojiang /** FIO_decompressSrcFile() :
2544*22ce4affSfengbojiang     Open `srcFileName`, transfer control to decompressDstFile()
2545*22ce4affSfengbojiang     @return : 0 : OK
2546*22ce4affSfengbojiang               1 : error
2547*22ce4affSfengbojiang */
FIO_decompressSrcFile(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,dRess_t ress,const char * dstFileName,const char * srcFileName)2548*22ce4affSfengbojiang static int FIO_decompressSrcFile(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, dRess_t ress, const char* dstFileName, const char* srcFileName)
2549*22ce4affSfengbojiang {
2550*22ce4affSfengbojiang     FILE* srcFile;
2551*22ce4affSfengbojiang     int result;
2552*22ce4affSfengbojiang 
2553*22ce4affSfengbojiang     if (UTIL_isDirectory(srcFileName)) {
2554*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
2555*22ce4affSfengbojiang         return 1;
2556*22ce4affSfengbojiang     }
2557*22ce4affSfengbojiang 
2558*22ce4affSfengbojiang     srcFile = FIO_openSrcFile(srcFileName);
2559*22ce4affSfengbojiang     if (srcFile==NULL) return 1;
2560*22ce4affSfengbojiang     ress.srcBufferLoaded = 0;
2561*22ce4affSfengbojiang 
2562*22ce4affSfengbojiang     result = FIO_decompressDstFile(fCtx, prefs, ress, srcFile, dstFileName, srcFileName);
2563*22ce4affSfengbojiang 
2564*22ce4affSfengbojiang     /* Close file */
2565*22ce4affSfengbojiang     if (fclose(srcFile)) {
2566*22ce4affSfengbojiang         DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));  /* error should not happen */
2567*22ce4affSfengbojiang         return 1;
2568*22ce4affSfengbojiang     }
2569*22ce4affSfengbojiang     if ( prefs->removeSrcFile  /* --rm */
2570*22ce4affSfengbojiang       && (result==0)      /* decompression successful */
2571*22ce4affSfengbojiang       && strcmp(srcFileName, stdinmark) ) /* not stdin */ {
2572*22ce4affSfengbojiang         /* We must clear the handler, since after this point calling it would
2573*22ce4affSfengbojiang          * delete both the source and destination files.
2574*22ce4affSfengbojiang          */
2575*22ce4affSfengbojiang         clearHandler();
2576*22ce4affSfengbojiang         if (FIO_removeFile(srcFileName)) {
2577*22ce4affSfengbojiang             /* failed to remove src file */
2578*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));
2579*22ce4affSfengbojiang             return 1;
2580*22ce4affSfengbojiang     }   }
2581*22ce4affSfengbojiang     return result;
2582*22ce4affSfengbojiang }
2583*22ce4affSfengbojiang 
2584*22ce4affSfengbojiang 
2585*22ce4affSfengbojiang 
FIO_decompressFilename(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,const char * dstFileName,const char * srcFileName,const char * dictFileName)2586*22ce4affSfengbojiang int FIO_decompressFilename(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs,
2587*22ce4affSfengbojiang                            const char* dstFileName, const char* srcFileName,
2588*22ce4affSfengbojiang                            const char* dictFileName)
2589*22ce4affSfengbojiang {
2590*22ce4affSfengbojiang     dRess_t const ress = FIO_createDResources(prefs, dictFileName);
2591*22ce4affSfengbojiang 
2592*22ce4affSfengbojiang     int const decodingError = FIO_decompressSrcFile(fCtx, prefs, ress, dstFileName, srcFileName);
2593*22ce4affSfengbojiang 
2594*22ce4affSfengbojiang     FIO_freeDResources(ress);
2595*22ce4affSfengbojiang     return decodingError;
2596*22ce4affSfengbojiang }
2597*22ce4affSfengbojiang 
2598*22ce4affSfengbojiang static const char *suffixList[] = {
2599*22ce4affSfengbojiang     ZSTD_EXTENSION,
2600*22ce4affSfengbojiang     TZSTD_EXTENSION,
2601*22ce4affSfengbojiang #ifndef ZSTD_NODECOMPRESS
2602*22ce4affSfengbojiang     ZSTD_ALT_EXTENSION,
2603*22ce4affSfengbojiang #endif
2604*22ce4affSfengbojiang #ifdef ZSTD_GZDECOMPRESS
2605*22ce4affSfengbojiang     GZ_EXTENSION,
2606*22ce4affSfengbojiang     TGZ_EXTENSION,
2607*22ce4affSfengbojiang #endif
2608*22ce4affSfengbojiang #ifdef ZSTD_LZMADECOMPRESS
2609*22ce4affSfengbojiang     LZMA_EXTENSION,
2610*22ce4affSfengbojiang     XZ_EXTENSION,
2611*22ce4affSfengbojiang     TXZ_EXTENSION,
2612*22ce4affSfengbojiang #endif
2613*22ce4affSfengbojiang #ifdef ZSTD_LZ4DECOMPRESS
2614*22ce4affSfengbojiang     LZ4_EXTENSION,
2615*22ce4affSfengbojiang     TLZ4_EXTENSION,
2616*22ce4affSfengbojiang #endif
2617*22ce4affSfengbojiang     NULL
2618*22ce4affSfengbojiang };
2619*22ce4affSfengbojiang 
2620*22ce4affSfengbojiang static const char *suffixListStr =
2621*22ce4affSfengbojiang     ZSTD_EXTENSION "/" TZSTD_EXTENSION
2622*22ce4affSfengbojiang #ifdef ZSTD_GZDECOMPRESS
2623*22ce4affSfengbojiang     "/" GZ_EXTENSION "/" TGZ_EXTENSION
2624*22ce4affSfengbojiang #endif
2625*22ce4affSfengbojiang #ifdef ZSTD_LZMADECOMPRESS
2626*22ce4affSfengbojiang     "/" LZMA_EXTENSION "/" XZ_EXTENSION "/" TXZ_EXTENSION
2627*22ce4affSfengbojiang #endif
2628*22ce4affSfengbojiang #ifdef ZSTD_LZ4DECOMPRESS
2629*22ce4affSfengbojiang     "/" LZ4_EXTENSION "/" TLZ4_EXTENSION
2630*22ce4affSfengbojiang #endif
2631*22ce4affSfengbojiang ;
2632*22ce4affSfengbojiang 
2633*22ce4affSfengbojiang /* FIO_determineDstName() :
2634*22ce4affSfengbojiang  * create a destination filename from a srcFileName.
2635*22ce4affSfengbojiang  * @return a pointer to it.
2636*22ce4affSfengbojiang  * @return == NULL if there is an error */
2637*22ce4affSfengbojiang static const char*
FIO_determineDstName(const char * srcFileName,const char * outDirName)2638*22ce4affSfengbojiang FIO_determineDstName(const char* srcFileName, const char* outDirName)
2639*22ce4affSfengbojiang {
2640*22ce4affSfengbojiang     static size_t dfnbCapacity = 0;
2641*22ce4affSfengbojiang     static char* dstFileNameBuffer = NULL;   /* using static allocation : this function cannot be multi-threaded */
2642*22ce4affSfengbojiang     size_t dstFileNameEndPos;
2643*22ce4affSfengbojiang     char* outDirFilename = NULL;
2644*22ce4affSfengbojiang     const char* dstSuffix = "";
2645*22ce4affSfengbojiang     size_t dstSuffixLen = 0;
2646*22ce4affSfengbojiang 
2647*22ce4affSfengbojiang     size_t sfnSize = strlen(srcFileName);
2648*22ce4affSfengbojiang 
2649*22ce4affSfengbojiang     size_t srcSuffixLen;
2650*22ce4affSfengbojiang     const char* const srcSuffix = strrchr(srcFileName, '.');
2651*22ce4affSfengbojiang     if (srcSuffix == NULL) {
2652*22ce4affSfengbojiang         DISPLAYLEVEL(1,
2653*22ce4affSfengbojiang             "zstd: %s: unknown suffix (%s expected). "
2654*22ce4affSfengbojiang             "Can't derive the output file name. "
2655*22ce4affSfengbojiang             "Specify it with -o dstFileName. Ignoring.\n",
2656*22ce4affSfengbojiang             srcFileName, suffixListStr);
2657*22ce4affSfengbojiang         return NULL;
2658*22ce4affSfengbojiang     }
2659*22ce4affSfengbojiang     srcSuffixLen = strlen(srcSuffix);
2660*22ce4affSfengbojiang 
2661*22ce4affSfengbojiang     {
2662*22ce4affSfengbojiang         const char** matchedSuffixPtr;
2663*22ce4affSfengbojiang         for (matchedSuffixPtr = suffixList; *matchedSuffixPtr != NULL; matchedSuffixPtr++) {
2664*22ce4affSfengbojiang             if (!strcmp(*matchedSuffixPtr, srcSuffix)) {
2665*22ce4affSfengbojiang                 break;
2666*22ce4affSfengbojiang             }
2667*22ce4affSfengbojiang         }
2668*22ce4affSfengbojiang 
2669*22ce4affSfengbojiang         /* check suffix is authorized */
2670*22ce4affSfengbojiang         if (sfnSize <= srcSuffixLen || *matchedSuffixPtr == NULL) {
2671*22ce4affSfengbojiang             DISPLAYLEVEL(1,
2672*22ce4affSfengbojiang                 "zstd: %s: unknown suffix (%s expected). "
2673*22ce4affSfengbojiang                 "Can't derive the output file name. "
2674*22ce4affSfengbojiang                 "Specify it with -o dstFileName. Ignoring.\n",
2675*22ce4affSfengbojiang                 srcFileName, suffixListStr);
2676*22ce4affSfengbojiang             return NULL;
2677*22ce4affSfengbojiang         }
2678*22ce4affSfengbojiang 
2679*22ce4affSfengbojiang         if ((*matchedSuffixPtr)[1] == 't') {
2680*22ce4affSfengbojiang             dstSuffix = ".tar";
2681*22ce4affSfengbojiang             dstSuffixLen = strlen(dstSuffix);
2682*22ce4affSfengbojiang         }
2683*22ce4affSfengbojiang     }
2684*22ce4affSfengbojiang 
2685*22ce4affSfengbojiang     if (outDirName) {
2686*22ce4affSfengbojiang         outDirFilename = FIO_createFilename_fromOutDir(srcFileName, outDirName, 0);
2687*22ce4affSfengbojiang         sfnSize = strlen(outDirFilename);
2688*22ce4affSfengbojiang         assert(outDirFilename != NULL);
2689*22ce4affSfengbojiang     }
2690*22ce4affSfengbojiang 
2691*22ce4affSfengbojiang     if (dfnbCapacity+srcSuffixLen <= sfnSize+1+dstSuffixLen) {
2692*22ce4affSfengbojiang         /* allocate enough space to write dstFilename into it */
2693*22ce4affSfengbojiang         free(dstFileNameBuffer);
2694*22ce4affSfengbojiang         dfnbCapacity = sfnSize + 20;
2695*22ce4affSfengbojiang         dstFileNameBuffer = (char*)malloc(dfnbCapacity);
2696*22ce4affSfengbojiang         if (dstFileNameBuffer==NULL)
2697*22ce4affSfengbojiang             EXM_THROW(74, "%s : not enough memory for dstFileName",
2698*22ce4affSfengbojiang                       strerror(errno));
2699*22ce4affSfengbojiang     }
2700*22ce4affSfengbojiang 
2701*22ce4affSfengbojiang     /* return dst name == src name truncated from suffix */
2702*22ce4affSfengbojiang     assert(dstFileNameBuffer != NULL);
2703*22ce4affSfengbojiang     dstFileNameEndPos = sfnSize - srcSuffixLen;
2704*22ce4affSfengbojiang     if (outDirFilename) {
2705*22ce4affSfengbojiang         memcpy(dstFileNameBuffer, outDirFilename, dstFileNameEndPos);
2706*22ce4affSfengbojiang         free(outDirFilename);
2707*22ce4affSfengbojiang     } else {
2708*22ce4affSfengbojiang         memcpy(dstFileNameBuffer, srcFileName, dstFileNameEndPos);
2709*22ce4affSfengbojiang     }
2710*22ce4affSfengbojiang 
2711*22ce4affSfengbojiang     /* The short tar extensions tzst, tgz, txz and tlz4 files should have "tar"
2712*22ce4affSfengbojiang      * extension on decompression. Also writes terminating null. */
2713*22ce4affSfengbojiang     strcpy(dstFileNameBuffer + dstFileNameEndPos, dstSuffix);
2714*22ce4affSfengbojiang     return dstFileNameBuffer;
2715*22ce4affSfengbojiang 
2716*22ce4affSfengbojiang     /* note : dstFileNameBuffer memory is not going to be free */
2717*22ce4affSfengbojiang }
2718*22ce4affSfengbojiang 
2719*22ce4affSfengbojiang int
FIO_decompressMultipleFilenames(FIO_ctx_t * const fCtx,FIO_prefs_t * const prefs,const char ** srcNamesTable,const char * outMirroredRootDirName,const char * outDirName,const char * outFileName,const char * dictFileName)2720*22ce4affSfengbojiang FIO_decompressMultipleFilenames(FIO_ctx_t* const fCtx,
2721*22ce4affSfengbojiang                                 FIO_prefs_t* const prefs,
2722*22ce4affSfengbojiang                                 const char** srcNamesTable,
2723*22ce4affSfengbojiang                                 const char* outMirroredRootDirName,
2724*22ce4affSfengbojiang                                 const char* outDirName, const char* outFileName,
2725*22ce4affSfengbojiang                                 const char* dictFileName)
2726*22ce4affSfengbojiang {
2727*22ce4affSfengbojiang     int status;
2728*22ce4affSfengbojiang     int error = 0;
2729*22ce4affSfengbojiang     dRess_t ress = FIO_createDResources(prefs, dictFileName);
2730*22ce4affSfengbojiang 
2731*22ce4affSfengbojiang     if (outFileName) {
2732*22ce4affSfengbojiang         if (FIO_removeMultiFilesWarning(fCtx, prefs, outFileName, 1 /* displayLevelCutoff */)) {
2733*22ce4affSfengbojiang             FIO_freeDResources(ress);
2734*22ce4affSfengbojiang             return 1;
2735*22ce4affSfengbojiang         }
2736*22ce4affSfengbojiang         if (!prefs->testMode) {
2737*22ce4affSfengbojiang             ress.dstFile = FIO_openDstFile(fCtx, prefs, NULL, outFileName);
2738*22ce4affSfengbojiang             if (ress.dstFile == 0) EXM_THROW(19, "cannot open %s", outFileName);
2739*22ce4affSfengbojiang         }
2740*22ce4affSfengbojiang         for (; fCtx->currFileIdx < fCtx->nbFilesTotal; fCtx->currFileIdx++) {
2741*22ce4affSfengbojiang             status = FIO_decompressSrcFile(fCtx, prefs, ress, outFileName, srcNamesTable[fCtx->currFileIdx]);
2742*22ce4affSfengbojiang             if (!status) fCtx->nbFilesProcessed++;
2743*22ce4affSfengbojiang             error |= status;
2744*22ce4affSfengbojiang         }
2745*22ce4affSfengbojiang         if ((!prefs->testMode) && (fclose(ress.dstFile)))
2746*22ce4affSfengbojiang             EXM_THROW(72, "Write error : %s : cannot properly close output file",
2747*22ce4affSfengbojiang                         strerror(errno));
2748*22ce4affSfengbojiang     } else {
2749*22ce4affSfengbojiang         if (outMirroredRootDirName)
2750*22ce4affSfengbojiang             UTIL_mirrorSourceFilesDirectories(srcNamesTable, fCtx->nbFilesTotal, outMirroredRootDirName);
2751*22ce4affSfengbojiang 
2752*22ce4affSfengbojiang         for (; fCtx->currFileIdx < fCtx->nbFilesTotal; fCtx->currFileIdx++) {   /* create dstFileName */
2753*22ce4affSfengbojiang             const char* const srcFileName = srcNamesTable[fCtx->currFileIdx];
2754*22ce4affSfengbojiang             const char* dstFileName = NULL;
2755*22ce4affSfengbojiang             if (outMirroredRootDirName) {
2756*22ce4affSfengbojiang                 char* validMirroredDirName = UTIL_createMirroredDestDirName(srcFileName, outMirroredRootDirName);
2757*22ce4affSfengbojiang                 if (validMirroredDirName) {
2758*22ce4affSfengbojiang                     dstFileName = FIO_determineDstName(srcFileName, validMirroredDirName);
2759*22ce4affSfengbojiang                     free(validMirroredDirName);
2760*22ce4affSfengbojiang                 } else {
2761*22ce4affSfengbojiang                     DISPLAYLEVEL(2, "zstd: --output-dir-mirror cannot decompress '%s' into '%s'\n", srcFileName, outMirroredRootDirName);
2762*22ce4affSfengbojiang                 }
2763*22ce4affSfengbojiang             } else {
2764*22ce4affSfengbojiang                 dstFileName = FIO_determineDstName(srcFileName, outDirName);
2765*22ce4affSfengbojiang             }
2766*22ce4affSfengbojiang             if (dstFileName == NULL) { error=1; continue; }
2767*22ce4affSfengbojiang             status = FIO_decompressSrcFile(fCtx, prefs, ress, dstFileName, srcFileName);
2768*22ce4affSfengbojiang             if (!status) fCtx->nbFilesProcessed++;
2769*22ce4affSfengbojiang             error |= status;
2770*22ce4affSfengbojiang         }
2771*22ce4affSfengbojiang         if (outDirName)
2772*22ce4affSfengbojiang             FIO_checkFilenameCollisions(srcNamesTable , fCtx->nbFilesTotal);
2773*22ce4affSfengbojiang     }
2774*22ce4affSfengbojiang 
2775*22ce4affSfengbojiang     if (fCtx->nbFilesProcessed >= 1  && fCtx->nbFilesTotal > 1 && fCtx->totalBytesOutput != 0)
2776*22ce4affSfengbojiang         DISPLAYLEVEL(2, "%d files decompressed : %6zu bytes total \n", fCtx->nbFilesProcessed, fCtx->totalBytesOutput);
2777*22ce4affSfengbojiang 
2778*22ce4affSfengbojiang     FIO_freeDResources(ress);
2779*22ce4affSfengbojiang     return error;
2780*22ce4affSfengbojiang }
2781*22ce4affSfengbojiang 
2782*22ce4affSfengbojiang /* **************************************************************************
2783*22ce4affSfengbojiang  *  .zst file info (--list command)
2784*22ce4affSfengbojiang  ***************************************************************************/
2785*22ce4affSfengbojiang 
2786*22ce4affSfengbojiang typedef struct {
2787*22ce4affSfengbojiang     U64 decompressedSize;
2788*22ce4affSfengbojiang     U64 compressedSize;
2789*22ce4affSfengbojiang     U64 windowSize;
2790*22ce4affSfengbojiang     int numActualFrames;
2791*22ce4affSfengbojiang     int numSkippableFrames;
2792*22ce4affSfengbojiang     int decompUnavailable;
2793*22ce4affSfengbojiang     int usesCheck;
2794*22ce4affSfengbojiang     U32 nbFiles;
2795*22ce4affSfengbojiang } fileInfo_t;
2796*22ce4affSfengbojiang 
2797*22ce4affSfengbojiang typedef enum {
2798*22ce4affSfengbojiang   info_success=0,
2799*22ce4affSfengbojiang   info_frame_error=1,
2800*22ce4affSfengbojiang   info_not_zstd=2,
2801*22ce4affSfengbojiang   info_file_error=3,
2802*22ce4affSfengbojiang   info_truncated_input=4,
2803*22ce4affSfengbojiang } InfoError;
2804*22ce4affSfengbojiang 
2805*22ce4affSfengbojiang #define ERROR_IF(c,n,...) {             \
2806*22ce4affSfengbojiang     if (c) {                           \
2807*22ce4affSfengbojiang         DISPLAYLEVEL(1, __VA_ARGS__);  \
2808*22ce4affSfengbojiang         DISPLAYLEVEL(1, " \n");        \
2809*22ce4affSfengbojiang         return n;                      \
2810*22ce4affSfengbojiang     }                                  \
2811*22ce4affSfengbojiang }
2812*22ce4affSfengbojiang 
2813*22ce4affSfengbojiang static InfoError
FIO_analyzeFrames(fileInfo_t * info,FILE * const srcFile)2814*22ce4affSfengbojiang FIO_analyzeFrames(fileInfo_t* info, FILE* const srcFile)
2815*22ce4affSfengbojiang {
2816*22ce4affSfengbojiang     /* begin analyzing frame */
2817*22ce4affSfengbojiang     for ( ; ; ) {
2818*22ce4affSfengbojiang         BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
2819*22ce4affSfengbojiang         size_t const numBytesRead = fread(headerBuffer, 1, sizeof(headerBuffer), srcFile);
2820*22ce4affSfengbojiang         if (numBytesRead < ZSTD_FRAMEHEADERSIZE_MIN(ZSTD_f_zstd1)) {
2821*22ce4affSfengbojiang             if ( feof(srcFile)
2822*22ce4affSfengbojiang               && (numBytesRead == 0)
2823*22ce4affSfengbojiang               && (info->compressedSize > 0)
2824*22ce4affSfengbojiang               && (info->compressedSize != UTIL_FILESIZE_UNKNOWN) ) {
2825*22ce4affSfengbojiang                 unsigned long long file_position = (unsigned long long) LONG_TELL(srcFile);
2826*22ce4affSfengbojiang                 unsigned long long file_size = (unsigned long long) info->compressedSize;
2827*22ce4affSfengbojiang                 ERROR_IF(file_position != file_size, info_truncated_input,
2828*22ce4affSfengbojiang                   "Error: seeked to position %llu, which is beyond file size of %llu\n",
2829*22ce4affSfengbojiang                   file_position,
2830*22ce4affSfengbojiang                   file_size);
2831*22ce4affSfengbojiang                 break;  /* correct end of file => success */
2832*22ce4affSfengbojiang             }
2833*22ce4affSfengbojiang             ERROR_IF(feof(srcFile), info_not_zstd, "Error: reached end of file with incomplete frame");
2834*22ce4affSfengbojiang             ERROR_IF(1, info_frame_error, "Error: did not reach end of file but ran out of frames");
2835*22ce4affSfengbojiang         }
2836*22ce4affSfengbojiang         {   U32 const magicNumber = MEM_readLE32(headerBuffer);
2837*22ce4affSfengbojiang             /* Zstandard frame */
2838*22ce4affSfengbojiang             if (magicNumber == ZSTD_MAGICNUMBER) {
2839*22ce4affSfengbojiang                 ZSTD_frameHeader header;
2840*22ce4affSfengbojiang                 U64 const frameContentSize = ZSTD_getFrameContentSize(headerBuffer, numBytesRead);
2841*22ce4affSfengbojiang                 if ( frameContentSize == ZSTD_CONTENTSIZE_ERROR
2842*22ce4affSfengbojiang                   || frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN ) {
2843*22ce4affSfengbojiang                     info->decompUnavailable = 1;
2844*22ce4affSfengbojiang                 } else {
2845*22ce4affSfengbojiang                     info->decompressedSize += frameContentSize;
2846*22ce4affSfengbojiang                 }
2847*22ce4affSfengbojiang                 ERROR_IF(ZSTD_getFrameHeader(&header, headerBuffer, numBytesRead) != 0,
2848*22ce4affSfengbojiang                         info_frame_error, "Error: could not decode frame header");
2849*22ce4affSfengbojiang                 info->windowSize = header.windowSize;
2850*22ce4affSfengbojiang                 /* move to the end of the frame header */
2851*22ce4affSfengbojiang                 {   size_t const headerSize = ZSTD_frameHeaderSize(headerBuffer, numBytesRead);
2852*22ce4affSfengbojiang                     ERROR_IF(ZSTD_isError(headerSize), info_frame_error, "Error: could not determine frame header size");
2853*22ce4affSfengbojiang                     ERROR_IF(fseek(srcFile, ((long)headerSize)-((long)numBytesRead), SEEK_CUR) != 0,
2854*22ce4affSfengbojiang                             info_frame_error, "Error: could not move to end of frame header");
2855*22ce4affSfengbojiang                 }
2856*22ce4affSfengbojiang 
2857*22ce4affSfengbojiang                 /* skip all blocks in the frame */
2858*22ce4affSfengbojiang                 {   int lastBlock = 0;
2859*22ce4affSfengbojiang                     do {
2860*22ce4affSfengbojiang                         BYTE blockHeaderBuffer[3];
2861*22ce4affSfengbojiang                         ERROR_IF(fread(blockHeaderBuffer, 1, 3, srcFile) != 3,
2862*22ce4affSfengbojiang                                 info_frame_error, "Error while reading block header");
2863*22ce4affSfengbojiang                         {   U32 const blockHeader = MEM_readLE24(blockHeaderBuffer);
2864*22ce4affSfengbojiang                             U32 const blockTypeID = (blockHeader >> 1) & 3;
2865*22ce4affSfengbojiang                             U32 const isRLE = (blockTypeID == 1);
2866*22ce4affSfengbojiang                             U32 const isWrongBlock = (blockTypeID == 3);
2867*22ce4affSfengbojiang                             long const blockSize = isRLE ? 1 : (long)(blockHeader >> 3);
2868*22ce4affSfengbojiang                             ERROR_IF(isWrongBlock, info_frame_error, "Error: unsupported block type");
2869*22ce4affSfengbojiang                             lastBlock = blockHeader & 1;
2870*22ce4affSfengbojiang                             ERROR_IF(fseek(srcFile, blockSize, SEEK_CUR) != 0,
2871*22ce4affSfengbojiang                                     info_frame_error, "Error: could not skip to end of block");
2872*22ce4affSfengbojiang                         }
2873*22ce4affSfengbojiang                     } while (lastBlock != 1);
2874*22ce4affSfengbojiang                 }
2875*22ce4affSfengbojiang 
2876*22ce4affSfengbojiang                 /* check if checksum is used */
2877*22ce4affSfengbojiang                 {   BYTE const frameHeaderDescriptor = headerBuffer[4];
2878*22ce4affSfengbojiang                     int const contentChecksumFlag = (frameHeaderDescriptor & (1 << 2)) >> 2;
2879*22ce4affSfengbojiang                     if (contentChecksumFlag) {
2880*22ce4affSfengbojiang                         info->usesCheck = 1;
2881*22ce4affSfengbojiang                         ERROR_IF(fseek(srcFile, 4, SEEK_CUR) != 0,
2882*22ce4affSfengbojiang                                 info_frame_error, "Error: could not skip past checksum");
2883*22ce4affSfengbojiang                 }   }
2884*22ce4affSfengbojiang                 info->numActualFrames++;
2885*22ce4affSfengbojiang             }
2886*22ce4affSfengbojiang             /* Skippable frame */
2887*22ce4affSfengbojiang             else if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
2888*22ce4affSfengbojiang                 U32 const frameSize = MEM_readLE32(headerBuffer + 4);
2889*22ce4affSfengbojiang                 long const seek = (long)(8 + frameSize - numBytesRead);
2890*22ce4affSfengbojiang                 ERROR_IF(LONG_SEEK(srcFile, seek, SEEK_CUR) != 0,
2891*22ce4affSfengbojiang                         info_frame_error, "Error: could not find end of skippable frame");
2892*22ce4affSfengbojiang                 info->numSkippableFrames++;
2893*22ce4affSfengbojiang             }
2894*22ce4affSfengbojiang             /* unknown content */
2895*22ce4affSfengbojiang             else {
2896*22ce4affSfengbojiang                 return info_not_zstd;
2897*22ce4affSfengbojiang             }
2898*22ce4affSfengbojiang         }  /* magic number analysis */
2899*22ce4affSfengbojiang     }  /* end analyzing frames */
2900*22ce4affSfengbojiang     return info_success;
2901*22ce4affSfengbojiang }
2902*22ce4affSfengbojiang 
2903*22ce4affSfengbojiang 
2904*22ce4affSfengbojiang static InfoError
getFileInfo_fileConfirmed(fileInfo_t * info,const char * inFileName)2905*22ce4affSfengbojiang getFileInfo_fileConfirmed(fileInfo_t* info, const char* inFileName)
2906*22ce4affSfengbojiang {
2907*22ce4affSfengbojiang     InfoError status;
2908*22ce4affSfengbojiang     FILE* const srcFile = FIO_openSrcFile(inFileName);
2909*22ce4affSfengbojiang     ERROR_IF(srcFile == NULL, info_file_error, "Error: could not open source file %s", inFileName);
2910*22ce4affSfengbojiang 
2911*22ce4affSfengbojiang     info->compressedSize = UTIL_getFileSize(inFileName);
2912*22ce4affSfengbojiang     status = FIO_analyzeFrames(info, srcFile);
2913*22ce4affSfengbojiang 
2914*22ce4affSfengbojiang     fclose(srcFile);
2915*22ce4affSfengbojiang     info->nbFiles = 1;
2916*22ce4affSfengbojiang     return status;
2917*22ce4affSfengbojiang }
2918*22ce4affSfengbojiang 
2919*22ce4affSfengbojiang 
2920*22ce4affSfengbojiang /** getFileInfo() :
2921*22ce4affSfengbojiang  *  Reads information from file, stores in *info
2922*22ce4affSfengbojiang  * @return : InfoError status
2923*22ce4affSfengbojiang  */
2924*22ce4affSfengbojiang static InfoError
getFileInfo(fileInfo_t * info,const char * srcFileName)2925*22ce4affSfengbojiang getFileInfo(fileInfo_t* info, const char* srcFileName)
2926*22ce4affSfengbojiang {
2927*22ce4affSfengbojiang     ERROR_IF(!UTIL_isRegularFile(srcFileName),
2928*22ce4affSfengbojiang             info_file_error, "Error : %s is not a file", srcFileName);
2929*22ce4affSfengbojiang     return getFileInfo_fileConfirmed(info, srcFileName);
2930*22ce4affSfengbojiang }
2931*22ce4affSfengbojiang 
2932*22ce4affSfengbojiang 
2933*22ce4affSfengbojiang static void
displayInfo(const char * inFileName,const fileInfo_t * info,int displayLevel)2934*22ce4affSfengbojiang displayInfo(const char* inFileName, const fileInfo_t* info, int displayLevel)
2935*22ce4affSfengbojiang {
2936*22ce4affSfengbojiang     unsigned const unit = info->compressedSize < (1 MB) ? (1 KB) : (1 MB);
2937*22ce4affSfengbojiang     const char* const unitStr = info->compressedSize < (1 MB) ? "KB" : "MB";
2938*22ce4affSfengbojiang     double const windowSizeUnit = (double)info->windowSize / unit;
2939*22ce4affSfengbojiang     double const compressedSizeUnit = (double)info->compressedSize / unit;
2940*22ce4affSfengbojiang     double const decompressedSizeUnit = (double)info->decompressedSize / unit;
2941*22ce4affSfengbojiang     double const ratio = (info->compressedSize == 0) ? 0 : ((double)info->decompressedSize)/info->compressedSize;
2942*22ce4affSfengbojiang     const char* const checkString = (info->usesCheck ? "XXH64" : "None");
2943*22ce4affSfengbojiang     if (displayLevel <= 2) {
2944*22ce4affSfengbojiang         if (!info->decompUnavailable) {
2945*22ce4affSfengbojiang             DISPLAYOUT("%6d  %5d  %7.2f %2s  %9.2f %2s  %5.3f  %5s  %s\n",
2946*22ce4affSfengbojiang                     info->numSkippableFrames + info->numActualFrames,
2947*22ce4affSfengbojiang                     info->numSkippableFrames,
2948*22ce4affSfengbojiang                     compressedSizeUnit, unitStr, decompressedSizeUnit, unitStr,
2949*22ce4affSfengbojiang                     ratio, checkString, inFileName);
2950*22ce4affSfengbojiang         } else {
2951*22ce4affSfengbojiang             DISPLAYOUT("%6d  %5d  %7.2f %2s                       %5s  %s\n",
2952*22ce4affSfengbojiang                     info->numSkippableFrames + info->numActualFrames,
2953*22ce4affSfengbojiang                     info->numSkippableFrames,
2954*22ce4affSfengbojiang                     compressedSizeUnit, unitStr,
2955*22ce4affSfengbojiang                     checkString, inFileName);
2956*22ce4affSfengbojiang         }
2957*22ce4affSfengbojiang     } else {
2958*22ce4affSfengbojiang         DISPLAYOUT("%s \n", inFileName);
2959*22ce4affSfengbojiang         DISPLAYOUT("# Zstandard Frames: %d\n", info->numActualFrames);
2960*22ce4affSfengbojiang         if (info->numSkippableFrames)
2961*22ce4affSfengbojiang             DISPLAYOUT("# Skippable Frames: %d\n", info->numSkippableFrames);
2962*22ce4affSfengbojiang         DISPLAYOUT("Window Size: %.2f %2s (%llu B)\n",
2963*22ce4affSfengbojiang                    windowSizeUnit, unitStr,
2964*22ce4affSfengbojiang                    (unsigned long long)info->windowSize);
2965*22ce4affSfengbojiang         DISPLAYOUT("Compressed Size: %.2f %2s (%llu B)\n",
2966*22ce4affSfengbojiang                     compressedSizeUnit, unitStr,
2967*22ce4affSfengbojiang                     (unsigned long long)info->compressedSize);
2968*22ce4affSfengbojiang         if (!info->decompUnavailable) {
2969*22ce4affSfengbojiang             DISPLAYOUT("Decompressed Size: %.2f %2s (%llu B)\n",
2970*22ce4affSfengbojiang                     decompressedSizeUnit, unitStr,
2971*22ce4affSfengbojiang                     (unsigned long long)info->decompressedSize);
2972*22ce4affSfengbojiang             DISPLAYOUT("Ratio: %.4f\n", ratio);
2973*22ce4affSfengbojiang         }
2974*22ce4affSfengbojiang         DISPLAYOUT("Check: %s\n", checkString);
2975*22ce4affSfengbojiang         DISPLAYOUT("\n");
2976*22ce4affSfengbojiang     }
2977*22ce4affSfengbojiang }
2978*22ce4affSfengbojiang 
FIO_addFInfo(fileInfo_t fi1,fileInfo_t fi2)2979*22ce4affSfengbojiang static fileInfo_t FIO_addFInfo(fileInfo_t fi1, fileInfo_t fi2)
2980*22ce4affSfengbojiang {
2981*22ce4affSfengbojiang     fileInfo_t total;
2982*22ce4affSfengbojiang     memset(&total, 0, sizeof(total));
2983*22ce4affSfengbojiang     total.numActualFrames = fi1.numActualFrames + fi2.numActualFrames;
2984*22ce4affSfengbojiang     total.numSkippableFrames = fi1.numSkippableFrames + fi2.numSkippableFrames;
2985*22ce4affSfengbojiang     total.compressedSize = fi1.compressedSize + fi2.compressedSize;
2986*22ce4affSfengbojiang     total.decompressedSize = fi1.decompressedSize + fi2.decompressedSize;
2987*22ce4affSfengbojiang     total.decompUnavailable = fi1.decompUnavailable | fi2.decompUnavailable;
2988*22ce4affSfengbojiang     total.usesCheck = fi1.usesCheck & fi2.usesCheck;
2989*22ce4affSfengbojiang     total.nbFiles = fi1.nbFiles + fi2.nbFiles;
2990*22ce4affSfengbojiang     return total;
2991*22ce4affSfengbojiang }
2992*22ce4affSfengbojiang 
2993*22ce4affSfengbojiang static int
FIO_listFile(fileInfo_t * total,const char * inFileName,int displayLevel)2994*22ce4affSfengbojiang FIO_listFile(fileInfo_t* total, const char* inFileName, int displayLevel)
2995*22ce4affSfengbojiang {
2996*22ce4affSfengbojiang     fileInfo_t info;
2997*22ce4affSfengbojiang     memset(&info, 0, sizeof(info));
2998*22ce4affSfengbojiang     {   InfoError const error = getFileInfo(&info, inFileName);
2999*22ce4affSfengbojiang         switch (error) {
3000*22ce4affSfengbojiang             case info_frame_error:
3001*22ce4affSfengbojiang                 /* display error, but provide output */
3002*22ce4affSfengbojiang                 DISPLAYLEVEL(1, "Error while parsing \"%s\" \n", inFileName);
3003*22ce4affSfengbojiang                 break;
3004*22ce4affSfengbojiang             case info_not_zstd:
3005*22ce4affSfengbojiang                 DISPLAYOUT("File \"%s\" not compressed by zstd \n", inFileName);
3006*22ce4affSfengbojiang                 if (displayLevel > 2) DISPLAYOUT("\n");
3007*22ce4affSfengbojiang                 return 1;
3008*22ce4affSfengbojiang             case info_file_error:
3009*22ce4affSfengbojiang                 /* error occurred while opening the file */
3010*22ce4affSfengbojiang                 if (displayLevel > 2) DISPLAYOUT("\n");
3011*22ce4affSfengbojiang                 return 1;
3012*22ce4affSfengbojiang             case info_truncated_input:
3013*22ce4affSfengbojiang                 DISPLAYOUT("File \"%s\" is truncated \n", inFileName);
3014*22ce4affSfengbojiang                 if (displayLevel > 2) DISPLAYOUT("\n");
3015*22ce4affSfengbojiang                 return 1;
3016*22ce4affSfengbojiang             case info_success:
3017*22ce4affSfengbojiang             default:
3018*22ce4affSfengbojiang                 break;
3019*22ce4affSfengbojiang         }
3020*22ce4affSfengbojiang 
3021*22ce4affSfengbojiang         displayInfo(inFileName, &info, displayLevel);
3022*22ce4affSfengbojiang         *total = FIO_addFInfo(*total, info);
3023*22ce4affSfengbojiang         assert(error == info_success || error == info_frame_error);
3024*22ce4affSfengbojiang         return (int)error;
3025*22ce4affSfengbojiang     }
3026*22ce4affSfengbojiang }
3027*22ce4affSfengbojiang 
FIO_listMultipleFiles(unsigned numFiles,const char ** filenameTable,int displayLevel)3028*22ce4affSfengbojiang int FIO_listMultipleFiles(unsigned numFiles, const char** filenameTable, int displayLevel)
3029*22ce4affSfengbojiang {
3030*22ce4affSfengbojiang     /* ensure no specified input is stdin (needs fseek() capability) */
3031*22ce4affSfengbojiang     {   unsigned u;
3032*22ce4affSfengbojiang         for (u=0; u<numFiles;u++) {
3033*22ce4affSfengbojiang             ERROR_IF(!strcmp (filenameTable[u], stdinmark),
3034*22ce4affSfengbojiang                     1, "zstd: --list does not support reading from standard input");
3035*22ce4affSfengbojiang     }   }
3036*22ce4affSfengbojiang 
3037*22ce4affSfengbojiang     if (numFiles == 0) {
3038*22ce4affSfengbojiang         if (!IS_CONSOLE(stdin)) {
3039*22ce4affSfengbojiang             DISPLAYLEVEL(1, "zstd: --list does not support reading from standard input \n");
3040*22ce4affSfengbojiang         }
3041*22ce4affSfengbojiang         DISPLAYLEVEL(1, "No files given \n");
3042*22ce4affSfengbojiang         return 1;
3043*22ce4affSfengbojiang     }
3044*22ce4affSfengbojiang 
3045*22ce4affSfengbojiang     if (displayLevel <= 2) {
3046*22ce4affSfengbojiang         DISPLAYOUT("Frames  Skips  Compressed  Uncompressed  Ratio  Check  Filename\n");
3047*22ce4affSfengbojiang     }
3048*22ce4affSfengbojiang     {   int error = 0;
3049*22ce4affSfengbojiang         fileInfo_t total;
3050*22ce4affSfengbojiang         memset(&total, 0, sizeof(total));
3051*22ce4affSfengbojiang         total.usesCheck = 1;
3052*22ce4affSfengbojiang         /* --list each file, and check for any error */
3053*22ce4affSfengbojiang         {   unsigned u;
3054*22ce4affSfengbojiang             for (u=0; u<numFiles;u++) {
3055*22ce4affSfengbojiang                 error |= FIO_listFile(&total, filenameTable[u], displayLevel);
3056*22ce4affSfengbojiang         }   }
3057*22ce4affSfengbojiang         if (numFiles > 1 && displayLevel <= 2) {   /* display total */
3058*22ce4affSfengbojiang             unsigned const unit = total.compressedSize < (1 MB) ? (1 KB) : (1 MB);
3059*22ce4affSfengbojiang             const char* const unitStr = total.compressedSize < (1 MB) ? "KB" : "MB";
3060*22ce4affSfengbojiang             double const compressedSizeUnit = (double)total.compressedSize / unit;
3061*22ce4affSfengbojiang             double const decompressedSizeUnit = (double)total.decompressedSize / unit;
3062*22ce4affSfengbojiang             double const ratio = (total.compressedSize == 0) ? 0 : ((double)total.decompressedSize)/total.compressedSize;
3063*22ce4affSfengbojiang             const char* const checkString = (total.usesCheck ? "XXH64" : "");
3064*22ce4affSfengbojiang             DISPLAYOUT("----------------------------------------------------------------- \n");
3065*22ce4affSfengbojiang             if (total.decompUnavailable) {
3066*22ce4affSfengbojiang                 DISPLAYOUT("%6d  %5d  %7.2f %2s                       %5s  %u files\n",
3067*22ce4affSfengbojiang                         total.numSkippableFrames + total.numActualFrames,
3068*22ce4affSfengbojiang                         total.numSkippableFrames,
3069*22ce4affSfengbojiang                         compressedSizeUnit, unitStr,
3070*22ce4affSfengbojiang                         checkString, (unsigned)total.nbFiles);
3071*22ce4affSfengbojiang             } else {
3072*22ce4affSfengbojiang                 DISPLAYOUT("%6d  %5d  %7.2f %2s  %9.2f %2s  %5.3f  %5s  %u files\n",
3073*22ce4affSfengbojiang                         total.numSkippableFrames + total.numActualFrames,
3074*22ce4affSfengbojiang                         total.numSkippableFrames,
3075*22ce4affSfengbojiang                         compressedSizeUnit, unitStr, decompressedSizeUnit, unitStr,
3076*22ce4affSfengbojiang                         ratio, checkString, (unsigned)total.nbFiles);
3077*22ce4affSfengbojiang         }   }
3078*22ce4affSfengbojiang         return error;
3079*22ce4affSfengbojiang     }
3080*22ce4affSfengbojiang }
3081*22ce4affSfengbojiang 
3082*22ce4affSfengbojiang 
3083*22ce4affSfengbojiang #endif /* #ifndef ZSTD_NODECOMPRESS */
3084