Coverage Report

Created: 2026-05-30 06:16

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.70k
#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.70M
#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )
173
#else
174
#  define expect(expr,value)    (expr)
175
#endif
176
177
#ifndef likely
178
40.9k
#define likely(expr)     expect((expr) != 0, 1)
179
#endif
180
#ifndef unlikely
181
703k
#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.49k
#  define LZ4_memset(p,v,s) memset((p),(v),(s))
236
#endif
237
6.49k
#define MEM_INIT(p,v,s)   LZ4_memset((p),(v),(s))
238
239
240
/*-************************************
241
*  Common Constants
242
**************************************/
243
222k
#define MINMATCH 4
244
245
1.71k
#define WILDCOPYLENGTH 8
246
17.4k
#define LASTLITERALS   5   /* see ../doc/lz4_Block_format.md#parsing-restrictions */
247
23.1k
#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
16.6k
#define FASTLOOP_SAFE_DISTANCE 64
250
static const int LZ4_minLength = (MFLIMIT+1);
251
252
3.66k
#define KB *(1 <<10)
253
#define MB *(1 <<20)
254
0
#define GB *(1U<<30)
255
256
88.5k
#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
178k
#define ML_BITS  4
262
83.3k
#define ML_MASK  ((1U<<ML_BITS)-1)
263
53.9k
#define RUN_BITS (8-ML_BITS)
264
53.9k
#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
569k
#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
718k
#  define DEBUGLOG(l, ...) {}    /* disabled */
291
#endif
292
293
static int LZ4_isAligned(const void* ptr, size_t alignment)
294
4.79k
{
295
4.79k
    return ((size_t)ptr & (alignment -1)) == 0;
296
4.79k
}
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.79k
{
295
4.79k
    return ((size_t)ptr & (alignment -1)) == 0;
296
4.79k
}
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.38M
#    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.64k
#    define LZ4_memmove __builtin_memmove
359
#  else
360
#    define LZ4_memmove memmove
361
#  endif
362
#endif
363
364
static unsigned LZ4_isLittleEndian(void)
365
551k
{
366
551k
    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental */
367
551k
    return one.c[0];
368
551k
}
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
551k
{
366
551k
    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental */
367
551k
    return one.c[0];
368
551k
}
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.1k
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.1k
static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign16*)ptr)->u16; }
Unexecuted instantiation: lz4hc.c:LZ4_read16
395
853k
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
853k
static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign32*)ptr)->u32; }
Unexecuted instantiation: lz4hc.c:LZ4_read32
396
6.45M
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.45M
static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalignST*)ptr)->uArch; }
Unexecuted instantiation: lz4hc.c:LZ4_read_ARCH
397
398
24.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
24.7k
static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign16*)memPtr)->u16 = value; }
Unexecuted instantiation: lz4hc.c:LZ4_write16
399
32.5k
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.5k
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
18.5k
{
433
18.5k
    if (LZ4_isLittleEndian()) {
434
18.5k
        return LZ4_read16(memPtr);
435
18.5k
    } else {
436
0
        const BYTE* p = (const BYTE*)memPtr;
437
0
        return (U16)((U16)p[0] | (p[1]<<8));
438
0
    }
439
18.5k
}
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
18.5k
{
433
18.5k
    if (LZ4_isLittleEndian()) {
434
18.5k
        return LZ4_read16(memPtr);
435
18.5k
    } else {
436
0
        const BYTE* p = (const BYTE*)memPtr;
437
0
        return (U16)((U16)p[0] | (p[1]<<8));
438
0
    }
439
18.5k
}
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
24.7k
{
455
24.7k
    if (LZ4_isLittleEndian()) {
456
24.7k
        LZ4_write16(memPtr, value);
457
24.7k
    } else {
458
0
        BYTE* p = (BYTE*)memPtr;
459
0
        p[0] = (BYTE) value;
460
0
        p[1] = (BYTE)(value>>8);
461
0
    }
462
24.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
24.7k
{
455
24.7k
    if (LZ4_isLittleEndian()) {
456
24.7k
        LZ4_write16(memPtr, value);
457
24.7k
    } else {
458
0
        BYTE* p = (BYTE*)memPtr;
459
0
        p[0] = (BYTE) value;
460
0
        p[1] = (BYTE)(value>>8);
461
0
    }
462
24.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.2k
{
468
21.2k
    BYTE* d = (BYTE*)dstPtr;
469
21.2k
    const BYTE* s = (const BYTE*)srcPtr;
470
21.2k
    BYTE* const e = (BYTE*)dstEnd;
471
472
181k
    do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e);
473
21.2k
}
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.2k
{
468
21.2k
    BYTE* d = (BYTE*)dstPtr;
469
21.2k
    const BYTE* s = (const BYTE*)srcPtr;
470
21.2k
    BYTE* const e = (BYTE*)dstEnd;
471
472
181k
    do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e);
473
21.2k
}
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.01k
{
494
1.01k
    assert(srcPtr + offset == dstPtr);
495
1.01k
    if (offset < 8) {
496
912
        LZ4_write32(dstPtr, 0);   /* silence an msan warning when offset==0 */
497
912
        assert(offset != 1);   /* offset==0 happens on testing */
498
912
        LZ4_memcpy(dstPtr, srcPtr, 2);
499
912
        LZ4_memcpy(dstPtr + 2, srcPtr + 2, 2);
500
912
        srcPtr += inc32table[offset];
501
912
        LZ4_memcpy(dstPtr+4, srcPtr, 4);
502
912
        srcPtr -= dec64table[offset];
503
912
        dstPtr += 8;
504
912
    } else {
505
102
        LZ4_memcpy(dstPtr, srcPtr, 8);
506
102
        dstPtr += 8;
507
102
        srcPtr += 8;
508
102
    }
509
510
1.01k
    LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);
511
1.01k
}
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.01k
{
494
1.01k
    assert(srcPtr + offset == dstPtr);
495
1.01k
    if (offset < 8) {
496
912
        LZ4_write32(dstPtr, 0);   /* silence an msan warning when offset==0 */
497
912
        assert(offset != 1);   /* offset==0 happens on testing */
498
912
        LZ4_memcpy(dstPtr, srcPtr, 2);
499
912
        LZ4_memcpy(dstPtr + 2, srcPtr + 2, 2);
500
912
        srcPtr += inc32table[offset];
501
912
        LZ4_memcpy(dstPtr+4, srcPtr, 4);
502
912
        srcPtr -= dec64table[offset];
503
912
        dstPtr += 8;
504
912
    } else {
505
102
        LZ4_memcpy(dstPtr, srcPtr, 8);
506
102
        dstPtr += 8;
507
102
        srcPtr += 8;
508
102
    }
509
510
1.01k
    LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);
511
1.01k
}
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.65k
{
533
3.65k
    BYTE* d = (BYTE*)dstPtr;
534
3.65k
    const BYTE* s = (const BYTE*)srcPtr;
535
3.65k
    BYTE* const e = (BYTE*)dstEnd;
536
537
95.3k
    do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);
538
3.65k
}
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.65k
{
533
3.65k
    BYTE* d = (BYTE*)dstPtr;
534
3.65k
    const BYTE* s = (const BYTE*)srcPtr;
535
3.65k
    BYTE* const e = (BYTE*)dstEnd;
536
537
95.3k
    do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);
538
3.65k
}
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
5.82k
{
546
5.82k
    BYTE v[8];
547
548
5.82k
    assert(dstEnd >= dstPtr + MINMATCH);
549
550
5.82k
    switch(offset) {
551
1.70k
    case 1:
552
1.70k
        MEM_INIT(v, *srcPtr, 8);
553
1.70k
        break;
554
2.80k
    case 2:
555
2.80k
        LZ4_memcpy(v, srcPtr, 2);
556
2.80k
        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.80k
        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.80k
        break;
566
309
    case 4:
567
309
        LZ4_memcpy(v, srcPtr, 4);
568
309
        LZ4_memcpy(&v[4], srcPtr, 4);
569
309
        break;
570
1.01k
    default:
571
1.01k
        LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
572
1.01k
        return;
573
5.82k
    }
574
575
4.81k
    LZ4_memcpy(dstPtr, v, 8);
576
4.81k
    dstPtr += 8;
577
959k
    while (dstPtr < dstEnd) {
578
955k
        LZ4_memcpy(dstPtr, v, 8);
579
955k
        dstPtr += 8;
580
955k
    }
581
4.81k
}
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
5.82k
{
546
5.82k
    BYTE v[8];
547
548
5.82k
    assert(dstEnd >= dstPtr + MINMATCH);
549
550
5.82k
    switch(offset) {
551
1.70k
    case 1:
552
1.70k
        MEM_INIT(v, *srcPtr, 8);
553
1.70k
        break;
554
2.80k
    case 2:
555
2.80k
        LZ4_memcpy(v, srcPtr, 2);
556
2.80k
        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.80k
        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.80k
        break;
566
309
    case 4:
567
309
        LZ4_memcpy(v, srcPtr, 4);
568
309
        LZ4_memcpy(&v[4], srcPtr, 4);
569
309
        break;
570
1.01k
    default:
571
1.01k
        LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);
572
1.01k
        return;
573
5.82k
    }
