Coverage Report

Created: 2026-10-17 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/lz4/lib/lz4frame.c
Line
Count
Source
1
/*
2
 * LZ4 auto-framing library
3
 * Copyright (c) Yann Collet. All rights reserved.
4
 *
5
 * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions are
9
 * met:
10
 *
11
 * - Redistributions of source code must retain the above copyright
12
 *   notice, this list of conditions and the following disclaimer.
13
 * - Redistributions in binary form must reproduce the above
14
 *   copyright notice, this list of conditions and the following disclaimer
15
 *   in the documentation and/or other materials provided with the
16
 *   distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * You can contact the author at :
31
 * - LZ4 homepage : http://www.lz4.org
32
 * - LZ4 source repository : https://github.com/lz4/lz4
33
 */
34
35
/* LZ4F is a stand-alone API to create LZ4-compressed Frames
36
 * in full conformance with specification v1.6.1 .
37
 * This library rely upon memory management capabilities (malloc, free)
38
 * provided either by <stdlib.h>,
39
 * or redirected towards another library of user's choice
40
 * (see Memory Routines below).
41
 */
42
43
44
/*-************************************
45
*  Compiler Options
46
**************************************/
47
#include <limits.h>
48
#ifdef _MSC_VER    /* Visual Studio */
49
#  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
50
#endif
51
52
53
/*-************************************
54
*  Tuning parameters
55
**************************************/
56
/*
57
 * LZ4F_HEAPMODE :
58
 * Control how LZ4F_compressFrame allocates the Compression State,
59
 * either on stack (0:default, fastest), or in memory heap (1:requires malloc()).
60
 */
61
#ifndef LZ4F_HEAPMODE
62
#  define LZ4F_HEAPMODE 0
63
#endif
64
65
66
/*-************************************
67
*  Library declarations
68
**************************************/
69
#define LZ4F_STATIC_LINKING_ONLY
70
#include "lz4frame.h"
71
#define LZ4_STATIC_LINKING_ONLY
72
#include "lz4.h"
73
#define LZ4_HC_STATIC_LINKING_ONLY
74
#include "lz4hc.h"
75
#define XXH_STATIC_LINKING_ONLY
76
#include "xxhash.h"
77
78
79
/*-************************************
80
*  Memory routines
81
**************************************/
82
/*
83
 * User may redirect invocations of
84
 * malloc(), calloc() and free()
85
 * towards another library or solution of their choice
86
 * by modifying below section.
87
**/
88
89
#include <string.h>   /* memset, memcpy, memmove */
90
#ifndef LZ4_SRC_INCLUDED  /* avoid redefinition when sources are coalesced */
91
0
#  define MEM_INIT(p,v,s)   memset((p),(v),(s))
92
#endif
93
94
#ifndef LZ4_SRC_INCLUDED   /* avoid redefinition when sources are coalesced */
95
#  include <stdlib.h>   /* malloc, calloc, free */
96
0
#  define ALLOC(s)          malloc(s)
97
0
#  define ALLOC_AND_ZERO(s) calloc(1,(s))
98
0
#  define FREEMEM(p)        free(p)
99
#endif
100
101
static void* LZ4F_calloc(size_t s, LZ4F_CustomMem cmem)
102
0
{
103
    /* custom calloc defined : use it */
104
0
    if (cmem.customCalloc != NULL) {
105
0
        return cmem.customCalloc(cmem.opaqueState, s);
106
0
    }
107
    /* nothing defined : use default <stdlib.h>'s calloc() */
108
0
    if (cmem.customAlloc == NULL) {
109
0
        return ALLOC_AND_ZERO(s);
110
0
    }
111
    /* only custom alloc defined : use it, and combine it with memset() */
112
0
    {   void* const p = cmem.customAlloc(cmem.opaqueState, s);
113
0
        if (p != NULL) MEM_INIT(p, 0, s);
114
0
        return p;
115
0
}   }
116
117
static void* LZ4F_malloc(size_t s, LZ4F_CustomMem cmem)
118
0
{
119
    /* custom malloc defined : use it */
120
0
    if (cmem.customAlloc != NULL) {
121
0
        return cmem.customAlloc(cmem.opaqueState, s);
122
0
    }
123
    /* nothing defined : use default <stdlib.h>'s malloc() */
124
0
    return ALLOC(s);
125
0
}
126
127
static void LZ4F_free(void* p, LZ4F_CustomMem cmem)
128
0
{
129
0
    if (p == NULL) return;
130
0
    if (cmem.customFree != NULL) {
131
        /* custom allocation defined : use it */
132
0
        cmem.customFree(cmem.opaqueState, p);
133
0
        return;
134
0
    }
135
    /* nothing defined : use default <stdlib.h>'s free() */
136
0
    FREEMEM(p);
137
0
}
138
139
140
/*-************************************
141
*  Debug
142
**************************************/
143
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)
144
#  include <assert.h>
145
#else
146
#  ifndef assert
147
#    define assert(condition) ((void)0)
148
#  endif
149
#endif
150
151
0
#define LZ4F_STATIC_ASSERT(c)    { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
152
153
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) && !defined(DEBUGLOG)
154
#  include <stdio.h>
155
static int g_debuglog_enable = 1;
156
#  define DEBUGLOG(l, ...) {                                  \
157
                if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
158
                    fprintf(stderr, __FILE__ " %i: ", __LINE__ );  \
159
                    fprintf(stderr, __VA_ARGS__);             \
160
                    fprintf(stderr, " \n");                   \
161
            }   }
162
#else
163
0
#  define DEBUGLOG(l, ...)      {}    /* disabled */
164
#endif
165
166
167
/*-************************************
168
*  Basic Types
169
**************************************/
170
#ifndef LZ4_SRC_INCLUDED
171
# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
172
#   include <stdint.h>
173
    typedef  uint8_t BYTE;
174
    typedef uint16_t U16;
175
    typedef uint32_t U32;
176
    typedef  int32_t S32;
177
    typedef uint64_t U64;
178
# else
179
    typedef unsigned char      BYTE;
180
    typedef unsigned short     U16;
181
    typedef unsigned int       U32;
182
    typedef   signed int       S32;
183
    typedef unsigned long long U64;
184
# endif
185
#endif
186
187
188
/* unoptimized version; solves endianness & alignment issues */
189
static U32 LZ4F_readLE32 (const void* src)
190
0
{
191
0
    const BYTE* const srcPtr = (const BYTE*)src;
192
0
    U32 value32 = srcPtr[0];
193
0
    value32 |= ((U32)srcPtr[1])<< 8;
194
0
    value32 |= ((U32)srcPtr[2])<<16;
195
0
    value32 |= ((U32)srcPtr[3])<<24;
196
0
    return value32;
197
0
}
198
199
static void LZ4F_writeLE32 (void* dst, U32 value32)
200
0
{
201
0
    BYTE* const dstPtr = (BYTE*)dst;
202
0
    dstPtr[0] = (BYTE)value32;
203
0
    dstPtr[1] = (BYTE)(value32 >> 8);
204
0
    dstPtr[2] = (BYTE)(value32 >> 16);
205
0
    dstPtr[3] = (BYTE)(value32 >> 24);
206
0
}
207
208
static U64 LZ4F_readLE64 (const void* src)
209
0
{
210
0
    const BYTE* const srcPtr = (const BYTE*)src;
211
0
    U64 value64 = srcPtr[0];
212
0
    value64 |= ((U64)srcPtr[1]<<8);
213
0
    value64 |= ((U64)srcPtr[2]<<16);
214
0
    value64 |= ((U64)srcPtr[3]<<24);
215
0
    value64 |= ((U64)srcPtr[4]<<32);
216
0
    value64 |= ((U64)srcPtr[5]<<40);
217
0
    value64 |= ((U64)srcPtr[6]<<48);
218
0
    value64 |= ((U64)srcPtr[7]<<56);
219
0
    return value64;
220
0
}
221
222
static void LZ4F_writeLE64 (void* dst, U64 value64)
223
0
{
224
0
    BYTE* const dstPtr = (BYTE*)dst;
225
0
    dstPtr[0] = (BYTE)value64;
226
0
    dstPtr[1] = (BYTE)(value64 >> 8);
227
0
    dstPtr[2] = (BYTE)(value64 >> 16);
228
0
    dstPtr[3] = (BYTE)(value64 >> 24);
229
0
    dstPtr[4] = (BYTE)(value64 >> 32);
230
0
    dstPtr[5] = (BYTE)(value64 >> 40);
231
0
    dstPtr[6] = (BYTE)(value64 >> 48);
232
0
    dstPtr[7] = (BYTE)(value64 >> 56);
233
0
}
234
235
236
/*-************************************
237
*  Constants
238
**************************************/
239
#ifndef LZ4_SRC_INCLUDED   /* avoid double definition */
240
0
#  define KB *(1<<10)
241
0
#  define MB *(1<<20)
242
0
#  define GB *(1<<30)
243
#endif
244
245
0
#define _1BIT  0x01
246
0
#define _2BITS 0x03
247
0
#define _3BITS 0x07
248
0
#define _4BITS 0x0F
249
#define _8BITS 0xFF
250
251
0
#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
252
0
#define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB
253
254
static const size_t minFHSize = LZ4F_HEADER_SIZE_MIN;   /*  7 */
255
static const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX;   /* 19 */
256
static const size_t BHSize = LZ4F_BLOCK_HEADER_SIZE;  /* block header : size, and compress flag */
257
static const size_t BFSize = LZ4F_BLOCK_CHECKSUM_SIZE;  /* block footer : checksum (optional) */
258
259
260
/*-************************************
261
*  Structures and local types
262
**************************************/
263
264
typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_BlockCompressMode_e;
265
typedef enum { ctxNone, ctxFast, ctxHC } LZ4F_CtxType_e;
266
267
typedef struct LZ4F_cctx_s
268
{
269
    LZ4F_CustomMem cmem;
270
    LZ4F_preferences_t prefs;
271
    U32    version;
272
    U32    cStage;     /* 0 : compression uninitialized ; 1 : initialized, can compress */
273
    const LZ4F_CDict* cdict;
274
    size_t maxBlockSize;
275
    size_t tmpBuffCapacity;
276
    BYTE*  tmpBuff;    /* internal buffer, for streaming */
277
    BYTE*  tmpIn;      /* starting position of data compress within internal buffer (>= tmpBuff) */
278
    size_t tmpInSize;  /* amount of data to compress after tmpIn */
279
    U64    totalInSize;
280
    XXH32_state_t xxh;
281
    void*  lz4CtxPtr;
282
    U16    lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
283
    U16    lz4CtxType;  /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
284
    LZ4F_BlockCompressMode_e  blockCompressMode;
285
} LZ4F_cctx_t;
286
287
288
/*-************************************
289
*  Error management
290
**************************************/
291
#define LZ4F_GENERATE_STRING(STRING) #STRING,
292
static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };
293
294
295
unsigned LZ4F_isError(LZ4F_errorCode_t code)
296
0
{
297
0
    return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode));
298
0
}
299
300
const char* LZ4F_getErrorName(LZ4F_errorCode_t code)
301
0
{
302
0
    static const char* codeError = "Unspecified error code";
303
0
    if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];
304
0
    return codeError;
305
0
}
306
307
LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult)
308
0
{
309
0
    if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError;
310
0
    return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult);
311
0
}
312
313
static LZ4F_errorCode_t LZ4F_returnErrorCode(LZ4F_errorCodes code)
314
0
{
315
    /* A compilation error here means sizeof(ptrdiff_t) is not large enough */
316
0
    LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t));
317
0
    return (LZ4F_errorCode_t)-(ptrdiff_t)code;
318
0
}
319
320
0
#define RETURN_ERROR(e) return LZ4F_returnErrorCode(LZ4F_ERROR_ ## e)
321
322
0
#define RETURN_ERROR_IF(c,e) do {  \
323
0
        if (c) {                   \
324
0
            DEBUGLOG(3, "Error: " #c); \
325
0
            RETURN_ERROR(e);       \
326
0
        }                          \
327
0
    } while (0)
328
329
0
#define FORWARD_IF_ERROR(r) do { if (LZ4F_isError(r)) return (r); } while (0)
330
331
0
unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; }
332
333
0
int LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; }
334
335
size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID)
336
0
{
337
0
    static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };
338
339
0
    if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
340
0
    if (blockSizeID < LZ4F_max64KB || blockSizeID > LZ4F_max4MB)
341
0
        RETURN_ERROR(maxBlockSize_invalid);
342
0
    {   int const blockSizeIdx = (int)blockSizeID - (int)LZ4F_max64KB;
343
0
        return blockSizes[blockSizeIdx];
344
0
}   }
345
346
/*-************************************
347
*  Private functions
348
**************************************/
349
0
#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
350
351
static BYTE LZ4F_headerChecksum (const void* header, size_t length)
352
0
{
353
0
    U32 const xxh = XXH32(header, length, 0);
354
0
    return (BYTE)(xxh >> 8);
355
0
}
356
357
358
/*-************************************
359
*  Simple-pass compression functions
360
**************************************/
361
static LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID,
362
                                           const size_t srcSize)
363
0
{
364
0
    LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB;
365
0
    size_t maxBlockSize = 64 KB;
366
0
    while (requestedBSID > proposedBSID) {
367
0
        if (srcSize <= maxBlockSize)
368
0
            return proposedBSID;
369
0
        proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1);
370
0
        maxBlockSize <<= 2;
371
0
    }
372
0
    return requestedBSID;
