Coverage Report

Created: 2026-12-01 07:03

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
 * LZ4F_MULTITHREAD :
67
 * Enables multi-threaded compression, requested with LZ4F_preferences_t.nbWorkers.
68
 * Requires <pthread.h> on POSIX systems (compile and link with -pthread), or Windows threads.
69
 * Default is 0 : no threading code is compiled,
70
 * and multi-threaded requests are served serially by the calling thread, producing the same output.
71
 */
72
#ifndef LZ4F_MULTITHREAD
73
#  define LZ4F_MULTITHREAD 0
74
#endif
75
#if defined(LZ4_FREESTANDING) && (LZ4_FREESTANDING == 1)
76
#  undef  LZ4F_MULTITHREAD
77
#  define LZ4F_MULTITHREAD 0
78
#endif
79
#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)   /* MinGW.org, unlike mingw-w64, lacks Windows Vista API (condition variables) */
80
#  undef  LZ4F_MULTITHREAD
81
#  define LZ4F_MULTITHREAD 0
82
#endif
83
84
85
/*-************************************
86
*  Library declarations
87
**************************************/
88
#define LZ4F_STATIC_LINKING_ONLY
89
#include "lz4frame.h"
90
#define LZ4_STATIC_LINKING_ONLY
91
#include "lz4.h"
92
#define LZ4_HC_STATIC_LINKING_ONLY
93
#include "lz4hc.h"
94
#define XXH_STATIC_LINKING_ONLY
95
#include "xxhash.h"
96
97
98
/*-************************************
99
*  Memory routines
100
**************************************/
101
/*
102
 * Default allocation functions, employed when LZ4F_CustomMem doesn't define them :
103
 * malloc(), calloc() and free(), or LZ4_malloc(), LZ4_calloc() and LZ4_free()
104
 * when lz4 is compiled with LZ4_USER_MEMORY_FUNCTIONS (see lz4.c).
105
 * None with LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION (implied by LZ4_FREESTANDING) : allocation then fails without LZ4F_CustomMem.
106
**/
107
108
#if !LZ4_FREESTANDING
109
#  include <string.h>   /* memset, memcpy, memmove */
110
#endif
111
/* defined by the user with LZ4_FREESTANDING, or by lz4.c when sources are coalesced */
112
#ifndef LZ4_memcpy
113
311k
#  define LZ4_memcpy(d,s,n)  memcpy((d),(s),(n))
114
#endif
115
#ifndef LZ4_memmove
116
0
#  define LZ4_memmove(d,s,n) memmove((d),(s),(n))
117
#endif
118
#ifndef LZ4_memset
119
280k
#  define LZ4_memset(p,v,n)  memset((p),(v),(n))
120
#endif
121
#ifndef LZ4_SRC_INCLUDED  /* avoid redefinition when sources are coalesced */
122
280k
#  define MEM_INIT(p,v,s)   LZ4_memset((p),(v),(s))
123
#endif
124
125
#ifndef LZ4_SRC_INCLUDED   /* avoid redefinition when sources are coalesced */
126
#  if defined(LZ4_USER_MEMORY_FUNCTIONS)
127
     void* LZ4_malloc(size_t s);
128
     void* LZ4_calloc(size_t n, size_t s);
129
     void  LZ4_free(void* p);
130
#    define ALLOC(s)          LZ4_malloc(s)
131
#    define ALLOC_AND_ZERO(s) LZ4_calloc(1,(s))
132
#    define FREEMEM(p)        LZ4_free(p)
133
#  elif defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
134
#    define ALLOC(s)          NULL   /* no default allocator */
135
#    define ALLOC_AND_ZERO(s) NULL
136
#    define FREEMEM(p)        ((void)(p))
137
#  else
138
#    include <stdlib.h>   /* malloc, calloc, free */
139
66.8k
#    define ALLOC(s)          malloc(s)
140
47.0k
#    define ALLOC_AND_ZERO(s) calloc(1,(s))
141
113k
#    define FREEMEM(p)        free(p)
142
#  endif
143
#endif
144
145
static void* LZ4F_calloc(size_t s, LZ4F_CustomMem cmem)
146
47.0k
{
147
    /* custom calloc defined : use it */
148
47.0k
    if (cmem.customCalloc != NULL) {
149
0
        return cmem.customCalloc(cmem.opaqueState, s);
150
0
    }
151
    /* nothing defined : use default calloc(), if any */
152
47.0k
    if (cmem.customAlloc == NULL) {
153
47.0k
        return ALLOC_AND_ZERO(s);
154
47.0k
    }
155
    /* only custom alloc defined : use it, and combine it with LZ4_memset() */
156
0
    {   void* const p = cmem.customAlloc(cmem.opaqueState, s);
157
0
        if (p != NULL) MEM_INIT(p, 0, s);
158
0
        return p;
159
47.0k
}   }
160
161
static void* LZ4F_malloc(size_t s, LZ4F_CustomMem cmem)
162
66.8k
{
163
    /* custom malloc defined : use it */
164
66.8k
    if (cmem.customAlloc != NULL) {
165
0
        return cmem.customAlloc(cmem.opaqueState, s);
166
0
    }
167
    /* nothing defined : use default malloc(), if any */
168
66.8k
    return ALLOC(s);
169
66.8k
}
170
171
static void LZ4F_free(void* p, LZ4F_CustomMem cmem)
172
254k
{
173
254k
    if (p == NULL) return;
174
113k
    if (cmem.customFree != NULL) {
175
        /* custom allocation defined : use it */
176
0
        cmem.customFree(cmem.opaqueState, p);
177
0
        return;
178
0
    }
179
    /* nothing defined : use default free(), if any */
180
113k
    FREEMEM(p);
181
113k
}
182
183
184
/*-************************************
185
*  Debug
186
**************************************/
187
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)
188
#  include <assert.h>
189
#else
190
#  ifndef assert
191
#    define assert(condition) ((void)0)
192
#  endif
193
#endif
194
195
342k
#define LZ4F_STATIC_ASSERT(c)    { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */
196
197
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) && !defined(DEBUGLOG)
198
#  include <stdio.h>
199
static int g_debuglog_enable = 1;
200
#  define DEBUGLOG(l, ...) {                                  \
201
                if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
202
                    fprintf(stderr, __FILE__ " %i: ", __LINE__ );  \
203
                    fprintf(stderr, __VA_ARGS__);             \
204
                    fprintf(stderr, " \n");                   \
205
            }   }
206
#endif
207
#ifndef DEBUGLOG   /* may already be defined, e.g. by lz4.c in an amalgamated build */
208
792k
#  define DEBUGLOG(l, ...)      {}    /* disabled */
209
#endif
210
211
212
/*-************************************
213
*  Basic Types
214
**************************************/
215
#ifndef LZ4_SRC_INCLUDED
216
# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
217
#   include <stdint.h>
218
    typedef  uint8_t BYTE;
219
    typedef uint16_t U16;
220
    typedef uint32_t U32;
221
    typedef  int32_t S32;
222
    typedef uint64_t U64;
223
# else
224
    typedef unsigned char      BYTE;
225
    typedef unsigned short     U16;
226
    typedef unsigned int       U32;
227
    typedef   signed int       S32;
228
    typedef unsigned long long U64;
229
# endif
230
#endif
231
232
233
/* unoptimized version; solves endianness & alignment issues */
234
static U32 LZ4F_readLE32 (const void* src)
235
241k
{
236
241k
    const BYTE* const srcPtr = (const BYTE*)src;
237
241k
    U32 value32 = srcPtr[0];
238
241k
    value32 |= ((U32)srcPtr[1])<< 8;
239
241k
    value32 |= ((U32)srcPtr[2])<<16;
240
241k
    value32 |= ((U32)srcPtr[3])<<24;
241
241k
    return value32;
242
241k
}
243
244
static void LZ4F_writeLE32 (void* dst, U32 value32)
245
80.4k
{
246
80.4k
    BYTE* const dstPtr = (BYTE*)dst;
247
80.4k
    dstPtr[0] = (BYTE)value32;
248
80.4k
    dstPtr[1] = (BYTE)(value32 >> 8);
249
80.4k
    dstPtr[2] = (BYTE)(value32 >> 16);
250
80.4k
    dstPtr[3] = (BYTE)(value32 >> 24);
251
80.4k
}
252
253
static U64 LZ4F_readLE64 (const void* src)
254
1.37k
{
255
1.37k
    const BYTE* const srcPtr = (const BYTE*)src;
256
1.37k
    U64 value64 = srcPtr[0];
257
1.37k
    value64 |= ((U64)srcPtr[1]<<8);
258
1.37k
    value64 |= ((U64)srcPtr[2]<<16);
259
1.37k
    value64 |= ((U64)srcPtr[3]<<24);
260
1.37k
    value64 |= ((U64)srcPtr[4]<<32);
261
1.37k
    value64 |= ((U64)srcPtr[5]<<40);
262
1.37k
    value64 |= ((U64)srcPtr[6]<<48);
263
1.37k
    value64 |= ((U64)srcPtr[7]<<56);
264
1.37k
    return value64;
265
1.37k
}
266
267
static void LZ4F_writeLE64 (void* dst, U64 value64)
268
0
{
269
0
    BYTE* const dstPtr = (BYTE*)dst;
270
0
    dstPtr[0] = (BYTE)value64;
271
0
    dstPtr[1] = (BYTE)(value64 >> 8);
272
0
    dstPtr[2] = (BYTE)(value64 >> 16);
273
0
    dstPtr[3] = (BYTE)(value64 >> 24);
274
0
    dstPtr[4] = (BYTE)(value64 >> 32);
275
0
    dstPtr[5] = (BYTE)(value64 >> 40);
276
0
    dstPtr[6] = (BYTE)(value64 >> 48);
277
0
    dstPtr[7] = (BYTE)(value64 >> 56);
278
0
}
279
280
281
/*-************************************
282
*  Constants
283
**************************************/
284
#ifndef LZ4_SRC_INCLUDED   /* avoid double definition */
285
406k
#  define KB *(1<<10)
286
232k
#  define MB *(1<<20)
287
22.5k
#  define GB *(1<<30)
288
#endif
289
290
418k
#define _1BIT  0x01
291
61.6k
#define _2BITS 0x03
292
49.4k
#define _3BITS 0x07
293
33.3k
#define _4BITS 0x0F
294
#define _8BITS 0xFF
295
296
72.3k
#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
297
23.4k
#define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB
298
299
static const size_t minFHSize = LZ4F_HEADER_SIZE_MIN;   /*  7 */
300
static const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX;   /* 19 */
301
static const size_t BHSize = LZ4F_BLOCK_HEADER_SIZE;  /* block header : size, and compress flag */
302
static const size_t BFSize = LZ4F_BLOCK_CHECKSUM_SIZE;  /* block footer : checksum (optional) */
303
304
305
/*-************************************
306
*  Structures and local types
307
**************************************/
308
309
typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_BlockCompressMode_e;
310
typedef enum { ctxNone, ctxFast, ctxHC } LZ4F_CtxType_e;
311
312
struct LZ4F_CDict_s {
313
    LZ4F_CustomMem cmem;
314
    void* dictContent;
315
    LZ4_stream_t* fastCtx;
316
    LZ4_streamHC_t* HCCtx;
317
}; /* typedef'd to LZ4F_CDict within lz4frame_static.h */
318
319
typedef struct LZ4F_cctx_s
320
{
321
    LZ4F_CustomMem cmem;
322
    LZ4F_preferences_t prefs;
323
    U32    version;
324
    U32    cStage;     /* 0 : compression uninitialized ; 1 : initialized, can compress ; 2 : frame ending (LZ4F_compressEnd() in progress) */
325
    const LZ4F_CDict* cdict;
326
    size_t maxBlockSize;
327
    size_t tmpBuffCapacity;
328
    BYTE*  tmpBuff;    /* internal buffer, for streaming */
329
    BYTE*  tmpIn;      /* starting position of data compress within internal buffer (>= tmpBuff) */
330
    size_t tmpInSize;  /* amount of data to compress after tmpIn */
331
    U64    totalInSize;
332
    XXH32_state_t xxh;
333
    void*  lz4CtxPtr;
334
    U16    lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
335
    U16    lz4CtxType;  /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
336
    LZ4F_BlockCompressMode_e  blockCompressMode;
337
    struct LZ4F_mtCtx_s* mt;   /* multi-threading resources, kept across frames; NULL when never needed */
338
    U32    mtActive;   /* current frame is cut into jobs (prefs.nbWorkers >= 1) */
339
    /* LZ4F_flush() and LZ4F_compressEnd() : output not fitting into dstBuffer yet, see LZ4F_emitPending() */
340
    U32    flushStage; /* 0 : none ; 1 : flush point set, emitting ; LZ4F_compressEnd() only : 2 : footer ; 3 : completed */
341
    const BYTE* pending;   /* remaining output of a block (stageBuff), or of the frame footer */
342
    size_t pendingSize;
343
    BYTE*  stageBuff;  /* a block not fitting into dstBuffer : allocated on first need */
344
    size_t stageCapacity;
345
    BYTE   footer[8];  /* endMark + optional content checksum */
346
    /* raw dictionary (LZ4F_compressBegin_usingDict()) digested for current frame, then employed as a CDict */
347
    struct LZ4F_CDict_s rawDict;   /* fastCtx or HCCtx, the other one NULL ; no dictContent : not owned */
348
    LZ4_stream_t*   rawDictFast;   /* allocated on first need */
349
    LZ4_streamHC_t* rawDictHC;     /* allocated on first need */
350
} LZ4F_cctx_t;
351
352
/* multi-threaded compression, see LZ4F_preferences_t.nbWorkers */
353
typedef struct LZ4F_mtCtx_s LZ4F_mtCtx_t;
354
static void   LZ4F_mt_abort(LZ4F_mtCtx_t* mt);
355
static size_t LZ4F_mt_begin(LZ4F_cctx_t* cctx);
356
static void   LZ4F_mt_free(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem);
357
static size_t LZ4F_mt_sizeof(const LZ4F_mtCtx_t* mt);
358
359
360
/*-************************************
361
*  Error management
362
**************************************/
363
#define LZ4F_GENERATE_STRING(STRING) #STRING,
364
static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };
365
366
367
unsigned LZ4F_isError(LZ4F_errorCode_t code)
368
952k
{
369
952k
    return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode));
370
952k
}
371
372
const char* LZ4F_getErrorName(LZ4F_errorCode_t code)
373
0
{
374
0
    static const char* codeError = "Unspecified error code";
375
0
    if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];
376
0
    return codeError;
377
0
}
378
379
LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult)
380
0
{
381
0
    if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError;
382
0
    return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult);
383
0
}
384
385
static LZ4F_errorCode_t LZ4F_returnErrorCode(LZ4F_errorCodes code)
386
16.6k
{
387
    /* A compilation error here means sizeof(ptrdiff_t) is not large enough */
388
16.6k
    LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t));
389
16.6k
    return (LZ4F_errorCode_t)-(ptrdiff_t)code;
390
16.6k
}
391
392
15.7k
#define RETURN_ERROR(e) return LZ4F_returnErrorCode(LZ4F_ERROR_ ## e)
393
394
548k
#define RETURN_ERROR_IF(c,e) do {  \
395
622k
        if (c) {                   \
396
2.62k
            DEBUGLOG(3, "Error: " #c); \
397
2.62k
            RETURN_ERROR(e);       \
398
2.62k
        }                          \
399
548k
    } while (0)
400
401
/* note : @r is evaluated only once, so it can be an expression with side effects */
402
61.1k
#define FORWARD_IF_ERROR(r) do {                     \
403
61.1k
        size_t const err_code = (r);                 \
404
61.1k
        if (LZ4F_isError(err_code)) return err_code; \
405
61.1k
    } while (0)
406
407
/* a failed operation invalidates the frame, and discards its jobs (multi-threaded mode) :
408
 * next operations fail with compressionState_uninitialized, until LZ4F_compressBegin().
409
 * Idempotent : also employed to forward errors of functions which already invalidated the frame */
410
static void LZ4F_invalidateFrame(LZ4F_cctx_t* cctx)
411
15.6k
{
412
15.6k
    if (cctx->mtActive) LZ4F_mt_abort(cctx->mt);
413
15.6k
    cctx->cStage = 0;
414
15.6k
}
415
416
71.0k
#define FORWARD_IF_ERROR_INVALIDATE(r, cctx) do { \
417
71.0k
        size_t const err_code = (r);               \
418
71.0k
        if (LZ4F_isError(err_code)) {              \
419
0
            LZ4F_invalidateFrame(cctx);            \
420
0
            return err_code;                       \
421
0
        }                                          \
422
71.0k
    } while (0)
423
424
0
unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; }
425
426
0
int LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; }
427
428
size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID)
429
116k
{
430
116k
    static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };
431
432
116k
    if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
433
116k
    if (blockSizeID < LZ4F_max64KB || blockSizeID > LZ4F_max4MB)
434
0
        RETURN_ERROR(maxBlockSize_invalid);
435
116k
    {   int const blockSizeIdx = (int)blockSizeID - (int)LZ4F_max64KB;
436
116k
        return blockSizes[blockSizeIdx];
437
116k
}   }
438
439
/*-************************************
440
*  Private functions
441
**************************************/
442
#undef MIN
443
389k
#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
444
445
static BYTE LZ4F_headerChecksum (const void* header, size_t length)
446
15.6k
{
447
15.6k
    U32 const xxh = XXH32(header, length, 0);
448
15.6k
    return (BYTE)(xxh >> 8);
449
15.6k
}
450
451
452
/*-************************************
453
*  Simple-pass compression functions
454
**************************************/
455
static LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID,
456
                                           const size_t srcSize)
457
0
{
458
0
    LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB;
459
0
    size_t maxBlockSize = 64 KB;
460
0
    while (requestedBSID > proposedBSID) {
461
0
        if (srcSize <= maxBlockSize)
462
0
            return proposedBSID;
463
0
        proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1);
464
0
        maxBlockSize <<= 2;
465
0
    }
466
0
    return requestedBSID;
467
0
}
468
469
/*! LZ4F_compressBound_autoFlush() :
470
 *  worst case : @srcSize as blocks stored uncompressed, the last one partial, then the frame footer.
471
 *  Also bounds one-shot compression (LZ4F_compressFrameBound()), which compresses all its input at once.
472
 *  When srcSize==0, it bounds LZ4F_flush() and LZ4F_compressEnd() operations.
473
 */
474
static size_t LZ4F_compressBound_autoFlush(size_t srcSize, const LZ4F_preferences_t* prefsPtr)
475
6.54k
{
476
6.54k
    size_t const blockSize = LZ4F_getBlockSize(prefsPtr->frameInfo.blockSizeID);
477
6.54k
    size_t const nbFullBlocks = srcSize / blockSize;
478
6.54k
    size_t const lastBlockSize = srcSize & (blockSize-1);
479
6.54k
    size_t const nbBlocks = nbFullBlocks + (lastBlockSize>0);
480
6.54k
    size_t const blockCRCSize = BFSize * prefsPtr->frameInfo.blockChecksumFlag;
481
6.54k
    size_t const frameEnd = BHSize + (prefsPtr->frameInfo.contentChecksumFlag*BFSize);
482
6.54k
    assert(prefsPtr->autoFlush);
483
6.54k
    return ((BHSize + blockCRCSize) * nbBlocks) +
484
6.54k
           (blockSize * nbFullBlocks) + lastBlockSize + frameEnd;
485
6.54k
}
486
487
size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
488
0
{
489
0
    LZ4F_preferences_t prefs;
490
0
    size_t const headerSize = maxFHSize;      /* max header size, including optional fields */
491
492
0
    if (preferencesPtr!=NULL) prefs = *preferencesPtr;
493
0
    else MEM_INIT(&prefs, 0, sizeof(prefs));
494
0
    prefs.autoFlush = 1;
495
496
0
    return headerSize + LZ4F_compressBound_autoFlush(srcSize, &prefs);
497
0
}
498
499
500
/*-************************************
501
*  Multi-threading parameters
502
**************************************/
503
/* see LZ4F_preferences_t.nbWorkers */
504
/* sanity limit (ex: uninitialized preferences) ; on 32-bit systems, keeps LZ4F_compressBound() within address space */
505
#ifndef LZ4F_NBWORKERS_MAX
506
#  define LZ4F_NBWORKERS_MAX ((sizeof(size_t) >= 8) ? 1024u : 128u)
507
#endif
508
0
#define LZ4F_MT_PREFIX_SIZE (64 KB)   /* history employed by linked blocks */
509
510
/* Job size :
511
 * Input is cut into jobs at fixed positions of the frame's content (restarting after each flush) :
512
 * a whole nb of blocks, up to LZ4F_MT_JOBSIZE (lz4frame.h), or a single block when larger.
513
 * With linked blocks, each job restarts the stream, using previous 64 KB as dictionary.
514
 * Job boundaries are therefore part of the output definition : changing this size changes output of linked blocks.
515
 * With independent blocks, output only depends on block boundaries, not on job boundaries.
516
 * Small jobs balance load among threads, engage multi-threading on smaller inputs, and lower latency. */
517
static size_t LZ4F_mtJobSize(size_t blockSize)
518
0
{
519
0
    if (blockSize >= LZ4F_MT_JOBSIZE) return blockSize;
520
0
    return (LZ4F_MT_JOBSIZE / blockSize) * blockSize;   /* whole nb of blocks */
521
0
}
522
523
unsigned LZ4F_getMaxNbWorkers(void)
524
0
{
525
#if LZ4F_MULTITHREAD
526
    return LZ4F_NBWORKERS_MAX;
527
#else
528
0
    return 0;
529
0
#endif
530
0
}
531
532
/* frames are cut into jobs only with valid block modes, see LZ4F_mt_begin() */
533
static int LZ4F_mtEligible(const LZ4F_preferences_t* prefs)
534
24.8k
{
535
24.8k
    if (prefs->nbWorkers == 0) return 0;
536
    /* linked blocks : jobs define the output, so frames are cut into jobs even without threads */
537
0
    if (prefs->frameInfo.blockMode == LZ4F_blockLinked) return 1;
538
#if LZ4F_MULTITHREAD
539
    return (prefs->frameInfo.blockMode == LZ4F_blockIndependent);
540
#else
541
    /* independent blocks : the output is identical to single-threaded mode, which is faster without threads */
542
0
    return 0;
543
0
#endif
544
0
}
545
546
/* nb of job slots for @nbThreads worker threads :
547
 * one being filled, one per worker, plus room for jobs completed out of order,
548
 * since their outputs are emitted in order */
549
#ifndef LZ4F_MT_SLOTS_PER_THREAD
550
0
#  define LZ4F_MT_SLOTS_PER_THREAD 2
551
#endif
552
0
#define LZ4F_MT_NBSLOTS(nbThreads) ((size_t)(nbThreads) * LZ4F_MT_SLOTS_PER_THREAD + 1)
553
#ifndef LZ4F_MT_EXTRA_INBUFFS
554
0
#  define LZ4F_MT_EXTRA_INBUFFS 1
555
#endif
556
557
558
/*! LZ4F_blocksBound() :
559
 * @return worst case size of LZ4F_compressBlocks_internal() output */
560
static size_t LZ4F_blocksBound(size_t srcSize, size_t blockSize, LZ4F_blockChecksum_t crcFlag)
561
0
{
562
0
    size_t const nbBlocks = (srcSize + blockSize - 1) / blockSize;
563
0
    return srcSize + nbBlocks * (BHSize + (size_t)crcFlag * BFSize);
564
0
}
565
566
/*! LZ4F_mtCompressBound() :
567
 *  LZ4F_compressBound() for frames cut into jobs, without autoFlush : the job is the unit, instead of the block.
568
 *  LZ4F_compressUpdate() defers completed jobs not fitting into dstBuffer :
569
 *  output is only required to start a job while all slots are busy (the oldest one),
570
 *  and an invocation starts at most ceil(srcSize / jobSize) jobs, since the job being filled holds < jobSize bytes.
571
 *  @srcSize == 0 : LZ4F_flush() and LZ4F_compressEnd() emit at least one whole job per invocation, then the frame footer.
572
 *  The frame footer is always included, so that the bound grows with @srcSize. */
573
static size_t LZ4F_mtCompressBound(size_t srcSize, const LZ4F_preferences_t* prefs)
574
0
{
575
0
    size_t const bs = LZ4F_getBlockSize(prefs->frameInfo.blockSizeID);
576
0
    size_t const blockSize = LZ4F_isError(bs) ? 4 MB : bs;
577
0
    size_t const jobSize = LZ4F_mtJobSize(blockSize);
578
0
    size_t const nbJobs = srcSize ? (srcSize / jobSize) + ((srcSize % jobSize) != 0) : 1;
579
0
    size_t const frameEnd = BHSize + (prefs->frameInfo.contentChecksumFlag*BFSize);
580
0
    return nbJobs * LZ4F_blocksBound(jobSize, blockSize, prefs->frameInfo.blockChecksumFlag) + frameEnd;
581
0
}
582
583
/*! LZ4F_compressFrame_usingCDict() :
584
 *  Compress srcBuffer using a dictionary, in a single step.
585
 *  cdict can be NULL, in which case, no dictionary is used.
586
 *  Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
587
 *  Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit.
588
 *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,
589
 *  however, it's the only way to provide a dictID, so it's not recommended.
590
 * @return : number of bytes written into dstBuffer,
591
 *           or an error code if it fails (can be tested using LZ4F_isError())
592
 */
593
size_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
594
                                     void* dstBuffer, size_t dstCapacity,
595
                               const void* srcBuffer, size_t srcSize,
596
                               const LZ4F_CDict* cdict,
597
                               const LZ4F_preferences_t* preferencesPtr)
598
0
{
599
0
    LZ4F_preferences_t prefs;
600
0
    LZ4F_compressOptions_t options;
601
0
    BYTE* const dstStart = (BYTE*) dstBuffer;
602
0
    BYTE* dstPtr = dstStart;
603
0
    BYTE* const dstEnd = dstStart + dstCapacity;
604
605
0
    DEBUGLOG(4, "LZ4F_compressFrame_usingCDict (srcSize=%u)", (unsigned)srcSize);
606
0
    if (preferencesPtr!=NULL)
607
0
        prefs = *preferencesPtr;
608
0
    else
609
0
        MEM_INIT(&prefs, 0, sizeof(prefs));
610
0
    if (prefs.frameInfo.contentSize != 0)
611
0
        prefs.frameInfo.contentSize = (U64)srcSize;   /* auto-correct content size if selected (!=0) */
612
613
0
    FORWARD_IF_ERROR(LZ4F_getBlockSize(prefs.frameInfo.blockSizeID));   /* invalid blockSizeID */
614
0
    prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize);
615
0
    prefs.autoFlush = 1;
616
0
    if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))
617
0
        prefs.frameInfo.blockMode = LZ4F_blockIndependent;   /* only one block => no need for inter-block link */