574
575
4.81k
    LZ4_memcpy(dstPtr, v, 8);
576
4.81k
    dstPtr += 8;
577
959k
    while (dstPtr < dstEnd) {
578
955k
        LZ4_memcpy(dstPtr, v, 8);
579
955k
        dstPtr += 8;
580
955k
    }
581
4.81k
}
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
22.6k
{
590
22.6k
    assert(val != 0);
591
22.6k
    if (LZ4_isLittleEndian()) {
592
22.6k
        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
22.6k
        } 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
22.6k
    } 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
22.6k
}
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
22.6k
{
590
22.6k
    assert(val != 0);
591
22.6k
    if (LZ4_isLittleEndian()) {
592
22.6k
        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
22.6k
        } 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
22.6k
    } 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
22.6k
}
Unexecuted instantiation: lz4hc.c:LZ4_NbCommonBytes
685
686
687
5.92M
#define STEPSIZE sizeof(reg_t)
688
LZ4_FORCE_INLINE
689
unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
690
24.7k
{
691
24.7k
    const BYTE* const pStart = pIn;
692
693
24.7k
    if (likely(pIn < pInLimit-(STEPSIZE-1))) {
694
23.2k
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
695
23.2k
        if (!diff) {
696
13.1k
            pIn+=STEPSIZE; pMatch+=STEPSIZE;
697
13.1k
        } else {
698
10.1k
            return LZ4_NbCommonBytes(diff);
699
10.1k
    }   }
700
701
2.96M
    while (likely(pIn < pInLimit-(STEPSIZE-1))) {
702
2.96M
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
703
2.96M
        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
704
12.5k
        pIn += LZ4_NbCommonBytes(diff);
705
12.5k
        return (unsigned)(pIn - pStart);
706
2.96M
    }
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.5k
}
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
24.7k
{
691
24.7k
    const BYTE* const pStart = pIn;
692
693
24.7k
    if (likely(pIn < pInLimit-(STEPSIZE-1))) {
694
23.2k
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
695
23.2k
        if (!diff) {
696
13.1k
            pIn+=STEPSIZE; pMatch+=STEPSIZE;
697
13.1k
        } else {
698
10.1k
            return LZ4_NbCommonBytes(diff);
699
10.1k
    }   }
700
701
2.96M
    while (likely(pIn < pInLimit-(STEPSIZE-1))) {
702
2.96M
        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
703
2.96M
        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
704
12.5k
        pIn += LZ4_NbCommonBytes(diff);
705
12.5k
        return (unsigned)(pIn - pStart);
706
2.96M
    }
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.5k
}
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
6.90k
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
118k
{
788
118k
    if (tableType == byU16)
789
118k
        return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
790
0
    else
791
0
        return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
792
118k
}
793
794
LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
795
485k
{
796
485k
    const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
797
485k
    if (LZ4_isLittleEndian()) {
798
485k
        const U64 prime5bytes = 889523592379ULL;
799
485k
        return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
800
485k
    } else {
801
0
        const U64 prime8bytes = 11400714785074694791ULL;
802
0
        return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
803
0
    }
804
485k
}
805
806
LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
807
603k
{
808
603k
    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
118k
    return LZ4_hash4(LZ4_read32(p), tableType);
814
603k
#endif
815
603k
}
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
586k
{
831
586k
    switch (tableType)
832
586k
    {
833
0
    default: /* fallthrough */
834
0
    case clearedTable: /* fallthrough */
835
0
    case byPtr: { /* illegal! */ assert(0); return; }
836
480k
    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }
837
106k
    case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }
838
586k
    }
839
586k
}
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
561k
{
864
561k
    LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
865
561k
    if (tableType == byU32) {
866
471k
        const U32* const hashTable = (const U32*) tableBase;
867
471k
        assert(h < (1U << (LZ4_MEMORY_USAGE-2)));
868
471k
        return hashTable[h];
869
471k
    }
870
90.1k
    if (tableType == byU16) {
871
90.1k
        const U16* const hashTable = (const U16*) tableBase;
872
90.1k
        assert(h < (1U << (LZ4_MEMORY_USAGE-1)));
873
90.1k
        return hashTable[h];
874
90.1k
    }
875
90.1k
    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.18k
{
952
4.18k
    int result;
953
4.18k
    const BYTE* ip = (const BYTE*)source;
954
955
4.18k
    U32 const startIndex = cctx->currentOffset;
956
4.18k
    const BYTE* base = (const BYTE*)source - startIndex;
957
4.18k
    const BYTE* lowLimit;
958
959
4.18k
    const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
960
4.18k
    const BYTE* const dictionary =
961
4.18k
        dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
962
4.18k
    const U32 dictSize =
963
4.18k
        dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
964
4.18k
    const U32 dictDelta =
965
4.18k
        (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with indexes in current context */
966
967
4.18k
    int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
968
4.18k
    U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */
969
4.18k
    const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary;
970
4.18k
    const BYTE* anchor = (const BYTE*) source;
971
4.18k
    const BYTE* const iend = ip + inputSize;
972
4.18k
    const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;
973
4.18k
    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.18k
    const BYTE* dictBase = (dictionary == NULL) ? NULL :
978
4.18k
                           (dictDirective == usingDictCtx) ?
979
0
                            dictionary + dictSize - dictCtx->currentOffset :
980
0
                            dictionary + dictSize - startIndex;
981
982
4.18k
    BYTE* op = (BYTE*) dest;
983
4.18k
    BYTE* const olimit = op + maxOutputSize;
984
985
4.18k
    U32 offset = 0;
986
4.18k
    U32 forwardH;
987
988
4.18k
    DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType);
989
4.18k
    assert(ip != NULL);
990
4.18k
    if (tableType == byU16) assert(inputSize<LZ4_64Klimit);  /* Size too large (not within 64K limit) */
991
4.18k
    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.18k
    if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */
995
4.18k
    assert(acceleration >= 1);
996
997
4.18k
    lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
998
999
    /* Update context state */
1000
4.18k
    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.18k
    } else {
1006
4.18k
        cctx->dictSize += (U32)inputSize;
1007
4.18k
    }
1008
4.18k
    cctx->currentOffset += (U32)inputSize;
1009
4.18k
    cctx->tableType = (U32)tableType;
1010
1011
4.18k
    if (inputSize<LZ4_minLength) goto _last_literals;        /* Input too small, no compression (all literals) */
1012
1013
    /* First Byte */
1014
4.12k
    {   U32 const h = LZ4_hashPosition(ip, tableType);
1015
4.12k
        if (tableType == byPtr) {
1016
0
            LZ4_putPositionOnHash(ip, h, cctx->hashTable, byPtr);
1017
4.12k
        } else {
1018
4.12k
            LZ4_putIndexOnHash(startIndex, h, cctx->hashTable, tableType);
1019
4.12k
    }   }
1020
4.12k
    ip++; forwardH = LZ4_hashPosition(ip, tableType);
1021
1022
    /* Main Loop */
1023
17.0k
    for ( ; ; ) {
1024
17.0k
        const BYTE* match;
1025
17.0k
        BYTE* token;
1026
17.0k
        const BYTE* filledIp;
1027
1028
        /* Find a match */
1029
17.0k
        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.0k
        } else {   /* byU32, byU16 */
1050
1051
17.0k
            const BYTE* forwardIp = ip;
1052
17.0k
            int step = 1;
1053
17.0k
            int searchMatchNb = acceleration << LZ4_skipTrigger;
1054
538k
            do {
1055
538k
                U32 const h = forwardH;
1056
538k
                U32 const current = (U32)(forwardIp - base);
1057
538k
                U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
1058
538k
                assert(matchIndex <= current);
1059
538k
                assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
1060
538k
                ip = forwardIp;
1061
538k
                forwardIp += step;
1062
538k
                step = (searchMatchNb++ >> LZ4_skipTrigger);
1063
1064
538k
                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
1065
538k
                assert(ip < mflimitPlusOne);
1066
1067
537k
                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
537k
                } 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
537k
                } else {   /* single continuous memory segment */
1091
537k
                    match = base + matchIndex;
1092
537k
                }
1093
537k
                forwardH = LZ4_hashPosition(forwardIp, tableType);
1094
537k
                LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
1095
1096
537k
                DEBUGLOG(7, "candidate at pos=%u  (offset=%u \n", matchIndex, current - matchIndex);
1097
537k
                if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; }    /* match outside of valid area */
