Coverage Report

Created: 2026-08-09 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fluent-bit/lib/librdkafka-2.15.0/src/lz4.c
Line
Count
Source
1
/*
2
   LZ4 - Fast LZ compression algorithm
3
   Copyright (C) 2011-2020, Yann Collet.
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
/*-************************************
36
*  Tuning parameters
37
**************************************/
38
/*
39
 * LZ4_HEAPMODE :
40
 * Select how default compression functions will allocate memory for their hash table,
41
 * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
42
 */
43
#ifndef LZ4_HEAPMODE
44
#  define LZ4_HEAPMODE 0
45
#endif
46
47
/*
48
 * LZ4_ACCELERATION_DEFAULT :
49
 * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
50
 */
51
0
#define LZ4_ACCELERATION_DEFAULT 1
52
/*
53
 * LZ4_ACCELERATION_MAX :
54
 * Any "acceleration" value higher than this threshold
55
 * get treated as LZ4_ACCELERATION_MAX instead (fix #876)
56
 */
57
0
#define LZ4_ACCELERATION_MAX 65537
58
59
60
/*-************************************
61
*  CPU Feature Detection
62
**************************************/
63
/* LZ4_FORCE_MEMORY_ACCESS
64
 * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
65
 * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
66
 * The below switch allow to select different access method for improved performance.
67
 * Method 0 (default) : use `memcpy()`. Safe and portable.
68
 * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
69
 *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
70
 * Method 2 : direct access. This method is portable but violate C standard.
71
 *            It can generate buggy code on targets which assembly generation depends on alignment.
72
 *            But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
73
 * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
74
 * Prefer these methods in priority order (0 > 1 > 2)
75
 */
76
#ifndef LZ4_FORCE_MEMORY_ACCESS   /* can be defined externally */
77
#  if defined(__GNUC__) && \
78
  ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
79
  || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
80
#    define LZ4_FORCE_MEMORY_ACCESS 2
81
#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
82
#    define LZ4_FORCE_MEMORY_ACCESS 1
83
#  endif
84
#endif
85
86
/*
87
 * LZ4_FORCE_SW_BITCOUNT
88
 * Define this parameter if your target system or compiler does not support hardware bit count
89
 */
90
#if defined(_MSC_VER) && defined(_WIN32_WCE)   /* Visual Studio for WinCE doesn't support Hardware bit count */
91
#  undef  LZ4_FORCE_SW_BITCOUNT  /* avoid double def */
92
#  define LZ4_FORCE_SW_BITCOUNT
93
#endif
94
95
96
97
/*-************************************
98
*  Dependency
99
**************************************/
100
/*
101
 * LZ4_SRC_INCLUDED:
102
 * Amalgamation flag, whether lz4.c is included
103
 */
104
#ifndef LZ4_SRC_INCLUDED
105
#  define LZ4_SRC_INCLUDED 1
106
#endif
107
108
#ifndef LZ4_STATIC_LINKING_ONLY
109
#define LZ4_STATIC_LINKING_ONLY
110
#endif
111
112
#ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
113
#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
114
#endif
115
116
#define LZ4_STATIC_LINKING_ONLY  /* LZ4_DISTANCE_MAX */
117
#include "lz4.h"
118
/* see also "memory routines" below */
119
120
121
/*-************************************
122
*  Compiler Options
123
**************************************/
124
#if defined(_MSC_VER) && (_MSC_VER >= 1400)  /* Visual Studio 2005+ */
125
#  include <intrin.h>               /* only present in VS2005+ */
126
#  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
127
#  pragma warning(disable : 6237)   /* disable: C6237: conditional expression is always 0 */
128
#endif  /* _MSC_VER */
129
130
#ifndef LZ4_FORCE_INLINE
131
#  ifdef _MSC_VER    /* Visual Studio */
132
#    define LZ4_FORCE_INLINE static __forceinline
133
#  else
134
#    if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
135
#      ifdef __GNUC__
136
#        define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
137
#      else
138
#        define LZ4_FORCE_INLINE static inline
139
#      endif
140
#    else
141
#      define LZ4_FORCE_INLINE static
142
#    endif /* __STDC_VERSION__ */
143
#  endif  /* _MSC_VER */
144
#endif /* LZ4_FORCE_INLINE */
145
146
/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE
147
 * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8,
148
 * together with a simple 8-byte copy loop as a fall-back path.
149
 * However, this optimization hurts the decompression speed by >30%,
150
 * because the execution does not go to the optimized loop
151
 * for typical compressible data, and all of the preamble checks
152
 * before going to the fall-back path become useless overhead.
153
 * This optimization happens only with the -O3 flag, and -O2 generates
154
 * a simple 8-byte copy loop.
155
 * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8
156
 * functions are annotated with __attribute__((optimize("O2"))),
157
 * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute
158
 * of LZ4_wildCopy8 does not affect the compression speed.
159
 */
160
#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__)
161
#  define LZ4_FORCE_O2  __attribute__((optimize("O2")))
162
#  undef LZ4_FORCE_INLINE
163
#  define LZ4_FORCE_INLINE  static __inline __attribute__((optimize("O2"),always_inline))
164
#else
165
#  define LZ4_FORCE_O2
166
#endif
167
168
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
169
0
#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )
170
#else
171
#  define expect(expr,value)    (expr)
172
#endif
173
174
#ifndef likely
175
0
#define likely(expr)     expect((expr) != 0, 1)
176
#endif
177
#ifndef unlikely
178
0
#define unlikely(expr)   expect((expr) != 0, 0)
179
#endif
180
181
/* Should the alignment test prove unreliable, for some reason,
182
 * it can be disabled by setting LZ4_ALIGN_TEST to 0 */
183
#ifndef LZ4_ALIGN_TEST  /* can be externally provided */
184
# define LZ4_ALIGN_TEST 1
185
#endif
186
187
188
/*-************************************
189
*  Memory routines
190
**************************************/
191
192
/*! LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION :
193
 *  Disable relatively high-level LZ4/HC functions that use dynamic memory
194
 *  allocation functions (malloc(), calloc(), free()).
195
 *
196
 *  Note that this is a compile-time switch. And since it disables
197
 *  public/stable LZ4 v1 API functions, we don't recommend using this
198
 *  symbol to generate a library for distribution.
199
 *
200
 *  The following public functions are removed when this symbol is defined.
201
 *  - lz4   : LZ4_createStream, LZ4_freeStream,
202
 *            LZ4_createStreamDecode, LZ4_freeStreamDecode, LZ4_create (deprecated)
203
 *  - lz4hc : LZ4_createStreamHC, LZ4_freeStreamHC,
204
 *            LZ4_createHC (deprecated), LZ4_freeHC  (deprecated)
205
 *  - lz4frame, lz4file : All LZ4F_* functions
206
 */
207
#if defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
208
#  define ALLOC(s)          lz4_error_memory_allocation_is_disabled
209
#  define ALLOC_AND_ZERO(s) lz4_error_memory_allocation_is_disabled
210
#  define FREEMEM(p)        lz4_error_memory_allocation_is_disabled
211
#elif defined(LZ4_USER_MEMORY_FUNCTIONS)
212
/* memory management functions can be customized by user project.
213
 * Below functions must exist somewhere in the Project
214
 * and be available at link time */
215
void* LZ4_malloc(size_t s);
216
void* LZ4_calloc(size_t n, size_t s);
217
void  LZ4_free(void* p);
218
# define ALLOC(s)          LZ4_malloc(s)
219
# define ALLOC_AND_ZERO(s) LZ4_calloc(1,s)
220
# define FREEMEM(p)        LZ4_free(p)
221
#else
222
/* NOTE: While upgrading the lz4 version, replace the original `#else` block
223
 * in the code with this block, and retain this comment. */
224
struct rdkafka_s;
225
extern void *rd_kafka_mem_malloc(struct rdkafka_s *rk, size_t s);
226
extern void *rd_kafka_mem_calloc(struct rdkafka_s *rk, size_t n, size_t s);
227
extern void rd_kafka_mem_free(struct rdkafka_s *rk, void *p);
228
0
# define ALLOC(s)          rd_kafka_mem_malloc(NULL, s)
229
0
# define ALLOC_AND_ZERO(s) rd_kafka_mem_calloc(NULL, 1, s)
230
0
# define FREEMEM(p)        rd_kafka_mem_free(NULL, p)
231
#endif
232
233
#if ! LZ4_FREESTANDING
234
#  include <string.h>   /* memset, memcpy */
235
#endif
236
#if !defined(LZ4_memset)
237
0
#  define LZ4_memset(p,v,s) memset((p),(v),(s))
238
#endif
239
0
#define MEM_INIT(p,v,s)   LZ4_memset((p),(v),(s))
240
241
242
/*-************************************
243
*  Common Constants
244
**************************************/
245
0
#define MINMATCH 4
246
247
0
#define WILDCOPYLENGTH 8
248
0
#define LASTLITERALS   5   /* see ../doc/lz4_Block_format.md#parsing-restrictions */
249
0
#define MFLIMIT       12   /* see ../doc/lz4_Block_format.md#parsing-restrictions */
250
0
#define MATCH_SAFEGUARD_DISTANCE  ((2*WILDCOPYLENGTH) - MINMATCH)   /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */
251
0
#define FASTLOOP_SAFE_DISTANCE 64
252
static const int LZ4_minLength = (MFLIMIT+1);
253
254
0
#define KB *(1 <<10)
255
#define MB *(1 <<20)
256
0
#define GB *(1U<<30)
257
258
0
#define LZ4_DISTANCE_ABSOLUTE_MAX 65535
259
#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX)   /* max supported by LZ4 format */
260
#  error "LZ4_DISTANCE_MAX is too big : must be <= 65535"
261
#endif
262
263
0
#define ML_BITS  4
264
0
#define ML_MASK  ((1U<<ML_BITS)-1)
265
0
#define RUN_BITS (8-ML_BITS)
266
0
#define RUN_MASK ((1U<<RUN_BITS)-1)
267
268
269
/*-************************************
270
*  Error detection
271
**************************************/
272
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)
273
#  include <assert.h>
274
#else
275
#  ifndef assert
276
0
#    define assert(condition) ((void)0)
277
#  endif
278
#endif
279
280
0
#define LZ4_STATIC_ASSERT(c)   { enum { LZ4_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
281
282
#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2)
283
#  include <stdio.h>
284
   static int g_debuglog_enable = 1;
285
#  define DEBUGLOG(l, ...) {                          \
286
        if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
287
            fprintf(stderr, __FILE__ ": ");           \
288
            fprintf(stderr, __VA_ARGS__);             \
289
            fprintf(stderr, " \n");                   \
290
    }   }
291
#else
292
0
#  define DEBUGLOG(l, ...) {}    /* disabled */
293
#endif
294
295
static int LZ4_isAligned(const void* ptr, size_t alignment)
296
0
{
297
0
    return ((size_t)ptr & (alignment -1)) == 0;
298
0
}
Unexecuted instantiation: lz4hc.c:LZ4_isAligned
Unexecuted instantiation: lz4.c:LZ4_isAligned
299
300
301
/*-************************************
302
*  Types
303
**************************************/
304
#include <limits.h>
305
#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
306
# include <stdint.h>
307
  typedef  uint8_t BYTE;
308
  typedef uint16_t U16;
309
  typedef uint32_t U32;
310
  typedef  int32_t S32;
311
  typedef uint64_t U64;
312
  typedef uintptr_t uptrval;
313
#else
314
# if UINT_MAX != 4294967295UL
315
#   error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4"
316
# endif
317
  typedef unsigned char       BYTE;
318
  typedef unsigned short      U16;
319
  typedef unsigned int        U32;
320
  typedef   signed int        S32;
321
  typedef unsigned long long  U64;
322
  typedef size_t              uptrval;   /* generally true, except OpenVMS-64 */
323
#endif
324
325
#if defined(__x86_64__)
326
  typedef U64    reg_t;   /* 64-bits in x32 mode */
327
#else
328
  typedef size_t reg_t;   /* 32-bits in x32 mode */
329
#endif
330
331
typedef enum {
332
    notLimited = 0,
333
    limitedOutput = 1,
334
    fillOutput = 2
335
} limitedOutput_directive;
336
337
338
/*-************************************
339
*  Reading and writing into memory
340
**************************************/
341
342
/**
343
 * LZ4 relies on memcpy with a constant size being inlined. In freestanding
344
 * environments, the compiler can't assume the implementation of memcpy() is
345
 * standard compliant, so it can't apply its specialized memcpy() inlining
346
 * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze
347
 * memcpy() as if it were standard compliant, so it can inline it in freestanding
348
 * environments. This is needed when decompressing the Linux Kernel, for example.
349
 */