373
0
}
374
375
/*! LZ4F_compressBound_internal() :
376
 *  Provides dstCapacity given a srcSize to guarantee operation success in worst case situations.
377
 *  prefsPtr is optional : if NULL is provided, preferences will be set to cover worst case scenario.
378
 * @return is always the same for a srcSize and prefsPtr, so it can be relied upon to size reusable buffers.
379
 *  When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations.
380
 */
381
static size_t LZ4F_compressBound_internal(size_t srcSize,
382
                                    const LZ4F_preferences_t* preferencesPtr,
383
                                          size_t alreadyBuffered)
384
0
{
385
0
    LZ4F_preferences_t prefsNull = LZ4F_INIT_PREFERENCES;
386
0
    prefsNull.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;   /* worst case */
387
0
    prefsNull.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled;   /* worst case */
388
0
    {   const LZ4F_preferences_t* const prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr;
389
0
        U32 const flush = prefsPtr->autoFlush | (srcSize==0);
390
0
        LZ4F_blockSizeID_t const blockID = prefsPtr->frameInfo.blockSizeID;
391
0
        size_t const blockSize = LZ4F_getBlockSize(blockID);
392
0
        size_t const maxBuffered = blockSize - 1;
393
0
        size_t const bufferedSize = MIN(alreadyBuffered, maxBuffered);
394
0
        size_t const maxSrcSize = srcSize + bufferedSize;
395
0
        unsigned const nbFullBlocks = (unsigned)(maxSrcSize / blockSize);
396
0
        size_t const partialBlockSize = maxSrcSize & (blockSize-1);
397
0
        size_t const lastBlockSize = flush ? partialBlockSize : 0;
398
0
        unsigned const nbBlocks = nbFullBlocks + (lastBlockSize>0);
399
400
0
        size_t const blockCRCSize = BFSize * prefsPtr->frameInfo.blockChecksumFlag;
401
0
        size_t const frameEnd = BHSize + (prefsPtr->frameInfo.contentChecksumFlag*BFSize);
402
403
0
        return ((BHSize + blockCRCSize) * nbBlocks) +
404
0
               (blockSize * nbFullBlocks) + lastBlockSize + frameEnd;
405
0
    }
406
0
}
407
408
size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
409
0
{
410
0
    LZ4F_preferences_t prefs;
411
0
    size_t const headerSize = maxFHSize;      /* max header size, including optional fields */
412
413
0
    if (preferencesPtr!=NULL) prefs = *preferencesPtr;
414
0
    else MEM_INIT(&prefs, 0, sizeof(prefs));
415
0
    prefs.autoFlush = 1;
416
417
0
    return headerSize + LZ4F_compressBound_internal(srcSize, &prefs, 0);;
418
0
}
419
420
421
/*! LZ4F_compressFrame_usingCDict() :
422
 *  Compress srcBuffer using a dictionary, in a single step.
423
 *  cdict can be NULL, in which case, no dictionary is used.
424
 *  Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
425
 *  Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit.
426
 *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,
427
 *  however, it's the only way to provide a dictID, so it's not recommended.
428
 * @return : number of bytes written into dstBuffer,
429
 *           or an error code if it fails (can be tested using LZ4F_isError())
430
 */
431
size_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
432
                                     void* dstBuffer, size_t dstCapacity,
433
                               const void* srcBuffer, size_t srcSize,
434
                               const LZ4F_CDict* cdict,
435
                               const LZ4F_preferences_t* preferencesPtr)
436
0
{
437
0
    LZ4F_preferences_t prefs;
438
0
    LZ4F_compressOptions_t options;
439
0
    BYTE* const dstStart = (BYTE*) dstBuffer;
440
0
    BYTE* dstPtr = dstStart;
441
0
    BYTE* const dstEnd = dstStart + dstCapacity;
442
443
0
    DEBUGLOG(4, "LZ4F_compressFrame_usingCDict (srcSize=%u)", (unsigned)srcSize);
444
0
    if (preferencesPtr!=NULL)
445
0
        prefs = *preferencesPtr;
446
0
    else
447
0
        MEM_INIT(&prefs, 0, sizeof(prefs));
448
0
    if (prefs.frameInfo.contentSize != 0)
449
0
        prefs.frameInfo.contentSize = (U64)srcSize;   /* auto-correct content size if selected (!=0) */
450
451
0
    prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize);
452
0
    prefs.autoFlush = 1;
453
0
    if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))
454
0
        prefs.frameInfo.blockMode = LZ4F_blockIndependent;   /* only one block => no need for inter-block link */
455
456
0
    MEM_INIT(&options, 0, sizeof(options));
457
0
    options.stableSrc = 1;
458
459
0
    { size_t const headerSize = LZ4F_compressBegin_usingCDict(cctx, dstBuffer, dstCapacity, cdict, &prefs);  /* write header */
460
0
      FORWARD_IF_ERROR(headerSize);
461
0
      dstPtr += headerSize;   /* header size */ }
462
463
0
    assert(dstEnd >= dstPtr);
464
0
    { size_t const cSize = LZ4F_compressUpdate(cctx, dstPtr, (size_t)(dstEnd-dstPtr), srcBuffer, srcSize, &options);
465
0
      FORWARD_IF_ERROR(cSize);
466
0
      dstPtr += cSize; }
467
468
0
    assert(dstEnd >= dstPtr);
469
0
    { size_t const tailSize = LZ4F_compressEnd(cctx, dstPtr, (size_t)(dstEnd-dstPtr), &options);   /* flush last block, and generate suffix */
470
0
      FORWARD_IF_ERROR(tailSize);
471
0
      dstPtr += tailSize; }
472
473
0
    assert(dstEnd >= dstStart);
474
0
    return (size_t)(dstPtr - dstStart);
475
0
}
476
477
478
/*! LZ4F_compressFrame() :
479
 *  Compress an entire srcBuffer into a valid LZ4 frame, in a single step.
480
 *  Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
481
 *  Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit.
482
 *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
483
 * @return : number of bytes written into dstBuffer.
484
 *           or an error code if it fails (can be tested using LZ4F_isError())
485
 */
486
size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
487
                    const void* srcBuffer, size_t srcSize,
488
                    const LZ4F_preferences_t* preferencesPtr)
489
0
{
490
0
    size_t result;
491
#if (LZ4F_HEAPMODE)
492
    LZ4F_cctx_t* cctxPtr;
493
    result = LZ4F_createCompressionContext(&cctxPtr, LZ4F_VERSION);
494
    FORWARD_IF_ERROR(result);
495
#else
496
0
    LZ4F_cctx_t cctx;
497
0
    LZ4_stream_t lz4ctx;
498
0
    LZ4F_cctx_t* const cctxPtr = &cctx;
499
500
0
    MEM_INIT(&cctx, 0, sizeof(cctx));
501
0
    cctx.version = LZ4F_VERSION;
502
0
    cctx.tmpBuffCapacity = 5 MB;   /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc==1 */
503
0
    if ( preferencesPtr == NULL
504
0
      || preferencesPtr->compressionLevel < LZ4HC_CLEVEL_MIN ) {
505
0
        LZ4_initStream(&lz4ctx, sizeof(lz4ctx));
506
0
        cctxPtr->lz4CtxPtr = &lz4ctx;
507
0
        cctxPtr->lz4CtxAlloc = ctxFast;
508
0
        cctxPtr->lz4CtxType = ctxFast;
509
0
    }
510
0
#endif
511
0
    DEBUGLOG(4, "LZ4F_compressFrame");
512
513
0
    result = LZ4F_compressFrame_usingCDict(cctxPtr, dstBuffer, dstCapacity,
514
0
                                           srcBuffer, srcSize,
515
0
                                           NULL, preferencesPtr);
516
517
#if (LZ4F_HEAPMODE)
518
    LZ4F_freeCompressionContext(cctxPtr);
519
#else
520
0
    if ( preferencesPtr != NULL
521
0
      && preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN ) {
522
0
        LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);
523
0
    }
524
0
#endif
525
0
    return result;
526
0
}
527
528
529
/*-***************************************************
530
*   Dictionary compression
531
*****************************************************/
532
533
struct LZ4F_CDict_s {
534
    LZ4F_CustomMem cmem;
535
    void* dictContent;
536
    LZ4_stream_t* fastCtx;
537
    LZ4_streamHC_t* HCCtx;
538
}; /* typedef'd to LZ4F_CDict within lz4frame_static.h */
539
540
LZ4F_CDict*
541
LZ4F_createCDict_advanced(LZ4F_CustomMem cmem, const void* dictBuffer, size_t dictSize)
542
0
{
543
0
    const char* dictStart = (const char*)dictBuffer;
544
0
    LZ4F_CDict* cdict = NULL;
545
546
0
    DEBUGLOG(4, "LZ4F_createCDict_advanced");
547
548
0
    if (!dictStart)
549
0
        return NULL;
550
0
    cdict = (LZ4F_CDict*)LZ4F_malloc(sizeof(*cdict), cmem);
551
0
    if (!cdict)
552
0
        return NULL;
553
554
0
    cdict->cmem = cmem;
555
0
    if (dictSize > 64 KB) {
556
0
        dictStart += dictSize - 64 KB;
557
0
        dictSize = 64 KB;
558
0
    }
559
0
    cdict->dictContent = LZ4F_malloc(dictSize, cmem);
560
    /* note: using @cmem to allocate => can't use default create */
561
0
    cdict->fastCtx = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cmem);
562
0
    cdict->HCCtx = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cmem);
563
0
    if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) {
564
0
        LZ4F_freeCDict(cdict);
565
0
        return NULL;
566
0
    }
567
0
    memcpy(cdict->dictContent, dictStart, dictSize);
568
0
    LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
569
0
    LZ4_loadDictSlow(cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
570
0
    LZ4_initStreamHC(cdict->HCCtx, sizeof(LZ4_streamHC_t));
571
    /* note: we don't know at this point which compression level is going to be used
572
     * as a consequence, HCCtx is created for the more common HC mode */
573
0
    LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT);
574
0
    LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize);
575
0
    return cdict;
576
0
}
577
578
/*! LZ4F_createCDict() :
579
 *  When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once.
580
 *  LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
581
 *  LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
582
 * @dictBuffer can be released after LZ4F_CDict creation, since its content is copied within CDict
583
 * @return : digested dictionary for compression, or NULL if failed */
584
LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize)
585
0
{
586
0
    DEBUGLOG(4, "LZ4F_createCDict");
587
0
    return LZ4F_createCDict_advanced(LZ4F_defaultCMem, dictBuffer, dictSize);
588
0
}
589
590
void LZ4F_freeCDict(LZ4F_CDict* cdict)
591
0
{
592
0
    if (cdict==NULL) return;  /* support free on NULL */
593
0
    LZ4F_free(cdict->dictContent, cdict->cmem);
594
0
    LZ4F_free(cdict->fastCtx, cdict->cmem);
595
0
    LZ4F_free(cdict->HCCtx, cdict->cmem);
596
0
    LZ4F_free(cdict, cdict->cmem);
597
0
}
598
599
600
/*-*********************************
601
*  Advanced compression functions
602
***********************************/
603
604
LZ4F_cctx*
605
LZ4F_createCompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version)
606
0
{
607
0
    LZ4F_cctx* const cctxPtr =
608
0
        (LZ4F_cctx*)LZ4F_calloc(sizeof(LZ4F_cctx), customMem);
609
0
    if (cctxPtr==NULL) return NULL;
610
611
0
    cctxPtr->cmem = customMem;
612
0
    cctxPtr->version = version;
613
0
    cctxPtr->cStage = 0;   /* Uninitialized. Next stage : init cctx */
614
615
0
    return cctxPtr;
616
0
}
617
618
/*! LZ4F_createCompressionContext() :
619
 *  The first thing to do is to create a compressionContext object, which will be used in all compression operations.
620
 *  This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
621
 *  The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries.
622
 *  The function will provide a pointer to an allocated LZ4F_compressionContext_t object.
623
 *  If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
624
 *  Object can release its memory using LZ4F_freeCompressionContext();
625
**/
626
LZ4F_errorCode_t
627
LZ4F_createCompressionContext(LZ4F_cctx** LZ4F_compressionContextPtr, unsigned version)
628
0
{
629
0
    assert(LZ4F_compressionContextPtr != NULL); /* considered a violation of narrow contract */
630
    /* in case it nonetheless happen in production */
631
0
    RETURN_ERROR_IF(LZ4F_compressionContextPtr == NULL, parameter_null);
632
633
0
    *LZ4F_compressionContextPtr = LZ4F_createCompressionContext_advanced(LZ4F_defaultCMem, version);
634
0
    RETURN_ERROR_IF(*LZ4F_compressionContextPtr==NULL, allocation_failed);
635
0
    return LZ4F_OK_NoError;
636
0
}
637
638
LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr)
639
0
{
640
0
    if (cctxPtr != NULL) {  /* support free on NULL */
641
0
       LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);  /* note: LZ4_streamHC_t and LZ4_stream_t are simple POD types */
642
0
       LZ4F_free(cctxPtr->tmpBuff, cctxPtr->cmem);
643
0
       LZ4F_free(cctxPtr, cctxPtr->cmem);
644
0
    }
645
0
    return LZ4F_OK_NoError;
646
0
}
647
648
649
/**
650
 * This function prepares the internal LZ4(HC) stream for a new compression,
651
 * resetting the context and attaching the dictionary, if there is one.
652
 *
653
 * It needs to be called at the beginning of each independent compression
654
 * stream (i.e., at the beginning of a frame in blockLinked mode, or at the
655
 * beginning of each block in blockIndependent mode).
656
 */