1098
537k
                assert(matchIndex < current);
1099
537k
                if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX))
1100
462k
                  && (matchIndex+LZ4_DISTANCE_MAX < current)) {
1101
193k
                    continue;
1102
193k
                } /* too far */
1103
537k
                assert((current - matchIndex) <= LZ4_DISTANCE_MAX);  /* match now expected within distance */
1104
1105
343k
                if (LZ4_read32(match) == LZ4_read32(ip)) {
1106
15.3k
                    if (maybe_extMem) offset = current - matchIndex;
1107
15.3k
                    break;   /* match found */
1108
15.3k
                }
1109
1110
521k
            } while(1);
1111
17.0k
        }
1112
1113
        /* Catch up */
1114
15.3k
        filledIp = ip;
1115
15.3k
        assert(ip > anchor); /* this is always true as ip has been advanced before entering the main loop */
1116
15.3k
        if ((match > lowLimit) && unlikely(ip[-1] == match[-1])) {
1117
11.7k
            do { ip--; match--; } while (((ip > anchor) & (match > lowLimit)) && (unlikely(ip[-1] == match[-1])));
1118
1.20k
        }
1119
1120
        /* Encode Literals */
1121
15.3k
        {   unsigned const litLength = (unsigned)(ip - anchor);
1122
15.3k
            token = op++;
1123
15.3k
            if ((outputDirective == limitedOutput) &&  /* Check output buffer overflow */
1124
6.89k
                (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) {
1125
167
                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1126
167
            }
1127
15.2k
            if ((outputDirective == fillOutput) &&
1128
6.85k
                (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
224
                op--;
1130
224
                goto _last_literals;
1131
224
            }
1132
14.9k
            if (litLength >= RUN_MASK) {
1133
835
                unsigned len = litLength - RUN_MASK;
1134
835
                *token = (RUN_MASK<<ML_BITS);
1135
835
                for(; len >= 255 ; len-=255) *op++ = 255;
1136
835
                *op++ = (BYTE)len;
1137
835
            }
1138
14.1k
            else *token = (BYTE)(litLength<<ML_BITS);
1139
1140
            /* Copy Literals */
1141
14.9k
            LZ4_wildCopy8(op, anchor, op+litLength);
1142
14.9k
            op+=litLength;
1143
14.9k
            DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
1144
14.9k
                        (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source));
1145
14.9k
        }
1146
1147
24.8k
_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
24.8k
        if ((outputDirective == fillOutput) &&
1157
11.4k
            (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
166
            op = token;
1160
166
            goto _last_literals;
1161
166
        }
1162
1163
        /* Encode Offset */
1164
24.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
24.7k
        } else  {
1169
24.7k
            DEBUGLOG(6, "             with offset=%u  (same segment)", (U32)(ip - match));
1170
24.7k
            assert(ip-match <= LZ4_DISTANCE_MAX);
1171
24.7k
            LZ4_writeLE16(op, (U16)(ip - match)); op+=2;
1172
24.7k
        }
1173
1174
        /* Encode MatchLength */
1175
24.7k
        {   unsigned matchCode;
1176
1177
24.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
24.7k
            } else {
1191
24.7k
                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
1192
24.7k
                ip += (size_t)matchCode + MINMATCH;
1193
24.7k
                DEBUGLOG(6, "             with matchLength=%u", matchCode+MINMATCH);
1194
24.7k
            }
1195
1196
24.7k
            if ((outputDirective) &&    /* Check output buffer overflow */
1197
22.6k
                (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) {
1198
295
                if (outputDirective == fillOutput) {
1199
                    /* Match description too long : reduce it */
1200
115
                    U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;
1201
115
                    ip -= matchCode - newMatchCode;
1202
115
                    assert(newMatchCode < matchCode);
1203
115
                    matchCode = newMatchCode;
1204
115
                    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
180
                } else {
1218
180
                    assert(outputDirective == limitedOutput);
1219
180
                    return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1220
180
                }
1221
295
            }
1222
24.5k
            if (matchCode >= ML_MASK) {
1223
10.4k
                *token += ML_MASK;
1224
10.4k
                matchCode -= ML_MASK;
1225
10.4k
                LZ4_write32(op, 0xFFFFFFFF);
1226
27.6k
                while (matchCode >= 4*255) {
1227
17.2k
                    op+=4;
1228
17.2k
                    LZ4_write32(op, 0xFFFFFFFF);
1229
17.2k
                    matchCode -= 4*255;
1230
17.2k
                }
1231
10.4k
                op += matchCode / 255;
1232
10.4k
                *op++ = (BYTE)(matchCode % 255);
1233
10.4k
            } else
1234
14.0k
                *token += (BYTE)(matchCode);
1235
24.5k
        }
1236
        /* Ensure we have enough space for the last literals. */
1237
24.5k
        assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit));
1238
1239
24.5k
        anchor = ip;
1240
1241
        /* Test end of chunk */
1242
24.5k
        if (ip >= mflimitPlusOne) break;
1243
1244
        /* Fill table */
1245
22.7k
        {   U32 const h = LZ4_hashPosition(ip-2, tableType);
1246
22.7k
            if (tableType == byPtr) {
1247
0
                LZ4_putPositionOnHash(ip-2, h, cctx->hashTable, byPtr);
1248
22.7k
            } else {
1249
22.7k
                U32 const idx = (U32)((ip-2) - base);
1250
22.7k
                LZ4_putIndexOnHash(idx, h, cctx->hashTable, tableType);
1251
22.7k
        }   }
1252
1253
        /* Test next position */
1254
22.7k
        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
22.7k
        } else {   /* byU32, byU16 */
1263
1264
22.7k
            U32 const h = LZ4_hashPosition(ip, tableType);
1265
22.7k
            U32 const current = (U32)(ip-base);
1266
22.7k
            U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
1267
22.7k
            assert(matchIndex < current);
1268
22.7k
            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
22.7k
            } 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
22.7k
            } else {   /* single memory segment */
1290
22.7k
                match = base + matchIndex;
1291
22.7k
            }
1292
22.7k
            LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
1293
22.7k
            assert(matchIndex < current);
1294
22.7k
            if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)
1295
22.7k
              && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current))
1296
22.7k
              && (LZ4_read32(match) == LZ4_read32(ip)) ) {
1297
9.88k
                token=op++;
1298
9.88k
                *token=0;
1299
9.88k
                if (maybe_extMem) offset = current - matchIndex;
1300
9.88k
                DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
1301
9.88k
                            (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));
1302
9.88k
                goto _next_match;
1303
9.88k
            }
1304
22.7k
        }
1305
1306
        /* Prepare next loop */
1307
12.9k
        forwardH = LZ4_hashPosition(++ip, tableType);
1308
1309
12.9k
    }
1310
1311
3.83k
_last_literals:
1312
    /* Encode Last Literals */
1313
3.83k
    {   size_t lastRun = (size_t)(iend - anchor);
1314
3.83k
        if ( (outputDirective) &&  /* Check output buffer overflow */
1315
2.64k
            (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {
1316
742
            if (outputDirective == fillOutput) {
1317
                /* adapt lastRun to fill 'dst' */
1318
557
                assert(olimit >= op);
1319
557
                lastRun  = (size_t)(olimit-op) - 1/*token*/;
1320
557
                lastRun -= (lastRun + 256 - RUN_MASK) / 256;  /*additional length tokens*/
1321
557
            } else {
1322
185
                assert(outputDirective == limitedOutput);
1323
185
                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */
1324
185
            }
1325
742
        }
1326
3.64k
        DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun);
1327
3.64k
        if (lastRun >= RUN_MASK) {
1328
433
            size_t accumulator = lastRun - RUN_MASK;
1329
433
            *op++ = RUN_MASK << ML_BITS;
1330
433
            for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
1331
433
            *op++ = (BYTE) accumulator;
1332
3.21k
        } else {
1333
3.21k
            *op++ = (BYTE)(lastRun<<ML_BITS);
1334
3.21k
        }
1335
3.64k
        LZ4_memcpy(op, anchor, lastRun);
1336
3.64k
        ip = anchor + lastRun;
1337
3.64k
        op += lastRun;
1338
3.64k
    }
1339
1340
3.64k
    if (outputDirective == fillOutput) {
1341
1.48k
        *inputConsumed = (int) (((const char*)ip)-source);
1342
1.48k
    }
1343
3.64k
    result = (int)(((char*)op) - dest);
1344
3.64k
    assert(result > 0);
1345
3.64k
    DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result);