618
619
0
    if (LZ4F_mtEligible(&prefs)) {
620
        /* a single job produces the same output as single-threaded compression, without the setup cost */
621
0
        size_t const blockSize = LZ4F_getBlockSize(prefs.frameInfo.blockSizeID);
622
0
        if (LZ4F_isError(blockSize) || srcSize <= LZ4F_mtJobSize(blockSize))
623
0
            prefs.nbWorkers = 0;
624
0
    }
625
626
0
    MEM_INIT(&options, 0, sizeof(options));
627
0
    options.stableSrc = LZ4F_srcStableUntilFlush;   /* src remains until LZ4F_compressEnd() below */
628
629
0
    { size_t const headerSize = LZ4F_compressBegin_usingCDict(cctx, dstBuffer, dstCapacity, cdict, &prefs);  /* write header */
630
0
      FORWARD_IF_ERROR(headerSize);
631
0
      dstPtr += headerSize;   /* header size */ }
632
633
0
    assert(dstEnd >= dstPtr);
634
0
    { size_t const cSize = LZ4F_compressUpdate(cctx, dstPtr, (size_t)(dstEnd-dstPtr), srcBuffer, srcSize, &options);
635
0
      FORWARD_IF_ERROR(cSize);
636
0
      dstPtr += cSize; }
637
638
0
    assert(dstEnd >= dstPtr);
639
0
    { size_t const tailSize = LZ4F_compressEnd(cctx, dstPtr, (size_t)(dstEnd-dstPtr), &options);   /* flush last block, and generate suffix */
640
0
      int const completed = !LZ4F_isError(tailSize) && ((cctx->cStage == 0) || (cctx->flushStage == 3));
641
0
      if (!completed) {
642
          /* the frame doesn't fit */
643
0
          LZ4F_invalidateFrame(cctx);
644
0
          return LZ4F_isError(tailSize) ? tailSize : LZ4F_returnErrorCode(LZ4F_ERROR_dstCapacity_tooSmall);
645
0
      }
646
0
      cctx->cStage = 0;
647
0
      cctx->flushStage = 0;
648
0
      dstPtr += tailSize; }
649
650
0
    assert(dstEnd >= dstStart);
651
0
    return (size_t)(dstPtr - dstStart);
652
0
}
653
654
655
/*! LZ4F_compressFrame() :
656
 *  Compress an entire srcBuffer into a valid LZ4 frame, in a single step.
657
 *  Success is guaranteed when dstCapacity >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
658
 *  Otherwise, compression fails with dstCapacity_tooSmall if the frame doesn't fit.
659
 *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
660
 * @return : number of bytes written into dstBuffer.
661
 *           or an error code if it fails (can be tested using LZ4F_isError())
662
 */
663
size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
664
                    const void* srcBuffer, size_t srcSize,
665
                    const LZ4F_preferences_t* preferencesPtr)
666
0
{
667
0
    size_t result;
668
#if (LZ4F_HEAPMODE)
669
    LZ4F_cctx_t* const cctxPtr = LZ4F_createCompressionContext_advanced(LZ4F_defaultCMem, LZ4F_VERSION);
670
    RETURN_ERROR_IF(cctxPtr == NULL, allocation_failed);
671
#else
672
0
    LZ4F_cctx_t cctx;
673
0
    LZ4_stream_t lz4ctx;
674
0
    LZ4F_cctx_t* const cctxPtr = &cctx;
675
676
0
    MEM_INIT(&cctx, 0, sizeof(cctx));
677
0
    cctx.version = LZ4F_VERSION;
678
0
    cctx.tmpBuffCapacity = 5 MB;   /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc */
679
0
    if ( preferencesPtr == NULL
680
0
      || preferencesPtr->compressionLevel < LZ4HC_CLEVEL_MIN ) {
681
0
        LZ4_initStream(&lz4ctx, sizeof(lz4ctx));
682
0
        cctxPtr->lz4CtxPtr = &lz4ctx;
683
0
        cctxPtr->lz4CtxAlloc = ctxFast;
684
0
        cctxPtr->lz4CtxType = ctxFast;
685
0
    }
686
0
#endif
687
0
    DEBUGLOG(4, "LZ4F_compressFrame");
688
689
0
    result = LZ4F_compressFrame_usingCDict(cctxPtr, dstBuffer, dstCapacity,
690
0
                                           srcBuffer, srcSize,
691
0
                                           NULL, preferencesPtr);
692
693
#if (LZ4F_HEAPMODE)
694
    LZ4F_freeCompressionContext(cctxPtr);
695
#else
696
0
    if ( preferencesPtr != NULL
697
0
      && preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN ) {
698
0
        LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);
699
0
    }
700
0
    LZ4F_mt_free(cctxPtr->mt, cctxPtr->cmem);
701
0
    LZ4F_free(cctxPtr->stageBuff, cctxPtr->cmem);
702
0
#endif
703
0
    return result;
704
0
}
705
706
707
/*-***************************************************
708
*   Dictionary compression
709
*****************************************************/
710
711
LZ4F_CDict*
712
LZ4F_createCDict_advanced(LZ4F_CustomMem cmem, const void* dictBuffer, size_t dictSize)
713
0
{
714
0
    const char* dictStart = (const char*)dictBuffer;
715
0
    LZ4F_CDict* cdict = NULL;
716
717
0
    DEBUGLOG(4, "LZ4F_createCDict_advanced");
718
719
0
    if (!dictStart)
720
0
        return NULL;
721
0
    cdict = (LZ4F_CDict*)LZ4F_malloc(sizeof(*cdict), cmem);
722
0
    if (!cdict)
723
0
        return NULL;
724
725
0
    cdict->cmem = cmem;
726
0
    if (dictSize > 64 KB) {
727
0
        dictStart += dictSize - 64 KB;
728
0
        dictSize = 64 KB;
729
0
    }
730
0
    cdict->dictContent = LZ4F_malloc(dictSize, cmem);
731
    /* note: using @cmem to allocate => can't use default create */
732
0
    cdict->fastCtx = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cmem);
733
0
    cdict->HCCtx = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cmem);
734
0
    if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) {
735
0
        LZ4F_freeCDict(cdict);
736
0
        return NULL;
737
0
    }
738
0
    LZ4_memcpy(cdict->dictContent, dictStart, dictSize);
739
0
    LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
740
0
    LZ4_loadDictSlow(cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
741
0
    LZ4_initStreamHC(cdict->HCCtx, sizeof(LZ4_streamHC_t));
742
    /* note: we don't know at this point which compression level is going to be used
743
     * as a consequence, HCCtx is created for the more common HC mode */
744
0
    LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT);
745
0
    LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize);
746
0
    return cdict;
747
0
}
748
749
/*! LZ4F_createCDict() :
750
 *  When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once.
751
 *  LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
752
 *  LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
753
 * @dictBuffer can be released after LZ4F_CDict creation, since its content is copied within CDict
754
 * @return : digested dictionary for compression, or NULL if failed */
755
LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize)
756
0
{
757
0
    DEBUGLOG(4, "LZ4F_createCDict");
758
0
    return LZ4F_createCDict_advanced(LZ4F_defaultCMem, dictBuffer, dictSize);
759
0
}
760
761
void LZ4F_freeCDict(LZ4F_CDict* cdict)
762
0
{
763
0
    if (cdict==NULL) return;  /* support free on NULL */
764
0
    LZ4F_free(cdict->dictContent, cdict->cmem);
765
0
    LZ4F_free(cdict->fastCtx, cdict->cmem);
766
0
    LZ4F_free(cdict->HCCtx, cdict->cmem);
767
0
    LZ4F_free(cdict, cdict->cmem);
768
0
}
769
770
771
/*-*********************************
772
*  Advanced compression functions
773
***********************************/
774
775
LZ4F_cctx*
776
LZ4F_createCompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version)
777
15.6k
{
778
15.6k
    LZ4F_cctx* const cctxPtr =
779
15.6k
        (LZ4F_cctx*)LZ4F_calloc(sizeof(LZ4F_cctx), customMem);
780
15.6k
    if (cctxPtr==NULL) return NULL;
781
782
15.6k
    cctxPtr->cmem = customMem;
783
15.6k
    cctxPtr->version = version;
784
15.6k
    cctxPtr->cStage = 0;   /* Uninitialized. Next stage : init cctx */
785
786
15.6k
    return cctxPtr;
787
15.6k
}
788
789
/*! LZ4F_createCompressionContext() :
790
 *  The first thing to do is to create a compressionContext object, which will be used in all compression operations.
791
 *  This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
792
 *  The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries.
793
 *  The function will provide a pointer to an allocated LZ4F_compressionContext_t object.
794
 *  If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
795
 *  Object can release its memory using LZ4F_freeCompressionContext();
796
**/
797
LZ4F_errorCode_t
798
LZ4F_createCompressionContext(LZ4F_cctx** LZ4F_compressionContextPtr, unsigned version)
799
0
{
800
0
    assert(LZ4F_compressionContextPtr != NULL); /* considered a violation of narrow contract */
801
    /* in case it nonetheless happen in production */
802
0
    RETURN_ERROR_IF(LZ4F_compressionContextPtr == NULL, parameter_null);
803
804
0
    *LZ4F_compressionContextPtr = LZ4F_createCompressionContext_advanced(LZ4F_defaultCMem, version);
805
0
    RETURN_ERROR_IF(*LZ4F_compressionContextPtr==NULL, allocation_failed);
806
0
    return LZ4F_OK_NoError;
807
0
}
808
809
LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr)
810
15.6k
{
811
15.6k
    if (cctxPtr != NULL) {  /* support free on NULL */
812
15.6k
       LZ4F_mt_free(cctxPtr->mt, cctxPtr->cmem);   /* first : waits for jobs still in flight */
813
15.6k
       LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);  /* note: LZ4_streamHC_t and LZ4_stream_t are simple POD types */
814
15.6k
       LZ4F_free(cctxPtr->tmpBuff, cctxPtr->cmem);
815
15.6k
       LZ4F_free(cctxPtr->stageBuff, cctxPtr->cmem);
816
15.6k
       LZ4F_free(cctxPtr->rawDictFast, cctxPtr->cmem);
817
15.6k
       LZ4F_free(cctxPtr->rawDictHC, cctxPtr->cmem);
818
15.6k
       LZ4F_free(cctxPtr, cctxPtr->cmem);
819
15.6k
    }
820
15.6k
    return LZ4F_OK_NoError;
821
15.6k
}
822
823
824
/**
825
 * This function prepares the internal LZ4(HC) stream for a new compression,
826
 * resetting the context and attaching the dictionary, if there is one.
827
 *
828
 * It needs to be called at the beginning of each independent compression
829
 * stream (i.e., at the beginning of a frame in blockLinked mode, or at the
830
 * beginning of each block in blockIndependent mode).
831
 */
832
static void LZ4F_initStream(void* ctx,
833
                            const LZ4F_CDict* cdict,
834
                            int level,
835
19.0k
                            LZ4F_blockMode_t blockMode) {
836
19.0k
    if (level < LZ4HC_CLEVEL_MIN) {
837
        /* In these cases, we will call LZ4_compress_fast_continue(),
838
         * which needs an already reset context. Otherwise, we'll call a
839
         * one-shot API. The non-continued APIs internally perform their own
840
         * resets at the beginning of their calls, where they know what
841
         * tableType they need the context to be in. So in that case this
842
         * would be misguided / wasted work. */
843
6.74k
        if (cdict) {
844
0
            LZ4_resetStream_fast((LZ4_stream_t*)ctx);
845
0
            LZ4_attach_dictionary((LZ4_stream_t*)ctx, cdict->fastCtx);
846
6.74k
        } else if (blockMode == LZ4F_blockLinked) {
847
            /* Clear the table, rather than LZ4_resetStream_fast() :
848
             * output doesn't depend on the context's history,
849
             * and it's faster, unless the frame is tiny. */
850
3.05k
            LZ4_initStream(ctx, sizeof(LZ4_stream_t));
851
3.05k
        }
852
        /* In these cases, we'll call a one-shot API.
853
         * The non-continued APIs internally perform their own resets
854
         * at the beginning of their calls, where they know
855
         * which tableType they need the context to be in.
856
         * Therefore, a reset here would be wasted work. */
857
12.2k
    } else {
858
12.2k
        LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level);
859
12.2k
        if (cdict)
860
0
            LZ4_attach_HC_dictionary((LZ4_streamHC_t*)ctx, cdict->HCCtx);
861
12.2k
    }
862
19.0k
}
863
864
/* LZ4F_startStream() :
865
 * starts the LZ4 stream @ctx at the compression level of @prefs : for a frame, a job, or after uncompressed blocks.
866
 * With linked blocks, the stream starts from dictionary @cdict, or from history @dict (@dictSize bytes) ;
867
 * independent blocks start their own stream (see LZ4F_compressBlock()). */
868
static void LZ4F_startStream(void* ctx, const LZ4F_preferences_t* prefs,
869
                             const LZ4F_CDict* cdict, const void* dict, size_t dictSize)
870
15.6k
{
871
15.6k
    int const level = prefs->compressionLevel;
872
15.6k
    if (prefs->frameInfo.blockMode == LZ4F_blockLinked)
873
9.94k
        LZ4F_initStream(ctx, cdict, level, LZ4F_blockLinked);
874
15.6k
    if (level >= LZ4HC_CLEVEL_MIN)
875
10.3k
        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)ctx, (int)prefs->favorDecSpeed);
876
15.6k
    if (dict) {
877
0
        assert(cdict == NULL);
878
0
        assert(prefs->frameInfo.blockMode == LZ4F_blockLinked);
879
0
        assert(dictSize <= INT_MAX);
880
0
        if (level < LZ4HC_CLEVEL_MIN) {
881
0
            LZ4_loadDict((LZ4_stream_t*)ctx, (const char*)dict, (int)dictSize);
882
0
        } else {
883
0
            LZ4_loadDictHC((LZ4_streamHC_t*)ctx, (const char*)dict, (int)dictSize);
884
0
        }
885
0
    }
886
15.6k
}
887
888
/* LZ4F_sizeofLZ4State() :
889
 * @return the size of the inner LZ4 state (pointed by lz4CtxPtr) for @ctxType :
890
 *  LZ4_stream_t for fast levels, LZ4_streamHC_t for HC levels.
891
 *  ctxNone means no state allocated, hence a size of 0.
892
 *  Note : the larger of fast and HC states depends on LZ4_MEMORY_USAGE,
893
 *         so reusing an allocated state requires comparing sizes. */
894
static size_t LZ4F_sizeofLZ4State(LZ4F_CtxType_e ctxType)
895
31.3k
{
896
31.3k
    switch (ctxType) {
897
15.6k
    case ctxNone: return 0;
898
5.27k
    case ctxFast: return sizeof(LZ4_stream_t);
899
10.3k
    case ctxHC:   return LZ4_STREAMHC_EXTSIZE;   /* extended : levels >= 10 allocate nothing */
900
31.3k
    }
901
31.3k
    assert(0);   /* invalid ctxType */
902
0
    return 0;
903
0
}
904
905
/* LZ4F_initLZ4State() :
906
 * initializes the inner LZ4 state @state for @ctxType (fast or HC), at compression @level */
907
static void LZ4F_initLZ4State(void* state, LZ4F_CtxType_e ctxType, int level)
908
15.6k
{
909
15.6k
    if (ctxType == ctxFast) {
910
5.27k
        LZ4_initStream(state, sizeof(LZ4_stream_t));
911
10.3k
    } else {
912
10.3k
        assert(ctxType == ctxHC);
913
10.3k
        LZ4_initStreamHC(state, LZ4_STREAMHC_EXTSIZE);
914
10.3k
        LZ4_setCompressionLevel((LZ4_streamHC_t*)state, level);
915
10.3k
    }
916
15.6k
}
917
918
0
size_t LZ4F_cctx_size(const LZ4F_cctx* cctx) {
919
0
    if (cctx == NULL) {
920
0
        return 0;
921
0
    }
922
0
    return sizeof(*cctx) + cctx->tmpBuffCapacity + cctx->stageCapacity + LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc)
923
0
         + (cctx->rawDictFast ? sizeof(LZ4_stream_t) : 0) + (cctx->rawDictHC ? sizeof(LZ4_streamHC_t) : 0)
924
0
         + LZ4F_mt_sizeof(cctx->mt);
925
0
}
926
927
/* LZ4F_digestRawDict() :
928
 * digests @dictBuffer within states owned by @cctx, without copying it (it must outlive the compression session),
929
 * for the compression level of current frame, which then employs it as a CDict.
930
 * Since it's done for each frame, fast levels employ LZ4_loadDict(), faster than LZ4F_createCDict()'s LZ4_loadDictSlow().
931
 * HC levels digest it for the frame's level : level 2 (lz4mid) has its own format,
932
 * which a CDict (digested at default level) lacks.
933
 * @return : CDict, or NULL if allocation failed */
934
static const LZ4F_CDict* LZ4F_digestRawDict(LZ4F_cctx_t* cctx, const void* dictBuffer, size_t dictSize)
935
0
{
936
0
    const char* dictStart = (const char*)dictBuffer;
937
0
    if (dictSize > 64 KB) {
938
0
        dictStart += dictSize - 64 KB;
939
0
        dictSize = 64 KB;
940
0
    }
941
0
    cctx->rawDict.cmem = cctx->cmem;
942
0
    cctx->rawDict.dictContent = NULL;
943
0
    cctx->rawDict.fastCtx = NULL;
944
0
    cctx->rawDict.HCCtx = NULL;
945
0
    if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
946
0
        if (cctx->rawDictFast == NULL) cctx->rawDictFast = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cctx->cmem);
947
0
        if (cctx->rawDictFast == NULL) return NULL;
948
0
        LZ4_initStream(cctx->rawDictFast, sizeof(LZ4_stream_t));
949
0
        LZ4_loadDict(cctx->rawDictFast, dictStart, (int)dictSize);
950
0
        cctx->rawDict.fastCtx = cctx->rawDictFast;
951
0
    } else {
952
0
        if (cctx->rawDictHC == NULL) cctx->rawDictHC = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cctx->cmem);
953
0
        if (cctx->rawDictHC == NULL) return NULL;
954
0
        LZ4_initStreamHC(cctx->rawDictHC, sizeof(LZ4_streamHC_t));
955
0
        LZ4_setCompressionLevel(cctx->rawDictHC, cctx->prefs.compressionLevel);
956
0
        LZ4_loadDictHC(cctx->rawDictHC, dictStart, (int)dictSize);
957
0
        cctx->rawDict.HCCtx = cctx->rawDictHC;
958
0
    }
959
0
    return &cctx->rawDict;
960
0
}
961
962
/* LZ4F_compressBegin_internal()
963
 * Note: only accepts @cdict _or_ @dictBuffer as non NULL.
964
 */
965
static size_t LZ4F_compressBegin_internal(LZ4F_cctx* cctx,
966
                          void* dstBuffer, size_t dstCapacity,
967
                          const void* dictBuffer, size_t dictSize,
968
                          const LZ4F_CDict* cdict,
969
                          const LZ4F_preferences_t* preferencesPtr)
970
15.6k
{
971
15.6k
    LZ4F_preferences_t const prefNull = LZ4F_INIT_PREFERENCES;
972
15.6k
    BYTE* const dstStart = (BYTE*)dstBuffer;
973
15.6k
    BYTE* dstPtr = dstStart;
974
15.6k
    int mtFrame;   /* frame cut into jobs (multi-threaded compression) */
975
976
15.6k
    if (preferencesPtr == NULL) preferencesPtr = &prefNull;
977
    /* validate arguments before modifying @cctx : when they are rejected, a frame in progress continues */
978
15.6k
    {   size_t const headerSize = minFHSize
979
15.6k
                                + (preferencesPtr->frameInfo.contentSize ? 8 : 0)
980
15.6k
                                + (preferencesPtr->frameInfo.dictID ? 4 : 0);
981
15.6k
        RETURN_ERROR_IF(dstCapacity < headerSize, dstCapacity_tooSmall);
982
15.6k
    }
983
15.6k
    FORWARD_IF_ERROR( LZ4F_getBlockSize(preferencesPtr->frameInfo.blockSizeID) );
984
15.6k
    RETURN_ERROR_IF(dictSize > INT_MAX, parameter_invalid);
985
    /* from now on, a failure (allocation) leaves no frame in progress */
986
15.6k
    LZ4F_invalidateFrame(cctx);   /* jobs of an abandoned frame : must complete before @cctx is modified */
987
15.6k
    cctx->mtActive = 0;
988
15.6k
    cctx->flushStage = 0;
989
15.6k
    cctx->pendingSize = 0;
990
15.6k
    cctx->prefs = *preferencesPtr;
991
15.6k
    mtFrame = LZ4F_mtEligible(&cctx->prefs);
992
15.6k
    DEBUGLOG(5, "LZ4F_compressBegin_internal: Independent_blocks=%u", cctx->prefs.frameInfo.blockMode);
993
994
    /* cctx Management */
995
15.6k
    {   LZ4F_CtxType_e const ctxType = (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? ctxFast : ctxHC;
996
15.6k
        size_t const requiredSize = LZ4F_sizeofLZ4State(ctxType);
997
15.6k
        size_t const allocatedSize = LZ4F_sizeofLZ4State((LZ4F_CtxType_e)cctx->lz4CtxAlloc);
998
15.6k
        if (allocatedSize < requiredSize) {
999
            /* not enough space allocated : must take ownership of memory allocation,
1000
             * in order to respect custom allocator contract */
1001
15.6k
            LZ4F_free(cctx->lz4CtxPtr, cctx->cmem);
1002
15.6k
            cctx->lz4CtxAlloc = (U16)ctxNone;   /* in case allocation fails */
1003
15.6k
            cctx->lz4CtxPtr = LZ4F_malloc(requiredSize, cctx->cmem);
1004
15.6k
            RETURN_ERROR_IF(cctx->lz4CtxPtr == NULL, allocation_failed);
1005
15.6k
            cctx->lz4CtxAlloc = (U16)ctxType;
1006
15.6k
            cctx->lz4CtxType = (U16)ctxNone;    /* not initialized yet */
1007
15.6k
        }
1008
15.6k
        if (cctx->lz4CtxType != ctxType) {
1009
            /* initialize the state for the correct context type */
1010
15.6k
            LZ4F_initLZ4State(cctx->lz4CtxPtr, ctxType, cctx->prefs.compressionLevel);
1011
15.6k
            cctx->lz4CtxType = (U16)ctxType;
1012
15.6k
    }   }
1013
1014
    /* raw dictionary : employed by each block as a CDict (independent blocks, or jobs of multi-threaded frames) ;
1015
     * single-threaded linked blocks keep the historical behavior : dictionary loaded as history, preceding the first block,
1016
     * from a copy within @tmpBuff (see below) */
1017
15.6k
    if ( dictBuffer
1018
0
      && ((cctx->prefs.frameInfo.blockMode == LZ4F_blockIndependent) || mtFrame) ) {
1019
0
        assert(cdict == NULL);
1020
0
        cdict = LZ4F_digestRawDict(cctx, dictBuffer, dictSize);
1021
0
        RETURN_ERROR_IF(cdict == NULL, allocation_failed);
1022
0
        dictBuffer = NULL;
1023
0
        dictSize = 0;
1024
0
    }
1025
1026
    /* Buffer Management */
1027
15.6k
    if (cctx->prefs.frameInfo.blockSizeID == 0)
1028
5.76k
        cctx->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
1029
15.6k
    cctx->maxBlockSize = LZ4F_getBlockSize(cctx->prefs.frameInfo.blockSizeID);
1030
1031
15.6k
    {   size_t const requiredBuffSize = mtFrame ? 0 :   /* jobs employ their own buffers */
1032
15.6k
                preferencesPtr->autoFlush ?
1033
6.54k
                ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0) :  /* history, then inputs < 64 KB (see LZ4F_st_update()) */
1034
15.6k
                cctx->maxBlockSize + ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
1035
1036
15.6k
        if (cctx->tmpBuffCapacity < requiredBuffSize) {
1037
13.6k
            cctx->tmpBuffCapacity = 0;
1038
13.6k
            LZ4F_free(cctx->tmpBuff, cctx->cmem);
1039
13.6k
            cctx->tmpBuff = (BYTE*)LZ4F_malloc(requiredBuffSize, cctx->cmem);
1040
13.6k
            RETURN_ERROR_IF(cctx->tmpBuff == NULL, allocation_failed);
1041
13.6k
            cctx->tmpBuffCapacity = requiredBuffSize;
1042
13.6k
    }   }
1043
15.6k
    cctx->tmpIn = cctx->tmpBuff;
1044
15.6k
    cctx->tmpInSize = 0;
1045
15.6k
    if (dictBuffer) {
1046
        /* single-threaded linked blocks : the dictionary is copied into @tmpBuff, as saved history :
1047
         * buffered input follows it, and references it in prefix mode
1048
         * (faster than an external dictionary, which fast levels also lose after the first block) */
1049
0
        if (dictSize > 64 KB) {
1050
0
            dictBuffer = (const BYTE*)dictBuffer + dictSize - 64 KB;
1051
0
            dictSize = 64 KB;
1052
0
        }
1053
0
        assert(cctx->tmpBuffCapacity >= 128 KB);
1054
0
        LZ4_memcpy(cctx->tmpBuff, dictBuffer, dictSize);
1055
0
        dictBuffer = cctx->tmpBuff;
1056
0
        cctx->tmpIn = cctx->tmpBuff + dictSize;
1057
0
    }
1058
15.6k
    (void)XXH32_reset(&(cctx->xxh), 0);
1059
1060
    /* context init */
1061
15.6k
    cctx->cdict = cdict;
1062
15.6k
    cctx->blockCompressMode = LZ4B_COMPRESSED;   /* a frame starts with the LZ4 state just initialized (dictionary included) */
1063
15.6k
    LZ4F_startStream(cctx->lz4CtxPtr, &cctx->prefs, cdict, dictBuffer, dictSize);
1064
1065
    /* Stage 2 : Write Frame Header */
1066
1067
    /* Magic Number */
1068
15.6k
    LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
1069
15.6k
    dstPtr += 4;
1070
15.6k
    {   BYTE* const headerStart = dstPtr;
1071
1072
        /* FLG Byte */
1073
15.6k
        *dstPtr++ = (BYTE)(((1 & _2BITS) << 6)    /* Version('01') */
1074
15.6k
            + ((cctx->prefs.frameInfo.blockMode & _1BIT ) << 5)
1075
15.6k
            + ((cctx->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
1076
15.6k
            + ((unsigned)(cctx->prefs.frameInfo.contentSize > 0) << 3)
1077
15.6k
            + ((cctx->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
1078
15.6k
            +  (cctx->prefs.frameInfo.dictID > 0) );
1079
        /* BD Byte */
1080
15.6k
        *dstPtr++ = (BYTE)((cctx->prefs.frameInfo.blockSizeID & _3BITS) << 4);
1081
        /* Optional Frame content size field */
1082
15.6k
        if (cctx->prefs.frameInfo.contentSize) {
1083
0
            LZ4F_writeLE64(dstPtr, cctx->prefs.frameInfo.contentSize);
1084
0
            dstPtr += 8;
1085
0
            cctx->totalInSize = 0;
1086
0
        }
1087
        /* Optional dictionary ID field */
1088
15.6k
        if (cctx->prefs.frameInfo.dictID) {
1089
0
            LZ4F_writeLE32(dstPtr, cctx->prefs.frameInfo.dictID);
1090
0
            dstPtr += 4;
1091
0
        }
1092
        /* Header CRC Byte */
1093
15.6k
        *dstPtr = LZ4F_headerChecksum(headerStart, (size_t)(dstPtr - headerStart));
1094
15.6k
        dstPtr++;
1095
15.6k
    }
1096
1097
15.6k
    if (mtFrame) {
1098
0
        assert(dictBuffer == NULL);
1099
0
        FORWARD_IF_ERROR( LZ4F_mt_begin(cctx) );
1100
0
    }
1101
1102
15.6k
    cctx->cStage = 1;   /* header written, now request input data block */
1103
15.6k
    return (size_t)(dstPtr - dstStart);
1104
15.6k
}
1105
1106
size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
1107
                          void* dstBuffer, size_t dstCapacity,
1108
                          const LZ4F_preferences_t* preferencesPtr)
1109
15.6k
{
1110
15.6k
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
1111
15.6k
                                        NULL, 0,
1112
15.6k
                                        NULL, preferencesPtr);
1113
15.6k
}
1114
1115
size_t LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
1116
                          void* dstBuffer, size_t dstCapacity,
1117
                          const void* dict, size_t dictSize,
1118
                          const LZ4F_preferences_t* preferencesPtr)
1119
0
{
1120
0
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
1121
0
                                        dict, dictSize,
1122
0
                                        NULL, preferencesPtr);
1123
0
}
1124
1125
size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
1126
                          void* dstBuffer, size_t dstCapacity,