350
#if !defined(LZ4_memcpy)
351
#  if defined(__GNUC__) && (__GNUC__ >= 4)
352
0
#    define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size)
353
#  else
354
#    define LZ4_memcpy(dst, src, size) memcpy(dst, src, size)
355
#  endif
356
#endif
357
358
#if !defined(LZ4_memmove)
359
#  if defined(__GNUC__) && (__GNUC__ >= 4)
360
0
#    define LZ4_memmove __builtin_memmove
361
#  else
362
#    define LZ4_memmove memmove
363
#  endif
364
#endif
365
366
static unsigned LZ4_isLittleEndian(void)
367
0
{
368
0
    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental */
369
0
    return one.c[0];
370
0
}
Unexecuted instantiation: lz4hc.c:LZ4_isLittleEndian
Unexecuted instantiation: lz4.c:LZ4_isLittleEndian
371
372
373
#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
374
/* lie to the compiler about data alignment; use with caution */
375
376
static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
377
static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
378
static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
379
380
static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
381
static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
382
383
#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
384
385
/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
386
/* currently only defined for gcc and icc */
387
typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) LZ4_unalign;
388
389
0
static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign*)ptr)->u16; }
Unexecuted instantiation: lz4hc.c:LZ4_read16
Unexecuted instantiation: lz4.c:LZ4_read16
390
0
static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign*)ptr)->u32; }
Unexecuted instantiation: lz4hc.c:LZ4_read32
Unexecuted instantiation: lz4.c:LZ4_read32
391
0
static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalign*)ptr)->uArch; }
Unexecuted instantiation: lz4hc.c:LZ4_read_ARCH
Unexecuted instantiation: lz4.c:LZ4_read_ARCH
392
393
0
static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign*)memPtr)->u16 = value; }
Unexecuted instantiation: lz4hc.c:LZ4_write16
Unexecuted instantiation: lz4.c:LZ4_write16
394
0
static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign*)memPtr)->u32 = value; }
Unexecuted instantiation: lz4hc.c:LZ4_write32
Unexecuted instantiation: lz4.c:LZ4_write32
395
396
#else  /* safe and portable access using memcpy() */
397
398
static U16 LZ4_read16(const void* memPtr)
399
{
400
    U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
401
}
402
403
static U32 LZ4_read32(const void* memPtr)
404
{
405
    U32 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
406
}
407
408
static reg_t LZ4_read_ARCH(const void* memPtr)
409
{
410
    reg_t val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
411
}
412
413
static void LZ4_write16(void* memPtr, U16 value)
414
{
415
    LZ4_memcpy(memPtr, &value, sizeof(value));
416
}
417
418
static void LZ4_write32(void* memPtr, U32 value)
419
{
420
    LZ4_memcpy(memPtr, &value, sizeof(value));
421
}
422
423
#endif /* LZ4_FORCE_MEMORY_ACCESS */
424
425
426
static U16 LZ4_readLE16(const void* memPtr)
427
0
{
428
0
    if (LZ4_isLittleEndian()) {
429
0
        return LZ4_read16(memPtr);
430
0
    } else {
431
0
        const BYTE* p = (const BYTE*)memPtr;
432
0
        return (U16)((U16)p[0] + (p[1]<<8));
433
0
    }
434
0
}
Unexecuted instantiation: lz4hc.c:LZ4_readLE16
Unexecuted instantiation: lz4.c:LZ4_readLE16
435
436
static void LZ4_writeLE16(void* memPtr, U16 value)
437
0
{
438
0
    if (LZ4_isLittleEndian()) {
439
0
        LZ4_write16(memPtr, value);
440
0
    } else {
441
0
        BYTE* p = (BYTE*)memPtr;
442
0
        p[0] = (BYTE) value;
443
0
        p[1] = (BYTE)(value>>8);
444
0
    }
445
0
}
Unexecuted instantiation: lz4hc.c:LZ4_writeLE16
Unexecuted instantiation: lz4.c:LZ4_writeLE16
446
447
/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
448
LZ4_FORCE_INLINE
449
void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd)
450
0
{
451
0
    BYTE* d = (BYTE*)dstPtr;
452
0
    const BYTE* s = (const BYTE*)srcPtr;
453
0
    BYTE* const e = (BYTE*)dstEnd;
454
455
0
    do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e);
456
0
}
Unexecuted instantiation: lz4hc.c:LZ4_wildCopy8
Unexecuted instantiation: lz4.c:LZ4_wildCopy8
457
458
static const unsigned inc32table[8] = {0, 1, 2,  1,  0,  4, 4, 4};
459
static const int      dec64table[8] = {0, 0, 0, -1, -4,  1, 2, 3};
460
461
462
#ifndef LZ4_FAST_DEC_LOOP
463
#  if defined __i386__ || defined _M_IX86 || defined __x86_64__ || defined _M_X64
464
#    define LZ4_FAST_DEC_LOOP 1
465
#  elif defined(__aarch64__) && defined(__APPLE__)
466
#    define LZ4_FAST_DEC_LOOP 1
467
#  elif defined(__aarch64__) && !defined(__clang__)
468
     /* On non-Apple aarch64, we disable this optimization for clang because
469
      * on certain mobile chipsets, performance is reduced with clang. For
470
      * more information refer to https://github.com/lz4/lz4/pull/707 */
471
#    define LZ4_FAST_DEC_LOOP 1
472
#  else
473
#    define LZ4_FAST_DEC_LOOP 0
474
#  endif
475
#endif
476
477
#if LZ4_FAST_DEC_LOOP
478
479
LZ4_FORCE_INLINE void
480
LZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
481
0
{
482
0
    assert(srcPtr + offset == dstPtr);
483
0
    if (offset < 8) {
484
0
        LZ4_write32(dstPtr, 0);   /* silence an msan warning when offset==0 */
485
0
        dstPtr[0] = srcPtr[0];
486
0
        dstPtr[1] = srcPtr[1];
487
0
        dstPtr[2] = srcPtr[2];
488
0
        dstPtr[3] = srcPtr[3];
489
0
        srcPtr += inc32table[offset];
490
0
        LZ4_memcpy(dstPtr+4, srcPtr, 4);
491
0
        srcPtr -= dec64table[offset];
492
0
        dstPtr += 8;
493
0
    } else {
494
0
        LZ4_memcpy(dstPtr, srcPtr, 8);
495
0
        dstPtr += 8;
496
0
        srcPtr += 8;
497
0
    }
498
499
0
    LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);
500
0
}
Unexecuted instantiation: lz4hc.c:LZ4_memcpy_using_offset_base
Unexecuted instantiation: lz4.c:LZ4_memcpy_using_offset_base
501
502
/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd
503
 * this version copies two times 16 bytes (instead of one time 32 bytes)
504
 * because it must be compatible with offsets >= 16. */
505
LZ4_FORCE_INLINE void
506
LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)
507
0
{
508
0
    BYTE* d = (BYTE*)dstPtr;
509
0
    const BYTE* s = (const BYTE*)srcPtr;
510
0
    BYTE* const e = (BYTE*)dstEnd;
511
512
0
    do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);
513
0
}
Unexecuted instantiation: lz4hc.c:LZ4_wildCopy32
Unexecuted instantiation: lz4.c:LZ4_wildCopy32
514
515
/* LZ4_memcpy_using_offset()  presumes :
516
 * - dstEnd >= dstPtr + MINMATCH
517
 * - there is at least 8 bytes available to write after dstEnd */
518
LZ4_FORCE_INLINE void
519
LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
520
0
{
521
0
    BYTE v[8];
522
523
0
    assert(dstEnd >= dstPtr + MINMATCH);
524
525
0
    switch(offset) {
526
0
    case 1:
527
0
        MEM_INIT(v, *srcPtr, 8);
528
0
        break;
529
0
    case 2:
530
0
        LZ4_memcpy(v, srcPtr, 2);
531
0
        LZ4_memcpy(&v[2], srcPtr, 2);
532
#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
533
#  pragma warning(push)
534
#  pragma warning(disable : 6385) /* warning C6385: Reading invalid data from 'v'. */
535
#endif
536
0
        LZ4_memcpy(&v[4], v, 4);
537
#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
538
#  pragma warning(pop)
539
#endif
540
0
        break;
541
0
    case 4:
542
0
        LZ4_memcpy(v, srcPtr, 4);
543
0
        LZ4_memcpy(&v[4], srcPtr, 4);
544
0
        break;
545
0
    default:
546
0
        LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
547
0
        return;
548
0
    }
549
550
0
    LZ4_memcpy(dstPtr, v, 8);
551
0
    dstPtr += 8;
552
0
    while (dstPtr < dstEnd) {
553
0
        LZ4_memcpy(dstPtr, v, 8);
554
0
        dstPtr += 8;
555
0
    }
556
0
}
Unexecuted instantiation: lz4hc.c:LZ4_memcpy_using_offset
Unexecuted instantiation: lz4.c:LZ4_memcpy_using_offset
557
#endif
558
559
560
/*-************************************
561
*  Common functions
562
**************************************/
563
static unsigned LZ4_NbCommonBytes (reg_t val)
564
0
{
565
0
    assert(val != 0);
566
0
    if (LZ4_isLittleEndian()) {
567
0
        if (sizeof(val) == 8) {
568
#       if defined(_MSC_VER) && (_MSC_VER >= 1800) && (defined(_M_AMD64) && !defined(_M_ARM64EC)) && !defined(LZ4_FORCE_SW_BITCOUNT)
569
/*-*************************************************************************************************
570
* ARM64EC is a Microsoft-designed ARM64 ABI compatible with AMD64 applications on ARM64 Windows 11.
571
* The ARM64EC ABI does not support AVX/AVX2/AVX512 instructions, nor their relevant intrinsics
572
* including _tzcnt_u64. Therefore, we need to neuter the _tzcnt_u64 code path for ARM64EC.
573
****************************************************************************************************/
574
#         if defined(__clang__) && (__clang_major__ < 10)
575
            /* Avoid undefined clang-cl intrinsics issue.
576
             * See https://github.com/lz4/lz4/pull/1017 for details. */
577
            return (unsigned)__builtin_ia32_tzcnt_u64(val) >> 3;
578
#         else
579
            /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */
580
            return (unsigned)_tzcnt_u64(val) >> 3;
581
#         endif
582
#       elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
583
            unsigned long r = 0;
584
            _BitScanForward64(&r, (U64)val);
585
            return (unsigned)r >> 3;
586
#       elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
587
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
588
                                        !defined(LZ4_FORCE_SW_BITCOUNT)
589
            return (unsigned)__builtin_ctzll((U64)val) >> 3;
590
#       else
591
            const U64 m = 0x0101010101010101ULL;
592
            val ^= val - 1;
593
            return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56);
594
#       endif
595
0
        } else /* 32 bits */ {
596
#       if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
597
            unsigned long r;
598
            _BitScanForward(&r, (U32)val);
599
            return (unsigned)r >> 3;
600
#       elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
601
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
602
                        !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)
603
            return (unsigned)__builtin_ctz((U32)val) >> 3;
604
#       else
605
            const U32 m = 0x01010101;
606
            return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
607
#       endif
608
0
        }
609
0
    } else   /* Big Endian CPU */ {
610
0
        if (sizeof(val)==8) {
611
0
#       if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
612
0
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
613
0
                        !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)
614
0
            return (unsigned)__builtin_clzll((U64)val) >> 3;
615
#       else
616
#if 1
617
            /* this method is probably faster,
618
             * but adds a 128 bytes lookup table */
619
            static const unsigned char ctz7_tab[128] = {
620
                7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
621
                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
622
                5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
623
                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
624
                6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
625
                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
626
                5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
627
                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
628
            };
629
            U64 const mask = 0x0101010101010101ULL;
630
            U64 const t = (((val >> 8) - mask) | val) & mask;
631
            return ctz7_tab[(t * 0x0080402010080402ULL) >> 57];
632
#else
633
            /* this method doesn't consume memory space like the previous one,
634
             * but it contains several branches,
635
             * that may end up slowing execution */
636
            static const U32 by32 = sizeof(val)*4;  /* 32 on 64 bits (goal), 16 on 32 bits.
637
            Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
638
            Note that this code path is never triggered in 32-bits mode. */
639
            unsigned r;
640
            if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
641
            if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
642
            r += (!val);
643
            return r;
644
#endif
645
#       endif
646
0
        } else /* 32 bits */ {
647
0
#       if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
648
0
                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
649
0
                                        !defined(LZ4_FORCE_SW_BITCOUNT)
650
0
            return (unsigned)__builtin_clz((U32)val) >> 3;
651
#       else
652
            val >>= 8;
653
            val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |
654
              (val + 0x00FF0000)) >> 24;
655
            return (unsigned)val ^ 3;
656
#       endif
657
0
        }
658
0
    }