1346
3.64k
    return result;
1347
3.64k
}
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.19k
{
1366
4.19k
    DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i",
1367
4.19k
                srcSize, dstCapacity);
1368
1369
4.19k
    if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; }  /* Unsupported srcSize, too large (or negative) */
1370
4.19k
    if (srcSize == 0) {   /* src == NULL supported if srcSize == 0 */
1371
17
        if (outputDirective != notLimited && dstCapacity <= 0) return 0;  /* no output, can't write anything */
1372
16
        DEBUGLOG(5, "Generating an empty block");
1373
16
        assert(outputDirective == notLimited || dstCapacity >= 1);
1374
16
        assert(dst != NULL);
1375
16
        dst[0] = 0;
1376
16
        if (outputDirective == fillOutput) {
1377
7
            assert (inputConsumed != NULL);
1378
7
            *inputConsumed = 0;
1379
7
        }
1380
16
        return 1;
1381
16
    }
1382
4.19k
    assert(src != NULL);
1383
1384
4.18k
    return LZ4_compress_generic_validated(cctx, src, dst, srcSize,
1385
4.18k
                inputConsumed, /* only written into if outputDirective == fillOutput */
1386
4.18k
                dstCapacity, outputDirective,
1387
4.18k
                tableType, dictDirective, dictIssue, acceleration);
1388
4.18k
}
1389
1390
1391
int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
1392
2.70k
{
1393
2.70k
    LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse;
1394
2.70k
    assert(ctx != NULL);
1395
2.70k
    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
1396
2.70k
    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
1397
2.70k
    if (maxOutputSize >= LZ4_compressBound(inputSize)) {
1398
1.19k
        if (inputSize < LZ4_64Klimit) {
1399
1.19k
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
1400
1.19k
        } 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.51k
    } else {
1405
1.51k
        if (inputSize < LZ4_64Klimit) {
1406
1.25k
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
1407
1.25k
        } else {
1408
264
            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1409
264
            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
1410
264
        }
1411
1.51k
    }
1412
2.70k
}
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.11k
{
1464
2.11k
    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.11k
    LZ4_stream_t ctx;
1470
2.11k
    LZ4_stream_t* const ctxPtr = &ctx;
1471
2.11k
#endif
1472
2.11k
    result = LZ4_compress_fast_extState(ctxPtr, src, dest, srcSize, dstCapacity, acceleration);
1473
1474
#if (LZ4_HEAPMODE)
1475
    FREEMEM(ctxPtr);
1476
#endif
1477
2.11k
    return result;
1478
2.11k
}
1479
1480
1481
int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity)
1482
2.11k
{
1483
2.11k
    return LZ4_compress_fast(src, dst, srcSize, dstCapacity, 1);
1484
2.11k
}
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.08k
{
1492
2.08k
    void* const s = LZ4_initStream(state, sizeof (*state));
1493
2.08k
    assert(s != NULL); (void)s;
1494
1495
2.08k
    if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */
1496
596
        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, acceleration);
1497
1.49k
    } else {
1498
1.49k
        if (*srcSizePtr < LZ4_64Klimit) {
1499
1.23k
            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, acceleration);
1500
1.23k
        } else {
1501
254
            tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
1502
254
            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, acceleration);
1503
254
    }   }
1504
2.08k
}
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.08k
{
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.08k
    LZ4_stream_t ctxBody;
1522
2.08k
    LZ4_stream_t* const ctx = &ctxBody;
1523
2.08k
#endif
1524
1525
2.08k
    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.08k
    return result;
1531
2.08k
}
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.79k
{
1553
4.79k
#if LZ4_ALIGN_TEST
1554
4.79k
    typedef struct { char c; LZ4_stream_t t; } t_a;
1555
4.79k
    return sizeof(t_a) - sizeof(LZ4_stream_t);
1556
#else
1557
    return 1;  /* effectively disabled */
1558
#endif
1559
4.79k
}
1560
1561
LZ4_stream_t* LZ4_initStream (void* buffer, size_t size)
1562
4.79k
{
1563
4.79k
    DEBUGLOG(5, "LZ4_initStream");
1564
4.79k
    if (buffer == NULL) { return NULL; }
1565
4.79k
    if (size < sizeof(LZ4_stream_t)) { return NULL; }
1566
4.79k
    if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL;
1567
4.79k
    MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal));
1568
4.79k
    return (LZ4_stream_t*)buffer;
1569
4.79k
}
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
 * @ip : input pointer
1981
 * @ilimit : position after which if length is not decoded, the input is necessarily corrupted.
1982
 * @initial_check - check ip >= ipmax before start of loop.  Returns initial_error if so.
1983
 * @error (output) - error code.  Must be set to 0 before call.
1984
**/
1985
typedef size_t Rvl_t;
1986
static const Rvl_t rvl_error = (Rvl_t)(-1);
1987
LZ4_FORCE_INLINE Rvl_t
1988
read_variable_length(const BYTE** ip, const BYTE* ilimit,
1989
                     int initial_check)
1990
8.18k
{
1991
8.18k
    Rvl_t s, length = 0;
1992
8.18k
    assert(ip != NULL);
1993
8.18k
    assert(*ip !=  NULL);
1994
8.18k
    assert(ilimit != NULL);
1995
8.18k
    if (initial_check && unlikely((*ip) >= ilimit)) {    /* read limit reached */
1996
0
        return rvl_error;
1997
0
    }
1998
8.18k
    s = **ip;
1999
8.18k
    (*ip)++;
2000
8.18k
    length += s;
2001
8.18k
    if (unlikely((*ip) > ilimit)) {    /* read limit reached */
2002
0
        return rvl_error;
2003
0
    }
2004
    /* accumulator overflow detection (32-bit mode only) */
2005
8.18k
    if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
2006
0
        return rvl_error;
2007
0
    }
2008
8.18k
    if (likely(s != 255)) return length;
2009
43.8k
    do {
2010
43.8k
        s = **ip;
2011
43.8k
        (*ip)++;
2012
43.8k
        length += s;
2013
43.8k
        if (unlikely((*ip) > ilimit)) {    /* read limit reached */
2014
0
            return rvl_error;
2015
0
        }
2016
        /* accumulator overflow detection (32-bit mode only) */
2017
43.8k
        if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
2018
0
            return rvl_error;
2019
0
        }
2020
43.8k
    } while (s == 255);
2021
2022
2.95k
    return length;
2023
2.95k
}
2024
2025
/*! LZ4_decompress_generic() :
2026
 *  This generic decompression function covers all use cases.
2027
 *  It shall be instantiated several times, using different sets of directives.
2028
 *  Note that it is important for performance that this function really get inlined,
2029
 *  in order to remove useless branches during compilation optimization.
2030
 */
2031
LZ4_FORCE_INLINE int
2032
LZ4_decompress_generic(
2033
                 const char* const src,
2034
                 char* const dst,
2035
                 int srcSize,
2036
                 int outputSize,         /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
2037
2038
                 earlyEnd_directive partialDecoding,  /* full, partial */
2039
                 dict_directive dict,                 /* noDict, withPrefix64k, usingExtDict */
2040
                 const BYTE* const lowPrefix,  /* always <= dst, == dst when no prefix */
2041
                 const BYTE* const dictStart,  /* only if dict==usingExtDict */
2042
                 const size_t dictSize         /* note : = 0 if noDict */
2043
                 )