1127
                          const LZ4F_CDict* cdict,
1128
                          const LZ4F_preferences_t* preferencesPtr)
1129
0
{
1130
0
    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
1131
0
                                        NULL, 0,
1132
0
                                       cdict, preferencesPtr);
1133
0
}
1134
1135
1136
/*  LZ4F_compressBound() :
1137
 * @return minimum capacity of dstBuffer for a given srcSize to handle worst case scenario.
1138
 *  LZ4F_preferences_t structure is optional : if NULL, preferences will be set to cover worst case scenario.
1139
 *  This function cannot fail.
1140
 */
1141
size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
1142
15.6k
{
1143
15.6k
    size_t bound;
1144
15.6k
    size_t const blockCRCSize = preferencesPtr
1145
15.6k
                             ? BFSize * preferencesPtr->frameInfo.blockChecksumFlag
1146
15.6k
                             : BFSize;
1147
15.6k
    if (preferencesPtr && !preferencesPtr->autoFlush && LZ4F_mtEligible(preferencesPtr)) {
1148
        /* frame cut into jobs : output can lag behind input */
1149
0
        return LZ4F_mtCompressBound(srcSize, preferencesPtr);
1150
0
    }
1151
15.6k
    if (preferencesPtr && preferencesPtr->autoFlush) {
1152
        /* + 1 : output of LZ4F_flush() and LZ4F_compressEnd() remains strictly below LZ4F_compressBound(0),
1153
         * since a filled dstBuffer means more output may remain */
1154
6.54k
        return LZ4F_compressBound_autoFlush(srcSize, preferencesPtr) + (srcSize == 0);
1155
6.54k
    }
1156
    /* single-threaded : full blocks only, each one stored uncompressed in worst case.
1157
     * Up to (blockSize-1) bytes can already be buffered : srcSize completes at most srcSize/blockSize + 1 blocks.
1158
     * The buffered block can also be emitted separately (mode switch), or remain from an incomplete LZ4F_flush() :
1159
     * then, srcSize completes at most srcSize/blockSize blocks.
1160
     * @srcSize == 0 : LZ4F_flush() and LZ4F_compressEnd() emit the buffered block (< blockSize bytes : output
1161
     * remains strictly below the bound, so that a single invocation completes them), then the frame footer.
1162
     * The frame footer is always included, so that the bound grows with @srcSize. */
1163
9.12k
    {   size_t const bs = LZ4F_getBlockSize(preferencesPtr ? preferencesPtr->frameInfo.blockSizeID : LZ4F_default);
1164
9.12k
        size_t const blockSize = LZ4F_isError(bs) ? 4 MB : bs;
1165
9.12k
        size_t const contentCRCSize = preferencesPtr
1166
9.12k
                                    ? BFSize * preferencesPtr->frameInfo.contentChecksumFlag
1167
9.12k
                                    : BFSize;
1168
9.12k
        size_t const nbBlocks = srcSize / blockSize + 1;
1169
9.12k
        bound = nbBlocks * (blockSize + BHSize + blockCRCSize) + BHSize + contentCRCSize;
1170
9.12k
    }
1171
9.12k
    return bound;
1172
15.6k
}
1173
1174
1175
typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict);
1176
1177
1178
/*! LZ4F_makeBlock():
1179
 *  compress a single block, add header and optional checksum.
1180
 *  The block is stored uncompressed when compression doesn't save space.
1181
 * @return : size of the block written into @dst,
1182
 *           or an error code if it doesn't fit into @dstCapacity.
1183
 *  Note : success is guaranteed when dstCapacity >= BHSize + srcSize + crcSize
1184
 */
1185
static size_t LZ4F_makeBlock(void* dst, size_t dstCapacity,
1186
                       const void* src, size_t srcSize,
1187
                             compressFunc_t compress, void* lz4ctx, int level,
1188
                       const LZ4F_CDict* cdict,
1189
                             LZ4F_blockChecksum_t crcFlag)
1190
31.2k
{
1191
31.2k
    BYTE* const cSizePtr = (BYTE*)dst;
1192
31.2k
    size_t const overhead = BHSize + (size_t)crcFlag * BFSize;
1193
31.2k
    int cCapacity = (srcSize > 1) ? (int)srcSize - 1 : 1;
1194
31.2k
    U32 cSize;
1195
31.2k
    assert(compress != NULL);
1196
31.2k
    assert(srcSize > 0);
1197
31.2k
    RETURN_ERROR_IF(dstCapacity <= overhead, dstCapacity_tooSmall);
1198
31.2k
    if (dstCapacity - overhead < (size_t)cCapacity)
1199
0
        cCapacity = (int)(dstCapacity - overhead);
1200
31.2k
    cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+BHSize),
1201
31.2k
                          (int)srcSize, cCapacity,
1202
31.2k
                          level, cdict);
1203
1204
31.2k
    if (cSize == 0 || cSize >= srcSize) {
1205
5.65k
        RETURN_ERROR_IF(dstCapacity - overhead < srcSize, dstCapacity_tooSmall);
1206
5.65k
        cSize = (U32)srcSize;
1207
5.65k
        LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG);
1208
5.65k
        LZ4_memcpy(cSizePtr+BHSize, src, srcSize);
1209
25.5k
    } else {
1210
25.5k
        LZ4F_writeLE32(cSizePtr, cSize);
1211
25.5k
    }
1212
31.2k
    if (crcFlag) {
1213
11.4k
        U32 const crc32 = XXH32(cSizePtr+BHSize, cSize, 0);  /* checksum of compressed data */
1214
11.4k
        LZ4F_writeLE32(cSizePtr+BHSize+cSize, crc32);
1215
11.4k
    }
1216
31.2k
    return BHSize + cSize + ((U32)crcFlag)*BFSize;
1217
31.2k
}
1218
1219
/*! LZ4F_compressBlocks_internal():
1220
 *  compress @src as a sequence of blocks of @blockSize bytes (the last one can be smaller),
1221
 *  each with its header and optional checksum, but without frame header, endMark nor content checksum.
1222
 *  @lz4ctx must be prepared for @compress :
1223
 *  linked blocks continue the stream, so they need a state initialized at frame start (or with a prefix).
1224
 * @return : nb of bytes written into @dst,
1225
 *           or an error code if it doesn't fit into @dstCapacity.
1226
 *  Note : success is guaranteed when dstCapacity >= srcSize + nbBlocks * (BHSize + crcFlag * BFSize)
1227
 */
1228
static size_t LZ4F_compressBlocks_internal(void* dst, size_t dstCapacity,
1229
                                     const void* src, size_t srcSize, size_t blockSize,
1230
                                           compressFunc_t compress, void* lz4ctx, int level,
1231
                                     const LZ4F_CDict* cdict,
1232
                                           LZ4F_blockChecksum_t crcFlag)
1233
14.1k
{
1234
14.1k
    const BYTE* ip = (const BYTE*)src;
1235
14.1k
    const BYTE* const iend = srcSize ? ip + srcSize : ip;
1236
14.1k
    BYTE* const ostart = (BYTE*)dst;
1237
14.1k
    BYTE* op = ostart;
1238
14.1k
    BYTE* const oend = dstCapacity ? ostart + dstCapacity : ostart;
1239
1240
28.2k
    while (ip < iend) {
1241
14.1k
        size_t const bSize = MIN(blockSize, (size_t)(iend - ip));
1242
14.1k
        size_t const cSize = LZ4F_makeBlock(op, (size_t)(oend - op),
1243
14.1k
                                            ip, bSize,
1244
14.1k
                                            compress, lz4ctx, level,
1245
14.1k
                                            cdict, crcFlag);
1246
14.1k
        FORWARD_IF_ERROR(cSize);
1247
14.1k
        ip += bSize;
1248
14.1k
        op += cSize;
1249
14.1k
    }
1250
14.1k
    return (size_t)(op - ostart);
1251
14.1k
}
1252
1253
1254
/* Negative compression levels select LZ4 "fast" mode, with acceleration = -level + 1.
1255
 * Acceleration is capped at LZ4_ACCELERATION_MAX before this computation,
1256
 * which would overflow for INT_MIN and INT_MIN+1. */
1257
static int LZ4F_levelToAcceleration(int level)
1258
11.3k
{
1259
11.3k
    if (level >= 0) return 1;
1260
9.50k
    if (level < 1 - LZ4_ACCELERATION_MAX) return LZ4_ACCELERATION_MAX;
1261
9.50k
    return -level + 1;
1262
9.50k
}
1263
1264
static int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
1265
3.69k
{
1266
3.69k
    int const acceleration = LZ4F_levelToAcceleration(level);
1267
3.69k
    DEBUGLOG(5, "LZ4F_compressBlock (srcSize=%i)", srcSize);
1268
3.69k
    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);
1269
3.69k
    if (cdict) {
1270
0
        return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);
1271
3.69k
    } else {
1272
3.69k
        return LZ4_compress_fast_extState_fastReset(ctx, src, dst, srcSize, dstCapacity, acceleration);
1273
3.69k
    }
1274
3.69k
}
1275
1276
static int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
1277
7.66k
{
1278
7.66k
    int const acceleration = LZ4F_levelToAcceleration(level);
1279
7.66k
    (void)cdict; /* init once at beginning of frame */
1280
7.66k
    DEBUGLOG(5, "LZ4F_compressBlock_continue (srcSize=%i)", srcSize);
1281
7.66k
    return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);
1282
7.66k
}
1283
1284
static int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
1285
5.36k
{
1286
5.36k
    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);
1287
5.36k
    if (cdict) {
1288
0
        return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);
1289
0
    }
1290
5.36k
    return LZ4_compress_HC_extStateHC_fastReset(ctx, src, dst, srcSize, dstCapacity, level);
1291
5.36k
}
1292
1293
static int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
1294
14.4k
{
1295
14.4k
    (void)level; (void)cdict; /* init once at beginning of frame */
1296
14.4k
    return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);
1297
14.4k
}
1298
1299
static int LZ4F_doNotCompressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)
1300
0
{
1301
0
    (void)ctx; (void)src; (void)dst; (void)srcSize; (void)dstCapacity; (void)level; (void)cdict;
1302
0
    return 0;
1303
0
}
1304
1305
static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_BlockCompressMode_e  compressMode)
1306
48.9k
{
1307
48.9k
    if (compressMode == LZ4B_UNCOMPRESSED)
1308
0
        return LZ4F_doNotCompressBlock;
1309
48.9k
    if (level < LZ4HC_CLEVEL_MIN) {
1310
16.8k
        if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock;
1311
10.6k
        return LZ4F_compressBlock_continue;
1312
16.8k
    }
1313
32.1k
    if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC;
1314
21.9k
    return LZ4F_compressBlockHC_continue;
1315
32.1k
}
1316
1317
/* Save or shorten history (up to 64KB) into @tmpBuff */
1318
static void LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr)
1319
9.62k
{
1320
9.62k
    int const dictSize = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ?
1321
3.94k
                    LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB) :
1322
9.62k
                    LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);
1323
9.62k
    cctxPtr->tmpIn = cctxPtr->tmpBuff + dictSize;
1324
9.62k
}
1325
1326
typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;
1327
1328
static const LZ4F_compressOptions_t k_cOptionsNull = { 0, 0, 0, 0 };
1329
1330
/*-***************************************************
1331
*   Output not fitting into dstBuffer yet (LZ4F_flush(), LZ4F_compressEnd())
1332
*****************************************************/
1333
1334
/* stageBuff holds one block, stored uncompressed in worst case.
1335
 * @return : 0, or an error code (allocation_failed) */
1336
static size_t LZ4F_reserveStage(LZ4F_cctx_t* cctx)
1337
0
{
1338
0
    size_t const needed = cctx->maxBlockSize + BHSize + BFSize;
1339
0
    if (cctx->stageCapacity >= needed) return 0;
1340
0
    LZ4F_free(cctx->stageBuff, cctx->cmem);
1341
0
    cctx->stageCapacity = 0;
1342
0
    cctx->stageBuff = (BYTE*)LZ4F_malloc(needed, cctx->cmem);
1343
0
    RETURN_ERROR_IF(cctx->stageBuff == NULL, allocation_failed);
1344
0
    cctx->stageCapacity = needed;
1345
0
    return 0;
1346
0
}
1347
1348
/* copies pending output into @dst + @pos, as much as fits.
1349
 * @return : nb of bytes copied */
1350
static size_t LZ4F_copyPending(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity, size_t pos)
1351
71.1k
{
1352
71.1k
    size_t const n = MIN(cctx->pendingSize, dstCapacity - pos);
1353
71.1k
    assert(pos <= dstCapacity);
1354
71.1k
    if (n) {
1355
15.6k
        LZ4_memcpy(dst + pos, cctx->pending, n);
1356
15.6k
        cctx->pending += n;
1357
15.6k
    }
1358
71.1k
    cctx->pendingSize -= n;
1359
71.1k
    return n;
1360
71.1k
}
1361
1362
/* compression operations first emit output left pending by an incomplete LZ4F_flush(),
1363
 * entirely, since they must succeed : the flush ends there.
1364
 * @return : nb of bytes written into @dst, or an error code (callers invalidate the frame) */
1365
static size_t LZ4F_emitPendingWhole(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity)
1366
39.8k
{
1367
39.8k
    cctx->flushStage = 0;
1368
39.8k
    RETURN_ERROR_IF(cctx->pendingSize > dstCapacity, dstCapacity_tooSmall);
1369
39.8k
    return LZ4F_copyPending(cctx, dst, dstCapacity, 0);
1370
39.8k
}
1371
1372
/*! LZ4F_flushBlock() :
1373
 *  compresses input buffered within cctx (single-threaded mode), if any, into @dst.
1374
 * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */
1375
static size_t LZ4F_flushBlock(LZ4F_cctx_t* cctxPtr, void* dstBuffer, size_t dstCapacity)
1376
15.6k
{
1377
15.6k
    compressFunc_t compress;
1378
15.6k
    size_t cSize;
1379
1380
15.6k
    DEBUGLOG(5, "LZ4F_flushBlock: %zu buffered bytes (saved dict size = %i) (dstCapacity=%u)",
1381
15.6k
            cctxPtr->tmpInSize, (int)(cctxPtr->tmpIn - cctxPtr->tmpBuff), (unsigned)dstCapacity);
1382
15.6k
    if (cctxPtr->tmpInSize == 0) return 0;   /* nothing to flush */
1383
1384
    /* select compression function */
1385
9.11k
    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompressMode);
1386
1387
    /* compress tmp buffer */
1388
9.11k
    cSize = LZ4F_makeBlock(dstBuffer, dstCapacity,
1389
9.11k
                           cctxPtr->tmpIn, cctxPtr->tmpInSize,
1390
9.11k
                           compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
1391
9.11k
                           cctxPtr->cdict,
1392
9.11k
                           cctxPtr->prefs.frameInfo.blockChecksumFlag);
1393
9.11k
    FORWARD_IF_ERROR_INVALIDATE(cSize, cctxPtr);
1394
9.11k
    assert(((void)"flush overflows dstBuffer!", cSize <= dstCapacity));
1395
1396
9.11k
    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)
1397
5.41k
        cctxPtr->tmpIn += cctxPtr->tmpInSize;
1398
9.11k
    cctxPtr->tmpInSize = 0;
1399
1400
    /* keep tmpIn within limits */
1401
9.11k
    if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity)) {
1402
179
        assert(cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked);
1403
179
        LZ4F_localSaveDict(cctxPtr);
1404
179
    }
1405
1406
9.11k
    return cSize;
1407
9.11k
}
1408
1409
/* flush point, single-threaded mode : the buffered block is compressed into @dst when it fits in any case,
1410
 * otherwise into stageBuff, as pending output. Same output : compression capacity is the same.
1411
 * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */
1412
static size_t LZ4F_flushBlockPartial(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity)
1413
15.6k
{
1414
15.6k
    size_t const worstCase = cctx->tmpInSize + BHSize + (size_t)cctx->prefs.frameInfo.blockChecksumFlag * BFSize;
1415
15.6k
    size_t cSize;
1416
15.6k
    if ((cctx->tmpInSize == 0) || (dstCapacity >= worstCase))
1417
15.6k
        return LZ4F_flushBlock(cctx, dst, dstCapacity);
1418
0
    FORWARD_IF_ERROR_INVALIDATE(LZ4F_reserveStage(cctx), cctx);
1419
0
    cSize = LZ4F_flushBlock(cctx, cctx->stageBuff, cctx->stageCapacity);
1420
0
    FORWARD_IF_ERROR(cSize);   /* already invalidated */
1421
0
    cctx->pending = cctx->stageBuff;
1422
0
    cctx->pendingSize = cSize;
1423
0
    return 0;
1424
0
}
1425
1426
1427
/*-***************************************************
1428
*   Multi-threaded compression
1429
*****************************************************/
1430
/* When prefs.nbWorkers >= 1, input is cut into jobs (see LZ4F_mtJobSize()).
1431
 * Jobs are compressed by a pool of worker threads, kept within cctx,
1432
 * and their outputs are emitted in order by the calling thread.
1433
 * Output only depends on content and flush points :
1434
 * never on nb of workers, scheduling, input slicing, nor stableSrc.
1435
 * nbWorkers is the nb of worker threads compressing jobs : the calling thread fills and emits them.
1436
 * With a content checksum, one more thread hashes jobs, in order (see LZ4F_mt_hashJob()).
1437
 * At a flush point (LZ4F_flush(), LZ4F_compressEnd(), autoFlush), it waits for all jobs : when no other job is running,
1438
 * it compresses the flushed job itself. So at most nbWorkers threads compress at any time.
1439
 * Without multi-threading support (LZ4F_MULTITHREAD), the calling thread processes jobs alone, producing the same output.
1440
 * If no worker thread can be created, frame compression fails (allocation_failed) ;
1441
 * with fewer threads than requested (ex: system limits), it proceeds with them. */
1442
1443
/*! LZ4F_compressJob() :
1444
 *  compress one job, as a sequence of blocks (stored uncompressed when @mode == LZ4B_UNCOMPRESSED).
1445
 *  With linked blocks, each job restarts the stream, using as dictionary
1446
 *  the @prefixSize bytes of history right before @src,
1447
 *  or @cdict for the first job of the frame (@prefixSize == 0).
1448
 *  Output doesn't depend on @lz4ctx history.
1449
 * @return : nb of bytes written into @dst, or an error code */
1450
static size_t LZ4F_compressJob(void* lz4ctx, const LZ4F_preferences_t* prefs,
1451
                         const LZ4F_CDict* cdict, size_t blockSize,
1452
                               void* dst, size_t dstCapacity,
1453
                         const BYTE* src, size_t srcSize, size_t prefixSize,
1454
                               LZ4F_BlockCompressMode_e mode)
1455
0
{
1456
0
    int const level = prefs->compressionLevel;
1457
0
    LZ4F_blockMode_t const blockMode = prefs->frameInfo.blockMode;
1458
1459
0
    if (mode == LZ4B_UNCOMPRESSED) {   /* LZ4F_compressOptions_t.uncompressed */
1460
0
        return LZ4F_compressBlocks_internal(dst, dstCapacity, src, srcSize, blockSize,
1461
0
                                            LZ4F_doNotCompressBlock, NULL, 0, NULL,
1462
0
                                            prefs->frameInfo.blockChecksumFlag);
1463
0
    }
1464
1465
0
    assert(prefixSize <= LZ4F_MT_PREFIX_SIZE);
1466
0
    if (prefixSize) {
1467
0
        LZ4F_startStream(lz4ctx, prefs, NULL, src - prefixSize, prefixSize);
1468
0
    } else {
1469
0
        LZ4F_startStream(lz4ctx, prefs, cdict, NULL, 0);
1470
0
    }
1471
1472
0
    return LZ4F_compressBlocks_internal(dst, dstCapacity,
1473
0
                                        src, srcSize, blockSize,
1474
0
                                        LZ4F_selectCompression(blockMode, level, LZ4B_COMPRESSED),
1475
0
                                        lz4ctx, level, cdict,
1476
0
                                        prefs->frameInfo.blockChecksumFlag);
1477
0
}
1478
1479
typedef void (*LZ4F_job_f)(void* arg, unsigned workerID);
1480
typedef struct LZ4F_pool_s LZ4F_pool_t;
1481
1482
#if LZ4F_MULTITHREAD
1483
1484
#if defined(_WIN32)
1485
#  ifndef WIN32_LEAN_AND_MEAN
1486
#    define WIN32_LEAN_AND_MEAN
1487
#  endif
1488
   /* condition variables require Windows Vista+ ; _WIN32_WINNT may already be defined lower,
1489
    * ex: by <_mingw.h> (included by standard headers) on older mingw-w64 (0x502) */
1490
#  if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0600)
1491
#    if defined(_WINDOWS_)   /* <windows.h> already included (ex: amalgamated sources), without them */
1492
#      error "LZ4F_MULTITHREAD requires Windows Vista API : define _WIN32_WINNT >= 0x0600 before including <windows.h>, or disable LZ4F_MULTITHREAD"
1493
#    endif
1494
#    undef  _WIN32_WINNT
1495
#    define _WIN32_WINNT 0x0600
1496
#  endif
1497
#  include <windows.h>
1498
   typedef HANDLE             LZ4F_thread_t;
1499
   typedef CRITICAL_SECTION   LZ4F_mutex_t;
1500
   typedef CONDITION_VARIABLE LZ4F_cond_t;
1501
#  define LZ4F_mutex_init(m)     (InitializeCriticalSection(m), 0)
1502
#  define LZ4F_mutex_destroy(m)  DeleteCriticalSection(m)
1503
#  define LZ4F_mutex_lock(m)     EnterCriticalSection(m)
1504
#  define LZ4F_mutex_unlock(m)   LeaveCriticalSection(m)
1505
#  define LZ4F_cond_init(c)      (InitializeConditionVariable(c), 0)
1506
#  define LZ4F_cond_destroy(c)   ((void)(c))
1507
#  define LZ4F_cond_wait(c, m)   SleepConditionVariableCS((c), (m), INFINITE)
1508
#  define LZ4F_cond_signal(c)    WakeConditionVariable(c)
1509
#  define LZ4F_cond_broadcast(c) WakeAllConditionVariable(c)
1510
#else
1511
#  include <pthread.h>
1512
#  include <signal.h>
1513
   typedef pthread_t       LZ4F_thread_t;
1514
   typedef pthread_mutex_t LZ4F_mutex_t;
1515
   typedef pthread_cond_t  LZ4F_cond_t;
1516
#  define LZ4F_mutex_init(m)     pthread_mutex_init((m), NULL)
1517
#  define LZ4F_mutex_destroy(m)  pthread_mutex_destroy(m)
1518
#  define LZ4F_mutex_lock(m)     pthread_mutex_lock(m)
1519
#  define LZ4F_mutex_unlock(m)   pthread_mutex_unlock(m)
1520
#  define LZ4F_cond_init(c)      pthread_cond_init((c), NULL)
1521
#  define LZ4F_cond_destroy(c)   pthread_cond_destroy(c)
1522
#  define LZ4F_cond_wait(c, m)   pthread_cond_wait((c), (m))
1523
#  define LZ4F_cond_signal(c)    pthread_cond_signal(c)
1524
#  define LZ4F_cond_broadcast(c) pthread_cond_broadcast(c)
1525
   /* worker threads must not receive process-directed signals intended for the application,
1526
    * but synchronous signals (faults) remain deliverable : when blocked, a fault kills the process,
1527
    * bypassing the application's handlers (ex: SIGBUS from a memory-mapped input truncated during compression) */
1528
#  if defined(SIG_SETMASK) && (!defined(_POSIX_C_SOURCE) || (_POSIX_C_SOURCE >= 199506L))
1529
#    define LZ4F_MT_BLOCK_SIGNALS 1
1530
#  else
1531
#    define LZ4F_MT_BLOCK_SIGNALS 0
1532
#  endif
1533
#endif
1534
1535
/* some compression functions employ large stack buffers when not in HEAPMODE,
1536
 * while default thread stacks can be small (ex: 128 KB on musl) */
1537
#define LZ4F_MT_STACKSIZE_MIN (1 MB)
1538
1539
/* Persistent pool of worker threads, started on demand (see LZ4F_pool_submit()), up to maxThreads.
1540
 * Queued jobs are run by worker threads (workerID 1 to nbThreads) :
1541
 * the calling thread only submits jobs and waits for them (without pool, it runs jobs itself : workerID 0).
1542
 * Allocations happen in the calling thread, since @cmem might not be thread-safe :
1543
 * HC states are extended (LZ4_STREAMHC_EXTSIZE), so lz4hc allocates nothing within worker threads.
1544
 * Note : like any thread, workers don't survive fork() : a forked child must not employ this pool. */