659
0
}
Unexecuted instantiation: lz4hc.c:LZ4_NbCommonBytes
Unexecuted instantiation: lz4.c:LZ4_NbCommonBytes
660
661
662
0
#define STEPSIZE sizeof(reg_t)
663
LZ4_FORCE_INLINE
664
unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
665
0
{
666
0
    const BYTE* const pStart = pIn;
667
668
0
    if (likely(pIn < pInLimit-(STEPSIZE-1))) {
669
0
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
670
0
        if (!diff) {
671
0
            pIn+=STEPSIZE; pMatch+=STEPSIZE;
672
0
        } else {
673
0
            return LZ4_NbCommonBytes(diff);
674
0
    }   }
675
676
0
    while (likely(pIn < pInLimit-(STEPSIZE-1))) {
677
0
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
678
0
        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
679
0
        pIn += LZ4_NbCommonBytes(diff);
680
0
        return (unsigned)(pIn - pStart);
681
0
    }
682
683
0
    if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
684
0
    if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
685
0
    if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
686
0
    return (unsigned)(pIn - pStart);
687
0
}
Unexecuted instantiation: lz4hc.c:LZ4_count
Unexecuted instantiation: lz4.c:LZ4_count
688
689
690
#ifndef LZ4_COMMONDEFS_ONLY
691
/*-************************************
692
*  Local Constants
693
**************************************/
694
static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));
695
static const U32 LZ4_skipTrigger = 6;  /* Increase this value ==> compression run slower on incompressible data */
696
697
698
/*-************************************
699
*  Local Structures and types
700
**************************************/
701
typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;
702
703
/**
704
 * This enum distinguishes several different modes of accessing previous
705
 * content in the stream.
706
 *
707
 * - noDict        : There is no preceding content.
708
 * - withPrefix64k : Table entries up to ctx->dictSize before the current blob
709
 *                   blob being compressed are valid and refer to the preceding
710
 *                   content (of length ctx->dictSize), which is available
711
 *                   contiguously preceding in memory the content currently
712
 *                   being compressed.
713
 * - usingExtDict  : Like withPrefix64k, but the preceding content is somewhere
714
 *                   else in memory, starting at ctx->dictionary with length
715
 *                   ctx->dictSize.
716
 * - usingDictCtx  : Everything concerning the preceding content is
717
 *                   in a separate context, pointed to by ctx->dictCtx.
718
 *                   ctx->dictionary, ctx->dictSize, and table entries
719
 *                   in the current context that refer to positions
720
 *                   preceding the beginning of the current compression are
721
 *                   ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx
722
 *                   ->dictSize describe the location and size of the preceding
723
 *                   content, and matches are found by looking in the ctx
724
 *                   ->dictCtx->hashTable.
725
 */
726
typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;
727
typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
728
729
730
/*-************************************
731
*  Local Utils
732
**************************************/
733
0
int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
734
0
const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
735
0
int LZ4_compressBound(int isize)  { return LZ4_COMPRESSBOUND(isize); }
736
0
int LZ4_sizeofState(void) { return sizeof(LZ4_stream_t); }
737
738
739
/*-****************************************
740
*  Internal Definitions, used only in Tests
741
*******************************************/
742
#if defined (__cplusplus)
743
extern "C" {
744
#endif
745
746
int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize);
747
748
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
749
                                     int compressedSize, int maxOutputSize,
750
                                     const void* dictStart, size_t dictSize);
751
int LZ4_decompress_safe_partial_forceExtDict(const char* source, char* dest,
752
                                     int compressedSize, int targetOutputSize, int dstCapacity,
753
                                     const void* dictStart, size_t dictSize);
754
#if defined (__cplusplus)
755
}
756
#endif
757
758
/*-******************************
759
*  Compression functions
760
********************************/
761
LZ4_FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
762
0
{
763
0
    if (tableType == byU16)
764
0
        return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
765
0
    else
766
0
        return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
767
0
}
768
769
LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
770
0
{
771
0
    const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
772
0
    if (LZ4_isLittleEndian()) {
773
0
        const U64 prime5bytes = 889523592379ULL;
774
0
        return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
775
0
    } else {
776
0
        const U64 prime8bytes = 11400714785074694791ULL;
777
0
        return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
778
0
    }
779
0
}
780
781
LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
782
0
{
783
0
    if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
784
0
    return LZ4_hash4(LZ4_read32(p), tableType);
785
0
}
786
787
LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType)
788
0
{
789
0
    switch (tableType)
790
0
    {
791
0
    default: /* fallthrough */
792
0
    case clearedTable: { /* illegal! */ assert(0); return; }
793
0
    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; }
794
0
    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; }
795
0
    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; }
796
0
    }
797
0
}
798
799
LZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType)
800
0
{
801
0
    switch (tableType)
802
0
    {
803
0
    default: /* fallthrough */
804
0
    case clearedTable: /* fallthrough */
805
0
    case byPtr: { /* illegal! */ assert(0); return; }
806
0
    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }
807
0
    case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }
808
0
    }
809
0
}
810
811
LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h,
812
                                  void* tableBase, tableType_t const tableType,
813
                            const BYTE* srcBase)
814
0
{
815
0
    switch (tableType)
816
0
    {
817
0
    case clearedTable: { /* illegal! */ assert(0); return; }
818
0
    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
819
0
    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
820
0
    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
821
0
    }
822
0
}
823
824
LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
825
0
{
826
0
    U32 const h = LZ4_hashPosition(p, tableType);
827
0
    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
828
0
}
829
830
/* LZ4_getIndexOnHash() :
831
 * Index of match position registered in hash table.
832
 * hash position must be calculated by using base+index, or dictBase+index.
833
 * Assumption 1 : only valid if tableType == byU32 or byU16.
834
 * Assumption 2 : h is presumed valid (within limits of hash table)
835
 */
836
LZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType)
837
0
{
838
0
    LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
839
0
    if (tableType == byU32) {
840
0
        const U32* const hashTable = (const U32*) tableBase;
841
0
        assert(h < (1U << (LZ4_MEMORY_USAGE-2)));
842
0
        return hashTable[h];
843
0
    }
844
0
    if (tableType == byU16) {
845
0
        const U16* const hashTable = (const U16*) tableBase;
846
0
        assert(h < (1U << (LZ4_MEMORY_USAGE-1)));
847
0
        return hashTable[h];
848
0
    }
849
0
    assert(0); return 0;  /* forbidden case */
850
0
}
851
852
static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
853
0
{
854
0
    if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
855
0
    if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
856
0
    { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */
857
0
}
858
859
LZ4_FORCE_INLINE const BYTE*
860
LZ4_getPosition(const BYTE* p,
861
                const void* tableBase, tableType_t tableType,
862
                const BYTE* srcBase)
863
0
{
864
0
    U32 const h = LZ4_hashPosition(p, tableType);
865
0
    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
866
0
}
867
868
LZ4_FORCE_INLINE void
869
LZ4_prepareTable(LZ4_stream_t_internal* const cctx,
870
           const int inputSize,
871
0
           const tableType_t tableType) {
872
    /* If the table hasn't been used, it's guaranteed to be zeroed out, and is
873
     * therefore safe to use no matter what mode we're in. Otherwise, we figure
874
     * out if it's safe to leave as is or whether it needs to be reset.
875
     */
876
0
    if ((tableType_t)cctx->tableType != clearedTable) {
877
0
        assert(inputSize >= 0);
878
0
        if ((tableType_t)cctx->tableType != tableType
879
0
          || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU)
880
0
          || ((tableType == byU32) && cctx->currentOffset > 1 GB)
881
0
          || tableType == byPtr
882
0
          || inputSize >= 4 KB)
883
0
        {
884
0
            DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx);
885
0
            MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
886
0
            cctx->currentOffset = 0;
887
0
            cctx->tableType = (U32)clearedTable;
888
0
        } else {
889
0
            DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
890
0
        }
891
0
    }
892
893
    /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back,
894
     * is faster than compressing without a gap.
895
     * However, compressing with currentOffset == 0 is faster still,
896
     * so we preserve that case.
897
     */
898
0
    if (cctx->currentOffset != 0 && tableType == byU32) {
899
0
        DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset");
900
0
        cctx->currentOffset += 64 KB;
901
0
    }
902
903
    /* Finally, clear history */
904
0
    cctx->dictCtx = NULL;
905
0
    cctx->dictionary = NULL;
906
0
    cctx->dictSize = 0;
907
0
}
908
909
/** LZ4_compress_generic() :
910
 *  inlined, to ensure branches are decided at compilation time.
911
 *  Presumed already validated at this stage:
912
 *  - source != NULL
913
 *  - inputSize > 0
914
 */
915
LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
916
                 LZ4_stream_t_internal* const cctx,
917
                 const char* const source,
918
                 char* const dest,
919
                 const int inputSize,
920
                 int*  inputConsumed, /* only written when outputDirective == fillOutput */
921
                 const int maxOutputSize,
922
                 const limitedOutput_directive outputDirective,
923
                 const tableType_t tableType,
924
                 const dict_directive dictDirective,
925
                 const dictIssue_directive dictIssue,
926
                 const int acceleration)
927
0
{
928
0
    int result;
929
0
    const BYTE* ip = (const BYTE*) source;
930
931
0
    U32 const startIndex = cctx->currentOffset;
932
0
    const BYTE* base = (const BYTE*) source - startIndex;
933
0
    const BYTE* lowLimit;
934
935
0
    const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
936
0
    const BYTE* const dictionary =
937
0
        dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
938
0
    const U32 dictSize =
939
0
        dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
940
0
    const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with index in current context */
941
942
0
    int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
943
0
    U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */
944
0
    const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary;
945
0
    const BYTE* anchor = (const BYTE*) source;
946
0
    const BYTE* const iend = ip + inputSize;
947
0
    const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;
948
0
    const BYTE* const matchlimit = iend - LASTLITERALS;
949
950
    /* the dictCtx currentOffset is indexed on the start of the dictionary,
951
     * while a dictionary in the current context precedes the currentOffset */
952
0
    const BYTE* dictBase = (dictionary == NULL) ? NULL :
953
0
                           (dictDirective == usingDictCtx) ?
954
0
                            dictionary + dictSize - dictCtx->currentOffset :
955
0
                            dictionary + dictSize - startIndex;
956
957
0
    BYTE* op = (BYTE*) dest;
958
0
    BYTE* const olimit = op + maxOutputSize;
959
960
0
    U32 offset = 0;
961
0
    U32 forwardH;
962
963
0
    DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType);
964
0
    assert(ip != NULL);
965
    /* If init conditions are not met, we don't have to mark stream
966
     * as having dirty context, since no action was taken yet */
967
0
    if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */
968
0
    if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) { return 0; }  /* Size too large (not within 64K limit) */
969
0
    if (tableType==byPtr) assert(dictDirective==noDict);      /* only supported use case with byPtr */
970
0
    assert(acceleration >= 1);
971
972
0
    lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
973
974
    /* Update context state */
975
0
    if (dictDirective == usingDictCtx) {
976
        /* Subsequent linked blocks can't use the dictionary. */
977
        /* Instead, they use the block we just compressed. */
978
0
        cctx->dictCtx = NULL;
979
0
        cctx->dictSize = (U32)inputSize;
980
0
    } else {
981
0
        cctx->dictSize += (U32)inputSize;
982
0
    }
983
0
    cctx->currentOffset += (U32)inputSize;
984
0
    cctx->tableType = (U32)tableType;
985
986
0
    if (inputSize<LZ4_minLength) goto _last_literals;        /* Input too small, no compression (all literals) */
987
988
    /* First Byte */
989
0
    LZ4_putPosition(ip, cctx->hashTable, tableType, base);
990
0
    ip++; forwardH = LZ4_hashPosition(ip, tableType);
991
992
    /* Main Loop */
993
0
    for ( ; ; ) {
994
0
        const BYTE* match;
995
0
        BYTE* token;
996
0
        const BYTE* filledIp;
997
998
        /* Find a match */
999
0
        if (tableType == byPtr) {
1000
0
            const BYTE* forwardIp = ip;
1001
0
            int step = 1;
1002
0
            int searchMatchNb = acceleration << LZ4_skipTrigger;
1003
0
            do {
1004
0
                U32 const h = forwardH;
1005
0
                ip = forwardIp;
1006
0
                forwardIp += step;
1007
0
                step = (searchMatchNb++ >> LZ4_skipTrigger);
1008
1009
0
                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
1010
0
                assert(ip < mflimitPlusOne);
1011
1012
0
                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
1013
0
                forwardH = LZ4_hashPosition(forwardIp, tableType);
1014
0
                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
1015
1016
0
            } while ( (match+LZ4_DISTANCE_MAX < ip)
1017
0
                   || (LZ4_read32(match) != LZ4_read32(ip)) );
1018
1019
0
        } else {   /* byU32, byU16 */
1020
1021
0
            const BYTE* forwardIp = ip;
1022
0
            int step = 1;
1023
0
            int searchMatchNb = acceleration << LZ4_skipTrigger;
1024
0
            do {
1025
0
                U32 const h = forwardH;
1026
0
                U32 const current = (U32)(forwardIp - base);
1027
0
                U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
1028
0
                assert(matchIndex <= current);
1029
0
                assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
1030
0
                ip = forwardIp;
1031
0
                forwardIp += step;
1032
0
                step = (searchMatchNb++ >> LZ4_skipTrigger);
1033
1034
0
                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
1035
0
                assert(ip < mflimitPlusOne);
1036
1037
0
                if (dictDirective == usingDictCtx) {
1038
0
                    if (matchIndex < startIndex) {
1039
                        /* there was no match, try the dictionary */
1040
0
                        assert(tableType == byU32);
1041
0
                        matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
1042
0
                        match = dictBase + matchIndex;
1043
0
                        matchIndex += dictDelta;   /* make dictCtx index comparable with current context */
1044
0
                        lowLimit = dictionary;
1045
0
                    } else {
1046
0
                        match = base + matchIndex;
1047
0
                        lowLimit = (const BYTE*)source;
1048
0
                    }
1049
0
                } else if (dictDirective == usingExtDict) {
1050
0
                    if (matchIndex < startIndex) {
1051
0
                        DEBUGLOG(7, "extDict candidate: matchIndex=%5u  <  startIndex=%5u", matchIndex, startIndex);
1052
0
                        assert(startIndex - matchIndex >= MINMATCH);
1053
0
                        assert(dictBase);
1054
0
                        match = dictBase + matchIndex;
1055
0
                        lowLimit = dictionary;
1056
0
                    } else {
1057
0
                        match = base + matchIndex;
1058
0
                        lowLimit = (const BYTE*)source;
1059
0
                    }
1060
0
                } else {   /* single continuous memory segment */
1061
0
                    match = base + matchIndex;
1062
0
                }
1063
0
                forwardH = LZ4_hashPosition(forwardIp, tableType);
1064
0
                LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
1065
1066
0
                DEBUGLOG(7, "candidate at pos=%u  (offset=%u \n", matchIndex, current - matchIndex);
1067
0
                if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; }    /* match outside of valid area */
1068
0
                assert(matchIndex < current);
1069
0
                if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX))