657
static void LZ4F_initStream(void* ctx,
658
                            const LZ4F_CDict* cdict,
659
                            int level,
660
0
                            LZ4F_blockMode_t blockMode) {
661
0
    if (level < LZ4HC_CLEVEL_MIN) {
662
        /* In these cases, we will call LZ4_compress_fast_continue(),
663
         * which needs an already reset context. Otherwise, we'll call a
664
         * one-shot API. The non-continued APIs internally perform their own
665
         * resets at the beginning of their calls, where they know what
666
         * tableType they need the context to be in. So in that case this
667
         * would be misguided / wasted work. */
668
0
        if (cdict) {
669
0
            LZ4_resetStream_fast((LZ4_stream_t*)ctx);
670
0
            LZ4_attach_dictionary((LZ4_stream_t*)ctx, cdict->fastCtx);
671
0
        } else if (blockMode == LZ4F_blockLinked) {
672
            /* Clear the table, rather than LZ4_resetStream_fast() :
673
             * output doesn't depend on the context's history,
674
             * and it's faster, unless the frame is tiny. */
675
0
            LZ4_initStream(ctx, sizeof(LZ4_stream_t));
676
0
        }
677
        /* In these cases, we'll call a one-shot API.
678
         * The non-continued APIs internally perform their own resets
679
         * at the beginning of their calls, where they know
680
         * which tableType they need the context to be in.
681
         * Therefore, a reset here would be wasted work. */
682
0
    } else {
683
0
        LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level);
684
0
        if (cdict)
685
0
            LZ4_attach_HC_dictionary((LZ4_streamHC_t*)ctx, cdict->HCCtx);
686
0
    }
687
0
}
688
689
/* LZ4F_sizeofLZ4State() :
690
 * @return the size of the inner LZ4 state (pointed by lz4CtxPtr) for @ctxType :
691
 *  LZ4_stream_t for fast levels, LZ4_streamHC_t for HC levels.
692
 *  ctxNone means no state allocated, hence a size of 0.
693
 *  Note : the larger of fast and HC states depends on LZ4_MEMORY_USAGE,
694
 *         so reusing an allocated state requires comparing sizes. */
695
static size_t LZ4F_sizeofLZ4State(LZ4F_CtxType_e ctxType)
696
0
{
697
0
    switch (ctxType) {
698
0
    case ctxNone: return 0;
699
0
    case ctxFast: return sizeof(LZ4_stream_t);
700
0
    case ctxHC:   return sizeof(LZ4_streamHC_t);
701
0
    }
702
0
    assert(0);   /* invalid ctxType */
703
0
    return 0;
704
0
}
705
706
0
size_t LZ4F_cctx_size(const LZ4F_cctx* cctx) {
707
0
    if (cctx == NULL) {
708
0
        return 0;
709
0
    }
710
0
    return sizeof(*cctx) + cctx->tmpBuffCapacity + LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc);
711
0
}
712
713
/* LZ4F_compressBegin_internal()
714
 * Note: only accepts @cdict _or_ @dictBuffer as non NULL.
715
 */
716
static size_t LZ4F_compressBegin_internal(LZ4F_cctx* cctx,
717
                          void* dstBuffer, size_t dstCapacity,
718
                          const void* dictBuffer, size_t dictSize,
719
                          const LZ4F_CDict* cdict,
720
                          const LZ4F_preferences_t* preferencesPtr)
721
0
{
722
0
    LZ4F_preferences_t const prefNull = LZ4F_INIT_PREFERENCES;
723
0
    BYTE* const dstStart = (BYTE*)dstBuffer;
724
0
    BYTE* dstPtr = dstStart;
725
726
0
    if (preferencesPtr == NULL) preferencesPtr = &prefNull;
727
    /* validate before modifying @cctx */
728
0
    {   size_t const headerSize = minFHSize
729
0
                                + (preferencesPtr->frameInfo.contentSize ? 8 : 0)
730
0
                                + (preferencesPtr->frameInfo.dictID ? 4 : 0);
731
0
        RETURN_ERROR_IF(dstCapacity < headerSize, dstCapacity_tooSmall);
732
0
    }
733
0
    FORWARD_IF_ERROR( LZ4F_getBlockSize(preferencesPtr->frameInfo.blockSizeID) );
734
0
    cctx->prefs = *preferencesPtr;
735
0
    DEBUGLOG(5, "LZ4F_compressBegin_internal: Independent_blocks=%u", cctx->prefs.frameInfo.blockMode);
736
737
    /* cctx Management */
738
0
    {   LZ4F_CtxType_e const ctxType = (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? ctxFast : ctxHC;
739
0
        size_t const requiredSize = LZ4F_sizeofLZ4State(ctxType);
740
0
        size_t const allocatedSize = LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc);
741
0
        if (allocatedSize < requiredSize) {
742
            /* not enough space allocated */
743
0
            LZ4F_free(cctx->lz4CtxPtr, cctx->cmem);
744
0
            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
745
                /* must take ownership of memory allocation,
746
                 * in order to respect custom allocator contract */
747
0
                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_stream_t), cctx->cmem);
748
0
                if (cctx->lz4CtxPtr)
749
0
                    LZ4_initStream(cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
750
0
            } else {
751
0
                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_streamHC_t), cctx->cmem);
752
0
                if (cctx->lz4CtxPtr)
753
0
                    LZ4_initStreamHC(cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
754
0
            }
755
0
            RETURN_ERROR_IF(cctx->lz4CtxPtr == NULL, allocation_failed);
756
0
            cctx->lz4CtxAlloc = (U16)ctxType;
757
0
            cctx->lz4CtxType = (U16)ctxType;
758
0
        } else if (cctx->lz4CtxType != ctxType) {
759
            /* otherwise, a sufficient buffer is already allocated,
760
             * but we need to reset it to the correct context type */
761
0
            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
762
0
                LZ4_initStream((LZ4_stream_t*)cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
763
0
            } else {
764
0
                LZ4_initStreamHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
765
0
                LZ4_setCompressionLevel((LZ4_streamHC_t*)cctx->lz4CtxPtr, cctx->prefs.compressionLevel);
766
0
            }
767
0
            cctx->lz4CtxType = (U16)ctxType;
768
0
    }   }
769
770
    /* Buffer Management */
771
0
    if (cctx->prefs.frameInfo.blockSizeID == 0)
772
0
        cctx->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
773
0
    cctx->maxBlockSize = LZ4F_getBlockSize(cctx->prefs.frameInfo.blockSizeID);
774
775
0
    {   size_t const requiredBuffSize = preferencesPtr->autoFlush ?
776
0
                ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */
777
0
                cctx->maxBlockSize + ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
778
779
0
        if (cctx->tmpBuffCapacity < requiredBuffSize) {
780
0
            cctx->tmpBuffCapacity = 0;
781
0
            LZ4F_free(cctx->tmpBuff, cctx->cmem);
782
0
            cctx->tmpBuff = (BYTE*)LZ4F_malloc(requiredBuffSize, cctx->cmem);
783
0
            RETURN_ERROR_IF(cctx->tmpBuff == NULL, allocation_failed);
784
0
            cctx->tmpBuffCapacity = requiredBuffSize;
785
0
    }   }
786
0
    cctx->tmpIn = cctx->tmpBuff;
787
0
    cctx->tmpInSize = 0;
788
0
    (void)XXH32_reset(&(cctx->xxh), 0);
789
790
    /* context init */
791
0
    cctx->cdict = cdict;
792
0
    if (cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) {
793
        /* frame init only for blockLinked : blockIndependent will be init at each block */
794
0
        LZ4F_initStream(cctx->lz4CtxPtr, cdict, cctx->prefs.compressionLevel, LZ4F_blockLinked);
795
0
    }
796
0
    if (preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) {
797
0
        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctx->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);
798
0
    }
799
0
    if (dictBuffer) {
800
0
        assert(cdict == NULL);
801
0
        RETURN_ERROR_IF(dictSize > INT_MAX, parameter_invalid);
802
0
        if (cctx->lz4CtxType == ctxFast) {
803
            /* lz4 fast*/
804
0
            LZ4_loadDict((LZ4_stream_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
805
0
        } else {
806
            /* lz4hc */
807
0
            assert(cctx->lz4CtxType == ctxHC);
808
0
            LZ4_loadDictHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
809
0
        }
810
0
    }
811
812
    /* Stage 2 : Write Frame Header */
813
814
    /* Magic Number */
815
0
    LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
816
0
    dstPtr += 4;
817
0
    {   BYTE* const headerStart = dstPtr;
818
819
        /* FLG Byte */
820
0
        *dstPtr++ = (BYTE)(((1 & _2BITS) << 6)    /* Version('01') */
821
0
            + ((cctx->prefs.frameInfo.blockMode & _1BIT ) << 5)
822
0
            + ((cctx->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
823
0
            + ((unsigned)(cctx->prefs.frameInfo.contentSize > 0) << 3)
824
0
            + ((cctx->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
825
0
            +  (cctx->prefs.frameInfo.dictID > 0) );
826
        /* BD Byte */
827
0
        *dstPtr++ = (BYTE)((cctx->prefs.frameInfo.blockSizeID & _3BITS) << 4);
828
        /* Optional Frame content size field */
829
0
        if (cctx->prefs.frameInfo.contentSize) {
830
0
            LZ4F_writeLE64(dstPtr, cctx->prefs.frameInfo.contentSize);
831
0
            dstPtr += 8;
832
0
            cctx->totalInSize = 0;
833
0
        }
834
        /* Optional dictionary ID field */
835
0
        if (cctx->prefs.frameInfo.dictID) {
836
0
            LZ4F_writeLE32(dstPtr, cctx->prefs.frameInfo.dictID);
837
0
            dstPtr += 4;
838
0
        }
839
        /* Header CRC Byte */
840
0
        *dstPtr = LZ4F_headerChecksum(headerStart, (size_t)(dstPtr - headerStart));
841
0
        dstPtr++;
842
0
    }
843
844
0
    cctx->cStage = 1;   /* header written, now request input data block */
845
0
    return (size_t)(dstPtr - dstStart);
846
0
}
847
848
size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
849
                          void* dstBuffer, size_t dstCapacity,
850
                          const LZ4F_preferences_t* preferencesPtr)
851
0
{
852
0
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
853
0
                                        NULL, 0,
854
0
                                        NULL, preferencesPtr);
855
0
}
856
857
/* LZ4F_compressBegin_usingDictOnce:
858
 * Hidden implementation,
859
 * employed for multi-threaded compression
860
 * when frame defines linked blocks */
861
static size_t LZ4F_compressBegin_usingDictOnce(LZ4F_cctx* cctx,
862
                          void* dstBuffer, size_t dstCapacity,
863
                          const void* dict, size_t dictSize,
864
                          const LZ4F_preferences_t* preferencesPtr)
865
0
{
866
0
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
867
0
                                        dict, dictSize,
868
0
                                        NULL, preferencesPtr);
869
0
}
870
871
size_t LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
872
                          void* dstBuffer, size_t dstCapacity,
873
                          const void* dict, size_t dictSize,
874
                          const LZ4F_preferences_t* preferencesPtr)
875
0
{
876
    /* note : incorrect implementation :
877
     * this will only use the dictionary once,
878
     * instead of once *per* block when frames defines independent blocks */
879
0
    return LZ4F_compressBegin_usingDictOnce(cctx, dstBuffer, dstCapacity,
880
0
                                        dict, dictSize,
881
0
                                        preferencesPtr);
882
0
}
883
884
size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
885
                          void* dstBuffer, size_t dstCapacity,
886
                          const LZ4F_CDict* cdict,
887
                          const LZ4F_preferences_t* preferencesPtr)
888
0
{
889
0
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
890
0
                                        NULL, 0,
891
0
                                       cdict, preferencesPtr);
892
0
}
893
894
895
/*  LZ4F_compressBound() :
896
 * @return minimum capacity of dstBuffer for a given srcSize to handle worst case scenario.
897
 *  LZ4F_preferences_t structure is optional : if NULL, preferences will be set to cover worst case scenario.
898
 *  This function cannot fail.
899
 */
900
size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
901
0
{
902
0
    size_t bound;
903
0
    size_t const blockCRCSize = preferencesPtr
904
0
                             ? BFSize * preferencesPtr->frameInfo.blockChecksumFlag
905
0
                             : BFSize;
906
0
    if (preferencesPtr && preferencesPtr->autoFlush) {
907
0
        return LZ4F_compressBound_internal(srcSize, preferencesPtr, 0);
908
0
    }
909
0
    bound = LZ4F_compressBound_internal(srcSize+1, preferencesPtr, (size_t)-1);
910
    /* A mode switch may emit buffered input as a separate partial block. */
911
0
    return bound + BHSize + blockCRCSize;
912
0
}
913
914
915
typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict);
916
917
918
/*! LZ4F_makeBlock():
919
 *  compress a single block, add header and optional checksum.
920
 *  The block is stored uncompressed when compression doesn't save space.
921
 * @return : size of the block written into @dst,
922
 *           or an error code if it doesn't fit into @dstCapacity.
923
 *  Note : success is guaranteed when dstCapacity >= BHSize + srcSize + crcSize
924
 */
925
static size_t LZ4F_makeBlock(void* dst, size_t dstCapacity,
926
                       const void* src, size_t srcSize,
927
                             compressFunc_t compress, void* lz4ctx, int level,
928
                       const LZ4F_CDict* cdict,
929
                             LZ4F_blockChecksum_t crcFlag)
