• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2   LZ4io.c - LZ4 File/Stream Interface
3   Copyright (C) Yann Collet 2011-2017
4 
5   GPL v2 License
6 
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2 of the License, or
10   (at your option) any later version.
11 
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16 
17   You should have received a copy of the GNU General Public License along
18   with this program; if not, write to the Free Software Foundation, Inc.,
19   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 
21   You can contact the author at :
22   - LZ4 source repository : https://github.com/lz4/lz4
23   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
24 */
25 /*
26   Note : this is stand-alone program.
27   It is not part of LZ4 compression library, it is a user code of the LZ4 library.
28   - The license of LZ4 library is BSD.
29   - The license of xxHash library is BSD.
30   - The license of this source file is GPLv2.
31 */
32 
33 
34 /*-************************************
35 *  Compiler options
36 **************************************/
37 #ifdef _MSC_VER    /* Visual Studio */
38 #  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
39 #endif
40 #if defined(__MINGW32__) && !defined(_POSIX_SOURCE)
41 #  define _POSIX_SOURCE 1          /* disable %llu warnings with MinGW on Windows */
42 #endif
43 
44 
45 /*****************************
46 *  Includes
47 *****************************/
48 #include "platform.h"  /* Large File Support, SET_BINARY_MODE, SET_SPARSE_FILE_MODE, PLATFORM_POSIX_VERSION, __64BIT__ */
49 #include "util.h"      /* UTIL_getFileStat, UTIL_setFileStat */
50 #include <stdio.h>     /* fprintf, fopen, fread, stdin, stdout, fflush, getchar */
51 #include <stdlib.h>    /* malloc, free */
52 #include <string.h>    /* strerror, strcmp, strlen */
53 #include <time.h>      /* clock */
54 #include <sys/types.h> /* stat64 */
55 #include <sys/stat.h>  /* stat64 */
56 #include "lz4io.h"
57 #include "lz4.h"       /* still required for legacy format */
58 #include "lz4hc.h"     /* still required for legacy format */
59 #define LZ4F_STATIC_LINKING_ONLY
60 #include "lz4frame.h"
61 
62 
63 /*****************************
64 *  Constants
65 *****************************/
66 #define KB *(1 <<10)
67 #define MB *(1 <<20)
68 #define GB *(1U<<30)
69 
70 #define _1BIT  0x01
71 #define _2BITS 0x03
72 #define _3BITS 0x07
73 #define _4BITS 0x0F
74 #define _8BITS 0xFF
75 
76 #define MAGICNUMBER_SIZE    4
77 #define LZ4IO_MAGICNUMBER   0x184D2204
78 #define LZ4IO_SKIPPABLE0    0x184D2A50
79 #define LZ4IO_SKIPPABLEMASK 0xFFFFFFF0
80 #define LEGACY_MAGICNUMBER  0x184C2102
81 
82 #define CACHELINE 64
83 #define LEGACY_BLOCKSIZE   (8 MB)
84 #define MIN_STREAM_BUFSIZE (192 KB)
85 #define LZ4IO_BLOCKSIZEID_DEFAULT 7
86 #define LZ4_MAX_DICT_SIZE (64 KB)
87 
88 
89 /**************************************
90 *  Macros
91 **************************************/
92 #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
93 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
94 static int g_displayLevel = 0;   /* 0 : no display  ; 1: errors  ; 2 : + result + interaction + warnings ; 3 : + progression; 4 : + information */
95 
96 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
97             if ( ((clock() - g_time) > refreshRate)    \
98               || (g_displayLevel>=4) ) {               \
99                 g_time = clock();                      \
100                 DISPLAY(__VA_ARGS__);                  \
101                 if (g_displayLevel>=4) fflush(stderr); \
102         }   }
103 static const clock_t refreshRate = CLOCKS_PER_SEC / 6;
104 static clock_t g_time = 0;
105 
106 
107 /**************************************
108 *  Local Parameters
109 **************************************/
110 static int g_overwrite = 1;
111 static int g_testMode = 0;
112 static int g_blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT;
113 static int g_blockChecksum = 0;
114 static int g_streamChecksum = 1;
115 static int g_blockIndependence = 1;
116 static int g_sparseFileSupport = 1;
117 static int g_contentSizeFlag = 0;
118 static int g_useDictionary = 0;
119 static unsigned g_favorDecSpeed = 0;
120 static const char* g_dictionaryFilename = NULL;
121 
122 
123 /**************************************
124 *  Exceptions
125 ***************************************/
126 #ifndef DEBUG
127 #  define DEBUG 0
128 #endif
129 #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
130 #define EXM_THROW(error, ...)                                             \
131 {                                                                         \
132     DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
133     DISPLAYLEVEL(1, "Error %i : ", error);                                \
134     DISPLAYLEVEL(1, __VA_ARGS__);                                         \
135     DISPLAYLEVEL(1, " \n");                                               \
136     exit(error);                                                          \
137 }
138 
139 
140 /**************************************
141 *  Version modifiers
142 **************************************/
143 #define EXTENDED_ARGUMENTS
144 #define EXTENDED_HELP
145 #define EXTENDED_FORMAT
146 #define DEFAULT_DECOMPRESSOR LZ4IO_decompressLZ4F
147 
148 
149 /* ************************************************** */
150 /* ****************** Parameters ******************** */
151 /* ************************************************** */
152 
LZ4IO_setDictionaryFilename(const char * dictionaryFilename)153 int LZ4IO_setDictionaryFilename(const char* dictionaryFilename) {
154     g_dictionaryFilename = dictionaryFilename;
155     g_useDictionary = dictionaryFilename != NULL;
156     return g_useDictionary;
157 }
158 
159 /* Default setting : overwrite = 1; return : overwrite mode (0/1) */
LZ4IO_setOverwrite(int yes)160 int LZ4IO_setOverwrite(int yes)
161 {
162    g_overwrite = (yes!=0);
163    return g_overwrite;
164 }
165 
166 /* Default setting : testMode = 0; return : testMode (0/1) */
LZ4IO_setTestMode(int yes)167 int LZ4IO_setTestMode(int yes)
168 {
169    g_testMode = (yes!=0);
170    return g_testMode;
171 }
172 
173 /* blockSizeID : valid values : 4-5-6-7 */
LZ4IO_setBlockSizeID(unsigned bsid)174 size_t LZ4IO_setBlockSizeID(unsigned bsid)
175 {
176     static const size_t blockSizeTable[] = { 64 KB, 256 KB, 1 MB, 4 MB };
177     static const unsigned minBlockSizeID = 4;
178     static const unsigned maxBlockSizeID = 7;
179     if ((bsid < minBlockSizeID) || (bsid > maxBlockSizeID)) return 0;
180     g_blockSizeId = bsid;
181     return blockSizeTable[g_blockSizeId-minBlockSizeID];
182 }
183 
LZ4IO_setBlockMode(LZ4IO_blockMode_t blockMode)184 int LZ4IO_setBlockMode(LZ4IO_blockMode_t blockMode)
185 {
186     g_blockIndependence = (blockMode == LZ4IO_blockIndependent);
187     return g_blockIndependence;
188 }
189 
190 /* Default setting : no block checksum */
LZ4IO_setBlockChecksumMode(int enable)191 int LZ4IO_setBlockChecksumMode(int enable)
192 {
193     g_blockChecksum = (enable != 0);
194     return g_blockChecksum;
195 }
196 
197 /* Default setting : checksum enabled */
LZ4IO_setStreamChecksumMode(int enable)198 int LZ4IO_setStreamChecksumMode(int enable)
199 {
200     g_streamChecksum = (enable != 0);
201     return g_streamChecksum;
202 }
203 
204 /* Default setting : 0 (no notification) */
LZ4IO_setNotificationLevel(int level)205 int LZ4IO_setNotificationLevel(int level)
206 {
207     g_displayLevel = level;
208     return g_displayLevel;
209 }
210 
211 /* Default setting : 0 (disabled) */
LZ4IO_setSparseFile(int enable)212 int LZ4IO_setSparseFile(int enable)
213 {
214     g_sparseFileSupport = (enable!=0);
215     return g_sparseFileSupport;
216 }
217 
218 /* Default setting : 0 (disabled) */
LZ4IO_setContentSize(int enable)219 int LZ4IO_setContentSize(int enable)
220 {
221     g_contentSizeFlag = (enable!=0);
222     return g_contentSizeFlag;
223 }
224 
225 /* Default setting : 0 (disabled) */
LZ4IO_favorDecSpeed(int favor)226 void LZ4IO_favorDecSpeed(int favor)
227 {
228     g_favorDecSpeed = (favor!=0);
229 }
230 
231 static U32 g_removeSrcFile = 0;
LZ4IO_setRemoveSrcFile(unsigned flag)232 void LZ4IO_setRemoveSrcFile(unsigned flag) { g_removeSrcFile = (flag>0); }
233 
234 
235 
236 /* ************************************************************************ **
237 ** ********************** LZ4 File / Pipe compression ********************* **
238 ** ************************************************************************ */
239 
LZ4IO_GetBlockSize_FromBlockId(int id)240 static int LZ4IO_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); }
LZ4IO_isSkippableMagicNumber(unsigned int magic)241 static int LZ4IO_isSkippableMagicNumber(unsigned int magic) {
242     return (magic & LZ4IO_SKIPPABLEMASK) == LZ4IO_SKIPPABLE0;
243 }
244 
245 
246 /** LZ4IO_openSrcFile() :
247  * condition : `srcFileName` must be non-NULL.
248  * @result : FILE* to `dstFileName`, or NULL if it fails */
LZ4IO_openSrcFile(const char * srcFileName)249 static FILE* LZ4IO_openSrcFile(const char* srcFileName)
250 {
251     FILE* f;
252 
253     if (!strcmp (srcFileName, stdinmark)) {
254         DISPLAYLEVEL(4,"Using stdin for input\n");
255         f = stdin;
256         SET_BINARY_MODE(stdin);
257     } else {
258         f = fopen(srcFileName, "rb");
259         if ( f==NULL ) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno));
260     }
261 
262     return f;
263 }
264 
265 /** FIO_openDstFile() :
266  * condition : `dstFileName` must be non-NULL.
267  * @result : FILE* to `dstFileName`, or NULL if it fails */
LZ4IO_openDstFile(const char * dstFileName)268 static FILE* LZ4IO_openDstFile(const char* dstFileName)
269 {
270     FILE* f;
271 
272     if (!strcmp (dstFileName, stdoutmark)) {
273         DISPLAYLEVEL(4,"Using stdout for output\n");
274         f = stdout;
275         SET_BINARY_MODE(stdout);
276         if (g_sparseFileSupport==1) {
277             g_sparseFileSupport = 0;
278             DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n");
279         }
280     } else {
281         if (!g_overwrite && strcmp (dstFileName, nulmark)) {  /* Check if destination file already exists */
282             f = fopen( dstFileName, "rb" );
283             if (f != NULL) {  /* dest exists, prompt for overwrite authorization */
284                 fclose(f);
285                 if (g_displayLevel <= 1) {  /* No interaction possible */
286                     DISPLAY("%s already exists; not overwritten  \n", dstFileName);
287                     return NULL;
288                 }
289                 DISPLAY("%s already exists; do you wish to overwrite (y/N) ? ", dstFileName);
290                 {   int ch = getchar();
291                     if ((ch!='Y') && (ch!='y')) {
292                         DISPLAY("    not overwritten  \n");
293                         return NULL;
294                     }
295                     while ((ch!=EOF) && (ch!='\n')) ch = getchar();  /* flush rest of input line */
296         }   }   }
297         f = fopen( dstFileName, "wb" );
298         if (f==NULL) DISPLAYLEVEL(1, "%s: %s\n", dstFileName, strerror(errno));
299     }
300 
301     /* sparse file */
302     if (f && g_sparseFileSupport) { SET_SPARSE_FILE_MODE(f); }
303 
304     return f;
305 }
306 
307 
308 
309 /***************************************
310 *   Legacy Compression
311 ***************************************/
312 
313 /* unoptimized version; solves endianess & alignment issues */
LZ4IO_writeLE32(void * p,unsigned value32)314 static void LZ4IO_writeLE32 (void* p, unsigned value32)
315 {
316     unsigned char* const dstPtr = (unsigned char*)p;
317     dstPtr[0] = (unsigned char)value32;
318     dstPtr[1] = (unsigned char)(value32 >> 8);
319     dstPtr[2] = (unsigned char)(value32 >> 16);
320     dstPtr[3] = (unsigned char)(value32 >> 24);
321 }
322 
LZ4IO_LZ4_compress(const char * src,char * dst,int srcSize,int dstSize,int cLevel)323 static int LZ4IO_LZ4_compress(const char* src, char* dst, int srcSize, int dstSize, int cLevel)
324 {
325     (void)cLevel;
326     return LZ4_compress_fast(src, dst, srcSize, dstSize, 1);
327 }
328 
329 /* LZ4IO_compressFilename_Legacy :
330  * This function is intentionally "hidden" (not published in .h)
331  * It generates compressed streams using the old 'legacy' format */
LZ4IO_compressFilename_Legacy(const char * input_filename,const char * output_filename,int compressionlevel)332 int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename, int compressionlevel)
333 {
334     int (*compressionFunction)(const char* src, char* dst, int srcSize, int dstSize, int cLevel);
335     unsigned long long filesize = 0;
336     unsigned long long compressedfilesize = MAGICNUMBER_SIZE;
337     char* in_buff;
338     char* out_buff;
339     const int outBuffSize = LZ4_compressBound(LEGACY_BLOCKSIZE);
340     FILE* finput;
341     FILE* foutput;
342     clock_t clockEnd;
343 
344     /* Init */
345     clock_t const clockStart = clock();
346     compressionFunction = (compressionlevel < 3) ? LZ4IO_LZ4_compress : LZ4_compress_HC;
347 
348     finput = LZ4IO_openSrcFile(input_filename);
349     if (finput == NULL) EXM_THROW(20, "%s : open file error ", input_filename);
350     foutput = LZ4IO_openDstFile(output_filename);
351     if (foutput == NULL) { fclose(finput); EXM_THROW(20, "%s : open file error ", input_filename); }
352 
353     /* Allocate Memory */
354     in_buff = (char*)malloc(LEGACY_BLOCKSIZE);
355     out_buff = (char*)malloc(outBuffSize);
356     if (!in_buff || !out_buff) EXM_THROW(21, "Allocation error : not enough memory");
357 
358     /* Write Archive Header */
359     LZ4IO_writeLE32(out_buff, LEGACY_MAGICNUMBER);
360     { size_t const sizeCheck = fwrite(out_buff, 1, MAGICNUMBER_SIZE, foutput);
361       if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(22, "Write error : cannot write header"); }
362 
363     /* Main Loop */
364     while (1) {
365         unsigned int outSize;
366         /* Read Block */
367         size_t const inSize = (int) fread(in_buff, (size_t)1, (size_t)LEGACY_BLOCKSIZE, finput);
368         if (inSize == 0) break;
369         if (inSize > LEGACY_BLOCKSIZE) EXM_THROW(23, "Read error : wrong fread() size report ");   /* should be impossible */
370         filesize += inSize;
371 
372         /* Compress Block */
373         outSize = compressionFunction(in_buff, out_buff+4, (int)inSize, outBuffSize, compressionlevel);
374         compressedfilesize += outSize+4;
375         DISPLAYUPDATE(2, "\rRead : %i MB  ==> %.2f%%   ",
376                 (int)(filesize>>20), (double)compressedfilesize/filesize*100);
377 
378         /* Write Block */
379         LZ4IO_writeLE32(out_buff, outSize);
380         {   size_t const sizeCheck = fwrite(out_buff, 1, outSize+4, foutput);
381             if (sizeCheck!=(size_t)(outSize+4))
382                 EXM_THROW(24, "Write error : cannot write compressed block");
383     }   }
384     if (ferror(finput)) EXM_THROW(25, "Error while reading %s ", input_filename);
385 
386     /* Status */
387     clockEnd = clock();
388     if (clockEnd==clockStart) clockEnd+=1;  /* avoid division by zero (speed) */
389     filesize += !filesize;   /* avoid division by zero (ratio) */
390     DISPLAYLEVEL(2, "\r%79s\r", "");   /* blank line */
391     DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
392         filesize, compressedfilesize, (double)compressedfilesize / filesize * 100);
393     {   double const seconds = (double)(clockEnd - clockStart) / CLOCKS_PER_SEC;
394         DISPLAYLEVEL(4,"Done in %.2f s ==> %.2f MB/s\n", seconds,
395                         (double)filesize / seconds / 1024 / 1024);
396     }
397 
398     /* Close & Free */
399     free(in_buff);
400     free(out_buff);
401     fclose(finput);
402     fclose(foutput);
403 
404     return 0;
405 }
406 
407 
408 /*********************************************
409 *  Compression using Frame format
410 *********************************************/
411 
412 typedef struct {
413     void*  srcBuffer;
414     size_t srcBufferSize;
415     void*  dstBuffer;
416     size_t dstBufferSize;
417     LZ4F_compressionContext_t ctx;
418     LZ4F_CDict* cdict;
419 } cRess_t;
420 
LZ4IO_createDict(const char * dictFilename,size_t * dictSize)421 static void* LZ4IO_createDict(const char* dictFilename, size_t *dictSize) {
422     size_t readSize;
423     size_t dictEnd = 0;
424     size_t dictLen = 0;
425     size_t dictStart;
426     size_t circularBufSize = LZ4_MAX_DICT_SIZE;
427     char* circularBuf;
428     char* dictBuf;
429     FILE* dictFile;
430 
431     if (!dictFilename) EXM_THROW(25, "Dictionary error : no filename provided");
432 
433     circularBuf = (char *) malloc(circularBufSize);
434     if (!circularBuf) EXM_THROW(25, "Allocation error : not enough memory");
435 
436     dictFile = LZ4IO_openSrcFile(dictFilename);
437     if (!dictFile) EXM_THROW(25, "Dictionary error : could not open dictionary file");
438 
439     /* opportunistically seek to the part of the file we care about. If this */
440     /* fails it's not a problem since we'll just read everything anyways.    */
441     if (strcmp(dictFilename, stdinmark)) {
442         (void)UTIL_fseek(dictFile, -LZ4_MAX_DICT_SIZE, SEEK_END);
443     }
444 
445     do {
446         readSize = fread(circularBuf + dictEnd, 1, circularBufSize - dictEnd, dictFile);
447         dictEnd = (dictEnd + readSize) % circularBufSize;
448         dictLen += readSize;
449     } while (readSize>0);
450 
451     if (dictLen > LZ4_MAX_DICT_SIZE) {
452         dictLen = LZ4_MAX_DICT_SIZE;
453     }
454 
455     *dictSize = dictLen;
456 
457     dictStart = (circularBufSize + dictEnd - dictLen) % circularBufSize;
458 
459     if (dictStart == 0) {
460         /* We're in the simple case where the dict starts at the beginning of our circular buffer. */
461         dictBuf = circularBuf;
462         circularBuf = NULL;
463     } else {
464         /* Otherwise, we will alloc a new buffer and copy our dict into that. */
465         dictBuf = (char *) malloc(dictLen ? dictLen : 1);
466         if (!dictBuf) EXM_THROW(25, "Allocation error : not enough memory");
467 
468         memcpy(dictBuf, circularBuf + dictStart, circularBufSize - dictStart);
469         memcpy(dictBuf + circularBufSize - dictStart, circularBuf, dictLen - (circularBufSize - dictStart));
470     }
471 
472     fclose(dictFile);
473     free(circularBuf);
474 
475     return dictBuf;
476 }
477 
LZ4IO_createCDict(void)478 static LZ4F_CDict* LZ4IO_createCDict(void) {
479     size_t dictionarySize;
480     void* dictionaryBuffer;
481     LZ4F_CDict* cdict;
482     if (!g_useDictionary) {
483         return NULL;
484     }
485     dictionaryBuffer = LZ4IO_createDict(g_dictionaryFilename, &dictionarySize);
486     if (!dictionaryBuffer) EXM_THROW(25, "Dictionary error : could not create dictionary");
487     cdict = LZ4F_createCDict(dictionaryBuffer, dictionarySize);
488     free(dictionaryBuffer);
489     return cdict;
490 }
491 
LZ4IO_createCResources(void)492 static cRess_t LZ4IO_createCResources(void)
493 {
494     const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId);
495     cRess_t ress;
496 
497     LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION);
498     if (LZ4F_isError(errorCode)) EXM_THROW(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
499 
500     /* Allocate Memory */
501     ress.srcBuffer = malloc(blockSize);
502     ress.srcBufferSize = blockSize;
503     ress.dstBufferSize = LZ4F_compressFrameBound(blockSize, NULL);   /* cover worst case */
504     ress.dstBuffer = malloc(ress.dstBufferSize);
505     if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(31, "Allocation error : not enough memory");
506 
507     ress.cdict = LZ4IO_createCDict();
508 
509     return ress;
510 }
511 
LZ4IO_freeCResources(cRess_t ress)512 static void LZ4IO_freeCResources(cRess_t ress)
513 {
514     free(ress.srcBuffer);
515     free(ress.dstBuffer);
516 
517     LZ4F_freeCDict(ress.cdict);
518     ress.cdict = NULL;
519 
520     { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx);
521       if (LZ4F_isError(errorCode)) EXM_THROW(38, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); }
522 }
523 
524 /*
525  * LZ4IO_compressFilename_extRess()
526  * result : 0 : compression completed correctly
527  *          1 : missing or pb opening srcFileName
528  */
LZ4IO_compressFilename_extRess(cRess_t ress,const char * srcFileName,const char * dstFileName,int compressionLevel)529 static int LZ4IO_compressFilename_extRess(cRess_t ress, const char* srcFileName, const char* dstFileName, int compressionLevel)
530 {
531     unsigned long long filesize = 0;
532     unsigned long long compressedfilesize = 0;
533     FILE* srcFile;
534     FILE* dstFile;
535     void* const srcBuffer = ress.srcBuffer;
536     void* const dstBuffer = ress.dstBuffer;
537     const size_t dstBufferSize = ress.dstBufferSize;
538     const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId);
539     size_t readSize;
540     LZ4F_compressionContext_t ctx = ress.ctx;   /* just a pointer */
541     LZ4F_preferences_t prefs;
542 
543     /* Init */
544     srcFile = LZ4IO_openSrcFile(srcFileName);
545     if (srcFile == NULL) return 1;
546     dstFile = LZ4IO_openDstFile(dstFileName);
547     if (dstFile == NULL) { fclose(srcFile); return 1; }
548     memset(&prefs, 0, sizeof(prefs));
549 
550 
551     /* Set compression parameters */
552     prefs.autoFlush = 1;
553     prefs.compressionLevel = compressionLevel;
554     prefs.frameInfo.blockMode = (LZ4F_blockMode_t)g_blockIndependence;
555     prefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)g_blockSizeId;
556     prefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)g_blockChecksum;
557     prefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)g_streamChecksum;
558     prefs.favorDecSpeed = g_favorDecSpeed;
559     if (g_contentSizeFlag) {
560       U64 const fileSize = UTIL_getFileSize(srcFileName);
561       prefs.frameInfo.contentSize = fileSize;   /* == 0 if input == stdin */
562       if (fileSize==0)
563           DISPLAYLEVEL(3, "Warning : cannot determine input content size \n");
564     }
565 
566     /* read first block */
567     readSize  = fread(srcBuffer, (size_t)1, blockSize, srcFile);
568     if (ferror(srcFile)) EXM_THROW(30, "Error reading %s ", srcFileName);
569     filesize += readSize;
570 
571     /* single-block file */
572     if (readSize < blockSize) {
573         /* Compress in single pass */
574         size_t cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress.cdict, &prefs);
575         if (LZ4F_isError(cSize)) EXM_THROW(31, "Compression failed : %s", LZ4F_getErrorName(cSize));
576         compressedfilesize = cSize;
577         DISPLAYUPDATE(2, "\rRead : %u MB   ==> %.2f%%   ",
578                       (unsigned)(filesize>>20), (double)compressedfilesize/(filesize+!filesize)*100);   /* avoid division by zero */
579 
580         /* Write Block */
581         {   size_t const sizeCheck = fwrite(dstBuffer, 1, cSize, dstFile);
582             if (sizeCheck!=cSize) EXM_THROW(32, "Write error : cannot write compressed block");
583     }   }
584 
585     else
586 
587     /* multiple-blocks file */
588     {
589         /* Write Archive Header */
590         size_t headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress.cdict, &prefs);
591         if (LZ4F_isError(headerSize)) EXM_THROW(33, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
592         { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile);
593           if (sizeCheck!=headerSize) EXM_THROW(34, "Write error : cannot write header"); }
594         compressedfilesize += headerSize;
595 
596         /* Main Loop */
597         while (readSize>0) {
598             size_t outSize;
599 
600             /* Compress Block */
601             outSize = LZ4F_compressUpdate(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, NULL);
602             if (LZ4F_isError(outSize)) EXM_THROW(35, "Compression failed : %s", LZ4F_getErrorName(outSize));
603             compressedfilesize += outSize;
604             DISPLAYUPDATE(2, "\rRead : %u MB   ==> %.2f%%   ", (unsigned)(filesize>>20), (double)compressedfilesize/filesize*100);
605 
606             /* Write Block */
607             { size_t const sizeCheck = fwrite(dstBuffer, 1, outSize, dstFile);
608               if (sizeCheck!=outSize) EXM_THROW(36, "Write error : cannot write compressed block"); }
609 
610             /* Read next block */
611             readSize  = fread(srcBuffer, (size_t)1, (size_t)blockSize, srcFile);
612             filesize += readSize;
613         }
614         if (ferror(srcFile)) EXM_THROW(37, "Error reading %s ", srcFileName);
615 
616         /* End of Stream mark */
617         headerSize = LZ4F_compressEnd(ctx, dstBuffer, dstBufferSize, NULL);
618         if (LZ4F_isError(headerSize)) EXM_THROW(38, "End of file generation failed : %s", LZ4F_getErrorName(headerSize));
619 
620         { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile);
621           if (sizeCheck!=headerSize) EXM_THROW(39, "Write error : cannot write end of stream"); }
622         compressedfilesize += headerSize;
623     }
624 
625     /* Release files */
626     fclose (srcFile);
627     fclose (dstFile);
628 
629     /* Copy owner, file permissions and modification time */
630     {   stat_t statbuf;
631         if (strcmp (srcFileName, stdinmark)
632          && strcmp (dstFileName, stdoutmark)
633          && strcmp (dstFileName, nulmark)
634          && UTIL_getFileStat(srcFileName, &statbuf)) {
635             UTIL_setFileStat(dstFileName, &statbuf);
636     }   }
637 
638     if (g_removeSrcFile) {  /* remove source file : --rm */
639         if (remove(srcFileName))
640             EXM_THROW(40, "Remove error : %s: %s", srcFileName, strerror(errno));
641     }
642 
643     /* Final Status */
644     DISPLAYLEVEL(2, "\r%79s\r", "");
645     DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
646                     filesize, compressedfilesize,
647                     (double)compressedfilesize / (filesize + !filesize /* avoid division by zero */ ) * 100);
648 
649     return 0;
650 }
651 
652 
LZ4IO_compressFilename(const char * srcFileName,const char * dstFileName,int compressionLevel)653 int LZ4IO_compressFilename(const char* srcFileName, const char* dstFileName, int compressionLevel)
654 {
655     UTIL_time_t const timeStart = UTIL_getTime();
656     clock_t const cpuStart = clock();
657     cRess_t const ress = LZ4IO_createCResources();
658 
659     int const result = LZ4IO_compressFilename_extRess(ress, srcFileName, dstFileName, compressionLevel);
660 
661     /* Free resources */
662     LZ4IO_freeCResources(ress);
663 
664     /* Final Status */
665     {   clock_t const cpuEnd = clock();
666         double const cpuLoad_s = (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC;
667         U64 const timeLength_ns = UTIL_clockSpanNano(timeStart);
668         double const timeLength_s = (double)timeLength_ns / 1000000000;
669         DISPLAYLEVEL(4, "Completed in %.2f sec  (cpu load : %.0f%%)\n",
670                         timeLength_s, (cpuLoad_s / timeLength_s) * 100);
671     }
672 
673     return result;
674 }
675 
676 
677 #define FNSPACE 30
LZ4IO_compressMultipleFilenames(const char ** inFileNamesTable,int ifntSize,const char * suffix,int compressionLevel)678 int LZ4IO_compressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix, int compressionLevel)
679 {
680     int i;
681     int missed_files = 0;
682     char* dstFileName = (char*)malloc(FNSPACE);
683     size_t ofnSize = FNSPACE;
684     const size_t suffixSize = strlen(suffix);
685     cRess_t ress;
686 
687     if (dstFileName == NULL) return ifntSize;   /* not enough memory */
688     ress = LZ4IO_createCResources();
689 
690     /* loop on each file */
691     for (i=0; i<ifntSize; i++) {
692         size_t const ifnSize = strlen(inFileNamesTable[i]);
693         if (ofnSize <= ifnSize+suffixSize+1) { free(dstFileName); ofnSize = ifnSize + 20; dstFileName = (char*)malloc(ofnSize); if (dstFileName==NULL) { LZ4IO_freeCResources(ress); return ifntSize; } }
694         strcpy(dstFileName, inFileNamesTable[i]);
695         strcat(dstFileName, suffix);
696 
697         missed_files += LZ4IO_compressFilename_extRess(ress, inFileNamesTable[i], dstFileName, compressionLevel);
698     }
699 
700     /* Close & Free */
701     LZ4IO_freeCResources(ress);
702     free(dstFileName);
703 
704     return missed_files;
705 }
706 
707 
708 /* ********************************************************************* */
709 /* ********************** LZ4 file-stream Decompression **************** */
710 /* ********************************************************************* */
711 
LZ4IO_readLE32(const void * s)712 static unsigned LZ4IO_readLE32 (const void* s)
713 {
714     const unsigned char* const srcPtr = (const unsigned char*)s;
715     unsigned value32 = srcPtr[0];
716     value32 += (srcPtr[1]<<8);
717     value32 += (srcPtr[2]<<16);
718     value32 += ((unsigned)srcPtr[3])<<24;
719     return value32;
720 }
721 
722 
LZ4IO_fwriteSparse(FILE * file,const void * buffer,size_t bufferSize,unsigned storedSkips)723 static unsigned LZ4IO_fwriteSparse(FILE* file, const void* buffer, size_t bufferSize, unsigned storedSkips)
724 {
725     const size_t sizeT = sizeof(size_t);
726     const size_t maskT = sizeT -1 ;
727     const size_t* const bufferT = (const size_t*)buffer;   /* Buffer is supposed malloc'ed, hence aligned on size_t */
728     const size_t* ptrT = bufferT;
729     size_t bufferSizeT = bufferSize / sizeT;
730     const size_t* const bufferTEnd = bufferT + bufferSizeT;
731     const size_t segmentSizeT = (32 KB) / sizeT;
732 
733     if (!g_sparseFileSupport) {  /* normal write */
734         size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file);
735         if (sizeCheck != bufferSize) EXM_THROW(70, "Write error : cannot write decoded block");
736         return 0;
737     }
738 
739     /* avoid int overflow */
740     if (storedSkips > 1 GB) {
741         int const seekResult = UTIL_fseek(file, 1 GB, SEEK_CUR);
742         if (seekResult != 0) EXM_THROW(71, "1 GB skip error (sparse file support)");
743         storedSkips -= 1 GB;
744     }
745 
746     while (ptrT < bufferTEnd) {
747         size_t seg0SizeT = segmentSizeT;
748         size_t nb0T;
749 
750         /* count leading zeros */
751         if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT;
752         bufferSizeT -= seg0SizeT;
753         for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ;
754         storedSkips += (unsigned)(nb0T * sizeT);
755 
756         if (nb0T != seg0SizeT) {   /* not all 0s */
757             errno = 0;
758             {   int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR);
759                 if (seekResult) EXM_THROW(72, "Sparse skip error(%d): %s ; try --no-sparse", (int)errno, strerror(errno));
760             }
761             storedSkips = 0;
762             seg0SizeT -= nb0T;
763             ptrT += nb0T;
764             {   size_t const sizeCheck = fwrite(ptrT, sizeT, seg0SizeT, file);
765                 if (sizeCheck != seg0SizeT) EXM_THROW(73, "Write error : cannot write decoded block");
766         }   }
767         ptrT += seg0SizeT;
768     }
769 
770     if (bufferSize & maskT) {  /* size not multiple of sizeT : implies end of block */
771         const char* const restStart = (const char*)bufferTEnd;
772         const char* restPtr = restStart;
773         size_t const restSize =  bufferSize & maskT;
774         const char* const restEnd = restStart + restSize;
775         for (; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ;
776         storedSkips += (unsigned) (restPtr - restStart);
777         if (restPtr != restEnd) {
778             int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR);
779             if (seekResult) EXM_THROW(74, "Sparse skip error ; try --no-sparse");
780             storedSkips = 0;
781             {   size_t const sizeCheck = fwrite(restPtr, 1, restEnd - restPtr, file);
782                 if (sizeCheck != (size_t)(restEnd - restPtr)) EXM_THROW(75, "Write error : cannot write decoded end of block");
783         }   }
784     }
785 
786     return storedSkips;
787 }
788 
LZ4IO_fwriteSparseEnd(FILE * file,unsigned storedSkips)789 static void LZ4IO_fwriteSparseEnd(FILE* file, unsigned storedSkips)
790 {
791     if (storedSkips>0) {   /* implies g_sparseFileSupport>0 */
792         int const seekResult = UTIL_fseek(file, storedSkips-1, SEEK_CUR);
793         if (seekResult != 0) EXM_THROW(69, "Final skip error (sparse file)\n");
794         {   const char lastZeroByte[1] = { 0 };
795             size_t const sizeCheck = fwrite(lastZeroByte, 1, 1, file);
796             if (sizeCheck != 1) EXM_THROW(69, "Write error : cannot write last zero\n");
797     }   }
798 }
799 
800 
801 static unsigned g_magicRead = 0;   /* out-parameter of LZ4IO_decodeLegacyStream() */
LZ4IO_decodeLegacyStream(FILE * finput,FILE * foutput)802 static unsigned long long LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput)
803 {
804     unsigned long long streamSize = 0;
805     unsigned storedSkips = 0;
806 
807     /* Allocate Memory */
808     char* const in_buff  = (char*)malloc(LZ4_compressBound(LEGACY_BLOCKSIZE));
809     char* const out_buff = (char*)malloc(LEGACY_BLOCKSIZE);
810     if (!in_buff || !out_buff) EXM_THROW(51, "Allocation error : not enough memory");
811 
812     /* Main Loop */
813     while (1) {
814         unsigned int blockSize;
815 
816         /* Block Size */
817         {   size_t const sizeCheck = fread(in_buff, 1, 4, finput);
818             if (sizeCheck == 0) break;                   /* Nothing to read : file read is completed */
819             if (sizeCheck != 4) EXM_THROW(52, "Read error : cannot access block size "); }
820             blockSize = LZ4IO_readLE32(in_buff);       /* Convert to Little Endian */
821             if (blockSize > LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) {
822             /* Cannot read next block : maybe new stream ? */
823             g_magicRead = blockSize;
824             break;
825         }
826 
827         /* Read Block */
828         { size_t const sizeCheck = fread(in_buff, 1, blockSize, finput);
829           if (sizeCheck!=blockSize) EXM_THROW(52, "Read error : cannot access compressed block !"); }
830 
831         /* Decode Block */
832         {   int const decodeSize = LZ4_decompress_safe(in_buff, out_buff, blockSize, LEGACY_BLOCKSIZE);
833             if (decodeSize < 0) EXM_THROW(53, "Decoding Failed ! Corrupted input detected !");
834             streamSize += decodeSize;
835             /* Write Block */
836             storedSkips = LZ4IO_fwriteSparse(foutput, out_buff, decodeSize, storedSkips); /* success or die */
837     }   }
838     if (ferror(finput)) EXM_THROW(54, "Read error : ferror");
839 
840     LZ4IO_fwriteSparseEnd(foutput, storedSkips);
841 
842     /* Free */
843     free(in_buff);
844     free(out_buff);
845 
846     return streamSize;
847 }
848 
849 
850 
851 typedef struct {
852     void*  srcBuffer;
853     size_t srcBufferSize;
854     void*  dstBuffer;
855     size_t dstBufferSize;
856     FILE*  dstFile;
857     LZ4F_decompressionContext_t dCtx;
858     void*  dictBuffer;
859     size_t dictBufferSize;
860 } dRess_t;
861 
LZ4IO_loadDDict(dRess_t * ress)862 static void LZ4IO_loadDDict(dRess_t* ress) {
863     if (!g_useDictionary) {
864         ress->dictBuffer = NULL;
865         ress->dictBufferSize = 0;
866         return;
867     }
868 
869     ress->dictBuffer = LZ4IO_createDict(g_dictionaryFilename, &ress->dictBufferSize);
870     if (!ress->dictBuffer) EXM_THROW(25, "Dictionary error : could not create dictionary");
871 }
872 
873 static const size_t LZ4IO_dBufferSize = 64 KB;
LZ4IO_createDResources(void)874 static dRess_t LZ4IO_createDResources(void)
875 {
876     dRess_t ress;
877 
878     /* init */
879     LZ4F_errorCode_t const errorCode = LZ4F_createDecompressionContext(&ress.dCtx, LZ4F_VERSION);
880     if (LZ4F_isError(errorCode)) EXM_THROW(60, "Can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
881 
882     /* Allocate Memory */
883     ress.srcBufferSize = LZ4IO_dBufferSize;
884     ress.srcBuffer = malloc(ress.srcBufferSize);
885     ress.dstBufferSize = LZ4IO_dBufferSize;
886     ress.dstBuffer = malloc(ress.dstBufferSize);
887     if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(61, "Allocation error : not enough memory");
888 
889     LZ4IO_loadDDict(&ress);
890 
891     ress.dstFile = NULL;
892     return ress;
893 }
894 
LZ4IO_freeDResources(dRess_t ress)895 static void LZ4IO_freeDResources(dRess_t ress)
896 {
897     LZ4F_errorCode_t errorCode = LZ4F_freeDecompressionContext(ress.dCtx);
898     if (LZ4F_isError(errorCode)) EXM_THROW(69, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode));
899     free(ress.srcBuffer);
900     free(ress.dstBuffer);
901     free(ress.dictBuffer);
902 }
903 
904 
LZ4IO_decompressLZ4F(dRess_t ress,FILE * srcFile,FILE * dstFile)905 static unsigned long long LZ4IO_decompressLZ4F(dRess_t ress, FILE* srcFile, FILE* dstFile)
906 {
907     unsigned long long filesize = 0;
908     LZ4F_errorCode_t nextToLoad;
909     unsigned storedSkips = 0;
910 
911     /* Init feed with magic number (already consumed from FILE* sFile) */
912     {   size_t inSize = MAGICNUMBER_SIZE;
913         size_t outSize= 0;
914         LZ4IO_writeLE32(ress.srcBuffer, LZ4IO_MAGICNUMBER);
915         nextToLoad = LZ4F_decompress_usingDict(ress.dCtx, ress.dstBuffer, &outSize, ress.srcBuffer, &inSize, ress.dictBuffer, ress.dictBufferSize, NULL);
916         if (LZ4F_isError(nextToLoad)) EXM_THROW(62, "Header error : %s", LZ4F_getErrorName(nextToLoad));
917     }
918 
919     /* Main Loop */
920     for (;nextToLoad;) {
921         size_t readSize;
922         size_t pos = 0;
923         size_t decodedBytes = ress.dstBufferSize;
924 
925         /* Read input */
926         if (nextToLoad > ress.srcBufferSize) nextToLoad = ress.srcBufferSize;
927         readSize = fread(ress.srcBuffer, 1, nextToLoad, srcFile);
928         if (!readSize) break;   /* reached end of file or stream */
929 
930         while ((pos < readSize) || (decodedBytes == ress.dstBufferSize)) {  /* still to read, or still to flush */
931             /* Decode Input (at least partially) */
932             size_t remaining = readSize - pos;
933             decodedBytes = ress.dstBufferSize;
934             nextToLoad = LZ4F_decompress_usingDict(ress.dCtx, ress.dstBuffer, &decodedBytes, (char*)(ress.srcBuffer)+pos, &remaining, ress.dictBuffer, ress.dictBufferSize, NULL);
935             if (LZ4F_isError(nextToLoad)) EXM_THROW(66, "Decompression error : %s", LZ4F_getErrorName(nextToLoad));
936             pos += remaining;
937 
938             /* Write Block */
939             if (decodedBytes) {
940                 if (!g_testMode)
941                     storedSkips = LZ4IO_fwriteSparse(dstFile, ress.dstBuffer, decodedBytes, storedSkips);
942                 filesize += decodedBytes;
943                 DISPLAYUPDATE(2, "\rDecompressed : %u MB  ", (unsigned)(filesize>>20));
944             }
945 
946             if (!nextToLoad) break;
947         }
948     }
949     /* can be out because readSize == 0, which could be an fread() error */
950     if (ferror(srcFile)) EXM_THROW(67, "Read error");
951 
952     if (!g_testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips);
953     if (nextToLoad!=0) EXM_THROW(68, "Unfinished stream");
954 
955     return filesize;
956 }
957 
958 
959 #define PTSIZE  (64 KB)
960 #define PTSIZET (PTSIZE / sizeof(size_t))
LZ4IO_passThrough(FILE * finput,FILE * foutput,unsigned char MNstore[MAGICNUMBER_SIZE])961 static unsigned long long LZ4IO_passThrough(FILE* finput, FILE* foutput, unsigned char MNstore[MAGICNUMBER_SIZE])
962 {
963 	size_t buffer[PTSIZET];
964     size_t readBytes = 1;
965     unsigned long long total = MAGICNUMBER_SIZE;
966     unsigned storedSkips = 0;
967 
968     size_t const sizeCheck = fwrite(MNstore, 1, MAGICNUMBER_SIZE, foutput);
969     if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(50, "Pass-through write error");
970 
971     while (readBytes) {
972         readBytes = fread(buffer, 1, PTSIZE, finput);
973         total += readBytes;
974         storedSkips = LZ4IO_fwriteSparse(foutput, buffer, readBytes, storedSkips);
975     }
976     if (ferror(finput)) EXM_THROW(51, "Read Error");
977 
978     LZ4IO_fwriteSparseEnd(foutput, storedSkips);
979     return total;
980 }
981 
982 
983 /** Safely handle cases when (unsigned)offset > LONG_MAX */
fseek_u32(FILE * fp,unsigned offset,int where)984 static int fseek_u32(FILE *fp, unsigned offset, int where)
985 {
986     const unsigned stepMax = 1U << 30;
987     int errorNb = 0;
988 
989     if (where != SEEK_CUR) return -1;  /* Only allows SEEK_CUR */
990     while (offset > 0) {
991         unsigned s = offset;
992         if (s > stepMax) s = stepMax;
993         errorNb = UTIL_fseek(fp, (long) s, SEEK_CUR);
994         if (errorNb != 0) break;
995         offset -= s;
996     }
997     return errorNb;
998 }
999 
1000 #define ENDOFSTREAM ((unsigned long long)-1)
selectDecoder(dRess_t ress,FILE * finput,FILE * foutput)1001 static unsigned long long selectDecoder(dRess_t ress, FILE* finput, FILE* foutput)
1002 {
1003     unsigned char MNstore[MAGICNUMBER_SIZE];
1004     unsigned magicNumber;
1005     static unsigned nbFrames = 0;
1006 
1007     /* init */
1008     nbFrames++;
1009 
1010     /* Check Archive Header */
1011     if (g_magicRead) {  /* magic number already read from finput (see legacy frame)*/
1012         magicNumber = g_magicRead;
1013         g_magicRead = 0;
1014     } else {
1015         size_t const nbReadBytes = fread(MNstore, 1, MAGICNUMBER_SIZE, finput);
1016         if (nbReadBytes==0) { nbFrames = 0; return ENDOFSTREAM; }   /* EOF */
1017         if (nbReadBytes != MAGICNUMBER_SIZE)
1018           EXM_THROW(40, "Unrecognized header : Magic Number unreadable");
1019         magicNumber = LZ4IO_readLE32(MNstore);   /* Little Endian format */
1020     }
1021     if (LZ4IO_isSkippableMagicNumber(magicNumber))
1022         magicNumber = LZ4IO_SKIPPABLE0;   /* fold skippable magic numbers */
1023 
1024     switch(magicNumber)
1025     {
1026     case LZ4IO_MAGICNUMBER:
1027         return LZ4IO_decompressLZ4F(ress, finput, foutput);
1028     case LEGACY_MAGICNUMBER:
1029         DISPLAYLEVEL(4, "Detected : Legacy format \n");
1030         return LZ4IO_decodeLegacyStream(finput, foutput);
1031     case LZ4IO_SKIPPABLE0:
1032         DISPLAYLEVEL(4, "Skipping detected skippable area \n");
1033         {   size_t const nbReadBytes = fread(MNstore, 1, 4, finput);
1034             if (nbReadBytes != 4)
1035                 EXM_THROW(42, "Stream error : skippable size unreadable");
1036         }
1037         {   unsigned const size = LZ4IO_readLE32(MNstore);
1038             int const errorNb = fseek_u32(finput, size, SEEK_CUR);
1039             if (errorNb != 0)
1040                 EXM_THROW(43, "Stream error : cannot skip skippable area");
1041         }
1042         return 0;
1043     EXTENDED_FORMAT;  /* macro extension for custom formats */
1044     default:
1045         if (nbFrames == 1) {  /* just started */
1046             /* Wrong magic number at the beginning of 1st stream */
1047             if (!g_testMode && g_overwrite) {
1048                 nbFrames = 0;
1049                 return LZ4IO_passThrough(finput, foutput, MNstore);
1050             }
1051             EXM_THROW(44,"Unrecognized header : file cannot be decoded");
1052         }
1053         {   long int const position = ftell(finput);  /* only works for files < 2 GB */
1054             DISPLAYLEVEL(2, "Stream followed by undecodable data ");
1055             if (position != -1L)
1056                 DISPLAYLEVEL(2, "at position %i ", (int)position);
1057             DISPLAYLEVEL(2, "\n");
1058         }
1059         return ENDOFSTREAM;
1060     }
1061 }
1062 
1063 
LZ4IO_decompressSrcFile(dRess_t ress,const char * input_filename,const char * output_filename)1064 static int LZ4IO_decompressSrcFile(dRess_t ress, const char* input_filename, const char* output_filename)
1065 {
1066     FILE* const foutput = ress.dstFile;
1067     unsigned long long filesize = 0;
1068 
1069     /* Init */
1070     FILE* const finput = LZ4IO_openSrcFile(input_filename);
1071     if (finput==NULL) return 1;
1072 
1073     /* Loop over multiple streams */
1074     for ( ; ; ) {  /* endless loop, see break condition */
1075         unsigned long long const decodedSize =
1076                         selectDecoder(ress, finput, foutput);
1077         if (decodedSize == ENDOFSTREAM) break;
1078         filesize += decodedSize;
1079     }
1080 
1081     /* Close input */
1082     fclose(finput);
1083     if (g_removeSrcFile) {  /* --rm */
1084         if (remove(input_filename))
1085             EXM_THROW(45, "Remove error : %s: %s", input_filename, strerror(errno));
1086     }
1087 
1088     /* Final Status */
1089     DISPLAYLEVEL(2, "\r%79s\r", "");
1090     DISPLAYLEVEL(2, "%-20.20s : decoded %llu bytes \n", input_filename, filesize);
1091     (void)output_filename;
1092 
1093     return 0;
1094 }
1095 
1096 
LZ4IO_decompressDstFile(dRess_t ress,const char * input_filename,const char * output_filename)1097 static int LZ4IO_decompressDstFile(dRess_t ress, const char* input_filename, const char* output_filename)
1098 {
1099     stat_t statbuf;
1100     int stat_result = 0;
1101     FILE* const foutput = LZ4IO_openDstFile(output_filename);
1102     if (foutput==NULL) return 1;   /* failure */
1103 
1104     if ( strcmp(input_filename, stdinmark)
1105       && UTIL_getFileStat(input_filename, &statbuf))
1106         stat_result = 1;
1107 
1108     ress.dstFile = foutput;
1109     LZ4IO_decompressSrcFile(ress, input_filename, output_filename);
1110 
1111     fclose(foutput);
1112 
1113     /* Copy owner, file permissions and modification time */
1114     if ( stat_result != 0
1115       && strcmp (output_filename, stdoutmark)
1116       && strcmp (output_filename, nulmark)) {
1117         UTIL_setFileStat(output_filename, &statbuf);
1118         /* should return value be read ? or is silent fail good enough ? */
1119     }
1120 
1121     return 0;
1122 }
1123 
1124 
LZ4IO_decompressFilename(const char * input_filename,const char * output_filename)1125 int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename)
1126 {
1127     dRess_t const ress = LZ4IO_createDResources();
1128     clock_t const start = clock();
1129 
1130     int const missingFiles = LZ4IO_decompressDstFile(ress, input_filename, output_filename);
1131 
1132     clock_t const end = clock();
1133     double const seconds = (double)(end - start) / CLOCKS_PER_SEC;
1134     DISPLAYLEVEL(4, "Done in %.2f sec  \n", seconds);
1135 
1136     LZ4IO_freeDResources(ress);
1137     return missingFiles;
1138 }
1139 
1140 
LZ4IO_decompressMultipleFilenames(const char ** inFileNamesTable,int ifntSize,const char * suffix)1141 int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix)
1142 {
1143     int i;
1144     int skippedFiles = 0;
1145     int missingFiles = 0;
1146     char* outFileName = (char*)malloc(FNSPACE);
1147     size_t ofnSize = FNSPACE;
1148     size_t const suffixSize = strlen(suffix);
1149     dRess_t ress = LZ4IO_createDResources();
1150 
1151     if (outFileName==NULL) return ifntSize;   /* not enough memory */
1152     ress.dstFile = LZ4IO_openDstFile(stdoutmark);
1153 
1154     for (i=0; i<ifntSize; i++) {
1155         size_t const ifnSize = strlen(inFileNamesTable[i]);
1156         const char* const suffixPtr = inFileNamesTable[i] + ifnSize - suffixSize;
1157         if (!strcmp(suffix, stdoutmark)) {
1158             missingFiles += LZ4IO_decompressSrcFile(ress, inFileNamesTable[i], stdoutmark);
1159             continue;
1160         }
1161         if (ofnSize <= ifnSize-suffixSize+1) { free(outFileName); ofnSize = ifnSize + 20; outFileName = (char*)malloc(ofnSize); if (outFileName==NULL) return ifntSize; }
1162         if (ifnSize <= suffixSize  ||  strcmp(suffixPtr, suffix) != 0) {
1163             DISPLAYLEVEL(1, "File extension doesn't match expected LZ4_EXTENSION (%4s); will not process file: %s\n", suffix, inFileNamesTable[i]);
1164             skippedFiles++;
1165             continue;
1166         }
1167         memcpy(outFileName, inFileNamesTable[i], ifnSize - suffixSize);
1168         outFileName[ifnSize-suffixSize] = '\0';
1169         missingFiles += LZ4IO_decompressDstFile(ress, inFileNamesTable[i], outFileName);
1170     }
1171 
1172     LZ4IO_freeDResources(ress);
1173     free(outFileName);
1174     return missingFiles + skippedFiles;
1175 }
1176