2044
3.66k
{
2045
3.66k
    if ((src == NULL) || (outputSize < 0)) { return -1; }
2046
2047
3.66k
    {   const BYTE* ip = (const BYTE*) src;
2048
3.66k
        const BYTE* const iend = ip + srcSize;
2049
2050
3.66k
        BYTE* op = (BYTE*) dst;
2051
3.66k
        BYTE* const oend = op + outputSize;
2052
3.66k
        BYTE* cpy;
2053
2054
3.66k
        const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;
2055
2056
3.66k
        const int checkOffset = (dictSize < (int)(64 KB));
2057
2058
2059
        /* Set up the "end" pointers for the shortcut. */
2060
3.66k
        const BYTE* const shortiend = iend - 14 /*maxLL*/ - 2 /*offset*/;
2061
3.66k
        const BYTE* const shortoend = oend - 14 /*maxLL*/ - 18 /*maxML*/;
2062
2063
3.66k
        const BYTE* match;
2064
3.66k
        size_t offset;
2065
3.66k
        unsigned token;
2066
3.66k
        size_t length;
2067
2068
2069
3.66k
        DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
2070
2071
        /* Special cases */
2072
3.66k
        assert(lowPrefix <= op);
2073
3.66k
        if (unlikely(outputSize==0)) {
2074
            /* Empty output buffer */
2075
16
            if (partialDecoding) return 0;
2076
16
            return ((srcSize==1) && (*ip==0)) ? 0 : -1;
2077
16
        }
2078
3.64k
        if (unlikely(srcSize==0)) { return -1; }
2079
2080
    /* LZ4_FAST_DEC_LOOP:
2081
     * designed for modern OoO performance cpus,
2082
     * where copying reliably 32-bytes is preferable to an unpredictable branch.
2083
     * note : fast loop may show a regression for some client arm chips. */
2084
3.64k
#if LZ4_FAST_DEC_LOOP
2085
3.64k
        if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {
2086
2.25k
            DEBUGLOG(6, "move to safe decode loop");
2087
2.25k
            goto safe_decode;
2088
2.25k
        }
2089
2090
        /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */
2091
1.39k
        DEBUGLOG(6, "using fast decode loop");
2092
13.6k
        while (1) {
2093
            /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
2094
13.6k
            assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
2095
13.6k
            assert(ip < iend);
2096
13.6k
            token = *ip++;
2097
13.6k
            length = token >> ML_BITS;  /* literal length */
2098
13.6k
            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
2099
2100
13.6k
            if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy_early; }
2101
2102
            /* decode literal length */
2103
13.2k
            if (length == RUN_MASK) {
2104
638
                size_t const addl = read_variable_length(&ip, iend, 0);
2105
638
                if (addl == rvl_error) {
2106
0
                    DEBUGLOG(6, "error reading long literal length");
2107
0
                    goto _output_error;
2108
0
                }
2109
638
                length += addl;
2110
638
                cpy = op+length;
2111
638
                if (unlikely((uptrval)(cpy)<(uptrval)(op))) { goto _output_error; } /* overflow detection */
2112
638
                if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
2113
2114
                /* copy literals */
2115
638
                LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
2116
              #ifdef __aarch64__
2117
                if ((cpy>oend-64) || (ip+length>iend-64)) { goto safe_literal_copy; }
2118
                LZ4_wildCopy64(op, ip, cpy);
2119
              #else
2120
638
                if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
2121
381
                LZ4_wildCopy32(op, ip, cpy);
2122
381
              #endif
2123
381
                ip += length; op = cpy;
2124
12.6k
            } else {
2125
12.6k
                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
2126
                /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */
2127
12.6k
                LZ4_memcpy(op, ip, 16);
2128
12.6k
                ip += length; op += length;
2129
12.6k
            }
2130
2131
            /* get offset */
2132
12.9k
            offset = LZ4_readLE16(ip); ip+=2;
2133
12.9k
            DEBUGLOG(6, "blockPos%6u: offset = %u", (unsigned)(op-(BYTE*)dst), (unsigned)offset);
2134
12.9k
            match = op - offset;
2135
12.9k
            assert(match <= op);  /* overflow check */
2136
2137
            /* get matchlength */
2138
12.9k
            length = token & ML_MASK;
2139
12.9k
            DEBUGLOG(7, "  match length token = %u (len==%u)", (unsigned)length, (unsigned)length+MINMATCH);
2140
2141
12.9k
            if (length == ML_MASK) {
2142
6.42k
                size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
2143
6.42k
                if (addl == rvl_error) {
2144
0
                    DEBUGLOG(5, "error reading long match length");
2145
0
                    goto _output_error;
2146
0
                }
2147
6.42k
                length += addl;
2148
6.42k
                length += MINMATCH;
2149
6.42k
                DEBUGLOG(7, "  long match length == %u", (unsigned)length);
2150
6.42k
                if (unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */
2151
6.42k
                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
2152
328
                    goto safe_match_copy;
2153
328
                }
2154
6.56k
            } else {
2155
6.56k
                length += MINMATCH;
2156
6.56k
                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
2157
412
                    DEBUGLOG(7, "moving to safe_match_copy (ml==%u)", (unsigned)length);
2158
412
                    goto safe_match_copy;
2159
412
                }
2160
2161
                /* Fastpath check: skip LZ4_wildCopy32 when true */
2162
6.15k
                if ((dict == withPrefix64k) || (match >= lowPrefix)) {
2163
6.15k
                    if (offset >= 8) {
2164
3.14k
                        assert(match >= lowPrefix);
2165
3.14k
                        assert(match <= op);
2166
3.14k
                        assert(op + 18 <= oend);
2167
2168
3.14k
                        LZ4_memcpy(op, match, 8);
2169
3.14k
                        LZ4_memcpy(op+8, match+8, 8);
2170
3.14k
                        LZ4_memcpy(op+16, match+16, 2);
2171
3.14k
                        op += length;
2172
3.14k
                        continue;
2173
3.14k
            }   }   }
2174
2175
9.10k
            if ( checkOffset && (unlikely(match + dictSize < lowPrefix)) ) {
2176
0
                DEBUGLOG(5, "Error : pos=%zi, offset=%zi => outside buffers", op-lowPrefix, op-match);
2177
0
                goto _output_error;
2178
0
            }
2179
            /* match starting within external dictionary */
2180
9.10k
            if ((dict==usingExtDict) && (match < lowPrefix)) {
2181
0
                assert(dictEnd != NULL);
2182
0
                if (unlikely(op+length > oend-LASTLITERALS)) {
2183
0
                    if (partialDecoding) {
2184
0
                        DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
2185
0
                        length = MIN(length, (size_t)(oend-op));
2186
0
                    } else {
2187
0
                        DEBUGLOG(6, "end-of-block condition violated")
2188
0
                        goto _output_error;
2189
0
                }   }
2190
2191
0
                if (length <= (size_t)(lowPrefix-match)) {
2192
                    /* match fits entirely within external dictionary : just copy */
2193
0
                    LZ4_memmove(op, dictEnd - (lowPrefix-match), length);
2194
0
                    op += length;
2195
0
                } else {
2196
                    /* match stretches into both external dictionary and current block */
2197
0
                    size_t const copySize = (size_t)(lowPrefix - match);
2198
0
                    size_t const restSize = length - copySize;
2199
0
                    LZ4_memcpy(op, dictEnd - copySize, copySize);
2200
0
                    op += copySize;
2201
0
                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */
2202
0
                        BYTE* const endOfMatch = op + restSize;
2203
0
                        const BYTE* copyFrom = lowPrefix;
2204
0
                        while (op < endOfMatch) { *op++ = *copyFrom++; }
2205
0
                    } else {
2206
0
                        LZ4_memcpy(op, lowPrefix, restSize);
2207
0
                        op += restSize;
2208
0
                }   }
2209
0
                continue;
2210
0
            }
2211
2212
            /* copy match within block */
2213
9.10k
            cpy = op + length;
2214
2215
9.10k
            assert((op <= oend) && (oend-op >= 64));
2216
9.10k
            if (unlikely(offset<16)) {
2217
5.82k
                LZ4_memcpy_using_offset(op, match, cpy, offset);
2218
    #ifdef __aarch64__
2219
            } else if (offset >= 64) {
2220
                LZ4_wildCopy64(op, match, cpy);
2221
    #endif
2222
5.82k
            } else {
2223
3.27k
                LZ4_wildCopy32(op, match, cpy);
2224
3.27k
            }
2225
2226
9.10k
            op = cpy;   /* wildcopy correction */
2227
9.10k
        }
2228
2.25k
    safe_decode:
2229
2.25k
#endif
2230
2231
        /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
2232
2.25k
        DEBUGLOG(6, "using safe decode loop");