930
0
{
931
0
    BYTE* const cSizePtr = (BYTE*)dst;
932
0
    size_t const overhead = BHSize + (size_t)crcFlag * BFSize;
933
0
    int cCapacity = (srcSize > 1) ? (int)srcSize - 1 : 1;
934
0
    U32 cSize;
935
0
    assert(compress != NULL);
936
0
    assert(srcSize > 0);
937
0
    RETURN_ERROR_IF(dstCapacity <= overhead, dstCapacity_tooSmall);
938
0
    if (dstCapacity - overhead < (size_t)cCapacity)
939
0
        cCapacity = (int)(dstCapacity - overhead);
940
0
    cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+BHSize),
941
0
                          (int)srcSize, cCapacity,
942
0
                          level, cdict);
943
944
0
    if (cSize == 0 || cSize >= srcSize) {
945
0
        RETURN_ERROR_IF(dstCapacity - overhead < srcSize, dstCapacity_tooSmall);
946
0
        cSize = (U32)srcSize;
947
0
        LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG);
948
0
        memcpy(cSizePtr+BHSize, src, srcSize);
949
0
    } else {
950
0
        LZ4F_writeLE32(cSizePtr, cSize);
951
0
    }
952
0
    if (crcFlag) {
953
0
        U32 const crc32 = XXH32(cSizePtr+BHSize, cSize, 0);  /* checksum of compressed data */
954
0
        LZ4F_writeLE32(cSizePtr+BHSize+cSize, crc32);
955
0
    }
956
0
    return BHSize + cSize + ((U32)crcFlag)*BFSize;
957
0
}
958
959
960
static int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
961
0
{
962
0
    int const acceleration = (level < 0) ? -level + 1 : 1;
963
0
    DEBUGLOG(5, "LZ4F_compressBlock (srcSize=%i)", srcSize);
964
0
    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);
965
0
    if (cdict) {
966
0
        return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);
967
0
    } else {
968
0
        return LZ4_compress_fast_extState_fastReset(ctx, src, dst, srcSize, dstCapacity, acceleration);
969
0
    }
970
0
}
971
972
static int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
973
0
{
974
0
    int const acceleration = (level < 0) ? -level + 1 : 1;
975
0
    (void)cdict; /* init once at beginning of frame */
976
0
    DEBUGLOG(5, "LZ4F_compressBlock_continue (srcSize=%i)", srcSize);
977
0
    return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);
978
0
}
979
980
static int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
981
0
{
982
0
    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);
983
0
    if (cdict) {
984
0
        return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);
985
0
    }
986
0
    return LZ4_compress_HC_extStateHC_fastReset(ctx, src, dst, srcSize, dstCapacity, level);
987
0
}
988
989
static int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
990
0
{
991
0
    (void)level; (void)cdict; /* init once at beginning of frame */
992
0
    return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);
993
0
}
994
995
static int LZ4F_doNotCompressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
996
0
{
997
0
    (void)ctx; (void)src; (void)dst; (void)srcSize; (void)dstCapacity; (void)level; (void)cdict;
998
0
    return 0;
999
0
}
1000
1001
static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_BlockCompressMode_e  compressMode)
1002
0
{
1003
0
    if (compressMode == LZ4B_UNCOMPRESSED)
1004
0
        return LZ4F_doNotCompressBlock;
1005
0
    if (level < LZ4HC_CLEVEL_MIN) {
1006
0
        if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock;
1007
0
        return LZ4F_compressBlock_continue;
1008
0
    }
1009
0
    if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC;
1010
0
    return LZ4F_compressBlockHC_continue;
1011
0
}
1012
1013
/* Save or shorten history (up to 64KB) into @tmpBuff */
1014
static void LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr)
1015
0
{
1016
0
    int const dictSize = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ?
1017
0
                    LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB) :
1018
0
                    LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);
1019
0
    cctxPtr->tmpIn = cctxPtr->tmpBuff + dictSize;
1020
0
}
1021
1022
typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;
1023
1024
static const LZ4F_compressOptions_t k_cOptionsNull = { 0, { 0, 0, 0 } };
1025
1026
/* A failed operation leaves the frame in an inconsistent state :
1027
 * it's invalidated, and must be restarted with LZ4F_compressBegin() */
1028
0
#define FORWARD_IF_ERROR_INVALIDATE(r, cctx) do { \
1029
0
        if (LZ4F_isError(r)) {                     \
1030
0
            (cctx)->cStage = 0;                    \
1031
0
            return (r);                            \
1032
0
        }                                          \
1033
0
    } while (0)
1034
1035
1036
/*! LZ4F_compressUpdateImpl() :
1037
 *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
1038
 *  When successful, the function always entirely consumes @srcBuffer.
1039
 *  src data is either buffered or compressed into @dstBuffer.
1040
 *  If the block compression does not match the compression of the previous block, the old data is flushed
1041
 *  and operations continue with the new compression mode.
1042
 *  Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, preferencesPtr).
1043
 *  Otherwise, the operation fails with dstCapacity_tooSmall if its output doesn't fit.
1044
 * @compressOptionsPtr is optional : provide NULL to mean "default".
1045
 * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
1046
 *           or an error code if it fails (which can be tested using LZ4F_isError())
1047
 *  After an error, the frame is invalidated, and must be restarted with LZ4F_compressBegin().
1048
 */
1049
static size_t LZ4F_compressUpdateImpl(LZ4F_cctx* cctxPtr,
1050
                     void* dstBuffer, size_t dstCapacity,
1051
                     const void* srcBuffer, size_t srcSize,
1052
                     const LZ4F_compressOptions_t* compressOptionsPtr,
1053
                     LZ4F_BlockCompressMode_e blockCompression)
1054
0
  {
1055
0
    size_t const blockSize = cctxPtr->maxBlockSize;
1056
0
    const BYTE* srcPtr = (const BYTE*)srcBuffer;
1057
0
    const BYTE* const srcEnd = srcSize ? (assert(srcPtr!=NULL), srcPtr + srcSize) : srcPtr;
1058
0
    BYTE* const dstStart = (BYTE*)dstBuffer;
1059
0
    BYTE* const dstEnd = dstStart + dstCapacity;
1060
0
    BYTE* dstPtr = dstStart;
1061
0
    LZ4F_lastBlockStatus lastBlockCompressed = notDone;
1062
0
    compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, blockCompression);
1063
0
    size_t bytesWritten;
1064
0
    DEBUGLOG(4, "LZ4F_compressUpdate (srcSize=%zu)", srcSize);
1065
1066
0
    RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized);   /* state must be initialized and waiting for next block */
1067
1068
    /* flush currently written block, to continue with new block compression */
1069
0
    if (cctxPtr->blockCompressMode != blockCompression) {
1070
0
        bytesWritten = LZ4F_flush(cctxPtr, dstBuffer, dstCapacity, compressOptionsPtr);
1071
0
        FORWARD_IF_ERROR(bytesWritten);   /* note : a failed flush invalidates the frame */
1072
0
        dstPtr += bytesWritten;
1073
0
        cctxPtr->blockCompressMode = blockCompression;
1074
0
    }
1075
1076
0
    if (compressOptionsPtr == NULL) compressOptionsPtr = &k_cOptionsNull;
1077
1078
    /* complete tmp buffer */
1079
0
    if (cctxPtr->tmpInSize > 0) {   /* some data already within tmp buffer */
1080
0
        size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize;
1081
0
        assert(blockSize > cctxPtr->tmpInSize);
1082
0
        if (sizeToCopy > srcSize) {
1083
            /* add src to tmpIn buffer */
1084
0
            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);
1085
0
            srcPtr = srcEnd;
1086
0
            cctxPtr->tmpInSize += srcSize;
1087
            /* still needs some CRC */
1088
0
        } else {
1089
            /* complete tmpIn block and then compress it */
1090
0
            lastBlockCompressed = fromTmpBuffer;
1091
0
            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);
1092
0
            srcPtr += sizeToCopy;
1093
1094
0
            bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr),
1095
0
                                          cctxPtr->tmpIn, blockSize,
1096
0
                                          compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
1097
0
                                          cctxPtr->cdict,
1098
0
                                          cctxPtr->prefs.frameInfo.blockChecksumFlag);
1099
0
            FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
1100
0
            dstPtr += bytesWritten;
1101
0
            if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize;
1102
0
            cctxPtr->tmpInSize = 0;
1103
0
    }   }
1104
1105
0
    while ((size_t)(srcEnd - srcPtr) >= blockSize) {
1106
        /* compress full blocks */
1107
0
        lastBlockCompressed = fromSrcBuffer;
1108
0
        bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr),
1109
0
                                      srcPtr, blockSize,
1110
0
                                      compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
1111
0
                                      cctxPtr->cdict,
1112
0
                                      cctxPtr->prefs.frameInfo.blockChecksumFlag);
1113
0
        FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
1114
0
        dstPtr += bytesWritten;
1115
0
        srcPtr += blockSize;
1116
0
    }
1117
1118
0
    if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd)) {
1119
        /* autoFlush : remaining input (< blockSize) is compressed */
1120
0
        lastBlockCompressed = fromSrcBuffer;
1121
0
        bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr),
1122
0
                                      srcPtr, (size_t)(srcEnd - srcPtr),
1123
0
                                      compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
1124
0
                                      cctxPtr->cdict,
1125
0
                                      cctxPtr->prefs.frameInfo.blockChecksumFlag);
1126
0
        FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
1127
0
        dstPtr += bytesWritten;
1128
0
        srcPtr = srcEnd;
1129
0
    }
1130
1131
    /* preserve dictionary within @tmpBuff whenever necessary */
1132
0
    if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) {
1133
        /* linked blocks are only supported in compressed mode, see LZ4F_uncompressedUpdate */
1134
0
        assert(blockCompression == LZ4B_COMPRESSED);
1135
0
        if (compressOptionsPtr->stableSrc) {
1136
0
            cctxPtr->tmpIn = cctxPtr->tmpBuff;  /* src is stable : dictionary remains in src across invocations */
1137
0
        } else {
1138
0
            LZ4F_localSaveDict(cctxPtr);
1139
0
        }
1140
0
    }
1141
1142
    /* keep tmpIn within limits */
1143
0
    if (!(cctxPtr->prefs.autoFlush)  /* no autoflush : there may be some data left within internal buffer */
1144
0
      && (cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity) )  /* not enough room to store next block */
1145
0
    {
1146
        /* only preserve 64KB within internal buffer. Ensures there is enough room for next block.
1147
         * note: this situation necessarily implies lastBlockCompressed==fromTmpBuffer */
1148
0
        LZ4F_localSaveDict(cctxPtr);
1149
0
        assert((cctxPtr->tmpIn + blockSize) <= (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity));
1150
0
    }
1151
1152
    /* some input data left, necessarily < blockSize */
1153
0
    if (srcPtr < srcEnd) {
1154
        /* fill tmp buffer */
1155
0
        size_t const sizeToCopy = (size_t)(srcEnd - srcPtr);
1156
0
        memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);
1157
0
        cctxPtr->tmpInSize = sizeToCopy;
1158
0
    }
1159
1160
0
    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled)
1161
0
        (void)XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize);
1162
1163
0
    cctxPtr->totalInSize += srcSize;
1164
0
    return (size_t)(dstPtr - dstStart);
1165
0
}
1166
1167
/*! LZ4F_compressUpdate() :
1168
 *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
1169
 *  When successful, the function always entirely consumes @srcBuffer.
1170
 *  src data is either buffered or compressed into @dstBuffer.
1171
 *  If previously an uncompressed block was written, buffered data is flushed
1172
 *  before appending compressed data is continued.
1173
 *  Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, preferencesPtr).
1174
 *  Otherwise, the operation fails with dstCapacity_tooSmall if its output doesn't fit.
1175
 * @compressOptionsPtr is optional : provide NULL to mean "default".
1176
 * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
1177
 *           or an error code if it fails (which can be tested using LZ4F_isError())
1178
 *  After an error, the frame is invalidated, and must be restarted with LZ4F_compressBegin().
1179
 */
1180
size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr,
1181
                           void* dstBuffer, size_t dstCapacity,
1182
                     const void* srcBuffer, size_t srcSize,
1183
                     const LZ4F_compressOptions_t* compressOptionsPtr)
1184
0
{
1185
0
     return LZ4F_compressUpdateImpl(cctxPtr,
1186
0
                                   dstBuffer, dstCapacity,
1187
0
                                   srcBuffer, srcSize,
1188
0
                                   compressOptionsPtr, LZ4B_COMPRESSED);
1189
0
}
1190
1191
/*! LZ4F_uncompressedUpdate() :
1192
 *  Same as LZ4F_compressUpdate(), but requests blocks to be sent uncompressed.
1193
 *  This symbol is only supported when LZ4F_blockIndependent is used
1194
 *  Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, preferencesPtr).
1195
 *  Otherwise, the operation fails with dstCapacity_tooSmall if its output doesn't fit.
1196
 * @compressOptionsPtr is optional : provide NULL to mean "default".
1197
 * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
1198
 *           or an error code if it fails (which can be tested using LZ4F_isError())
1199
 *  After an error, the frame is invalidated, and must be restarted with LZ4F_compressBegin().
1200
 */
1201
size_t LZ4F_uncompressedUpdate(LZ4F_cctx* cctxPtr,
1202
                               void* dstBuffer, size_t dstCapacity,
1203
                         const void* srcBuffer, size_t srcSize,
1204
                         const LZ4F_compressOptions_t* compressOptionsPtr)