1070
0
                  && (matchIndex+LZ4_DISTANCE_MAX < current)) {
1071
0
                    continue;
1072
0
                } /* too far */
1073
0
                assert((current - matchIndex) <= LZ4_DISTANCE_MAX);  /* match now expected within distance */
1074
1075
0
                if (LZ4_read32(match) == LZ4_read32(ip)) {
1076
0
                    if (maybe_extMem) offset = current - matchIndex;
1077
0
                    break;   /* match found */
1078
0
                }
1079
1080
0
            } while(1);
1081
0
        }
1082
1083
        /* Catch up */
1084
0
        filledIp = ip;
1085
0
        while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
1086
1087
        /* Encode Literals */
1088
0
        {   unsigned const litLength = (unsigned)(ip - anchor);
1089
0
            token = op++;
1090
0
            if ((outputDirective == limitedOutput) &&  /* Check output buffer overflow */
1091
0
                (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) {
1092
0
                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1093
0
            }
1094
0
            if ((outputDirective == fillOutput) &&
1095
0
                (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) {
1096
0
                op--;
1097
0
                goto _last_literals;
1098
0
            }
1099
0
            if (litLength >= RUN_MASK) {
1100
0
                int len = (int)(litLength - RUN_MASK);
1101
0
                *token = (RUN_MASK<<ML_BITS);
1102
0
                for(; len >= 255 ; len-=255) *op++ = 255;
1103
0
                *op++ = (BYTE)len;
1104
0
            }
1105
0
            else *token = (BYTE)(litLength<<ML_BITS);
1106
1107
            /* Copy Literals */
1108
0
            LZ4_wildCopy8(op, anchor, op+litLength);
1109
0
            op+=litLength;
1110
0
            DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
1111
0
                        (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source));
1112
0
        }
1113
1114
0
_next_match:
1115
        /* at this stage, the following variables must be correctly set :
1116
         * - ip : at start of LZ operation
1117
         * - match : at start of previous pattern occurrence; can be within current prefix, or within extDict
1118
         * - offset : if maybe_ext_memSegment==1 (constant)
1119
         * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise
1120
         * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written
1121
         */
1122
1123
0
        if ((outputDirective == fillOutput) &&
1124
0
            (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)) {
1125
            /* the match was too close to the end, rewind and go to last literals */
1126
0
            op = token;
1127
0
            goto _last_literals;
1128
0
        }
1129
1130
        /* Encode Offset */
1131
0
        if (maybe_extMem) {   /* static test */
1132
0
            DEBUGLOG(6, "             with offset=%u  (ext if > %i)", offset, (int)(ip - (const BYTE*)source));
1133
0
            assert(offset <= LZ4_DISTANCE_MAX && offset > 0);
1134
0
            LZ4_writeLE16(op, (U16)offset); op+=2;
1135
0
        } else  {
1136
0
            DEBUGLOG(6, "             with offset=%u  (same segment)", (U32)(ip - match));
1137
0
            assert(ip-match <= LZ4_DISTANCE_MAX);
1138
0
            LZ4_writeLE16(op, (U16)(ip - match)); op+=2;
1139
0
        }
1140
1141
        /* Encode MatchLength */
1142
0
        {   unsigned matchCode;
1143
1144
0
            if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx)
1145
0
              && (lowLimit==dictionary) /* match within extDict */ ) {
1146
0
                const BYTE* limit = ip + (dictEnd-match);
1147
0
                assert(dictEnd > match);
1148
0
                if (limit > matchlimit) limit = matchlimit;
1149
0
                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
1150
0
                ip += (size_t)matchCode + MINMATCH;
1151
0
                if (ip==limit) {
1152
0
                    unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit);
1153
0
                    matchCode += more;
1154
0
                    ip += more;
1155
0
                }
1156
0
                DEBUGLOG(6, "             with matchLength=%u starting in extDict", matchCode+MINMATCH);
1157
0
            } else {
1158
0
                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
1159
0
                ip += (size_t)matchCode + MINMATCH;
1160
0
                DEBUGLOG(6, "             with matchLength=%u", matchCode+MINMATCH);
1161
0
            }
1162
1163
0
            if ((outputDirective) &&    /* Check output buffer overflow */
1164
0
                (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) {
1165
0
                if (outputDirective == fillOutput) {
1166
                    /* Match description too long : reduce it */
1167
0
                    U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;
1168
0
                    ip -= matchCode - newMatchCode;
1169
0
                    assert(newMatchCode < matchCode);
1170
0
                    matchCode = newMatchCode;
1171
0
                    if (unlikely(ip <= filledIp)) {
1172
                        /* We have already filled up to filledIp so if ip ends up less than filledIp
1173
                         * we have positions in the hash table beyond the current position. This is
1174
                         * a problem if we reuse the hash table. So we have to remove these positions
1175
                         * from the hash table.
1176
                         */
1177
0
                        const BYTE* ptr;
1178
0
                        DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip));
1179
0
                        for (ptr = ip; ptr <= filledIp; ++ptr) {
1180
0
                            U32 const h = LZ4_hashPosition(ptr, tableType);
1181
0
                            LZ4_clearHash(h, cctx->hashTable, tableType);
1182
0
                        }
1183
0
                    }
1184
0
                } else {
1185
0
                    assert(outputDirective == limitedOutput);
1186
0
                    return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1187
0
                }
1188
0
            }
1189
0
            if (matchCode >= ML_MASK) {
1190
0
                *token += ML_MASK;
1191
0
                matchCode -= ML_MASK;
1192
0
                LZ4_write32(op, 0xFFFFFFFF);
1193
0
                while (matchCode >= 4*255) {
1194
0
                    op+=4;
1195
0
                    LZ4_write32(op, 0xFFFFFFFF);
1196
0
                    matchCode -= 4*255;
1197
0
                }
1198
0
                op += matchCode / 255;
1199
0
                *op++ = (BYTE)(matchCode % 255);
1200
0
            } else
1201
0
                *token += (BYTE)(matchCode);
1202
0
        }
1203
        /* Ensure we have enough space for the last literals. */
1204
0
        assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit));
1205
1206
0
        anchor = ip;
1207
1208
        /* Test end of chunk */
1209
0
        if (ip >= mflimitPlusOne) break;
1210
1211
        /* Fill table */
1212
0
        LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
1213
1214
        /* Test next position */
1215
0
        if (tableType == byPtr) {
1216
1217
0
            match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
1218
0
            LZ4_putPosition(ip, cctx->hashTable, tableType, base);
1219
0
            if ( (match+LZ4_DISTANCE_MAX >= ip)
1220
0
              && (LZ4_read32(match) == LZ4_read32(ip)) )
1221
0
            { token=op++; *token=0; goto _next_match; }
1222
1223
0
        } else {   /* byU32, byU16 */
1224
1225
0
            U32 const h = LZ4_hashPosition(ip, tableType);
1226
0
            U32 const current = (U32)(ip-base);
1227
0
            U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
1228
0
            assert(matchIndex < current);
1229
0
            if (dictDirective == usingDictCtx) {
1230
0
                if (matchIndex < startIndex) {
1231
                    /* there was no match, try the dictionary */
1232
0
                    matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
1233
0
                    match = dictBase + matchIndex;
1234
0
                    lowLimit = dictionary;   /* required for match length counter */
1235
0
                    matchIndex += dictDelta;
1236
0
                } else {
1237
0
                    match = base + matchIndex;
1238
0
                    lowLimit = (const BYTE*)source;  /* required for match length counter */
1239
0
                }
1240
0
            } else if (dictDirective==usingExtDict) {
1241
0
                if (matchIndex < startIndex) {
1242
0
                    assert(dictBase);
1243
0
                    match = dictBase + matchIndex;
1244
0
                    lowLimit = dictionary;   /* required for match length counter */
1245
0
                } else {
1246
0
                    match = base + matchIndex;
1247
0
                    lowLimit = (const BYTE*)source;   /* required for match length counter */
1248
0
                }
1249
0
            } else {   /* single memory segment */
1250
0
                match = base + matchIndex;
1251
0
            }
1252
0
            LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
1253
0
            assert(matchIndex < current);
1254
0
            if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)
1255
0
              && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current))
1256
0
              && (LZ4_read32(match) == LZ4_read32(ip)) ) {
1257
0
                token=op++;
1258
0
                *token=0;
1259
0
                if (maybe_extMem) offset = current - matchIndex;
1260
0
                DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
1261
0
                            (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));
1262
0
                goto _next_match;
1263
0
            }
1264
0
        }
1265
1266
        /* Prepare next loop */
1267
0
        forwardH = LZ4_hashPosition(++ip, tableType);
1268
1269
0
    }
1270
1271
0
_last_literals:
1272
    /* Encode Last Literals */
1273
0
    {   size_t lastRun = (size_t)(iend - anchor);
1274
0
        if ( (outputDirective) &&  /* Check output buffer overflow */
1275
0
            (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {
1276
0
            if (outputDirective == fillOutput) {
1277
                /* adapt lastRun to fill 'dst' */
1278
0
                assert(olimit >= op);
1279
0
                lastRun  = (size_t)(olimit-op) - 1/*token*/;
1280
0
                lastRun -= (lastRun + 256 - RUN_MASK) / 256;  /*additional length tokens*/
1281
0
            } else {
1282
0
                assert(outputDirective == limitedOutput);
1283
0
                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1284
0
            }
1285
0
        }
1286
0
        DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun);
1287
0
        if (lastRun >= RUN_MASK) {
1288
0
            size_t accumulator = lastRun - RUN_MASK;
1289
0
            *op++ = RUN_MASK << ML_BITS;
1290
0
            for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
1291
0
            *op++ = (BYTE) accumulator;
1292
0
        } else {
1293
0
            *op++ = (BYTE)(lastRun<<ML_BITS);
1294
0
        }
1295
0
        LZ4_memcpy(op, anchor, lastRun);
1296
0
        ip = anchor + lastRun;
1297
0
        op += lastRun;
1298
0
    }
1299
1300
0
    if (outputDirective == fillOutput) {
1301
0
        *inputConsumed = (int) (((const char*)ip)-source);
1302
0
    }
1303
0
    result = (int)(((char*)op) - dest);
1304
0
    assert(result > 0);
1305
0
    DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result);
1306
0
    return result;
1307
0
}
1308
1309
/** LZ4_compress_generic() :
1310
 *  inlined, to ensure branches are decided at compilation time;
1311
 *  takes care of src == (NULL, 0)
1312
 *  and forward the rest to LZ4_compress_generic_validated */
1313
LZ4_FORCE_INLINE int LZ4_compress_generic(
1314
                 LZ4_stream_t_internal* const cctx,
1315
                 const char* const src,
1316
                 char* const dst,
1317
                 const int srcSize,
1318
                 int *inputConsumed, /* only written when outputDirective == fillOutput */
1319
                 const int dstCapacity,
1320
                 const limitedOutput_directive outputDirective,
1321
                 const tableType_t tableType,
1322
                 const dict_directive dictDirective,
1323
                 const dictIssue_directive dictIssue,
1324
                 const int acceleration)
1325
0
{
1326
0
    DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i",
1327
0
                srcSize, dstCapacity);
1328
1329
0
    if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; }  /* Unsupported srcSize, too large (or negative) */
1330
0
    if (srcSize == 0) {   /* src == NULL supported if srcSize == 0 */
1331
0
        if (outputDirective != notLimited && dstCapacity <= 0) return 0;  /* no output, can't write anything */
1332
0
        DEBUGLOG(5, "Generating an empty block");
1333
0
        assert(outputDirective == notLimited || dstCapacity >= 1);
1334
0
        assert(dst != NULL);
1335
0
        dst[0] = 0;
1336
0
        if (outputDirective == fillOutput) {
1337
0
            assert (inputConsumed != NULL);
1338
0
            *inputConsumed = 0;
1339
0
        }
1340
0
        return 1;
1341
0
    }
1342
0
    assert(src != NULL);
1343
1344
0
    return LZ4_compress_generic_validated(cctx, src, dst, srcSize,
1345
0
                inputConsumed, /* only written into if outputDirective == fillOutput */
1346
0
                dstCapacity, outputDirective,
1347
0
                tableType, dictDirective, dictIssue, acceleration);