1545
typedef struct { LZ4F_job_f fn; void* arg; } LZ4F_poolJob_t;
1546
typedef struct { LZ4F_pool_t* pool; unsigned workerID; } LZ4F_poolWorker_t;
1547
1548
struct LZ4F_pool_s {
1549
    LZ4F_mutex_t lock;
1550
    LZ4F_cond_t  jobQueued;    /* to worker threads */
1551
    LZ4F_cond_t  jobDone;      /* to the calling thread */
1552
    LZ4F_poolJob_t* queue;     /* circular */
1553
    unsigned queueCapacity;
1554
    unsigned queueHead;
1555
    unsigned queueSize;
1556
    int shutdown;
1557
    int cancel;                /* jobs of an abandoned frame : not started yet, they end without running */
1558
    unsigned nbDone;           /* incremented at each job completion */
1559
    unsigned nbBusy;           /* worker threads running a job */
1560
    LZ4F_thread_t* threads;
1561
    LZ4F_poolWorker_t* workers;
1562
    unsigned nbThreads;        /* started on demand, up to maxThreads */
1563
    unsigned maxThreads;
1564
};
1565
1566
/* requires lock */
1567
static LZ4F_poolJob_t LZ4F_pool_pop(LZ4F_pool_t* pool)
1568
{
1569
    LZ4F_poolJob_t const job = pool->queue[pool->queueHead];
1570
    assert(pool->queueSize > 0);
1571
    pool->queueHead = (pool->queueHead + 1) % pool->queueCapacity;
1572
    pool->queueSize--;
1573
    return job;
1574
}
1575
1576
static void LZ4F_pool_work(LZ4F_poolWorker_t* worker)
1577
{
1578
    LZ4F_pool_t* const pool = worker->pool;
1579
    int busy = 0;
1580
    for (;;) {
1581
        LZ4F_poolJob_t job;
1582
        LZ4F_mutex_lock(&pool->lock);
1583
        if (busy) pool->nbBusy--;
1584
        while ((pool->queueSize == 0) && !pool->shutdown)
1585
            LZ4F_cond_wait(&pool->jobQueued, &pool->lock);
1586
        if (pool->queueSize == 0) {   /* shutdown */
1587
            LZ4F_mutex_unlock(&pool->lock);
1588
            return;
1589
        }
1590
        job = LZ4F_pool_pop(pool);
1591
        pool->nbBusy++;
1592
        busy = 1;
1593
        LZ4F_mutex_unlock(&pool->lock);
1594
        job.fn(job.arg, worker->workerID);
1595
    }
1596
}
1597
1598
#if defined(_WIN32)
1599
static DWORD WINAPI LZ4F_pool_thread(LPVOID arg)
1600
{
1601
    LZ4F_pool_work((LZ4F_poolWorker_t*)arg);
1602
    return 0;
1603
}
1604
#else
1605
static void* LZ4F_pool_thread(void* arg)
1606
{
1607
    LZ4F_pool_work((LZ4F_poolWorker_t*)arg);
1608
    return NULL;
1609
}
1610
#endif
1611
1612
/* starts threads, up to @nbThreads in total
1613
 * @return : nb of threads of @pool (fewer than @nbThreads when a creation fails) */