1205
0
{
1206
0
    return LZ4F_compressUpdateImpl(cctxPtr,
1207
0
                                   dstBuffer, dstCapacity,
1208
0
                                   srcBuffer, srcSize,
1209
0
                                   compressOptionsPtr, LZ4B_UNCOMPRESSED);
1210
0
}
1211
1212
1213
/*! LZ4F_flush() :
1214
 *  When compressed data must be sent immediately, without waiting for a block to be filled,
1215
 *  invoke LZ4F_flush(), which will immediately compress any remaining data stored within LZ4F_cctx.
1216
 *  The result of the function is the number of bytes written into dstBuffer.
1217
 *  It can be zero, this means there was no data left within LZ4F_cctx.
1218
 *  The function outputs an error code if it fails (can be tested using LZ4F_isError())
1219
 *  Success is guaranteed when dstCapacity >= LZ4F_compressBound(0, preferencesPtr).
1220
 *  Otherwise, it fails with dstCapacity_tooSmall if its output doesn't fit,
1221
 *  in which case the frame is invalidated, and must be restarted with LZ4F_compressBegin().
1222
 *  LZ4F_compressOptions_t* is optional. NULL is a valid argument.
1223
 */
1224
size_t LZ4F_flush(LZ4F_cctx* cctxPtr,
1225
                  void* dstBuffer, size_t dstCapacity,
1226
            const LZ4F_compressOptions_t* compressOptionsPtr)
1227
0
{
1228
0
    compressFunc_t compress;
1229
0
    size_t cSize;
1230
1231
0
    DEBUGLOG(5, "LZ4F_flush: %zu buffered bytes (saved dict size = %i) (dstCapacity=%u)",
1232
0
            cctxPtr->tmpInSize, (int)(cctxPtr->tmpIn - cctxPtr->tmpBuff), (unsigned)dstCapacity);
1233
0
    RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized);
1234
0
    if (cctxPtr->tmpInSize == 0) return 0;   /* nothing to flush */
1235
0
    (void)compressOptionsPtr;   /* not useful (yet) */
1236
1237
    /* select compression function */
1238
0
    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompressMode);
1239
1240
    /* compress tmp buffer */
1241
0
    cSize = LZ4F_makeBlock(dstBuffer, dstCapacity,
1242
0
                           cctxPtr->tmpIn, cctxPtr->tmpInSize,
1243
0
                           compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
1244
0
                           cctxPtr->cdict,
1245
0
                           cctxPtr->prefs.frameInfo.blockChecksumFlag);
1246
0
    FORWARD_IF_ERROR_INVALIDATE(cSize, cctxPtr);
1247
0
    assert(((void)"flush overflows dstBuffer!", cSize <= dstCapacity));
1248
1249
0
    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)
1250
0
        cctxPtr->tmpIn += cctxPtr->tmpInSize;
1251
0
    cctxPtr->tmpInSize = 0;
1252
1253
    /* keep tmpIn within limits */
1254
0
    if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity)) {
1255
0
        assert(cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked);
1256
0
        LZ4F_localSaveDict(cctxPtr);
1257
0
    }
1258
1259
0
    return cSize;
1260
0
}
1261
1262
1263
/*! LZ4F_compressEnd() :
1264
 *  When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
1265
 *  It will flush whatever data remained within compressionContext (like LZ4_flush())
1266
 *  but also properly finalize the frame, with an endMark and an (optional) checksum.
1267
 *  LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
1268
 * @return: the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))
1269
 *       or an error code if it fails (can be tested using LZ4F_isError())
1270
 *  The context can then be used again to compress a new frame, starting with LZ4F_compressBegin().
1271
 */
1272
size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr,
1273
                        void* dstBuffer, size_t dstCapacity,
1274
                  const LZ4F_compressOptions_t* compressOptionsPtr)
1275
0
{
1276
0
    BYTE* const dstStart = (BYTE*)dstBuffer;
1277
0
    BYTE* dstPtr = dstStart;
1278
1279
0
    size_t const flushSize = LZ4F_flush(cctxPtr, dstBuffer, dstCapacity, compressOptionsPtr);
1280
0
    DEBUGLOG(5,"LZ4F_compressEnd: dstCapacity=%u", (unsigned)dstCapacity);
1281
0
    FORWARD_IF_ERROR(flushSize);   /* note : a failed flush invalidates the frame */
1282
0
    dstPtr += flushSize;
1283
1284
0
    assert(flushSize <= dstCapacity);
1285
0
    dstCapacity -= flushSize;
1286
1287
    /* From now on, the frame is either completed, or failed : it can't be continued.
1288
     * State is re-usable for a new frame (with identical preferences) */
1289
0
    cctxPtr->cStage = 0;
1290
1291
0
    RETURN_ERROR_IF(dstCapacity < 4, dstCapacity_tooSmall);
1292
0
    LZ4F_writeLE32(dstPtr, 0);
1293
0
    dstPtr += 4;   /* endMark */
1294
1295
0
    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) {
1296
0
        U32 const xxh = XXH32_digest(&(cctxPtr->xxh));
1297
0
        RETURN_ERROR_IF(dstCapacity < 8, dstCapacity_tooSmall);
1298
0
        DEBUGLOG(5,"Writing 32-bit content checksum (0x%0X)", xxh);
1299
0
        LZ4F_writeLE32(dstPtr, xxh);
1300
0
        dstPtr+=4;   /* content Checksum */
1301
0
    }
1302
1303
0
    if (cctxPtr->prefs.frameInfo.contentSize) {
1304
0
        if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)
1305
0
            RETURN_ERROR(frameSize_wrong);
1306
0
    }
1307
1308
0
    return (size_t)(dstPtr - dstStart);
1309
0
}
1310
1311
1312
/*-***************************************************
1313
*   Frame Decompression
1314
*****************************************************/
1315
1316
typedef enum {
1317
    dstage_getFrameHeader=0, dstage_storeFrameHeader,
1318
    dstage_init,
1319
    dstage_getBlockHeader, dstage_storeBlockHeader,
1320
    dstage_copyDirect, dstage_getBlockChecksum,
1321
    dstage_getCBlock, dstage_storeCBlock,
1322
    dstage_flushOut,
1323
    dstage_getSuffix, dstage_storeSuffix,
1324
    dstage_getSFrameSize, dstage_storeSFrameSize,
1325
    dstage_skipSkippable
1326
} dStage_t;
1327
1328
struct LZ4F_dctx_s {
1329
    LZ4F_CustomMem cmem;
1330
    LZ4F_frameInfo_t frameInfo;
1331
    U32    version;
1332
    dStage_t dStage;
1333
    U64    frameRemainingSize;
1334
    size_t maxBlockSize;
1335
    size_t tmpOutBufferCapacity;
1336
    BYTE*  tmpIn;
1337
    size_t tmpInCapacity;
1338
    size_t tmpInSize;
1339
    size_t tmpInTarget;
1340
    BYTE*  tmpOutBuffer;
1341
    const BYTE* dict;
1342
    size_t dictSize;
1343
    BYTE*  tmpOut;
1344
    size_t tmpOutSize;
1345
    size_t tmpOutStart;
1346
    XXH32_state_t xxh;
1347
    XXH32_state_t blockChecksum;
1348
    int    skipBlockChecksum;
1349
    int    skipContentChecksum;
1350
    BYTE   header[LZ4F_HEADER_SIZE_MAX];
1351
};  /* typedef'd to LZ4F_dctx in lz4frame.h */
1352
1353
1354
LZ4F_dctx* LZ4F_createDecompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version)
1355
0
{
1356
0
    LZ4F_dctx* const dctx = (LZ4F_dctx*)LZ4F_calloc(sizeof(LZ4F_dctx), customMem);
1357
0
    if (dctx == NULL) return NULL;
1358
1359
0
    dctx->cmem = customMem;
1360
0
    dctx->version = version;
1361
0
    return dctx;
1362
0
}
1363
1364
/*! LZ4F_createDecompressionContext() :
1365
 *  Create a decompressionContext object, which will track all decompression operations.
1366
 *  Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object.
1367
 *  Object can later be released using LZ4F_freeDecompressionContext().
1368
 * @return : if != 0, there was an error during context creation.
1369
 */
1370
LZ4F_errorCode_t
1371
LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber)
1372
0
{
1373
0
    assert(LZ4F_decompressionContextPtr != NULL);  /* violation of narrow contract */
1374
0
    RETURN_ERROR_IF(LZ4F_decompressionContextPtr == NULL, parameter_null);  /* in case it nonetheless happen in production */
1375
1376
0
    *LZ4F_decompressionContextPtr = LZ4F_createDecompressionContext_advanced(LZ4F_defaultCMem, versionNumber);
1377
0
    if (*LZ4F_decompressionContextPtr == NULL) {  /* failed allocation */
1378
0
        RETURN_ERROR(allocation_failed);
1379
0
    }
1380
0
    return LZ4F_OK_NoError;
1381
0
}
1382
1383
LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx)
1384
0
{
1385
0
    LZ4F_errorCode_t result = LZ4F_OK_NoError;
1386
0
    if (dctx != NULL) {   /* can accept NULL input, like free() */
1387
0
      result = (LZ4F_errorCode_t)dctx->dStage;
1388
0
      LZ4F_free(dctx->tmpIn, dctx->cmem);
1389
0
      LZ4F_free(dctx->tmpOutBuffer, dctx->cmem);
1390
0
      LZ4F_free(dctx, dctx->cmem);
1391
0
    }
1392
0
    return result;
1393
0
}
1394
1395
0
size_t LZ4F_dctx_size(const LZ4F_dctx* dctx) {
1396
0
    if (dctx == NULL) {
1397
0
        return 0;
1398
0
    }
1399
0
    return sizeof(*dctx) + dctx->tmpInCapacity + dctx->tmpOutBufferCapacity;
1400
0
}
1401
1402
1403
/*==---   Streaming Decompression operations   ---==*/
1404
void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx)
1405
0
{
1406
0
    DEBUGLOG(5, "LZ4F_resetDecompressionContext");
1407
0
    dctx->dStage = dstage_getFrameHeader;
1408
0
    dctx->dict = NULL;
1409
0
    dctx->dictSize = 0;
1410
0
    dctx->skipBlockChecksum = 0;
1411
0
    dctx->skipContentChecksum = 0;
1412
0
    dctx->frameRemainingSize = 0;
1413
0
}
1414
1415
1416
/*! LZ4F_decodeHeader() :
1417
 *  input   : `src` points at the **beginning of the frame**
1418
 *  output  : set internal values of dctx, such as
1419
 *            dctx->frameInfo and dctx->dStage.
1420
 *            Also allocates internal buffers.
1421
 *  @return : nb Bytes read from src (necessarily <= srcSize)
1422
 *            or an error code (testable with LZ4F_isError())
1423
 */
1424
static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize)
1425
0
{
1426
0
    unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID;
1427
0
    size_t frameHeaderSize;
1428
0
    const BYTE* srcPtr = (const BYTE*)src;
1429
1430
0
    DEBUGLOG(5, "LZ4F_decodeHeader");
1431
    /* need to decode header to get frameInfo */
1432
0
    RETURN_ERROR_IF(srcSize < minFHSize, frameHeader_incomplete);   /* minimal frame header size */
1433
0
    MEM_INIT(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo));
1434
1435
    /* special case : skippable frames */
1436
0
    if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) {
1437
0
        dctx->frameInfo.frameType = LZ4F_skippableFrame;
1438
0
        if (src == (void*)(dctx->header)) {
1439
0
            dctx->tmpInSize = srcSize;
1440
0
            dctx->tmpInTarget = 8;
1441
0
            dctx->dStage = dstage_storeSFrameSize;
1442
0
            return srcSize;
1443
0
        } else {
1444
0
            dctx->dStage = dstage_getSFrameSize;
1445
0
            return 4;
1446
0
    }   }
1447
1448
    /* control magic number */
1449
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1450
    if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) {
1451
        DEBUGLOG(4, "frame header error : unknown magic number");
1452
        RETURN_ERROR(frameType_unknown);
1453
    }
1454
#endif
1455
0
    dctx->frameInfo.frameType = LZ4F_frame;
1456
1457
    /* Flags */
1458
0
    {   U32 const FLG = srcPtr[4];
1459
0
        U32 const version = (FLG>>6) & _2BITS;
1460
0
        blockChecksumFlag = (FLG>>4) & _1BIT;
1461
0
        blockMode = (FLG>>5) & _1BIT;
1462
0
        contentSizeFlag = (FLG>>3) & _1BIT;
1463
0
        contentChecksumFlag = (FLG>>2) & _1BIT;
1464
0
        dictIDFlag = FLG & _1BIT;
1465
        /* validate */
1466
0
        if (((FLG>>1)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */
1467
0
        if (version != 1) RETURN_ERROR(headerVersion_wrong);       /* Version Number, only supported value */
1468
0
    }
1469
0
    DEBUGLOG(6, "contentSizeFlag: %u", contentSizeFlag);
1470
1471
    /* Frame Header Size */
1472
0
    frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
1473
1474
0
    if (srcSize < frameHeaderSize) {
1475
        /* not enough input to fully decode frame header */
1476
0
        if (srcPtr != dctx->header)
1477
0
            memcpy(dctx->header, srcPtr, srcSize);
1478
0
        dctx->tmpInSize = srcSize;
1479
0
        dctx->tmpInTarget = frameHeaderSize;
1480
0
        dctx->dStage = dstage_storeFrameHeader;
1481
0
        return srcSize;
1482
0
    }
1483
1484
0
    {   U32 const BD = srcPtr[5];
1485
0
        blockSizeID = (BD>>4) & _3BITS;
1486
        /* validate */
1487
0
        if (((BD>>7)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set);   /* Reserved bit */
1488
0
        if (blockSizeID < 4) RETURN_ERROR(maxBlockSize_invalid);    /* 4-7 only supported values for the time being */
1489
0
        if (((BD>>0)&_4BITS) != 0) RETURN_ERROR(reservedFlag_set);  /* Reserved bits */
1490
0
    }
1491
1492
    /* check header */
1493
0
    assert(frameHeaderSize > 5);
1494
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1495
    {   BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5);
1496
        RETURN_ERROR_IF(HC != srcPtr[frameHeaderSize-1], headerChecksum_invalid);
1497
    }
1498
#endif
1499
1500
    /* save */
1501
0
    dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode;
1502
0
    dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag;
1503
0
    dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag;
1504
0
    dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID;
1505
0
    dctx->maxBlockSize = LZ4F_getBlockSize((LZ4F_blockSizeID_t)blockSizeID);
1506
0
    if (contentSizeFlag) {
1507
0
        dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6);
1508
0
    }
1509
0
    if (dictIDFlag)
1510
0
        dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5);