2233
8.51k
        while (1) {
2234
8.51k
            assert(ip < iend);
2235
8.51k
            token = *ip++;
2236
8.51k
            length = token >> ML_BITS;  /* literal length */
2237
8.51k
            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
2238
2239
            /* A two-stage shortcut for the most common case:
2240
             * 1) If the literal length is 0..14, and there is enough space,
2241
             * enter the shortcut and copy 16 bytes on behalf of the literals
2242
             * (in the fast mode, only 8 bytes can be safely copied this way).
2243
             * 2) Further if the match length is 4..18, copy 18 bytes in a similar
2244
             * manner; but we ensure that there's enough space in the output for
2245
             * those 18 bytes earlier, upon entering the shortcut (in other words,
2246
             * there is a combined check for both stages).
2247
             */
2248
8.51k
            if ( (length != RUN_MASK)
2249
                /* strictly "less than" on input, to re-enter the loop with at least one byte */
2250
8.06k
              && likely((ip < shortiend) & (op <= shortoend)) ) {
2251
                /* Copy the literals */
2252
1.60k
                LZ4_memcpy(op, ip, 16);
2253
1.60k
                op += length; ip += length;
2254
2255
                /* The second stage: prepare for match copying, decode full info.
2256
                 * If it doesn't work out, the info won't be wasted. */
2257
1.60k
                length = token & ML_MASK; /* match length */
2258
1.60k
                DEBUGLOG(7, "blockPos%6u: matchLength token = %u (len=%u)", (unsigned)(op-(BYTE*)dst), (unsigned)length, (unsigned)length + 4);
2259
1.60k
                offset = LZ4_readLE16(ip); ip += 2;
2260
1.60k
                match = op - offset;
2261
1.60k
                assert(match <= op); /* check overflow */
2262
2263
                /* Do not deal with overlapping matches. */
2264
1.60k
                if ( (length != ML_MASK)
2265
1.45k
                  && (offset >= 8)
2266
688
                  && (dict==withPrefix64k || match >= lowPrefix) ) {
2267
                    /* Copy the match. */
2268
688
                    LZ4_memcpy(op + 0, match + 0, 8);
2269
688
                    LZ4_memcpy(op + 8, match + 8, 8);
2270
688
                    LZ4_memcpy(op +16, match +16, 2);
2271
688
                    op += length + MINMATCH;
2272
                    /* Both stages worked, load the next token. */
2273
688
                    continue;
2274
688
                }
2275
2276
                /* The second stage didn't work out, but the info is ready.
2277
                 * Propel it right to the point of match copying. */
2278
912
                goto _copy_match;
2279
1.60k
            }
2280
2281
6.91k
#if LZ4_FAST_DEC_LOOP
2282
7.31k
        safe_literal_copy_early:
2283
7.31k
#endif
2284
2285
            /* decode literal length */
2286
7.31k
            if (length == RUN_MASK) {
2287
454
                size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1);
2288
454
                if (addl == rvl_error) { goto _output_error; }
2289
454
                length += addl;
2290
454
                if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
2291
454
                if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
2292
454
            }
2293
2294
            /* copy literals */
2295
7.31k
            cpy = op+length;
2296
2297
7.31k
#if LZ4_FAST_DEC_LOOP
2298
7.57k
        safe_literal_copy:
2299
7.57k
#endif
2300
2301
7.57k
            LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
2302
7.57k
            if ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) {
2303
                /* We've either hit the input parsing restriction or the output parsing restriction.
2304
                 * In the normal scenario, decoding a full block, it must be the last sequence,
2305
                 * otherwise it's an error (invalid input or dimensions).
2306
                 * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow.
2307
                 */
2308
3.64k
                if (partialDecoding) {
2309
                    /* Since we are partial decoding we may be in this block because of the output parsing
2310
                     * restriction, which is not valid since the output buffer is allowed to be undersized.
2311
                     */
2312
0
                    DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end")
2313
0
                    DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length);
2314
0
                    DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op));
2315
0
                    DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip));
2316
                    /* Finishing in the middle of a literals segment,
2317
                     * due to lack of input.
2318
                     */
2319
0
                    if (ip+length > iend) {
2320
0
                        length = (size_t)(iend-ip);
2321
0
                        cpy = op + length;
2322
0
                    }
2323
                    /* Finishing in the middle of a literals segment,
2324
                     * due to lack of output space.
2325
                     */
2326
0
                    if (cpy > oend) {
2327
0
                        cpy = oend;
2328
0
                        assert(op<=oend);
2329
0
                        length = (size_t)(oend-op);
2330
0
                    }
2331
3.64k
                } else {
2332
                     /* We must be on the last sequence (or invalid) because of the parsing limitations
2333
                      * so check that we exactly consume the input and don't overrun the output buffer.
2334
                      */
2335
3.64k
                    if ((ip+length != iend) || (cpy > oend)) {
2336
0
                        DEBUGLOG(5, "should have been last run of literals")
2337
0
                        DEBUGLOG(5, "ip(%p) + length(%i) = %p != iend (%p)", (void*)ip, (int)length, (void*)(ip+length), (void*)iend);
2338
0
                        DEBUGLOG(5, "or cpy(%p) > (oend-MFLIMIT)(%p)", (void*)cpy, (void*)(oend-MFLIMIT));
2339
0
                        DEBUGLOG(5, "after writing %u bytes / %i bytes available", (unsigned)(op-(BYTE*)dst), outputSize);
2340
0
                        goto _output_error;
2341
0
                    }
2342
3.64k
                }
2343
3.64k
                LZ4_memmove(op, ip, length);  /* supports overlapping memory regions, for in-place decompression scenarios */
2344
3.64k
                ip += length;
2345
3.64k
                op += length;
2346
                /* Necessarily EOF when !partialDecoding.
2347
                 * When partialDecoding, it is EOF if we've either
2348
                 * filled the output buffer or
2349
                 * can't proceed with reading an offset for following match.
2350
                 */
2351
3.64k
                if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) {
2352
3.64k
                    break;
2353
3.64k
                }
2354
3.92k
            } else {
2355
3.92k
                LZ4_wildCopy8(op, ip, cpy);   /* can overwrite up to 8 bytes beyond cpy */
2356
3.92k
                ip += length; op = cpy;
2357
3.92k
            }
2358
2359
            /* get offset */
2360
3.92k
            offset = LZ4_readLE16(ip); ip+=2;
2361
3.92k
            match = op - offset;
2362
2363
            /* get matchlength */
2364
3.92k
            length = token & ML_MASK;
2365
3.92k
            DEBUGLOG(7, "blockPos%6u: matchLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
2366
2367
4.83k
    _copy_match:
2368
4.83k
            if (length == ML_MASK) {
2369
663
                size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
2370
663
                if (addl == rvl_error) { goto _output_error; }
2371
663
                length += addl;
2372
663
                if (unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error;   /* overflow detection */
2373
663
            }
2374
4.83k
            length += MINMATCH;
2375
2376
4.83k
#if LZ4_FAST_DEC_LOOP
2377
5.57k
        safe_match_copy:
2378
5.57k
#endif
2379
5.57k
            if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error;   /* Error : offset outside buffers */
2380
            /* match starting within external dictionary */
2381
5.57k
            if ((dict==usingExtDict) && (match < lowPrefix)) {
2382
0
                assert(dictEnd != NULL);
2383
0
                if (unlikely(op+length > oend-LASTLITERALS)) {
2384
0
                    if (partialDecoding) length = MIN(length, (size_t)(oend-op));
2385
0
                    else goto _output_error;   /* doesn't respect parsing restriction */
2386
0
                }
2387
2388
0
                if (length <= (size_t)(lowPrefix-match)) {
2389
                    /* match fits entirely within external dictionary : just copy */
2390
0
                    LZ4_memmove(op, dictEnd - (lowPrefix-match), length);
2391
0
                    op += length;
2392
0
                } else {
2393
                    /* match stretches into both external dictionary and current block */
2394
0
                    size_t const copySize = (size_t)(lowPrefix - match);
2395
0
                    size_t const restSize = length - copySize;
2396
0
                    LZ4_memcpy(op, dictEnd - copySize, copySize);
2397
0
                    op += copySize;
2398
0
                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */
2399
0
                        BYTE* const endOfMatch = op + restSize;
2400
0
                        const BYTE* copyFrom = lowPrefix;
2401
0
                        while (op < endOfMatch) *op++ = *copyFrom++;
2402
0
                    } else {
2403
0
                        LZ4_memcpy(op, lowPrefix, restSize);
2404
0
                        op += restSize;
2405
0
                }   }
2406
0
                continue;
2407
0
            }
2408
5.57k
            assert(match >= lowPrefix);
2409
2410
            /* copy match within block */
2411
5.57k
            cpy = op + length;
2412
2413
            /* partialDecoding : may end anywhere within the block */
2414
5.57k
            assert(op<=oend);
2415
5.57k
            if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
2416
0
                size_t const mlen = MIN(length, (size_t)(oend-op));
2417
0
                const BYTE* const matchEnd = match + mlen;
2418
0
                BYTE* const copyEnd = op + mlen;
2419
0
                if (matchEnd > op) {   /* overlap copy */
2420
0
                    while (op < copyEnd) { *op++ = *match++; }
2421
0
                } else {
2422
0
                    LZ4_memcpy(op, match, mlen);
2423
0
                }
2424
0
                op = copyEnd;
2425
0
                if (op == oend) { break; }
2426
0
                continue;
2427
0
            }
