blob: 9c3c2b7af69c0088a7584d999a3cb7a78dbd6f72 [file] [log] [blame]
Yann Collet4ded9e52016-08-30 10:04:33 -07001/**
2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree. An additional grant
7 * of patent rights can be found in the PATENTS file in the same directory.
8 */
Yann Collet4856a002015-01-24 01:58:16 +01009
Yann Colleteeb8ba12015-10-22 16:55:40 +010010/* *************************************
Yann Collet4856a002015-01-24 01:58:16 +010011* Compiler Options
Yann Colleteeb8ba12015-10-22 16:55:40 +010012***************************************/
Yann Collet94ca85d2016-08-14 01:19:12 +020013#ifdef _MSC_VER /* Visual */
Przemyslaw Skibinskie6797412016-12-21 13:47:11 +010014# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
Yann Collet94ca85d2016-08-14 01:19:12 +020015# pragma warning(disable : 4204) /* non-constant aggregate initializer */
16#endif
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010017#if defined(__MINGW32__) && !defined(_POSIX_SOURCE)
18# define _POSIX_SOURCE 1 /* disable %llu warnings with MinGW on Windows */
19#endif
Yann Collet4856a002015-01-24 01:58:16 +010020
Yann Collet179b1972016-11-02 17:30:49 -070021
Yann Collet6f3acba2016-02-12 20:19:48 +010022/*-*************************************
Yann Collet4856a002015-01-24 01:58:16 +010023* Includes
Yann Colleteeb8ba12015-10-22 16:55:40 +010024***************************************/
Przemyslaw Skibinski7a8a03c2016-12-21 15:08:44 +010025#include "platform.h" /* Large Files support, SET_BINARY_MODE */
26#include "util.h" /* UTIL_getFileSize */
Yann Collet9f432922015-11-09 17:42:17 +010027#include <stdio.h> /* fprintf, fopen, fread, _fileno, stdin, stdout */
28#include <stdlib.h> /* malloc, free */
29#include <string.h> /* strcmp, strlen */
30#include <time.h> /* clock */
31#include <errno.h> /* errno */
inikepd5ff2c32016-04-28 14:40:45 +020032
Przemyslaw Skibinski2f6ccee2016-12-21 13:23:34 +010033#include "mem.h"
Yann Collet4856a002015-01-24 01:58:16 +010034#include "fileio.h"
Yann Colletd3b7f8d2016-06-04 19:47:02 +020035#define ZSTD_STATIC_LINKING_ONLY /* ZSTD_magicNumber, ZSTD_frameHeaderSize_max */
36#include "zstd.h"
Przemyslaw Skibinskiabfb51f2016-11-30 15:05:54 +010037#ifdef ZSTD_GZDECOMPRESS
38#include "zlib.h"
Przemyslaw Skibinski6b508b12016-12-05 18:02:40 +010039#if !defined(z_const)
40 #define z_const
41#endif
Przemyslaw Skibinskiabfb51f2016-11-30 15:05:54 +010042#endif
Yann Collet4856a002015-01-24 01:58:16 +010043
44
Yann Collet6f3acba2016-02-12 20:19:48 +010045/*-*************************************
Yann Collet4856a002015-01-24 01:58:16 +010046* Constants
Yann Colleteeb8ba12015-10-22 16:55:40 +010047***************************************/
Yann Collet92d75662016-07-03 01:10:53 +020048#define KB *(1<<10)
49#define MB *(1<<20)
50#define GB *(1U<<30)
51
Yann Collet4856a002015-01-24 01:58:16 +010052#define _1BIT 0x01
53#define _2BITS 0x03
54#define _3BITS 0x07
55#define _4BITS 0x0F
56#define _6BITS 0x3F
57#define _8BITS 0xFF
58
Yann Collet88fcd292015-11-25 14:42:45 +010059#define BLOCKSIZE (128 KB)
60#define ROLLBUFFERSIZE (BLOCKSIZE*8*64)
Yann Collet4856a002015-01-24 01:58:16 +010061
Yann Collet6f3acba2016-02-12 20:19:48 +010062#define FIO_FRAMEHEADERSIZE 5 /* as a define, because needed to allocated table on stack */
63#define FSE_CHECKSUM_SEED 0
Yann Collet4856a002015-01-24 01:58:16 +010064
65#define CACHELINE 64
66
Yann Collet6fca9e72016-05-31 02:40:42 +020067#define MAX_DICT_SIZE (8 MB) /* protection against large input (attack scenario) */
Yann Collet6f3acba2016-02-12 20:19:48 +010068
inikep3c7c3522016-04-22 13:59:05 +020069#define FNSPACE 30
Przemyslaw Skibinski0e146752016-11-30 13:34:21 +010070#define GZ_EXTENSION ".gz"
inikep3c7c3522016-04-22 13:59:05 +020071
Yann Collet4856a002015-01-24 01:58:16 +010072
Yann Collet459a6b72016-02-15 20:37:23 +010073/*-*************************************
Yann Collet4856a002015-01-24 01:58:16 +010074* Macros
Yann Colleteeb8ba12015-10-22 16:55:40 +010075***************************************/
Yann Collet4856a002015-01-24 01:58:16 +010076#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
77#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
78static U32 g_displayLevel = 2; /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */
Yann Collet8a1d1a62016-03-10 21:02:25 +010079void FIO_setNotificationLevel(unsigned level) { g_displayLevel=level; }
Yann Collet4856a002015-01-24 01:58:16 +010080
81#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
Yann Colletb71adf42016-07-02 01:05:31 +020082 if ((clock() - g_time > refreshRate) || (g_displayLevel>=4)) \
Yann Collet4856a002015-01-24 01:58:16 +010083 { g_time = clock(); DISPLAY(__VA_ARGS__); \
84 if (g_displayLevel>=4) fflush(stdout); } }
Yann Colletb71adf42016-07-02 01:05:31 +020085static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100;
Yann Collet4856a002015-01-24 01:58:16 +010086static clock_t g_time = 0;
87
Yann Collet92d75662016-07-03 01:10:53 +020088#define MIN(a,b) ((a) < (b) ? (a) : (b))
89
Yann Collet459a6b72016-02-15 20:37:23 +010090
91/*-*************************************
Yann Colletb71adf42016-07-02 01:05:31 +020092* Local Parameters - Not thread safe
Yann Colleteeb8ba12015-10-22 16:55:40 +010093***************************************/
Yann Collet4856a002015-01-24 01:58:16 +010094static U32 g_overwrite = 0;
Yann Collet4856a002015-01-24 01:58:16 +010095void FIO_overwriteMode(void) { g_overwrite=1; }
Yann Collet75424d12016-05-23 16:56:56 +020096static U32 g_sparseFileSupport = 1; /* 0 : no sparse allowed; 1: auto (file yes, stdout no); 2: force sparse */
97void FIO_setSparseWrite(unsigned sparse) { g_sparseFileSupport=sparse; }
Yann Collet6381e992016-05-31 02:29:45 +020098static U32 g_dictIDFlag = 1;
99void FIO_setDictIDFlag(unsigned dictIDFlag) { g_dictIDFlag = dictIDFlag; }
Yann Colletc98f8e72016-06-20 16:31:24 +0200100static U32 g_checksumFlag = 1;
Yann Collet87cfbe32016-06-01 19:22:15 +0200101void FIO_setChecksumFlag(unsigned checksumFlag) { g_checksumFlag = checksumFlag; }
Yann Colletb09b12c2016-06-09 22:59:51 +0200102static U32 g_removeSrcFile = 0;
103void FIO_setRemoveSrcFile(unsigned flag) { g_removeSrcFile = (flag>0); }
Yann Colletd4cda272016-10-14 13:13:13 -0700104static U32 g_memLimit = 0;
105void FIO_setMemLimit(unsigned memLimit) { g_memLimit = memLimit; }
106
Yann Collet4856a002015-01-24 01:58:16 +0100107
108
Yann Collet459a6b72016-02-15 20:37:23 +0100109/*-*************************************
Yann Collet4856a002015-01-24 01:58:16 +0100110* Exceptions
Yann Colleteeb8ba12015-10-22 16:55:40 +0100111***************************************/
112#ifndef DEBUG
113# define DEBUG 0
114#endif
Yann Collet4856a002015-01-24 01:58:16 +0100115#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
116#define EXM_THROW(error, ...) \
117{ \
118 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
119 DISPLAYLEVEL(1, "Error %i : ", error); \
120 DISPLAYLEVEL(1, __VA_ARGS__); \
Yann Colletcdff19c2016-11-11 17:26:54 -0800121 DISPLAYLEVEL(1, " \n"); \
Yann Collet4856a002015-01-24 01:58:16 +0100122 exit(error); \
123}
124
125
Yann Collet459a6b72016-02-15 20:37:23 +0100126/*-*************************************
Yann Collet4856a002015-01-24 01:58:16 +0100127* Functions
Yann Colleteeb8ba12015-10-22 16:55:40 +0100128***************************************/
Yann Colletcdff19c2016-11-11 17:26:54 -0800129/** FIO_openSrcFile() :
130 * condition : `dstFileName` must be non-NULL.
131 * @result : FILE* to `dstFileName`, or NULL if it fails */
Yann Colletf0624362016-02-12 15:56:46 +0100132static FILE* FIO_openSrcFile(const char* srcFileName)
133{
134 FILE* f;
135
136 if (!strcmp (srcFileName, stdinmark)) {
137 DISPLAYLEVEL(4,"Using stdin for input\n");
138 f = stdin;
139 SET_BINARY_MODE(stdin);
140 } else {
141 f = fopen(srcFileName, "rb");
Yann Colletfb5e3852016-08-13 20:49:47 +0200142 if ( f==NULL ) DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno));
Yann Colletf0624362016-02-12 15:56:46 +0100143 }
144
Yann Colletf0624362016-02-12 15:56:46 +0100145 return f;
146}
147
Yann Collet43eeea42016-09-15 15:38:44 +0200148/** FIO_openDstFile() :
149 * condition : `dstFileName` must be non-NULL.
150 * @result : FILE* to `dstFileName`, or NULL if it fails */
Yann Colletf0624362016-02-12 15:56:46 +0100151static FILE* FIO_openDstFile(const char* dstFileName)
152{
153 FILE* f;
154
155 if (!strcmp (dstFileName, stdoutmark)) {
156 DISPLAYLEVEL(4,"Using stdout for output\n");
157 f = stdout;
158 SET_BINARY_MODE(stdout);
Yann Collet75424d12016-05-23 16:56:56 +0200159 if (g_sparseFileSupport==1) {
160 g_sparseFileSupport = 0;
161 DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n");
162 }
Yann Colletf0624362016-02-12 15:56:46 +0100163 } else {
Yann Collet6381e992016-05-31 02:29:45 +0200164 if (!g_overwrite && strcmp (dstFileName, nulmark)) { /* Check if destination file already exists */
Yann Colletf0624362016-02-12 15:56:46 +0100165 f = fopen( dstFileName, "rb" );
166 if (f != 0) { /* dest file exists, prompt for overwrite authorization */
167 fclose(f);
168 if (g_displayLevel <= 1) {
169 /* No interaction possible */
170 DISPLAY("zstd: %s already exists; not overwritten \n", dstFileName);
Yann Colletb71adf42016-07-02 01:05:31 +0200171 return NULL;
Yann Colletf0624362016-02-12 15:56:46 +0100172 }
173 DISPLAY("zstd: %s already exists; do you wish to overwrite (y/N) ? ", dstFileName);
Yann Collet75424d12016-05-23 16:56:56 +0200174 { int ch = getchar();
Yann Colletf0624362016-02-12 15:56:46 +0100175 if ((ch!='Y') && (ch!='y')) {
176 DISPLAY(" not overwritten \n");
Yann Colletb71adf42016-07-02 01:05:31 +0200177 return NULL;
Yann Colletf0624362016-02-12 15:56:46 +0100178 }
179 while ((ch!=EOF) && (ch!='\n')) ch = getchar(); /* flush rest of input line */
180 } } }
181 f = fopen( dstFileName, "wb" );
Yann Colletfb5e3852016-08-13 20:49:47 +0200182 if (f==NULL) DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno));
Yann Colletf0624362016-02-12 15:56:46 +0100183 }
Yann Colletb71adf42016-07-02 01:05:31 +0200184
Yann Colletf0624362016-02-12 15:56:46 +0100185 return f;
186}
187
188
Yann Collet8a1d1a62016-03-10 21:02:25 +0100189/*! FIO_loadFile() :
Yann Collet09b21ee2016-03-15 12:56:03 +0100190* creates a buffer, pointed by `*bufferPtr`,
Yann Collet8a1d1a62016-03-10 21:02:25 +0100191* loads `filename` content into it,
Yann Collet6fca9e72016-05-31 02:40:42 +0200192* up to MAX_DICT_SIZE bytes.
193* @return : loaded size
Yann Colletdeb078b2015-12-17 20:30:14 +0100194*/
195static size_t FIO_loadFile(void** bufferPtr, const char* fileName)
196{
197 FILE* fileHandle;
Yann Colletdeb078b2015-12-17 20:30:14 +0100198 U64 fileSize;
199
200 *bufferPtr = NULL;
Yann Collet2ce49232016-02-02 14:36:49 +0100201 if (fileName == NULL) return 0;
Yann Colletdeb078b2015-12-17 20:30:14 +0100202
203 DISPLAYLEVEL(4,"Loading %s as dictionary \n", fileName);
204 fileHandle = fopen(fileName, "rb");
Yann Colletb71adf42016-07-02 01:05:31 +0200205 if (fileHandle==0) EXM_THROW(31, "zstd: %s: %s", fileName, strerror(errno));
inikep69fcd7c2016-04-28 12:23:33 +0200206 fileSize = UTIL_getFileSize(fileName);
Yann Collet2ce49232016-02-02 14:36:49 +0100207 if (fileSize > MAX_DICT_SIZE) {
Yann Colletdeb078b2015-12-17 20:30:14 +0100208 int seekResult;
209 if (fileSize > 1 GB) EXM_THROW(32, "Dictionary file %s is too large", fileName); /* avoid extreme cases */
inikep5a548702016-08-18 09:00:25 +0200210 DISPLAYLEVEL(2,"Dictionary %s is too large : using last %u bytes only \n", fileName, (U32)MAX_DICT_SIZE);
Yann Colletdeb078b2015-12-17 20:30:14 +0100211 seekResult = fseek(fileHandle, (long int)(fileSize-MAX_DICT_SIZE), SEEK_SET); /* use end of file */
Yann Colletb71adf42016-07-02 01:05:31 +0200212 if (seekResult != 0) EXM_THROW(33, "zstd: %s: %s", fileName, strerror(errno));
Yann Colletdeb078b2015-12-17 20:30:14 +0100213 fileSize = MAX_DICT_SIZE;
214 }
Yann Colletb71adf42016-07-02 01:05:31 +0200215 *bufferPtr = malloc((size_t)fileSize);
Yann Colleted7fb842016-07-02 11:14:30 +0200216 if (*bufferPtr==NULL) EXM_THROW(34, "zstd: %s", strerror(errno));
Yann Collet6fca9e72016-05-31 02:40:42 +0200217 { size_t const readSize = fread(*bufferPtr, 1, (size_t)fileSize, fileHandle);
218 if (readSize!=fileSize) EXM_THROW(35, "Error reading dictionary file %s", fileName); }
Yann Colletdeb078b2015-12-17 20:30:14 +0100219 fclose(fileHandle);
220 return (size_t)fileSize;
221}
222
inikep3c7c3522016-04-22 13:59:05 +0200223#ifndef ZSTD_NOCOMPRESS
Yann Collet4f137032015-12-17 02:23:58 +0100224
Yann Collet8a1d1a62016-03-10 21:02:25 +0100225/*-**********************************************************************
Yann Collet4f137032015-12-17 02:23:58 +0100226* Compression
227************************************************************************/
228typedef struct {
229 void* srcBuffer;
230 size_t srcBufferSize;
231 void* dstBuffer;
232 size_t dstBufferSize;
Yann Collet6263ba52016-08-13 23:45:45 +0200233 ZSTD_CStream* cctx;
Yann Colletf0624362016-02-12 15:56:46 +0100234 FILE* dstFile;
Yann Collet459a6b72016-02-15 20:37:23 +0100235 FILE* srcFile;
Yann Collet4f137032015-12-17 02:23:58 +0100236} cRess_t;
237
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100238static cRess_t FIO_createCResources(const char* dictFileName, int cLevel,
239 U64 srcSize, ZSTD_compressionParameters* comprParams)
Yann Collet4f137032015-12-17 02:23:58 +0100240{
241 cRess_t ress;
Yann Collet5e80dd32016-07-13 17:38:39 +0200242 memset(&ress, 0, sizeof(ress));
Yann Collet4f137032015-12-17 02:23:58 +0100243
Yann Collet6263ba52016-08-13 23:45:45 +0200244 ress.cctx = ZSTD_createCStream();
245 if (ress.cctx == NULL) EXM_THROW(30, "zstd: allocation error : can't create ZSTD_CStream");
246 ress.srcBufferSize = ZSTD_CStreamInSize();
Yann Collet4f137032015-12-17 02:23:58 +0100247 ress.srcBuffer = malloc(ress.srcBufferSize);
Yann Collet6263ba52016-08-13 23:45:45 +0200248 ress.dstBufferSize = ZSTD_CStreamOutSize();
Yann Collet4f137032015-12-17 02:23:58 +0100249 ress.dstBuffer = malloc(ress.dstBufferSize);
Yann Colleted7fb842016-07-02 11:14:30 +0200250 if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(31, "zstd: allocation error : not enough memory");
Yann Collet4f137032015-12-17 02:23:58 +0100251
252 /* dictionary */
Yann Collet43eeea42016-09-15 15:38:44 +0200253 { void* dictBuffer;
254 size_t const dictBuffSize = FIO_loadFile(&dictBuffer, dictFileName);
255 if (dictFileName && (dictBuffer==NULL)) EXM_THROW(32, "zstd: allocation error : can't create dictBuffer");
Yann Collet993060e2016-09-21 16:46:08 +0200256 { ZSTD_parameters params = ZSTD_getParams(cLevel, srcSize, dictBuffSize);
Yann Collet43eeea42016-09-15 15:38:44 +0200257 params.fParams.contentSizeFlag = 1;
258 params.fParams.checksumFlag = g_checksumFlag;
259 params.fParams.noDictIDFlag = !g_dictIDFlag;
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100260 if (comprParams->windowLog) params.cParams.windowLog = comprParams->windowLog;
261 if (comprParams->chainLog) params.cParams.chainLog = comprParams->chainLog;
262 if (comprParams->hashLog) params.cParams.hashLog = comprParams->hashLog;
263 if (comprParams->searchLog) params.cParams.searchLog = comprParams->searchLog;
264 if (comprParams->searchLength) params.cParams.searchLength = comprParams->searchLength;
265 if (comprParams->targetLength) params.cParams.targetLength = comprParams->targetLength;
Przemyslaw Skibinskic71e5522016-12-13 20:04:32 +0100266 if (comprParams->strategy) params.cParams.strategy = (ZSTD_strategy)(comprParams->strategy - 1);
Yann Collet993060e2016-09-21 16:46:08 +0200267 { size_t const errorCode = ZSTD_initCStream_advanced(ress.cctx, dictBuffer, dictBuffSize, params, srcSize);
Yann Collet43eeea42016-09-15 15:38:44 +0200268 if (ZSTD_isError(errorCode)) EXM_THROW(33, "Error initializing CStream : %s", ZSTD_getErrorName(errorCode));
269 } }
270 free(dictBuffer);
271 }
Yann Collet4f137032015-12-17 02:23:58 +0100272
273 return ress;
274}
275
276static void FIO_freeCResources(cRess_t ress)
277{
Yann Collet4f137032015-12-17 02:23:58 +0100278 free(ress.srcBuffer);
279 free(ress.dstBuffer);
Yann Collet43eeea42016-09-15 15:38:44 +0200280 ZSTD_freeCStream(ress.cctx); /* never fails */
Yann Collet4f137032015-12-17 02:23:58 +0100281}
282
283
Yann Colletf0624362016-02-12 15:56:46 +0100284/*! FIO_compressFilename_internal() :
Yann Collet8a1d1a62016-03-10 21:02:25 +0100285 * same as FIO_compressFilename_extRess(), with `ress.desFile` already opened.
Yann Colletf0624362016-02-12 15:56:46 +0100286 * @return : 0 : compression completed correctly,
287 * 1 : missing or pb opening srcFileName
Yann Collet4f137032015-12-17 02:23:58 +0100288 */
Yann Colletf0624362016-02-12 15:56:46 +0100289static int FIO_compressFilename_internal(cRess_t ress,
Yann Collet43eeea42016-09-15 15:38:44 +0200290 const char* dstFileName, const char* srcFileName)
Yann Collet4f137032015-12-17 02:23:58 +0100291{
Yann Colletf8494622016-05-07 22:43:40 +0200292 FILE* const srcFile = ress.srcFile;
293 FILE* const dstFile = ress.dstFile;
Yann Colletb44be742016-03-26 20:52:14 +0100294 U64 readsize = 0;
Yann Collet4f137032015-12-17 02:23:58 +0100295 U64 compressedfilesize = 0;
inikep69fcd7c2016-04-28 12:23:33 +0200296 U64 const fileSize = UTIL_getFileSize(srcFileName);
Yann Collet4f137032015-12-17 02:23:58 +0100297
Yann Collet4f137032015-12-17 02:23:58 +0100298 /* init */
Yann Collet43eeea42016-09-15 15:38:44 +0200299 { size_t const resetError = ZSTD_resetCStream(ress.cctx, fileSize);
300 if (ZSTD_isError(resetError)) EXM_THROW(21, "Error initializing compression : %s", ZSTD_getErrorName(resetError));
301 }
Yann Collet4f137032015-12-17 02:23:58 +0100302
303 /* Main compression loop */
Yann Collet1c8e1942016-01-26 16:31:22 +0100304 while (1) {
Yann Collet4f137032015-12-17 02:23:58 +0100305 /* Fill input Buffer */
Yann Colletb44be742016-03-26 20:52:14 +0100306 size_t const inSize = fread(ress.srcBuffer, (size_t)1, ress.srcBufferSize, srcFile);
Yann Collet4f137032015-12-17 02:23:58 +0100307 if (inSize==0) break;
Yann Colletb44be742016-03-26 20:52:14 +0100308 readsize += inSize;
309 DISPLAYUPDATE(2, "\rRead : %u MB ", (U32)(readsize>>20));
Yann Collet4f137032015-12-17 02:23:58 +0100310
Yann Collet2cac5b32016-07-13 14:15:08 +0200311 /* Compress using buffered streaming */
Yann Collet53e17fb2016-08-17 01:39:22 +0200312 { ZSTD_inBuffer inBuff = { ress.srcBuffer, inSize, 0 };
313 ZSTD_outBuffer outBuff= { ress.dstBuffer, ress.dstBufferSize, 0 };
314 { size_t const result = ZSTD_compressStream(ress.cctx, &outBuff, &inBuff);
Yann Collet6263ba52016-08-13 23:45:45 +0200315 if (ZSTD_isError(result)) EXM_THROW(23, "Compression error : %s ", ZSTD_getErrorName(result)); }
Yann Collet53e17fb2016-08-17 01:39:22 +0200316 if (inBuff.pos != inBuff.size)
Yann Collet4f137032015-12-17 02:23:58 +0100317 /* inBuff should be entirely consumed since buffer sizes are recommended ones */
318 EXM_THROW(24, "Compression error : input block not fully consumed");
319
320 /* Write cBlock */
Yann Collet53e17fb2016-08-17 01:39:22 +0200321 { size_t const sizeCheck = fwrite(ress.dstBuffer, 1, outBuff.pos, dstFile);
322 if (sizeCheck!=outBuff.pos) EXM_THROW(25, "Write error : cannot write compressed block into %s", dstFileName); }
323 compressedfilesize += outBuff.pos;
Yann Collet4f137032015-12-17 02:23:58 +0100324 }
Yann Colletb44be742016-03-26 20:52:14 +0100325 DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ", (U32)(readsize>>20), (double)compressedfilesize/readsize*100);
Yann Collet4f137032015-12-17 02:23:58 +0100326 }
327
328 /* End of Frame */
Yann Collet53e17fb2016-08-17 01:39:22 +0200329 { ZSTD_outBuffer outBuff = { ress.dstBuffer, ress.dstBufferSize, 0 };
330 size_t const result = ZSTD_endStream(ress.cctx, &outBuff);
Yann Collet4f137032015-12-17 02:23:58 +0100331 if (result!=0) EXM_THROW(26, "Compression error : cannot create frame end");
332
Yann Collet53e17fb2016-08-17 01:39:22 +0200333 { size_t const sizeCheck = fwrite(ress.dstBuffer, 1, outBuff.pos, dstFile);
334 if (sizeCheck!=outBuff.pos) EXM_THROW(27, "Write error : cannot write frame end into %s", dstFileName); }
335 compressedfilesize += outBuff.pos;
Yann Collet4f137032015-12-17 02:23:58 +0100336 }
337
338 /* Status */
339 DISPLAYLEVEL(2, "\r%79s\r", "");
David Lam0f270452016-08-13 11:26:21 -0700340 DISPLAYLEVEL(2,"%-20s :%6.2f%% (%6llu => %6llu bytes, %s) \n", srcFileName,
Yann Collet44f684d2016-07-13 19:30:40 +0200341 (double)compressedfilesize/(readsize+(!readsize) /* avoid div by zero */ )*100,
342 (unsigned long long)readsize, (unsigned long long) compressedfilesize,
343 dstFileName);
Yann Collet4f137032015-12-17 02:23:58 +0100344
Yann Collet4f137032015-12-17 02:23:58 +0100345 return 0;
346}
347
348
Yann Colletb71adf42016-07-02 01:05:31 +0200349/*! FIO_compressFilename_srcFile() :
350 * note : ress.destFile already opened
Yann Collet459a6b72016-02-15 20:37:23 +0100351 * @return : 0 : compression completed correctly,
352 * 1 : missing or pb opening srcFileName
353 */
354static int FIO_compressFilename_srcFile(cRess_t ress,
Yann Collet43eeea42016-09-15 15:38:44 +0200355 const char* dstFileName, const char* srcFileName)
Yann Collet459a6b72016-02-15 20:37:23 +0100356{
357 int result;
358
359 /* File check */
Yann Colletb09b12c2016-06-09 22:59:51 +0200360 if (UTIL_isDirectory(srcFileName)) {
361 DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
362 return 1;
363 }
Przemyslaw Skibinski64fa2db2017-01-25 13:02:33 +0100364 if (!UTIL_doesFileExists(srcFileName)) {
365 DISPLAYLEVEL(1, "zstd: %s is not a regular file -- ignored \n", srcFileName);
366 return 1;
367 }
368
Yann Collet459a6b72016-02-15 20:37:23 +0100369 ress.srcFile = FIO_openSrcFile(srcFileName);
370 if (!ress.srcFile) return 1; /* srcFile could not be opened */
371
Yann Collet43eeea42016-09-15 15:38:44 +0200372 result = FIO_compressFilename_internal(ress, dstFileName, srcFileName);
Yann Collet459a6b72016-02-15 20:37:23 +0100373
Yann Collet459a6b72016-02-15 20:37:23 +0100374 fclose(ress.srcFile);
Yann Collet43eeea42016-09-15 15:38:44 +0200375 if (g_removeSrcFile && !result) { if (remove(srcFileName)) EXM_THROW(1, "zstd: %s: %s", srcFileName, strerror(errno)); } /* remove source file : --rm */
Yann Collet459a6b72016-02-15 20:37:23 +0100376 return result;
377}
378
379
Yann Colletb09b12c2016-06-09 22:59:51 +0200380/*! FIO_compressFilename_dstFile() :
Yann Colletf0624362016-02-12 15:56:46 +0100381 * @return : 0 : compression completed correctly,
Yann Colletb09b12c2016-06-09 22:59:51 +0200382 * 1 : pb
Yann Colletf0624362016-02-12 15:56:46 +0100383 */
Yann Colletb09b12c2016-06-09 22:59:51 +0200384static int FIO_compressFilename_dstFile(cRess_t ress,
Yann Collet43eeea42016-09-15 15:38:44 +0200385 const char* dstFileName, const char* srcFileName)
Yann Colletf0624362016-02-12 15:56:46 +0100386{
387 int result;
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100388 stat_t statbuf;
389 int stat_result = 0;
Yann Colletf0624362016-02-12 15:56:46 +0100390
391 ress.dstFile = FIO_openDstFile(dstFileName);
Yann Collet43eeea42016-09-15 15:38:44 +0200392 if (ress.dstFile==NULL) return 1; /* could not open dstFileName */
Yann Colletf0624362016-02-12 15:56:46 +0100393
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100394 if (strcmp (srcFileName, stdinmark) && UTIL_getFileStat(srcFileName, &statbuf)) stat_result = 1;
Yann Collet43eeea42016-09-15 15:38:44 +0200395 result = FIO_compressFilename_srcFile(ress, dstFileName, srcFileName);
Chip Turner6de382c2016-03-13 22:24:46 -0700396
Yann Collet43eeea42016-09-15 15:38:44 +0200397 if (fclose(ress.dstFile)) { DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno)); result=1; } /* error closing dstFile */
Yann Collet44f684d2016-07-13 19:30:40 +0200398 if (result!=0) { if (remove(dstFileName)) EXM_THROW(1, "zstd: %s: %s", dstFileName, strerror(errno)); } /* remove operation artefact */
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100399 else if (strcmp (dstFileName, stdoutmark) && stat_result) UTIL_setFileStat(dstFileName, &statbuf);
Yann Colletf0624362016-02-12 15:56:46 +0100400 return result;
401}
402
403
Yann Collet9d909222015-12-17 14:09:55 +0100404int FIO_compressFilename(const char* dstFileName, const char* srcFileName,
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100405 const char* dictFileName, int compressionLevel, ZSTD_compressionParameters* comprParams)
Yann Collet4856a002015-01-24 01:58:16 +0100406{
Yann Collet6381e992016-05-31 02:29:45 +0200407 clock_t const start = clock();
Yann Collet993060e2016-09-21 16:46:08 +0200408 U64 const srcSize = UTIL_getFileSize(srcFileName);
Yann Colletb09b12c2016-06-09 22:59:51 +0200409
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100410 cRess_t const ress = FIO_createCResources(dictFileName, compressionLevel, srcSize, comprParams);
Yann Collet43eeea42016-09-15 15:38:44 +0200411 int const result = FIO_compressFilename_dstFile(ress, dstFileName, srcFileName);
Yann Collet9d909222015-12-17 14:09:55 +0100412
Yann Colletb71adf42016-07-02 01:05:31 +0200413 double const seconds = (double)(clock() - start) / CLOCKS_PER_SEC;
414 DISPLAYLEVEL(4, "Completed in %.2f sec \n", seconds);
415
416 FIO_freeCResources(ress);
417 return result;
Yann Collet4856a002015-01-24 01:58:16 +0100418}
419
420
Yann Collet9d909222015-12-17 14:09:55 +0100421int FIO_compressMultipleFilenames(const char** inFileNamesTable, unsigned nbFiles,
Yann Collet4f137032015-12-17 02:23:58 +0100422 const char* suffix,
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100423 const char* dictFileName, int compressionLevel,
424 ZSTD_compressionParameters* comprParams)
Yann Collet4f137032015-12-17 02:23:58 +0100425{
Yann Collet4f137032015-12-17 02:23:58 +0100426 int missed_files = 0;
Yann Collet4f137032015-12-17 02:23:58 +0100427 size_t dfnSize = FNSPACE;
Yann Collet44f684d2016-07-13 19:30:40 +0200428 char* dstFileName = (char*)malloc(FNSPACE);
Yann Colletf8494622016-05-07 22:43:40 +0200429 size_t const suffixSize = suffix ? strlen(suffix) : 0;
Yann Collet993060e2016-09-21 16:46:08 +0200430 U64 const srcSize = (nbFiles != 1) ? 0 : UTIL_getFileSize(inFileNamesTable[0]) ;
Przemyslaw Skibinski8349d672016-12-13 13:24:59 +0100431 cRess_t ress = FIO_createCResources(dictFileName, compressionLevel, srcSize, comprParams);
Yann Collet4f137032015-12-17 02:23:58 +0100432
433 /* init */
Yann Collet44f684d2016-07-13 19:30:40 +0200434 if (dstFileName==NULL) EXM_THROW(27, "FIO_compressMultipleFilenames : allocation error for dstFileName");
435 if (suffix == NULL) EXM_THROW(28, "FIO_compressMultipleFilenames : dst unknown"); /* should never happen */
Yann Collet4f137032015-12-17 02:23:58 +0100436
437 /* loop on each file */
Yann Collet459a6b72016-02-15 20:37:23 +0100438 if (!strcmp(suffix, stdoutmark)) {
Yann Colletf8494622016-05-07 22:43:40 +0200439 unsigned u;
Yann Collet459a6b72016-02-15 20:37:23 +0100440 ress.dstFile = stdout;
inikep60af95d2016-05-19 10:29:49 +0200441 SET_BINARY_MODE(stdout);
Yann Collet459a6b72016-02-15 20:37:23 +0100442 for (u=0; u<nbFiles; u++)
Yann Collet43eeea42016-09-15 15:38:44 +0200443 missed_files += FIO_compressFilename_srcFile(ress, stdoutmark, inFileNamesTable[u]);
Przemyslaw Skibinski26306fc2016-11-03 11:38:01 +0100444 if (fclose(ress.dstFile)) EXM_THROW(29, "Write error : cannot properly close stdout");
Yann Collet459a6b72016-02-15 20:37:23 +0100445 } else {
Yann Colletf8494622016-05-07 22:43:40 +0200446 unsigned u;
Yann Colletf0624362016-02-12 15:56:46 +0100447 for (u=0; u<nbFiles; u++) {
448 size_t ifnSize = strlen(inFileNamesTable[u]);
449 if (dfnSize <= ifnSize+suffixSize+1) { free(dstFileName); dfnSize = ifnSize + 20; dstFileName = (char*)malloc(dfnSize); }
450 strcpy(dstFileName, inFileNamesTable[u]);
451 strcat(dstFileName, suffix);
Yann Collet43eeea42016-09-15 15:38:44 +0200452 missed_files += FIO_compressFilename_dstFile(ress, dstFileName, inFileNamesTable[u]);
Yann Collet459a6b72016-02-15 20:37:23 +0100453 } }
Yann Collet4f137032015-12-17 02:23:58 +0100454
455 /* Close & Free */
456 FIO_freeCResources(ress);
457 free(dstFileName);
458
459 return missed_files;
460}
461
Yann Colletf8494622016-05-07 22:43:40 +0200462#endif /* #ifndef ZSTD_NOCOMPRESS */
inikep3c7c3522016-04-22 13:59:05 +0200463
Yann Collet4f137032015-12-17 02:23:58 +0100464
inikepdb396432016-04-22 18:22:30 +0200465
466#ifndef ZSTD_NODECOMPRESS
467
Yann Collet4f137032015-12-17 02:23:58 +0100468/* **************************************************************************
469* Decompression
470****************************************************************************/
Yann Colletdeb078b2015-12-17 20:30:14 +0100471typedef struct {
472 void* srcBuffer;
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100473 size_t srcBufferLoaded;
Yann Colletdeb078b2015-12-17 20:30:14 +0100474 size_t srcBufferSize;
475 void* dstBuffer;
476 size_t dstBufferSize;
Yann Collet6263ba52016-08-13 23:45:45 +0200477 ZSTD_DStream* dctx;
Yann Collet1f1f2392016-02-12 18:33:26 +0100478 FILE* dstFile;
Yann Colletdeb078b2015-12-17 20:30:14 +0100479} dRess_t;
480
481static dRess_t FIO_createDResources(const char* dictFileName)
482{
483 dRess_t ress;
Yann Collet5e80dd32016-07-13 17:38:39 +0200484 memset(&ress, 0, sizeof(ress));
Yann Colletdeb078b2015-12-17 20:30:14 +0100485
Yann Collet5e80dd32016-07-13 17:38:39 +0200486 /* Allocation */
Yann Collet6263ba52016-08-13 23:45:45 +0200487 ress.dctx = ZSTD_createDStream();
488 if (ress.dctx==NULL) EXM_THROW(60, "Can't create ZSTD_DStream");
Yann Colletd4cda272016-10-14 13:13:13 -0700489 ZSTD_setDStreamParameter(ress.dctx, ZSTDdsp_maxWindowSize, g_memLimit);
Yann Collet6263ba52016-08-13 23:45:45 +0200490 ress.srcBufferSize = ZSTD_DStreamInSize();
Yann Colletdeb078b2015-12-17 20:30:14 +0100491 ress.srcBuffer = malloc(ress.srcBufferSize);
Yann Collet6263ba52016-08-13 23:45:45 +0200492 ress.dstBufferSize = ZSTD_DStreamOutSize();
Yann Colletdeb078b2015-12-17 20:30:14 +0100493 ress.dstBuffer = malloc(ress.dstBufferSize);
494 if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(61, "Allocation error : not enough memory");
495
496 /* dictionary */
Yann Collet3ecbe6a2016-09-14 17:26:59 +0200497 { void* dictBuffer;
498 size_t const dictBufferSize = FIO_loadFile(&dictBuffer, dictFileName);
499 size_t const initError = ZSTD_initDStream_usingDict(ress.dctx, dictBuffer, dictBufferSize);
500 if (ZSTD_isError(initError)) EXM_THROW(61, "ZSTD_initDStream_usingDict error : %s", ZSTD_getErrorName(initError));
501 free(dictBuffer);
502 }
Yann Colletdeb078b2015-12-17 20:30:14 +0100503
504 return ress;
505}
506
507static void FIO_freeDResources(dRess_t ress)
508{
Yann Collet6263ba52016-08-13 23:45:45 +0200509 size_t const errorCode = ZSTD_freeDStream(ress.dctx);
510 if (ZSTD_isError(errorCode)) EXM_THROW(69, "Error : can't free ZSTD_DStream context resource : %s", ZSTD_getErrorName(errorCode));
Yann Colletdeb078b2015-12-17 20:30:14 +0100511 free(ress.srcBuffer);
512 free(ress.dstBuffer);
Yann Colletdeb078b2015-12-17 20:30:14 +0100513}
Yann Collet4f137032015-12-17 02:23:58 +0100514
515
Yann Collet75424d12016-05-23 16:56:56 +0200516/** FIO_fwriteSparse() :
517* @return : storedSkips, to be provided to next call to FIO_fwriteSparse() of LZ4IO_fwriteSparseEnd() */
518static unsigned FIO_fwriteSparse(FILE* file, const void* buffer, size_t bufferSize, unsigned storedSkips)
519{
520 const size_t* const bufferT = (const size_t*)buffer; /* Buffer is supposed malloc'ed, hence aligned on size_t */
521 size_t bufferSizeT = bufferSize / sizeof(size_t);
522 const size_t* const bufferTEnd = bufferT + bufferSizeT;
523 const size_t* ptrT = bufferT;
524 static const size_t segmentSizeT = (32 KB) / sizeof(size_t); /* 0-test re-attempted every 32 KB */
525
526 if (!g_sparseFileSupport) { /* normal write */
527 size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file);
528 if (sizeCheck != bufferSize) EXM_THROW(70, "Write error : cannot write decoded block");
529 return 0;
530 }
531
532 /* avoid int overflow */
533 if (storedSkips > 1 GB) {
534 int const seekResult = fseek(file, 1 GB, SEEK_CUR);
535 if (seekResult != 0) EXM_THROW(71, "1 GB skip error (sparse file support)");
536 storedSkips -= 1 GB;
537 }
538
539 while (ptrT < bufferTEnd) {
540 size_t seg0SizeT = segmentSizeT;
541 size_t nb0T;
542
543 /* count leading zeros */
544 if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT;
545 bufferSizeT -= seg0SizeT;
546 for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ;
547 storedSkips += (unsigned)(nb0T * sizeof(size_t));
548
549 if (nb0T != seg0SizeT) { /* not all 0s */
550 int const seekResult = fseek(file, storedSkips, SEEK_CUR);
551 if (seekResult) EXM_THROW(72, "Sparse skip error ; try --no-sparse");
552 storedSkips = 0;
553 seg0SizeT -= nb0T;
554 ptrT += nb0T;
555 { size_t const sizeCheck = fwrite(ptrT, sizeof(size_t), seg0SizeT, file);
556 if (sizeCheck != seg0SizeT) EXM_THROW(73, "Write error : cannot write decoded block");
557 } }
558 ptrT += seg0SizeT;
559 }
560
561 { static size_t const maskT = sizeof(size_t)-1;
562 if (bufferSize & maskT) { /* size not multiple of sizeof(size_t) : implies end of block */
563 const char* const restStart = (const char*)bufferTEnd;
564 const char* restPtr = restStart;
565 size_t restSize = bufferSize & maskT;
566 const char* const restEnd = restStart + restSize;
567 for ( ; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ;
568 storedSkips += (unsigned) (restPtr - restStart);
569 if (restPtr != restEnd) {
570 int seekResult = fseek(file, storedSkips, SEEK_CUR);
571 if (seekResult) EXM_THROW(74, "Sparse skip error ; try --no-sparse");
572 storedSkips = 0;
573 { size_t const sizeCheck = fwrite(restPtr, 1, restEnd - restPtr, file);
574 if (sizeCheck != (size_t)(restEnd - restPtr)) EXM_THROW(75, "Write error : cannot write decoded end of block");
575 } } } }
576
577 return storedSkips;
578}
579
580static void FIO_fwriteSparseEnd(FILE* file, unsigned storedSkips)
581{
582 if (storedSkips-->0) { /* implies g_sparseFileSupport>0 */
583 int const seekResult = fseek(file, storedSkips, SEEK_CUR);
584 if (seekResult != 0) EXM_THROW(69, "Final skip error (sparse file)\n");
585 { const char lastZeroByte[1] = { 0 };
586 size_t const sizeCheck = fwrite(lastZeroByte, 1, 1, file);
587 if (sizeCheck != 1) EXM_THROW(69, "Write error : cannot write last zero\n");
588 } }
589}
590
Yann Colletbe50aaa2015-09-10 23:26:09 +0100591
Yann Colletde95f962016-05-23 19:46:47 +0200592/** FIO_passThrough() : just copy input into output, for compatibility with gzip -df mode
593 @return : 0 (no error) */
Przemyslaw Skibinski7c6bbc32016-12-05 18:31:14 +0100594static unsigned FIO_passThrough(FILE* foutput, FILE* finput, void* buffer, size_t bufferSize, size_t alreadyLoaded)
Yann Colletde95f962016-05-23 19:46:47 +0200595{
Yann Collet179b1972016-11-02 17:30:49 -0700596 size_t const blockSize = MIN(64 KB, bufferSize);
Yann Colletddbb8e22016-05-24 00:52:14 +0200597 size_t readFromInput = 1;
Yann Colletde95f962016-05-23 19:46:47 +0200598 unsigned storedSkips = 0;
599
Przemyslaw Skibinski7c6bbc32016-12-05 18:31:14 +0100600 /* assumption : ress->srcBufferLoaded bytes already loaded and stored within buffer */
601 { size_t const sizeCheck = fwrite(buffer, 1, alreadyLoaded, foutput);
602 if (sizeCheck != alreadyLoaded) EXM_THROW(50, "Pass-through write error"); }
Yann Colletde95f962016-05-23 19:46:47 +0200603
Yann Colletddbb8e22016-05-24 00:52:14 +0200604 while (readFromInput) {
605 readFromInput = fread(buffer, 1, blockSize, finput);
606 storedSkips = FIO_fwriteSparse(foutput, buffer, readFromInput, storedSkips);
Yann Colletde95f962016-05-23 19:46:47 +0200607 }
608
609 FIO_fwriteSparseEnd(foutput, storedSkips);
610 return 0;
611}
612
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100613
614/** FIO_decompressFrame() :
615 @return : size of decoded frame
616*/
617unsigned long long FIO_decompressFrame(dRess_t* ress,
618 FILE* finput,
619 U64 alreadyDecoded)
620{
621 U64 frameSize = 0;
622 U32 storedSkips = 0;
623
624 ZSTD_resetDStream(ress->dctx);
625
626 /* Header loading (optional, saves one loop) */
627 { size_t const toRead = 9;
628 if (ress->srcBufferLoaded < toRead)
629 ress->srcBufferLoaded += fread(((char*)ress->srcBuffer) + ress->srcBufferLoaded, 1, toRead - ress->srcBufferLoaded, finput);
630 }
631
632 /* Main decompression Loop */
633 while (1) {
634 ZSTD_inBuffer inBuff = { ress->srcBuffer, ress->srcBufferLoaded, 0 };
635 ZSTD_outBuffer outBuff= { ress->dstBuffer, ress->dstBufferSize, 0 };
636 size_t const readSizeHint = ZSTD_decompressStream(ress->dctx, &outBuff, &inBuff);
637 if (ZSTD_isError(readSizeHint)) EXM_THROW(36, "Decoding error : %s", ZSTD_getErrorName(readSizeHint));
638
639 /* Write block */
Przemyslaw Skibinski6b508b12016-12-05 18:02:40 +0100640 storedSkips = FIO_fwriteSparse(ress->dstFile, ress->dstBuffer, outBuff.pos, storedSkips);
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100641 frameSize += outBuff.pos;
642 DISPLAYUPDATE(2, "\rDecoded : %u MB... ", (U32)((alreadyDecoded+frameSize)>>20) );
643
644 if (inBuff.pos > 0) {
645 memmove(ress->srcBuffer, (char*)ress->srcBuffer + inBuff.pos, inBuff.size - inBuff.pos);
646 ress->srcBufferLoaded -= inBuff.pos;
647 }
648
649 if (readSizeHint == 0) break; /* end of frame */
650 if (inBuff.size != inBuff.pos) EXM_THROW(37, "Decoding error : should consume entire input");
651
652 /* Fill input buffer */
653 { size_t const toRead = MIN(readSizeHint, ress->srcBufferSize); /* support large skippable frames */
654 if (ress->srcBufferLoaded < toRead)
655 ress->srcBufferLoaded += fread(((char*)ress->srcBuffer) + ress->srcBufferLoaded, 1, toRead - ress->srcBufferLoaded, finput);
656 if (ress->srcBufferLoaded < toRead) EXM_THROW(39, "Read error : premature end");
657 } }
658
659 FIO_fwriteSparseEnd(ress->dstFile, storedSkips);
660
661 return frameSize;
662}
663
664
Przemyslaw Skibinski19aad422016-12-01 11:56:31 +0100665#ifdef ZSTD_GZDECOMPRESS
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100666static unsigned long long FIO_decompressGzFrame(dRess_t* ress, FILE* srcFile, const char* srcFileName)
Przemyslaw Skibinskib0f2ef22016-12-02 13:50:29 +0100667{
Yann Collet5bd42372016-12-02 12:40:57 -0800668 unsigned long long outFileSize = 0;
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100669 z_stream strm;
Yann Collet5bd42372016-12-02 12:40:57 -0800670
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100671 strm.zalloc = Z_NULL;
672 strm.zfree = Z_NULL;
673 strm.opaque = Z_NULL;
674 strm.next_in = 0;
675 strm.avail_in = Z_NULL;
Yann Collet5bd42372016-12-02 12:40:57 -0800676 if (inflateInit2(&strm, 15 /* maxWindowLogSize */ + 16 /* gzip only */) != Z_OK) return 0; /* see http://www.zlib.net/manual.html */
677
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100678 strm.next_out = ress->dstBuffer;
679 strm.avail_out = ress->dstBufferSize;
680 strm.avail_in = ress->srcBufferLoaded;
681 strm.next_in = (z_const unsigned char*)ress->srcBuffer;
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100682
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100683 for ( ; ; ) {
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100684 int ret;
685 if (strm.avail_in == 0) {
686 ress->srcBufferLoaded = fread(ress->srcBuffer, 1, ress->srcBufferSize, srcFile);
687 if (ress->srcBufferLoaded == 0) break;
688 strm.next_in = (z_const unsigned char*)ress->srcBuffer;
689 strm.avail_in = ress->srcBufferLoaded;
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100690 }
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100691 ret = inflate(&strm, Z_NO_FLUSH);
692 if (ret != Z_OK && ret != Z_STREAM_END) { DISPLAY("zstd: %s: inflate error %d \n", srcFileName, ret); return 0; }
693 { size_t const decompBytes = ress->dstBufferSize - strm.avail_out;
Yann Collet5bd42372016-12-02 12:40:57 -0800694 if (decompBytes) {
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100695 if (fwrite(ress->dstBuffer, 1, decompBytes, ress->dstFile) != decompBytes) EXM_THROW(31, "Write error : cannot write to output file");
Yann Collet5bd42372016-12-02 12:40:57 -0800696 outFileSize += decompBytes;
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100697 strm.next_out = ress->dstBuffer;
698 strm.avail_out = ress->dstBufferSize;
699 }
700 }
701 if (ret == Z_STREAM_END) break;
702 }
Przemyslaw Skibinski19aad422016-12-01 11:56:31 +0100703
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100704 if (strm.avail_in > 0) memmove(ress->srcBuffer, strm.next_in, strm.avail_in);
705 ress->srcBufferLoaded = strm.avail_in;
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100706 inflateEnd(&strm);
707 return outFileSize;
Przemyslaw Skibinski19aad422016-12-01 11:56:31 +0100708}
709#endif
710
711
Yann Collet1f1f2392016-02-12 18:33:26 +0100712/** FIO_decompressSrcFile() :
713 Decompression `srcFileName` into `ress.dstFile`
714 @return : 0 : OK
715 1 : operation not started
716*/
Yann Collet743b33f2016-12-02 15:18:57 -0800717static int FIO_decompressSrcFile(dRess_t ress, const char* dstFileName, const char* srcFileName)
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100718{
Przemyslaw Skibinskib0f2ef22016-12-02 13:50:29 +0100719 FILE* srcFile;
Yann Colleta1dd6b92016-07-26 16:44:09 +0200720 unsigned readSomething = 0;
Yann Collet5bd42372016-12-02 12:40:57 -0800721 unsigned long long filesize = 0;
Przemyslaw Skibinski0e146752016-11-30 13:34:21 +0100722
Yann Colletb09b12c2016-06-09 22:59:51 +0200723 if (UTIL_isDirectory(srcFileName)) {
724 DISPLAYLEVEL(1, "zstd: %s is a directory -- ignored \n", srcFileName);
725 return 1;
726 }
Przemyslaw Skibinski64fa2db2017-01-25 13:02:33 +0100727 if (!UTIL_doesFileExists(srcFileName)) {
728 DISPLAYLEVEL(1, "zstd: %s is not a regular file -- ignored \n", srcFileName);
729 return 1;
730 }
Przemyslaw Skibinski0e146752016-11-30 13:34:21 +0100731
Przemyslaw Skibinskib0f2ef22016-12-02 13:50:29 +0100732 srcFile = FIO_openSrcFile(srcFileName);
733 if (srcFile==0) return 1;
Yann Collet88fcd292015-11-25 14:42:45 +0100734
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100735 /* for each frame */
736 for ( ; ; ) {
737 /* check magic number -> version */
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100738 size_t const toRead = 4;
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100739 const BYTE* buf = (const BYTE*)ress.srcBuffer;
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100740 if (ress.srcBufferLoaded < toRead)
741 ress.srcBufferLoaded += fread((char*)ress.srcBuffer + ress.srcBufferLoaded, (size_t)1, toRead - ress.srcBufferLoaded, srcFile);
742 if (ress.srcBufferLoaded==0) {
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100743 if (readSomething==0) { DISPLAY("zstd: %s: unexpected end of file \n", srcFileName); fclose(srcFile); return 1; } /* srcFileName is empty */
744 break; /* no more input */
745 }
746 readSomething = 1; /* there is at least >= 4 bytes in srcFile */
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100747 if (ress.srcBufferLoaded < toRead) { DISPLAY("zstd: %s: unknown header \n", srcFileName); fclose(srcFile); return 1; } /* srcFileName is empty */
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100748 if (buf[0] == 31 && buf[1] == 139) { /* gz header */
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100749#ifdef ZSTD_GZDECOMPRESS
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100750 unsigned long long const result = FIO_decompressGzFrame(&ress, srcFile, srcFileName);
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100751 if (result == 0) return 1;
752 filesize += result;
Przemyslaw Skibinskiabfb51f2016-11-30 15:05:54 +0100753#else
Yann Collet5bd42372016-12-02 12:40:57 -0800754 DISPLAYLEVEL(1, "zstd: %s: gzip file cannot be uncompressed (zstd compiled without ZSTD_GZDECOMPRESS) -- ignored \n", srcFileName);
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100755 return 1;
Przemyslaw Skibinskiabfb51f2016-11-30 15:05:54 +0100756#endif
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100757 } else {
758 if (!ZSTD_isFrame(ress.srcBuffer, toRead)) {
Yann Collet743b33f2016-12-02 15:18:57 -0800759 if ((g_overwrite) && !strcmp (dstFileName, stdoutmark)) { /* pass-through mode */
Przemyslaw Skibinski7c6bbc32016-12-05 18:31:14 +0100760 unsigned const result = FIO_passThrough(ress.dstFile, srcFile, ress.srcBuffer, ress.srcBufferSize, ress.srcBufferLoaded);
Przemyslaw Skibinski690753e2016-12-02 16:20:16 +0100761 if (fclose(srcFile)) EXM_THROW(32, "zstd: %s close error", srcFileName); /* error should never happen */
762 return result;
763 } else {
764 DISPLAYLEVEL(1, "zstd: %s: not in zstd format \n", srcFileName);
765 fclose(srcFile);
766 return 1;
767 } }
Przemyslaw Skibinskib493e3b2016-12-05 17:39:38 +0100768 filesize += FIO_decompressFrame(&ress, srcFile, filesize);
Przemyslaw Skibinskic5eebca2016-12-02 15:01:31 +0100769 }
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100770 }
771
Yann Colletdeb078b2015-12-17 20:30:14 +0100772 /* Final Status */
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100773 DISPLAYLEVEL(2, "\r%79s\r", "");
Yann Collet1c69baa2016-08-28 12:47:17 -0700774 DISPLAYLEVEL(2, "%-20s: %llu bytes \n", srcFileName, filesize);
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100775
Przemyslaw Skibinskib0f2ef22016-12-02 13:50:29 +0100776 /* Close file */
777 if (fclose(srcFile)) EXM_THROW(33, "zstd: %s close error", srcFileName); /* error should never happen */
778 if (g_removeSrcFile) { if (remove(srcFileName)) EXM_THROW(34, "zstd: %s: %s", srcFileName, strerror(errno)); };
Yann Collet1f1f2392016-02-12 18:33:26 +0100779 return 0;
780}
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100781
Yann Collet1f1f2392016-02-12 18:33:26 +0100782
783/** FIO_decompressFile_extRess() :
784 decompress `srcFileName` into `dstFileName`
785 @return : 0 : OK
786 1 : operation aborted (src not available, dst already taken, etc.)
787*/
Yann Colletb09b12c2016-06-09 22:59:51 +0200788static int FIO_decompressDstFile(dRess_t ress,
Yann Collet5bd42372016-12-02 12:40:57 -0800789 const char* dstFileName, const char* srcFileName)
Yann Collet1f1f2392016-02-12 18:33:26 +0100790{
Chip Turner6de382c2016-03-13 22:24:46 -0700791 int result;
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100792 stat_t statbuf;
793 int stat_result = 0;
Przemyslaw Skibinskia42794d2016-11-02 13:08:39 +0100794
Yann Collet1f1f2392016-02-12 18:33:26 +0100795 ress.dstFile = FIO_openDstFile(dstFileName);
796 if (ress.dstFile==0) return 1;
797
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100798 if (strcmp (srcFileName, stdinmark) && UTIL_getFileStat(srcFileName, &statbuf)) stat_result = 1;
Yann Collet743b33f2016-12-02 15:18:57 -0800799 result = FIO_decompressSrcFile(ress, dstFileName, srcFileName);
Yann Collet1f1f2392016-02-12 18:33:26 +0100800
Yann Collet0018ca22016-11-07 14:41:21 -0800801 if (fclose(ress.dstFile)) EXM_THROW(38, "Write error : cannot properly close %s", dstFileName);
Przemyslaw Skibinskia42794d2016-11-02 13:08:39 +0100802
Yann Colletaad9fe52016-09-07 07:00:08 +0200803 if ( (result != 0)
804 && strcmp(dstFileName, nulmark) /* special case : don't remove() /dev/null (#316) */
805 && remove(dstFileName) )
Yann Collet03d3f232016-09-07 07:01:33 +0200806 result=1; /* don't do anything special if remove() fails */
Przemyslaw Skibinskifcf22e32016-11-02 14:08:07 +0100807 else if (strcmp (dstFileName, stdoutmark) && stat_result) UTIL_setFileStat(dstFileName, &statbuf);
Chip Turner6de382c2016-03-13 22:24:46 -0700808 return result;
Yann Colletb1f3f4b2015-10-18 22:18:32 +0100809}
810
811
Yann Colletdeb078b2015-12-17 20:30:14 +0100812int FIO_decompressFilename(const char* dstFileName, const char* srcFileName,
813 const char* dictFileName)
814{
815 int missingFiles = 0;
816 dRess_t ress = FIO_createDResources(dictFileName);
817
Yann Colletb09b12c2016-06-09 22:59:51 +0200818 missingFiles += FIO_decompressDstFile(ress, dstFileName, srcFileName);
Yann Colletdeb078b2015-12-17 20:30:14 +0100819
820 FIO_freeDResources(ress);
821 return missingFiles;
822}
823
824
825#define MAXSUFFIXSIZE 8
826int FIO_decompressMultipleFilenames(const char** srcNamesTable, unsigned nbFiles,
827 const char* suffix,
828 const char* dictFileName)
829{
Yann Colletdeb078b2015-12-17 20:30:14 +0100830 int skippedFiles = 0;
831 int missingFiles = 0;
Yann Collet8b23eea2016-05-10 05:37:43 +0200832 dRess_t ress = FIO_createDResources(dictFileName);
Yann Colletdeb078b2015-12-17 20:30:14 +0100833
Yann Collet44f684d2016-07-13 19:30:40 +0200834 if (suffix==NULL) EXM_THROW(70, "zstd: decompression: unknown dst"); /* should never happen */
835
Yann Collet743b33f2016-12-02 15:18:57 -0800836 if (!strcmp(suffix, stdoutmark) || !strcmp(suffix, nulmark)) { /* special cases : -c or -t */
Yann Colletf8494622016-05-07 22:43:40 +0200837 unsigned u;
Yann Colletaccfd802016-02-15 19:33:16 +0100838 ress.dstFile = FIO_openDstFile(suffix);
839 if (ress.dstFile == 0) EXM_THROW(71, "cannot open %s", suffix);
840 for (u=0; u<nbFiles; u++)
Yann Collet743b33f2016-12-02 15:18:57 -0800841 missingFiles += FIO_decompressSrcFile(ress, suffix, srcNamesTable[u]);
Przemyslaw Skibinski26306fc2016-11-03 11:38:01 +0100842 if (fclose(ress.dstFile)) EXM_THROW(72, "Write error : cannot properly close stdout");
Yann Colletaccfd802016-02-15 19:33:16 +0100843 } else {
Yann Collet44f684d2016-07-13 19:30:40 +0200844 size_t const suffixSize = strlen(suffix);
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100845 size_t const gzipSuffixSize = strlen(GZ_EXTENSION);
Yann Collet8b23eea2016-05-10 05:37:43 +0200846 size_t dfnSize = FNSPACE;
Yann Colletf8494622016-05-07 22:43:40 +0200847 unsigned u;
Yann Collet8b23eea2016-05-10 05:37:43 +0200848 char* dstFileName = (char*)malloc(FNSPACE);
Yann Collet44f684d2016-07-13 19:30:40 +0200849 if (dstFileName==NULL) EXM_THROW(73, "not enough memory for dstFileName");
Yann Collet1f1f2392016-02-12 18:33:26 +0100850 for (u=0; u<nbFiles; u++) { /* create dstFileName */
Yann Collet8b23eea2016-05-10 05:37:43 +0200851 const char* const srcFileName = srcNamesTable[u];
852 size_t const sfnSize = strlen(srcFileName);
853 const char* const suffixPtr = srcFileName + sfnSize - suffixSize;
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100854 const char* const gzipSuffixPtr = srcFileName + sfnSize - gzipSuffixSize;
Yann Colletaccfd802016-02-15 19:33:16 +0100855 if (dfnSize+suffixSize <= sfnSize+1) {
856 free(dstFileName);
857 dfnSize = sfnSize + 20;
858 dstFileName = (char*)malloc(dfnSize);
Yann Collet44f684d2016-07-13 19:30:40 +0200859 if (dstFileName==NULL) EXM_THROW(74, "not enough memory for dstFileName");
Yann Colletaccfd802016-02-15 19:33:16 +0100860 }
861 if (sfnSize <= suffixSize || strcmp(suffixPtr, suffix) != 0) {
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100862 if (sfnSize <= gzipSuffixSize || strcmp(gzipSuffixPtr, GZ_EXTENSION) != 0) {
Przemyslaw Skibinski8489f182016-12-05 13:47:00 +0100863 DISPLAYLEVEL(1, "zstd: %s: unknown suffix (%s/%s expected) -- ignored \n", srcFileName, suffix, GZ_EXTENSION);
Przemyslaw Skibinski0e146752016-11-30 13:34:21 +0100864 skippedFiles++;
865 continue;
866 } else {
Przemyslaw Skibinski4b504f12016-12-02 13:11:39 +0100867 memcpy(dstFileName, srcFileName, sfnSize - gzipSuffixSize);
868 dstFileName[sfnSize-gzipSuffixSize] = '\0';
Przemyslaw Skibinski0e146752016-11-30 13:34:21 +0100869 }
870 } else {
871 memcpy(dstFileName, srcFileName, sfnSize - suffixSize);
872 dstFileName[sfnSize-suffixSize] = '\0';
Yann Collet1f1f2392016-02-12 18:33:26 +0100873 }
Yann Colletdeb078b2015-12-17 20:30:14 +0100874
Yann Colletb09b12c2016-06-09 22:59:51 +0200875 missingFiles += FIO_decompressDstFile(ress, dstFileName, srcFileName);
Yann Collet8b23eea2016-05-10 05:37:43 +0200876 }
877 free(dstFileName);
878 }
Yann Colletdeb078b2015-12-17 20:30:14 +0100879
880 FIO_freeDResources(ress);
Yann Colletdeb078b2015-12-17 20:30:14 +0100881 return missingFiles + skippedFiles;
882}
Yann Colletaccfd802016-02-15 19:33:16 +0100883
Yann Collet8b23eea2016-05-10 05:37:43 +0200884#endif /* #ifndef ZSTD_NODECOMPRESS */