1511
1512
0
    dctx->dStage = dstage_init;
1513
1514
0
    return frameHeaderSize;
1515
0
}
1516
1517
1518
/*! LZ4F_headerSize() :
1519
 * @return : size of frame header
1520
 *           or an error code, which can be tested using LZ4F_isError()
1521
 */
1522
size_t LZ4F_headerSize(const void* src, size_t srcSize)
1523
0
{
1524
0
    RETURN_ERROR_IF(src == NULL, srcPtr_wrong);
1525
1526
    /* minimal srcSize to determine header size */
1527
0
    if (srcSize < LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH)
1528
0
        RETURN_ERROR(frameHeader_incomplete);
1529
1530
    /* special case : skippable frames */
1531
0
    if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START)
1532
0
        return 8;
1533
1534
    /* control magic number */
1535
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1536
    if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER)
1537
        RETURN_ERROR(frameType_unknown);
1538
#endif
1539
1540
    /* Frame Header Size */
1541
0
    {   BYTE const FLG = ((const BYTE*)src)[4];
1542
0
        U32 const contentSizeFlag = (FLG>>3) & _1BIT;
1543
0
        U32 const dictIDFlag = FLG & _1BIT;
1544
0
        return minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
1545
0
    }
1546
0
}
1547
1548
/*! LZ4F_getFrameInfo() :
1549
 *  This function extracts frame parameters (max blockSize, frame checksum, etc.).
1550
 *  Usage is optional. Objective is to provide relevant information for allocation purposes.
1551
 *  This function works in 2 situations :
1552
 *   - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process.
1553
 *     Amount of input data provided must be large enough to successfully decode the frame header.
1554
 *     A header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. It's possible to provide more input data than this minimum.
1555
 *   - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx.
1556
 *  The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value).
1557
 *  Decompression must resume from (srcBuffer + *srcSizePtr).
1558
 * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call,
1559
 *           or an error code which can be tested using LZ4F_isError()
1560
 *  note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped.
1561
 *  note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure.
1562
 */
1563
LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx,
1564
                                   LZ4F_frameInfo_t* frameInfoPtr,
1565
                             const void* srcBuffer, size_t* srcSizePtr)
1566
0
{
1567
0
    assert(dctx != NULL);
1568
0
    RETURN_ERROR_IF(frameInfoPtr == NULL, parameter_null);
1569
0
    RETURN_ERROR_IF(srcSizePtr == NULL, parameter_null);
1570
1571
0
    LZ4F_STATIC_ASSERT(dstage_getFrameHeader < dstage_storeFrameHeader);
1572
0
    if (dctx->dStage > dstage_storeFrameHeader) {
1573
        /* frameInfo already decoded */
1574
0
        size_t o=0, i=0;
1575
0
        *srcSizePtr = 0;
1576
0
        *frameInfoPtr = dctx->frameInfo;
1577
        /* returns : recommended nb of bytes for LZ4F_decompress() */
1578
0
        return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL);
1579
0
    } else {
1580
0
        if (dctx->dStage == dstage_storeFrameHeader) {
1581
            /* frame decoding already started, in the middle of header => automatic fail */
1582
0
            *srcSizePtr = 0;
1583
0
            RETURN_ERROR(frameDecoding_alreadyStarted);
1584
0
        } else {
1585
0
            size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr);
1586
0
            if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; }
1587
0
            if (*srcSizePtr < hSize) {
1588
0
                *srcSizePtr=0;
1589
0
                RETURN_ERROR(frameHeader_incomplete);
1590
0
            }
1591
1592
0
            {   size_t decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize);
1593
0
                if (LZ4F_isError(decodeResult)) {
1594
0
                    *srcSizePtr = 0;
1595
0
                } else {
1596
0
                    *srcSizePtr = decodeResult;
1597
0
                    decodeResult = BHSize;   /* block header size */
1598
0
                }
1599
0
                *frameInfoPtr = dctx->frameInfo;
1600
0
                return decodeResult;
1601
0
    }   }   }
1602
0
}
1603
1604
1605
/* LZ4F_updateDict() :
1606
 * only used for LZ4F_blockLinked mode
1607
 * Condition : @dstPtr != NULL
1608
 */
1609
static void LZ4F_updateDict(LZ4F_dctx* dctx,
1610
                      const BYTE* dstPtr, size_t dstSize, const BYTE* dstBufferStart,
1611
                      unsigned withinTmp)
1612
0
{
1613
0
    assert(dstPtr != NULL);
1614
0
    if (dctx->dictSize==0) dctx->dict = (const BYTE*)dstPtr;  /* will lead to prefix mode */
1615
0
    assert(dctx->dict != NULL);
1616
1617
0
    if (dctx->dict + dctx->dictSize == dstPtr) {  /* prefix mode, everything within dstBuffer */
1618
0
        dctx->dictSize += dstSize;
1619
0
        return;
1620
0
    }
1621
1622
0
    assert(dstPtr >= dstBufferStart);
1623
0
    if ((size_t)(dstPtr - dstBufferStart) + dstSize >= 64 KB) {  /* history in dstBuffer becomes large enough to become dictionary */
1624
0
        dctx->dict = (const BYTE*)dstBufferStart;
1625
0
        dctx->dictSize = (size_t)(dstPtr - dstBufferStart) + dstSize;
1626
0
        return;
1627
0
    }
1628
1629
0
    assert(dstSize < 64 KB);   /* if dstSize >= 64 KB, dictionary would be set into dstBuffer directly */
1630
1631
    /* dstBuffer does not contain whole useful history (64 KB), so it must be saved within tmpOutBuffer */
1632
0
    assert(dctx->tmpOutBuffer != NULL);
1633
1634
0
    if (withinTmp && (dctx->dict == dctx->tmpOutBuffer)) {   /* continue history within tmpOutBuffer */
1635
        /* withinTmp expectation : content of [dstPtr,dstSize] is same as [dict+dictSize,dstSize], so we just extend it */
1636
0
        assert(dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart);
1637
0
        dctx->dictSize += dstSize;
1638
0
        return;
1639
0
    }
1640
1641
0
    if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */
1642
0
        size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer);
1643
0
        size_t copySize = 64 KB - dctx->tmpOutSize;
1644
0
        const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart;
1645
0
        if (dctx->tmpOutSize > 64 KB) copySize = 0;
1646
0
        if (copySize > preserveSize) copySize = preserveSize;
1647
1648
0
        memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
1649
1650
0
        dctx->dict = dctx->tmpOutBuffer;
1651
0
        dctx->dictSize = preserveSize + dctx->tmpOutStart + dstSize;
1652
0
        return;
1653
0
    }
1654
1655
0
    if (dctx->dict == dctx->tmpOutBuffer) {    /* copy dst into tmp to complete dict */
1656
0
        if (dctx->dictSize + dstSize > dctx->tmpOutBufferCapacity) {  /* tmp buffer not large enough */
1657
0
            size_t const preserveSize = 64 KB - dstSize;
1658
0
            memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);
1659
0
            dctx->dictSize = preserveSize;
1660
0
        }
1661
0
        memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize);
1662
0
        dctx->dictSize += dstSize;
1663
0
        return;
1664
0
    }
1665
1666
    /* join dict & dest into tmp */
1667
0
    {   size_t preserveSize = 64 KB - dstSize;
1668
0
        if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize;
1669
0
        memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);
1670
0
        memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize);
1671
0
        dctx->dict = dctx->tmpOutBuffer;
1672
0
        dctx->dictSize = preserveSize + dstSize;
1673
0
    }
1674
0
}
1675
1676
1677
/*! LZ4F_decompress() :
1678
 *  Call this function repetitively to regenerate compressed data in srcBuffer.
1679
 *  The function will attempt to decode up to *srcSizePtr bytes from srcBuffer
1680
 *  into dstBuffer of capacity *dstSizePtr.
1681
 *
1682
 *  The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
1683
 *
1684
 *  The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
1685
 *  If number of bytes read is < number of bytes provided, then decompression operation is not complete.
1686
 *  Remaining data will have to be presented again in a subsequent invocation.
1687
 *
1688
 *  The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.
1689
 *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.
1690
 *  Respecting the hint provides a small boost to performance, since it allows less buffer shuffling.
1691
 *  Note that this is just a hint, and it's always possible to any srcSize value.
1692
 *  When a frame is fully decoded, @return will be 0.
1693
 *  If decompression failed, @return is an error code which can be tested using LZ4F_isError().
1694
 */
1695
size_t LZ4F_decompress(LZ4F_dctx* dctx,
1696
                       void* dstBuffer, size_t* dstSizePtr,
1697
                       const void* srcBuffer, size_t* srcSizePtr,
1698
                       const LZ4F_decompressOptions_t* decompressOptionsPtr)
1699
0
{
1700
0
    static const BYTE emptySrc = 0;   /* NULL srcBuffer (no input, used by LZ4F_getFrameInfo()) points here instead :
1701
                                       * NULL+0 and memcpy(dst, NULL, 0) are UB */
1702
0
    LZ4F_decompressOptions_t optionsNull;
1703
0
    const BYTE* const srcStart = srcBuffer ? (const BYTE*)srcBuffer : &emptySrc;
1704
0
    const BYTE* const srcEnd = srcBuffer ? srcStart + *srcSizePtr : srcStart;
1705
0
    const BYTE* srcPtr = srcStart;
1706
0
    BYTE* const dstStart = (BYTE*)dstBuffer;
1707
0
    BYTE* const dstEnd = dstStart ? dstStart + *dstSizePtr : NULL;
1708
0
    BYTE* dstPtr = dstStart;
1709
0
    const BYTE* selectedIn = NULL;
1710
0
    unsigned doAnotherStage = 1;
1711
0
    size_t nextSrcSizeHint = 1;
1712
1713
1714
0
    DEBUGLOG(5, "LZ4F_decompress: src[%p](%u) => dst[%p](%u)",
1715
0
            srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr);
1716
0
    if (dstBuffer == NULL) assert(*dstSizePtr == 0);
1717
0
    if (srcBuffer == NULL) assert(*srcSizePtr == 0);
1718
0
    MEM_INIT(&optionsNull, 0, sizeof(optionsNull));
1719
0
    if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;
1720
0
    *srcSizePtr = 0;
1721
0
    *dstSizePtr = 0;
1722
0
    assert(dctx != NULL);
1723
0
    if (decompressOptionsPtr->skipChecksums) {   /* once set, disable for the remainder of the frame */
1724
0
        dctx->skipBlockChecksum = 1;
1725
0
        dctx->skipContentChecksum = 1;
1726
0
    }
1727
1728
    /* behaves as a state machine */
1729
1730
0
    while (doAnotherStage) {
1731
1732
0
        switch(dctx->dStage)
1733
0
        {
1734
1735
0
        case dstage_getFrameHeader:
1736
0
            DEBUGLOG(6, "dstage_getFrameHeader");
1737
0
            if ((size_t)(srcEnd-srcPtr) >= maxFHSize) {  /* enough to decode - shortcut */
1738
0
                size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, (size_t)(srcEnd-srcPtr));  /* will update dStage appropriately */
1739
0
                FORWARD_IF_ERROR(hSize);
1740
0
                srcPtr += hSize;
1741
0
                break;
1742
0
            }
1743
0
            dctx->tmpInSize = 0;
1744
0
            if (srcEnd-srcPtr == 0) return minFHSize;   /* 0-size input */
1745
0
            dctx->tmpInTarget = minFHSize;   /* minimum size to decode header */
1746
0
            dctx->dStage = dstage_storeFrameHeader;
1747
            /* fall-through */
1748
1749
0
        case dstage_storeFrameHeader:
1750
0
            DEBUGLOG(6, "dstage_storeFrameHeader");
1751
0
            {   size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr));
1752
0
                memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);
1753
0
                dctx->tmpInSize += sizeToCopy;
1754
0
                srcPtr += sizeToCopy;
1755
0
            }
1756
0
            if (dctx->tmpInSize < dctx->tmpInTarget) {
1757
0
                nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize;   /* rest of header + nextBlockHeader */
1758
0
                doAnotherStage = 0;   /* not enough src data, ask for some more */
1759
0
                break;
1760
0
            }
1761
0
            FORWARD_IF_ERROR( LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget) ); /* will update dStage appropriately */
1762
0
            break;
1763
1764
0
        case dstage_init:
1765
0
            DEBUGLOG(6, "dstage_init");
1766
0
            if (dctx->frameInfo.contentChecksumFlag) (void)XXH32_reset(&(dctx->xxh), 0);
1767
            /* internal buffers allocation */
1768
0
            {   size_t const tmpInNeeded = dctx->maxBlockSize + BFSize /* block checksum */;
1769
0
                size_t const tmpOutNeeded = dctx->maxBlockSize
1770
0
                    + ((dctx->frameInfo.blockMode==LZ4F_blockLinked) ? 128 KB : 0);
1771
0
                if ( (tmpInNeeded > dctx->tmpInCapacity)
1772
0
                  || (tmpOutNeeded > dctx->tmpOutBufferCapacity) ) {   /* tmp buffers too small */
1773
                    /* capacities remain 0 until allocation succeeds,
1774
                     * so that allocation will be re-attempted on next entry */
1775
0
                    LZ4F_free(dctx->tmpIn, dctx->cmem);
1776
0
                    dctx->tmpInCapacity = 0;
1777
0
                    dctx->tmpIn = (BYTE*)LZ4F_malloc(tmpInNeeded, dctx->cmem);
1778
0
                    RETURN_ERROR_IF(dctx->tmpIn == NULL, allocation_failed);
1779
0
                    dctx->tmpInCapacity = tmpInNeeded;
1780
0
                    LZ4F_free(dctx->tmpOutBuffer, dctx->cmem);
1781
0
                    dctx->tmpOutBufferCapacity = 0;
1782
0
                    dctx->tmpOutBuffer= (BYTE*)LZ4F_malloc(tmpOutNeeded, dctx->cmem);
1783
0
                    RETURN_ERROR_IF(dctx->tmpOutBuffer== NULL, allocation_failed);
1784
0
                    dctx->tmpOutBufferCapacity = tmpOutNeeded;
1785
0
            }   }
1786
0
            dctx->tmpInSize = 0;
1787
0
            dctx->tmpInTarget = 0;
1788
0
            dctx->tmpOut = dctx->tmpOutBuffer;
1789
0
            dctx->tmpOutStart = 0;
1790
0
            dctx->tmpOutSize = 0;
1791
1792
0
            dctx->dStage = dstage_getBlockHeader;
1793
            /* fall-through */
1794
1795
0
        case dstage_getBlockHeader:
1796
0
            if ((size_t)(srcEnd - srcPtr) >= BHSize) {
1797
0
                selectedIn = srcPtr;
1798
0
                srcPtr += BHSize;
1799
0
            } else {
1800
                /* not enough input to read cBlockSize field */
1801
0
                dctx->tmpInSize = 0;
1802
0
                dctx->dStage = dstage_storeBlockHeader;
1803
0
            }
1804
1805
0
            if (dctx->dStage == dstage_storeBlockHeader)   /* can be skipped */
1806
0
        case dstage_storeBlockHeader:
1807
0
            {   size_t const remainingInput = (size_t)(srcEnd - srcPtr);
1808
0
                size_t const wantedData = BHSize - dctx->tmpInSize;
1809
0
                size_t const sizeToCopy = MIN(wantedData, remainingInput);
1810
0
                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);
1811
0
                srcPtr += sizeToCopy;
1812
0
                dctx->tmpInSize += sizeToCopy;
1813
1814
0
                if (dctx->tmpInSize < BHSize) {   /* not enough input for cBlockSize */
1815
0
                    nextSrcSizeHint = BHSize - dctx->tmpInSize;
1816
0
                    doAnotherStage  = 0;
1817
0
                    break;
1818
0
                }
1819
0
                selectedIn = dctx->tmpIn;
1820
0
            }   /* if (dctx->dStage == dstage_storeBlockHeader) */
1821
1822
        /* decode block header */
1823
0
            {   U32 const blockHeader = LZ4F_readLE32(selectedIn);
1824
0
                size_t const nextCBlockSize = blockHeader & 0x7FFFFFFFU;
1825
0
                size_t const crcSize = dctx->frameInfo.blockChecksumFlag * BFSize;
1826
0
                if (blockHeader==0) {  /* frameEnd signal, no more block */
1827
0
                    DEBUGLOG(5, "end of frame");
1828
0
                    dctx->dStage = dstage_getSuffix;
1829
0
                    break;
1830
0
                }
1831
0
                if (nextCBlockSize > dctx->maxBlockSize) {
1832
0
                    RETURN_ERROR(maxBlockSize_invalid);
1833
0
                }
1834
0
                if (blockHeader & LZ4F_BLOCKUNCOMPRESSED_FLAG) {
1835
                    /* next block is uncompressed */
1836
0
                    dctx->tmpInTarget = nextCBlockSize;
1837
0
                    DEBUGLOG(5, "next block is uncompressed (size %u)", (U32)nextCBlockSize);
1838
0
                    if (dctx->frameInfo.blockChecksumFlag) {
1839
0
                        (void)XXH32_reset(&dctx->blockChecksum, 0);
1840
0
                    }
1841
0
                    dctx->dStage = dstage_copyDirect;
1842
0
                    break;
1843
0
                }
1844
                /* next block is a compressed block */
1845
0
                dctx->tmpInTarget = nextCBlockSize + crcSize;
1846
0
                dctx->dStage = dstage_getCBlock;
1847
0
                if (dstPtr==dstEnd || srcPtr==srcEnd) {
1848
0
                    nextSrcSizeHint = BHSize + nextCBlockSize + crcSize;
1849
0
                    doAnotherStage = 0;
1850
0
                }
1851
0
                break;
1852
0
            }
1853
1854
0
        case dstage_copyDirect:   /* uncompressed block */
1855
0
            DEBUGLOG(6, "dstage_copyDirect");
1856
0
            {   size_t sizeToCopy;
1857
0
                if (dstPtr == NULL) {
1858
0
                    sizeToCopy = 0;
1859
0
                } else {
1860
0
                    size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr));
1861
0
                    sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize);
1862
0
                    memcpy(dstPtr, srcPtr, sizeToCopy);
1863
0
                    if (dctx->frameInfo.blockChecksumFlag && !dctx->skipBlockChecksum)
1864
0
                        (void)XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy);
1865
0
                    if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum)
1866
0
                        (void)XXH32_update(&dctx->xxh, srcPtr, sizeToCopy);
1867
0
                    if (dctx->frameInfo.contentSize)
1868
0
                        dctx->frameRemainingSize -= sizeToCopy;
1869
1870
                    /* history management (linked blocks only)*/
1871
0
                    if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {
1872
0
                        LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0);
1873
0
                    }
1874
0
                    srcPtr += sizeToCopy;
1875
0
                    dstPtr += sizeToCopy;
1876
0
                }
1877
0
                if (sizeToCopy == dctx->tmpInTarget) {   /* all done */
1878
0
                    if (dctx->frameInfo.blockChecksumFlag) {
1879
0
                        dctx->tmpInSize = 0;
1880
0
                        dctx->dStage = dstage_getBlockChecksum;
1881
0
                    } else
1882
0
                        dctx->dStage = dstage_getBlockHeader;  /* new block */
1883
0
                    break;
1884
0
                }
1885
0
                dctx->tmpInTarget -= sizeToCopy;  /* need to copy more */
1886
0
            }
1887
0
            nextSrcSizeHint = dctx->tmpInTarget +
1888
0
                            +(dctx->frameInfo.blockChecksumFlag ? BFSize : 0)
1889
0
                            + BHSize /* next header size */;
1890
0
            doAnotherStage = 0;
1891
0
            break;
1892
1893
        /* check block checksum for recently transferred uncompressed block */
1894
0
        case dstage_getBlockChecksum:
1895
0
            DEBUGLOG(6, "dstage_getBlockChecksum");
1896
0
            {   const void* crcSrc;
1897
0
                if ((srcEnd-srcPtr >= 4) && (dctx->tmpInSize==0)) {
1898
0
                    crcSrc = srcPtr;
1899
0
                    srcPtr += 4;
1900
0
                } else {
1901
0
                    size_t const stillToCopy = 4 - dctx->tmpInSize;
1902
0
                    size_t const sizeToCopy = MIN(stillToCopy, (size_t)(srcEnd-srcPtr));
1903
0
                    memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);
1904
0
                    dctx->tmpInSize += sizeToCopy;
1905
0
                    srcPtr += sizeToCopy;
1906
0
                    if (dctx->tmpInSize < 4) {  /* all input consumed */
1907
0
                        nextSrcSizeHint = (4 - dctx->tmpInSize) + BHSize /* next header size */;
1908
0
                        doAnotherStage = 0;
1909
0
                        break;
1910
0
                    }
1911
0
                    crcSrc = dctx->header;
1912
0
                }
1913
0
                if (!dctx->skipBlockChecksum) {
1914
0
                    U32 const readCRC = LZ4F_readLE32(crcSrc);
1915
0
                    U32 const calcCRC = XXH32_digest(&dctx->blockChecksum);
1916
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1917
                    DEBUGLOG(6, "compare block checksum");
1918
                    if (readCRC != calcCRC) {
1919
                        DEBUGLOG(4, "incorrect block checksum: %08X != %08X",
1920
                                readCRC, calcCRC);
1921
                        RETURN_ERROR(blockChecksum_invalid);
1922
                    }
1923
#else
1924
0
                    (void)readCRC;
1925
0
                    (void)calcCRC;
1926
0
#endif
1927
0
            }   }
1928
0
            dctx->dStage = dstage_getBlockHeader;  /* new block */
1929
0
            break;
1930
1931
0
        case dstage_getCBlock:
1932
0
            DEBUGLOG(6, "dstage_getCBlock");
1933
0
            if ((size_t)(srcEnd-srcPtr) < dctx->tmpInTarget) {
1934
0
                dctx->tmpInSize = 0;
1935
0
                dctx->dStage = dstage_storeCBlock;
1936
0
                break;
1937
0
            }
1938
            /* input large enough to read full block directly */
1939
0
            selectedIn = srcPtr;
1940
0
            srcPtr += dctx->tmpInTarget;
1941
1942
0
            if (0)  /* always jump over next block */
1943
0
        case dstage_storeCBlock:
1944
0
            {   size_t const wantedData = dctx->tmpInTarget - dctx->tmpInSize;
1945
0
                size_t const inputLeft = (size_t)(srcEnd-srcPtr);
1946
0
                size_t const sizeToCopy = MIN(wantedData, inputLeft);
1947
0
                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);
1948
0
                dctx->tmpInSize += sizeToCopy;
1949
0
                srcPtr += sizeToCopy;
1950
0
                if (dctx->tmpInSize < dctx->tmpInTarget) { /* need more input */
1951
0
                    nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize)   /* block checksum included */
1952
0
                                    + BHSize /* next header size */;
1953
0
                    doAnotherStage = 0;
1954
0
                    break;
1955
0
                }
1956
0
                selectedIn = dctx->tmpIn;
1957
0
            }
1958
1959
            /* At this stage, input is large enough to decode a block */
1960
1961
            /* First, decode and control block checksum if it exists */
1962
0
            if (dctx->frameInfo.blockChecksumFlag) {
1963
0
                assert(dctx->tmpInTarget >= 4);
1964
0
                dctx->tmpInTarget -= 4;
1965
0
                assert(selectedIn != NULL);  /* selectedIn is defined at this stage (either srcPtr, or dctx->tmpIn) */
1966
0
                if (!dctx->skipBlockChecksum) {
1967
0
                    U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget);
1968
0
                    U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0);
1969
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1970
                    RETURN_ERROR_IF(readBlockCrc != calcBlockCrc, blockChecksum_invalid);
1971
#else
1972
0
                    (void)readBlockCrc;
1973
0
                    (void)calcBlockCrc;
1974
0
#endif
1975
0
            }   }
1976
1977
            /* decode directly into destination buffer if there is enough room */
1978
0
            if ( ((size_t)(dstEnd-dstPtr) >= dctx->maxBlockSize)
1979
                 /* unless the dictionary is stored in tmpOut:
1980
                  * in which case it's faster to decode within tmpOut
1981
                  * to benefit from prefix speedup */
1982
0
              && !(dctx->dict!= NULL && (const BYTE*)dctx->dict + dctx->dictSize == dctx->tmpOut) )
1983
0
            {
1984
0
                const char* dict = (const char*)dctx->dict;
1985
0
                size_t dictSize = dctx->dictSize;
1986
0
                int decodedSize;
1987
0
                assert(dstPtr != NULL);
1988
0
                if (dict && dictSize > 1 GB) {
1989
                    /* overflow control : dctx->dictSize is an int, avoid truncation / sign issues */
1990
0
                    dict += dictSize - 64 KB;
1991
0
                    dictSize = 64 KB;
1992
0
                }
1993
0
                decodedSize = LZ4_decompress_safe_usingDict(
1994
0
                        (const char*)selectedIn, (char*)dstPtr,
1995
0
                        (int)dctx->tmpInTarget, (int)dctx->maxBlockSize,
1996
0
                        dict, (int)dictSize);
1997
0
                RETURN_ERROR_IF(decodedSize < 0, decompressionFailed);
1998
0
                if ((dctx->frameInfo.contentChecksumFlag) && (!dctx->skipContentChecksum))
1999
0
                    XXH32_update(&(dctx->xxh), dstPtr, (size_t)decodedSize);
2000
0
                if (dctx->frameInfo.contentSize)
2001
0
                    dctx->frameRemainingSize -= (size_t)decodedSize;
2002
2003
                /* dictionary management */
2004
0
                if (dctx->frameInfo.blockMode==LZ4F_blockLinked) {
2005
0
                    LZ4F_updateDict(dctx, dstPtr, (size_t)decodedSize, dstStart, 0);
2006
0
                }
2007
2008
0
                dstPtr += decodedSize;
2009
0
                dctx->dStage = dstage_getBlockHeader;  /* end of block, let's get another one */
2010
0
                break;
2011
0
            }