1614
static unsigned LZ4F_pool_startThreads(LZ4F_pool_t* pool, unsigned nbThreads)
1615
{
1616
    unsigned n;
1617
#if defined(_WIN32)
1618
    assert(nbThreads <= pool->maxThreads);
1619
    for (n = pool->nbThreads; n < nbThreads; n++) {
1620
        /* stack size : reserved, and committed on demand (otherwise, CreateThread() commits it upfront) */
1621
        pool->threads[n] = CreateThread(NULL, LZ4F_MT_STACKSIZE_MIN, LZ4F_pool_thread, &pool->workers[n],
1622
                                        STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
1623
        if (pool->threads[n] == NULL) break;
1624
    }
1625
#else
1626
    pthread_attr_t attr;
1627
    int const attrOK = !pthread_attr_init(&attr);
1628
#  if LZ4F_MT_BLOCK_SIGNALS
1629
    sigset_t allSignals, previousMask;
1630
    sigfillset(&allSignals);
1631
    sigdelset(&allSignals, SIGBUS);
1632
    sigdelset(&allSignals, SIGSEGV);
1633
    sigdelset(&allSignals, SIGFPE);
1634
    sigdelset(&allSignals, SIGILL);
1635
    pthread_sigmask(SIG_SETMASK, &allSignals, &previousMask);   /* new threads inherit this mask */
1636
#  endif
1637
    if (attrOK) {
1638
        size_t stackSize;
1639
        if (!pthread_attr_getstacksize(&attr, &stackSize) && (stackSize < LZ4F_MT_STACKSIZE_MIN))
1640
            (void)pthread_attr_setstacksize(&attr, LZ4F_MT_STACKSIZE_MIN);
1641
    }
1642
    assert(nbThreads <= pool->maxThreads);
1643
    for (n = pool->nbThreads; n < nbThreads; n++) {
1644
        if (pthread_create(&pool->threads[n], attrOK ? &attr : NULL, LZ4F_pool_thread, &pool->workers[n])) break;
1645
    }
1646
#  if LZ4F_MT_BLOCK_SIGNALS
1647
    pthread_sigmask(SIG_SETMASK, &previousMask, NULL);
1648
#  endif
1649
    if (attrOK) pthread_attr_destroy(&attr);
1650
#endif
1651
    pool->nbThreads = n;
1652
    return n;
1653
}
1654
1655
static void LZ4F_pool_freeMem(LZ4F_pool_t* pool, LZ4F_CustomMem cmem)
1656
{
1657
    LZ4F_free(pool->queue, cmem);
1658
    LZ4F_free(pool->threads, cmem);
1659
    LZ4F_free(pool->workers, cmem);
1660
    LZ4F_free(pool, cmem);
1661
}
1662
1663
static void LZ4F_pool_free(LZ4F_pool_t* pool, LZ4F_CustomMem cmem)
1664
{
1665
    unsigned n;
1666
    if (pool == NULL) return;
1667
    LZ4F_mutex_lock(&pool->lock);
1668
    pool->shutdown = 1;
1669
    LZ4F_cond_broadcast(&pool->jobQueued);
1670
    LZ4F_mutex_unlock(&pool->lock);
1671
    for (n = 0; n < pool->nbThreads; n++) {
1672
#if defined(_WIN32)
1673
        WaitForSingleObject(pool->threads[n], INFINITE);   /* never ends under the loader lock (see lz4frame.h) */
1674
        CloseHandle(pool->threads[n]);
1675
#else
1676
        pthread_join(pool->threads[n], NULL);
1677
#endif
1678
    }
1679
    LZ4F_cond_destroy(&pool->jobDone);
1680
    LZ4F_cond_destroy(&pool->jobQueued);
1681
    LZ4F_mutex_destroy(&pool->lock);
1682
    LZ4F_pool_freeMem(pool, cmem);
1683
}
1684
1685
/*! LZ4F_pool_create() :
1686
 *  threads are started on demand (see LZ4F_pool_submit()), up to @maxThreads.
1687
 * @return : a pool with one thread started, or NULL */
1688
static LZ4F_pool_t* LZ4F_pool_create(unsigned maxThreads, unsigned queueCapacity, LZ4F_CustomMem cmem)
1689
{
1690
    LZ4F_pool_t* const pool = (LZ4F_pool_t*)LZ4F_calloc(sizeof(*pool), cmem);
1691
    if (pool == NULL) return NULL;
1692
    pool->queue = (LZ4F_poolJob_t*)LZ4F_malloc(queueCapacity * sizeof(*pool->queue), cmem);
1693
    pool->threads = (LZ4F_thread_t*)LZ4F_malloc(maxThreads * sizeof(*pool->threads), cmem);
1694
    pool->workers = (LZ4F_poolWorker_t*)LZ4F_malloc(maxThreads * sizeof(*pool->workers), cmem);
1695
    if (pool->queue == NULL || pool->threads == NULL || pool->workers == NULL) {
1696
        LZ4F_pool_freeMem(pool, cmem);
1697
        return NULL;
1698
    }
1699
    if (LZ4F_mutex_init(&pool->lock)) {
1700
        LZ4F_pool_freeMem(pool, cmem);
1701
        return NULL;
1702
    }
1703
    if (LZ4F_cond_init(&pool->jobQueued)) {
1704
        LZ4F_mutex_destroy(&pool->lock);
1705
        LZ4F_pool_freeMem(pool, cmem);
1706
        return NULL;
1707
    }
1708
    if (LZ4F_cond_init(&pool->jobDone)) {
1709
        LZ4F_cond_destroy(&pool->jobQueued);
1710
        LZ4F_mutex_destroy(&pool->lock);
1711
        LZ4F_pool_freeMem(pool, cmem);
1712
        return NULL;
1713
    }
1714
    pool->queueCapacity = queueCapacity;
1715
    pool->maxThreads = maxThreads;
1716
    {   unsigned n;
1717
        for (n = 0; n < maxThreads; n++) {
1718
            pool->workers[n].pool = pool;
1719
            pool->workers[n].workerID = n+1;
1720
    }   }
1721
    if (LZ4F_pool_startThreads(pool, 1) == 0) {
1722
        LZ4F_pool_free(pool, cmem);
1723
        return NULL;
1724
    }
1725
    return pool;
1726
}
1727
1728
/* A frame cut into jobs has a pool : its creation failure fails the frame (see LZ4F_mt_begin()).
1729
 * Only LZ4F_pool_free() and LZ4F_pool_setCancel() accept a NULL pool, left by such a failure (see LZ4F_mt_free()). */
1730
1731
static unsigned LZ4F_pool_nbThreads(const LZ4F_pool_t* pool)
1732
{
1733
    assert(pool != NULL);
1734
    return pool->nbThreads;
1735
}
1736
1737
/* memory allocated with the custom allocator (thread stacks excluded) */
1738
static size_t LZ4F_pool_sizeof(const LZ4F_pool_t* pool)
1739
{
1740
    assert(pool != NULL);
1741
    return sizeof(*pool) + pool->queueCapacity * sizeof(*pool->queue)
1742
         + pool->maxThreads * (sizeof(*pool->threads) + sizeof(*pool->workers));
1743
}
1744
1745
/* @return : 1 when queued jobs outnumber idle threads, and more threads can be started (see LZ4F_pool_startThreads()) */
1746
static int LZ4F_pool_submit(LZ4F_pool_t* pool, LZ4F_job_f fn, void* arg)
1747
{
1748
    int moreThreads;
1749
    assert(pool != NULL);
1750
    LZ4F_mutex_lock(&pool->lock);
1751
    assert(pool->queueSize < pool->queueCapacity);
1752
    {   LZ4F_poolJob_t* const job = pool->queue + (pool->queueHead + pool->queueSize) % pool->queueCapacity;
1753
        job->fn = fn;
1754
        job->arg = arg;
1755
    }
1756
    pool->queueSize++;
1757
    moreThreads = (pool->queueSize > pool->nbThreads - pool->nbBusy) && (pool->nbThreads < pool->maxThreads);
1758
    LZ4F_cond_signal(&pool->jobQueued);
1759
    LZ4F_mutex_unlock(&pool->lock);
1760
    return moreThreads;
1761
}
1762
1763
/* one task of a job completed : the job is done when *pending reaches 0 */
1764
static void LZ4F_pool_taskDone(LZ4F_pool_t* pool, int* pending)
1765
{
1766
    assert(pool != NULL);
1767
    LZ4F_mutex_lock(&pool->lock);
1768
    assert(*pending > 0);
1769
    if (--*pending == 0) {
1770
        pool->nbDone++;
1771
        LZ4F_cond_broadcast(&pool->jobDone);
1772
    }
1773
    LZ4F_mutex_unlock(&pool->lock);
1774
}
1775
1776
static void LZ4F_pool_setCancel(LZ4F_pool_t* pool, int cancel)
1777
{
1778
    if (pool == NULL) return;
1779
    LZ4F_mutex_lock(&pool->lock);
1780
    pool->cancel = cancel;
1781
    LZ4F_mutex_unlock(&pool->lock);
1782
}
1783
1784
static int LZ4F_pool_isCancelled(LZ4F_pool_t* pool)
1785
{
1786
    int cancel;
1787
    assert(pool != NULL);
1788
    LZ4F_mutex_lock(&pool->lock);
1789
    cancel = pool->cancel;
1790
    LZ4F_mutex_unlock(&pool->lock);
1791
    return cancel;
1792
}
1793
1794
static int LZ4F_pool_isDone(LZ4F_pool_t* pool, const int* pending)
1795
{
1796
    int done;
1797
    assert(pool != NULL);
1798
    LZ4F_mutex_lock(&pool->lock);
1799
    done = (*pending == 0);
1800
    LZ4F_mutex_unlock(&pool->lock);
1801
    return done;
1802
}
1803
1804
/* waits for all tasks of a job (*pending == 0) */
1805
static void LZ4F_pool_waitDone(LZ4F_pool_t* pool, const int* pending)
1806
{
1807
    assert(pool != NULL);
1808
    LZ4F_mutex_lock(&pool->lock);
1809
    while (*pending) LZ4F_cond_wait(&pool->jobDone, &pool->lock);
1810
    LZ4F_mutex_unlock(&pool->lock);
1811
}
1812
1813
static unsigned LZ4F_pool_nbDone(LZ4F_pool_t* pool)
1814
{
1815
    unsigned nbDone;
1816
    assert(pool != NULL);
1817
    LZ4F_mutex_lock(&pool->lock);
1818
    nbDone = pool->nbDone;
1819
    LZ4F_mutex_unlock(&pool->lock);
1820
    return nbDone;
1821
}
1822
1823
/* waits for any job completion after @nbDone was observed */
1824
static void LZ4F_pool_waitAny(LZ4F_pool_t* pool, unsigned nbDone)
1825
{
1826
    assert(pool != NULL);
1827
    LZ4F_mutex_lock(&pool->lock);
1828
    while (pool->nbDone == nbDone) LZ4F_cond_wait(&pool->jobDone, &pool->lock);
1829
    LZ4F_mutex_unlock(&pool->lock);
1830
}
1831
1832
#else  /* !LZ4F_MULTITHREAD : no pool is ever created, jobs run within the calling thread */
1833
1834
0
static unsigned LZ4F_pool_nbThreads(const LZ4F_pool_t* pool) { (void)pool; return 0; }
1835
0
static size_t LZ4F_pool_sizeof(const LZ4F_pool_t* pool) { (void)pool; return 0; }
1836
0
static void LZ4F_pool_free(LZ4F_pool_t* pool, LZ4F_CustomMem cmem) { (void)pool; (void)cmem; }
1837
0
static int  LZ4F_pool_submit(LZ4F_pool_t* pool, LZ4F_job_f fn, void* arg) { (void)pool; fn(arg, 0); return 0; }
1838
0
static unsigned LZ4F_pool_startThreads(LZ4F_pool_t* pool, unsigned nbThreads) { (void)pool; (void)nbThreads; return 0; }
1839
0
static void LZ4F_pool_taskDone(LZ4F_pool_t* pool, int* pending) { (void)pool; assert(*pending > 0); (*pending)--; }
1840
0
static void LZ4F_pool_setCancel(LZ4F_pool_t* pool, int cancel) { (void)pool; (void)cancel; }
1841
0
static int  LZ4F_pool_isCancelled(LZ4F_pool_t* pool) { (void)pool; return 0; }
1842
0
static int  LZ4F_pool_isDone(LZ4F_pool_t* pool, const int* pending) { (void)pool; return *pending == 0; }
1843
0
static void LZ4F_pool_waitDone(LZ4F_pool_t* pool, const int* pending) { (void)pool; (void)pending; assert(*pending == 0); }
1844
0
static unsigned LZ4F_pool_nbDone(LZ4F_pool_t* pool) { (void)pool; return 0; }
1845
0
static void LZ4F_pool_waitAny(LZ4F_pool_t* pool, unsigned nbDone) { (void)pool; (void)nbDone; assert(0); }
1846
1847
#endif  /* LZ4F_MULTITHREAD */
1848
1849
typedef struct {
1850
    LZ4F_mtCtx_t* mt;
1851
    const BYTE* src;     /* job content, right after its prefixSize bytes of history */
1852
    size_t srcSize;
1853
    size_t prefixSize;
1854
    BYTE* inBuff;        /* input buffer (LZ4F_MT_PREFIX_SIZE + jobSize), when content is copied : NULL when read in place */
1855
    BYTE* outBuff;       /* compressed blocks */
1856
    LZ4F_BlockCompressMode_e mode;   /* LZ4B_UNCOMPRESSED : uncompressed input (LZ4F_compressOptions_t.uncompressed) */
1857
    size_t cSize;        /* result : compressed size, or error code */
1858
    int pending;         /* tasks not completed yet : compression, and hashing (content checksum) ; 0 : result available (protected by pool's lock) */
1859
} LZ4F_mtJob_t;
1860
1861
struct LZ4F_mtCtx_s {
1862
    LZ4F_CustomMem cmem;
1863
    LZ4F_pool_t* pool;       /* NULL without multi-threading support (jobs run within the calling thread), or after a failed creation */
1864
    LZ4F_pool_t* hPool;      /* hashing thread (content checksum), created on first need : jobs hashed in order ; NULL : hashed by the calling thread */
1865
    unsigned poolRequested;  /* nbWorkers requested when pool was created : threads are started on demand, up to it */
1866
    void** states;           /* one LZ4 state per worker (allocated when it starts) ; states[0] : cctx's own state, without pool */
1867
    unsigned nbStates;       /* capacity of states[] */
1868
    LZ4F_CtxType_e statesType;
1869
    LZ4F_mtJob_t* jobs;      /* ring buffer of job slots, for the maximum nb of threads : outBuff allocated on first use */
1870
    unsigned nbJobSlots;
1871
    size_t inCapacity;       /* of each input buffer */
1872
    size_t outCapacity;      /* of each outBuff */
1873
    /* input buffers are only needed until their job is compressed : they are shared by job slots */
1874
    BYTE** inBuffs;          /* all allocated input buffers */
1875
    BYTE** inFree;           /* free input buffers (stack) */
1876
    unsigned nbInBuffs;
1877
    unsigned nbInFree;
1878
    unsigned maxInBuffs;     /* capacity of inBuffs[] and inFree[] : one per thread, plus the one being filled */
1879
    unsigned oldest;         /* oldest submitted job, not emitted yet */
1880
    size_t emitted;          /* part of the oldest job already emitted, see LZ4F_mt_emitPartial() */
1881
    unsigned nbSubmitted;
1882
    int filling;             /* the slot following submitted jobs is being filled */
1883
    BYTE* history;           /* last bytes of content, up to LZ4F_MT_PREFIX_SIZE (linked blocks) */
1884
    size_t historySize;
1885
    const BYTE* stableEnd;   /* end of previous input, when stable (LZ4F_srcStableUntilFlush) */
1886
    size_t stableRun;        /* stable input contiguously preceding stableEnd, up to LZ4F_MT_PREFIX_SIZE */
1887
    /* current frame */
1888
    const LZ4F_preferences_t* prefs;
1889
    const LZ4F_CDict* cdict;
1890
    size_t blockSize;
1891
    size_t jobSize;
1892
    XXH32_state_t* xxh;      /* content checksum, or NULL : jobs are hashed in order, see LZ4F_mt_hashJob() */
1893
};
1894
1895
static void LZ4F_mt_runJob(void* arg, unsigned workerID)
1896
0
{
1897
0
    LZ4F_mtJob_t* const job = (LZ4F_mtJob_t*)arg;
1898
0
    LZ4F_mtCtx_t* const mt = job->mt;
1899
0
    assert(mt->states[workerID] != NULL);
1900
0
    if (LZ4F_pool_isCancelled(mt->pool)) {
1901
0
        job->cSize = 0;   /* abandoned frame : result discarded */
1902
0
    } else {
1903
0
        job->cSize = LZ4F_compressJob(mt->states[workerID], mt->prefs, mt->cdict, mt->blockSize,
1904
0
                                      job->outBuff, mt->outCapacity,
1905
0
                                      job->src, job->srcSize, job->prefixSize, job->mode);
1906
0
    }
1907
0
    LZ4F_pool_taskDone(mt->pool, &job->pending);
1908
0
}
1909
1910
/* content checksum : by the hashing thread, which runs jobs in order (or by the calling thread, without it) */
1911
static void LZ4F_mt_hashJob(void* arg, unsigned workerID)
1912
0
{
1913
0
    LZ4F_mtJob_t* const job = (LZ4F_mtJob_t*)arg;
1914
0
    LZ4F_mtCtx_t* const mt = job->mt;
1915
0
    (void)workerID;
1916
0
    if (!LZ4F_pool_isCancelled(mt->pool))   /* abandoned frame : checksum discarded */
1917
0
        (void)XXH32_update(mt->xxh, job->src, job->srcSize);
1918
0
    LZ4F_pool_taskDone(mt->pool, &job->pending);
1919
0
}
1920
1921
/* jobs in flight : up to LZ4F_MT_NBSLOTS() of current nb of threads (within ring buffer of job slots) */
1922
static unsigned LZ4F_mt_nbUsableSlots(const LZ4F_mtCtx_t* mt)
1923
0
{
1924
0
    unsigned const nbThreads = LZ4F_pool_nbThreads(mt->pool);
1925
0
    return nbThreads ? (unsigned)LZ4F_MT_NBSLOTS(nbThreads) : 1;
1926
0
}
1927
1928
/* allocates the LZ4 state of worker @workerID, unless already done
1929
 * @return : 1 when the state is ready, 0 if allocation failed */
1930
static int LZ4F_mt_allocState(LZ4F_mtCtx_t* mt, unsigned workerID, int level)
1931
0
{
1932
0
    if (mt->states[workerID] == NULL) {
1933
0
        void* const state = LZ4F_malloc(LZ4F_sizeofLZ4State(mt->statesType), mt->cmem);
1934
0
        if (state == NULL) return 0;
1935
0
        LZ4F_initLZ4State(state, mt->statesType, level);
1936
0
        mt->states[workerID] = state;
1937
0
    }
1938
0
    return 1;
1939
0
}
1940
1941
/* starts one more worker thread, with its LZ4 state (allocated by the calling thread) :
1942
 * on failure (allocation, thread creation), compression proceeds with current threads */
1943
static void LZ4F_mt_addWorker(LZ4F_mtCtx_t* mt)
1944
0
{
1945
0
    unsigned const workerID = LZ4F_pool_nbThreads(mt->pool) + 1;
1946
0
    assert(workerID < mt->nbStates);
1947
0
    if (LZ4F_mt_allocState(mt, workerID, mt->prefs->compressionLevel))
1948
0
        (void)LZ4F_pool_startThreads(mt->pool, workerID);
1949
0
}
1950
1951
/* @n-th submitted job, from the oldest one : @n == nbSubmitted is the slot following them (see LZ4F_mt_fillingSlot()) */
1952
static LZ4F_mtJob_t* LZ4F_mt_job(LZ4F_mtCtx_t* mt, unsigned n)
1953
0
{
1954
0
    return mt->jobs + (mt->oldest + n) % mt->nbJobSlots;
1955
0
}
1956
1957
static LZ4F_mtJob_t* LZ4F_mt_fillingSlot(LZ4F_mtCtx_t* mt)
1958
0
{
1959
0
    return LZ4F_mt_job(mt, mt->nbSubmitted);
1960
0
}
1961
1962
/* keeps the last LZ4F_MT_PREFIX_SIZE bytes of content */
1963
static void LZ4F_mt_addHistory(LZ4F_mtCtx_t* mt, const BYTE* content, size_t size)
1964
0
{
1965
0
    if (size >= LZ4F_MT_PREFIX_SIZE) {
1966
0
        LZ4_memcpy(mt->history, content + size - LZ4F_MT_PREFIX_SIZE, LZ4F_MT_PREFIX_SIZE);
1967
0
        mt->historySize = LZ4F_MT_PREFIX_SIZE;
1968
0
    } else {
1969
0
        size_t const kept = MIN(mt->historySize, LZ4F_MT_PREFIX_SIZE - size);
1970
0
        LZ4_memmove(mt->history, mt->history + mt->historySize - kept, kept);
1971
0
        LZ4_memcpy(mt->history + kept, content, size);
1972
0
        mt->historySize = kept + size;
1973
0
    }
1974
0
}
1975
1976
/* submits the job being filled : to worker threads,
1977
 * or, @inCallingThread, runs it right away with the cctx's own state (states[0], unused by workers) */
1978
static void LZ4F_mt_submit_internal(LZ4F_mtCtx_t* mt, int inCallingThread)
1979
0
{
1980
0
    LZ4F_mtJob_t* const job = LZ4F_mt_fillingSlot(mt);
1981
0
    assert(mt->filling);
1982
0
    assert(job->srcSize > 0);
1983
0
    job->pending = 1 + (mt->xxh != NULL);   /* compression, and hashing */
1984
0
    mt->filling = 0;
1985
0
    mt->nbSubmitted++;
1986
0
    if (inCallingThread)
1987
0
        LZ4F_mt_runJob(job, 0);
1988
0
    else if (LZ4F_pool_submit(mt->pool, LZ4F_mt_runJob, job))
1989
0
        LZ4F_mt_addWorker(mt);   /* more jobs than idle threads */
1990
0
    if (mt->xxh != NULL) {
1991
0
        if (mt->hPool != NULL)
1992
0
            (void)LZ4F_pool_submit(mt->hPool, LZ4F_mt_hashJob, job);
1993
0
        else
1994
0
            LZ4F_mt_hashJob(job, 0);
1995
0
    }
1996
0
    if (mt->prefs->frameInfo.blockMode == LZ4F_blockLinked)
1997
0
        LZ4F_mt_addHistory(mt, job->src, job->srcSize);   /* job content is only read while job runs */
1998
0
}
1999
2000
0
static void LZ4F_mt_submit(LZ4F_mtCtx_t* mt) { LZ4F_mt_submit_internal(mt, 0); }
2001
2002
/* the calling thread is about to wait for all jobs : when no other job is running, it compresses the last one itself,
2003
 * which saves the synchronization with a worker (same output : jobs don't depend on their state) */
2004
0
static void LZ4F_mt_submitLast(LZ4F_mtCtx_t* mt) { LZ4F_mt_submit_internal(mt, mt->nbSubmitted == 0); }
2005
2006
/* input buffer of a completed job returns to the free stack */
2007
static void LZ4F_mt_releaseInBuff(LZ4F_mtCtx_t* mt, LZ4F_mtJob_t* job)
2008
0
{
2009
0
    if (job->inBuff == NULL) return;
2010
0
    assert(mt->nbInFree < mt->nbInBuffs);
2011
0
    mt->inFree[mt->nbInFree++] = job->inBuff;
2012
0
    job->inBuff = NULL;
2013
0
}
2014
2015
/* the oldest job, completed, is emitted or discarded : its slot is free */
2016
static void LZ4F_mt_retireOldest(LZ4F_mtCtx_t* mt)
2017
0
{
2018
0
    LZ4F_mt_releaseInBuff(mt, mt->jobs + mt->oldest);
2019
0
    mt->oldest = (mt->oldest + 1) % mt->nbJobSlots;
2020
0
    mt->nbSubmitted--;
2021
0
    mt->emitted = 0;
2022
0
}
2023
2024
/*! LZ4F_mt_acquireInBuff() :
2025
 *  When all input buffers are employed, one is reclaimed from a submitted job,
2026
 *  the first one to complete (job durations vary).
2027
 * @return : an input buffer, or NULL if allocation failed */
2028
static BYTE* LZ4F_mt_acquireInBuff(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem)
2029
0
{
2030
0
    if (mt->nbInFree) return mt->inFree[--mt->nbInFree];
2031
0
    if (mt->nbInBuffs < LZ4F_pool_nbThreads(mt->pool) + LZ4F_MT_EXTRA_INBUFFS) {
2032
0
        BYTE* const buff = (BYTE*)LZ4F_malloc(mt->inCapacity, cmem);
2033
0
        assert(mt->nbInBuffs < mt->maxInBuffs);
2034
0
        if (buff != NULL) mt->inBuffs[mt->nbInBuffs++] = buff;
2035
0
        return buff;
2036
0
    }
2037
0
    for (;;) {
2038
0
        unsigned const nbDone = LZ4F_pool_nbDone(mt->pool);
2039
0
        unsigned n;
2040
0
        for (n = 0; n < mt->nbSubmitted; n++) {
2041
0
            LZ4F_mtJob_t* const job = LZ4F_mt_job(mt, n);
2042
0
            if ((job->inBuff != NULL) && LZ4F_pool_isDone(mt->pool, &job->pending)) {
2043
0
                BYTE* const buff = job->inBuff;
2044
0
                job->inBuff = NULL;
2045
0
                return buff;
2046
0
        }   }
2047
        /* buffers are held by submitted jobs, still running : wait for one of them */
2048
0
        LZ4F_pool_waitAny(mt->pool, nbDone);
2049
0
    }
2050
0
}
2051
2052
/* emits oldest submitted job into @dst + @pos, waiting for it if needed.
2053
 * On error, the job remains submitted : callers invalidate the frame, discarding its jobs (FORWARD_IF_ERROR_INVALIDATE) */
2054
static size_t LZ4F_mt_emitOldest(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos)
2055
0
{
2056
0
    LZ4F_mtJob_t* const job = mt->jobs + mt->oldest;
2057
0
    size_t toEmit;
2058
0
    assert(mt->nbSubmitted > 0);
2059
0
    assert(pos <= dstCapacity);
2060
0
    LZ4F_pool_waitDone(mt->pool, &job->pending);
2061
0
    FORWARD_IF_ERROR(job->cSize);
2062
0
    toEmit = job->cSize - mt->emitted;   /* part already emitted by an incomplete LZ4F_flush() */
2063
0
    RETURN_ERROR_IF(toEmit > dstCapacity - pos, dstCapacity_tooSmall);
2064
0
    LZ4_memcpy(dst + pos, job->outBuff + mt->emitted, toEmit);
2065
0
    LZ4F_mt_retireOldest(mt);
2066
0
    return toEmit;
2067
0
}
2068
2069
/* emits submitted jobs in order : all of them (@all), or only the already completed ones fitting into @dst
2070
 * (their emission isn't required yet : the others are emitted later).
2071
 * On error, callers invalidate the frame (FORWARD_IF_ERROR_INVALIDATE) */
2072
static size_t LZ4F_mt_emit(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos, int all)
2073
0
{
2074
0
    size_t written = 0;
2075
0
    while (mt->nbSubmitted > 0) {
2076
0
        const LZ4F_mtJob_t* const job = mt->jobs + mt->oldest;
2077
0
        if (!all) {
2078
0
            if (!LZ4F_pool_isDone(mt->pool, &job->pending)) break;
2079
0
            if (job->cSize - mt->emitted > dstCapacity - (pos + written)) break;   /* also defers an error code */
2080
0
        }
2081
0
        {   size_t const r = LZ4F_mt_emitOldest(mt, dst, dstCapacity, pos + written);
2082
0
            FORWARD_IF_ERROR(r);
2083
0
            written += r;
2084
0
    }   }
2085
0
    return written;
2086
0
}
2087
2088
/* discards submitted jobs : those not started yet end without running, others are waited for */
2089
static void LZ4F_mt_abort(LZ4F_mtCtx_t* mt)
2090
0
{
2091
0
    LZ4F_pool_setCancel(mt->pool, 1);
2092
0
    while (mt->nbSubmitted > 0) {
2093
0
        LZ4F_pool_waitDone(mt->pool, &mt->jobs[mt->oldest].pending);
2094
0
        LZ4F_mt_retireOldest(mt);
2095
0
    }
2096
0
    LZ4F_pool_setCancel(mt->pool, 0);
2097
0
    if (mt->filling) LZ4F_mt_releaseInBuff(mt, LZ4F_mt_fillingSlot(mt));
2098
0
    mt->filling = 0;
2099
0
    mt->emitted = 0;
2100
0
    mt->stableEnd = NULL;
2101
0
}
2102
2103
static void LZ4F_mt_freeStates(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem)
2104
0
{
2105
0
    unsigned n;
2106
0
    for (n = 1; n < mt->nbStates; n++) LZ4F_free(mt->states[n], cmem);   /* states[0] belongs to cctx ; NULL : not allocated */
2107
0
    LZ4F_free(mt->states, cmem);
2108
0
    mt->states = NULL;
2109
0
    mt->nbStates = 0;
2110
0
}
2111
2112
static void LZ4F_mt_freeInBuffs(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem)
2113
0
{
2114
0
    unsigned n;
2115
0
    assert(mt->nbInFree == mt->nbInBuffs);   /* no job in flight */
2116
0
    for (n = 0; n < mt->nbInBuffs; n++) LZ4F_free(mt->inBuffs[n], cmem);
2117
0
    LZ4F_free(mt->inBuffs, cmem);
2118
0
    LZ4F_free(mt->inFree, cmem);
2119
0
    mt->inBuffs = mt->inFree = NULL;
2120
0
    mt->nbInBuffs = mt->nbInFree = mt->maxInBuffs = 0;
2121
0
}
2122
2123
static void LZ4F_mt_freeJobs(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem)
2124
0
{
2125
0
    unsigned n;
2126
0
    for (n = 0; n < mt->nbJobSlots; n++) {
2127
0
        assert(mt->jobs[n].inBuff == NULL);
2128
0
        LZ4F_free(mt->jobs[n].outBuff, cmem);
2129
0
    }
2130
0
    LZ4F_free(mt->jobs, cmem);
2131
0
    mt->jobs = NULL;
2132
0
    mt->nbJobSlots = 0;
2133
0
}
2134
2135
static void LZ4F_mt_free(LZ4F_mtCtx_t* mt, LZ4F_CustomMem cmem)
2136
15.6k
{
2137
15.6k
    if (mt == NULL) return;
2138
0
    LZ4F_mt_abort(mt);
2139
0
    LZ4F_pool_free(mt->pool, cmem);
2140
0
    LZ4F_pool_free(mt->hPool, cmem);
2141
0
    LZ4F_mt_freeStates(mt, cmem);
2142
0
    LZ4F_mt_freeJobs(mt, cmem);
2143
0
    LZ4F_mt_freeInBuffs(mt, cmem);
2144
0
    LZ4F_free(mt->history, cmem);
2145
0
    LZ4F_free(mt, cmem);
2146
0
}
2147
2148
static size_t LZ4F_mt_sizeof(const LZ4F_mtCtx_t* mt)
2149
0
{
2150
0
    size_t size;
2151
0
    unsigned n;
2152
0
    if (mt == NULL) return 0;
2153
0
    size = sizeof(*mt) + LZ4F_MT_PREFIX_SIZE
2154
0
         + mt->nbStates * sizeof(void*)
2155
0
         + mt->nbJobSlots * sizeof(LZ4F_mtJob_t)
2156
0
         + mt->maxInBuffs * 2 * sizeof(BYTE*) + mt->nbInBuffs * mt->inCapacity
2157
0
         + (mt->pool ? LZ4F_pool_sizeof(mt->pool) : 0)
2158
0
         + (mt->hPool ? LZ4F_pool_sizeof(mt->hPool) : 0);
2159
0
    for (n = 1; n < mt->nbStates; n++) if (mt->states[n] != NULL) size += LZ4F_sizeofLZ4State(mt->statesType);
2160
0
    for (n = 0; n < mt->nbJobSlots; n++) if (mt->jobs[n].outBuff != NULL) size += mt->outCapacity;
2161
0
    return size;
2162
0
}
2163
2164
/*! LZ4F_mt_begin() :
2165
 *  prepares multi-threading resources for a new frame, cut into jobs.
2166
 *  Resources are kept within cctx, and reused by next frames.
2167
 *  Requires a cctx prepared by LZ4F_compressBegin_internal(), with no job in flight.
2168
 * @return : 0, or an error code */
2169
static size_t LZ4F_mt_begin(LZ4F_cctx_t* cctx)
2170
0
{
2171
0
    LZ4F_CustomMem const cmem = cctx->cmem;
2172
0
    unsigned const nbWorkers = MIN(cctx->prefs.nbWorkers, LZ4F_NBWORKERS_MAX);
2173
0
    LZ4F_CtxType_e const ctxType = (LZ4F_CtxType_e)cctx->lz4CtxType;
2174
0
    size_t const blockSize = cctx->maxBlockSize;
2175
0
    size_t const jobSize = LZ4F_mtJobSize(blockSize);
2176
0
    size_t const inCapacity = LZ4F_MT_PREFIX_SIZE + jobSize;
2177
0
    size_t const outCapacity = LZ4F_blocksBound(jobSize, blockSize, LZ4F_blockChecksumEnabled);
2178
0
    int const checksum = (cctx->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled);
2179
0
    LZ4F_mtCtx_t* mt = cctx->mt;
2180
0
    unsigned nbThreads, maxThreads, nbJobSlots;
2181
2182
0
    assert(nbWorkers >= 1);
2183
0
    (void)nbWorkers;   /* only employed by multi-threading support */
2184
0
    if (mt == NULL) {
2185
0
        mt = (LZ4F_mtCtx_t*)LZ4F_calloc(sizeof(*mt), cmem);
2186
0
        RETURN_ERROR_IF(mt == NULL, allocation_failed);
2187
0
        mt->history = (BYTE*)LZ4F_malloc(LZ4F_MT_PREFIX_SIZE, cmem);
2188
0
        if (mt->history == NULL) {
2189
0
            LZ4F_free(mt, cmem);
2190
0
            RETURN_ERROR(allocation_failed);
2191
0
        }
2192
0
        mt->cmem = cmem;
2193
0
        cctx->mt = mt;
2194
0
    }
2195
0
    assert(mt->nbSubmitted == 0 && !mt->filling);
2196
2197
    /* worker threads */
2198
#if LZ4F_MULTITHREAD
2199
    /* an incomplete pool (fewer threads than requested) is kept ;
2200
     * without any worker thread, frame compression fails, and next frames try again */
2201
    if ((mt->pool == NULL) || (mt->poolRequested != nbWorkers)) {
2202
        LZ4F_pool_free(mt->pool, cmem);
2203
        mt->pool = LZ4F_pool_create(nbWorkers, (unsigned)LZ4F_MT_NBSLOTS(nbWorkers), cmem);   /* queue : all job slots */
2204
        mt->poolRequested = nbWorkers;
2205
        LZ4F_pool_free(mt->hPool, cmem);   /* its queue holds all job slots too */
2206
        mt->hPool = NULL;
2207
        RETURN_ERROR_IF(mt->pool == NULL, allocation_failed);
2208
    }
2209
    /* content checksum : hashing thread, kept for next frames ; on creation failure, the calling thread hashes jobs */
2210
    if (checksum && (mt->hPool == NULL))
2211
        mt->hPool = LZ4F_pool_create(1, (unsigned)LZ4F_MT_NBSLOTS(nbWorkers), cmem);
2212
#endif
2213
    /* resources are sized for the maximum nb of threads, but only allocated when needed :
2214
     * threads with their LZ4 state, job slots' outputs and input buffers */
2215
0
    nbThreads = LZ4F_pool_nbThreads(mt->pool);   /* already started */
2216
0
    maxThreads = mt->pool ? mt->poolRequested : 0;
2217
0
    nbJobSlots = maxThreads ? (unsigned)LZ4F_MT_NBSLOTS(maxThreads) : 1;
2218
2219
    /* one LZ4 state per worker */
2220
0
    if ((mt->nbStates != maxThreads + 1) || (mt->statesType != ctxType)) {
2221
0
        LZ4F_mt_freeStates(mt, cmem);
2222
0
        mt->states = (void**)LZ4F_calloc((maxThreads + 1) * sizeof(void*), cmem);
2223
0
        RETURN_ERROR_IF(mt->states == NULL, allocation_failed);
2224
0
        mt->nbStates = maxThreads + 1;
2225
0
        mt->statesType = ctxType;
2226
0
    }
2227
0
    {   unsigned n;
2228
0
        for (n = 1; n <= nbThreads; n++)   /* threads already started (previous frames) */
2229
0
            RETURN_ERROR_IF(!LZ4F_mt_allocState(mt, n, cctx->prefs.compressionLevel), allocation_failed);
2230
0
    }
2231
0
    mt->states[0] = cctx->lz4CtxPtr;
2232
2233
    /* job slots (outputs allocated on first use) */
2234
0
    if (mt->nbJobSlots != nbJobSlots) {
2235
0
        LZ4F_mt_freeJobs(mt, cmem);
2236
0
        mt->jobs = (LZ4F_mtJob_t*)LZ4F_calloc(nbJobSlots * sizeof(LZ4F_mtJob_t), cmem);
2237
0
        RETURN_ERROR_IF(mt->jobs == NULL, allocation_failed);
2238
0
        mt->nbJobSlots = nbJobSlots;
2239
0
    }
2240
0
    if (mt->outCapacity < outCapacity) {
2241
0
        unsigned n;
2242
0
        for (n = 0; n < mt->nbJobSlots; n++) {
2243
0
            LZ4F_free(mt->jobs[n].outBuff, cmem);
2244
0
            mt->jobs[n].outBuff = NULL;
2245
0
        }
2246
0
        mt->outCapacity = outCapacity;
2247
0
    }
2248
2249
    /* input buffers : one per thread, plus the one being filled (allocated on first need) */
2250
0
    if ((mt->maxInBuffs != maxThreads + LZ4F_MT_EXTRA_INBUFFS) || (mt->inCapacity < inCapacity)) {
2251
0
        LZ4F_mt_freeInBuffs(mt, cmem);
2252
0
        mt->inBuffs = (BYTE**)LZ4F_malloc((maxThreads + LZ4F_MT_EXTRA_INBUFFS) * sizeof(BYTE*), cmem);
2253
0
        mt->inFree = (BYTE**)LZ4F_malloc((maxThreads + LZ4F_MT_EXTRA_INBUFFS) * sizeof(BYTE*), cmem);
2254
0
        if ((mt->inBuffs == NULL) || (mt->inFree == NULL)) {
2255
0
            LZ4F_mt_freeInBuffs(mt, cmem);
2256
0
            RETURN_ERROR(allocation_failed);
2257
0
        }
2258
0
        mt->maxInBuffs = maxThreads + LZ4F_MT_EXTRA_INBUFFS;
2259
0
        mt->inCapacity = inCapacity;
2260
0
    }
2261
2262
    /* current frame */
2263
0
    {   unsigned n;
2264
0
        for (n = 0; n < nbJobSlots; n++) mt->jobs[n].mt = mt;
2265
0
    }
2266
0
    mt->prefs = &cctx->prefs;
2267
0
    mt->cdict = cctx->cdict;
2268
0
    mt->blockSize = blockSize;
2269
0
    mt->jobSize = jobSize;
2270
0
    mt->xxh = checksum ? &cctx->xxh : NULL;
2271
0
    mt->oldest = 0;
2272
0
    mt->emitted = 0;
2273
0
    mt->nbSubmitted = 0;
2274
0
    mt->filling = 0;
2275
0
    mt->historySize = 0;
2276
0
    mt->stableEnd = NULL;
2277
0
    mt->stableRun = 0;
2278
0
    cctx->mtActive = 1;
2279
0
    return 0;
2280
0
}
2281
2282
/*! LZ4F_mt_flushPoint() :
2283
 *  LZ4F_flush() and LZ4F_compressEnd(), multi-threaded mode : the job being filled is submitted (see LZ4F_mt_submitLast()),
2284
 *  and all jobs are waited for : input is no longer read, and their output is emitted by LZ4F_mt_emitPartial(). */
2285
static void LZ4F_mt_flushPoint(LZ4F_mtCtx_t* mt)
2286
0
{
2287
0
    unsigned n;
2288
0
    if (mt->filling) LZ4F_mt_submitLast(mt);
2289
0
    for (n = 0; n < mt->nbSubmitted; n++)
2290
0
        LZ4F_pool_waitDone(mt->pool, &LZ4F_mt_job(mt, n)->pending);
2291
0
}
2292
2293
/*! LZ4F_mt_emitPartial() :
2294
 *  emits completed jobs in order into @dst + @pos, as much as fits : the oldest one can be emitted partially.
2295
 *  Requires all submitted jobs completed, see LZ4F_mt_flushPoint().
2296
 * @return : nb of bytes written, or an error code */
2297
static size_t LZ4F_mt_emitPartial(LZ4F_mtCtx_t* mt, BYTE* dst, size_t dstCapacity, size_t pos)
2298
0
{
2299
0
    size_t const start = pos;
2300
0
    while (mt->nbSubmitted > 0) {
2301
0
        LZ4F_mtJob_t* const job = mt->jobs + mt->oldest;
2302
0
        size_t n;
2303
0
        assert(LZ4F_pool_isDone(mt->pool, &job->pending));
2304
0
        FORWARD_IF_ERROR(job->cSize);
2305
0
        n = MIN(job->cSize - mt->emitted, dstCapacity - pos);
2306
0
        if (n) LZ4_memcpy(dst + pos, job->outBuff + mt->emitted, n);
2307
0
        pos += n;
2308
0
        mt->emitted += n;
2309
0
        if (mt->emitted < job->cSize) break;   /* dst is full */
2310
0
        LZ4F_mt_retireOldest(mt);
2311
0
    }
2312
0
    return pos - start;
2313
0
}
2314
2315
/*! LZ4F_mt_update() :
2316
 *  LZ4F_compressUpdate(), multi-threaded mode (@mode : compressed or uncompressed input ; @cOptPtr : not NULL).
2317
 *  Input is copied into jobs, submitted once full.
2318
 *  Job content is read in place instead, when it remains available until the job completes :
2319
 *  with stableSrc == LZ4F_srcStableUntilFlush, or with autoFlush, since all jobs complete within the invocation.
2320
 *  LZ4F_srcStable (historical value 1) only guarantees the last 64 KB : content is copied.
2321
 *  Uncompressed segments are jobs too : a mode switch submits the job being filled,
2322
 *  so that blocks are cut as in single-threaded mode (the buffered block is flushed on a mode switch).
2323
 *  Completed jobs are emitted in order, as long as they fit. With autoFlush, all input is compressed and emitted.
2324
 *  Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, prefs) :
2325
 *  without autoFlush, output is only required to start a job while all slots are busy (oldest job). */
2326
static size_t LZ4F_mt_update(LZ4F_cctx_t* cctx,
2327
                             void* dstBuffer, size_t dstCapacity,
2328
                       const void* srcBuffer, size_t srcSize,
2329
                       const LZ4F_compressOptions_t* cOptPtr,
2330
                             LZ4F_BlockCompressMode_e mode)
2331
0
{
2332
0
    LZ4F_mtCtx_t* const mt = cctx->mt;
2333
0
    const BYTE* const istart = (const BYTE*)srcBuffer;
2334
0
    const BYTE* ip = istart;
2335
0
    const BYTE* const iend = srcSize ? istart + srcSize : istart;
2336
0
    BYTE* const dst = (BYTE*)dstBuffer;
2337
0
    size_t pos = 0;
2338
0
    int const linked = (cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked);
2339
0
    int const stableUntilFlush = (cOptPtr->stableSrc == LZ4F_srcStableUntilFlush);
2340
0
    int const inPlace = cctx->prefs.autoFlush || stableUntilFlush;
2341
    /* stable input remains available : when contiguous with previous input, history can be read in place */
2342
0
    size_t const prevRun = (stableUntilFlush && srcSize && (istart == mt->stableEnd)) ? mt->stableRun : 0;
2343
2344
0
    DEBUGLOG(4, "LZ4F_mt_update (srcSize=%u, mode=%u)", (unsigned)srcSize, (unsigned)mode);
2345
0
    RETURN_ERROR_IF(cctx->cStage != 1, compressionState_uninitialized);
2346
0
    assert(cctx->pendingSize == 0);   /* multi-threaded mode : pending output is within jobs */
2347
0
    cctx->flushStage = 0;   /* an incomplete LZ4F_flush() ends here : remaining jobs are emitted as usual */
2348
0
    if (mt->filling && (LZ4F_mt_fillingSlot(mt)->mode != mode))
2349
0
        LZ4F_mt_submit(mt);   /* mode switch */
2350
2351
0
    while (ip < iend) {
2352
0
        LZ4F_mtJob_t* const job = LZ4F_mt_fillingSlot(mt);
2353
0
        if (!mt->filling) {
2354
            /* new job */
2355
0
            size_t const remaining = (size_t)(iend - ip);
2356
0
            size_t const prefixSize = linked ? mt->historySize : 0;
2357
0
            if (mt->nbSubmitted >= LZ4F_mt_nbUsableSlots(mt)) {
2358
                /* all slots busy : emit oldest job, to free a slot */
2359
0
                size_t const r = LZ4F_mt_emitOldest(mt, dst, dstCapacity, pos);
2360
0
                FORWARD_IF_ERROR_INVALIDATE(r, cctx);
2361
0
                pos += r;
2362
0
                assert(job == LZ4F_mt_fillingSlot(mt));
2363
0
            }
2364
0
            if (job->outBuff == NULL) {   /* first use of this slot */
2365
0
                job->outBuff = (BYTE*)LZ4F_malloc(mt->outCapacity, cctx->cmem);
2366
0
                if (job->outBuff == NULL) {
2367
0
                    LZ4F_invalidateFrame(cctx);
2368
0
                    RETURN_ERROR(allocation_failed);
2369
0
                }
2370
0
            }
2371
0
            mt->filling = 1;
2372
0
            job->mode = mode;
2373
0
            job->prefixSize = prefixSize;
2374
0
            if ( inPlace
2375
0
              && ((remaining >= mt->jobSize) || cctx->prefs.autoFlush)
2376
0
              && (prevRun + (size_t)(ip - istart) >= prefixSize) ) {
2377
                /* read in place : whole job is within @srcBuffer, and its history right before */
2378
0
                size_t const jobSize = MIN(remaining, mt->jobSize);
2379
0
                job->src = ip;
2380
0
                job->srcSize = jobSize;
2381
0
                if (cctx->prefs.autoFlush && (jobSize == remaining))
2382
0
                    LZ4F_mt_submitLast(mt);   /* all jobs are waited for before returning */
2383
0
                else
2384
0
                    LZ4F_mt_submit(mt);
2385
0
                ip += jobSize;
2386
0
                continue;
2387
0
            }
2388
            /* copy : history first, right before content */
2389
0
            assert(job->inBuff == NULL);
2390
0
            job->inBuff = LZ4F_mt_acquireInBuff(mt, cctx->cmem);
2391
0
            if (job->inBuff == NULL) {
2392
0
                mt->filling = 0;
2393
0
                LZ4F_invalidateFrame(cctx);
2394
0
                RETURN_ERROR(allocation_failed);
2395
0
            }
2396
0
            job->src = job->inBuff + LZ4F_MT_PREFIX_SIZE;
2397
0
            job->srcSize = 0;
2398
0
            LZ4_memcpy(job->inBuff + LZ4F_MT_PREFIX_SIZE - prefixSize, mt->history + mt->historySize - prefixSize, prefixSize);
2399
0
        }
2400
0
        {   size_t const toCopy = MIN(mt->jobSize - job->srcSize, (size_t)(iend - ip));
2401
0
            assert(job->src == job->inBuff + LZ4F_MT_PREFIX_SIZE);
2402
0
            LZ4_memcpy(job->inBuff + LZ4F_MT_PREFIX_SIZE + job->srcSize, ip, toCopy);
2403
0
            job->srcSize += toCopy;
2404
0
            if (job->srcSize == mt->jobSize) LZ4F_mt_submit(mt);
2405
0
            ip += toCopy;
2406
0
        }
2407
0
    }
2408
0
    cctx->totalInSize += srcSize;
2409
0
    if (srcSize) {
2410
0
        mt->stableEnd = stableUntilFlush ? iend : NULL;
2411
0
        mt->stableRun = MIN(prevRun + srcSize, LZ4F_MT_PREFIX_SIZE);
2412
0
    }
2413
2414
    /* autoFlush : the last job is submitted too (see LZ4F_mt_submitLast()), and all jobs are emitted */
2415
0
    if (cctx->prefs.autoFlush && mt->filling) LZ4F_mt_submitLast(mt);
2416
0
    {   size_t const r = LZ4F_mt_emit(mt, dst, dstCapacity, pos, cctx->prefs.autoFlush != 0);
2417
0
        FORWARD_IF_ERROR_INVALIDATE(r, cctx);
2418
0
        return pos + r;
2419
0
    }
2420
0
}
2421
2422
2423
/*! LZ4F_st_update() :
2424
 *  LZ4F_compressUpdate(), single-threaded mode (@blockCompression : compressed or uncompressed input ;
2425
 *  @compressOptionsPtr : not NULL).
2426
 *  Input first completes the block buffered within cctx, then full blocks are compressed directly from @srcBuffer
2427
 *  (all remaining input with autoFlush), and the remainder is buffered.
2428
 *  A change of @blockCompression first flushes the buffered block. */
2429
static size_t LZ4F_st_update(LZ4F_cctx* cctxPtr,
2430
                     void* dstBuffer, size_t dstCapacity,
2431
                     const void* srcBuffer, size_t srcSize,
2432
                     const LZ4F_compressOptions_t* compressOptionsPtr,
2433
                     LZ4F_BlockCompressMode_e blockCompression)
2434
39.8k
  {
2435
39.8k
    size_t const blockSize = cctxPtr->maxBlockSize;
2436
39.8k
    const BYTE* srcPtr = (const BYTE*)srcBuffer;
2437
39.8k
    const BYTE* const srcEnd = srcSize ? (assert(srcPtr!=NULL), srcPtr + srcSize) : srcPtr;
2438
39.8k
    BYTE* const dstStart = (BYTE*)dstBuffer;
2439
39.8k
    BYTE* const dstEnd = dstStart + dstCapacity;
2440
39.8k
    BYTE* dstPtr = dstStart;
2441
39.8k
    LZ4F_lastBlockStatus lastBlockCompressed = notDone;
2442
39.8k
    compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, blockCompression);
2443
39.8k
    size_t bytesWritten;
2444
39.8k
    DEBUGLOG(4, "LZ4F_compressUpdate (srcSize=%zu)", srcSize);
2445
2446
39.8k
    RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized);   /* state must be initialized and waiting for next block */
