Path: blob/main/sys/contrib/openzfs/module/zfs/lz4.c
48383 views
// SPDX-License-Identifier: BSD-2-Clause1/*2LZ4 - Fast LZ compression algorithm3Copyright (C) 2011-present, Yann Collet.45BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)67Redistribution and use in source and binary forms, with or without8modification, are permitted provided that the following conditions are9met:1011* Redistributions of source code must retain the above copyright12notice, this list of conditions and the following disclaimer.13* Redistributions in binary form must reproduce the above14copyright notice, this list of conditions and the following disclaimer15in the documentation and/or other materials provided with the16distribution.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2930You can contact the author at :31- LZ4 homepage : http://www.lz4.org32- LZ4 source repository : https://github.com/lz4/lz433*/3435/*36* This file contains unmodified code from lz4 1.9.3's decompressor, plus37* associated macros and constants.38*39* It also contains a couple of defines from the old lz4.c to make things40* fit together smoothly.41*42*/4344#include <sys/zfs_context.h>4546int LZ4_uncompress_unknownOutputSize(const char *source, char *dest,47int isize, int maxOutputSize);4849/*50* Tuning parameters51*/5253/*54* COMPRESSIONLEVEL: Increasing this value improves compression ratio55* Lowering this value reduces memory usage. Reduced memory usage56* typically improves speed, due to cache effect (ex: L1 32KB for Intel,57* L1 64KB for AMD). Memory usage formula : N->2^(N+2) Bytes58* (examples : 12 -> 16KB ; 17 -> 512KB)59*/60#define COMPRESSIONLEVEL 126162/*63* NOTCOMPRESSIBLE_CONFIRMATION: Decreasing this value will make the64* algorithm skip faster data segments considered "incompressible".65* This may decrease compression ratio dramatically, but will be66* faster on incompressible data. Increasing this value will make67* the algorithm search more before declaring a segment "incompressible".68* This could improve compression a bit, but will be slower on69* incompressible data. The default value (6) is recommended.70*/71#define NOTCOMPRESSIBLE_CONFIRMATION 67273/*74* Little Endian or Big Endian?75* Note: overwrite the below #define if you know your architecture endianness.76*/77#if defined(_ZFS_BIG_ENDIAN)78#define LZ4_BIG_ENDIAN 179#else80/*81* Little Endian assumed. PDP Endian and other very rare endian format82* are unsupported.83*/84#undef LZ4_BIG_ENDIAN85#endif8687/*-************************************88* CPU Feature Detection89**************************************/90/* LZ4_FORCE_MEMORY_ACCESS91* By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.92* Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.93* The below switch allow to select different access method for improved performance.94* Method 0 (default) : use `memcpy()`. Safe and portable.95* Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).96* This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.97* Method 2 : direct access. This method is portable but violate C standard.98* It can generate buggy code on targets which assembly generation depends on alignment.99* But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)100* See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.101* Prefer these methods in priority order (0 > 1 > 2)102*/103#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */104# if defined(__GNUC__) && \105( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \106|| defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )107# define LZ4_FORCE_MEMORY_ACCESS 2108# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)109# define LZ4_FORCE_MEMORY_ACCESS 1110# endif111#endif112113/*114* LZ4_FORCE_SW_BITCOUNT115* Define this parameter if your target system or compiler does not support hardware bit count116*/117/*118* Illumos : we can't use GCC's __builtin_ctz family of builtins in the119* kernel120* Linux : we can use GCC's __builtin_ctz family of builtins in the121* kernel122*/123#undef LZ4_FORCE_SW_BITCOUNT124#if defined(__sunos__)125#define LZ4_FORCE_SW_BITCOUNT126#endif127128/*129* Compiler Options130*/131/* Disable restrict */132#define restrict133134/*135* Linux : GCC_VERSION is defined as of 3.9-rc1, so undefine it.136* torvalds/linux@3f3f8d2f48acfd8ed3b8e6b7377935da57b27b16137*/138#ifdef GCC_VERSION139#undef GCC_VERSION140#endif141142#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)143144#ifndef LZ4_FORCE_INLINE145# ifdef _MSC_VER /* Visual Studio */146# define LZ4_FORCE_INLINE static __forceinline147# else148# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */149# ifdef __GNUC__150# define LZ4_FORCE_INLINE static inline __attribute__((always_inline))151# else152# define LZ4_FORCE_INLINE static inline153# endif154# else155# define LZ4_FORCE_INLINE static156# endif /* __STDC_VERSION__ */157# endif /* _MSC_VER */158#endif /* LZ4_FORCE_INLINE */159160/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE161* gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8,162* together with a simple 8-byte copy loop as a fall-back path.163* However, this optimization hurts the decompression speed by >30%,164* because the execution does not go to the optimized loop165* for typical compressible data, and all of the preamble checks166* before going to the fall-back path become useless overhead.167* This optimization happens only with the -O3 flag, and -O2 generates168* a simple 8-byte copy loop.169* With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8170* functions are annotated with __attribute__((optimize("O2"))),171* and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute172* of LZ4_wildCopy8 does not affect the compression speed.173*/174#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__)175# define LZ4_FORCE_O2 __attribute__((optimize("O2")))176# undef LZ4_FORCE_INLINE177# define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"),always_inline))178#else179# define LZ4_FORCE_O2180#endif181182#ifndef expect183#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)184# define expect(expr,value) (__builtin_expect ((expr),(value)) )185#else186# define expect(expr,value) (expr)187#endif188#endif189190#ifndef likely191#define likely(expr) expect((expr) != 0, 1)192#endif193194#ifndef unlikely195#define unlikely(expr) expect((expr) != 0, 0)196#endif197198#ifndef _KERNEL199#include <stdlib.h> /* malloc, calloc, free */200#include <string.h> /* memset, memcpy */201#endif202#define ALLOC(s) malloc(s)203#define ALLOC_AND_ZERO(s) calloc(1,s)204#define FREEMEM(p) free(p)205206#define MEM_INIT(p,v,s) memset((p),(v),(s))207208209/*-************************************210* Common Constants211**************************************/212#define MINMATCH 4213214#define WILDCOPYLENGTH 8215#define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */216#define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */217#define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */218#define FASTLOOP_SAFE_DISTANCE 64219220#define KB *(1 <<10)221#define MB *(1 <<20)222#define GB *(1U<<30)223224#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */225# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */226#endif227228#define LZ4_DISTANCE_ABSOLUTE_MAX 65535229#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */230# error "LZ4_DISTANCE_MAX is too big : must be <= 65535"231#endif232233#define ML_BITS 4234#define ML_MASK ((1U<<ML_BITS)-1)235#define RUN_BITS (8-ML_BITS)236#define RUN_MASK ((1U<<RUN_BITS)-1)237238#define DEBUGLOG(l, ...) {} /* disabled */239240#ifndef assert241#define assert ASSERT242#endif243244/*-************************************245* Types246**************************************/247#ifndef _KERNEL248#include <limits.h>249#endif250#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)251#ifndef _KERNEL252#include <stdint.h>253#endif254typedef uint8_t BYTE;255typedef uint16_t U16;256typedef uint32_t U32;257typedef int32_t S32;258typedef uint64_t U64;259typedef uintptr_t uptrval;260#else261# if UINT_MAX != 4294967295UL262# error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4"263# endif264typedef unsigned char BYTE;265typedef unsigned short U16;266typedef unsigned int U32;267typedef signed int S32;268typedef unsigned long long U64;269typedef size_t uptrval; /* generally true, except OpenVMS-64 */270#endif271272#if defined(__x86_64__)273typedef U64 reg_t; /* 64-bits in x32 mode */274#else275typedef size_t reg_t; /* 32-bits in x32 mode */276#endif277278typedef enum {279notLimited = 0,280limitedOutput = 1,281fillOutput = 2282} limitedOutput_directive;283284285/*-************************************286* Reading and writing into memory287**************************************/288289/**290* LZ4 relies on memcpy with a constant size being inlined. In freestanding291* environments, the compiler can't assume the implementation of memcpy() is292* standard compliant, so it can't apply its specialized memcpy() inlining293* logic. When possible, use __builtin_memcpy() to tell the compiler to analyze294* memcpy() as if it were standard compliant, so it can inline it in freestanding295* environments. This is needed when decompressing the Linux Kernel, for example.296*/297#if defined(__GNUC__) && (__GNUC__ >= 4)298#define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size)299#else300#define LZ4_memcpy(dst, src, size) memcpy(dst, src, size)301#endif302303static unsigned LZ4_isLittleEndian(void)304{305const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */306return one.c[0];307}308309310#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)311/* lie to the compiler about data alignment; use with caution */312313static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }314315static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }316static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }317318#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)319320/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */321/* currently only defined for gcc and icc */322typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;323324static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }325326static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }327328#else /* safe and portable access using memcpy() */329330static U16 LZ4_read16(const void* memPtr)331{332U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;333}334335static void LZ4_write32(void* memPtr, U32 value)336{337LZ4_memcpy(memPtr, &value, sizeof(value));338}339340#endif /* LZ4_FORCE_MEMORY_ACCESS */341342static U16 LZ4_readLE16(const void* memPtr)343{344if (LZ4_isLittleEndian()) {345return LZ4_read16(memPtr);346} else {347const BYTE* p = (const BYTE*)memPtr;348return (U16)((U16)p[0] + (p[1]<<8));349}350}351352/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */353LZ4_FORCE_INLINE354void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd)355{356BYTE* d = (BYTE*)dstPtr;357const BYTE* s = (const BYTE*)srcPtr;358BYTE* const e = (BYTE*)dstEnd;359360do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e);361}362363static const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};364static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};365366367#ifndef LZ4_FAST_DEC_LOOP368# if defined __i386__ || defined _M_IX86 || defined __x86_64__ || defined _M_X64369# define LZ4_FAST_DEC_LOOP 1370# elif defined(__aarch64__) && !defined(__clang__)371/* On aarch64, we disable this optimization for clang because on certain372* mobile chipsets, performance is reduced with clang. For information373* refer to https://github.com/lz4/lz4/pull/707 */374# define LZ4_FAST_DEC_LOOP 1375# else376# define LZ4_FAST_DEC_LOOP 0377# endif378#endif379380#if LZ4_FAST_DEC_LOOP381382LZ4_FORCE_INLINE void383LZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)384{385assert(srcPtr + offset == dstPtr);386if (offset < 8) {387LZ4_write32(dstPtr, 0); /* silence an msan warning when offset==0 */388dstPtr[0] = srcPtr[0];389dstPtr[1] = srcPtr[1];390dstPtr[2] = srcPtr[2];391dstPtr[3] = srcPtr[3];392srcPtr += inc32table[offset];393LZ4_memcpy(dstPtr+4, srcPtr, 4);394srcPtr -= dec64table[offset];395dstPtr += 8;396} else {397LZ4_memcpy(dstPtr, srcPtr, 8);398dstPtr += 8;399srcPtr += 8;400}401402LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);403}404405/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd406* this version copies two times 16 bytes (instead of one time 32 bytes)407* because it must be compatible with offsets >= 16. */408LZ4_FORCE_INLINE void409LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)410{411BYTE* d = (BYTE*)dstPtr;412const BYTE* s = (const BYTE*)srcPtr;413BYTE* const e = (BYTE*)dstEnd;414415do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);416}417418/* LZ4_memcpy_using_offset() presumes :419* - dstEnd >= dstPtr + MINMATCH420* - there is at least 8 bytes available to write after dstEnd */421LZ4_FORCE_INLINE void422LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)423{424BYTE v[8];425426assert(dstEnd >= dstPtr + MINMATCH);427428switch(offset) {429case 1:430MEM_INIT(v, *srcPtr, 8);431break;432case 2:433LZ4_memcpy(v, srcPtr, 2);434LZ4_memcpy(&v[2], srcPtr, 2);435LZ4_memcpy(&v[4], v, 4);436break;437case 4:438LZ4_memcpy(v, srcPtr, 4);439LZ4_memcpy(&v[4], srcPtr, 4);440break;441default:442LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);443return;444}445446LZ4_memcpy(dstPtr, v, 8);447dstPtr += 8;448while (dstPtr < dstEnd) {449LZ4_memcpy(dstPtr, v, 8);450dstPtr += 8;451}452}453#endif454455456/*-************************************457* Local Structures and types458**************************************/459typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;460461/**462* This enum distinguishes several different modes of accessing previous463* content in the stream.464*465* - noDict : There is no preceding content.466* - withPrefix64k : Table entries up to ctx->dictSize before the current blob467* blob being compressed are valid and refer to the preceding468* content (of length ctx->dictSize), which is available469* contiguously preceding in memory the content currently470* being compressed.471* - usingExtDict : Like withPrefix64k, but the preceding content is somewhere472* else in memory, starting at ctx->dictionary with length473* ctx->dictSize.474* - usingDictCtx : Like usingExtDict, but everything concerning the preceding475* content is in a separate context, pointed to by476* ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table477* entries in the current context that refer to positions478* preceding the beginning of the current compression are479* ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx480* ->dictSize describe the location and size of the preceding481* content, and matches are found by looking in the ctx482* ->dictCtx->hashTable.483*/484typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;485typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;486487/*-*******************************488* Decompression functions489********************************/490491typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;492typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;493494typedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error;495496LZ4_FORCE_INLINE unsigned497read_variable_length(const BYTE**ip, const BYTE* lencheck,498int loop_check, int initial_check,499variable_length_error* error)500{501U32 length = 0;502U32 s;503if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */504*error = initial_error;505return length;506}507do {508s = **ip;509(*ip)++;510length += s;511if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */512*error = loop_error;513return length;514}515} while (s==255);516517return length;518}519520#define LZ4_STATIC_ASSERT(c) ASSERT(c)521522523/*! LZ4_decompress_generic() :524* This generic decompression function covers all use cases.525* It shall be instantiated several times, using different sets of directives.526* Note that it is important for performance that this function really get inlined,527* in order to remove useless branches during compilation optimization.528*/529LZ4_FORCE_INLINE int530LZ4_decompress_generic(531const char* const src,532char* const dst,533int srcSize,534int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */535536endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */537earlyEnd_directive partialDecoding, /* full, partial */538dict_directive dict, /* noDict, withPrefix64k, usingExtDict */539const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */540const BYTE* const dictStart, /* only if dict==usingExtDict */541const size_t dictSize /* note : = 0 if noDict */542)543{544if ((src == NULL) || (outputSize < 0)) { return -1; }545546{ const BYTE* ip = (const BYTE*) src;547const BYTE* const iend = ip + srcSize;548549BYTE* op = (BYTE*) dst;550BYTE* const oend = op + outputSize;551BYTE* cpy;552553const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;554555const int safeDecode = (endOnInput==endOnInputSize);556const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));557558559/* Set up the "end" pointers for the shortcut. */560const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;561const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;562563const BYTE* match;564size_t offset;565unsigned token;566size_t length;567568569DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);570571/* Special cases */572assert(lowPrefix <= op);573if ((endOnInput) && (unlikely(outputSize==0))) {574/* Empty output buffer */575if (partialDecoding) return 0;576return ((srcSize==1) && (*ip==0)) ? 0 : -1;577}578if ((!endOnInput) && (unlikely(outputSize==0))) { return (*ip==0 ? 1 : -1); }579if ((endOnInput) && unlikely(srcSize==0)) { return -1; }580581/* Currently the fast loop shows a regression on qualcomm arm chips. */582#if LZ4_FAST_DEC_LOOP583if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {584DEBUGLOG(6, "skip fast decode loop");585goto safe_decode;586}587588/* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */589while (1) {590/* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */591assert(oend - op >= FASTLOOP_SAFE_DISTANCE);592if (endOnInput) { assert(ip < iend); }593token = *ip++;594length = token >> ML_BITS; /* literal length */595596assert(!endOnInput || ip <= iend); /* ip < iend before the increment */597598/* decode literal length */599if (length == RUN_MASK) {600variable_length_error error = ok;601length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error);602if (error == initial_error) { goto _output_error; }603if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */604if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */605606/* copy literals */607cpy = op+length;608LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);609if (endOnInput) { /* LZ4_decompress_safe() */610if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }611LZ4_wildCopy32(op, ip, cpy);612} else { /* LZ4_decompress_fast() */613if (cpy>oend-8) { goto safe_literal_copy; }614LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :615* it doesn't know input length, and only relies on end-of-block properties */616}617ip += length; op = cpy;618} else {619cpy = op+length;620if (endOnInput) { /* LZ4_decompress_safe() */621DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);622/* We don't need to check oend, since we check it once for each loop below */623if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }624/* Literals can only be 14, but hope compilers optimize if we copy by a register size */625LZ4_memcpy(op, ip, 16);626} else { /* LZ4_decompress_fast() */627/* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :628* it doesn't know input length, and relies on end-of-block properties */629LZ4_memcpy(op, ip, 8);630if (length > 8) { LZ4_memcpy(op+8, ip+8, 8); }631}632ip += length; op = cpy;633}634635/* get offset */636offset = LZ4_readLE16(ip); ip+=2;637match = op - offset;638assert(match <= op);639640/* get matchlength */641length = token & ML_MASK;642643if (length == ML_MASK) {644variable_length_error error = ok;645if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */646length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);647if (error != ok) { goto _output_error; }648if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */649length += MINMATCH;650if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {651goto safe_match_copy;652}653} else {654length += MINMATCH;655if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {656goto safe_match_copy;657}658659/* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */660if ((dict == withPrefix64k) || (match >= lowPrefix)) {661if (offset >= 8) {662assert(match >= lowPrefix);663assert(match <= op);664assert(op + 18 <= oend);665666LZ4_memcpy(op, match, 8);667LZ4_memcpy(op+8, match+8, 8);668LZ4_memcpy(op+16, match+16, 2);669op += length;670continue;671} } }672673if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */674/* match starting within external dictionary */675if ((dict==usingExtDict) && (match < lowPrefix)) {676if (unlikely(op+length > oend-LASTLITERALS)) {677if (partialDecoding) {678DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");679length = MIN(length, (size_t)(oend-op));680} else {681goto _output_error; /* end-of-block condition violated */682} }683684if (length <= (size_t)(lowPrefix-match)) {685/* match fits entirely within external dictionary : just copy */686memmove(op, dictEnd - (lowPrefix-match), length);687op += length;688} else {689/* match stretches into both external dictionary and current block */690size_t const copySize = (size_t)(lowPrefix - match);691size_t const restSize = length - copySize;692LZ4_memcpy(op, dictEnd - copySize, copySize);693op += copySize;694if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */695BYTE* const endOfMatch = op + restSize;696const BYTE* copyFrom = lowPrefix;697while (op < endOfMatch) { *op++ = *copyFrom++; }698} else {699LZ4_memcpy(op, lowPrefix, restSize);700op += restSize;701} }702continue;703}704705/* copy match within block */706cpy = op + length;707708assert((op <= oend) && (oend-op >= 32));709if (unlikely(offset<16)) {710LZ4_memcpy_using_offset(op, match, cpy, offset);711} else {712LZ4_wildCopy32(op, match, cpy);713}714715op = cpy; /* wildcopy correction */716}717safe_decode:718#endif719720/* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */721while (1) {722token = *ip++;723length = token >> ML_BITS; /* literal length */724725assert(!endOnInput || ip <= iend); /* ip < iend before the increment */726727/* A two-stage shortcut for the most common case:728* 1) If the literal length is 0..14, and there is enough space,729* enter the shortcut and copy 16 bytes on behalf of the literals730* (in the fast mode, only 8 bytes can be safely copied this way).731* 2) Further if the match length is 4..18, copy 18 bytes in a similar732* manner; but we ensure that there's enough space in the output for733* those 18 bytes earlier, upon entering the shortcut (in other words,734* there is a combined check for both stages).735*/736if ( (endOnInput ? length != RUN_MASK : length <= 8)737/* strictly "less than" on input, to re-enter the loop with at least one byte */738&& likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {739/* Copy the literals */740LZ4_memcpy(op, ip, endOnInput ? 16 : 8);741op += length; ip += length;742743/* The second stage: prepare for match copying, decode full info.744* If it doesn't work out, the info won't be wasted. */745length = token & ML_MASK; /* match length */746offset = LZ4_readLE16(ip); ip += 2;747match = op - offset;748assert(match <= op); /* check overflow */749750/* Do not deal with overlapping matches. */751if ( (length != ML_MASK)752&& (offset >= 8)753&& (dict==withPrefix64k || match >= lowPrefix) ) {754/* Copy the match. */755LZ4_memcpy(op + 0, match + 0, 8);756LZ4_memcpy(op + 8, match + 8, 8);757LZ4_memcpy(op +16, match +16, 2);758op += length + MINMATCH;759/* Both stages worked, load the next token. */760continue;761}762763/* The second stage didn't work out, but the info is ready.764* Propel it right to the point of match copying. */765goto _copy_match;766}767768/* decode literal length */769if (length == RUN_MASK) {770variable_length_error error = ok;771length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error);772if (error == initial_error) { goto _output_error; }773if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */774if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */775}776777/* copy literals */778cpy = op+length;779#if LZ4_FAST_DEC_LOOP780safe_literal_copy:781#endif782LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);783if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )784|| ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )785{786/* We've either hit the input parsing restriction or the output parsing restriction.787* In the normal scenario, decoding a full block, it must be the last sequence,788* otherwise it's an error (invalid input or dimensions).789* In partialDecoding scenario, it's necessary to ensure there is no buffer overflow.790*/791if (partialDecoding) {792/* Since we are partial decoding we may be in this block because of the output parsing793* restriction, which is not valid since the output buffer is allowed to be undersized.794*/795assert(endOnInput);796DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end")797DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length);798DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op));799DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip));800/* Finishing in the middle of a literals segment,801* due to lack of input.802*/803if (ip+length > iend) {804length = (size_t)(iend-ip);805cpy = op + length;806}807/* Finishing in the middle of a literals segment,808* due to lack of output space.809*/810if (cpy > oend) {811cpy = oend;812assert(op<=oend);813length = (size_t)(oend-op);814}815} else {816/* We must be on the last sequence because of the parsing limitations so check817* that we exactly regenerate the original size (must be exact when !endOnInput).818*/819if ((!endOnInput) && (cpy != oend)) { goto _output_error; }820/* We must be on the last sequence (or invalid) because of the parsing limitations821* so check that we exactly consume the input and don't overrun the output buffer.822*/823if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) {824DEBUGLOG(6, "should have been last run of literals")825DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);826DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend);827goto _output_error;828}829}830memmove(op, ip, length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */831ip += length;832op += length;833/* Necessarily EOF when !partialDecoding.834* When partialDecoding, it is EOF if we've either835* filled the output buffer or836* can't proceed with reading an offset for following match.837*/838if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) {839break;840}841} else {842LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */843ip += length; op = cpy;844}845846/* get offset */847offset = LZ4_readLE16(ip); ip+=2;848match = op - offset;849850/* get matchlength */851length = token & ML_MASK;852853_copy_match:854if (length == ML_MASK) {855variable_length_error error = ok;856length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);857if (error != ok) goto _output_error;858if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */859}860length += MINMATCH;861862#if LZ4_FAST_DEC_LOOP863safe_match_copy:864#endif865if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */866/* match starting within external dictionary */867if ((dict==usingExtDict) && (match < lowPrefix)) {868if (unlikely(op+length > oend-LASTLITERALS)) {869if (partialDecoding) length = MIN(length, (size_t)(oend-op));870else goto _output_error; /* doesn't respect parsing restriction */871}872873if (length <= (size_t)(lowPrefix-match)) {874/* match fits entirely within external dictionary : just copy */875memmove(op, dictEnd - (lowPrefix-match), length);876op += length;877} else {878/* match stretches into both external dictionary and current block */879size_t const copySize = (size_t)(lowPrefix - match);880size_t const restSize = length - copySize;881LZ4_memcpy(op, dictEnd - copySize, copySize);882op += copySize;883if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */884BYTE* const endOfMatch = op + restSize;885const BYTE* copyFrom = lowPrefix;886while (op < endOfMatch) *op++ = *copyFrom++;887} else {888LZ4_memcpy(op, lowPrefix, restSize);889op += restSize;890} }891continue;892}893assert(match >= lowPrefix);894895/* copy match within block */896cpy = op + length;897898/* partialDecoding : may end anywhere within the block */899assert(op<=oend);900if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {901size_t const mlen = MIN(length, (size_t)(oend-op));902const BYTE* const matchEnd = match + mlen;903BYTE* const copyEnd = op + mlen;904if (matchEnd > op) { /* overlap copy */905while (op < copyEnd) { *op++ = *match++; }906} else {907LZ4_memcpy(op, match, mlen);908}909op = copyEnd;910if (op == oend) { break; }911continue;912}913914if (unlikely(offset<8)) {915LZ4_write32(op, 0); /* silence msan warning when offset==0 */916op[0] = match[0];917op[1] = match[1];918op[2] = match[2];919op[3] = match[3];920match += inc32table[offset];921LZ4_memcpy(op+4, match, 4);922match -= dec64table[offset];923} else {924LZ4_memcpy(op, match, 8);925match += 8;926}927op += 8;928929if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {930BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);931if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */932if (op < oCopyLimit) {933LZ4_wildCopy8(op, match, oCopyLimit);934match += oCopyLimit - op;935op = oCopyLimit;936}937while (op < cpy) { *op++ = *match++; }938} else {939LZ4_memcpy(op, match, 8);940if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); }941}942op = cpy; /* wildcopy correction */943}944945/* end of decoding */946if (endOnInput) {947DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst));948return (int) (((char*)op)-dst); /* Nb of output bytes decoded */949} else {950return (int) (((const char*)ip)-src); /* Nb of input bytes read */951}952953/* Overflow error detected */954_output_error:955return (int) (-(((const char*)ip)-src))-1;956}957}958959/*960* LZ4_uncompress_unknownOutputSize() :961* isize : is the input size, therefore the compressed size962* maxOutputSize : is the size of the destination buffer (which must be963* already allocated)964* return : the number of bytes decoded in the destination buffer965* (necessarily <= maxOutputSize). If the source stream is966* malformed, the function will stop decoding and return a967* negative result, indicating the byte position of the faulty968* instruction. This function never writes beyond dest +969* maxOutputSize, and is therefore protected against malicious970* data packets.971* note : Destination buffer must be already allocated.972* This version is slightly slower than real_LZ4_uncompress()973*974*/975976/*977* Note: In upstream code, LZ4_uncompress_unknownOutputSize is now a legacy978* wrapper for LZ4_decompress_safe which is a wrapper for979* LZ4_decompress_generic; this wrapper flattens that, rather than980* rewriting the callers.981*/982int LZ4_uncompress_unknownOutputSize(const char* source, char* dest, int compressedSize, int maxDecompressedSize)983{984return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,985endOnInputSize, decode_full_block, noDict,986(BYTE*)dest, NULL, 0);987}988989990