2012
2013
            /* not enough place into dst : decode into tmpOut */
2014
2015
            /* manage dictionary */
2016
0
            if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {
2017
0
                if (dctx->dict == dctx->tmpOutBuffer) {
2018
                    /* truncate dictionary to 64 KB if too big */
2019
0
                    if (dctx->dictSize > 128 KB) {
2020
0
                        memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB);
2021
0
                        dctx->dictSize = 64 KB;
2022
0
                    }
2023
0
                    dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize;
2024
0
                } else {  /* dict not within tmpOut */
2025
0
                    size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB);
2026
0
                    dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace;
2027
0
            }   }
2028
2029
            /* Decode block into tmpOut */
2030
0
            {   const char* dict = (const char*)dctx->dict;
2031
0
                size_t dictSize = dctx->dictSize;
2032
0
                int decodedSize;
2033
0
                if (dict && dictSize > 1 GB) {
2034
                    /* the dictSize param is an int, avoid truncation / sign issues */
2035
0
                    dict += dictSize - 64 KB;
2036
0
                    dictSize = 64 KB;
2037
0
                }
2038
0
                decodedSize = LZ4_decompress_safe_usingDict(
2039
0
                        (const char*)selectedIn, (char*)dctx->tmpOut,
2040
0
                        (int)dctx->tmpInTarget, (int)dctx->maxBlockSize,
2041
0
                        dict, (int)dictSize);
2042
0
                RETURN_ERROR_IF(decodedSize < 0, decompressionFailed);
2043
0
                if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum)
2044
0
                    XXH32_update(&(dctx->xxh), dctx->tmpOut, (size_t)decodedSize);
2045
0
                if (dctx->frameInfo.contentSize)
2046
0
                    dctx->frameRemainingSize -= (size_t)decodedSize;
2047
0
                dctx->tmpOutSize = (size_t)decodedSize;
2048
0
                dctx->tmpOutStart = 0;
2049
0
                dctx->dStage = dstage_flushOut;
2050
0
            }
2051
            /* fall-through */
2052
2053
0
        case dstage_flushOut:  /* flush decoded data from tmpOut to dstBuffer */
2054
0
            DEBUGLOG(6, "dstage_flushOut");
2055
0
            if (dstPtr != NULL) {
2056
0
                size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr));
2057
0
                memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy);
2058
2059
                /* dictionary management */
2060
0
                if (dctx->frameInfo.blockMode == LZ4F_blockLinked)
2061
0
                    LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1 /*withinTmp*/);
2062
2063
0
                dctx->tmpOutStart += sizeToCopy;
2064
0
                dstPtr += sizeToCopy;
2065
0
            }
2066
0
            if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */
2067
0
                dctx->dStage = dstage_getBlockHeader;  /* get next block */
2068
0
                break;
2069
0
            }
2070
            /* could not flush everything : stop there, just request a block header */
2071
0
            doAnotherStage = 0;
2072
0
            nextSrcSizeHint = BHSize;
2073
0
            break;
2074
2075
0
        case dstage_getSuffix:
2076
0
            RETURN_ERROR_IF(dctx->frameRemainingSize, frameSize_wrong);   /* incorrect frame size decoded */
2077
0
            if (!dctx->frameInfo.contentChecksumFlag) {  /* no checksum, frame is completed */
2078
0
                nextSrcSizeHint = 0;
2079
0
                LZ4F_resetDecompressionContext(dctx);
2080
0
                doAnotherStage = 0;
2081
0
                break;
2082
0
            }
2083
0
            if ((srcEnd - srcPtr) < 4) {  /* not enough size for entire CRC */
2084
0
                dctx->tmpInSize = 0;
2085
0
                dctx->dStage = dstage_storeSuffix;
2086
0
            } else {
2087
0
                selectedIn = srcPtr;
2088
0
                srcPtr += 4;
2089
0
            }
2090
2091
0
            if (dctx->dStage == dstage_storeSuffix)   /* can be skipped */
2092
0
        case dstage_storeSuffix:
2093
0
            {   size_t const remainingInput = (size_t)(srcEnd - srcPtr);
2094
0
                size_t const wantedData = 4 - dctx->tmpInSize;
2095
0
                size_t const sizeToCopy = MIN(wantedData, remainingInput);
2096
0
                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);
2097
0
                srcPtr += sizeToCopy;
2098
0
                dctx->tmpInSize += sizeToCopy;
2099
0
                if (dctx->tmpInSize < 4) { /* not enough input to read complete suffix */
2100
0
                    nextSrcSizeHint = 4 - dctx->tmpInSize;
2101
0
                    doAnotherStage=0;
2102
0
                    break;
2103
0
                }
2104
0
                selectedIn = dctx->tmpIn;
2105
0
            }   /* if (dctx->dStage == dstage_storeSuffix) */
2106
2107
        /* case dstage_checkSuffix: */   /* no direct entry, avoid initialization risks */
2108
0
            if (!dctx->skipContentChecksum) {
2109
0
                U32 const readCRC = LZ4F_readLE32(selectedIn);
2110
0
                U32 const resultCRC = XXH32_digest(&(dctx->xxh));
2111
0
                DEBUGLOG(4, "frame checksum: stored 0x%0X vs 0x%0X processed", readCRC, resultCRC);
2112
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2113
                RETURN_ERROR_IF(readCRC != resultCRC, contentChecksum_invalid);
2114
#else
2115
0
                (void)readCRC;
2116
0
                (void)resultCRC;
2117
0
#endif
2118
0
            }
2119
0
            nextSrcSizeHint = 0;
2120
0
            LZ4F_resetDecompressionContext(dctx);
2121
0
            doAnotherStage = 0;
2122
0
            break;
2123
2124
0
        case dstage_getSFrameSize:
2125
0
            if ((srcEnd - srcPtr) >= 4) {
2126
0
                selectedIn = srcPtr;
2127
0
                srcPtr += 4;
2128
0
            } else {
2129
                /* not enough input to read cBlockSize field */
2130
0
                dctx->tmpInSize = 4;
2131
0
                dctx->tmpInTarget = 8;
2132
0
                dctx->dStage = dstage_storeSFrameSize;
2133
0
            }
2134
2135
0
            if (dctx->dStage == dstage_storeSFrameSize)
2136
0
        case dstage_storeSFrameSize:
2137
0
            {   size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize,
2138
0
                                             (size_t)(srcEnd - srcPtr) );
2139
0
                memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);
2140
0
                srcPtr += sizeToCopy;
2141
0
                dctx->tmpInSize += sizeToCopy;
2142
0
                if (dctx->tmpInSize < dctx->tmpInTarget) {
2143
                    /* not enough input to get full sBlockSize; wait for more */
2144
0
                    nextSrcSizeHint = dctx->tmpInTarget - dctx->tmpInSize;
2145
0
                    doAnotherStage = 0;
2146
0
                    break;
2147
0
                }
2148
0
                selectedIn = dctx->header + 4;
2149
0
            }   /* if (dctx->dStage == dstage_storeSFrameSize) */
2150
2151
        /* case dstage_decodeSFrameSize: */   /* no direct entry */
2152
0
            {   size_t const SFrameSize = LZ4F_readLE32(selectedIn);
2153
0
                dctx->frameInfo.contentSize = SFrameSize;
2154
0
                dctx->tmpInTarget = SFrameSize;
2155
0
                dctx->dStage = dstage_skipSkippable;
2156
0
                break;
2157
0
            }
2158
2159
0
        case dstage_skipSkippable:
2160
0
            {   size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr));
2161
0
                srcPtr += skipSize;
2162
0
                dctx->tmpInTarget -= skipSize;
2163
0
                doAnotherStage = 0;
2164
0
                nextSrcSizeHint = dctx->tmpInTarget;
2165
0
                if (nextSrcSizeHint) break;  /* still more to skip */
2166
                /* frame fully skipped : prepare context for a new frame */
2167
0
                LZ4F_resetDecompressionContext(dctx);
2168
0
                break;
2169
0
            }
2170
0
        }   /* switch (dctx->dStage) */
2171
0
    }   /* while (doAnotherStage) */
2172
2173
    /* preserve history within tmpOut whenever necessary */
2174
0
    LZ4F_STATIC_ASSERT((unsigned)dstage_init == 2);
2175
0
    if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked)  /* next block will use up to 64KB from previous ones */
2176
0
      && (dctx->dict != dctx->tmpOutBuffer)             /* dictionary is not already within tmp */
2177
0
      && (dctx->dict != NULL)                           /* dictionary exists */
2178
0
      && (!decompressOptionsPtr->stableDst)             /* cannot rely on dst data to remain there for next call */
2179
0
      && ((unsigned)(dctx->dStage)-2 < (unsigned)(dstage_getSuffix)-2) )  /* valid stages : [init ... getSuffix[ */
2180
0
    {
2181
0
        if (dctx->dStage == dstage_flushOut) {
2182
0
            size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer);
2183
0
            size_t copySize = 64 KB - dctx->tmpOutSize;
2184
0
            const BYTE* oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart;
2185
0
            if (dctx->tmpOutSize > 64 KB) copySize = 0;
2186
0
            if (copySize > preserveSize) copySize = preserveSize;
2187
0
            assert(dctx->tmpOutBuffer != NULL);
2188
2189
0
            memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
2190
2191
0
            dctx->dict = dctx->tmpOutBuffer;
2192
0
            dctx->dictSize = preserveSize + dctx->tmpOutStart;
2193
0
        } else {
2194
0
            const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize;
2195
0
            size_t const newDictSize = MIN(dctx->dictSize, 64 KB);
2196
2197
0
            memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);
2198
2199
0
            dctx->dict = dctx->tmpOutBuffer;
2200
0
            dctx->dictSize = newDictSize;
2201
0
            dctx->tmpOut = dctx->tmpOutBuffer + newDictSize;
2202
0
        }
2203
0
    }
2204
2205
0
    *srcSizePtr = (size_t)(srcPtr - srcStart);
2206
0
    *dstSizePtr = (size_t)(dstPtr - dstStart);
2207
0
    return nextSrcSizeHint;
2208
0
}
2209
2210
/*! LZ4F_decompress_usingDict() :
2211
 *  Same as LZ4F_decompress(), using a predefined dictionary.
2212
 *  Dictionary is used "in place", without any preprocessing.
2213
 *  It must remain accessible throughout the entire frame decoding.
2214
 */
2215
size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx,
2216
                       void* dstBuffer, size_t* dstSizePtr,
2217
                       const void* srcBuffer, size_t* srcSizePtr,
2218
                       const void* dict, size_t dictSize,
2219
                       const LZ4F_decompressOptions_t* decompressOptionsPtr)
2220
0
{
2221
0
    if (dctx->dStage <= dstage_init) {
2222
0
        dctx->dict = (const BYTE*)dict;
2223
0
        dctx->dictSize = dictSize;
2224
0
    }
2225
0
    return LZ4F_decompress(dctx, dstBuffer, dstSizePtr,
2226
0
                           srcBuffer, srcSizePtr,
2227
0
                           decompressOptionsPtr);
2228
0
}
2229
2230
/*! LZ4F_resumeFrame() :
2231
 *  see lz4frame.h (static section) */
2232
size_t LZ4F_resumeFrame(LZ4F_dctx* dctx, const LZ4F_frameInfo_t* frameInfo,
2233
                        unsigned long long decodedPos,
2234
                        const void* dict, size_t dictSize)
2235
0
{
2236
0
    assert(dctx != NULL);
2237
0
    RETURN_ERROR_IF(frameInfo == NULL, parameter_null);
2238
0
    RETURN_ERROR_IF(dict == NULL && dictSize > 0, parameter_null);
2239
0
    RETURN_ERROR_IF(frameInfo->frameType != LZ4F_frame, frameType_unknown);
2240
0
    RETURN_ERROR_IF(frameInfo->blockSizeID < LZ4F_max64KB || frameInfo->blockSizeID > LZ4F_max4MB, maxBlockSize_invalid);
2241
0
    RETURN_ERROR_IF((unsigned)frameInfo->blockMode > 1, blockMode_invalid);
2242
0
    RETURN_ERROR_IF((unsigned)frameInfo->blockChecksumFlag > 1, parameter_invalid);
2243
0
    RETURN_ERROR_IF((unsigned)frameInfo->contentChecksumFlag > 1, parameter_invalid);
2244
0
    RETURN_ERROR_IF(frameInfo->contentSize && decodedPos > frameInfo->contentSize, frameSize_wrong);
2245
2246
0
    LZ4F_resetDecompressionContext(dctx);
2247
0
    dctx->frameInfo = *frameInfo;
2248
0
    dctx->maxBlockSize = LZ4F_getBlockSize(frameInfo->blockSizeID);
2249
0
    if (frameInfo->contentSize)
2250
0
        dctx->frameRemainingSize = frameInfo->contentSize - decodedPos;
2251
0
    dctx->dict = (const BYTE*)dict;
2252
0
    dctx->dictSize = dictSize;
2253
0
    dctx->skipContentChecksum = 1;   /* content checksum covers the whole frame : can't be verified */
2254
0
    dctx->dStage = dstage_init;
2255
0
    return 0;
2256
0
}