Coverage Report

Created: 2026-06-14 06:29

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