2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
12 /* *************************************
14 ***************************************/
15 #ifdef _MSC_VER /* Visual */
16 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
17 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
19 #if defined(__MINGW32__) && !defined(_POSIX_SOURCE)
20 # define _POSIX_SOURCE 1 /* disable %llu warnings with MinGW on Windows */
23 /*-*************************************
25 ***************************************/
26 #include "platform.h" /* Large Files support, SET_BINARY_MODE */
27 #include "util.h" /* UTIL_getFileSize, UTIL_isRegularFile */
28 #include <stdio.h> /* fprintf, fopen, fread, _fileno, stdin, stdout */
29 #include <stdlib.h> /* malloc, free */
30 #include <string.h> /* strcmp, strlen */
32 #include <errno.h> /* errno */
35 #if defined (_MSC_VER)
36 # include <sys/stat.h>
40 #include "mem.h" /* U32, U64 */
43 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_magicNumber, ZSTD_frameHeaderSize_max */
45 #include "zstd_errors.h" /* ZSTD_error_frameParameter_windowTooLarge */
47 #if defined(ZSTD_GZCOMPRESS) || defined(ZSTD_GZDECOMPRESS)
49 # if !defined(z_const)
54 #if defined(ZSTD_LZMACOMPRESS) || defined(ZSTD_LZMADECOMPRESS)
58 #define LZ4_MAGICNUMBER 0x184D2204
59 #if defined(ZSTD_LZ4COMPRESS) || defined(ZSTD_LZ4DECOMPRESS)
60 # define LZ4F_ENABLE_OBSOLETE_ENUMS
61 # include <lz4frame.h>
66 /*-*************************************
68 ***************************************/
73 #define ADAPT_WINDOWLOG_DEFAULT 23 /* 8 MB */
74 #define DICTSIZE_MAX (32 MB) /* protection against large input (attack scenario) */
79 /*-*************************************
81 ***************************************/
82 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
83 #define DISPLAYOUT(...) fprintf(stdout, __VA_ARGS__)
84 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
85 static int g_displayLevel = 2; /* 0 : no display; 1: errors; 2: + result + interaction + warnings; 3: + progression; 4: + information */
86 void FIO_setNotificationLevel(unsigned level) { g_displayLevel=level; }
88 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
89 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
91 #define READY_FOR_UPDATE() (UTIL_clockSpanMicro(g_displayClock) > g_refreshRate)
92 #define DELAY_NEXT_UPDATE() { g_displayClock = UTIL_getTime(); }
93 #define DISPLAYUPDATE(l, ...) { \
94 if (g_displayLevel>=l) { \
95 if (READY_FOR_UPDATE() || (g_displayLevel>=4)) { \
96 DELAY_NEXT_UPDATE(); \
97 DISPLAY(__VA_ARGS__); \
98 if (g_displayLevel>=4) fflush(stderr); \
101 #undef MIN /* in case it would be already defined */
102 #define MIN(a,b) ((a) < (b) ? (a) : (b))
105 #define EXM_THROW(error, ...) \
107 DISPLAYLEVEL(1, "zstd: "); \
108 DISPLAYLEVEL(5, "Error defined at %s, line %i : \n", __FILE__, __LINE__); \
109 DISPLAYLEVEL(1, "error %i : ", error); \
110 DISPLAYLEVEL(1, __VA_ARGS__); \
111 DISPLAYLEVEL(1, " \n"); \
115 #define CHECK_V(v, f) \
117 if (ZSTD_isError(v)) { \
118 DISPLAYLEVEL(5, "%s \n", #f); \
119 EXM_THROW(11, "%s", ZSTD_getErrorName(v)); \
121 #define CHECK(f) { size_t err; CHECK_V(err, f); }
124 /*-************************************
125 * Signal (Ctrl-C trapping)
126 **************************************/
127 static const char* g_artefact = NULL;
128 static void INThandler(int sig)
130 assert(sig==SIGINT); (void)sig;
131 #if !defined(_MSC_VER)
132 signal(sig, SIG_IGN); /* this invocation generates a buggy warning in Visual Studio */
135 assert(UTIL_isRegularFile(g_artefact));
141 static void addHandler(char const* dstFileName)
143 if (UTIL_isRegularFile(dstFileName)) {
144 g_artefact = dstFileName;
145 signal(SIGINT, INThandler);
151 static void clearHandler(void)
153 if (g_artefact) signal(SIGINT, SIG_DFL);
158 /*-*********************************************************
159 * Termination signal trapping (Print debug stack trace)
160 ***********************************************************/
161 #if defined(__has_feature) && !defined(BACKTRACE_ENABLE) /* Clang compiler */
162 # if (__has_feature(address_sanitizer))
163 # define BACKTRACE_ENABLE 0
164 # endif /* __has_feature(address_sanitizer) */
165 #elif defined(__SANITIZE_ADDRESS__) && !defined(BACKTRACE_ENABLE) /* GCC compiler */
166 # define BACKTRACE_ENABLE 0
169 #if !defined(BACKTRACE_ENABLE)
170 /* automatic detector : backtrace enabled by default on linux+glibc and osx */
171 # if (defined(__linux__) && defined(__GLIBC__)) \
172 || (defined(__APPLE__) && defined(__MACH__))
173 # define BACKTRACE_ENABLE 1
175 # define BACKTRACE_ENABLE 0
179 /* note : after this point, BACKTRACE_ENABLE is necessarily defined */
184 #include <execinfo.h> /* backtrace, backtrace_symbols */
186 #define MAX_STACK_FRAMES 50
188 static void ABRThandler(int sig) {
190 void* addrlist[MAX_STACK_FRAMES];
195 case SIGABRT: name = "SIGABRT"; break;
196 case SIGFPE: name = "SIGFPE"; break;
197 case SIGILL: name = "SIGILL"; break;
198 case SIGINT: name = "SIGINT"; break;
199 case SIGSEGV: name = "SIGSEGV"; break;
200 default: name = "UNKNOWN";
203 DISPLAY("Caught %s signal, printing stack:\n", name);
204 /* Retrieve current stack addresses. */
205 addrlen = backtrace(addrlist, MAX_STACK_FRAMES);
210 /* Create readable strings to each frame. */
211 symbollist = backtrace_symbols(addrlist, addrlen);
212 /* Print the stack trace, excluding calls handling the signal. */
213 for (i = ZSTD_START_SYMBOLLIST_FRAME; i < addrlen; i++) {
214 DISPLAY("%s\n", symbollist[i]);
217 /* Reset and raise the signal so default handler runs. */
218 signal(sig, SIG_DFL);
223 void FIO_addAbortHandler()
226 signal(SIGABRT, ABRThandler);
227 signal(SIGFPE, ABRThandler);
228 signal(SIGILL, ABRThandler);
229 signal(SIGSEGV, ABRThandler);
230 signal(SIGBUS, ABRThandler);
235 /*-************************************************************
236 * Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
237 ***************************************************************/
238 #if defined(_MSC_VER) && _MSC_VER >= 1400
239 # define LONG_SEEK _fseeki64
240 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */
241 # define LONG_SEEK fseeko
242 #elif defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)
243 # define LONG_SEEK fseeko64
244 #elif defined(_WIN32) && !defined(__DJGPP__)
245 # include <windows.h>
246 static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
249 off.QuadPart = offset;
250 if (origin == SEEK_END)
252 else if (origin == SEEK_CUR)
253 method = FILE_CURRENT;
257 if (SetFilePointerEx((HANDLE) _get_osfhandle(_fileno(file)), off, NULL, method))
263 # define LONG_SEEK fseek
267 /*-*************************************
268 * Local Parameters - Not thread safe
269 ***************************************/
270 static FIO_compressionType_t g_compressionType = FIO_zstdCompression;
271 void FIO_setCompressionType(FIO_compressionType_t compressionType) { g_compressionType = compressionType; }
272 static U32 g_overwrite = 0;
273 void FIO_overwriteMode(void) { g_overwrite=1; }
274 static U32 g_sparseFileSupport = 1; /* 0: no sparse allowed; 1: auto (file yes, stdout no); 2: force sparse */
275 void FIO_setSparseWrite(unsigned sparse) { g_sparseFileSupport=sparse; }
276 static U32 g_dictIDFlag = 1;
277 void FIO_setDictIDFlag(unsigned dictIDFlag) { g_dictIDFlag = dictIDFlag; }
278 static U32 g_checksumFlag = 1;
279 void FIO_setChecksumFlag(unsigned checksumFlag) { g_checksumFlag = checksumFlag; }
280 static U32 g_removeSrcFile = 0;
281 void FIO_setRemoveSrcFile(unsigned flag) { g_removeSrcFile = (flag>0); }
282 static U32 g_memLimit = 0;
283 void FIO_setMemLimit(unsigned memLimit) { g_memLimit = memLimit; }
284 static U32 g_nbWorkers = 1;
285 void FIO_setNbWorkers(unsigned nbWorkers) {
286 #ifndef ZSTD_MULTITHREAD
287 if (nbWorkers > 0) DISPLAYLEVEL(2, "Note : multi-threading is disabled \n");
289 g_nbWorkers = nbWorkers;
291 static U32 g_blockSize = 0;
292 void FIO_setBlockSize(unsigned blockSize) {
293 if (blockSize && g_nbWorkers==0)
294 DISPLAYLEVEL(2, "Setting block size is useless in single-thread mode \n");
295 g_blockSize = blockSize;
297 #define FIO_OVERLAP_LOG_NOTSET 9999
298 static U32 g_overlapLog = FIO_OVERLAP_LOG_NOTSET;
299 void FIO_setOverlapLog(unsigned overlapLog){
300 if (overlapLog && g_nbWorkers==0)
301 DISPLAYLEVEL(2, "Setting overlapLog is useless in single-thread mode \n");
302 g_overlapLog = overlapLog;
304 static U32 g_adaptiveMode = 0;
305 void FIO_setAdaptiveMode(unsigned adapt) {
306 if ((adapt>0) && (g_nbWorkers==0))
307 EXM_THROW(1, "Adaptive mode is not compatible with single thread mode \n");
308 g_adaptiveMode = adapt;
310 static int g_minAdaptLevel = -50; /* initializing this value requires a constant, so ZSTD_minCLevel() doesn't work */
311 void FIO_setAdaptMin(int minCLevel)
313 #ifndef ZSTD_NOCOMPRESS
314 assert(minCLevel >= ZSTD_minCLevel());
316 g_minAdaptLevel = minCLevel;
318 static int g_maxAdaptLevel = 22; /* initializing this value requires a constant, so ZSTD_maxCLevel() doesn't work */
319 void FIO_setAdaptMax(int maxCLevel)
321 g_maxAdaptLevel = maxCLevel;
324 static U32 g_ldmFlag = 0;
325 void FIO_setLdmFlag(unsigned ldmFlag) {
326 g_ldmFlag = (ldmFlag>0);
328 static U32 g_ldmHashLog = 0;
329 void FIO_setLdmHashLog(unsigned ldmHashLog) {
330 g_ldmHashLog = ldmHashLog;
332 static U32 g_ldmMinMatch = 0;
333 void FIO_setLdmMinMatch(unsigned ldmMinMatch) {
334 g_ldmMinMatch = ldmMinMatch;
337 #define FIO_LDM_PARAM_NOTSET 9999
338 static U32 g_ldmBucketSizeLog = FIO_LDM_PARAM_NOTSET;
339 void FIO_setLdmBucketSizeLog(unsigned ldmBucketSizeLog) {
340 g_ldmBucketSizeLog = ldmBucketSizeLog;
343 static U32 g_ldmHashEveryLog = FIO_LDM_PARAM_NOTSET;
344 void FIO_setLdmHashEveryLog(unsigned ldmHashEveryLog) {
345 g_ldmHashEveryLog = ldmHashEveryLog;
350 /*-*************************************
352 ***************************************/
354 * @result : Unlink `fileName`, even if it's read-only */
355 static int FIO_remove(const char* path)
357 if (!UTIL_isRegularFile(path)) {
358 DISPLAYLEVEL(2, "zstd: Refusing to remove non-regular file %s\n", path);
361 #if defined(_WIN32) || defined(WIN32)
362 /* windows doesn't allow remove read-only files,
363 * so try to make it writable first */
364 chmod(path, _S_IWRITE);
369 /** FIO_openSrcFile() :
370 * condition : `srcFileName` must be non-NULL.
371 * @result : FILE* to `srcFileName`, or NULL if it fails */
372 static FILE* FIO_openSrcFile(const char* srcFileName)
374 assert(srcFileName != NULL);
375 if (!strcmp (srcFileName, stdinmark)) {
376 DISPLAYLEVEL(4,"Using stdin for input\n");
377 SET_BINARY_MODE(stdin);
381 if (!UTIL_isRegularFile(srcFileName)) {
382 DISPLAYLEVEL(1, "zstd: %s is not a regular file -- ignored \n",
387 { FILE* const f = fopen(srcFileName, "rb");
389 DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));
394 /** FIO_openDstFile() :
395 * condition : `dstFileName` must be non-NULL.
396 * @result : FILE* to `dstFileName`, or NULL if it fails */
397 static FILE* FIO_openDstFile(const char* dstFileName)
399 assert(dstFileName != NULL);
400 if (!strcmp (dstFileName, stdoutmark)) {
401 DISPLAYLEVEL(4,"Using stdout for output\n");
402 SET_BINARY_MODE(stdout);
403 if (g_sparseFileSupport==1) {
404 g_sparseFileSupport = 0;
405 DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n");
410 if (g_sparseFileSupport == 1) {
411 g_sparseFileSupport = ZSTD_SPARSE_DEFAULT;
414 if (UTIL_isRegularFile(dstFileName)) {
416 if (!strcmp(dstFileName, nulmark)) {
417 EXM_THROW(40, "%s is unexpectedly a regular file", dstFileName);
419 /* Check if destination file already exists */
420 fCheck = fopen( dstFileName, "rb" );
421 if (fCheck != NULL) { /* dst file exists, authorization prompt */
424 if (g_displayLevel <= 1) {
425 /* No interaction possible */
426 DISPLAY("zstd: %s already exists; not overwritten \n",
430 DISPLAY("zstd: %s already exists; overwrite (y/N) ? ",
432 { int ch = getchar();
433 if ((ch!='Y') && (ch!='y')) {
434 DISPLAY(" not overwritten \n");
437 /* flush rest of input line */
438 while ((ch!=EOF) && (ch!='\n')) ch = getchar();
441 FIO_remove(dstFileName);
444 { FILE* const f = fopen( dstFileName, "wb" );
446 DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno));
452 /*! FIO_createDictBuffer() :
453 * creates a buffer, pointed by `*bufferPtr`,
454 * loads `filename` content into it, up to DICTSIZE_MAX bytes.
455 * @return : loaded size
456 * if fileName==NULL, returns 0 and a NULL pointer
458 static size_t FIO_createDictBuffer(void** bufferPtr, const char* fileName)
463 assert(bufferPtr != NULL);
465 if (fileName == NULL) return 0;
467 DISPLAYLEVEL(4,"Loading %s as dictionary \n", fileName);
468 fileHandle = fopen(fileName, "rb");
469 if (fileHandle==NULL) EXM_THROW(31, "%s: %s", fileName, strerror(errno));
470 fileSize = UTIL_getFileSize(fileName);
471 if (fileSize > DICTSIZE_MAX) {
472 EXM_THROW(32, "Dictionary file %s is too large (> %u MB)",
473 fileName, DICTSIZE_MAX >> 20); /* avoid extreme cases */
475 *bufferPtr = malloc((size_t)fileSize);
476 if (*bufferPtr==NULL) EXM_THROW(34, "%s", strerror(errno));
477 { size_t const readSize = fread(*bufferPtr, 1, (size_t)fileSize, fileHandle);
478 if (readSize!=fileSize)
479 EXM_THROW(35, "Error reading dictionary file %s", fileName);
482 return (size_t)fileSize;
485 #ifndef ZSTD_NOCOMPRESS
487 /* **********************************************************************
489 ************************************************************************/
494 size_t srcBufferSize;
496 size_t dstBufferSize;
500 static cRess_t FIO_createCResources(const char* dictFileName, int cLevel,
502 ZSTD_compressionParameters comprParams) {
504 memset(&ress, 0, sizeof(ress));
506 DISPLAYLEVEL(6, "FIO_createCResources \n");
507 ress.cctx = ZSTD_createCCtx();
508 if (ress.cctx == NULL)
509 EXM_THROW(30, "allocation error : can't create ZSTD_CCtx");
510 ress.srcBufferSize = ZSTD_CStreamInSize();
511 ress.srcBuffer = malloc(ress.srcBufferSize);
512 ress.dstBufferSize = ZSTD_CStreamOutSize();
513 ress.dstBuffer = malloc(ress.dstBufferSize);
514 if (!ress.srcBuffer || !ress.dstBuffer)
515 EXM_THROW(31, "allocation error : not enough memory");
517 /* Advanced parameters, including dictionary */
519 size_t const dictBuffSize = FIO_createDictBuffer(&dictBuffer, dictFileName); /* works with dictFileName==NULL */
520 if (dictFileName && (dictBuffer==NULL))
521 EXM_THROW(32, "allocation error : can't create dictBuffer");
523 if (g_adaptiveMode && !g_ldmFlag && !comprParams.windowLog)
524 comprParams.windowLog = ADAPT_WINDOWLOG_DEFAULT;
526 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_contentSizeFlag, 1) ); /* always enable content size when available (note: supposed to be default) */
527 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_dictIDFlag, g_dictIDFlag) );
528 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_checksumFlag, g_checksumFlag) );
529 /* compression level */
530 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_compressionLevel, (unsigned)cLevel) );
531 /* long distance matching */
532 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_enableLongDistanceMatching, g_ldmFlag) );
533 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_ldmHashLog, g_ldmHashLog) );
534 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_ldmMinMatch, g_ldmMinMatch) );
535 if (g_ldmBucketSizeLog != FIO_LDM_PARAM_NOTSET) {
536 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_ldmBucketSizeLog, g_ldmBucketSizeLog) );
538 if (g_ldmHashEveryLog != FIO_LDM_PARAM_NOTSET) {
539 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_ldmHashEveryLog, g_ldmHashEveryLog) );
541 /* compression parameters */
542 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_windowLog, comprParams.windowLog) );
543 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_chainLog, comprParams.chainLog) );
544 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_hashLog, comprParams.hashLog) );
545 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_searchLog, comprParams.searchLog) );
546 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_minMatch, comprParams.searchLength) );
547 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_targetLength, comprParams.targetLength) );
548 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_compressionStrategy, (U32)comprParams.strategy) );
549 /* multi-threading */
550 #ifdef ZSTD_MULTITHREAD
551 DISPLAYLEVEL(5,"set nb workers = %u \n", g_nbWorkers);
552 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_nbWorkers, g_nbWorkers) );
553 if ( (g_overlapLog == FIO_OVERLAP_LOG_NOTSET)
554 && (cLevel == ZSTD_maxCLevel()) )
555 g_overlapLog = 9; /* full overlap */
556 if (g_overlapLog != FIO_OVERLAP_LOG_NOTSET) {
557 DISPLAYLEVEL(3,"set overlapLog = %u \n", g_overlapLog);
558 CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_overlapSizeLog, g_overlapLog) );
562 CHECK( ZSTD_CCtx_setPledgedSrcSize(ress.cctx, srcSize) ); /* set the value temporarily for dictionary loading, to adapt compression parameters */
563 CHECK( ZSTD_CCtx_loadDictionary(ress.cctx, dictBuffer, dictBuffSize) );
564 CHECK( ZSTD_CCtx_setPledgedSrcSize(ress.cctx, ZSTD_CONTENTSIZE_UNKNOWN) ); /* reset */
572 static void FIO_freeCResources(cRess_t ress)
574 free(ress.srcBuffer);
575 free(ress.dstBuffer);
576 ZSTD_freeCStream(ress.cctx); /* never fails */
580 #ifdef ZSTD_GZCOMPRESS
581 static unsigned long long
582 FIO_compressGzFrame(cRess_t* ress,
583 const char* srcFileName, U64 const srcFileSize,
584 int compressionLevel, U64* readsize)
586 unsigned long long inFileSize = 0, outFileSize = 0;
590 if (compressionLevel > Z_BEST_COMPRESSION)
591 compressionLevel = Z_BEST_COMPRESSION;
593 strm.zalloc = Z_NULL;
595 strm.opaque = Z_NULL;
597 ret = deflateInit2(&strm, compressionLevel, Z_DEFLATED,
598 15 /* maxWindowLogSize */ + 16 /* gzip only */,
599 8, Z_DEFAULT_STRATEGY); /* see http://www.zlib.net/manual.html */
601 EXM_THROW(71, "zstd: %s: deflateInit2 error %d \n", srcFileName, ret);
605 strm.next_out = (Bytef*)ress->dstBuffer;
606 strm.avail_out = (uInt)ress->dstBufferSize;
609 if (strm.avail_in == 0) {
610 size_t const inSize = fread(ress->srcBuffer, 1, ress->srcBufferSize, ress->srcFile);
611 if (inSize == 0) break;
612 inFileSize += inSize;
613 strm.next_in = (z_const unsigned char*)ress->srcBuffer;
614 strm.avail_in = (uInt)inSize;
616 ret = deflate(&strm, Z_NO_FLUSH);
618 EXM_THROW(72, "zstd: %s: deflate error %d \n", srcFileName, ret);
619 { size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
621 if (fwrite(ress->dstBuffer, 1, decompBytes, ress->dstFile) != decompBytes)
622 EXM_THROW(73, "Write error : cannot write to output file");
623 outFileSize += decompBytes;
624 strm.next_out = (Bytef*)ress->dstBuffer;
625 strm.avail_out = (uInt)ress->dstBufferSize;
628 if (srcFileSize == UTIL_FILESIZE_UNKNOWN)
629 DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%%",
630 (U32)(inFileSize>>20),
631 (double)outFileSize/inFileSize*100)
633 DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%%",
634 (U32)(inFileSize>>20), (U32)(srcFileSize>>20),
635 (double)outFileSize/inFileSize*100);
639 ret = deflate(&strm, Z_FINISH);
640 { size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
642 if (fwrite(ress->dstBuffer, 1, decompBytes, ress->dstFile) != decompBytes)
643 EXM_THROW(75, "Write error : cannot write to output file");
644 outFileSize += decompBytes;
645 strm.next_out = (Bytef*)ress->dstBuffer;
646 strm.avail_out = (uInt)ress->dstBufferSize;
648 if (ret == Z_STREAM_END) break;
649 if (ret != Z_BUF_ERROR)
650 EXM_THROW(77, "zstd: %s: deflate error %d \n", srcFileName, ret);
653 ret = deflateEnd(&strm);
655 EXM_THROW(79, "zstd: %s: deflateEnd error %d \n", srcFileName, ret);
656 *readsize = inFileSize;
663 #ifdef ZSTD_LZMACOMPRESS
664 static unsigned long long
665 FIO_compressLzmaFrame(cRess_t* ress,
666 const char* srcFileName, U64 const srcFileSize,
667 int compressionLevel, U64* readsize, int plain_lzma)
669 unsigned long long inFileSize = 0, outFileSize = 0;
670 lzma_stream strm = LZMA_STREAM_INIT;
671 lzma_action action = LZMA_RUN;
674 if (compressionLevel < 0) compressionLevel = 0;
675 if (compressionLevel > 9) compressionLevel = 9;
678 lzma_options_lzma opt_lzma;
679 if (lzma_lzma_preset(&opt_lzma, compressionLevel))
680 EXM_THROW(71, "zstd: %s: lzma_lzma_preset error", srcFileName);
681 ret = lzma_alone_encoder(&strm, &opt_lzma); /* LZMA */
683 EXM_THROW(71, "zstd: %s: lzma_alone_encoder error %d", srcFileName, ret);
685 ret = lzma_easy_encoder(&strm, compressionLevel, LZMA_CHECK_CRC64); /* XZ */
687 EXM_THROW(71, "zstd: %s: lzma_easy_encoder error %d", srcFileName, ret);
692 strm.next_out = (BYTE*)ress->dstBuffer;
693 strm.avail_out = ress->dstBufferSize;
696 if (strm.avail_in == 0) {
697 size_t const inSize = fread(ress->srcBuffer, 1, ress->srcBufferSize, ress->srcFile);
698 if (inSize == 0) action = LZMA_FINISH;
699 inFileSize += inSize;
700 strm.next_in = (BYTE const*)ress->srcBuffer;
701 strm.avail_in = inSize;
704 ret = lzma_code(&strm, action);
706 if (ret != LZMA_OK && ret != LZMA_STREAM_END)
707 EXM_THROW(72, "zstd: %s: lzma_code encoding error %d", srcFileName, ret);
708 { size_t const compBytes = ress->dstBufferSize - strm.avail_out;
710 if (fwrite(ress->dstBuffer, 1, compBytes, ress->dstFile) != compBytes)
711 EXM_THROW(73, "Write error : cannot write to output file");
712 outFileSize += compBytes;
713 strm.next_out = (BYTE*)ress->dstBuffer;
714 strm.avail_out = ress->dstBufferSize;
716 if (srcFileSize == UTIL_FILESIZE_UNKNOWN)
717 DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%%",
718 (U32)(inFileSize>>20),
719 (double)outFileSize/inFileSize*100)
721 DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%%",
722 (U32)(inFileSize>>20), (U32)(srcFileSize>>20),
723 (double)outFileSize/inFileSize*100);
724 if (ret == LZMA_STREAM_END) break;
728 *readsize = inFileSize;
734 #ifdef ZSTD_LZ4COMPRESS
735 #if LZ4_VERSION_NUMBER <= 10600
736 #define LZ4F_blockLinked blockLinked
737 #define LZ4F_max64KB max64KB
739 static int FIO_LZ4_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); }
740 static unsigned long long
741 FIO_compressLz4Frame(cRess_t* ress,
742 const char* srcFileName, U64 const srcFileSize,
743 int compressionLevel, U64* readsize)
745 const size_t blockSize = FIO_LZ4_GetBlockSize_FromBlockId(LZ4F_max64KB);
746 unsigned long long inFileSize = 0, outFileSize = 0;
748 LZ4F_preferences_t prefs;
749 LZ4F_compressionContext_t ctx;
751 LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
752 if (LZ4F_isError(errorCode))
753 EXM_THROW(31, "zstd: failed to create lz4 compression context");
755 memset(&prefs, 0, sizeof(prefs));
757 assert(blockSize <= ress->srcBufferSize);
760 prefs.compressionLevel = compressionLevel;
761 prefs.frameInfo.blockMode = LZ4F_blockLinked;
762 prefs.frameInfo.blockSizeID = LZ4F_max64KB;
763 prefs.frameInfo.contentChecksumFlag = (contentChecksum_t)g_checksumFlag;
764 #if LZ4_VERSION_NUMBER >= 10600
765 prefs.frameInfo.contentSize = (srcFileSize==UTIL_FILESIZE_UNKNOWN) ? 0 : srcFileSize;
767 assert(LZ4F_compressBound(blockSize, &prefs) <= ress->dstBufferSize);
771 size_t headerSize = LZ4F_compressBegin(ctx, ress->dstBuffer, ress->dstBufferSize, &prefs);
772 if (LZ4F_isError(headerSize))
773 EXM_THROW(33, "File header generation failed : %s",
774 LZ4F_getErrorName(headerSize));
775 if (fwrite(ress->dstBuffer, 1, headerSize, ress->dstFile) != headerSize)
776 EXM_THROW(34, "Write error : cannot write header");
777 outFileSize += headerSize;
779 /* Read first block */
780 readSize = fread(ress->srcBuffer, (size_t)1, (size_t)blockSize, ress->srcFile);
781 inFileSize += readSize;
788 outSize = LZ4F_compressUpdate(ctx, ress->dstBuffer, ress->dstBufferSize, ress->srcBuffer, readSize, NULL);
789 if (LZ4F_isError(outSize))
790 EXM_THROW(35, "zstd: %s: lz4 compression failed : %s",
791 srcFileName, LZ4F_getErrorName(outSize));
792 outFileSize += outSize;
793 if (srcFileSize == UTIL_FILESIZE_UNKNOWN)
794 DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%%",
795 (U32)(inFileSize>>20),
796 (double)outFileSize/inFileSize*100)
798 DISPLAYUPDATE(2, "\rRead : %u / %u MB ==> %.2f%%",
799 (U32)(inFileSize>>20), (U32)(srcFileSize>>20),
800 (double)outFileSize/inFileSize*100);
803 { size_t const sizeCheck = fwrite(ress->dstBuffer, 1, outSize, ress->dstFile);
804 if (sizeCheck!=outSize) EXM_THROW(36, "Write error : cannot write compressed block"); }
806 /* Read next block */
807 readSize = fread(ress->srcBuffer, (size_t)1, (size_t)blockSize, ress->srcFile);
808 inFileSize += readSize;
810 if (ferror(ress->srcFile)) EXM_THROW(37, "Error reading %s ", srcFileName);
812 /* End of Stream mark */
813 headerSize = LZ4F_compressEnd(ctx, ress->dstBuffer, ress->dstBufferSize, NULL);
814 if (LZ4F_isError(headerSize))
815 EXM_THROW(38, "zstd: %s: lz4 end of file generation failed : %s",
816 srcFileName, LZ4F_getErrorName(headerSize));
818 { size_t const sizeCheck = fwrite(ress->dstBuffer, 1, headerSize, ress->dstFile);
819 if (sizeCheck!=headerSize) EXM_THROW(39, "Write error : cannot write end of stream"); }
820 outFileSize += headerSize;
823 *readsize = inFileSize;
824 LZ4F_freeCompressionContext(ctx);
831 static unsigned long long
832 FIO_compressZstdFrame(const cRess_t* ressPtr,
833 const char* srcFileName, U64 fileSize,
834 int compressionLevel, U64* readsize)
836 cRess_t const ress = *ressPtr;
837 FILE* const srcFile = ress.srcFile;
838 FILE* const dstFile = ress.dstFile;
839 U64 compressedfilesize = 0;
840 ZSTD_EndDirective directive = ZSTD_e_continue;
843 ZSTD_frameProgression previous_zfp_update = { 0, 0, 0, 0, 0, 0 };
844 ZSTD_frameProgression previous_zfp_correction = { 0, 0, 0, 0, 0, 0 };
845 typedef enum { noChange, slower, faster } speedChange_e;
846 speedChange_e speedChange = noChange;
847 unsigned flushWaiting = 0;
848 unsigned inputPresented = 0;
849 unsigned inputBlocked = 0;
850 unsigned lastJobID = 0;
852 DISPLAYLEVEL(6, "compression using zstd format \n");
855 if (fileSize != UTIL_FILESIZE_UNKNOWN) {
856 CHECK(ZSTD_CCtx_setPledgedSrcSize(ress.cctx, fileSize));
860 /* Main compression loop */
863 /* Fill input Buffer */
864 size_t const inSize = fread(ress.srcBuffer, (size_t)1, ress.srcBufferSize, srcFile);
865 ZSTD_inBuffer inBuff = { ress.srcBuffer, inSize, 0 };
866 DISPLAYLEVEL(6, "fread %u bytes from source \n", (U32)inSize);
869 if ((inSize == 0) || (*readsize == fileSize))
870 directive = ZSTD_e_end;
873 while ((inBuff.pos != inBuff.size) /* input buffer must be entirely ingested */
874 || (directive == ZSTD_e_end && stillToFlush != 0) ) {
876 size_t const oldIPos = inBuff.pos;
877 ZSTD_outBuffer outBuff = { ress.dstBuffer, ress.dstBufferSize, 0 };
878 size_t const toFlushNow = ZSTD_toFlushNow(ress.cctx);
879 CHECK_V(stillToFlush, ZSTD_compress_generic(ress.cctx, &outBuff, &inBuff, directive));
883 if (oldIPos == inBuff.pos) inputBlocked++; /* input buffer is full and can't take any more : input speed is faster than consumption rate */
884 if (!toFlushNow) flushWaiting = 1;
886 /* Write compressed stream */
887 DISPLAYLEVEL(6, "ZSTD_compress_generic(end:%u) => input pos(%u)<=(%u)size ; output generated %u bytes \n",
888 (U32)directive, (U32)inBuff.pos, (U32)inBuff.size, (U32)outBuff.pos);
890 size_t const sizeCheck = fwrite(ress.dstBuffer, 1, outBuff.pos, dstFile);
891 if (sizeCheck != outBuff.pos)
892 EXM_THROW(25, "Write error : cannot write compressed block");
893 compressedfilesize += outBuff.pos;
896 /* display notification; and adapt compression level */
897 if (READY_FOR_UPDATE()) {
898 ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress.cctx);
899 double const cShare = (double)zfp.produced / (zfp.consumed + !zfp.consumed/*avoid div0*/) * 100;
901 /* display progress notifications */
902 if (g_displayLevel >= 3) {
903 DISPLAYUPDATE(3, "\r(L%i) Buffered :%4u MB - Consumed :%4u MB - Compressed :%4u MB => %.2f%% ",
905 (U32)((zfp.ingested - zfp.consumed) >> 20),
906 (U32)(zfp.consumed >> 20),
907 (U32)(zfp.produced >> 20),
909 } else { /* summarized notifications if == 2; */
910 DISPLAYLEVEL(2, "\rRead : %u ", (U32)(zfp.consumed >> 20));
911 if (fileSize != UTIL_FILESIZE_UNKNOWN)
912 DISPLAYLEVEL(2, "/ %u ", (U32)(fileSize >> 20));
913 DISPLAYLEVEL(2, "MB ==> %2.f%% ", cShare);
917 /* adaptive mode : statistics measurement and speed correction */
918 if (g_adaptiveMode) {
920 /* check output speed */
921 if (zfp.currentJobID > 1) { /* only possible if nbWorkers >= 1 */
923 unsigned long long newlyProduced = zfp.produced - previous_zfp_update.produced;
924 unsigned long long newlyFlushed = zfp.flushed - previous_zfp_update.flushed;
925 assert(zfp.produced >= previous_zfp_update.produced);
926 assert(g_nbWorkers >= 1);
928 /* test if compression is blocked
929 * either because output is slow and all buffers are full
930 * or because input is slow and no job can start while waiting for at least one buffer to be filled.
931 * note : excluse starting part, since currentJobID > 1 */
932 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)*/
933 && (zfp.nbActiveWorkers == 0) /* confirmed : no compression ongoing */
935 DISPLAYLEVEL(6, "all buffers full : compression stopped => slow down \n")
936 speedChange = slower;
939 previous_zfp_update = zfp;
941 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) */
942 && (flushWaiting == 0) /* flush speed was never slowed by lack of production, so it's operating at max capacity */
944 DISPLAYLEVEL(6, "compression faster than flush (%llu > %llu), and flushed was never slowed down by lack of production => slow down \n", newlyProduced, newlyFlushed);
945 speedChange = slower;
950 /* course correct only if there is at least one new job completed */
951 if (zfp.currentJobID > lastJobID) {
952 DISPLAYLEVEL(6, "compression level adaptation check \n")
954 /* check input speed */
955 if (zfp.currentJobID > g_nbWorkers+1) { /* warm up period, to fill all workers */
956 if (inputBlocked <= 0) {
957 DISPLAYLEVEL(6, "input is never blocked => input is slower than ingestion \n");
958 speedChange = slower;
959 } else if (speedChange == noChange) {
960 unsigned long long newlyIngested = zfp.ingested - previous_zfp_correction.ingested;
961 unsigned long long newlyConsumed = zfp.consumed - previous_zfp_correction.consumed;
962 unsigned long long newlyProduced = zfp.produced - previous_zfp_correction.produced;
963 unsigned long long newlyFlushed = zfp.flushed - previous_zfp_correction.flushed;
964 previous_zfp_correction = zfp;
965 assert(inputPresented > 0);
966 DISPLAYLEVEL(6, "input blocked %u/%u(%.2f) - ingested:%u vs %u:consumed - flushed:%u vs %u:produced \n",
967 inputBlocked, inputPresented, (double)inputBlocked/inputPresented*100,
968 (U32)newlyIngested, (U32)newlyConsumed,
969 (U32)newlyFlushed, (U32)newlyProduced);
970 if ( (inputBlocked > inputPresented / 8) /* input is waiting often, because input buffers is full : compression or output too slow */
971 && (newlyFlushed * 33 / 32 > newlyProduced) /* flush everything that is produced */
972 && (newlyIngested * 33 / 32 > newlyConsumed) /* input speed as fast or faster than compression speed */
974 DISPLAYLEVEL(6, "recommend faster as in(%llu) >= (%llu)comp(%llu) <= out(%llu) \n",
975 newlyIngested, newlyConsumed, newlyProduced, newlyFlushed);
976 speedChange = faster;
983 if (speedChange == slower) {
984 DISPLAYLEVEL(6, "slower speed , higher compression \n")
986 if (compressionLevel > ZSTD_maxCLevel()) compressionLevel = ZSTD_maxCLevel();
987 if (compressionLevel > g_maxAdaptLevel) compressionLevel = g_maxAdaptLevel;
988 compressionLevel += (compressionLevel == 0); /* skip 0 */
989 ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_compressionLevel, (unsigned)compressionLevel);
991 if (speedChange == faster) {
992 DISPLAYLEVEL(6, "faster speed , lighter compression \n")
994 if (compressionLevel < g_minAdaptLevel) compressionLevel = g_minAdaptLevel;
995 compressionLevel -= (compressionLevel == 0); /* skip 0 */
996 ZSTD_CCtx_setParameter(ress.cctx, ZSTD_p_compressionLevel, (unsigned)compressionLevel);
998 speedChange = noChange;
1000 lastJobID = zfp.currentJobID;
1001 } /* if (zfp.currentJobID > lastJobID) */
1002 } /* if (g_adaptiveMode) */
1003 } /* if (READY_FOR_UPDATE()) */
1004 } /* while ((inBuff.pos != inBuff.size) */
1005 } while (directive != ZSTD_e_end);
1007 if (ferror(srcFile)) {
1008 EXM_THROW(26, "Read error : I/O error");
1010 if (fileSize != UTIL_FILESIZE_UNKNOWN && *readsize != fileSize) {
1011 EXM_THROW(27, "Read error : Incomplete read : %llu / %llu B",
1012 (unsigned long long)*readsize, (unsigned long long)fileSize);
1015 return compressedfilesize;
1018 /*! FIO_compressFilename_internal() :
1019 * same as FIO_compressFilename_extRess(), with `ress.desFile` already opened.
1020 * @return : 0 : compression completed correctly,
1021 * 1 : missing or pb opening srcFileName
1024 FIO_compressFilename_internal(cRess_t ress,
1025 const char* dstFileName, const char* srcFileName,
1026 int compressionLevel)
1029 U64 compressedfilesize = 0;
1030 U64 const fileSize = UTIL_getFileSize(srcFileName);
1031 DISPLAYLEVEL(5, "%s: %u bytes \n", srcFileName, (U32)fileSize);
1033 /* compression format selection */
1034 switch (g_compressionType) {
1036 case FIO_zstdCompression:
1037 compressedfilesize = FIO_compressZstdFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize);
1040 case FIO_gzipCompression:
1041 #ifdef ZSTD_GZCOMPRESS
1042 compressedfilesize = FIO_compressGzFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize);
1044 (void)compressionLevel;
1045 EXM_THROW(20, "zstd: %s: file cannot be compressed as gzip (zstd compiled without ZSTD_GZCOMPRESS) -- ignored \n",
1050 case FIO_xzCompression:
1051 case FIO_lzmaCompression:
1052 #ifdef ZSTD_LZMACOMPRESS
1053 compressedfilesize = FIO_compressLzmaFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize, g_compressionType==FIO_lzmaCompression);
1055 (void)compressionLevel;
1056 EXM_THROW(20, "zstd: %s: file cannot be compressed as xz/lzma (zstd compiled without ZSTD_LZMACOMPRESS) -- ignored \n",
1061 case FIO_lz4Compression:
1062 #ifdef ZSTD_LZ4COMPRESS
1063 compressedfilesize = FIO_compressLz4Frame(&ress, srcFileName, fileSize, compressionLevel, &readsize);
1065 (void)compressionLevel;
1066 EXM_THROW(20, "zstd: %s: file cannot be compressed as lz4 (zstd compiled without ZSTD_LZ4COMPRESS) -- ignored \n",
1073 DISPLAYLEVEL(2, "\r%79s\r", "");
1074 DISPLAYLEVEL(2,"%-20s :%6.2f%% (%6llu => %6llu bytes, %s) \n",
1076 (double)compressedfilesize / (readsize+(!readsize)/*avoid div by zero*/) * 100,
1077 (unsigned long long)readsize, (unsigned long long) compressedfilesize,
1084 /*! FIO_compressFilename_dstFile() :
1085 * open dstFileName, or pass-through if ress.dstFile != NULL,
1086 * then start compression with FIO_compressFilename_internal().
1087 * Manages source removal (--rm) and file permissions transfer.
1088 * note : ress.srcFile must be != NULL,
1089 * so reach this function through FIO_compressFilename_srcFile().
1090 * @return : 0 : compression completed correctly,
1093 static int FIO_compressFilename_dstFile(cRess_t ress,
1094 const char* dstFileName,
1095 const char* srcFileName,
1096 int compressionLevel)
1098 int closeDstFile = 0;
1101 int transfer_permissions = 0;
1103 assert(ress.srcFile != NULL);
1105 if (ress.dstFile == NULL) {
1107 DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: opening dst: %s", dstFileName);
1108 ress.dstFile = FIO_openDstFile(dstFileName);
1109 if (ress.dstFile==NULL) return 1; /* could not open dstFileName */
1110 /* Must only be added after FIO_openDstFile() succeeds.
1111 * Otherwise we may delete the destination file if it already exists,
1112 * and the user presses Ctrl-C when asked if they wish to overwrite.
1114 addHandler(dstFileName);
1116 if ( strcmp (srcFileName, stdinmark)
1117 && UTIL_getFileStat(srcFileName, &statbuf))
1118 transfer_permissions = 1;
1121 result = FIO_compressFilename_internal(ress, dstFileName, srcFileName, compressionLevel);
1124 FILE* const dstFile = ress.dstFile;
1125 ress.dstFile = NULL;
1129 if (fclose(dstFile)) { /* error closing dstFile */
1130 DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno));
1133 if ( (result != 0) /* operation failure */
1134 && strcmp(dstFileName, nulmark) /* special case : don't remove() /dev/null */
1135 && strcmp(dstFileName, stdoutmark) /* special case : don't remove() stdout */
1137 FIO_remove(dstFileName); /* remove compression artefact; note don't do anything special if remove() fails */
1138 } else if ( strcmp(dstFileName, stdoutmark)
1139 && strcmp(dstFileName, nulmark)
1140 && transfer_permissions) {
1141 UTIL_setFileStat(dstFileName, &statbuf);
1149 /*! FIO_compressFilename_srcFile() :
1150 * @return : 0 : compression completed correctly,
1151 * 1 : missing or pb opening srcFileName
1154 FIO_compressFilename_srcFile(cRess_t ress,
1155 const char* dstFileName,
1156 const char* srcFileName,
1157 int compressionLevel)
1162 if (UTIL_isDirectory(srcFileName)) {
1163 DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
1167 ress.srcFile = FIO_openSrcFile(srcFileName);
1168 if (ress.srcFile == NULL) return 1; /* srcFile could not be opened */
1170 result = FIO_compressFilename_dstFile(ress, dstFileName, srcFileName, compressionLevel);
1172 fclose(ress.srcFile);
1173 ress.srcFile = NULL;
1174 if ( g_removeSrcFile /* --rm */
1175 && result == 0 /* success */
1176 && strcmp(srcFileName, stdinmark) /* exception : don't erase stdin */
1178 /* We must clear the handler, since after this point calling it would
1179 * delete both the source and destination files.
1182 if (FIO_remove(srcFileName))
1183 EXM_THROW(1, "zstd: %s: %s", srcFileName, strerror(errno));
1189 int FIO_compressFilename(const char* dstFileName, const char* srcFileName,
1190 const char* dictFileName, int compressionLevel,
1191 ZSTD_compressionParameters comprParams)
1193 clock_t const start = clock();
1194 U64 const fileSize = UTIL_getFileSize(srcFileName);
1195 U64 const srcSize = (fileSize == UTIL_FILESIZE_UNKNOWN) ? ZSTD_CONTENTSIZE_UNKNOWN : fileSize;
1197 cRess_t const ress = FIO_createCResources(dictFileName, compressionLevel, srcSize, comprParams);
1198 int const result = FIO_compressFilename_srcFile(ress, dstFileName, srcFileName, compressionLevel);
1200 double const seconds = (double)(clock() - start) / CLOCKS_PER_SEC;
1201 DISPLAYLEVEL(4, "Completed in %.2f sec \n", seconds);
1203 FIO_freeCResources(ress);
1208 /* FIO_determineCompressedName() :
1209 * create a destination filename for compressed srcFileName.
1210 * @return a pointer to it.
1211 * This function never returns an error (it may abort() in case of pb)
1214 FIO_determineCompressedName(const char* srcFileName, const char* suffix)
1216 static size_t dfnbCapacity = 0;
1217 static char* dstFileNameBuffer = NULL; /* using static allocation : this function cannot be multi-threaded */
1219 size_t const sfnSize = strlen(srcFileName);
1220 size_t const suffixSize = strlen(suffix);
1222 if (dfnbCapacity <= sfnSize+suffixSize+1) {
1223 /* resize buffer for dstName */
1224 free(dstFileNameBuffer);
1225 dfnbCapacity = sfnSize + suffixSize + 30;
1226 dstFileNameBuffer = (char*)malloc(dfnbCapacity);
1227 if (!dstFileNameBuffer) {
1228 EXM_THROW(30, "zstd: %s", strerror(errno));
1230 assert(dstFileNameBuffer != NULL);
1231 memcpy(dstFileNameBuffer, srcFileName, sfnSize);
1232 memcpy(dstFileNameBuffer+sfnSize, suffix, suffixSize+1 /* Include terminating null */);
1234 return dstFileNameBuffer;
1238 /* FIO_compressMultipleFilenames() :
1239 * compress nbFiles files
1240 * into one destination (outFileName)
1241 * or into one file each (outFileName == NULL, but suffix != NULL).
1243 int FIO_compressMultipleFilenames(const char** inFileNamesTable, unsigned nbFiles,
1244 const char* outFileName, const char* suffix,
1245 const char* dictFileName, int compressionLevel,
1246 ZSTD_compressionParameters comprParams)
1249 U64 const firstFileSize = UTIL_getFileSize(inFileNamesTable[0]);
1250 U64 const firstSrcSize = (firstFileSize == UTIL_FILESIZE_UNKNOWN) ? ZSTD_CONTENTSIZE_UNKNOWN : firstFileSize;
1251 U64 const srcSize = (nbFiles != 1) ? ZSTD_CONTENTSIZE_UNKNOWN : firstSrcSize ;
1252 cRess_t ress = FIO_createCResources(dictFileName, compressionLevel, srcSize, comprParams);
1255 assert(outFileName != NULL || suffix != NULL);
1257 if (outFileName != NULL) { /* output into a single destination (stdout typically) */
1258 ress.dstFile = FIO_openDstFile(outFileName);
1259 if (ress.dstFile == NULL) { /* could not open outFileName */
1263 for (u=0; u<nbFiles; u++)
1264 error |= FIO_compressFilename_srcFile(ress, outFileName, inFileNamesTable[u], compressionLevel);
1265 if (fclose(ress.dstFile))
1266 EXM_THROW(29, "Write error : cannot properly close %s", outFileName);
1267 ress.dstFile = NULL;
1271 for (u=0; u<nbFiles; u++) {
1272 const char* const srcFileName = inFileNamesTable[u];
1273 const char* const dstFileName = FIO_determineCompressedName(srcFileName, suffix); /* cannot fail */
1274 error |= FIO_compressFilename_srcFile(ress, dstFileName, srcFileName, compressionLevel);
1277 FIO_freeCResources(ress);
1281 #endif /* #ifndef ZSTD_NOCOMPRESS */
1285 #ifndef ZSTD_NODECOMPRESS
1287 /* **************************************************************************
1289 ***************************************************************************/
1292 size_t srcBufferSize;
1293 size_t srcBufferLoaded;
1295 size_t dstBufferSize;
1300 static dRess_t FIO_createDResources(const char* dictFileName)
1303 memset(&ress, 0, sizeof(ress));
1306 ress.dctx = ZSTD_createDStream();
1307 if (ress.dctx==NULL) EXM_THROW(60, "Can't create ZSTD_DStream");
1308 CHECK( ZSTD_setDStreamParameter(ress.dctx, DStream_p_maxWindowSize, g_memLimit) );
1309 ress.srcBufferSize = ZSTD_DStreamInSize();
1310 ress.srcBuffer = malloc(ress.srcBufferSize);
1311 ress.dstBufferSize = ZSTD_DStreamOutSize();
1312 ress.dstBuffer = malloc(ress.dstBufferSize);
1313 if (!ress.srcBuffer || !ress.dstBuffer)
1314 EXM_THROW(61, "Allocation error : not enough memory");
1318 size_t const dictBufferSize = FIO_createDictBuffer(&dictBuffer, dictFileName);
1319 CHECK( ZSTD_initDStream_usingDict(ress.dctx, dictBuffer, dictBufferSize) );
1326 static void FIO_freeDResources(dRess_t ress)
1328 CHECK( ZSTD_freeDStream(ress.dctx) );
1329 free(ress.srcBuffer);
1330 free(ress.dstBuffer);
1334 /** FIO_fwriteSparse() :
1335 * @return : storedSkips, to be provided to next call to FIO_fwriteSparse() of LZ4IO_fwriteSparseEnd() */
1336 static unsigned FIO_fwriteSparse(FILE* file, const void* buffer, size_t bufferSize, unsigned storedSkips)
1338 const size_t* const bufferT = (const size_t*)buffer; /* Buffer is supposed malloc'ed, hence aligned on size_t */
1339 size_t bufferSizeT = bufferSize / sizeof(size_t);
1340 const size_t* const bufferTEnd = bufferT + bufferSizeT;
1341 const size_t* ptrT = bufferT;
1342 static const size_t segmentSizeT = (32 KB) / sizeof(size_t); /* 0-test re-attempted every 32 KB */
1344 if (!g_sparseFileSupport) { /* normal write */
1345 size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file);
1346 if (sizeCheck != bufferSize) EXM_THROW(70, "Write error : cannot write decoded block");
1350 /* avoid int overflow */
1351 if (storedSkips > 1 GB) {
1352 int const seekResult = LONG_SEEK(file, 1 GB, SEEK_CUR);
1353 if (seekResult != 0) EXM_THROW(71, "1 GB skip error (sparse file support)");
1354 storedSkips -= 1 GB;
1357 while (ptrT < bufferTEnd) {
1358 size_t seg0SizeT = segmentSizeT;
1361 /* count leading zeros */
1362 if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT;
1363 bufferSizeT -= seg0SizeT;
1364 for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ;
1365 storedSkips += (unsigned)(nb0T * sizeof(size_t));
1367 if (nb0T != seg0SizeT) { /* not all 0s */
1368 int const seekResult = LONG_SEEK(file, storedSkips, SEEK_CUR);
1369 if (seekResult) EXM_THROW(72, "Sparse skip error ; try --no-sparse");
1373 { size_t const sizeCheck = fwrite(ptrT, sizeof(size_t), seg0SizeT, file);
1374 if (sizeCheck != seg0SizeT)
1375 EXM_THROW(73, "Write error : cannot write decoded block");
1380 { static size_t const maskT = sizeof(size_t)-1;
1381 if (bufferSize & maskT) {
1382 /* size not multiple of sizeof(size_t) : implies end of block */
1383 const char* const restStart = (const char*)bufferTEnd;
1384 const char* restPtr = restStart;
1385 size_t restSize = bufferSize & maskT;
1386 const char* const restEnd = restStart + restSize;
1387 for ( ; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ;
1388 storedSkips += (unsigned) (restPtr - restStart);
1389 if (restPtr != restEnd) {
1390 int seekResult = LONG_SEEK(file, storedSkips, SEEK_CUR);
1392 EXM_THROW(74, "Sparse skip error ; try --no-sparse");
1394 { size_t const sizeCheck = fwrite(restPtr, 1, restEnd - restPtr, file);
1395 if (sizeCheck != (size_t)(restEnd - restPtr))
1396 EXM_THROW(75, "Write error : cannot write decoded end of block");
1402 static void FIO_fwriteSparseEnd(FILE* file, unsigned storedSkips)
1404 if (storedSkips-->0) { /* implies g_sparseFileSupport>0 */
1405 int const seekResult = LONG_SEEK(file, storedSkips, SEEK_CUR);
1406 if (seekResult != 0) EXM_THROW(69, "Final skip error (sparse file)");
1407 { const char lastZeroByte[1] = { 0 };
1408 size_t const sizeCheck = fwrite(lastZeroByte, 1, 1, file);
1410 EXM_THROW(69, "Write error : cannot write last zero");
1415 /** FIO_passThrough() : just copy input into output, for compatibility with gzip -df mode
1416 @return : 0 (no error) */
1417 static unsigned FIO_passThrough(FILE* foutput, FILE* finput, void* buffer, size_t bufferSize, size_t alreadyLoaded)
1419 size_t const blockSize = MIN(64 KB, bufferSize);
1420 size_t readFromInput = 1;
1421 unsigned storedSkips = 0;
1423 /* assumption : ress->srcBufferLoaded bytes already loaded and stored within buffer */
1424 { size_t const sizeCheck = fwrite(buffer, 1, alreadyLoaded, foutput);
1425 if (sizeCheck != alreadyLoaded) {
1426 DISPLAYLEVEL(1, "Pass-through write error \n");
1430 while (readFromInput) {
1431 readFromInput = fread(buffer, 1, blockSize, finput);
1432 storedSkips = FIO_fwriteSparse(foutput, buffer, readFromInput, storedSkips);
1435 FIO_fwriteSparseEnd(foutput, storedSkips);
1439 /* FIO_highbit64() :
1440 * gives position of highest bit.
1441 * note : only works for v > 0 !
1443 static unsigned FIO_highbit64(unsigned long long v)
1448 while (v) { v >>= 1; count++; }
1452 /* FIO_zstdErrorHelp() :
1453 * detailed error message when requested window size is too large */
1454 static void FIO_zstdErrorHelp(dRess_t* ress, size_t err, char const* srcFileName)
1456 ZSTD_frameHeader header;
1458 /* Help message only for one specific error */
1459 if (ZSTD_getErrorCode(err) != ZSTD_error_frameParameter_windowTooLarge)
1462 /* Try to decode the frame header */
1463 err = ZSTD_getFrameHeader(&header, ress->srcBuffer, ress->srcBufferLoaded);
1465 unsigned long long const windowSize = header.windowSize;
1466 U32 const windowLog = FIO_highbit64(windowSize) + ((windowSize & (windowSize - 1)) != 0);
1467 assert(g_memLimit > 0);
1468 DISPLAYLEVEL(1, "%s : Window size larger than maximum : %llu > %u\n",
1469 srcFileName, windowSize, g_memLimit);
1470 if (windowLog <= ZSTD_WINDOWLOG_MAX) {
1471 U32 const windowMB = (U32)((windowSize >> 20) + ((windowSize & ((1 MB) - 1)) != 0));
1472 assert(windowSize < (U64)(1ULL << 52)); /* ensure now overflow for windowMB */
1473 DISPLAYLEVEL(1, "%s : Use --long=%u or --memory=%uMB\n",
1474 srcFileName, windowLog, windowMB);
1478 DISPLAYLEVEL(1, "%s : Window log larger than ZSTD_WINDOWLOG_MAX=%u; not supported\n",
1479 srcFileName, ZSTD_WINDOWLOG_MAX);
1482 /** FIO_decompressFrame() :
1483 * @return : size of decoded zstd frame, or an error code
1485 #define FIO_ERROR_FRAME_DECODING ((unsigned long long)(-2))
1486 static unsigned long long FIO_decompressZstdFrame(dRess_t* ress,
1488 const char* srcFileName,
1492 U32 storedSkips = 0;
1494 size_t const srcFileLength = strlen(srcFileName);
1495 if (srcFileLength>20) srcFileName += srcFileLength-20; /* display last 20 characters only */
1497 ZSTD_resetDStream(ress->dctx);
1499 /* Header loading : ensures ZSTD_getFrameHeader() will succeed */
1500 { size_t const toDecode = ZSTD_FRAMEHEADERSIZE_MAX;
1501 if (ress->srcBufferLoaded < toDecode) {
1502 size_t const toRead = toDecode - ress->srcBufferLoaded;
1503 void* const startPosition = (char*)ress->srcBuffer + ress->srcBufferLoaded;
1504 ress->srcBufferLoaded += fread(startPosition, 1, toRead, finput);
1507 /* Main decompression Loop */
1509 ZSTD_inBuffer inBuff = { ress->srcBuffer, ress->srcBufferLoaded, 0 };
1510 ZSTD_outBuffer outBuff= { ress->dstBuffer, ress->dstBufferSize, 0 };
1511 size_t const readSizeHint = ZSTD_decompressStream(ress->dctx, &outBuff, &inBuff);
1512 if (ZSTD_isError(readSizeHint)) {
1513 DISPLAYLEVEL(1, "%s : Decoding error (36) : %s \n",
1514 srcFileName, ZSTD_getErrorName(readSizeHint));
1515 FIO_zstdErrorHelp(ress, readSizeHint, srcFileName);
1516 return FIO_ERROR_FRAME_DECODING;
1520 storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, outBuff.pos, storedSkips);
1521 frameSize += outBuff.pos;
1522 DISPLAYUPDATE(2, "\r%-20.20s : %u MB... ",
1523 srcFileName, (U32)((alreadyDecoded+frameSize)>>20) );
1525 if (inBuff.pos > 0) {
1526 memmove(ress->srcBuffer, (char*)ress->srcBuffer + inBuff.pos, inBuff.size - inBuff.pos);
1527 ress->srcBufferLoaded -= inBuff.pos;
1530 if (readSizeHint == 0) break; /* end of frame */
1531 if (inBuff.size != inBuff.pos) {
1532 DISPLAYLEVEL(1, "%s : Decoding error (37) : should consume entire input \n",
1534 return FIO_ERROR_FRAME_DECODING;
1537 /* Fill input buffer */
1538 { size_t const toDecode = MIN(readSizeHint, ress->srcBufferSize); /* support large skippable frames */
1539 if (ress->srcBufferLoaded < toDecode) {
1540 size_t const toRead = toDecode - ress->srcBufferLoaded; /* > 0 */
1541 void* const startPosition = (char*)ress->srcBuffer + ress->srcBufferLoaded;
1542 size_t const readSize = fread(startPosition, 1, toRead, finput);
1544 DISPLAYLEVEL(1, "%s : Read error (39) : premature end \n",
1546 return FIO_ERROR_FRAME_DECODING;
1548 ress->srcBufferLoaded += readSize;
1551 FIO_fwriteSparseEnd(ress->dstFile, storedSkips);
1557 #ifdef ZSTD_GZDECOMPRESS
1558 static unsigned long long FIO_decompressGzFrame(dRess_t* ress,
1559 FILE* srcFile, const char* srcFileName)
1561 unsigned long long outFileSize = 0;
1563 int flush = Z_NO_FLUSH;
1564 int decodingError = 0;
1566 strm.zalloc = Z_NULL;
1567 strm.zfree = Z_NULL;
1568 strm.opaque = Z_NULL;
1571 /* see http://www.zlib.net/manual.html */
1572 if (inflateInit2(&strm, 15 /* maxWindowLogSize */ + 16 /* gzip only */) != Z_OK)
1573 return FIO_ERROR_FRAME_DECODING;
1575 strm.next_out = (Bytef*)ress->dstBuffer;
1576 strm.avail_out = (uInt)ress->dstBufferSize;
1577 strm.avail_in = (uInt)ress->srcBufferLoaded;
1578 strm.next_in = (z_const unsigned char*)ress->srcBuffer;
1582 if (strm.avail_in == 0) {
1583 ress->srcBufferLoaded = fread(ress->srcBuffer, 1, ress->srcBufferSize, srcFile);
1584 if (ress->srcBufferLoaded == 0) flush = Z_FINISH;
1585 strm.next_in = (z_const unsigned char*)ress->srcBuffer;
1586 strm.avail_in = (uInt)ress->srcBufferLoaded;
1588 ret = inflate(&strm, flush);
1589 if (ret == Z_BUF_ERROR) {
1590 DISPLAYLEVEL(1, "zstd: %s: premature gz end \n", srcFileName);
1591 decodingError = 1; break;
1593 if (ret != Z_OK && ret != Z_STREAM_END) {
1594 DISPLAYLEVEL(1, "zstd: %s: inflate error %d \n", srcFileName, ret);
1595 decodingError = 1; break;
1597 { size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
1599 if (fwrite(ress->dstBuffer, 1, decompBytes, ress->dstFile) != decompBytes) {
1600 DISPLAYLEVEL(1, "zstd: %s \n", strerror(errno));
1601 decodingError = 1; break;
1603 outFileSize += decompBytes;
1604 strm.next_out = (Bytef*)ress->dstBuffer;
1605 strm.avail_out = (uInt)ress->dstBufferSize;
1608 if (ret == Z_STREAM_END) break;
1611 if (strm.avail_in > 0)
1612 memmove(ress->srcBuffer, strm.next_in, strm.avail_in);
1613 ress->srcBufferLoaded = strm.avail_in;
1614 if ( (inflateEnd(&strm) != Z_OK) /* release resources ; error detected */
1615 && (decodingError==0) ) {
1616 DISPLAYLEVEL(1, "zstd: %s: inflateEnd error \n", srcFileName);
1619 return decodingError ? FIO_ERROR_FRAME_DECODING : outFileSize;
1624 #ifdef ZSTD_LZMADECOMPRESS
1625 static unsigned long long FIO_decompressLzmaFrame(dRess_t* ress, FILE* srcFile, const char* srcFileName, int plain_lzma)
1627 unsigned long long outFileSize = 0;
1628 lzma_stream strm = LZMA_STREAM_INIT;
1629 lzma_action action = LZMA_RUN;
1631 int decodingError = 0;
1636 initRet = lzma_alone_decoder(&strm, UINT64_MAX); /* LZMA */
1638 initRet = lzma_stream_decoder(&strm, UINT64_MAX, 0); /* XZ */
1641 if (initRet != LZMA_OK) {
1642 DISPLAYLEVEL(1, "zstd: %s: %s error %d \n",
1643 plain_lzma ? "lzma_alone_decoder" : "lzma_stream_decoder",
1644 srcFileName, initRet);
1645 return FIO_ERROR_FRAME_DECODING;
1648 strm.next_out = (BYTE*)ress->dstBuffer;
1649 strm.avail_out = ress->dstBufferSize;
1650 strm.next_in = (BYTE const*)ress->srcBuffer;
1651 strm.avail_in = ress->srcBufferLoaded;
1655 if (strm.avail_in == 0) {
1656 ress->srcBufferLoaded = fread(ress->srcBuffer, 1, ress->srcBufferSize, srcFile);
1657 if (ress->srcBufferLoaded == 0) action = LZMA_FINISH;
1658 strm.next_in = (BYTE const*)ress->srcBuffer;
1659 strm.avail_in = ress->srcBufferLoaded;
1661 ret = lzma_code(&strm, action);
1663 if (ret == LZMA_BUF_ERROR) {
1664 DISPLAYLEVEL(1, "zstd: %s: premature lzma end \n", srcFileName);
1665 decodingError = 1; break;
1667 if (ret != LZMA_OK && ret != LZMA_STREAM_END) {
1668 DISPLAYLEVEL(1, "zstd: %s: lzma_code decoding error %d \n",
1670 decodingError = 1; break;
1672 { size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
1674 if (fwrite(ress->dstBuffer, 1, decompBytes, ress->dstFile) != decompBytes) {
1675 DISPLAYLEVEL(1, "zstd: %s \n", strerror(errno));
1676 decodingError = 1; break;
1678 outFileSize += decompBytes;
1679 strm.next_out = (BYTE*)ress->dstBuffer;
1680 strm.avail_out = ress->dstBufferSize;
1682 if (ret == LZMA_STREAM_END) break;
1685 if (strm.avail_in > 0)
1686 memmove(ress->srcBuffer, strm.next_in, strm.avail_in);
1687 ress->srcBufferLoaded = strm.avail_in;
1689 return decodingError ? FIO_ERROR_FRAME_DECODING : outFileSize;
1693 #ifdef ZSTD_LZ4DECOMPRESS
1694 static unsigned long long FIO_decompressLz4Frame(dRess_t* ress,
1695 FILE* srcFile, const char* srcFileName)
1697 unsigned long long filesize = 0;
1698 LZ4F_errorCode_t nextToLoad;
1699 LZ4F_decompressionContext_t dCtx;
1700 LZ4F_errorCode_t const errorCode = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
1701 int decodingError = 0;
1703 if (LZ4F_isError(errorCode)) {
1704 DISPLAYLEVEL(1, "zstd: failed to create lz4 decompression context \n");
1705 return FIO_ERROR_FRAME_DECODING;
1708 /* Init feed with magic number (already consumed from FILE* sFile) */
1709 { size_t inSize = 4;
1711 MEM_writeLE32(ress->srcBuffer, LZ4_MAGICNUMBER);
1712 nextToLoad = LZ4F_decompress(dCtx, ress->dstBuffer, &outSize, ress->srcBuffer, &inSize, NULL);
1713 if (LZ4F_isError(nextToLoad)) {
1714 DISPLAYLEVEL(1, "zstd: %s: lz4 header error : %s \n",
1715 srcFileName, LZ4F_getErrorName(nextToLoad));
1716 LZ4F_freeDecompressionContext(dCtx);
1717 return FIO_ERROR_FRAME_DECODING;
1721 for (;nextToLoad;) {
1724 size_t decodedBytes = ress->dstBufferSize;
1727 if (nextToLoad > ress->srcBufferSize) nextToLoad = ress->srcBufferSize;
1728 readSize = fread(ress->srcBuffer, 1, nextToLoad, srcFile);
1729 if (!readSize) break; /* reached end of file or stream */
1731 while ((pos < readSize) || (decodedBytes == ress->dstBufferSize)) { /* still to read, or still to flush */
1732 /* Decode Input (at least partially) */
1733 size_t remaining = readSize - pos;
1734 decodedBytes = ress->dstBufferSize;
1735 nextToLoad = LZ4F_decompress(dCtx, ress->dstBuffer, &decodedBytes, (char*)(ress->srcBuffer)+pos, &remaining, NULL);
1736 if (LZ4F_isError(nextToLoad)) {
1737 DISPLAYLEVEL(1, "zstd: %s: lz4 decompression error : %s \n",
1738 srcFileName, LZ4F_getErrorName(nextToLoad));
1739 decodingError = 1; nextToLoad = 0; break;
1745 if (fwrite(ress->dstBuffer, 1, decodedBytes, ress->dstFile) != decodedBytes) {
1746 DISPLAYLEVEL(1, "zstd: %s \n", strerror(errno));
1747 decodingError = 1; nextToLoad = 0; break;
1749 filesize += decodedBytes;
1750 DISPLAYUPDATE(2, "\rDecompressed : %u MB ", (unsigned)(filesize>>20));
1753 if (!nextToLoad) break;
1756 /* can be out because readSize == 0, which could be an fread() error */
1757 if (ferror(srcFile)) {
1758 DISPLAYLEVEL(1, "zstd: %s: read error \n", srcFileName);
1762 if (nextToLoad!=0) {
1763 DISPLAYLEVEL(1, "zstd: %s: unfinished lz4 stream \n", srcFileName);
1767 LZ4F_freeDecompressionContext(dCtx);
1768 ress->srcBufferLoaded = 0; /* LZ4F will reach exact frame boundary */
1770 return decodingError ? FIO_ERROR_FRAME_DECODING : filesize;
1776 /** FIO_decompressFrames() :
1777 * Find and decode frames inside srcFile
1778 * srcFile presumed opened and valid
1782 static int FIO_decompressFrames(dRess_t ress, FILE* srcFile,
1783 const char* dstFileName, const char* srcFileName)
1785 unsigned readSomething = 0;
1786 unsigned long long filesize = 0;
1787 assert(srcFile != NULL);
1789 /* for each frame */
1791 /* check magic number -> version */
1792 size_t const toRead = 4;
1793 const BYTE* const buf = (const BYTE*)ress.srcBuffer;
1794 if (ress.srcBufferLoaded < toRead) /* load up to 4 bytes for header */
1795 ress.srcBufferLoaded += fread((char*)ress.srcBuffer + ress.srcBufferLoaded,
1796 (size_t)1, toRead - ress.srcBufferLoaded, srcFile);
1797 if (ress.srcBufferLoaded==0) {
1798 if (readSomething==0) { /* srcFile is empty (which is invalid) */
1799 DISPLAYLEVEL(1, "zstd: %s: unexpected end of file \n", srcFileName);
1801 } /* else, just reached frame boundary */
1802 break; /* no more input */
1804 readSomething = 1; /* there is at least 1 byte in srcFile */
1805 if (ress.srcBufferLoaded < toRead) {
1806 DISPLAYLEVEL(1, "zstd: %s: unknown header \n", srcFileName);
1809 if (ZSTD_isFrame(buf, ress.srcBufferLoaded)) {
1810 unsigned long long const frameSize = FIO_decompressZstdFrame(&ress, srcFile, srcFileName, filesize);
1811 if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
1812 filesize += frameSize;
1813 } else if (buf[0] == 31 && buf[1] == 139) { /* gz magic number */
1814 #ifdef ZSTD_GZDECOMPRESS
1815 unsigned long long const frameSize = FIO_decompressGzFrame(&ress, srcFile, srcFileName);
1816 if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
1817 filesize += frameSize;
1819 DISPLAYLEVEL(1, "zstd: %s: gzip file cannot be uncompressed (zstd compiled without HAVE_ZLIB) -- ignored \n", srcFileName);
1822 } else if ((buf[0] == 0xFD && buf[1] == 0x37) /* xz magic number */
1823 || (buf[0] == 0x5D && buf[1] == 0x00)) { /* lzma header (no magic number) */
1824 #ifdef ZSTD_LZMADECOMPRESS
1825 unsigned long long const frameSize = FIO_decompressLzmaFrame(&ress, srcFile, srcFileName, buf[0] != 0xFD);
1826 if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
1827 filesize += frameSize;
1829 DISPLAYLEVEL(1, "zstd: %s: xz/lzma file cannot be uncompressed (zstd compiled without HAVE_LZMA) -- ignored \n", srcFileName);
1832 } else if (MEM_readLE32(buf) == LZ4_MAGICNUMBER) {
1833 #ifdef ZSTD_LZ4DECOMPRESS
1834 unsigned long long const frameSize = FIO_decompressLz4Frame(&ress, srcFile, srcFileName);
1835 if (frameSize == FIO_ERROR_FRAME_DECODING) return 1;
1836 filesize += frameSize;
1838 DISPLAYLEVEL(1, "zstd: %s: lz4 file cannot be uncompressed (zstd compiled without HAVE_LZ4) -- ignored \n", srcFileName);
1841 } else if ((g_overwrite) && !strcmp (dstFileName, stdoutmark)) { /* pass-through mode */
1842 return FIO_passThrough(ress.dstFile, srcFile,
1843 ress.srcBuffer, ress.srcBufferSize, ress.srcBufferLoaded);
1845 DISPLAYLEVEL(1, "zstd: %s: unsupported format \n", srcFileName);
1847 } } /* for each frame */
1850 DISPLAYLEVEL(2, "\r%79s\r", "");
1851 DISPLAYLEVEL(2, "%-20s: %llu bytes \n", srcFileName, filesize);
1856 /** FIO_decompressDstFile() :
1858 or path-through if ress.dstFile is already != 0,
1859 then start decompression process (FIO_decompressFrames()).
1861 1 : operation aborted
1863 static int FIO_decompressDstFile(dRess_t ress, FILE* srcFile,
1864 const char* dstFileName, const char* srcFileName)
1868 int transfer_permissions = 0;
1869 int releaseDstFile = 0;
1871 if (ress.dstFile == NULL) {
1874 ress.dstFile = FIO_openDstFile(dstFileName);
1875 if (ress.dstFile==0) return 1;
1877 /* Must only be added after FIO_openDstFile() succeeds.
1878 * Otherwise we may delete the destination file if it already exists,
1879 * and the user presses Ctrl-C when asked if they wish to overwrite.
1881 addHandler(dstFileName);
1883 if ( strcmp(srcFileName, stdinmark) /* special case : don't transfer permissions from stdin */
1884 && UTIL_getFileStat(srcFileName, &statbuf) )
1885 transfer_permissions = 1;
1889 result = FIO_decompressFrames(ress, srcFile, dstFileName, srcFileName);
1891 if (releaseDstFile) {
1892 FILE* const dstFile = ress.dstFile;
1894 ress.dstFile = NULL;
1895 if (fclose(dstFile)) {
1896 DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno));
1900 if ( (result != 0) /* operation failure */
1901 && strcmp(dstFileName, nulmark) /* special case : don't remove() /dev/null (#316) */
1902 && strcmp(dstFileName, stdoutmark) /* special case : don't remove() stdout */
1904 FIO_remove(dstFileName); /* remove decompression artefact; note: don't do anything special if remove() fails */
1905 } else { /* operation success */
1906 if ( strcmp(dstFileName, stdoutmark) /* special case : don't chmod stdout */
1907 && strcmp(dstFileName, nulmark) /* special case : don't chmod /dev/null */
1908 && transfer_permissions ) /* file permissions correctly extracted from src */
1909 UTIL_setFileStat(dstFileName, &statbuf); /* transfer file permissions from src into dst */
1917 /** FIO_decompressSrcFile() :
1918 Open `srcFileName`, transfer control to decompressDstFile()
1922 static int FIO_decompressSrcFile(dRess_t ress, const char* dstFileName, const char* srcFileName)
1927 if (UTIL_isDirectory(srcFileName)) {
1928 DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
1932 srcFile = FIO_openSrcFile(srcFileName);
1933 if (srcFile==NULL) return 1;
1934 ress.srcBufferLoaded = 0;
1936 result = FIO_decompressDstFile(ress, srcFile, dstFileName, srcFileName);
1939 if (fclose(srcFile)) {
1940 DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno)); /* error should not happen */
1943 if ( g_removeSrcFile /* --rm */
1944 && (result==0) /* decompression successful */
1945 && strcmp(srcFileName, stdinmark) ) /* not stdin */ {
1946 /* We must clear the handler, since after this point calling it would
1947 * delete both the source and destination files.
1950 if (FIO_remove(srcFileName)) {
1951 /* failed to remove src file */
1952 DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));
1960 int FIO_decompressFilename(const char* dstFileName, const char* srcFileName,
1961 const char* dictFileName)
1963 dRess_t const ress = FIO_createDResources(dictFileName);
1965 int const decodingError = FIO_decompressSrcFile(ress, dstFileName, srcFileName);
1967 FIO_freeDResources(ress);
1968 return decodingError;
1972 /* FIO_determineDstName() :
1973 * create a destination filename from a srcFileName.
1974 * @return a pointer to it.
1975 * @return == NULL if there is an error */
1977 FIO_determineDstName(const char* srcFileName)
1979 static size_t dfnbCapacity = 0;
1980 static char* dstFileNameBuffer = NULL; /* using static allocation : this function cannot be multi-threaded */
1982 size_t const sfnSize = strlen(srcFileName);
1984 const char* const suffixPtr = strrchr(srcFileName, '.');
1985 if (suffixPtr == NULL) {
1986 DISPLAYLEVEL(1, "zstd: %s: unknown suffix -- ignored \n",
1990 suffixSize = strlen(suffixPtr);
1992 /* check suffix is authorized */
1993 if (sfnSize <= suffixSize
1994 || ( strcmp(suffixPtr, ZSTD_EXTENSION)
1995 #ifdef ZSTD_GZDECOMPRESS
1996 && strcmp(suffixPtr, GZ_EXTENSION)
1998 #ifdef ZSTD_LZMADECOMPRESS
1999 && strcmp(suffixPtr, XZ_EXTENSION)
2000 && strcmp(suffixPtr, LZMA_EXTENSION)
2002 #ifdef ZSTD_LZ4DECOMPRESS
2003 && strcmp(suffixPtr, LZ4_EXTENSION)
2006 const char* suffixlist = ZSTD_EXTENSION
2007 #ifdef ZSTD_GZDECOMPRESS
2010 #ifdef ZSTD_LZMADECOMPRESS
2011 "/" XZ_EXTENSION "/" LZMA_EXTENSION
2013 #ifdef ZSTD_LZ4DECOMPRESS
2017 DISPLAYLEVEL(1, "zstd: %s: unknown suffix (%s expected) -- ignored \n",
2018 srcFileName, suffixlist);
2022 /* allocate enough space to write dstFilename into it */
2023 if (dfnbCapacity+suffixSize <= sfnSize+1) {
2024 free(dstFileNameBuffer);
2025 dfnbCapacity = sfnSize + 20;
2026 dstFileNameBuffer = (char*)malloc(dfnbCapacity);
2027 if (dstFileNameBuffer==NULL)
2028 EXM_THROW(74, "not enough memory for dstFileName");
2031 /* return dst name == src name truncated from suffix */
2032 assert(dstFileNameBuffer != NULL);
2033 memcpy(dstFileNameBuffer, srcFileName, sfnSize - suffixSize);
2034 dstFileNameBuffer[sfnSize-suffixSize] = '\0';
2035 return dstFileNameBuffer;
2037 /* note : dstFileNameBuffer memory is not going to be free */
2042 FIO_decompressMultipleFilenames(const char* srcNamesTable[], unsigned nbFiles,
2043 const char* outFileName,
2044 const char* dictFileName)
2047 dRess_t ress = FIO_createDResources(dictFileName);
2051 ress.dstFile = FIO_openDstFile(outFileName);
2052 if (ress.dstFile == 0) EXM_THROW(71, "cannot open %s", outFileName);
2053 for (u=0; u<nbFiles; u++)
2054 error |= FIO_decompressSrcFile(ress, outFileName, srcNamesTable[u]);
2055 if (fclose(ress.dstFile))
2056 EXM_THROW(72, "Write error : cannot properly close output file");
2059 for (u=0; u<nbFiles; u++) { /* create dstFileName */
2060 const char* const srcFileName = srcNamesTable[u];
2061 const char* const dstFileName = FIO_determineDstName(srcFileName);
2062 if (dstFileName == NULL) { error=1; continue; }
2064 error |= FIO_decompressSrcFile(ress, dstFileName, srcFileName);
2068 FIO_freeDResources(ress);
2074 /* **************************************************************************
2075 * .zst file info (--list command)
2076 ***************************************************************************/
2079 U64 decompressedSize;
2082 int numActualFrames;
2083 int numSkippableFrames;
2084 int decompUnavailable;
2089 typedef enum { info_success=0, info_frame_error=1, info_not_zstd=2, info_file_error=3 } InfoError;
2091 #define ERROR_IF(c,n,...) { \
2093 DISPLAYLEVEL(1, __VA_ARGS__); \
2094 DISPLAYLEVEL(1, " \n"); \
2100 FIO_analyzeFrames(fileInfo_t* info, FILE* const srcFile)
2102 /* begin analyzing frame */
2104 BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
2105 size_t const numBytesRead = fread(headerBuffer, 1, sizeof(headerBuffer), srcFile);
2106 if (numBytesRead < ZSTD_frameHeaderSize_min) {
2108 && (numBytesRead == 0)
2109 && (info->compressedSize > 0)
2110 && (info->compressedSize != UTIL_FILESIZE_UNKNOWN) ) {
2111 break; /* correct end of file => success */
2113 ERROR_IF(feof(srcFile), info_not_zstd, "Error: reached end of file with incomplete frame");
2114 ERROR_IF(1, info_frame_error, "Error: did not reach end of file but ran out of frames");
2116 { U32 const magicNumber = MEM_readLE32(headerBuffer);
2117 /* Zstandard frame */
2118 if (magicNumber == ZSTD_MAGICNUMBER) {
2119 ZSTD_frameHeader header;
2120 U64 const frameContentSize = ZSTD_getFrameContentSize(headerBuffer, numBytesRead);
2121 if ( frameContentSize == ZSTD_CONTENTSIZE_ERROR
2122 || frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN ) {
2123 info->decompUnavailable = 1;
2125 info->decompressedSize += frameContentSize;
2127 ERROR_IF(ZSTD_getFrameHeader(&header, headerBuffer, numBytesRead) != 0,
2128 info_frame_error, "Error: could not decode frame header");
2129 info->windowSize = header.windowSize;
2130 /* move to the end of the frame header */
2131 { size_t const headerSize = ZSTD_frameHeaderSize(headerBuffer, numBytesRead);
2132 ERROR_IF(ZSTD_isError(headerSize), info_frame_error, "Error: could not determine frame header size");
2133 ERROR_IF(fseek(srcFile, ((long)headerSize)-((long)numBytesRead), SEEK_CUR) != 0,
2134 info_frame_error, "Error: could not move to end of frame header");
2137 /* skip all blocks in the frame */
2138 { int lastBlock = 0;
2140 BYTE blockHeaderBuffer[3];
2141 ERROR_IF(fread(blockHeaderBuffer, 1, 3, srcFile) != 3,
2142 info_frame_error, "Error while reading block header");
2143 { U32 const blockHeader = MEM_readLE24(blockHeaderBuffer);
2144 U32 const blockTypeID = (blockHeader >> 1) & 3;
2145 U32 const isRLE = (blockTypeID == 1);
2146 U32 const isWrongBlock = (blockTypeID == 3);
2147 long const blockSize = isRLE ? 1 : (long)(blockHeader >> 3);
2148 ERROR_IF(isWrongBlock, info_frame_error, "Error: unsupported block type");
2149 lastBlock = blockHeader & 1;
2150 ERROR_IF(fseek(srcFile, blockSize, SEEK_CUR) != 0,
2151 info_frame_error, "Error: could not skip to end of block");
2153 } while (lastBlock != 1);
2156 /* check if checksum is used */
2157 { BYTE const frameHeaderDescriptor = headerBuffer[4];
2158 int const contentChecksumFlag = (frameHeaderDescriptor & (1 << 2)) >> 2;
2159 if (contentChecksumFlag) {
2160 info->usesCheck = 1;
2161 ERROR_IF(fseek(srcFile, 4, SEEK_CUR) != 0,
2162 info_frame_error, "Error: could not skip past checksum");
2164 info->numActualFrames++;
2166 /* Skippable frame */
2167 else if ((magicNumber & 0xFFFFFFF0U) == ZSTD_MAGIC_SKIPPABLE_START) {
2168 U32 const frameSize = MEM_readLE32(headerBuffer + 4);
2169 long const seek = (long)(8 + frameSize - numBytesRead);
2170 ERROR_IF(LONG_SEEK(srcFile, seek, SEEK_CUR) != 0,
2171 info_frame_error, "Error: could not find end of skippable frame");
2172 info->numSkippableFrames++;
2174 /* unknown content */
2176 return info_not_zstd;
2178 } /* magic number analysis */
2179 } /* end analyzing frames */
2180 return info_success;
2185 getFileInfo_fileConfirmed(fileInfo_t* info, const char* inFileName)
2188 FILE* const srcFile = FIO_openSrcFile(inFileName);
2189 ERROR_IF(srcFile == NULL, info_file_error, "Error: could not open source file %s", inFileName);
2191 info->compressedSize = UTIL_getFileSize(inFileName);
2192 status = FIO_analyzeFrames(info, srcFile);
2201 * Reads information from file, stores in *info
2202 * @return : InfoError status
2205 getFileInfo(fileInfo_t* info, const char* srcFileName)
2207 ERROR_IF(!UTIL_isRegularFile(srcFileName),
2208 info_file_error, "Error : %s is not a file", srcFileName);
2209 return getFileInfo_fileConfirmed(info, srcFileName);
2214 displayInfo(const char* inFileName, const fileInfo_t* info, int displayLevel)
2216 unsigned const unit = info->compressedSize < (1 MB) ? (1 KB) : (1 MB);
2217 const char* const unitStr = info->compressedSize < (1 MB) ? "KB" : "MB";
2218 double const windowSizeUnit = (double)info->windowSize / unit;
2219 double const compressedSizeUnit = (double)info->compressedSize / unit;
2220 double const decompressedSizeUnit = (double)info->decompressedSize / unit;
2221 double const ratio = (info->compressedSize == 0) ? 0 : ((double)info->decompressedSize)/info->compressedSize;
2222 const char* const checkString = (info->usesCheck ? "XXH64" : "None");
2223 if (displayLevel <= 2) {
2224 if (!info->decompUnavailable) {
2225 DISPLAYOUT("%6d %5d %7.2f %2s %9.2f %2s %5.3f %5s %s\n",
2226 info->numSkippableFrames + info->numActualFrames,
2227 info->numSkippableFrames,
2228 compressedSizeUnit, unitStr, decompressedSizeUnit, unitStr,
2229 ratio, checkString, inFileName);
2231 DISPLAYOUT("%6d %5d %7.2f %2s %5s %s\n",
2232 info->numSkippableFrames + info->numActualFrames,
2233 info->numSkippableFrames,
2234 compressedSizeUnit, unitStr,
2235 checkString, inFileName);
2238 DISPLAYOUT("%s \n", inFileName);
2239 DISPLAYOUT("# Zstandard Frames: %d\n", info->numActualFrames);
2240 if (info->numSkippableFrames)
2241 DISPLAYOUT("# Skippable Frames: %d\n", info->numSkippableFrames);
2242 DISPLAYOUT("Window Size: %.2f %2s (%llu B)\n",
2243 windowSizeUnit, unitStr,
2244 (unsigned long long)info->windowSize);
2245 DISPLAYOUT("Compressed Size: %.2f %2s (%llu B)\n",
2246 compressedSizeUnit, unitStr,
2247 (unsigned long long)info->compressedSize);
2248 if (!info->decompUnavailable) {
2249 DISPLAYOUT("Decompressed Size: %.2f %2s (%llu B)\n",
2250 decompressedSizeUnit, unitStr,
2251 (unsigned long long)info->decompressedSize);
2252 DISPLAYOUT("Ratio: %.4f\n", ratio);
2254 DISPLAYOUT("Check: %s\n", checkString);
2259 static fileInfo_t FIO_addFInfo(fileInfo_t fi1, fileInfo_t fi2)
2262 memset(&total, 0, sizeof(total));
2263 total.numActualFrames = fi1.numActualFrames + fi2.numActualFrames;
2264 total.numSkippableFrames = fi1.numSkippableFrames + fi2.numSkippableFrames;
2265 total.compressedSize = fi1.compressedSize + fi2.compressedSize;
2266 total.decompressedSize = fi1.decompressedSize + fi2.decompressedSize;
2267 total.decompUnavailable = fi1.decompUnavailable | fi2.decompUnavailable;
2268 total.usesCheck = fi1.usesCheck & fi2.usesCheck;
2269 total.nbFiles = fi1.nbFiles + fi2.nbFiles;
2274 FIO_listFile(fileInfo_t* total, const char* inFileName, int displayLevel)
2277 memset(&info, 0, sizeof(info));
2278 { InfoError const error = getFileInfo(&info, inFileName);
2279 if (error == info_frame_error) {
2280 /* display error, but provide output */
2281 DISPLAYLEVEL(1, "Error while parsing %s \n", inFileName);
2283 else if (error == info_not_zstd) {
2284 DISPLAYOUT("File %s not compressed by zstd \n", inFileName);
2285 if (displayLevel > 2) DISPLAYOUT("\n");
2288 else if (error == info_file_error) {
2289 /* error occurred while opening the file */
2290 if (displayLevel > 2) DISPLAYOUT("\n");
2293 displayInfo(inFileName, &info, displayLevel);
2294 *total = FIO_addFInfo(*total, info);
2295 assert(error>=0 || error<=1);
2300 int FIO_listMultipleFiles(unsigned numFiles, const char** filenameTable, int displayLevel)
2302 /* ensure no specified input is stdin (needs fseek() capability) */
2304 for (u=0; u<numFiles;u++) {
2305 ERROR_IF(!strcmp (filenameTable[u], stdinmark),
2306 1, "zstd: --list does not support reading from standard input");
2309 if (numFiles == 0) {
2310 if (!IS_CONSOLE(stdin)) {
2311 DISPLAYLEVEL(1, "zstd: --list does not support reading from standard input \n");
2313 DISPLAYLEVEL(1, "No files given \n");
2317 if (displayLevel <= 2) {
2318 DISPLAYOUT("Frames Skips Compressed Uncompressed Ratio Check Filename\n");
2322 memset(&total, 0, sizeof(total));
2323 total.usesCheck = 1;
2324 /* --list each file, and check for any error */
2326 for (u=0; u<numFiles;u++) {
2327 error |= FIO_listFile(&total, filenameTable[u], displayLevel);
2329 if (numFiles > 1 && displayLevel <= 2) { /* display total */
2330 unsigned const unit = total.compressedSize < (1 MB) ? (1 KB) : (1 MB);
2331 const char* const unitStr = total.compressedSize < (1 MB) ? "KB" : "MB";
2332 double const compressedSizeUnit = (double)total.compressedSize / unit;
2333 double const decompressedSizeUnit = (double)total.decompressedSize / unit;
2334 double const ratio = (total.compressedSize == 0) ? 0 : ((double)total.decompressedSize)/total.compressedSize;
2335 const char* const checkString = (total.usesCheck ? "XXH64" : "");
2336 DISPLAYOUT("----------------------------------------------------------------- \n");
2337 if (total.decompUnavailable) {
2338 DISPLAYOUT("%6d %5d %7.2f %2s %5s %u files\n",
2339 total.numSkippableFrames + total.numActualFrames,
2340 total.numSkippableFrames,
2341 compressedSizeUnit, unitStr,
2342 checkString, total.nbFiles);
2344 DISPLAYOUT("%6d %5d %7.2f %2s %9.2f %2s %5.3f %5s %u files\n",
2345 total.numSkippableFrames + total.numActualFrames,
2346 total.numSkippableFrames,
2347 compressedSizeUnit, unitStr, decompressedSizeUnit, unitStr,
2348 ratio, checkString, total.nbFiles);
2355 #endif /* #ifndef ZSTD_NODECOMPRESS */