2447
2448
    /* output left pending by an incomplete LZ4F_flush() */
2449
39.8k
    bytesWritten = LZ4F_emitPendingWhole(cctxPtr, dstPtr, dstCapacity);
2450
39.8k
    FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
2451
39.8k
    dstPtr += bytesWritten;
2452
2453
    /* flush currently written block, to continue with new block compression */
2454
39.8k
    if (cctxPtr->blockCompressMode != blockCompression) {
2455
0
        bytesWritten = LZ4F_flushBlock(cctxPtr, dstPtr, (size_t)(dstEnd - dstPtr));
2456
0
        FORWARD_IF_ERROR(bytesWritten);   /* note : a failed flush invalidates the frame */
2457
0
        dstPtr += bytesWritten;
2458
0
        cctxPtr->blockCompressMode = blockCompression;
2459
0
        if ((blockCompression == LZ4B_UNCOMPRESSED) && (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)) {
2460
            /* linked blocks : the decoder's history will contain uncompressed data, unknown to the LZ4 state :
2461
             * history is dropped, blocks compressed next don't reference anything before them */
2462
0
            LZ4F_startStream(cctxPtr->lz4CtxPtr, &cctxPtr->prefs, NULL, NULL, 0);
2463
0
        }
2464
0
    }
2465
2466
    /* complete tmp buffer */
2467
39.8k
    if (cctxPtr->tmpInSize > 0) {   /* some data already within tmp buffer */
2468
9.90k
        size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize;
2469
9.90k
        assert(blockSize > cctxPtr->tmpInSize);
2470
9.90k
        if (sizeToCopy > srcSize) {
2471
            /* add src to tmpIn buffer */
2472
8.63k
            LZ4_memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);
2473
8.63k
            srcPtr = srcEnd;
2474
8.63k
            cctxPtr->tmpInSize += srcSize;
2475
            /* still needs some CRC */
2476
8.63k
        } else {
2477
            /* complete tmpIn block and then compress it */
2478
1.27k
            lastBlockCompressed = fromTmpBuffer;
2479
1.27k
            LZ4_memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);
2480
1.27k
            srcPtr += sizeToCopy;
2481
2482
1.27k
            bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr),
2483
1.27k
                                          cctxPtr->tmpIn, blockSize,
2484
1.27k
                                          compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
2485
1.27k
                                          cctxPtr->cdict,
2486
1.27k
                                          cctxPtr->prefs.frameInfo.blockChecksumFlag);
2487
1.27k
            FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
2488
1.27k
            dstPtr += bytesWritten;
2489
1.27k
            if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize;
2490
1.27k
            cctxPtr->tmpInSize = 0;
2491
1.27k
    }   }
2492
2493
    /* compress full blocks; with autoFlush, remaining input (< blockSize) is compressed too */
2494
39.8k
    {   size_t const remaining = (size_t)(srcEnd - srcPtr);
2495
39.8k
        size_t const toCompress = cctxPtr->prefs.autoFlush ? remaining : remaining - (remaining % blockSize);
2496
        /* autoFlush, linked blocks, unstable input smaller than the history window (64 KB) :
2497
         * compressed from @srcBuffer, it would become the only history of next blocks.
2498
         * It's compressed from tmpBuff instead, right after the history, which remains whole. */
2499
39.8k
        int const viaTmp = cctxPtr->prefs.autoFlush
2500
19.6k
                        && (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)
2501
14.6k
                        && !compressOptionsPtr->stableSrc
2502
14.6k
                        && (blockCompression == LZ4B_COMPRESSED)
2503
14.6k
                        && (toCompress > 0) && (toCompress < 64 KB);
2504
39.8k
        if (viaTmp) {
2505
6.69k
            if (cctxPtr->tmpIn + toCompress > cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity)
2506
0
                LZ4F_localSaveDict(cctxPtr);   /* tmpBuff >= 128 KB : room after the history */
2507
6.69k
            LZ4_memcpy(cctxPtr->tmpIn, srcPtr, toCompress);
2508
6.69k
            lastBlockCompressed = fromTmpBuffer;
2509
6.69k
            bytesWritten = LZ4F_makeBlock(dstPtr, (size_t)(dstEnd - dstPtr),
2510
6.69k
                                          cctxPtr->tmpIn, toCompress,
2511
6.69k
                                          compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
2512
6.69k
                                          cctxPtr->cdict,
2513
6.69k
                                          cctxPtr->prefs.frameInfo.blockChecksumFlag);
2514
6.69k
            FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
2515
6.69k
            dstPtr += bytesWritten;
2516
6.69k
            srcPtr += toCompress;
2517
6.69k
            cctxPtr->tmpIn += toCompress;
2518
33.1k
        } else if (toCompress) {
2519
14.1k
            lastBlockCompressed = fromSrcBuffer;
2520
14.1k
            bytesWritten = LZ4F_compressBlocks_internal(dstPtr, (size_t)(dstEnd - dstPtr),
2521
14.1k
                                          srcPtr, toCompress, blockSize,
2522
14.1k
                                          compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,
2523
14.1k
                                          cctxPtr->cdict,
2524
14.1k
                                          cctxPtr->prefs.frameInfo.blockChecksumFlag);
2525
14.1k
            FORWARD_IF_ERROR_INVALIDATE(bytesWritten, cctxPtr);
2526
14.1k
            dstPtr += bytesWritten;
2527
14.1k
            srcPtr += toCompress;
2528
14.1k
    }   }
2529
2530
    /* preserve dictionary within @tmpBuff whenever necessary */
2531
39.8k
    if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) {
2532
        /* note : after uncompressed blocks, the LZ4 state is empty (history dropped), so is the saved dictionary */
2533
8.99k
        if (compressOptionsPtr->stableSrc) {
2534
0
            cctxPtr->tmpIn = cctxPtr->tmpBuff;  /* src is stable : dictionary remains in src across invocations */
2535
8.99k
        } else {
2536
8.99k
            LZ4F_localSaveDict(cctxPtr);
2537
8.99k
        }
2538
8.99k
    }
2539
2540
    /* keep tmpIn within limits */
2541
39.8k
    if (!(cctxPtr->prefs.autoFlush)  /* no autoflush : there may be some data left within internal buffer */
2542
20.2k
      && (cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity) )  /* not enough room to store next block */
2543
444
    {
2544
        /* only preserve 64KB within internal buffer. Ensures there is enough room for next block.
2545
         * note: this situation necessarily implies lastBlockCompressed==fromTmpBuffer */
2546
444
        LZ4F_localSaveDict(cctxPtr);
2547
444
        assert((cctxPtr->tmpIn + blockSize) <= (cctxPtr->tmpBuff + cctxPtr->tmpBuffCapacity));
2548
444
    }
2549
2550
    /* some input data left, necessarily < blockSize */
2551
39.8k
    if (srcPtr < srcEnd) {
2552
        /* fill tmp buffer */
2553
10.3k
        size_t const sizeToCopy = (size_t)(srcEnd - srcPtr);
2554
10.3k
        LZ4_memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);
2555
10.3k
        cctxPtr->tmpInSize = sizeToCopy;
2556
10.3k
    }
2557
2558
39.8k
    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled)
2559
15.8k
        (void)XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize);
2560
2561
39.8k
    cctxPtr->totalInSize += srcSize;
2562
39.8k
    return (size_t)(dstPtr - dstStart);
2563
39.8k
}
2564
2565
/*! LZ4F_compressUpdate() :
2566
 *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
2567
 *  When successful, the function always entirely consumes @srcBuffer.
2568
 *  src data is either buffered or compressed into @dstBuffer.
2569
 *  With @compressOptionsPtr->uncompressed == 1, src data is stored as uncompressed blocks instead.
2570
 *  With linked blocks, blocks compressed next don't reference data preceding them (single-threaded mode),
2571
 *  or reference the uncompressed data (multi-threaded mode, see LZ4F_compressJob()).
2572
 *  A switch between compressed and uncompressed input first flushes buffered data.
2573
 *  Success is guaranteed when @dstCapacity >= LZ4F_compressBound(srcSize, preferencesPtr).
2574
 *  Otherwise, the operation fails with dstCapacity_tooSmall if its output doesn't fit.
2575
 * @compressOptionsPtr is optional : provide NULL to mean "default".
2576
 * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
2577
 *           or an error code if it fails (which can be tested using LZ4F_isError())
2578
 *  After an error, the frame is invalidated, and must be restarted with LZ4F_compressBegin().
2579
 */
2580
size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr,
2581
                           void* dstBuffer, size_t dstCapacity,
2582
                     const void* srcBuffer, size_t srcSize,
2583
                     const LZ4F_compressOptions_t* compressOptionsPtr)
2584
39.8k
{
2585
39.8k
    LZ4F_BlockCompressMode_e mode;
2586
39.8k
    if (compressOptionsPtr == NULL) compressOptionsPtr = &k_cOptionsNull;
2587
39.8k
    mode = (compressOptionsPtr->uncompressed == 1) ? LZ4B_UNCOMPRESSED : LZ4B_COMPRESSED;
2588
39.8k
    if (cctxPtr->mtActive)
2589
0
        return LZ4F_mt_update(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, compressOptionsPtr, mode);
2590
39.8k
    return LZ4F_st_update(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, compressOptionsPtr, mode);
2591
39.8k
}
2592
2593
/*! LZ4F_uncompressedUpdate() : deprecated
2594
 *  LZ4F_compressUpdate() with option uncompressed.
2595
 */
2596
size_t LZ4F_uncompressedUpdate(LZ4F_cctx* cctxPtr,
2597
                               void* dstBuffer, size_t dstCapacity,
2598
                         const void* srcBuffer, size_t srcSize,
2599
                         const LZ4F_compressOptions_t* compressOptionsPtr)
2600
0
{
2601
0
    LZ4F_compressOptions_t cOpts = k_cOptionsNull;
2602
0
    if (compressOptionsPtr != NULL) cOpts = *compressOptionsPtr;
2603
0
    cOpts.uncompressed = 1;
2604
0
    return LZ4F_compressUpdate(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, &cOpts);
2605
0
}
2606
2607
2608
/* emits pending output into @dst + @pos, as much as fits : block or footer (pending), then jobs (multi-threaded mode).
2609
 * @return : new position, or an error code (the frame is then invalidated) */
2610
static size_t LZ4F_emitPending(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity, size_t pos)
2611
15.6k
{
2612
15.6k
    pos += LZ4F_copyPending(cctx, dst, dstCapacity, pos);
2613
15.6k
    if (cctx->mtActive && (cctx->pendingSize == 0)) {
2614
0
        size_t const r = LZ4F_mt_emitPartial(cctx->mt, dst, dstCapacity, pos);
2615
0
        FORWARD_IF_ERROR_INVALIDATE(r, cctx);
2616
0
        pos += r;
2617
0
    }
2618
15.6k
    return pos;
2619
15.6k
}
2620
2621
static int LZ4F_outputPending(const LZ4F_cctx_t* cctx)
2622
15.6k
{
2623
15.6k
    return (cctx->pendingSize > 0) || (cctx->mtActive && (cctx->mt->nbSubmitted > 0));
2624
15.6k
}
2625
2626
/* @return : 1 if LZ4F_flush() has output to produce */
2627
static int LZ4F_somethingToFlush(const LZ4F_cctx_t* cctx)
2628
0
{
2629
0
    if (LZ4F_outputPending(cctx)) return 1;
2630
0
    if (cctx->mtActive) return cctx->mt->filling;
2631
0
    return cctx->tmpInSize > 0;
2632
0
}
2633
2634
/* flush point : input retained within cctx is compressed, and no longer read.
2635
 * @return : nb of bytes written into @dst, or an error code (the frame is then invalidated) */
2636
static size_t LZ4F_flushPoint(LZ4F_cctx_t* cctx, BYTE* dst, size_t dstCapacity)
2637
15.6k
{
2638
15.6k
    size_t r = 0;
2639
15.6k
    if (cctx->mtActive) {
2640
0
        LZ4F_mt_flushPoint(cctx->mt);
2641
15.6k
    } else {
2642
15.6k
        r = LZ4F_flushBlockPartial(cctx, dst, dstCapacity);
2643
15.6k
    }
2644
15.6k
    if (!LZ4F_isError(r)) cctx->flushStage = 1;
2645
15.6k
    return r;
2646
15.6k
}
2647
2648
/*! LZ4F_flush() :
2649
 *  When compressed data must be sent immediately, without waiting for a block to be filled,
2650
 *  invoke LZ4F_flush(), which will immediately compress any remaining data stored within LZ4F_cctx.
2651
 *  The invocation fills @dstBuffer, or completes the flush :
2652
 *  as long as it returns @dstCapacity, output may remain : invoke LZ4F_flush() again.
2653
 *  The first invocation sets the flush point : input retained within cctx is compressed (all jobs completed).
2654
 *  The result of the function is the number of bytes written into dstBuffer.
2655
 *  It can be zero, this means there was no data left within LZ4F_cctx.
2656
 *  The function outputs an error code if it fails (can be tested using LZ4F_isError())
2657
 *  A single invocation completes the flush when dstCapacity >= LZ4F_compressBound(0, preferencesPtr).
2658
 *  dstCapacity == 0 is rejected (dstCapacity_tooSmall) when there is something to flush, without modifying the frame.
2659
 *  LZ4F_compressOptions_t* is optional : NULL is a valid argument.
2660
 */
2661
size_t LZ4F_flush(LZ4F_cctx* cctxPtr,
2662
                  void* dstBuffer, size_t dstCapacity,
2663
            const LZ4F_compressOptions_t* compressOptionsPtr)
2664
0
{
2665
0
    BYTE* const dst = (BYTE*)dstBuffer;
2666
0
    size_t pos = 0;
2667
0
    DEBUGLOG(5, "LZ4F_flush (dstCapacity=%u)", (unsigned)dstCapacity);
2668
0
    (void)compressOptionsPtr;   /* not useful (yet) */
2669
0
    RETURN_ERROR_IF(cctxPtr->cStage != 1, compressionState_uninitialized);
2670
0
    if (dstCapacity == 0) {
2671
        /* no progress possible : rejected, the frame continues */
2672
0
        RETURN_ERROR_IF(LZ4F_somethingToFlush(cctxPtr), dstCapacity_tooSmall);
2673
0
        cctxPtr->flushStage = 0;
2674
0
        return 0;
2675
0
    }
2676
0
    if (cctxPtr->flushStage == 0) {
2677
0
        pos = LZ4F_flushPoint(cctxPtr, dst, dstCapacity);
2678
0
        FORWARD_IF_ERROR(pos);   /* already invalidated */
2679
0
    }
2680
0
    pos = LZ4F_emitPending(cctxPtr, dst, dstCapacity, pos);
2681
0
    FORWARD_IF_ERROR(pos);   /* already invalidated */
2682
0
    if (pos < dstCapacity) cctxPtr->flushStage = 0;   /* completed */
2683
0
    return pos;
2684
0
}
2685
2686
2687
/*! LZ4F_compressEnd() :
2688
 *  When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
2689
 *  It will flush whatever data remained within compressionContext (like LZ4_flush())
2690
 *  but also properly finalize the frame, with an endMark and an (optional) checksum.
2691
 *  The invocation fills @dstBuffer, or completes the frame :
2692
 *  as long as it returns @dstCapacity, output may remain : invoke LZ4F_compressEnd() again.
2693
 *  LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
2694
 * @return: the number of bytes written into dstBuffer (the last invocation writes the endMark, unless already written)
2695
 *       or an error code if it fails (can be tested using LZ4F_isError())
2696
 *  Once completed, the context can be used again to compress a new frame, starting with LZ4F_compressBegin().
2697
 */
2698
size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr,
2699
                        void* dstBuffer, size_t dstCapacity,
2700
                  const LZ4F_compressOptions_t* compressOptionsPtr)
2701
15.6k
{
2702
15.6k
    BYTE* const dst = (BYTE*)dstBuffer;
2703
15.6k
    size_t pos = 0;
2704
15.6k
    DEBUGLOG(5,"LZ4F_compressEnd: dstCapacity=%u", (unsigned)dstCapacity);
2705
15.6k
    (void)compressOptionsPtr;   /* not useful (yet) */
2706
15.6k
    RETURN_ERROR_IF((cctxPtr->cStage != 1) && (cctxPtr->cStage != 2), compressionState_uninitialized);
2707
15.6k
    RETURN_ERROR_IF(dstCapacity == 0, dstCapacity_tooSmall);   /* no progress possible : rejected, the frame continues */
2708
2709
15.6k
    if (cctxPtr->cStage == 1) {
2710
        /* end of frame : no more input */
2711
15.6k
        if (cctxPtr->prefs.frameInfo.contentSize && (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)) {
2712
0
            LZ4F_invalidateFrame(cctxPtr);
2713
0
            RETURN_ERROR(frameSize_wrong);
2714
0
        }
2715
15.6k
        cctxPtr->cStage = 2;
2716
15.6k
        if (cctxPtr->flushStage == 0) {
2717
15.6k
            pos = LZ4F_flushPoint(cctxPtr, dst, dstCapacity);
2718
15.6k
            FORWARD_IF_ERROR(pos);   /* already invalidated */
2719
15.6k
    }   }
2720
2721
15.6k
    if (cctxPtr->flushStage == 1) {
2722
15.6k
        pos = LZ4F_emitPending(cctxPtr, dst, dstCapacity, pos);
2723
15.6k
        FORWARD_IF_ERROR(pos);   /* already invalidated */
2724
15.6k
        if (LZ4F_outputPending(cctxPtr)) return pos;   /* dstBuffer is full */
2725
        /* footer : endMark, then optional content checksum */
2726
15.6k
        LZ4F_writeLE32(cctxPtr->footer, 0);
2727
15.6k
        cctxPtr->pendingSize = 4;
2728
15.6k
        if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) {
2729
6.36k
            U32 const xxh = XXH32_digest(&(cctxPtr->xxh));
2730
6.36k
            DEBUGLOG(5,"Writing 32-bit content checksum (0x%0X)", xxh);
2731
6.36k
            LZ4F_writeLE32(cctxPtr->footer + 4, xxh);
2732
6.36k
            cctxPtr->pendingSize = 8;
2733
6.36k
        }
2734
15.6k
        cctxPtr->pending = cctxPtr->footer;
2735
15.6k
        cctxPtr->flushStage = 2;
2736
15.6k
    }
2737
2738
15.6k
    if (cctxPtr->flushStage == 2) {
2739
15.6k
        pos += LZ4F_copyPending(cctxPtr, dst, dstCapacity, pos);
2740
15.6k
        if (cctxPtr->pendingSize) return pos;   /* dstBuffer is full */
2741
15.6k
        cctxPtr->flushStage = 3;
2742
15.6k
    }
2743
2744
15.6k
    assert(cctxPtr->flushStage == 3);
2745
15.6k
    if (pos < dstCapacity) {
2746
        /* completed : the context is available for a new frame */
2747
15.6k
        cctxPtr->cStage = 0;
2748
15.6k
        cctxPtr->flushStage = 0;
2749
15.6k
    }   /* otherwise, completed, but dstBuffer is full : next invocation returns 0 */
2750
15.6k
    return pos;
2751
15.6k
}
2752
2753
2754
/*-***************************************************
2755
*   Frame Decompression
2756
*****************************************************/
2757
2758
typedef enum {
2759
    dstage_getFrameHeader=0, dstage_storeFrameHeader,
2760
    dstage_init,
2761
    dstage_getBlockHeader,
2762
    dstage_copyDirect, dstage_getBlockChecksum,
2763
    dstage_getCBlock,
2764
    dstage_flushOut,
2765
    dstage_getSuffix,
2766
    dstage_getSFrameSize,
2767
    dstage_skipSkippable
2768
} dStage_t;
2769
2770
struct LZ4F_dctx_s {
2771
    LZ4F_CustomMem cmem;
2772
    LZ4F_frameInfo_t frameInfo;
2773
    U32    version;
2774
    dStage_t dStage;
2775
    U64    frameRemainingSize;
2776
    size_t maxBlockSize;
2777
    size_t tmpOutBufferCapacity;
2778
    BYTE*  tmpIn;
2779
    size_t tmpInCapacity;
2780
    size_t tmpInSize;
2781
    size_t tmpInTarget;
2782
    unsigned progressive;    /* see LZ4F_setProgressiveDecoding() */
2783
    unsigned progressiveFrame;   /* progressive decoding of the current frame : set at its start (tmpOutBuffer sized for it) */
2784
    size_t tmpInDecoded;     /* first block, incomplete : bytes of tmpIn already decoded (see LZ4F_decodeProgressive()) */
2785
    size_t blockDecoded;     /* first block, incomplete : its decoded size so far */
2786
    const BYTE* blockDict;   /* dictionary before the first block : restored after it (independent blocks) */
2787
    size_t blockDictSize;
2788
    unsigned blockNb;        /* blocks of the frame started so far, up to 2 */
2789
    BYTE*  tmpOutBuffer;
2790
    const BYTE* dict;
2791
    size_t dictSize;
2792
    BYTE*  tmpOut;
2793
    size_t tmpOutSize;
2794
    size_t tmpOutStart;
2795
    XXH32_state_t xxh;
2796
    XXH32_state_t blockChecksum;
2797
    int    skipBlockChecksum;
2798
    int    skipContentChecksum;
2799
    unsigned frameEnded;     /* a frame just ended : frameInfo still describes it (see LZ4F_getFrameInfo()) */
2800
    BYTE   header[LZ4F_HEADER_SIZE_MAX];
2801
};  /* typedef'd to LZ4F_dctx in lz4frame.h */
2802
2803
2804
LZ4F_dctx* LZ4F_createDecompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version)
2805
31.3k
{
2806
31.3k
    LZ4F_dctx* const dctx = (LZ4F_dctx*)LZ4F_calloc(sizeof(LZ4F_dctx), customMem);
2807
31.3k
    if (dctx == NULL) return NULL;
2808
2809
31.3k
    dctx->cmem = customMem;
2810
31.3k
    dctx->version = version;
2811
31.3k
    return dctx;
2812
31.3k
}
2813
2814
/*! LZ4F_createDecompressionContext() :
2815
 *  Create a decompressionContext object, which will track all decompression operations.
2816
 *  Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object.
2817
 *  Object can later be released using LZ4F_freeDecompressionContext().
2818
 * @return : if != 0, there was an error during context creation.
2819
 */
2820
LZ4F_errorCode_t
2821
LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber)
2822
0
{
2823
0
    assert(LZ4F_decompressionContextPtr != NULL);  /* violation of narrow contract */
2824
0
    RETURN_ERROR_IF(LZ4F_decompressionContextPtr == NULL, parameter_null);  /* in case it nonetheless happen in production */
2825
2826
0
    *LZ4F_decompressionContextPtr = LZ4F_createDecompressionContext_advanced(LZ4F_defaultCMem, versionNumber);
2827
0
    if (*LZ4F_decompressionContextPtr == NULL) {  /* failed allocation */
2828
0
        RETURN_ERROR(allocation_failed);
2829
0
    }
2830
0
    return LZ4F_OK_NoError;
2831
0
}
2832
2833
LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx)
2834
31.3k
{
2835
31.3k
    LZ4F_errorCode_t result = LZ4F_OK_NoError;
2836
31.3k
    if (dctx != NULL) {   /* can accept NULL input, like free() */
2837
31.3k
      result = (LZ4F_errorCode_t)dctx->dStage;
2838
31.3k
      LZ4F_free(dctx->tmpIn, dctx->cmem);
2839
31.3k
      LZ4F_free(dctx->tmpOutBuffer, dctx->cmem);
2840
31.3k
      LZ4F_free(dctx, dctx->cmem);
2841
31.3k
    }
2842
31.3k
    return result;
2843
31.3k
}
2844
2845
0
size_t LZ4F_dctx_size(const LZ4F_dctx* dctx) {
2846
0
    if (dctx == NULL) {
2847
0
        return 0;
2848
0
    }
2849
0
    return sizeof(*dctx) + dctx->tmpInCapacity + dctx->tmpOutBufferCapacity;
2850
0
}
2851
2852
2853
/*==---   Streaming Decompression operations   ---==*/
2854
void LZ4F_setProgressiveDecoding(LZ4F_dctx* dctx, unsigned enable)
2855
0
{
2856
0
    dctx->progressive = (enable != 0);
2857
0
}
2858
2859
void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx)
2860
33.5k
{
2861
33.5k
    DEBUGLOG(5, "LZ4F_resetDecompressionContext");
2862
33.5k
    dctx->dStage = dstage_getFrameHeader;
2863
33.5k
    dctx->dict = NULL;
2864
33.5k
    dctx->dictSize = 0;
2865
33.5k
    dctx->skipBlockChecksum = 0;
2866
33.5k
    dctx->skipContentChecksum = 0;
2867
33.5k
    dctx->frameRemainingSize = 0;
2868
33.5k
    dctx->frameEnded = 0;
2869
33.5k
}
2870
2871
/* LZ4F_endFrame() :
2872
 * prepares dctx for a new frame, keeping the parameters of the frame that just ended (see LZ4F_getFrameInfo()) */
2873
static void LZ4F_endFrame(LZ4F_dctx* dctx)
2874
18.3k
{
2875
18.3k
    LZ4F_resetDecompressionContext(dctx);
2876
18.3k
    dctx->frameEnded = 1;
2877
18.3k
}
2878
2879
2880
/*! LZ4F_decodeHeader() :
2881
 *  input   : `src` points at the **beginning of the frame**, srcSize >= minFHSize
2882
 *  output  : set internal values of dctx, such as
2883
 *            dctx->frameInfo and dctx->dStage.
2884
 *  @return : nb Bytes read from src (necessarily <= srcSize)
2885
 *            or an error code (testable with LZ4F_isError())
2886
 */
2887
static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize)
2888
50.1k
{
2889
50.1k
    unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID;
2890
50.1k
    size_t frameHeaderSize;
2891
50.1k
    const BYTE* srcPtr = (const BYTE*)src;
2892
2893
50.1k
    DEBUGLOG(5, "LZ4F_decodeHeader");
2894
50.1k
    assert(srcSize >= minFHSize);   /* minimal frame header size */
2895
50.1k
    MEM_INIT(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo));
2896
50.1k
    dctx->frameEnded = 0;
2897
2898
    /* special case : skippable frames */