1348
0
}
1349
1350
1351
int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
1352
0
{
1353
0
    LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse;
1354
0
    assert(ctx != NULL);
1355
0
    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
1356
0
    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
1357
0
    if (maxOutputSize >= LZ4_compressBound(inputSize)) {
1358
0
        if (inputSize < LZ4_64Klimit) {
1359
0
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
1360
0
        } else {
1361
0
            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1362
0
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
1363
0
        }
1364
0
    } else {
1365
0
        if (inputSize < LZ4_64Klimit) {
1366
0
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
1367
0
        } else {
1368
0
            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1369
0
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
1370
0
        }
1371
0
    }
1372
0
}
1373
1374
/**
1375
 * LZ4_compress_fast_extState_fastReset() :
1376
 * A variant of LZ4_compress_fast_extState().
1377
 *
1378
 * Using this variant avoids an expensive initialization step. It is only safe
1379
 * to call if the state buffer is known to be correctly initialized already
1380
 * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of
1381
 * "correctly initialized").
1382
 */
1383
int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
1384
0
{
1385
0
    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
1386
0
    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
1387
0
    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
1388
1389
0
    if (dstCapacity >= LZ4_compressBound(srcSize)) {
1390
0
        if (srcSize < LZ4_64Klimit) {
1391
0
            const tableType_t tableType = byU16;
1392
0
            LZ4_prepareTable(ctx, srcSize, tableType);
1393
0
            if (ctx->currentOffset) {
1394
0
                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
1395
0
            } else {
1396
0
                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
1397
0
            }
1398
0
        } else {
1399
0
            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1400
0
            LZ4_prepareTable(ctx, srcSize, tableType);
1401
0
            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
1402
0
        }
1403
0
    } else {
1404
0
        if (srcSize < LZ4_64Klimit) {
1405
0
            const tableType_t tableType = byU16;
1406
0
            LZ4_prepareTable(ctx, srcSize, tableType);
1407
0
            if (ctx->currentOffset) {
1408
0
                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
1409
0
            } else {
1410
0
                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
1411
0
            }
1412
0
        } else {
1413
0
            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1414
0
            LZ4_prepareTable(ctx, srcSize, tableType);
1415
0
            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
1416
0
        }
1417
0
    }
1418
0
}
1419
1420
1421
int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
1422
0
{
1423
0
    int result;
1424
#if (LZ4_HEAPMODE)
1425
    LZ4_stream_t* ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
1426
    if (ctxPtr == NULL) return 0;
1427
#else
1428
0
    LZ4_stream_t ctx;
1429
0
    LZ4_stream_t* const ctxPtr = &ctx;
1430
0
#endif
1431
0
    result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
1432
1433
#if (LZ4_HEAPMODE)
1434
    FREEMEM(ctxPtr);
1435
#endif
1436
0
    return result;
1437
0
}
1438
1439
1440
int LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize)
1441
0
{
1442
0
    return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);
1443
0
}
1444
1445
1446
/* Note!: This function leaves the stream in an unclean/broken state!
1447
 * It is not safe to subsequently use the same state with a _fastReset() or
1448
 * _continue() call without resetting it. */
1449
static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
1450
0
{
1451
0
    void* const s = LZ4_initStream(state, sizeof (*state));
1452
0
    assert(s != NULL); (void)s;
1453
1454
0
    if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */
1455
0
        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
1456
0
    } else {
1457
0
        if (*srcSizePtr < LZ4_64Klimit) {
1458
0
            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
1459
0
        } else {
1460
0
            tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1461
0
            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
1462
0
    }   }
1463
0
}
1464
1465
1466
int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
1467
0
{
1468
#if (LZ4_HEAPMODE)
1469
    LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
1470
    if (ctx == NULL) return 0;
1471
#else
1472
0
    LZ4_stream_t ctxBody;
1473
0
    LZ4_stream_t* ctx = &ctxBody;
1474
0
#endif
1475
1476
0
    int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
1477
1478
#if (LZ4_HEAPMODE)
1479
    FREEMEM(ctx);
1480
#endif
1481
0
    return result;
1482
0
}
1483
1484
1485
1486
/*-******************************
1487
*  Streaming functions
1488
********************************/
1489
1490
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
1491
LZ4_stream_t* LZ4_createStream(void)
1492
0
{
1493
0
    LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));
1494
0
    LZ4_STATIC_ASSERT(sizeof(LZ4_stream_t) >= sizeof(LZ4_stream_t_internal));
1495
0
    DEBUGLOG(4, "LZ4_createStream %p", lz4s);
1496
0
    if (lz4s == NULL) return NULL;
1497
0
    LZ4_initStream(lz4s, sizeof(*lz4s));
1498
0
    return lz4s;
1499
0
}
1500
#endif
1501
1502
static size_t LZ4_stream_t_alignment(void)
1503
0
{
1504
0
#if LZ4_ALIGN_TEST
1505
0
    typedef struct { char c; LZ4_stream_t t; } t_a;
1506
0
    return sizeof(t_a) - sizeof(LZ4_stream_t);
1507
#else
1508
    return 1;  /* effectively disabled */
1509
#endif
1510
0
}
1511
1512
LZ4_stream_t* LZ4_initStream (void* buffer, size_t size)
1513
0
{
1514
0
    DEBUGLOG(5, "LZ4_initStream");
1515
0
    if (buffer == NULL) { return NULL; }
1516
0
    if (size < sizeof(LZ4_stream_t)) { return NULL; }
1517
0
    if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL;
1518
0
    MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal));
1519
0
    return (LZ4_stream_t*)buffer;
1520
0
}
1521
1522
/* resetStream is now deprecated,
1523
 * prefer initStream() which is more general */
1524
void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
1525
0
{
1526
0
    DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream);
1527
0
    MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal));
1528
0
}
1529
1530
0
void LZ4_resetStream_fast(LZ4_stream_t* ctx) {
1531
0
    LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);
1532
0
}
1533
1534
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
1535
int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
1536
0
{
1537
0
    if (!LZ4_stream) return 0;   /* support free on NULL */
1538
0
    DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream);
1539
0
    FREEMEM(LZ4_stream);
1540
0
    return (0);
1541
0
}
1542
#endif
1543
1544
1545
0
#define HASH_UNIT sizeof(reg_t)
1546
int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
1547
0
{
1548
0
    LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
1549
0
    const tableType_t tableType = byU32;
1550
0
    const BYTE* p = (const BYTE*)dictionary;
1551
0
    const BYTE* const dictEnd = p + dictSize;
1552
0
    const BYTE* base;
1553
1554
0
    DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
1555
1556
    /* It's necessary to reset the context,
1557
     * and not just continue it with prepareTable()
1558
     * to avoid any risk of generating overflowing matchIndex
1559
     * when compressing using this dictionary */
1560
0
    LZ4_resetStream(LZ4_dict);
1561
1562
    /* We always increment the offset by 64 KB, since, if the dict is longer,
1563
     * we truncate it to the last 64k, and if it's shorter, we still want to
1564
     * advance by a whole window length so we can provide the guarantee that
1565
     * there are only valid offsets in the window, which allows an optimization
1566
     * in LZ4_compress_fast_continue() where it uses noDictIssue even when the
1567
     * dictionary isn't a full 64k. */
1568
0
    dict->currentOffset += 64 KB;
1569
1570
0
    if (dictSize < (int)HASH_UNIT) {
1571
0
        return 0;
1572
0
    }
1573
1574
0
    if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
1575
0
    base = dictEnd - dict->currentOffset;
1576
0
    dict->dictionary = p;
1577
0
    dict->dictSize = (U32)(dictEnd - p);
1578
0
    dict->tableType = (U32)tableType;
1579
1580
0
    while (p <= dictEnd-HASH_UNIT) {
1581
0
        LZ4_putPosition(p, dict->hashTable, tableType, base);
1582
0
        p+=3;
1583
0
    }
1584
1585
0
    return (int)dict->dictSize;
1586
0
}
1587
1588
void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream)
1589
0
{
1590
0
    const LZ4_stream_t_internal* dictCtx = (dictionaryStream == NULL) ? NULL :
1591
0
        &(dictionaryStream->internal_donotuse);
1592
1593
0
    DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)",
1594
0
             workingStream, dictionaryStream,
1595
0
             dictCtx != NULL ? dictCtx->dictSize : 0);
1596
1597
0
    if (dictCtx != NULL) {
1598
        /* If the current offset is zero, we will never look in the
1599
         * external dictionary context, since there is no value a table
1600
         * entry can take that indicate a miss. In that case, we need
1601
         * to bump the offset to something non-zero.
1602
         */
1603
0
        if (workingStream->internal_donotuse.currentOffset == 0) {
1604
0
            workingStream->internal_donotuse.currentOffset = 64 KB;
1605
0
        }
1606
1607
        /* Don't actually attach an empty dictionary.
1608
         */
1609
0
        if (dictCtx->dictSize == 0) {
1610
0
            dictCtx = NULL;
1611
0
        }
1612
0
    }
1613
0
    workingStream->internal_donotuse.dictCtx = dictCtx;
1614
0
}
1615
1616
1617
static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize)
1618
0
{
1619
0
    assert(nextSize >= 0);
1620
0
    if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) {   /* potential ptrdiff_t overflow (32-bits mode) */
1621
        /* rescale hash table */
1622
0
        U32 const delta = LZ4_dict->currentOffset - 64 KB;
1623
0
        const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
1624
0
        int i;
1625
0
        DEBUGLOG(4, "LZ4_renormDictT");
1626
0
        for (i=0; i<LZ4_HASH_SIZE_U32; i++) {
1627
0
            if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;
1628
0
            else LZ4_dict->hashTable[i] -= delta;
1629
0
        }
1630
0
        LZ4_dict->currentOffset = 64 KB;
1631
0
        if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
1632
0
        LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
1633
0
    }
1634
0
}
1635
1636
1637
int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream,
1638
                                const char* source, char* dest,
1639
                                int inputSize, int maxOutputSize,
1640
                                int acceleration)
1641
0
{
1642
0
    const tableType_t tableType = byU32;
1643
0
    LZ4_stream_t_internal* const streamPtr = &LZ4_stream->internal_donotuse;
1644
0
    const char* dictEnd = streamPtr->dictSize ? (const char*)streamPtr->dictionary + streamPtr->dictSize : NULL;
1645
1646
0
    DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i, dictSize=%u)", inputSize, streamPtr->dictSize);
1647
1648
0
    LZ4_renormDictT(streamPtr, inputSize);   /* fix index overflow */
1649
0
    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
1650
0
    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
1651
1652
    /* invalidate tiny dictionaries */
1653
0
    if ( (streamPtr->dictSize < 4)     /* tiny dictionary : not enough for a hash */
1654
0
      && (dictEnd != source)           /* prefix mode */
1655
0
      && (inputSize > 0)               /* tolerance : don't lose history, in case next invocation would use prefix mode */
1656
0
      && (streamPtr->dictCtx == NULL)  /* usingDictCtx */
1657
0
      ) {
1658
0
        DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary);
1659
        /* remove dictionary existence from history, to employ faster prefix mode */
1660
0
        streamPtr->dictSize = 0;
1661
0
        streamPtr->dictionary = (const BYTE*)source;
1662
0
        dictEnd = source;
1663
0
    }
1664
1665
    /* Check overlapping input/dictionary space */
1666
0
    {   const char* const sourceEnd = source + inputSize;
1667
0
        if ((sourceEnd > (const char*)streamPtr->dictionary) && (sourceEnd < dictEnd)) {
1668
0
            streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
1669
0
            if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
1670
0
            if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
1671
0
            streamPtr->dictionary = (const BYTE*)dictEnd - streamPtr->dictSize;
1672
0
        }
1673
0
    }
1674
1675
    /* prefix mode : source data follows dictionary */
1676
0
    if (dictEnd == source) {
1677
0
        if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
1678
0
            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);
1679
0
        else
1680
0
            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);
1681
0
    }
1682
1683
    /* external dictionary mode */
1684
0
    {   int result;
1685
0
        if (streamPtr->dictCtx) {
1686
            /* We depend here on the fact that dictCtx'es (produced by
1687
             * LZ4_loadDict) guarantee that their tables contain no references
1688
             * to offsets between dictCtx->currentOffset - 64 KB and
1689
             * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe
1690
             * to use noDictIssue even when the dict isn't a full 64 KB.
1691
             */
1692
0
            if (inputSize > 4 KB) {
1693
                /* For compressing large blobs, it is faster to pay the setup
1694
                 * cost to copy the dictionary's tables into the active context,
1695
                 * so that the compression loop is only looking into one table.
1696
                 */
1697
0
                LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr));
1698
0
                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
1699
0
            } else {
1700
0
                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
1701
0
            }
1702
0
        } else {  /* small data <= 4 KB */
1703
0
            if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
1704
0
                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
1705
0
            } else {
1706
0
                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
1707
0
            }
1708
0
        }
1709
0
        streamPtr->dictionary = (const BYTE*)source;
1710
0
        streamPtr->dictSize = (U32)inputSize;
1711
0
        return result;
1712
0
    }
1713
0
}
1714
1715
1716
/* Hidden debug function, to force-test external dictionary mode */
1717
int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
1718
0
{
1719
0
    LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
1720
0
    int result;
1721
1722
0
    LZ4_renormDictT(streamPtr, srcSize);
1723
1724
0
    if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
1725
0
        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
1726
0
    } else {
1727
0
        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
1728
0
    }
1729
1730
0
    streamPtr->dictionary = (const BYTE*)source;
1731
0
    streamPtr->dictSize = (U32)srcSize;