2428
2429
5.57k
            if (unlikely(offset<8)) {
2430
4.00k
                LZ4_write32(op, 0);   /* silence msan warning when offset==0 */
2431
4.00k
                op[0] = match[0];
2432
4.00k
                op[1] = match[1];
2433
4.00k
                op[2] = match[2];
2434
4.00k
                op[3] = match[3];
2435
4.00k
                match += inc32table[offset];
2436
4.00k
                LZ4_memcpy(op+4, match, 4);
2437
4.00k
                match -= dec64table[offset];
2438
4.00k
            } else {
2439
1.56k
                LZ4_memcpy(op, match, 8);
2440
1.56k
                match += 8;
2441
1.56k
            }
2442
5.57k
            op += 8;
2443
2444
5.57k
            if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
2445
1.71k
                BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
2446
1.71k
                if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */
2447
1.71k
                if (op < oCopyLimit) {
2448
671
                    LZ4_wildCopy8(op, match, oCopyLimit);
2449
671
                    match += oCopyLimit - op;
2450
671
                    op = oCopyLimit;
2451
671
                }
2452
2.54k
                while (op < cpy) { *op++ = *match++; }
2453
3.86k
            } else {
2454
3.86k
                LZ4_memcpy(op, match, 8);
2455
3.86k
                if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); }
2456
3.86k
            }
2457
5.57k
            op = cpy;   /* wildcopy correction */
2458
5.57k
        }
2459
2460
        /* end of decoding */
2461
3.64k
        DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst));
2462
3.64k
        return (int) (((char*)op)-dst);     /* Nb of output bytes decoded */
2463
2464
        /* Overflow error detected */
2465
0
    _output_error:
2466
0
        return (int) (-(((const char*)ip)-src))-1;
2467
2.25k
    }
2468
2.25k
}
2469
2470
2471
/*===== Instantiate the API decoding functions. =====*/
2472
2473
LZ4_FORCE_O2
2474
int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
2475
3.66k
{
2476
3.66k
    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,
2477
3.66k
                                  decode_full_block, noDict,
2478
3.66k
                                  (BYTE*)dest, NULL, 0);
2479
3.66k
}
2480
2481
LZ4_FORCE_O2
2482
int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity)
2483
0
{
2484
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2485
0
    return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,
2486
0
                                  partial_decode,
2487
0
                                  noDict, (BYTE*)dst, NULL, 0);
2488
0
}
2489
2490
LZ4_FORCE_O2
2491
int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
2492
0
{
2493
0
    DEBUGLOG(5, "LZ4_decompress_fast");
2494
0
    return LZ4_decompress_unsafe_generic(
2495
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2496
0
                0, NULL, 0);
2497
0
}
2498
2499
/*===== Instantiate a few more decoding cases, used more than once. =====*/
2500
2501
LZ4_FORCE_O2 /* Exported, an obsolete API function. */
2502
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
2503
0
{
2504
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2505
0
                                  decode_full_block, withPrefix64k,
2506
0
                                  (BYTE*)dest - 64 KB, NULL, 0);
2507
0
}
2508
2509
LZ4_FORCE_O2
2510
static int LZ4_decompress_safe_partial_withPrefix64k(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity)
2511
0
{
2512
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2513
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2514
0
                                  partial_decode, withPrefix64k,
2515
0
                                  (BYTE*)dest - 64 KB, NULL, 0);
2516
0
}
2517
2518
/* Another obsolete API function, paired with the previous one. */
2519
int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
2520
0
{
2521
0
    return LZ4_decompress_unsafe_generic(
2522
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2523
0
                64 KB, NULL, 0);
2524
0
}
2525
2526
LZ4_FORCE_O2
2527
static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize,
2528
                                               size_t prefixSize)
2529
0
{
2530
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2531
0
                                  decode_full_block, noDict,
2532
0
                                  (BYTE*)dest-prefixSize, NULL, 0);
2533
0
}
2534
2535
LZ4_FORCE_O2
2536
static int LZ4_decompress_safe_partial_withSmallPrefix(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity,
2537
                                               size_t prefixSize)
2538
0
{
2539
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2540
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2541
0
                                  partial_decode, noDict,
2542
0
                                  (BYTE*)dest-prefixSize, NULL, 0);
2543
0
}
2544
2545
LZ4_FORCE_O2
2546
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
2547
                                     int compressedSize, int maxOutputSize,
2548
                                     const void* dictStart, size_t dictSize)
2549
0
{
2550
0
    DEBUGLOG(5, "LZ4_decompress_safe_forceExtDict");
2551
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2552
0
                                  decode_full_block, usingExtDict,
2553
0
                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
2554
0
}
2555
2556
LZ4_FORCE_O2
2557
int LZ4_decompress_safe_partial_forceExtDict(const char* source, char* dest,
2558
                                     int compressedSize, int targetOutputSize, int dstCapacity,
2559
                                     const void* dictStart, size_t dictSize)
2560
0
{
2561
0
    dstCapacity = MIN(targetOutputSize, dstCapacity);
2562
0
    return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity,
2563
0
                                  partial_decode, usingExtDict,
2564
0
                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);
2565
0
}
2566
2567
LZ4_FORCE_O2
2568
static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,
2569
                                       const void* dictStart, size_t dictSize)
2570
0
{
2571
0
    return LZ4_decompress_unsafe_generic(
2572
0
                (const BYTE*)source, (BYTE*)dest, originalSize,
2573
0
                0, (const BYTE*)dictStart, dictSize);
2574
0
}
2575
2576
/* The "double dictionary" mode, for use with e.g. ring buffers: the first part
2577
 * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
2578
 * These routines are used only once, in LZ4_decompress_*_continue().
2579
 */
2580
LZ4_FORCE_INLINE
2581
int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,
2582
                                   size_t prefixSize, const void* dictStart, size_t dictSize)
2583
0
{
2584
0
    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
2585
0
                                  decode_full_block, usingExtDict,
2586
0
                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
2587
0
}
2588
2589
/*===== streaming decompression functions =====*/
2590
2591
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
2592
LZ4_streamDecode_t* LZ4_createStreamDecode(void)
2593
0
{
2594
0
    LZ4_STATIC_ASSERT(sizeof(LZ4_streamDecode_t) >= sizeof(LZ4_streamDecode_t_internal));
2595
0
    return (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
2596
0
}
2597
2598
int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
2599
0
{
2600
0
    if (LZ4_stream == NULL) { return 0; }  /* support free on NULL */
2601
0
    FREEMEM(LZ4_stream);
2602
0
    return 0;
2603
0
}
2604
#endif
2605
2606
/*! LZ4_setStreamDecode() :
2607
 *  Use this function to instruct where to find the dictionary.
2608
 *  This function is not necessary if previous data is still available where it was decoded.
2609
 *  Loading a size of 0 is allowed (same effect as no dictionary).
2610
 * @return : 1 if OK, 0 if error
2611
 */
2612
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
2613
0
{
2614
0
    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
2615
0
    lz4sd->prefixSize = (size_t)dictSize;
2616
0
    if (dictSize) {
2617
0
        assert(dictionary != NULL);
2618
0
        lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
2619
0
    } else {
2620
0
        lz4sd->prefixEnd = (const BYTE*) dictionary;
2621
0
    }
2622
0
    lz4sd->externalDict = NULL;
2623
0
    lz4sd->extDictSize  = 0;
2624
0
    return 1;
2625
0
}
2626
2627
/*! LZ4_decoderRingBufferSize() :
2628
 *  when setting a ring buffer for streaming decompression (optional scenario),
2629
 *  provides the minimum size of this ring buffer
2630
 *  to be compatible with any source respecting maxBlockSize condition.
2631
 *  Note : in a ring buffer scenario,
2632
 *  blocks are presumed decompressed next to each other.
2633
 *  When not enough space remains for next block (remainingSize < maxBlockSize),
2634
 *  decoding resumes from beginning of ring buffer.
2635
 * @return : minimum ring buffer size,
2636
 *           or 0 if there is an error (invalid maxBlockSize).
2637
 */
2638
int LZ4_decoderRingBufferSize(int maxBlockSize)
2639
0
{
2640
0
    if (maxBlockSize < 0) return 0;
2641
0
    if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
2642
0
    if (maxBlockSize < 16) maxBlockSize = 16;
2643
0
    return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
2644
0
}
2645
2646
/*
2647
*_continue() :
2648
    These decoding functions allow decompression of multiple blocks in "streaming" mode.
2649
    Previously decoded blocks must still be available at the memory position where they were decoded.
2650
    If it's not possible, save the relevant part of decoded data into a safe buffer,
2651
    and indicate where it stands using LZ4_setStreamDecode()
2652
*/
2653
LZ4_FORCE_O2
2654
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)
2655
0
{
2656
0
    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
2657
0
    int result;
2658
2659
0
    if (lz4sd->prefixSize == 0) {
2660
        /* The first call, no dictionary yet. */
2661
0
        assert(lz4sd->extDictSize == 0);
2662
0
        result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
2663
0
        if (result <= 0) return result;
2664
0
        lz4sd->prefixSize = (size_t)result;
2665
0
        lz4sd->prefixEnd = (BYTE*)dest + result;
2666
0
    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
2667
        /* They're rolling the current segment. */
2668
0
        if (lz4sd->prefixSize >= 64 KB - 1)
2669
0
            result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
2670
0
        else if (lz4sd->extDictSize == 0)
2671
0
            result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,
2672
0
                                                         lz4sd->prefixSize);
2673
0
        else
2674
0
            result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,
2675
0
                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
2676
0
        if (result <= 0) return result;
2677
0
        lz4sd->prefixSize += (size_t)result;
2678
0
        lz4sd->prefixEnd  += result;
2679
0
    } else {
2680
        /* The buffer wraps around, or they're switching to another buffer. */
2681
0
        lz4sd->extDictSize = lz4sd->prefixSize;
2682
0
        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
2683
0
        result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,
2684
0
                                                  lz4sd->externalDict, lz4sd->extDictSize);