2899
50.1k
    if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) {
2900
4.15k
        dctx->frameInfo.frameType = LZ4F_skippableFrame;
2901
4.15k
        dctx->dStage = dstage_getSFrameSize;
2902
4.15k
        if (src == (void*)(dctx->header)) {
2903
            /* the beginning of the frame size field is already gathered in header+4 */
2904
3.81k
            assert(srcSize <= 8);
2905
3.81k
            dctx->tmpInSize = srcSize - 4;
2906
3.81k
            return srcSize;
2907
3.81k
        } else {
2908
342
            dctx->tmpInSize = 0;
2909
342
            return 4;
2910
342
    }   }
2911
2912
    /* control magic number */
2913
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2914
    if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) {
2915
        DEBUGLOG(4, "frame header error : unknown magic number");
2916
        RETURN_ERROR(frameType_unknown);
2917
    }
2918
#endif
2919
45.9k
    dctx->frameInfo.frameType = LZ4F_frame;
2920
2921
    /* Flags */
2922
45.9k
    {   U32 const FLG = srcPtr[4];
2923
45.9k
        U32 const version = (FLG>>6) & _2BITS;
2924
45.9k
        blockChecksumFlag = (FLG>>4) & _1BIT;
2925
45.9k
        blockMode = (FLG>>5) & _1BIT;
2926
45.9k
        contentSizeFlag = (FLG>>3) & _1BIT;
2927
45.9k
        contentChecksumFlag = (FLG>>2) & _1BIT;
2928
45.9k
        dictIDFlag = FLG & _1BIT;
2929
        /* validate */
2930
45.9k
        if (((FLG>>1)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */
2931
43.4k
        if (version != 1) RETURN_ERROR(headerVersion_wrong);       /* Version Number, only supported value */
2932
43.4k
    }
2933
35.0k
    DEBUGLOG(6, "contentSizeFlag: %u", contentSizeFlag);
2934
2935
    /* Frame Header Size */
2936
35.0k
    frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
2937
2938
35.0k
    if (srcSize < frameHeaderSize) {
2939
        /* only the minimal header is gathered into dctx->header : gather the rest */
2940
1.20k
        assert(srcPtr == dctx->header);
2941
1.20k
        assert(dctx->dStage == dstage_storeFrameHeader);
2942
1.20k
        assert(dctx->tmpInSize == srcSize);
2943
1.20k
        dctx->tmpInTarget = frameHeaderSize;
2944
1.20k
        return srcSize;
2945
1.20k
    }
2946
2947
33.8k
    {   U32 const BD = srcPtr[5];
2948
33.8k
        blockSizeID = (BD>>4) & _3BITS;
2949
        /* validate */
2950
33.8k
        if (((BD>>7)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set);   /* Reserved bit */
2951
33.6k
        if (blockSizeID < 4) RETURN_ERROR(maxBlockSize_invalid);    /* 4-7 only supported values for the time being */
2952
33.3k
        if (((BD>>0)&_4BITS) != 0) RETURN_ERROR(reservedFlag_set);  /* Reserved bits */
2953
33.3k
    }
2954
2955
    /* check header */
2956
33.3k
    assert(frameHeaderSize > 5);
2957
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2958
    {   BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5);
2959
        RETURN_ERROR_IF(HC != srcPtr[frameHeaderSize-1], headerChecksum_invalid);
2960
    }
2961
#endif
2962
2963
    /* save */
2964
33.1k
    dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode;
2965
33.1k
    dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag;
2966
33.1k
    dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag;
2967
33.1k
    dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID;
2968
33.1k
    dctx->maxBlockSize = LZ4F_getBlockSize((LZ4F_blockSizeID_t)blockSizeID);
2969
33.1k
    if (contentSizeFlag) {
2970
1.37k
        dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6);
2971
1.37k
    }
2972
33.1k
    if (dictIDFlag)
2973
1.91k
        dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5);
2974
2975
33.1k
    dctx->dStage = dstage_init;
2976
2977
33.1k
    return frameHeaderSize;
2978
33.1k
}
2979
2980
2981
/*! LZ4F_headerSize() :
2982
 * @return : size of frame header
2983
 *           or an error code, which can be tested using LZ4F_isError()
2984
 */
2985
size_t LZ4F_headerSize(const void* src, size_t srcSize)
2986
31.0k
{
2987
31.0k
    RETURN_ERROR_IF(src == NULL, srcPtr_wrong);
2988
2989
    /* minimal srcSize to determine header size */
2990
31.0k
    if (srcSize < LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH)
2991
0
        RETURN_ERROR(frameHeader_incomplete);
2992
2993
    /* special case : skippable frames */
2994
31.0k
    if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START)
2995
342
        return 8;
2996
2997
    /* control magic number */
2998
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
2999
    if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER)
3000
        RETURN_ERROR(frameType_unknown);
3001
#endif
3002
3003
    /* Frame Header Size */
3004
30.7k
    {   BYTE const FLG = ((const BYTE*)src)[4];
3005
30.7k
        U32 const contentSizeFlag = (FLG>>3) & _1BIT;
3006
30.7k
        U32 const dictIDFlag = FLG & _1BIT;
3007
30.7k
        return minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
3008
31.0k
    }
3009
31.0k
}
3010
3011
/*! LZ4F_getFrameInfo() :
3012
 *  This function extracts frame parameters (max blockSize, frame checksum, etc.).
3013
 *  Usage is optional. Objective is to provide relevant information for allocation purposes.
3014
 *  This function works in 2 situations :
3015
 *   - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process.
3016
 *     Amount of input data provided must be large enough to successfully decode the frame header.
3017
 *     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.
3018
 *   - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx.
3019
 *   - After the end of a frame, with no input (*srcSizePtr == 0) : parameters of this frame are extracted from dctx, and the function returns 0.
3020
 *  The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value).
3021
 *  Decompression must resume from (srcBuffer + *srcSizePtr).
3022
 * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call,
3023
 *           or an error code which can be tested using LZ4F_isError()
3024
 *  note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped.
3025
 *  note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure.
3026
 */
3027
LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx,
3028
                                   LZ4F_frameInfo_t* frameInfoPtr,
3029
                             const void* srcBuffer, size_t* srcSizePtr)
3030
98.9k
{
3031
98.9k
    assert(dctx != NULL);
3032
98.9k
    RETURN_ERROR_IF(frameInfoPtr == NULL, parameter_null);
3033
98.9k
    RETURN_ERROR_IF(srcSizePtr == NULL, parameter_null);
3034
3035
98.9k
    LZ4F_STATIC_ASSERT(dstage_getFrameHeader < dstage_storeFrameHeader);
3036
98.9k
    if (dctx->dStage > dstage_storeFrameHeader) {
3037
        /* frameInfo already decoded */
3038
66.6k
        size_t o=0, i=0;
3039
66.6k
        *srcSizePtr = 0;
3040
66.6k
        *frameInfoPtr = dctx->frameInfo;
3041
        /* returns : recommended nb of bytes for LZ4F_decompress() */
3042
66.6k
        return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL);
3043
66.6k
    } else {
3044
32.2k
        if (dctx->dStage == dstage_storeFrameHeader) {
3045
            /* frame decoding already started, in the middle of header => automatic fail */
3046
1.18k
            *srcSizePtr = 0;
3047
1.18k
            RETURN_ERROR(frameDecoding_alreadyStarted);
3048
31.0k
        } else if (dctx->frameEnded && (*srcSizePtr == 0)) {
3049
            /* no input, after the end of a frame : parameters of this frame */
3050
0
            *frameInfoPtr = dctx->frameInfo;
3051
0
            return 0;
3052
31.0k
        } else {
3053
31.0k
            size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr);
3054
31.0k
            if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; }
3055
31.0k
            if (*srcSizePtr < hSize) {
3056
314
                *srcSizePtr=0;
3057
314
                RETURN_ERROR(frameHeader_incomplete);
3058
314
            }
3059
3060
30.7k
            {   size_t decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize);
3061
30.7k
                if (LZ4F_isError(decodeResult)) {
3062
11.3k
                    *srcSizePtr = 0;
3063
19.3k
                } else {
3064
19.3k
                    *srcSizePtr = decodeResult;
3065
19.3k
                    decodeResult = BHSize;   /* block header size */
3066
19.3k
                }
3067
30.7k
                *frameInfoPtr = dctx->frameInfo;
3068
30.7k
                return decodeResult;
3069
31.0k
    }   }   }
3070
98.9k
}
3071
3072
3073
/* LZ4F_moveDictBeforeTmpOut() :
3074
 * The block decoded in tmpOut is being flushed, while the history preceding it is elsewhere.
3075
 * Copy the end of this history in front of tmpOut (up to 64 KB with the block), so that the dictionary
3076
 * becomes contiguous within tmpOutBuffer, ending with the flushed part of tmpOut.
3077
 * @flushSize : bytes being flushed, not yet counted in tmpOutStart
3078
 */
3079
static void LZ4F_moveDictBeforeTmpOut(LZ4F_dctx* dctx, size_t flushSize)
3080
5.50k
{
3081
5.50k
    size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer);
3082
5.50k
    size_t copySize = 64 KB - dctx->tmpOutSize;
3083
5.50k
    const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart;
3084
5.50k
    if (dctx->tmpOutSize > 64 KB) copySize = 0;
3085
5.50k
    if (copySize > preserveSize) copySize = preserveSize;
3086
5.50k
    assert(dctx->tmpOutBuffer != NULL);
3087
3088
5.50k
    LZ4_memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
3089
3090
5.50k
    dctx->dict = dctx->tmpOutBuffer;
3091
5.50k
    dctx->dictSize = preserveSize + dctx->tmpOutStart + flushSize;
3092
5.50k
}
3093
3094
/* LZ4F_updateDict() :
3095
 * A linked block references the previous 64 KB of output.
3096
 * After each output [dstPtr, dstPtr+dstSize) (a block, or a part of it),
3097
 * records where this history is, for the next block :
3098
 * [dict, dict+dictSize) is contiguous, and ends with dstPtr+dstSize.
3099
 * It stays within dstBuffer (from @dstBufferStart) when possible, otherwise it's copied into tmpOutBuffer.
3100
 * Condition : @dstPtr != NULL
3101
 */
3102
static void LZ4F_updateDict(LZ4F_dctx* dctx,
3103
                      const BYTE* dstPtr, size_t dstSize, const BYTE* dstBufferStart,
3104
                      unsigned withinTmp)
3105
57.5k
{
3106
57.5k
    assert(dctx != NULL);
3107
57.5k
    assert(dstPtr != NULL);
3108
57.5k
    if (dctx->dictSize==0) dctx->dict = (const BYTE*)dstPtr;  /* will lead to prefix mode */
3109
57.5k
    assert(dctx->dict != NULL);
3110
3111
    /* prefix mode : the output follows the history within the same buffer.
3112
     * A history filling tmpOutBuffer can only be followed by another allocation : not a continuation. */
3113
57.5k
    if ( (dctx->dict + dctx->dictSize == dstPtr)
3114
25.7k
      && !((dctx->dict == dctx->tmpOutBuffer) && (dctx->dictSize >= dctx->tmpOutBufferCapacity)) ) {
3115
25.7k
        dctx->dictSize += dstSize;
3116
25.7k
        return;
3117
25.7k
    }
3118
3119
57.5k
    assert(dstPtr >= dstBufferStart);
3120
31.8k
    if ((size_t)(dstPtr - dstBufferStart) + dstSize >= 64 KB) {  /* history in dstBuffer becomes large enough to become dictionary */
3121
7.33k
        dctx->dict = (const BYTE*)dstBufferStart;
3122
7.33k
        dctx->dictSize = (size_t)(dstPtr - dstBufferStart) + dstSize;
3123
7.33k
        return;
3124
7.33k
    }
3125
3126
31.8k
    assert(dstSize < 64 KB);   /* if dstSize >= 64 KB, dictionary would be set into dstBuffer directly */
3127
3128
    /* dstBuffer does not contain whole useful history (64 KB), so it must be saved within tmpOutBuffer */
3129
24.4k
    assert(dctx->tmpOutBuffer != NULL);
3130
3131
24.4k
    if (withinTmp && (dctx->dict == dctx->tmpOutBuffer)) {   /* continue history within tmpOutBuffer */
3132
        /* withinTmp expectation : content of [dstPtr,dstSize] is same as [dict+dictSize,dstSize], so we just extend it */
3133
15.5k
        assert(dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart);
3134
15.5k
        dctx->dictSize += dstSize;
3135
15.5k
        return;
3136
15.5k
    }
3137
3138
8.98k
    if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */
3139
0
        LZ4F_moveDictBeforeTmpOut(dctx, dstSize);
3140
0
        return;
3141
0
    }
3142
3143
8.98k
    if (dctx->dict == dctx->tmpOutBuffer) {    /* copy dst into tmp to complete dict */
3144
8.98k
        if (dctx->dictSize + dstSize > dctx->tmpOutBufferCapacity) {  /* tmp buffer not large enough */
3145
353
            size_t const preserveSize = 64 KB - dstSize;
3146
353
            LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);
3147
353
            dctx->dictSize = preserveSize;
3148
353
        }
3149
8.98k
        LZ4_memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize);
3150
8.98k
        dctx->dictSize += dstSize;
3151
8.98k
        return;
3152
8.98k
    }
3153
3154
    /* join dict & dest into tmp */
3155
0
    {   size_t preserveSize = 64 KB - dstSize;
3156
0
        if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize;
3157
0
        LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);
3158
0
        LZ4_memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize);
3159
0
        dctx->dict = dctx->tmpOutBuffer;
3160
0
        dctx->dictSize = preserveSize + dstSize;
3161
0
    }
3162
0
}
3163
3164
3165
/* LZ4F_endMarkFollows() :
3166
 * the frame's endMark is within input, right after the block just output (after @skip bytes : its block checksum, if not consumed yet) :
3167
 * no block follows, so the history of linked blocks is no longer needed (saving it can cost as much as decoding a small block).
3168
 * Only valid once the block is entirely output : the same invocation then reads the endMark, which ends the frame. */
3169
static int LZ4F_endMarkFollows(const BYTE* srcPtr, const BYTE* srcEnd, size_t skip)
3170
39.7k
{
3171
39.7k
    return ((size_t)(srcEnd - srcPtr) >= skip + BHSize) && (LZ4F_readLE32(srcPtr + skip) == 0);
3172
39.7k
}
3173
3174
/* LZ4F_decodeBlock() :
3175
 * Decode compressed block @src (block checksum excluded) into @dst (capacity >= @dstCapacity),
3176
 * using current dictionary, and update content checksum and remaining frame size.
3177
 * @seqSizePtr != NULL : the block is incomplete (@srcSize bytes received so far) :
3178
 *                      decode its complete sequences, *seqSizePtr = their size (see LZ4_decompress_incomplete()).
3179
 * @return : decoded size, or an error code (testable with LZ4F_isError())
3180
 */
3181
/* LZ4F_decodeDetached() :
3182
 * History detached from @dst (not just before it) : beyond the block's first 64 KB, no match can reach it.
3183
 * So the first LZ4F_DETACHED_PART bytes are decoded with it (LZ4_decompress_incomplete() stops before the first
3184
 * sequence which doesn't fit), then the rest with them as a prefix, which is faster. Rarely, the sequence after
3185
 * the stop reaches the history (a long match crossing the limit) : the block is decoded again, as on any error.
3186
 * Not in place (input within @dst) : the first decoding would overwrite it.
3187
 * @return : decoded size, or < 0 (error) */
3188
52.0k
#define LZ4F_DETACHED_PART (64 KB + 512)
3189
static int LZ4F_decodeDetached(const char* src, int srcSize, char* dst, int dstCapacity, const char* dict, int dictSize)
3190
52.0k
{
3191
52.0k
    if ( (dstCapacity > LZ4F_DETACHED_PART) && (dictSize > 0) && (dict + dictSize != dst)
3192
15
      && (((size_t)(src + srcSize) <= (size_t)dst) || ((size_t)src >= (size_t)(dst + dstCapacity))) ) {
3193
15
        int partSrcSize = srcSize;
3194
15
        int const partSize = LZ4_decompress_incomplete(src, dst, &partSrcSize, LZ4F_DETACHED_PART, dict, dictSize);
3195
15
        if (partSize >= 0) {
3196
15
            int const r = LZ4_decompress_safe_usingDict(src + partSrcSize, dst + partSize,
3197
15
                                    srcSize - partSrcSize, dstCapacity - partSize, dst, partSize);
3198
15
            if (r >= 0) return partSize + r;
3199
15
    }   }
3200
52.0k
    return LZ4_decompress_safe_usingDict(src, dst, srcSize, dstCapacity, dict, dictSize);
3201
52.0k
}
3202
3203
static size_t LZ4F_decodeBlock(LZ4F_dctx* dctx, const BYTE* src, size_t srcSize,
3204
                               BYTE* dst, size_t dstCapacity, size_t* seqSizePtr)
3205
52.0k
{
3206
52.0k
    const char* dict = (const char*)dctx->dict;
3207
52.0k
    size_t dictSize = dctx->dictSize;
3208
52.0k
    int decodedSize;
3209
52.0k
    assert(dst != NULL);
3210
52.0k
    if (dict && dictSize > 1 GB) {
3211
        /* the dictSize param is an int, avoid truncation / sign issues */
3212
0
        dict += dictSize - 64 KB;
3213
0
        dictSize = 64 KB;
3214
0
    }
3215
52.0k
    if (seqSizePtr) {
3216
0
        int seqSize = (int)srcSize;
3217
0
        decodedSize = LZ4_decompress_incomplete(
3218
0
                (const char*)src, (char*)dst,
3219
0
                &seqSize, (int)dstCapacity,
3220
0
                dict, (int)dictSize);
3221
0
        *seqSizePtr = (size_t)seqSize;
3222
52.0k
    } else {
3223
52.0k
        decodedSize = LZ4F_decodeDetached(
3224
52.0k
                (const char*)src, (int)srcSize,
3225
52.0k
                (char*)dst, (int)dstCapacity,
3226
52.0k
                dict, (int)dictSize);
3227
52.0k
    }
3228
52.0k
    RETURN_ERROR_IF(decodedSize < 0, decompressionFailed);
3229
49.4k
    RETURN_ERROR_IF(dctx->frameInfo.contentSize && (U64)decodedSize > dctx->frameRemainingSize, frameSize_wrong);
3230
49.4k
    if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum)
3231
21.4k
        XXH32_update(&(dctx->xxh), dst, (size_t)decodedSize);
3232
49.4k
    if (dctx->frameInfo.contentSize)
3233
2.51k
        dctx->frameRemainingSize -= (size_t)decodedSize;
3234
49.4k
    return (size_t)decodedSize;
3235
49.4k
}
3236
3237
/* LZ4F_decodeProgressive() :
3238
 * The frame's first block is incomplete (dctx->tmpInSize bytes gathered so far into tmpIn) :
3239
 * decode its complete sequences into @dst, up to @dstCapacity bytes, without waiting for the rest.
3240
 * The rest is decoded once the block is complete, with this output as history.
3241
 * @return : decoded size, or an error code */
3242
static size_t LZ4F_decodeProgressive(LZ4F_dctx* dctx, BYTE* dst, size_t dstCapacity, const BYTE* dstStart)
3243
0
{
3244
0
    size_t seqSize;
3245
0
    size_t const decodedSize = LZ4F_decodeBlock(dctx,
3246
0
                                dctx->tmpIn + dctx->tmpInDecoded, dctx->tmpInSize - dctx->tmpInDecoded,
3247
0
                                dst, MIN(dstCapacity, dctx->maxBlockSize - dctx->blockDecoded), &seqSize);
3248
0
    if (LZ4F_isError(decodedSize) || (decodedSize == 0)) return decodedSize;
3249
0
    if (dctx->blockDecoded == 0) {
3250
0
        dctx->blockDict = dctx->dict;
3251
0
        dctx->blockDictSize = dctx->dictSize;
3252
0
    }
3253
    /* history : the block's dictionary, then its output (independent blocks : not the previous blocks) */
3254
0
    LZ4F_updateDict(dctx, dst, decodedSize,
3255
0
                    (dctx->frameInfo.blockMode == LZ4F_blockLinked) ? dstStart : dst, 0);
3256
0
    dctx->tmpInDecoded += seqSize;
3257
0
    dctx->blockDecoded += decodedSize;
3258
0
    return decodedSize;
3259
0
}
3260
3261
/* LZ4F_endBlock() :
3262
 * after a compressed block : the beginning of a block decoded progressively is no longer history (independent blocks) */
3263
static void LZ4F_endBlock(LZ4F_dctx* dctx)
3264
49.4k
{
3265
49.4k
    if (dctx->blockDecoded && (dctx->frameInfo.blockMode == LZ4F_blockIndependent)) {
3266
0
        dctx->dict = dctx->blockDict;
3267
0
        dctx->dictSize = dctx->blockDictSize;
3268
0
    }
3269
49.4k
    dctx->tmpInDecoded = 0;
3270
49.4k
    dctx->blockDecoded = 0;
3271
49.4k
}
3272
3273
3274
/* LZ4F_gatherInput() :
3275
 * Provides @wanted contiguous input bytes : directly from src if they are all available and none is buffered yet,
3276
 * otherwise accumulated into @buffer, over as many calls as needed (dctx->tmpInSize bytes buffered so far).
3277
 * @return : pointer to the @wanted bytes (*srcPtrPtr is moved past consumed input),
3278
 *           or NULL if input is exhausted before (all of it is then buffered).
3279
 */
3280
static const BYTE*
3281
LZ4F_gatherInput(LZ4F_dctx* dctx, BYTE* buffer, size_t wanted,
3282
                 const BYTE** srcPtrPtr, const BYTE* srcEnd)
3283
245k
{
3284
245k
    const BYTE* const srcPtr = *srcPtrPtr;
3285
245k
    size_t const available = (size_t)(srcEnd - srcPtr);
3286
245k
    if ((dctx->tmpInSize == 0) && (available >= wanted)) {
3287
131k
        *srcPtrPtr = srcPtr + wanted;
3288
131k
        return srcPtr;
3289
131k
    }
3290
113k
    {   size_t const sizeToCopy = MIN(wanted - dctx->tmpInSize, available);
3291
113k
        LZ4_memcpy(buffer + dctx->tmpInSize, srcPtr, sizeToCopy);
3292
113k
        dctx->tmpInSize += sizeToCopy;
3293
113k
        *srcPtrPtr = srcPtr + sizeToCopy;
3294
113k
    }
3295
113k
    if (dctx->tmpInSize < wanted) return NULL;
3296
19.1k
    dctx->tmpInSize = 0;   /* ready for next gathering */
3297
19.1k
    return buffer;
3298
113k
}
3299
3300
3301
/*! LZ4F_decompress() :
3302
 *  Call this function repetitively to regenerate compressed data in srcBuffer.
3303
 *  The function will attempt to decode up to *srcSizePtr bytes from srcBuffer
3304
 *  into dstBuffer of capacity *dstSizePtr.
3305
 *
3306
 *  The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
3307
 *
3308
 *  The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
3309
 *  If number of bytes read is < number of bytes provided, then decompression operation is not complete.
3310
 *  Remaining data will have to be presented again in a subsequent invocation.
3311
 *
3312
 *  The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.
3313
 *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.
3314
 *  Respecting the hint provides a small boost to performance, since it allows less buffer shuffling.
3315
 *  Note that this is just a hint, and it's always possible to any srcSize value.
3316
 *  When a frame is fully decoded, @return will be 0.
3317
 *  If decompression failed, @return is an error code which can be tested using LZ4F_isError().
3318
 */
3319
size_t LZ4F_decompress(LZ4F_dctx* dctx,
3320
                       void* dstBuffer, size_t* dstSizePtr,
3321
                       const void* srcBuffer, size_t* srcSizePtr,
3322
                       const LZ4F_decompressOptions_t* decompressOptionsPtr)
3323
230k
{
3324
230k
    static const BYTE emptySrc = 0;   /* NULL srcBuffer (no input, used by LZ4F_getFrameInfo()) points here instead :
3325
                                       * NULL+0 and LZ4_memcpy(dst, NULL, 0) are UB */
3326
230k
    LZ4F_decompressOptions_t optionsNull;
3327
230k
    const BYTE* const srcStart = srcBuffer ? (const BYTE*)srcBuffer : &emptySrc;
3328
230k
    const BYTE* const srcEnd = srcBuffer ? srcStart + *srcSizePtr : srcStart;
3329
230k
    const BYTE* srcPtr = srcStart;
3330
230k
    BYTE* const dstStart = (BYTE*)dstBuffer;
3331
230k
    BYTE* const dstEnd = dstStart ? dstStart + *dstSizePtr : NULL;
3332
230k
    BYTE* dstPtr = dstStart;
3333
230k
    const BYTE* selectedIn = NULL;
3334
230k
    unsigned doAnotherStage = 1;
3335
230k
    size_t nextSrcSizeHint = 1;
3336
3337
3338
230k
    DEBUGLOG(5, "LZ4F_decompress: src[%p](%u) => dst[%p](%u)",
3339
230k
            srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr);
3340
230k
    if (dstBuffer == NULL) assert(*dstSizePtr == 0);
3341
230k
    if (srcBuffer == NULL) assert(*srcSizePtr == 0);
3342
230k
    MEM_INIT(&optionsNull, 0, sizeof(optionsNull));
3343
230k
    if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;
3344
230k
    *srcSizePtr = 0;
3345
230k
    *dstSizePtr = 0;
3346
230k
    assert(dctx != NULL);
3347
230k
    switch (decompressOptionsPtr->skipChecksums) {   /* once set, disable for the remainder of the frame */
3348
230k
    case LZ4F_verifyChecksums: break;
3349
0
    case LZ4F_skipAllChecksums: dctx->skipBlockChecksum = 1; dctx->skipContentChecksum = 1; break;
3350
0
    case LZ4F_skipContentChecksum: dctx->skipContentChecksum = 1; break;
3351
0
    case LZ4F_skipBlockChecksums: dctx->skipBlockChecksum = 1; break;
3352
0
    default: RETURN_ERROR(parameter_invalid);
3353
230k
    }
3354
3355
    /* behaves as a state machine */
3356
3357
571k
    while (doAnotherStage) {
3358
3359
345k
        switch(dctx->dStage)
3360
345k
        {
3361
3362
18.2k
        case dstage_getFrameHeader:
3363
18.2k
            DEBUGLOG(6, "dstage_getFrameHeader");
3364
18.2k
            if ((size_t)(srcEnd-srcPtr) >= maxFHSize) {  /* enough to decode - shortcut */
3365
0
                size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, (size_t)(srcEnd-srcPtr));  /* will update dStage appropriately */
3366
0
                if (LZ4F_isError(hSize)) { nextSrcSizeHint = hSize; goto _output; }
3367
0
                srcPtr += hSize;
3368
0
                break;
3369
0
            }
3370
18.2k
            dctx->tmpInSize = 0;
3371
18.2k
            if (srcEnd-srcPtr == 0) return minFHSize;   /* 0-size input */
3372
18.2k
            dctx->tmpInTarget = minFHSize;   /* minimum size to decode header */
3373
18.2k
            dctx->dStage = dstage_storeFrameHeader;
3374
            /* fall-through */
3375
3376
20.8k
        case dstage_storeFrameHeader:
3377
20.8k
            DEBUGLOG(6, "dstage_storeFrameHeader");
3378
20.8k
            {   size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr));
3379
20.8k
                LZ4_memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);