1732
1733
0
    return result;
1734
0
}
1735
1736
1737
/*! LZ4_saveDict() :
1738
 *  If previously compressed data block is not guaranteed to remain available at its memory location,
1739
 *  save it into a safer place (char* safeBuffer).
1740
 *  Note : no need to call LZ4_loadDict() afterwards, dictionary is immediately usable,
1741
 *         one can therefore call LZ4_compress_fast_continue() right after.
1742
 * @return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
1743
 */
1744
int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
1745
0
{
1746
0
    LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
1747
1748
0
    DEBUGLOG(5, "LZ4_saveDict : dictSize=%i, safeBuffer=%p", dictSize, safeBuffer);
1749
1750
0
    if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */
1751
0
    if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; }
1752
1753
0
    if (safeBuffer == NULL) assert(dictSize == 0);
1754
0
    if (dictSize > 0) {
1755
0
        const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;
1756
0
        assert(dict->dictionary);
1757
0
        LZ4_memmove(safeBuffer, previousDictEnd - dictSize, (size_t)dictSize);
1758
0
    }
1759
1760
0
    dict->dictionary = (const BYTE*)safeBuffer;
1761
0
    dict->dictSize = (U32)dictSize;
1762
1763
0
    return dictSize;
1764
0
}
1765
1766
1767
1768
/*-*******************************
1769
 *  Decompression functions
1770
 ********************************/
1771
1772
typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
1773
1774
#undef MIN
1775
0
#define MIN(a,b)    ( (a) < (b) ? (a) : (b) )
1776
1777
1778
/* variant for decompress_unsafe()
1779
 * does not know end of input
1780
 * presumes input is well formed
1781
 * note : will consume at least one byte */
1782
size_t read_long_length_no_check(const BYTE** pp)
1783
0
{
1784
0
    size_t b, l = 0;
1785
0
    do { b = **pp; (*pp)++; l += b; } while (b==255);
1786
0
    DEBUGLOG(6, "read_long_length_no_check: +length=%zu using %zu input bytes", l, l/255 + 1)
1787
0
    return l;
1788
0
}
1789
1790
/* core decoder variant for LZ4_decompress_fast*()
1791
 * for legacy support only : these entry points are deprecated.
1792
 * - Presumes input is correctly formed (no defense vs malformed inputs)
1793
 * - Does not know input size (presume input buffer is "large enough")
1794
 * - Decompress a full block (only)
1795
 * @return : nb of bytes read from input.
1796
 * Note : this variant is not optimized for speed, just for maintenance.
1797
 *        the goal is to remove support of decompress_fast*() variants by v2.0
1798
**/
1799
LZ4_FORCE_INLINE int
1800
LZ4_decompress_unsafe_generic(
1801
                 const BYTE* const istart,
1802
                 BYTE* const ostart,
1803
                 int decompressedSize,
1804
1805
                 size_t prefixSize,
1806
                 const BYTE* const dictStart,  /* only if dict==usingExtDict */
1807
                 const size_t dictSize         /* note: =0 if dictStart==NULL */
1808
                 )
1809
0
{
1810
0
    const BYTE* ip = istart;
1811
0
    BYTE* op = (BYTE*)ostart;
1812
0
    BYTE* const oend = ostart + decompressedSize;
1813
0
    const BYTE* const prefixStart = ostart - prefixSize;
1814
1815
0
    DEBUGLOG(5, "LZ4_decompress_unsafe_generic");
1816
0
    if (dictStart == NULL) assert(dictSize == 0);
1817
1818
0
    while (1) {
1819
        /* start new sequence */
1820
0
        unsigned token = *ip++;
1821
1822
        /* literals */
1823
0
        {   size_t ll = token >> ML_BITS;
1824
0
            if (ll==15) {
1825
                /* long literal length */
1826
0
                ll += read_long_length_no_check(&ip);
1827
0
            }
1828
0
            if ((size_t)(oend-op) < ll) return -1; /* output buffer overflow */
1829
0
            LZ4_memmove(op, ip, ll); /* support in-place decompression */
1830
0
            op += ll;
1831
0
            ip += ll;
1832
0
            if ((size_t)(oend-op) < MFLIMIT) {
1833
0
                if (op==oend) break;  /* end of block */
1834
0
                DEBUGLOG(5, "invalid: literals end at distance %zi from end of block", oend-op);
1835
                /* incorrect end of block :
1836
                 * last match must start at least MFLIMIT==12 bytes before end of output block */
1837
0
                return -1;
1838
0
        }   }
1839
1840
        /* match */
1841
0
        {   size_t ml = token & 15;
1842
0
            size_t const offset = LZ4_readLE16(ip);
1843
0
            ip+=2;
1844
1845
0
            if (ml==15) {
1846
                /* long literal length */
1847
0
                ml += read_long_length_no_check(&ip);
1848
0
            }
1849
0
            ml += MINMATCH;
1850
1851
0
            if ((size_t)(oend-op) < ml) return -1; /* output buffer overflow */
1852
1853
0
            {   const BYTE* match = op - offset;
1854
1855
                /* out of range */
1856
0
                if (offset > (size_t)(op - prefixStart) + dictSize) {
1857
0
                    DEBUGLOG(6, "offset out of range");
1858
0
                    return -1;
1859
0
                }
1860
1861
                /* check special case : extDict */
1862
0
                if (offset > (size_t)(op - prefixStart)) {
1863
                    /* extDict scenario */
1864
0
                    const BYTE* const dictEnd = dictStart + dictSize;
1865
0
                    const BYTE* extMatch = dictEnd - (offset - (size_t)(op-prefixStart));
1866
0
                    size_t const extml = (size_t)(dictEnd - extMatch);
1867
0
                    if (extml > ml) {
1868
                        /* match entirely within extDict */
1869
0
                        LZ4_memmove(op, extMatch, ml);
1870
0
                        op += ml;
1871
0
                        ml = 0;
1872
0
                    } else {
1873
                        /* match split between extDict & prefix */
1874
0
                        LZ4_memmove(op, extMatch, extml);
1875
0
                        op += extml;
1876
0
                        ml -= extml;
1877
0
                    }
1878
0
                    match = prefixStart;
1879
0
                }
1880
1881
                /* match copy - slow variant, supporting overlap copy */
1882
0
                {   size_t u;
1883
0
                    for (u=0; u<ml; u++) {
1884
0
                        op[u] = match[u];
1885
0
            }   }   }
1886
0
            op += ml;
1887
0
            if ((size_t)(oend-op) < LASTLITERALS) {
1888
0
                DEBUGLOG(5, "invalid: match ends at distance %zi from end of block", oend-op);
1889
                /* incorrect end of block :
1890
                 * last match must stop at least LASTLITERALS==5 bytes before end of output block */
1891
0
                return -1;
1892
0
            }
1893
0
        } /* match */
1894
0
    } /* main loop */
1895
0
    return (int)(ip - istart);
1896
0
}
1897
1898
1899
/* Read the variable-length literal or match length.
1900
 *
1901
 * @ip : input pointer
1902
 * @ilimit : position after which if length is not decoded, the input is necessarily corrupted.
1903
 * @initial_check - check ip >= ipmax before start of loop.  Returns initial_error if so.
1904
 * @error (output) - error code.  Must be set to 0 before call.
1905
**/
1906
typedef size_t Rvl_t;
1907
static const Rvl_t rvl_error = (Rvl_t)(-1);
1908
LZ4_FORCE_INLINE Rvl_t
1909
read_variable_length(const BYTE** ip, const BYTE* ilimit,
1910
                     int initial_check)
1911
0
{
1912
0
    Rvl_t s, length = 0;
1913
0
    assert(ip != NULL);
1914
0
    assert(*ip !=  NULL);
1915
0
    assert(ilimit != NULL);
1916
0
    if (initial_check && unlikely((*ip) >= ilimit)) {    /* read limit reached */
1917
0
        return rvl_error;
1918
0
    }
1919
0
    do {
1920
0
        s = **ip;
1921
0
        (*ip)++;
1922
0
        length += s;
1923
0
        if (unlikely((*ip) > ilimit)) {    /* read limit reached */
1924
0
            return rvl_error;
1925
0
        }
1926
        /* accumulator overflow detection (32-bit mode only) */
1927
0
        if ((sizeof(length)<8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
1928
0
            return rvl_error;
1929
0
        }
1930
0
    } while (s==255);
1931
1932
0
    return length;
1933
0
}
1934
1935
/*! LZ4_decompress_generic() :
1936
 *  This generic decompression function covers all use cases.
1937
 *  It shall be instantiated several times, using different sets of directives.
1938
 *  Note that it is important for performance that this function really get inlined,
1939
 *  in order to remove useless branches during compilation optimization.
1940
 */
1941
LZ4_FORCE_INLINE int
1942
LZ4_decompress_generic(
1943
                 const char* const src,
1944
                 char* const dst,
1945
                 int srcSize,
1946
                 int outputSize,         /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
1947
1948
                 earlyEnd_directive partialDecoding,  /* full, partial */
1949
                 dict_directive dict,                 /* noDict, withPrefix64k, usingExtDict */
1950
                 const BYTE* const lowPrefix,  /* always <= dst, == dst when no prefix */
1951
                 const BYTE* const dictStart,  /* only if dict==usingExtDict */
1952
                 const size_t dictSize         /* note : = 0 if noDict */
1953
                 )
1954
0
{
1955
0
    if ((src == NULL) || (outputSize < 0)) { return -1; }
1956
1957
0
    {   const BYTE* ip = (const BYTE*) src;
1958
0
        const BYTE* const iend = ip + srcSize;
1959
1960
0
        BYTE* op = (BYTE*) dst;
1961
0
        BYTE* const oend = op + outputSize;
1962
0
        BYTE* cpy;
1963
1964
0
        const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;
1965
1966
0
        const int checkOffset = (dictSize < (int)(64 KB));
1967
1968
1969
        /* Set up the "end" pointers for the shortcut. */
1970
0
        const BYTE* const shortiend = iend - 14 /*maxLL*/ - 2 /*offset*/;
1971
0
        const BYTE* const shortoend = oend - 14 /*maxLL*/ - 18 /*maxML*/;
1972
1973
0
        const BYTE* match;
1974
0
        size_t offset;
1975
0
        unsigned token;
1976
0
        size_t length;
1977
1978
1979
0
        DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
1980
1981
        /* Special cases */
1982
0
        assert(lowPrefix <= op);
1983
0
        if (unlikely(outputSize==0)) {
1984
            /* Empty output buffer */
1985
0
            if (partialDecoding) return 0;
1986
0
            return ((srcSize==1) && (*ip==0)) ? 0 : -1;
1987
0
        }
1988
0
        if (unlikely(srcSize==0)) { return -1; }
1989
1990
    /* LZ4_FAST_DEC_LOOP:
1991
     * designed for modern OoO performance cpus,
1992
     * where copying reliably 32-bytes is preferable to an unpredictable branch.
1993
     * note : fast loop may show a regression for some client arm chips. */
1994
0
#if LZ4_FAST_DEC_LOOP
1995
0
        if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {
1996
0
            DEBUGLOG(6, "skip fast decode loop");
1997
0
            goto safe_decode;
1998
0
        }
1999
2000
        /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */
2001
0
        while (1) {
2002
            /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
2003
0
            assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
2004
0
            assert(ip < iend);
2005
0
            token = *ip++;
2006
0
            length = token >> ML_BITS;  /* literal length */
2007
2008
            /* decode literal length */
2009
0
            if (length == RUN_MASK) {
2010
0
                size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1);
2011
0
                if (addl == rvl_error) { goto _output_error; }
2012
0
                length += addl;
2013
0
                if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
2014
0
                if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
2015
2016
                /* copy literals */
2017
0
                cpy = op+length;
2018
0
                LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
2019
0
                if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
2020
0
                LZ4_wildCopy32(op, ip, cpy);
2021
0
                ip += length; op = cpy;
2022
0
            } else {
2023
0
                cpy = op+length;
2024
0
                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
2025
                /* We don't need to check oend, since we check it once for each loop below */
2026
0
                if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }
2027
                /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */
2028
0
                LZ4_memcpy(op, ip, 16);
2029
0
                ip += length; op = cpy;
2030
0
            }
2031
2032
            /* get offset */
2033
0
            offset = LZ4_readLE16(ip); ip+=2;
2034
0
            match = op - offset;
2035
0
            assert(match <= op);  /* overflow check */
2036
2037
            /* get matchlength */
2038
0
            length = token & ML_MASK;
2039
2040
0
            if (length == ML_MASK) {
2041
0
                size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
2042
0
                if (addl == rvl_error) { goto _output_error; }
2043
0
                length += addl;
2044
0
                length += MINMATCH;
2045
0
                if (unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */
2046
0
                if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
2047
0
                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
2048
0
                    goto safe_match_copy;
2049
0
                }
2050
0
            } else {
2051
0
                length += MINMATCH;
2052
0
                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
2053
0
                    goto safe_match_copy;
2054
0
                }
2055
2056
                /* Fastpath check: skip LZ4_wildCopy32 when true */
2057
0
                if ((dict == withPrefix64k) || (match >= lowPrefix)) {
2058
0
                    if (offset >= 8) {
2059
0
                        assert(match >= lowPrefix);
2060
0
                        assert(match <= op);
2061
0
                        assert(op + 18 <= oend);
2062
2063
0
                        LZ4_memcpy(op, match, 8);
2064
0
                        LZ4_memcpy(op+8, match+8, 8);
2065
0
                        LZ4_memcpy(op+16, match+16, 2);
2066
0
                        op += length;
2067
0
                        continue;
2068
0
            }   }   }
2069
2070
0
            if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
2071
            /* match starting within external dictionary */
2072
0
            if ((dict==usingExtDict) && (match < lowPrefix)) {
2073
0
                assert(dictEnd != NULL);
2074
0
                if (unlikely(op+length > oend-LASTLITERALS)) {
2075
0
                    if (partialDecoding) {
2076
0
                        DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
2077
0
                        length = MIN(length, (size_t)(oend-op));
2078
0
                    } else {
2079
0
                        goto _output_error;  /* end-of-block condition violated */
2080
0
                }   }
2081
2082
0
                if (length <= (size_t)(lowPrefix-match)) {
2083
                    /* match fits entirely within external dictionary : just copy */
2084
0
                    LZ4_memmove(op, dictEnd - (lowPrefix-match), length);
2085
0
                    op += length;
2086
0
                } else {
2087
                    /* match stretches into both external dictionary and current block */
2088
0
                    size_t const copySize = (size_t)(lowPrefix - match);
2089
0
                    size_t const restSize = length - copySize;
2090
0
                    LZ4_memcpy(op, dictEnd - copySize, copySize);
2091
0
                    op += copySize;
2092
0
                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */
2093
0
                        BYTE* const endOfMatch = op + restSize;
2094
0
                        const BYTE* copyFrom = lowPrefix;
2095
0
                        while (op < endOfMatch) { *op++ = *copyFrom++; }
2096
0
                    } else {
2097
0
                        LZ4_memcpy(op, lowPrefix, restSize);
2098
0
                        op += restSize;
2099
0
                }   }
2100
0
                continue;
2101
0
            }