2685
0
        if (result <= 0) return result;
2686
0
        lz4sd->prefixSize = (size_t)result;
2687
0
        lz4sd->prefixEnd  = (BYTE*)dest + result;
2688
0
    }
2689
2690
0
    return result;
2691
0
}
2692
2693
LZ4_FORCE_O2 int
2694
LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode,
2695
                        const char* source, char* dest, int originalSize)
2696
0
{
2697
0
    LZ4_streamDecode_t_internal* const lz4sd =
2698
0
        (assert(LZ4_streamDecode!=NULL), &LZ4_streamDecode->internal_donotuse);
2699
0
    int result;
2700
2701
0
    DEBUGLOG(5, "LZ4_decompress_fast_continue (toDecodeSize=%i)", originalSize);
2702
0
    assert(originalSize >= 0);
2703
2704
0
    if (lz4sd->prefixSize == 0) {
2705
0
        DEBUGLOG(5, "first invocation : no prefix nor extDict");
2706
0
        assert(lz4sd->extDictSize == 0);
2707
0
        result = LZ4_decompress_fast(source, dest, originalSize);
2708
0
        if (result <= 0) return result;
2709
0
        lz4sd->prefixSize = (size_t)originalSize;
2710
0
        lz4sd->prefixEnd = (BYTE*)dest + originalSize;
2711
0
    } else if (lz4sd->prefixEnd == (BYTE*)dest) {
2712
0
        DEBUGLOG(5, "continue using existing prefix");
2713
0
        result = LZ4_decompress_unsafe_generic(
2714
0
                        (const BYTE*)source, (BYTE*)dest, originalSize,
2715
0
                        lz4sd->prefixSize,
2716
0
                        lz4sd->externalDict, lz4sd->extDictSize);
2717
0
        if (result <= 0) return result;
2718
0
        lz4sd->prefixSize += (size_t)originalSize;
2719
0
        lz4sd->prefixEnd  += originalSize;
2720
0
    } else {
2721
0
        DEBUGLOG(5, "prefix becomes extDict");
2722
0
        lz4sd->extDictSize = lz4sd->prefixSize;
2723
0
        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
2724
0
        result = LZ4_decompress_fast_extDict(source, dest, originalSize,
2725
0
                                             lz4sd->externalDict, lz4sd->extDictSize);
2726
0
        if (result <= 0) return result;
2727
0
        lz4sd->prefixSize = (size_t)originalSize;
2728
0
        lz4sd->prefixEnd  = (BYTE*)dest + originalSize;
2729
0
    }
2730
2731
0
    return result;
2732
0
}
2733
2734
2735
/*
2736
Advanced decoding functions :
2737
*_usingDict() :
2738
    These decoding functions work the same as "_continue" ones,
2739
    the dictionary must be explicitly provided within parameters
2740
*/
2741
2742
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
2743
0
{
2744
0
    if (dictSize==0)
2745
0
        return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);
2746
0
    if (dictStart+dictSize == dest) {
2747
0
        if (dictSize >= 64 KB - 1) {
2748
0
            return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);
2749
0
        }
2750
0
        assert(dictSize >= 0);
2751
0
        return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);
2752
0
    }
2753
0
    assert(dictSize >= 0);
2754
0
    return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);
2755
0
}
2756
2757
int LZ4_decompress_safe_partial_usingDict(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity, const char* dictStart, int dictSize)
2758
0
{
2759
0
    if (dictSize==0)
2760
0
        return LZ4_decompress_safe_partial(source, dest, compressedSize, targetOutputSize, dstCapacity);
2761
0
    if (dictStart+dictSize == dest) {
2762
0
        if (dictSize >= 64 KB - 1) {
2763
0
            return LZ4_decompress_safe_partial_withPrefix64k(source, dest, compressedSize, targetOutputSize, dstCapacity);
2764
0
        }
2765
0
        assert(dictSize >= 0);
2766
0
        return LZ4_decompress_safe_partial_withSmallPrefix(source, dest, compressedSize, targetOutputSize, dstCapacity, (size_t)dictSize);
2767
0
    }
2768
0
    assert(dictSize >= 0);
2769
0
    return LZ4_decompress_safe_partial_forceExtDict(source, dest, compressedSize, targetOutputSize, dstCapacity, dictStart, (size_t)dictSize);
2770
0
}
2771
2772
int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
2773
0
{
2774
0
    if (dictSize==0 || dictStart+dictSize == dest)
2775
0
        return LZ4_decompress_unsafe_generic(
2776
0
                        (const BYTE*)source, (BYTE*)dest, originalSize,
2777
0
                        (size_t)dictSize, NULL, 0);
2778
0
    assert(dictSize >= 0);
2779
0
    return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize);
2780
0
}
2781
2782
2783
/*=*************************************************
2784
*  Obsolete Functions
2785
***************************************************/
2786
/* obsolete compression functions */
2787
int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
2788
0
{
2789
0
    return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
2790
0
}
2791
int LZ4_compress(const char* src, char* dest, int srcSize)
2792
0
{
2793
0
    return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize));
2794
0
}
2795
int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)
2796
0
{
2797
0
    return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
2798
0
}
2799
int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)
2800
0
{
2801
0
    return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
2802
0
}
2803
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)
2804
0
{
2805
0
    return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
2806
0
}
2807
int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
2808
0
{
2809
0
    return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
2810
0
}
2811
2812
/*
2813
These decompression functions are deprecated and should no longer be used.
2814
They are only provided here for compatibility with older user programs.
2815
- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
2816
- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
2817
*/
2818
int LZ4_uncompress (const char* source, char* dest, int outputSize)
2819
0
{
2820
0
    return LZ4_decompress_fast(source, dest, outputSize);
2821
0
}
2822
int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)
2823
0
{
2824
0
    return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
2825
0
}
2826
2827
/* Obsolete Streaming functions */
2828
2829
0
int LZ4_sizeofStreamState(void) { return sizeof(LZ4_stream_t); }
2830
2831
int LZ4_resetStreamState(void* state, char* inputBuffer)
2832
0
{
2833
0
    (void)inputBuffer;
2834
0
    LZ4_resetStream((LZ4_stream_t*)state);
2835
0
    return 0;
2836
0
}
2837
2838
#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
2839
void* LZ4_create (char* inputBuffer)
2840
0
{
2841
0
    (void)inputBuffer;
2842
0
    return LZ4_createStream();
2843
0
}
2844
#endif
2845
2846
char* LZ4_slideInputBuffer (void* state)
2847
0
{
2848
    /* avoid const char * -> char * conversion warning */
2849
0
    return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;
2850
0
}
2851
2852
#endif   /* LZ4_COMMONDEFS_ONLY */