3380
20.8k
                dctx->tmpInSize += sizeToCopy;
3381
20.8k
                srcPtr += sizeToCopy;
3382
20.8k
            }
3383
20.8k
            if (dctx->tmpInSize < dctx->tmpInTarget) {
3384
1.44k
                nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize;   /* rest of header + nextBlockHeader */
3385
1.44k
                doAnotherStage = 0;   /* not enough src data, ask for some more */
3386
1.44k
                break;
3387
1.44k
            }
3388
19.3k
            {   size_t const hSize = LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget); /* will update dStage appropriately */
3389
19.3k
                if (LZ4F_isError(hSize)) { nextSrcSizeHint = hSize; goto _output; }
3390
19.3k
            }
3391
19.1k
            break;
3392
3393
33.9k
        case dstage_init:
3394
33.9k
            DEBUGLOG(6, "dstage_init");
3395
33.9k
            if (dctx->frameInfo.contentChecksumFlag) (void)XXH32_reset(&(dctx->xxh), 0);
3396
            /* internal buffers allocation */
3397
33.9k
            {   size_t const tmpInNeeded = dctx->maxBlockSize + BFSize /* block checksum */;
3398
33.9k
                size_t const tmpOutNeeded = dctx->maxBlockSize   /* + history : linked blocks, or first block decoded progressively */
3399
33.9k
                    + (((dctx->frameInfo.blockMode==LZ4F_blockLinked) || dctx->progressive) ? 128 KB : 0);
3400
33.9k
                if ( (tmpInNeeded > dctx->tmpInCapacity)
3401
18.7k
                  || (tmpOutNeeded > dctx->tmpOutBufferCapacity) ) {   /* tmp buffers too small */
3402
                    /* capacities remain 0 until allocation succeeds,
3403
                     * so that allocation will be re-attempted on next entry */
3404
18.7k
                    LZ4F_free(dctx->tmpIn, dctx->cmem);
3405
18.7k
                    dctx->tmpInCapacity = 0;
3406
18.7k
                    dctx->tmpIn = (BYTE*)LZ4F_malloc(tmpInNeeded, dctx->cmem);
3407
18.7k
                    if (dctx->tmpIn == NULL) {
3408
0
                        nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_allocation_failed);
3409
0
                        goto _output;
3410
0
                    }
3411
18.7k
                    dctx->tmpInCapacity = tmpInNeeded;
3412
18.7k
                    LZ4F_free(dctx->tmpOutBuffer, dctx->cmem);
3413
18.7k
                    dctx->tmpOutBufferCapacity = 0;
3414
18.7k
                    dctx->tmpOutBuffer= (BYTE*)LZ4F_malloc(tmpOutNeeded, dctx->cmem);
3415
18.7k
                    if (dctx->tmpOutBuffer== NULL) {
3416
0
                        nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_allocation_failed);
3417
0
                        goto _output;
3418
0
                    }
3419
18.7k
                    dctx->tmpOutBufferCapacity = tmpOutNeeded;
3420
18.7k
            }   }
3421
33.9k
            dctx->tmpInSize = 0;
3422
33.9k
            dctx->tmpInTarget = 0;
3423
33.9k
            dctx->progressiveFrame = dctx->progressive;
3424
33.9k
            dctx->tmpInDecoded = 0;
3425
33.9k
            dctx->blockDecoded = 0;
3426
33.9k
            dctx->blockNb = 0;
3427
33.9k
            dctx->tmpOut = dctx->tmpOutBuffer;
3428
33.9k
            dctx->tmpOutStart = 0;
3429
33.9k
            dctx->tmpOutSize = 0;
3430
3431
33.9k
            dctx->dStage = dstage_getBlockHeader;
3432
            /* fall-through */
3433
3434
100k
        case dstage_getBlockHeader:
3435
100k
            selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, BHSize, &srcPtr, srcEnd);
3436
100k
            if (selectedIn == NULL) {   /* not enough input for cBlockSize */
3437
14.0k
                nextSrcSizeHint = BHSize - dctx->tmpInSize;
3438
14.0k
                doAnotherStage = 0;
3439
14.0k
                break;
3440
14.0k
            }
3441
3442
            /* decode block header */
3443
86.8k
            {   U32 const blockHeader = LZ4F_readLE32(selectedIn);
3444
86.8k
                size_t const nextCBlockSize = blockHeader & 0x7FFFFFFFU;
3445
86.8k
                size_t const crcSize = dctx->frameInfo.blockChecksumFlag * BFSize;
3446
86.8k
                if (blockHeader==0) {  /* frameEnd signal, no more block */
3447
19.5k
                    DEBUGLOG(5, "end of frame");
3448
19.5k
                    dctx->dStage = dstage_getSuffix;
3449
19.5k
                    break;
3450
19.5k
                }
3451
67.3k
                if (dctx->blockNb < 2) dctx->blockNb++;
3452
67.3k
                if (nextCBlockSize > dctx->maxBlockSize) {
3453
669
                    nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_maxBlockSize_invalid);
3454
669
                    goto _output;
3455
669
                }
3456
66.6k
                if (blockHeader & LZ4F_BLOCKUNCOMPRESSED_FLAG) {
3457
                    /* next block is uncompressed */
3458
14.2k
                    if (dctx->frameInfo.contentSize && nextCBlockSize > dctx->frameRemainingSize) {
3459
33
                        nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_frameSize_wrong);
3460
33
                        goto _output;
3461
33
                    }
3462
14.2k
                    dctx->tmpInTarget = nextCBlockSize;
3463
14.2k
                    DEBUGLOG(5, "next block is uncompressed (size %u)", (U32)nextCBlockSize);
3464
14.2k
                    if (dctx->frameInfo.blockChecksumFlag) {
3465
5.20k
                        (void)XXH32_reset(&dctx->blockChecksum, 0);
3466
5.20k
                    }
3467
14.2k
                    dctx->dStage = dstage_copyDirect;
3468
14.2k
                    break;
3469
14.2k
                }
3470
                /* next block is a compressed block */
3471
52.4k
                dctx->tmpInTarget = nextCBlockSize + crcSize;
3472
52.4k
                assert(dctx->tmpInDecoded == 0 && dctx->blockDecoded == 0);   /* see LZ4F_endBlock() */
3473
52.4k
                dctx->dStage = dstage_getCBlock;
3474
52.4k
                if (dstPtr==dstEnd || srcPtr==srcEnd) {
3475
52.4k
                    nextSrcSizeHint = BHSize + nextCBlockSize + crcSize;
3476
52.4k
                    doAnotherStage = 0;
3477
52.4k
                }
3478
52.4k
                break;
3479
52.4k
            }
3480
3481
49.0k
        case dstage_copyDirect:   /* uncompressed block */
3482
49.0k
            DEBUGLOG(6, "dstage_copyDirect");
3483
49.0k
            {   size_t sizeToCopy;
3484
49.0k
                if (dstPtr == NULL) {
3485
13.7k
                    sizeToCopy = 0;
3486
35.3k
                } else {
3487
35.3k
                    size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr));
3488
35.3k
                    sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize);
3489
35.3k
                    LZ4_memcpy(dstPtr, srcPtr, sizeToCopy);
3490
35.3k
                    if (dctx->frameInfo.blockChecksumFlag && !dctx->skipBlockChecksum)
3491
13.3k
                        (void)XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy);
3492
35.3k
                    if (dctx->frameInfo.contentChecksumFlag && !dctx->skipContentChecksum)
3493
14.8k
                        (void)XXH32_update(&dctx->xxh, srcPtr, sizeToCopy);
3494
35.3k
                    if (dctx->frameInfo.contentSize)
3495
1.60k
                        dctx->frameRemainingSize -= sizeToCopy;
3496
3497
                    /* history management (linked blocks only), unless the frame ends with this block */
3498
35.3k
                    if ( (dctx->frameInfo.blockMode == LZ4F_blockLinked)
3499
25.1k
                      && !( (sizeToCopy == dctx->tmpInTarget)
3500
22.5k
                         && LZ4F_endMarkFollows(srcPtr + sizeToCopy, srcEnd, dctx->frameInfo.blockChecksumFlag * BFSize) ) ) {
3501
22.5k
                        LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0);
3502
22.5k
                    }
3503
35.3k
                    srcPtr += sizeToCopy;
3504
35.3k
                    dstPtr += sizeToCopy;
3505
35.3k
                }
3506
49.0k
                if (sizeToCopy == dctx->tmpInTarget) {   /* all done */
3507
12.3k
                    if (dctx->frameInfo.blockChecksumFlag)
3508
4.44k
                        dctx->dStage = dstage_getBlockChecksum;
3509
7.93k
                    else
3510
7.93k
                        dctx->dStage = dstage_getBlockHeader;  /* new block */
3511
12.3k
                    break;
3512
12.3k
                }
3513
36.7k
                dctx->tmpInTarget -= sizeToCopy;  /* need to copy more */
3514
36.7k
            }
3515
0
            nextSrcSizeHint = dctx->tmpInTarget
3516
36.7k
                            + (dctx->frameInfo.blockChecksumFlag ? BFSize : 0)
3517
36.7k
                            + BHSize /* next header size */;
3518
36.7k
            doAnotherStage = 0;
3519
36.7k
            break;
3520
3521
        /* check block checksum for recently transferred uncompressed block */
3522
4.85k
        case dstage_getBlockChecksum:
3523
4.85k
            DEBUGLOG(6, "dstage_getBlockChecksum");
3524
4.85k
            selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, BFSize, &srcPtr, srcEnd);
3525
4.85k
            if (selectedIn == NULL) {   /* all input consumed */
3526
444
                nextSrcSizeHint = (BFSize - dctx->tmpInSize) + BHSize /* next header size */;
3527
444
                doAnotherStage = 0;
3528
444
                break;
3529
444
            }
3530
4.40k
            if (!dctx->skipBlockChecksum) {
3531
4.40k
                U32 const readCRC = LZ4F_readLE32(selectedIn);
3532
4.40k
                U32 const calcCRC = XXH32_digest(&dctx->blockChecksum);
3533
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3534
                DEBUGLOG(6, "compare block checksum");
3535
                if (readCRC != calcCRC) {
3536
                    DEBUGLOG(4, "incorrect block checksum: %08X != %08X",
3537
                            readCRC, calcCRC);
3538
                    nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_blockChecksum_invalid);
3539
                    goto _output;
3540
                }
3541
#else
3542
4.40k
                (void)readCRC;
3543
4.40k
                (void)calcCRC;
3544
4.40k
#endif
3545
4.40k
            }
3546
4.40k
            dctx->dStage = dstage_getBlockHeader;  /* new block */
3547
4.40k
            break;
3548
3549
119k
        case dstage_getCBlock:
3550
119k
            DEBUGLOG(6, "dstage_getCBlock");
3551
119k
            selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, dctx->tmpInTarget, &srcPtr, srcEnd);
3552
119k
            if (selectedIn == NULL) {   /* need more input */
3553
                /* first block of the frame : output what can be decoded already (see LZ4F_setProgressiveDecoding()),
3554
                 * unless a block checksum must be verified first */
3555
67.6k
                if ( dctx->progressiveFrame && (dctx->blockNb == 1)
3556
0
                  && !dctx->frameInfo.blockChecksumFlag && (dstPtr != NULL) ) {
3557
0
                    size_t const decodedSize = LZ4F_decodeProgressive(dctx, dstPtr, (size_t)(dstEnd - dstPtr), dstStart);
3558
0
                    if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; }
3559
0
                    dstPtr += decodedSize;
3560
0
                }
3561
67.6k
                nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize)   /* block checksum included */
3562
67.6k
                                + BHSize /* next header size */;
3563
67.6k
                doAnotherStage = 0;
3564
67.6k
                break;
3565
67.6k
            }
3566
3567
            /* At this stage, input is large enough to decode a block */
3568
            /* (or the rest of a block decoded progressively : dctx->tmpInDecoded bytes already decoded, never with block checksum) */
3569
119k
            assert((dctx->tmpInDecoded == 0) || (selectedIn == dctx->tmpIn));
3570
52.0k
            assert((dctx->tmpInDecoded == 0) || !dctx->frameInfo.blockChecksumFlag);
3571
3572
            /* First, decode and control block checksum if it exists */
3573
52.0k
            if (dctx->frameInfo.blockChecksumFlag) {
3574
21.0k
                assert(dctx->tmpInTarget >= 4);
3575
21.0k
                dctx->tmpInTarget -= 4;
3576
21.0k
                if (!dctx->skipBlockChecksum) {
3577
21.0k
                    U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget);
3578
21.0k
                    U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0);
3579
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3580
                    if (readBlockCrc != calcBlockCrc) {
3581
                        nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_blockChecksum_invalid);
3582
                        goto _output;
3583
                    }
3584
#else
3585
21.0k
                    (void)readBlockCrc;
3586
21.0k
                    (void)calcBlockCrc;
3587
21.0k
#endif
3588
21.0k
            }   }
3589
3590
            /* decode directly into destination buffer if there is enough room */
3591
52.0k
            if ( ((size_t)(dstEnd-dstPtr) >= dctx->maxBlockSize - dctx->blockDecoded)
3592
                 /* unless the dictionary is stored in tmpOut:
3593
                  * in which case it's faster to decode within tmpOut
3594
                  * to benefit from prefix speedup (but the rest of a block decoded progressively would be copied) */
3595
14.6k
              && ( dctx->blockDecoded
3596
14.6k
                || !(dctx->dict!= NULL && (const BYTE*)dctx->dict + dctx->dictSize == dctx->tmpOut) ) )
3597
8.39k
            {   size_t const decodedSize = LZ4F_decodeBlock(dctx,
3598
8.39k
                                selectedIn + dctx->tmpInDecoded, dctx->tmpInTarget - dctx->tmpInDecoded,
3599
8.39k
                                dstPtr, dctx->maxBlockSize - dctx->blockDecoded, NULL);
3600
8.39k
                if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; }
3601
3602
                /* dictionary management, unless the frame ends with this block */
3603
7.68k
                if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked)
3604
5.52k
                  && !LZ4F_endMarkFollows(srcPtr, srcEnd, 0) ) {
3605
5.40k
                    LZ4F_updateDict(dctx, dstPtr, decodedSize, dstStart, 0);
3606
5.40k
                }
3607
3608
7.68k
                dstPtr += decodedSize;
3609
7.68k
                LZ4F_endBlock(dctx);
3610
7.68k
                dctx->dStage = dstage_getBlockHeader;  /* end of block, let's get another one */
3611
7.68k
                break;
3612
8.39k
            }
3613
3614
            /* not enough place into dst : decode into tmpOut */
3615
3616
            /* manage dictionary : history of linked blocks, or beginning of a block decoded progressively */
3617
43.6k
            if ((dctx->frameInfo.blockMode == LZ4F_blockLinked) || dctx->blockDecoded) {
3618
32.4k
                if (dctx->dict == dctx->tmpOutBuffer) {
3619
                    /* truncate dictionary to 64 KB if too big */
3620
19.9k
                    if (dctx->dictSize > 128 KB) {
3621
1.18k
                        LZ4_memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB);
3622
1.18k
                        dctx->dictSize = 64 KB;
3623
1.18k
                    }
3624
19.9k
                    dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize;
3625
19.9k
                } else {  /* dict not within tmpOut */
3626
12.5k
                    size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB);
3627
12.5k
                    dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace;
3628
12.5k
            }   }
3629
3630
            /* Decode block into tmpOut */
3631
43.6k
            {   size_t const decodedSize = LZ4F_decodeBlock(dctx,
3632
43.6k
                                selectedIn + dctx->tmpInDecoded, dctx->tmpInTarget - dctx->tmpInDecoded,
3633
43.6k
                                dctx->tmpOut, dctx->maxBlockSize - dctx->blockDecoded, NULL);
3634
43.6k
                if (LZ4F_isError(decodedSize)) { nextSrcSizeHint = decodedSize; goto _output; }
3635
41.7k
                LZ4F_endBlock(dctx);
3636
41.7k
                dctx->tmpOutSize = decodedSize;
3637
41.7k
                dctx->tmpOutStart = 0;
3638
41.7k
                dctx->dStage = dstage_flushOut;
3639
41.7k
            }
3640
            /* fall-through */
3641
3642
52.2k
        case dstage_flushOut:  /* flush decoded data from tmpOut to dstBuffer */
3643
52.2k
            DEBUGLOG(6, "dstage_flushOut");
3644
52.2k
            if (dstPtr != NULL) {
3645
52.2k
                size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr));
3646
52.2k
                LZ4_memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy);
3647
3648
                /* dictionary management, unless the frame ends with this block */
3649
52.2k
                if ( (dctx->frameInfo.blockMode == LZ4F_blockLinked)
3650
39.5k
                  && !( (dctx->tmpOutStart + sizeToCopy == dctx->tmpOutSize)
3651
25.3k
                     && LZ4F_endMarkFollows(srcPtr, srcEnd, 0) ) )
3652
29.6k
                    LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1 /*withinTmp*/);
3653
3654
52.2k
                dctx->tmpOutStart += sizeToCopy;
3655
52.2k
                dstPtr += sizeToCopy;
3656
52.2k
            }
3657
52.2k
            if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */
3658
33.4k
                dctx->dStage = dstage_getBlockHeader;  /* get next block */
3659
33.4k
                break;
3660
33.4k
            }
3661
            /* could not flush everything : stop there, just request a block header */
3662
18.7k
            doAnotherStage = 0;
3663
18.7k
            nextSrcSizeHint = BHSize;
3664
18.7k
            break;
3665
3666
23.0k
        case dstage_getSuffix:
3667
23.0k
            if (dctx->frameRemainingSize) {   /* incorrect frame size decoded */
3668
154
                nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_frameSize_wrong);
3669
154
                goto _output;
3670
154
            }
3671
22.8k
            if (!dctx->frameInfo.contentChecksumFlag) {  /* no checksum, frame is completed */
3672
10.9k
                nextSrcSizeHint = 0;
3673
10.9k
                LZ4F_endFrame(dctx);
3674
10.9k
                doAnotherStage = 0;
3675
10.9k
                break;
3676
10.9k
            }
3677
11.9k
            selectedIn = LZ4F_gatherInput(dctx, dctx->tmpIn, 4, &srcPtr, srcEnd);
3678
11.9k
            if (selectedIn == NULL) {   /* not enough input to read complete suffix */
3679
8.47k
                nextSrcSizeHint = 4 - dctx->tmpInSize;
3680
8.47k
                doAnotherStage = 0;
3681
8.47k
                break;
3682
8.47k
            }
3683
3.47k
            if (!dctx->skipContentChecksum) {
3684
3.37k
                U32 const readCRC = LZ4F_readLE32(selectedIn);
3685
3.37k
                U32 const resultCRC = XXH32_digest(&(dctx->xxh));
3686
3.37k
                DEBUGLOG(4, "frame checksum: stored 0x%0X vs 0x%0X processed", readCRC, resultCRC);
3687
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
3688
                if (readCRC != resultCRC) {
3689
                    nextSrcSizeHint = LZ4F_returnErrorCode(LZ4F_ERROR_contentChecksum_invalid);
3690
                    goto _output;
3691
                }
3692
#else
3693
3.37k
                (void)readCRC;
3694
3.37k
                (void)resultCRC;
3695
3.37k
#endif
3696
3.37k
            }
3697
3.47k
            nextSrcSizeHint = 0;
3698
3.47k
            LZ4F_endFrame(dctx);
3699
3.47k
            doAnotherStage = 0;
3700
3.47k
            break;
3701
3702
7.79k
        case dstage_getSFrameSize:
3703
7.79k
            selectedIn = LZ4F_gatherInput(dctx, dctx->header + 4, 4, &srcPtr, srcEnd);
3704
7.79k
            if (selectedIn == NULL) {   /* not enough input to read the skippable frame size */
3705
3.70k
                nextSrcSizeHint = 4 - dctx->tmpInSize;
3706
3.70k
                doAnotherStage = 0;
3707
3.70k
                break;
3708
3.70k
            }
3709
4.08k
            {   size_t const SFrameSize = LZ4F_readLE32(selectedIn);
3710
4.08k
                dctx->frameInfo.contentSize = SFrameSize;
3711
4.08k
                dctx->tmpInTarget = SFrameSize;
3712
4.08k
                dctx->dStage = dstage_skipSkippable;
3713
4.08k
                break;
3714
7.79k
            }
3715
3716
8.39k
        case dstage_skipSkippable:
3717
8.39k
            {   size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr));
3718
8.39k
                srcPtr += skipSize;
3719
8.39k
                dctx->tmpInTarget -= skipSize;
3720
8.39k
                doAnotherStage = 0;
3721
8.39k
                nextSrcSizeHint = dctx->tmpInTarget;
3722
8.39k
                if (nextSrcSizeHint) break;  /* still more to skip */
3723
                /* frame fully skipped : prepare context for a new frame */
3724
3.92k
                LZ4F_endFrame(dctx);
3725
3.92k
                break;
3726
8.39k
            }
3727
345k
        }   /* switch (dctx->dStage) */
3728
345k
    }   /* while (doAnotherStage) */
3729
3730
    /* preserve history within tmpOut whenever necessary */
3731
226k
    LZ4F_STATIC_ASSERT((unsigned)dstage_init == 2);
3732
226k
    if ( ( (dctx->frameInfo.blockMode==LZ4F_blockLinked)  /* next block will use up to 64KB from previous ones */
3733
59.4k
        || (dctx->blockDecoded && (dctx->dStage == dstage_getCBlock)) )  /* rest of the block decoded progressively too */
3734
167k
      && (dctx->dict != dctx->tmpOutBuffer)             /* dictionary is not already within tmp */
3735
103k
      && (dctx->dict != NULL)                           /* dictionary exists */
3736
31.2k
      && (!decompressOptionsPtr->stableDst)             /* cannot rely on dst data to remain there for next call */
3737
31.2k
      && ((unsigned)(dctx->dStage)-2 < (unsigned)(dstage_getSuffix)-2) )  /* valid stages : [init ... getSuffix[ */
3738
31.2k
    {
3739
31.2k
        if (dctx->dStage == dstage_flushOut) {
3740
5.50k
            LZ4F_moveDictBeforeTmpOut(dctx, 0);
3741
25.7k
        } else {
3742
25.7k
            const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize;
3743
25.7k
            size_t const newDictSize = MIN(dctx->dictSize, 64 KB);
3744
3745
25.7k
            LZ4_memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);
3746
3747
25.7k
            dctx->dict = dctx->tmpOutBuffer;
3748
25.7k
            dctx->dictSize = newDictSize;
3749
25.7k
            dctx->tmpOut = dctx->tmpOutBuffer + newDictSize;
3750
25.7k
        }
3751
31.2k
    }
3752
3753
230k
_output:   /* also on error : report progress, but do not preserve history for reuse */
3754
230k
    *srcSizePtr = (size_t)(srcPtr - srcStart);
3755
230k
    *dstSizePtr = dstStart ? (size_t)(dstPtr - dstStart) : 0;
3756
230k
    return nextSrcSizeHint;
3757
226k
}
3758
3759
/*! LZ4F_decompress_usingDict() :
3760
 *  Same as LZ4F_decompress(), using a predefined dictionary.
3761
 *  Dictionary is used "in place", without any preprocessing.
3762
 *  It must remain accessible throughout the entire frame decoding.
3763
 */
3764
size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx,
3765
                       void* dstBuffer, size_t* dstSizePtr,
3766
                       const void* srcBuffer, size_t* srcSizePtr,
3767
                       const void* dict, size_t dictSize,
3768
                       const LZ4F_decompressOptions_t* decompressOptionsPtr)
3769
0
{
3770
0
    if (dctx->dStage <= dstage_init) {
3771
0
        dctx->dict = (const BYTE*)dict;
3772
0
        dctx->dictSize = dictSize;
3773
0
    }
3774
0
    return LZ4F_decompress(dctx, dstBuffer, dstSizePtr,
3775
0
                           srcBuffer, srcSizePtr,
3776
0
                           decompressOptionsPtr);
3777
0
}
3778
3779
/*! LZ4F_resumeFrame() :
3780
 *  see lz4frame.h (static section) */
3781
size_t LZ4F_resumeFrame(LZ4F_dctx* dctx, const LZ4F_frameInfo_t* frameInfo,
3782
                        unsigned long long decodedPos,
3783
                        const void* dict, size_t dictSize)
3784
1.20k
{
3785
1.20k
    assert(dctx != NULL);
3786
1.20k
    RETURN_ERROR_IF(frameInfo == NULL, parameter_null);
3787
1.20k
    RETURN_ERROR_IF(dict == NULL && dictSize > 0, parameter_null);
3788
1.20k
    RETURN_ERROR_IF(frameInfo->frameType != LZ4F_frame, frameType_unknown);
3789
1.20k
    RETURN_ERROR_IF(frameInfo->blockSizeID < LZ4F_max64KB || frameInfo->blockSizeID > LZ4F_max4MB, maxBlockSize_invalid);
3790
1.20k
    RETURN_ERROR_IF((unsigned)frameInfo->blockMode > 1, blockMode_invalid);
3791
1.20k
    RETURN_ERROR_IF((unsigned)frameInfo->blockChecksumFlag > 1, parameter_invalid);
3792
1.20k
    RETURN_ERROR_IF((unsigned)frameInfo->contentChecksumFlag > 1, parameter_invalid);
3793
1.20k
    RETURN_ERROR_IF(frameInfo->contentSize && decodedPos > frameInfo->contentSize, frameSize_wrong);
3794
3795
1.20k
    LZ4F_resetDecompressionContext(dctx);
3796
1.20k
    dctx->frameInfo = *frameInfo;
3797
1.20k
    dctx->maxBlockSize = LZ4F_getBlockSize(frameInfo->blockSizeID);
3798
1.20k
    if (frameInfo->contentSize)
3799
168
        dctx->frameRemainingSize = frameInfo->contentSize - decodedPos;
3800
1.20k
    dctx->dict = (const BYTE*)dict;
3801
1.20k
    dctx->dictSize = dictSize;
3802
1.20k
    dctx->skipContentChecksum = 1;   /* content checksum covers the whole frame : can't be verified */
3803
1.20k
    dctx->dStage = dstage_init;
3804
1.20k
    return 0;
3805
1.20k
}