2102
2103
            /* copy match within block */
2104
0
            cpy = op + length;
2105
2106
0
            assert((op <= oend) && (oend-op >= 32));
2107
0
            if (unlikely(offset<16)) {
2108
0
                LZ4_memcpy_using_offset(op, match, cpy, offset);
2109
0
            } else {
2110
0
                LZ4_wildCopy32(op, match, cpy);
2111
0
            }
2112
2113
0
            op = cpy;   /* wildcopy correction */
2114
0
        }
2115
0
    safe_decode:
2116
0
#endif
2117
2118
        /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
2119
0
        while (1) {
2120
0
            assert(ip < iend);
2121
0
            token = *ip++;
2122
0
            length = token >> ML_BITS;  /* literal length */
2123
2124
            /* A two-stage shortcut for the most common case:
2125
             * 1) If the literal length is 0..14, and there is enough space,
2126
             * enter the shortcut and copy 16 bytes on behalf of the literals
2127
             * (in the fast mode, only 8 bytes can be safely copied this way).
2128
             * 2) Further if the match length is 4..18, copy 18 bytes in a similar
2129
             * manner; but we ensure that there's enough space in the output for
2130
             * those 18 bytes earlier, upon entering the shortcut (in other words,
2131
             * there is a combined check for both stages).
2132
             */
2133
0
            if ( (length != RUN_MASK)
2134
                /* strictly "less than" on input, to re-enter the loop with at least one byte */
2135
0
              && likely((ip < shortiend) & (op <= shortoend)) ) {
2136
                /* Copy the literals */
2137
0
                LZ4_memcpy(op, ip, 16);
2138
0
                op += length; ip += length;
2139
2140
                /* The second stage: prepare for match copying, decode full info.
2141
                 * If it doesn't work out, the info won't be wasted. */
2142
0
                length = token & ML_MASK; /* match length */
2143
0
                offset = LZ4_readLE16(ip); ip += 2;
2144
0
                match = op - offset;
2145
0
                assert(match <= op); /* check overflow */
2146
2147
                /* Do not deal with overlapping matches. */
2148
0
                if ( (length != ML_MASK)
2149
0
                  && (offset >= 8)
2150
0
                  && (dict==withPrefix64k || match >= lowPrefix) ) {
2151
                    /* Copy the match. */
2152
0
                    LZ4_memcpy(op + 0, match + 0, 8);
2153
0
                    LZ4_memcpy(op + 8, match + 8, 8);
2154
0
                    LZ4_memcpy(op +16, match +16, 2);
2155
0
                    op += length + MINMATCH;
2156
                    /* Both stages worked, load the next token. */
2157
0
                    continue;
2158
0
                }
2159
2160
                /* The second stage didn't work out, but the info is ready.
2161
                 * Propel it right to the point of match copying. */
2162
0
                goto _copy_match;
2163
0
            }
2164
2165
            /* decode literal length */
2166
0
            if (length == RUN_MASK) {
2167
0
                size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1);
2168
0
                if (addl == rvl_error) { goto _output_error; }
2169
0
                length += addl;
2170
0
                if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
2171
0
                if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
2172
0
            }
2173
2174
            /* copy literals */
2175
0
            cpy = op+length;
2176
0
#if LZ4_FAST_DEC_LOOP
2177
0
        safe_literal_copy:
2178
0
#endif
2179
0
            LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
2180
0
            if ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) {
2181
                /* We've either hit the input parsing restriction or the output parsing restriction.
2182
                 * In the normal scenario, decoding a full block, it must be the last sequence,
2183
                 * otherwise it's an error (invalid input or dimensions).
2184
                 * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow.
2185
                 */
2186
0
                if (partialDecoding) {
2187
                    /* Since we are partial decoding we may be in this block because of the output parsing
2188
                     * restriction, which is not valid since the output buffer is allowed to be undersized.
2189
                     */
2190
0
                    DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end")
2191
0
                    DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length);
2192
0
                    DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op));
2193
0
                    DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip));
2194
                    /* Finishing in the middle of a literals segment,
2195
                     * due to lack of input.
2196
                     */
2197
0
                    if (ip+length > iend) {
2198
0
                        length = (size_t)(iend-ip);
2199
0
                        cpy = op + length;
2200
0
                    }
2201
                    /* Finishing in the middle of a literals segment,
2202
                     * due to lack of output space.
2203
                     */
2204
0
                    if (cpy > oend) {
2205
0
                        cpy = oend;
2206
0
                        assert(op<=oend);
2207
0
                        length = (size_t)(oend-op);
2208
0
                    }
2209
0
                } else {
2210
                     /* We must be on the last sequence (or invalid) because of the parsing limitations
2211
                      * so check that we exactly consume the input and don't overrun the output buffer.
2212
                      */
2213
0
                    if ((ip+length != iend) || (cpy > oend)) {
2214
0
                        DEBUGLOG(6, "should have been last run of literals")
2215
0
                        DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);
2216
0
                        DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend);
2217
0
                        goto _output_error;
2218
0
                    }
2219
0
                }
2220
0
                LZ4_memmove(op, ip, length);  /* supports overlapping memory regions, for in-place decompression scenarios */
2221
0
                ip += length;
2222
0
                op += length;
2223
                /* Necessarily EOF when !partialDecoding.
2224
                 * When partialDecoding, it is EOF if we've either
2225
                 * filled the output buffer or
2226
                 * can't proceed with reading an offset for following match.
2227
                 */
2228
0
                if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) {
2229
0
                    break;
2230
0
                }
2231
0
            } else {
2232
0
                LZ4_wildCopy8(op, ip, cpy);   /* can overwrite up to 8 bytes beyond cpy */
2233
0
                ip += length; op = cpy;
2234
0
            }
2235
2236
            /* get offset */
2237
0
            offset = LZ4_readLE16(ip); ip+=2;
2238
0
            match = op - offset;
2239
2240
            /* get matchlength */
2241
0
            length = token & ML_MASK;
2242
2243
0
    _copy_match:
2244
0
            if (length == ML_MASK) {
2245
0
                size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
2246
0
                if (addl == rvl_error) { goto _output_error; }
2247
0
                length += addl;
2248
0
                if (unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error;   /* overflow detection */
2249
0
            }
2250
0
            length += MINMATCH;
2251
2252
0
#if LZ4_FAST_DEC_LOOP
2253
0
        safe_match_copy:
2254
0
#endif
2255
0
            if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error;   /* Error : offset outside buffers */
2256
            /* match starting within external dictionary */
2257
0
            if ((dict==usingExtDict) && (match < lowPrefix)) {
2258
0
                assert(dictEnd != NULL);
2259
0
                if (unlikely(op+length > oend-LASTLITERALS)) {
2260
0
                    if (partialDecoding) length = MIN(length, (size_t)(oend-op));
2261
0
                    else goto _output_error;   /* doesn't respect parsing restriction */
2262
0
                }
2263
2264
0
                if (length <= (size_t)(lowPrefix-match)) {
2265
                    /* match fits entirely within external dictionary : just copy */
2266
0
                    LZ4_memmove(op, dictEnd - (lowPrefix-match), length);
2267
0
                    op += length;
2268
0
                } else {
2269
                    /* match stretches into both external dictionary and current block */
2270
0
                    size_t const copySize = (size_t)(lowPrefix - match);
2271
0
                    size_t const restSize = length - copySize;
2272
0
                    LZ4_memcpy(op, dictEnd - copySize, copySize);
2273
0
                    op += copySize;
2274
0
                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */
2275
0
                        BYTE* const endOfMatch = op + restSize;
2276
0
                        const BYTE* copyFrom = lowPrefix;
2277
0
                        while (op < endOfMatch) *op++ = *copyFrom++;
2278
0
                    } else {
2279
0
                        LZ4_memcpy(op, lowPrefix, restSize);
2280
0
                        op += restSize;
2281
0
                }   }
2282
0
                continue;
2283
0
            }
2284
0
            assert(match >= lowPrefix);
2285
2286
            /* copy match within block */
2287
0
            cpy = op + length;
2288
2289
            /* partialDecoding : may end anywhere within the block */
2290
0
            assert(op<=oend);
2291
0
            if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
2292
0
                size_t const mlen = MIN(length, (size_t)(oend-op));
2293
0
                const BYTE* const matchEnd = match + mlen;
2294
0
                BYTE* const copyEnd = op + mlen;
2295
0
                if (matchEnd > op) {   /* overlap copy */
2296
0
                    while (op < copyEnd) { *op++ = *match++; }
2297
0
                } else {
2298
0
                    LZ4_memcpy(op, match, mlen);
2299
0
                }
2300
0
                op = copyEnd;
2301
0
                if (op == oend) { break; }
2302
0
                continue;
2303
0
            }
2304
2305
0
            if (unlikely(offset<8)) {
2306
0
                LZ4_write32(op, 0);   /* silence msan warning when offset==0 */
2307
0
                op[0] = match[0];
2308
0
                op[1] = match[1];
2309
0
                op[2] = match[2];
2310
0
                op[3] = match[3];
2311
0
                match += inc32table[offset];
2312
0
                LZ4_memcpy(op+4, match, 4);
2313
0
                match -= dec64table[offset];
2314
0
            } else {
2315
0
                LZ4_memcpy(op, match, 8);
2316
0
                match += 8;
2317
0
            }
2318
0
            op += 8;
2319
2320
0
            if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
2321
0
                BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
2322
0
                if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
2323
0
                if (op < oCopyLimit) {
2324
0
                    LZ4_wildCopy8(op, match, oCopyLimit);
2325
0
                    match += oCopyLimit - op;
2326
0
                    op = oCopyLimit;
2327
0
                }
2328
0
                while (op < cpy) { *op++ = *match++; }
2329
0
            } else {
2330
0
                LZ4_memcpy(op, match, 8);
2331
0
                if (length > 16)  { LZ4_wildCopy8(op+8, match+8, cpy); }
2332
0
            }
2333
0
            op = cpy;   /* wildcopy correction */
2334
0
        }
2335
2336
        /* end of decoding */
2337
0
        DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst));
2338
0
        return (int) (((char*)op)-dst);     /* Nb of output bytes decoded */
2339
2340
        /* Overflow error detected */
2341
0
    _output_error:
2342
0
        return (int) (-(((const char*)ip)-src))-1;
2343
0
    }
2344
0
}
2345
2346
2347
/*===== Instantiate the API decoding functions. =====*/
2348
2349
LZ4_FORCE_O2
2350
int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
2351
0
{
2352
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
2353
0
                                  decode_full_block, noDict,
2354
0
                                  (BYTE*)dest, NULL, 0);
2355
0
}
2356
2357
LZ4_FORCE_O2
2358
int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity)
2359
0
{
2360
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2361
0
    return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
2362
0
                                  partial_decode,
2363
0
                                  noDict, (BYTE*)dst, NULL, 0);
2364
0
}
2365
2366
LZ4_FORCE_O2
2367
int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
2368
0
{
2369
0
    DEBUGLOG(5, "LZ4_decompress_fast");
2370
0
    return LZ4_decompress_unsafe_generic(
2371
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2372
0
                0, NULL, 0);
2373
0
}
2374
2375
/*===== Instantiate a few more decoding cases, used more than once. =====*/
2376
2377
LZ4_FORCE_O2 /* Exported, an obsolete API function. */
2378
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
2379
0
{
2380
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2381
0
                                  decode_full_block, withPrefix64k,
2382
0
                                  (BYTE*)dest - 64 KB, NULL, 0);
2383
0
}
2384
2385
LZ4_FORCE_O2
2386
static int LZ4_decompress_safe_partial_withPrefix64k(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity)
2387
0
{
2388
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2389
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2390
0
                                  partial_decode, withPrefix64k,
2391
0
                                  (BYTE*)dest - 64 KB, NULL, 0);
2392
0
}
2393
2394
/* Another obsolete API function, paired with the previous one. */
2395
int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
2396
0
{
2397
0
    return LZ4_decompress_unsafe_generic(
2398
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2399
0
                64 KB, NULL, 0);
2400
0
}
2401
2402
LZ4_FORCE_O2
2403
static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize,
2404
                                               size_t prefixSize)
2405
0
{
2406
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2407
0
                                  decode_full_block, noDict,
2408
0
                                  (BYTE*)dest-prefixSize, NULL, 0);
2409
0
}
2410
2411
LZ4_FORCE_O2
2412
static int LZ4_decompress_safe_partial_withSmallPrefix(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity,
2413
                                               size_t prefixSize)
2414
0
{
2415
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2416
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2417
0
                                  partial_decode, noDict,
2418
0
                                  (BYTE*)dest-prefixSize, NULL, 0);
2419
0
}
2420
2421
LZ4_FORCE_O2
2422
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
2423
                                     int compressedSize, int maxOutputSize,
2424
                                     const void* dictStart, size_t dictSize)
2425
0
{
2426
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2427
0
                                  decode_full_block, usingExtDict,
2428
0
                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
2429
0
}
2430
2431
LZ4_FORCE_O2
2432
int LZ4_decompress_safe_partial_forceExtDict(const char* source, char* dest,
2433
                                     int compressedSize, int targetOutputSize, int dstCapacity,
2434
                                     const void* dictStart, size_t dictSize)
2435
0
{
2436
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2437
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2438
0
                                  partial_decode, usingExtDict,
2439
0
                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
2440
0
}
2441
2442
LZ4_FORCE_O2
2443
static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,
2444
                                       const void* dictStart, size_t dictSize)
2445
0
{
2446
0
    return LZ4_decompress_unsafe_generic(
2447
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2448
0
                0, (const BYTE*)dictStart, dictSize);
2449
0
}
2450
2451
/* The "double dictionary" mode, for use with e.g. ring buffers: the first part
2452
 * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
2453
 * These routines are used only once, in LZ4_decompress_*_continue().
2454
 */
2455
LZ4_FORCE_INLINE
2456
int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,
2457
                                   size_t prefixSize, const void* dictStart, size_t dictSize)
2458
0
{
2459
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2460
0
                                  decode_full_block, usingExtDict,
2461
0
                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
2462
0
}
2463
2464
/*===== streaming decompression functions =====*/
2465
2466
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
2467
LZ4_streamDecode_t* LZ4_createStreamDecode(void)
2468
0
{
2469
0
    LZ4_STATIC_ASSERT(sizeof(LZ4_streamDecode_t) >= sizeof(LZ4_streamDecode_t_internal));
2470
0
    return (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
2471
0
}
2472
2473
int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
2474
0
{
2475
0
    if (LZ4_stream == NULL) { return 0; }  /* support free on NULL */
2476
0
    FREEMEM(LZ4_stream);
2477
0
    return 0;
2478
0
}
2479
#endif
2480
2481
/*! LZ4_setStreamDecode() :
2482
 *  Use this function to instruct where to find the dictionary.
2483
 *  This function is not necessary if previous data is still available where it was decoded.
2484
 *  Loading a size of 0 is allowed (same effect as no dictionary).
2485
 * @return : 1 if OK, 0 if error
2486
 */
2487
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
2488
0
{
2489
0
    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
2490
0
    lz4sd->prefixSize = (size_t)dictSize;
2491
0
    if (dictSize) {
2492
0
        assert(dictionary != NULL);
2493
0
        lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
2494
0
    } else {
2495
0
        lz4sd->prefixEnd = (const BYTE*) dictionary;
2496
0
    }
2497
0
    lz4sd->externalDict = NULL;
2498
0
    lz4sd->extDictSize  = 0;
2499
0
    return 1;
2500
0
}
2501
2502
/*! LZ4_decoderRingBufferSize() :
2503
 *  when setting a ring buffer for streaming decompression (optional scenario),
2504
 *  provides the minimum size of this ring buffer
2505
 *  to be compatible with any source respecting maxBlockSize condition.
2506
 *  Note : in a ring buffer scenario,
2507
 *  blocks are presumed decompressed next to each other.
2508
 *  When not enough space remains for next block (remainingSize < maxBlockSize),
2509
 *  decoding resumes from beginning of ring buffer.
2510
 * @return : minimum ring buffer size,
2511
 *           or 0 if there is an error (invalid maxBlockSize).
2512
 */
2513
int LZ4_decoderRingBufferSize(int maxBlockSize)
2514
0
{
2515
0
    if (maxBlockSize < 0) return 0;
2516
0
    if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
2517
0
    if (maxBlockSize < 16) maxBlockSize = 16;
2518
0
    return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
2519
0
}
2520
2521
/*
2522
*_continue() :
2523
    These decoding functions allow decompression of multiple blocks in "streaming" mode.
2524
    Previously decoded blocks must still be available at the memory position where they were decoded.
2525
    If it's not possible, save the relevant part of decoded data into a safe buffer,
2526
    and indicate where it stands using LZ4_setStreamDecode()
2527
*/
2528
LZ4_FORCE_O2
2529
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
2530
0
{
2531
0
    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
2532
0
    int result;
2533
2534
0
    if (lz4sd->prefixSize == 0) {
2535
        /* The first call, no dictionary yet. */
2536
0
        assert(lz4sd->extDictSize == 0);
2537
0
        result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
2538
0
        if (result <= 0) return result;
2539
0
        lz4sd->prefixSize = (size_t)result;
2540
0
        lz4sd->prefixEnd = (BYTE*)dest + result;
2541
0
    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
2542
        /* They're rolling the current segment. */
2543
0
        if (lz4sd->prefixSize >= 64 KB - 1)
2544
0
            result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
2545
0
        else if (lz4sd->extDictSize == 0)
2546
0
            result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
2547
0
                                                         lz4sd->prefixSize);
2548
0
        else
2549
0
            result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
2550
0
                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
2551
0
        if (result <= 0) return result;
2552
0
        lz4sd->prefixSize += (size_t)result;
2553
0
        lz4sd->prefixEnd  += result;
2554
0
    } else {
2555
        /* The buffer wraps around, or they're switching to another buffer. */
2556
0
        lz4sd->extDictSize = lz4sd->prefixSize;
2557
0
        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
2558
0
        result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
2559
0
                                                  lz4sd->externalDict, lz4sd->extDictSize);
2560
0
        if (result <= 0) return result;
2561
0
        lz4sd->prefixSize = (size_t)result;
2562
0
        lz4sd->prefixEnd  = (BYTE*)dest + result;
2563
0
    }
2564
2565
0
    return result;
2566
0
}
2567
2568
LZ4_FORCE_O2 int
2569
LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode,
2570
                        const char* source, char* dest, int originalSize)
2571
0
{
2572
0
    LZ4_streamDecode_t_internal* const lz4sd =
2573
0
        (assert(LZ4_streamDecode!=NULL), &LZ4_streamDecode->internal_donotuse);
2574
0
    int result;
2575
2576
0
    DEBUGLOG(5, "LZ4_decompress_fast_continue (toDecodeSize=%i)", originalSize);
2577
0
    assert(originalSize >= 0);
2578
2579
0
    if (lz4sd->prefixSize == 0) {
2580
0
        DEBUGLOG(5, "first invocation : no prefix nor extDict");
2581
0
        assert(lz4sd->extDictSize == 0);
2582
0
        result = LZ4_decompress_fast(source, dest, originalSize);
2583
0
        if (result <= 0) return result;
2584
0
        lz4sd->prefixSize = (size_t)originalSize;
2585
0
        lz4sd->prefixEnd = (BYTE*)dest + originalSize;
2586
0
    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
2587
0
        DEBUGLOG(5, "continue using existing prefix");
2588
0
        result = LZ4_decompress_unsafe_generic(
2589
0
                        (const BYTE*)source, (BYTE*)dest, originalSize,
2590
0
                        lz4sd->prefixSize,
2591
0
                        lz4sd->externalDict, lz4sd->extDictSize);
2592
0
        if (result <= 0) return result;
2593
0
        lz4sd->prefixSize += (size_t)originalSize;
2594
0
        lz4sd->prefixEnd  += originalSize;
2595
0
    } else {
2596
0
        DEBUGLOG(5, "prefix becomes extDict");
2597
0
        lz4sd->extDictSize = lz4sd->prefixSize;
2598
0
        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
2599
0
        result = LZ4_decompress_fast_extDict(source, dest, originalSize,
2600
0
                                             lz4sd->externalDict, lz4sd->extDictSize);
2601
0
        if (result <= 0) return result;
2602
0
        lz4sd->prefixSize = (size_t)originalSize;
2603
0
        lz4sd->prefixEnd  = (BYTE*)dest + originalSize;
2604
0
    }
2605
2606
0
    return result;
2607
0
}
2608
2609
2610
/*
2611
Advanced decoding functions :
2612
*_usingDict() :
2613
    These decoding functions work the same as "_continue" ones,
2614
    the dictionary must be explicitly provided within parameters
2615
*/
2616
2617
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
2618
0
{
2619
0
    if (dictSize==0)
2620
0
        return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
2621
0
    if (dictStart+dictSize == dest) {
2622
0
        if (dictSize >= 64 KB - 1) {
2623
0
            return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
2624
0
        }
2625
0
        assert(dictSize >= 0);
2626
0
        return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);
2627
0
    }
2628
0
    assert(dictSize >= 0);
2629
0
    return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);
2630
0
}
2631
2632
int LZ4_decompress_safe_partial_usingDict(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity, const char* dictStart, int dictSize)
2633
0
{
2634
0
    if (dictSize==0)
2635
0
        return LZ4_decompress_safe_partial(source, dest, compressedSize, targetOutputSize, dstCapacity);
2636
0
    if (dictStart+dictSize == dest) {
2637
0
        if (dictSize >= 64 KB - 1) {
2638
0
            return LZ4_decompress_safe_partial_withPrefix64k(source, dest, compressedSize, targetOutputSize, dstCapacity);
2639
0
        }
2640
0
        assert(dictSize >= 0);
2641
0
        return LZ4_decompress_safe_partial_withSmallPrefix(source, dest, compressedSize, targetOutputSize, dstCapacity, (size_t)dictSize);
2642
0
    }
2643
0
    assert(dictSize >= 0);
2644
0
    return LZ4_decompress_safe_partial_forceExtDict(source, dest, compressedSize, targetOutputSize, dstCapacity, dictStart, (size_t)dictSize);
2645
0
}
2646
2647
int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
2648
0
{
2649
0
    if (dictSize==0 || dictStart+dictSize == dest)
2650
0
        return LZ4_decompress_unsafe_generic(
2651
0
                        (const BYTE*)source, (BYTE*)dest, originalSize,
2652
0
                        (size_t)dictSize, NULL, 0);
2653
0
    assert(dictSize >= 0);
2654
0
    return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize);
2655
0
}
2656
2657
2658
/*=*************************************************
2659
*  Obsolete Functions
2660
***************************************************/
2661
/* obsolete compression functions */
2662
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
2663
0
{
2664
0
    return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
2665
0
}
2666
int LZ4_compress(const char* src, char* dest, int srcSize)
2667
0
{
2668
0
    return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize));
2669
0
}
2670
int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)
2671
0
{
2672
0
    return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
2673
0
}
2674
int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)
2675
0
{
2676
0
    return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
2677
0
}
2678
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)
2679
0
{
2680
0
    return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
2681
0
}
2682
int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
2683
0
{
2684
0
    return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
2685
0
}
2686
2687
/*
2688
These decompression functions are deprecated and should no longer be used.
2689
They are only provided here for compatibility with older user programs.
2690
- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
2691
- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
2692
*/
2693
int LZ4_uncompress (const char* source, char* dest, int outputSize)
2694
0
{
2695
0
    return LZ4_decompress_fast(source, dest, outputSize);
2696
0
}
2697
int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)
2698
0
{
2699
0
    return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
2700
0
}
2701
2702
/* Obsolete Streaming functions */
2703
2704
0
int LZ4_sizeofStreamState(void) { return sizeof(LZ4_stream_t); }
2705
2706
int LZ4_resetStreamState(void* state, char* inputBuffer)
2707
0
{
2708
0
    (void)inputBuffer;
2709
0
    LZ4_resetStream((LZ4_stream_t*)state);
2710
0
    return 0;
2711
0
}
2712
2713
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
2714
void* LZ4_create (char* inputBuffer)
2715
0
{
2716
0
    (void)inputBuffer;
2717
0
    return LZ4_createStream();
2718
0
}
2719
#endif
2720
2721
char* LZ4_slideInputBuffer (void* state)
2722
0
{
2723
    /* avoid const char * -> char * conversion warning */
2724
0
    return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;
2725
0
}
2726
2727
#endif   /* LZ4_COMMONDEFS_ONLY */