diff --git a/docs/news.rst b/docs/news.rst index ff7a4f54..9a7f7494 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -7,6 +7,7 @@ Version History next (not yet released) ======================= +* Bundled zstd library upgraded from 1.5.7 to 1.6.0. * PyO3 Rust crate upgraded from 0.25 to 0.30. Backwards Compatibility Notes diff --git a/tests/test_module_attributes.py b/tests/test_module_attributes.py index a390e1fb..f5457076 100644 --- a/tests/test_module_attributes.py +++ b/tests/test_module_attributes.py @@ -5,7 +5,7 @@ class TestModuleAttributes(unittest.TestCase): def test_version(self): - self.assertEqual(zstd.ZSTD_VERSION, (1, 5, 7)) + self.assertEqual(zstd.ZSTD_VERSION, (1, 6, 0)) self.assertEqual(zstd.__version__, "0.25.0") diff --git a/zstd/zstd.c b/zstd/zstd.c index cdc5194e..ce83d8ce 100644 --- a/zstd/zstd.c +++ b/zstd/zstd.c @@ -337,7 +337,7 @@ int g_debuglevel = DEBUGLEVEL; /* ************************************* * Dependencies ***************************************/ -/**** start inlining mem.h ****/ +/**** start inlining bmi2.h ****/ /* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. @@ -348,28 +348,8 @@ int g_debuglevel = DEBUGLEVEL; * You may select, at your option, one of the above-listed licenses. */ -#ifndef MEM_H_MODULE -#define MEM_H_MODULE - -/*-**************************************** -* Dependencies -******************************************/ -#include /* size_t, ptrdiff_t */ -/**** start inlining compiler.h ****/ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * All rights reserved. - * - * This source code is licensed under both the BSD-style license (found in the - * LICENSE file in the root directory of this source tree) and the GPLv2 (found - * in the COPYING file in the root directory of this source tree). - * You may select, at your option, one of the above-listed licenses. - */ - -#ifndef ZSTD_COMPILER_H -#define ZSTD_COMPILER_H - -#include +#ifndef ZSTD_BMI2_H +#define ZSTD_BMI2_H /**** start inlining portability_macros.h ****/ /* @@ -476,6 +456,18 @@ int g_debuglevel = DEBUGLEVEL; # endif #endif +/* + * The Linux kernel importer consumes the outer guard while preserving the + * distinction below. Normal x86 kernel objects can use the kernel CPU-feature + * policy, while preboot objects cannot use that infrastructure. + */ +#if defined(ZSTD_LINUX_KERNEL) +# if defined(__KERNEL__) && defined(CONFIG_X86) && \ + !defined(__DISABLE_EXPORTS) +# define ZSTD_USE_KERNEL_CPU_FEATURES +# endif +#endif + /** * Only enable assembly for GNU C compatible compilers, * because other platforms may not support GAS assembly syntax. @@ -542,9 +534,90 @@ int g_debuglevel = DEBUGLEVEL; # define ZSTD_CET_ENDBRANCH #endif +/** + * ZSTD_IS_DETERMINISTIC_BUILD must be set to 0 if any compilation macro is + * active that impacts the compressed output. + * + * NOTE: ZSTD_MULTITHREAD is allowed to be set or unset. + */ +#if defined(ZSTD_CLEVEL_DEFAULT) \ + || defined(ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ + || defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) +# define ZSTD_IS_DETERMINISTIC_BUILD 0 +#else +# define ZSTD_IS_DETERMINISTIC_BUILD 1 +#endif + #endif /* ZSTD_PORTABILITY_MACROS_H */ /**** ended inlining portability_macros.h ****/ +#if defined(ZSTD_USE_KERNEL_CPU_FEATURES) +# include +#endif + +/* + * Select between the BMI2 and default implementations at the final dispatch + * site. Integrations may ignore the caller-provided hint and consult their own + * CPU-feature policy instead. + * + * ZSTD_USE_BMI2() may not evaluate its argument. ZSTD_SET_BMI2() may not + * evaluate its value argument, which avoids executing the userspace CPUID + * probe when the integration supplies the dispatch decision. + */ +#if !DYNAMIC_BMI2 +# define ZSTD_USE_BMI2(bmi2) 0 +# define ZSTD_SET_BMI2(state, value) do { } while (0) +#elif defined(ZSTD_USE_KERNEL_CPU_FEATURES) +# define ZSTD_USE_BMI2(bmi2) cpu_feature_enabled(X86_FEATURE_BMI2) +# define ZSTD_SET_BMI2(state, value) do { (state) = 0; } while (0) +#else +# define ZSTD_USE_BMI2(bmi2) (bmi2) +# define ZSTD_SET_BMI2(state, value) do { (state) = (value); } while (0) +#endif + +#endif /* ZSTD_BMI2_H */ +/**** ended inlining bmi2.h ****/ +/**** start inlining mem.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef MEM_H_MODULE +#define MEM_H_MODULE + +/*-**************************************** +* Dependencies +******************************************/ +#include /* size_t, ptrdiff_t */ +/**** start inlining compiler.h ****/ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under both the BSD-style license (found in the + * LICENSE file in the root directory of this source tree) and the GPLv2 (found + * in the COPYING file in the root directory of this source tree). + * You may select, at your option, one of the above-listed licenses. + */ + +#ifndef ZSTD_COMPILER_H +#define ZSTD_COMPILER_H + +#include + +/**** skipping file: portability_macros.h ****/ + /*-******************************************************* * Compiler specifics *********************************************************/ @@ -584,7 +657,7 @@ int g_debuglevel = DEBUGLEVEL; #endif /* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ -#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) +#if defined(__GNUC__) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) /* clang-cl defines __clang__ but not __GNUC__ */ # define UNUSED_ATTR __attribute__((unused)) #else # define UNUSED_ATTR @@ -628,9 +701,9 @@ int g_debuglevel = DEBUGLEVEL; #elif defined(__IAR_SYSTEMS_ICC__) # define MEM_STATIC static inline UNUSED_ATTR #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define MEM_STATIC static inline +# define MEM_STATIC static inline UNUSED_ATTR #elif defined(_MSC_VER) -# define MEM_STATIC static __inline +# define MEM_STATIC static __inline UNUSED_ATTR #else # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ #endif @@ -662,6 +735,10 @@ int g_debuglevel = DEBUGLEVEL; #define BMI2_TARGET_ATTRIBUTE TARGET_ATTRIBUTE("lzcnt,bmi,bmi2") /* prefetch + * PREFETCH_L1(ptr) / PREFETCH_L2(ptr) take a `const void*`. + * `ptr` is only used as an address hint: it may point anywhere, + * including invalid or out-of-bounds memory, and is never accessed. + * Each variant below must therefore accept a `const void*` argument. * can be disabled, by declaring NO_PREFETCH build macro */ #if defined(NO_PREFETCH) # define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */ @@ -675,8 +752,12 @@ int g_debuglevel = DEBUGLEVEL; # define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */) # define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */) # elif defined(__aarch64__) -# define PREFETCH_L1(ptr) do { __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr))); } while (0) -# define PREFETCH_L2(ptr) do { __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr))); } while (0) + /* The "Q" operand needs an lvalue, so cast to `const char*` before + * dereferencing: dereferencing a `const void*` is ill-formed in C + * (-Wvoid-ptr-dereference). The `prfm` instruction is only a hint and + * never faults, whatever the address. */ +# define PREFETCH_L1(ptr) do { __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(const char*)(ptr))); } while (0) +# define PREFETCH_L2(ptr) do { __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(const char*)(ptr))); } while (0) # else # define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */ # define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */ @@ -748,6 +829,18 @@ int g_debuglevel = DEBUGLEVEL; # if defined(__ARM_NEON) || defined(_M_ARM64) # define ZSTD_ARCH_ARM_NEON # endif +# if defined(__ARM_FEATURE_SVE) +# define ZSTD_ARCH_ARM_SVE +# endif +# if defined(__ARM_FEATURE_SVE2) +# define ZSTD_ARCH_ARM_SVE2 +# endif +# if defined(__riscv) && defined(__riscv_vector) +# if ((defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14) || \ + (defined(__clang__) && __clang_major__ >= 19)) + #define ZSTD_ARCH_RISCV_RVV +# endif +#endif # # if defined(ZSTD_ARCH_X86_AVX2) # include @@ -757,6 +850,12 @@ int g_debuglevel = DEBUGLEVEL; # elif defined(ZSTD_ARCH_ARM_NEON) # include # endif +# if defined(ZSTD_ARCH_ARM_SVE) || defined(ZSTD_ARCH_ARM_SVE2) +# include +# endif +# if defined(ZSTD_ARCH_RISCV_RVV) +# include +# endif #endif /* C-language Attributes are added in C23. */ @@ -887,9 +986,9 @@ ptrdiff_t ZSTD_wrappedPtrDiff(unsigned char const* lhs, unsigned char const* rhs */ MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add) +const void* ZSTD_wrappedPtrAdd(const void* ptr, ptrdiff_t add) { - return ptr + add; + return (const char*)ptr + add; } /** @@ -900,9 +999,9 @@ unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add) */ MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub) +const void* ZSTD_wrappedPtrSub(const void* ptr, ptrdiff_t sub) { - return ptr - sub; + return (const char*)ptr - sub; } /** @@ -912,9 +1011,9 @@ unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub) * @returns `ptr + add` except it defines `NULL + 0 == NULL`. */ MEM_STATIC -unsigned char* ZSTD_maybeNullPtrAdd(unsigned char* ptr, ptrdiff_t add) +void* ZSTD_maybeNullPtrAdd(void* ptr, ptrdiff_t add) { - return add > 0 ? ptr + add : ptr; + return add > 0 ? (char*)ptr + add : ptr; } /* Issue #3240 reports an ASAN failure on an llvm-mingw build. Out of an @@ -1950,7 +2049,7 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros32_fallback(U32 val) 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; - return DeBruijnBytePos[((U32) ((val & -(S32) val) * 0x077CB531U)) >> 27]; + return DeBruijnBytePos[((U32) ((val & (0-val)) * 0x077CB531U)) >> 27]; } } @@ -2207,8 +2306,8 @@ typedef enum { BIT_DStream_unfinished = 0, /* fully refilled */ } BIT_DStream_status; /* result of BIT_reloadDStream() */ MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize); -MEM_STATIC BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); -MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); +FORCE_INLINE_TEMPLATE BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); +FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); @@ -2537,7 +2636,7 @@ FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) /* start < ptr < limitPtr => cautious update */ { U32 nbBytes = bitD->bitsConsumed >> 3; BIT_DStream_status result = BIT_DStream_unfinished; - if (bitD->ptr - nbBytes < bitD->start) { + if (nbBytes > (size_t)(bitD->ptr - bitD->start)) { nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */ result = BIT_DStream_endOfBuffer; } @@ -3415,17 +3514,17 @@ BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2( { return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); } +#else +#define FSE_readNCount_body_bmi2 FSE_readNCount_body_default #endif size_t FSE_readNCount_bmi2( short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, const void* headerBuffer, size_t hbSize, int bmi2) { -#if DYNAMIC_BMI2 - if (bmi2) { + if (ZSTD_USE_BMI2(bmi2)) { return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); } -#endif (void)bmi2; return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize); } @@ -3536,6 +3635,8 @@ static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, si { return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1); } +#else +#define HUF_readStats_body_bmi2 HUF_readStats_body_default #endif size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats, @@ -3544,11 +3645,9 @@ size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats, void* workSpace, size_t wkspSize, int flags) { -#if DYNAMIC_BMI2 - if (flags & HUF_flags_bmi2) { + if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) { return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize); } -#endif (void)flags; return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize); } @@ -3640,6 +3739,7 @@ const char* ERR_getErrorString(ERR_enum code) ****************************************************************/ /**** skipping file: debug.h ****/ /**** skipping file: bitstream.h ****/ +/**** skipping file: bmi2.h ****/ /**** skipping file: compiler.h ****/ #define FSE_STATIC_LINKING_ONLY /**** skipping file: fse.h ****/ @@ -3921,15 +4021,15 @@ BMI2_TARGET_ATTRIBUTE static size_t FSE_decompress_wksp_body_bmi2(void* dst, siz { return FSE_decompress_wksp_body(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize, 1); } +#else +#define FSE_decompress_wksp_body_bmi2 FSE_decompress_wksp_body_default #endif size_t FSE_decompress_wksp_bmi2(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, unsigned maxLog, void* workSpace, size_t wkspSize, int bmi2) { -#if DYNAMIC_BMI2 - if (bmi2) { + if (ZSTD_USE_BMI2(bmi2)) { return FSE_decompress_wksp_body_bmi2(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize); } -#endif (void)bmi2; return FSE_decompress_wksp_body_default(dst, dstCapacity, cSrc, cSrcSize, maxLog, workSpace, wkspSize); } @@ -4225,7 +4325,14 @@ int ZSTD_pthread_mutex_init(ZSTD_pthread_mutex_t* mutex, pthread_mutexattr_t con *mutex = (pthread_mutex_t*)ZSTD_malloc(sizeof(pthread_mutex_t)); if (!*mutex) return 1; - return pthread_mutex_init(*mutex, attr); + { + int const ret = pthread_mutex_init(*mutex, attr); + if (ret != 0) { + ZSTD_free(*mutex); + *mutex = NULL; + } + return ret; + } } int ZSTD_pthread_mutex_destroy(ZSTD_pthread_mutex_t* mutex) @@ -4246,7 +4353,14 @@ int ZSTD_pthread_cond_init(ZSTD_pthread_cond_t* cond, pthread_condattr_t const* *cond = (pthread_cond_t*)ZSTD_malloc(sizeof(pthread_cond_t)); if (!*cond) return 1; - return pthread_cond_init(*cond, attr); + { + int const ret = pthread_cond_init(*cond, attr); + if (ret != 0) { + ZSTD_free(*cond); + *cond = NULL; + } + return ret; + } } int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond) @@ -4408,8 +4522,8 @@ extern "C" { /*------ Version ------*/ #define ZSTD_VERSION_MAJOR 1 -#define ZSTD_VERSION_MINOR 5 -#define ZSTD_VERSION_RELEASE 7 +#define ZSTD_VERSION_MINOR 6 +#define ZSTD_VERSION_RELEASE 0 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) /*! ZSTD_versionNumber() : @@ -4474,30 +4588,30 @@ ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, /*====== Decompression helper functions ======*/ -/*! ZSTD_getFrameContentSize() : requires v1.3.0+ - * `src` should point to the start of a ZSTD encoded frame. - * `srcSize` must be at least as large as the frame header. - * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. - * @return : - decompressed size of `src` frame content, if known - * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined - * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) - * note 1 : a 0 return value means the frame is valid but "empty". - * When invoking this method on a skippable frame, it will return 0. - * note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode). - * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. - * In which case, it's necessary to use streaming mode to decompress data. - * Optionally, application can rely on some implicit limit, - * as ZSTD_decompress() only needs an upper bound of decompressed size. - * (For example, data could be necessarily cut into blocks <= 16 KB). - * note 3 : decompressed size is always present when compression is completed using single-pass functions, - * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). - * note 4 : decompressed size can be very large (64-bits value), - * potentially larger than what local system can handle as a single memory segment. - * In which case, it's necessary to use streaming mode to decompress data. - * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. - * Always ensure return value fits within application's authorized limits. - * Each application can set its own limits. - * note 6 : This function replaces ZSTD_getDecompressedSize() */ +/*! @brief Returns the decompressed content size stored in a ZSTD frame header. + * + * @since v1.3.0 + * + * @param src Pointer to the beginning of a ZSTD encoded frame. + * @param srcSize Size of the buffer pointed to by @p src. It must be at least as large as the frame header. + * Any value greater than or equal to `ZSTD_frameHeaderSize_max` is sufficient. + * @return The decompressed size in bytes when the value is available in the frame header. + * @retval ZSTD_CONTENTSIZE_UNKNOWN The frame does not encode a decompressed size (typical for streaming). + * @retval ZSTD_CONTENTSIZE_ERROR An error occurred (e.g. invalid magic number, @p srcSize too small). + * + * @note The return value is not compatible with `ZSTD_isError()`. + * @note A return value of 0 denotes a valid but empty frame. Skippable frames also report 0. + * @note The decompressed size field is optional. When it is absent (the function returns @c ZSTD_CONTENTSIZE_UNKNOWN), + * the caller must rely on streaming decompression or an application-specific upper bound. `ZSTD_decompress()` + * only requires an upper bound, so applications may enforce their own block limits (for example 16 KB). + * @note The decompressed size is guaranteed to be present when compression was performed with single-pass APIs such as + * `ZSTD_compress()`, `ZSTD_compressCCtx()`, `ZSTD_compress_usingDict()`, or `ZSTD_compress_usingCDict()`. + * @note The decompressed size is a 64-bit value and may exceed the addressable space of the system. Use streaming + * decompression when the value is too large to materialize in contiguous memory. + * @warning When processing untrusted input, validate the returned size against the application's limits; attackers may + * forge an arbitrarily large value. + * @note This function replaces `ZSTD_getDecompressedSize()`. + */ #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); @@ -4524,6 +4638,28 @@ ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t * which is always equal to its content size + 8 bytes for headers. */ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); +typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; +#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ +typedef struct { + unsigned long long frameContentSize; /**< if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ + unsigned long long windowSize; /**< can be very large, up to <= frameContentSize */ + unsigned blockSizeMax; + ZSTD_FrameType_e frameType; /**< if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ + unsigned headerSize; + unsigned dictID; /**< for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ + unsigned checksumFlag; + unsigned _reserved1; + unsigned _reserved2; +} ZSTD_FrameHeader; +#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ + +/*! ZSTD_getFrameHeader() : Requires v1.6.0+ + * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. + * @return : 0 => header is complete, `zfhPtr` is correctly filled, + * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, + * or an error code, which can be tested using ZSTD_isError() */ +ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); + /*====== Compression helper functions ======*/ @@ -4606,6 +4742,9 @@ ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer * * Same as ZSTD_decompress(), * requires an allocated ZSTD_DCtx. * Compatible with sticky parameters (see below). + * The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). + * See ZSTD_DCtx_refPrefix() for the effect on a referenced prefix. */ ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, @@ -4895,6 +5034,7 @@ typedef enum { * - The session : will stop compressing current frame, and make CCtx ready to start a new one. * Useful after an error, or to interrupt any ongoing compression. * Any internal data not yet flushed is cancelled. + * With nbWorkers >= 1, it waits for the jobs already started to complete. * Compression parameters and dictionary remain unchanged. * They will be used to compress next frame. * Resetting session never fails. @@ -4986,7 +5126,11 @@ ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param /*! ZSTD_DCtx_reset() : * Return a DCtx to clean state. * Session and parameters can be reset jointly or separately. - * Parameters can only be reset when no active frame is being decompressed. + * ZSTD_reset_parameters can only be used when no frame is being decompressed; + * otherwise it returns ZSTD_error_stage_wrong without resetting the parameters. + * ZSTD_reset_session_and_parameters also abandons any active frame. + * A successful parameter reset discards any referenced prefix or dictionary. + * See ZSTD_DCtx_refPrefix() for the effect of a session-only reset on a prefix. * @return : 0, or an error code, which can be tested with ZSTD_isError() */ ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); @@ -5240,8 +5384,11 @@ ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); * Note: when an operation returns with an error code, the @zds state may be left in undefined state. * It's UB to invoke `ZSTD_decompressStream()` on such a state. * In order to re-use such a state, it must be first reset, - * which can be done explicitly (`ZSTD_DCtx_reset()`), - * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) + * which can be done explicitly (`ZSTD_DCtx_reset(zds, ZSTD_reset_session_only)`), + * or is implied for operations starting some new decompression job + * (`ZSTD_initDStream()`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`, `ZSTD_decompress_usingDDict()`). + * The single-shot functions also leave the session clean: + * streaming can start a new frame afterwards without an explicit reset. */ ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); @@ -5270,7 +5417,9 @@ ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, * Dictionary must be identical to the one used during compression. * Note : This function loads the dictionary, resulting in significant startup delay. * It's intended for a dictionary used only once. - * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ + * Note : When `dict == NULL || dictSize < 8` no dictionary is used. + * Note : The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). */ ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, @@ -5320,6 +5469,13 @@ typedef struct ZSTD_DDict_s ZSTD_DDict; * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); +/*! ZSTD_createDDict_byReference() : Requires v1.6.0+ + * Create a digested dictionary, ready to start decompression operation without startup delay. + * Dictionary content is referenced, and therefore stays in dictBuffer. + * It is important that dictBuffer outlives DDict, + * it must remain read accessible throughout the lifetime of DDict */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); + /*! ZSTD_freeDDict() : * Function frees memory allocated with ZSTD_createDDict() * If a NULL pointer is passed, no operation is performed. */ @@ -5327,7 +5483,10 @@ ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); /*! ZSTD_decompress_usingDDict() : * Decompression using a digested Dictionary. - * Recommended when same dictionary is used multiple times. */ + * Recommended when same dictionary is used multiple times. + * Uses the supplied DDict, regardless of dictionaries referenced in dctx. + * The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). */ ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, @@ -5405,6 +5564,23 @@ ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); */ ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); +typedef enum { + ZSTD_dct_auto = 0, /**< dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ + ZSTD_dct_rawContent = 1, /**< ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ + ZSTD_dct_fullDict = 2 /**< refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ +} ZSTD_dictContentType_e; + +typedef enum { + ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ + ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ +} ZSTD_dictLoadMethod_e; + +/*! ZSTD_CCtx_loadDictionary_advanced() : Requires v1.6.0+ + * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + /*! ZSTD_CCtx_refCDict() : Requires v1.4.0+ * Reference a prepared dictionary, to be used for all future compressed frames. * Note that compression parameters are enforced from within CDict, @@ -5448,6 +5624,8 @@ ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, * @result : 0, or an error code (which can be tested with ZSTD_isError()). * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, * meaning "return to no-dictionary mode". + * Loading any dictionary also discards the multiple-DDict reference table, + * without disabling ZSTD_d_refMultipleDDicts. * Note 1 : Loading a dictionary involves building tables, * which has a non-negligible impact on CPU usage and latency. * It's recommended to "load once, use many times", to amortize the cost @@ -5458,15 +5636,29 @@ ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, */ ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); +/*! ZSTD_DCtx_loadDictionary_advanced() : Requires v1.6.0+ + * Same as ZSTD_DCtx_loadDictionary(), + * but gives direct control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + /*! ZSTD_DCtx_refDDict() : Requires v1.4.0+ * Reference a prepared dictionary, to be used to decompress next frames. - * The dictionary remains active for decompression of future frames using same DCtx. + * In single-DDict mode, the dictionary remains active for decompression of + * future frames using the same DCtx. * * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function * will store the DDict references in a table, and the DDict used for decompression * will be determined at decompression time, as per the dict ID in the frame. - * The memory for the table is allocated on the first call to refDDict, and can be - * freed with ZSTD_freeDCtx(). + * The memory for the table is allocated on the first call to refDDict. + * The table is freed by ZSTD_DCtx_refDDict(dctx, NULL), by ZSTD_DCtx_reset() + * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters, by any + * ZSTD_DCtx_loadDictionary() or ZSTD_DCtx_refPrefix() call, by disabling + * multiple-DDict mode, and by ZSTD_freeDCtx(). + * Disabling multiple-DDict mode releases all dictionary references from the set; + * no dictionary from the set is retained for subsequent decompression. + * Referencing a DDict invalidates any previously loaded dictionary or prefix. * * If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary * will be managed, and referencing a dictionary effectively "discards" any previous one. @@ -5478,18 +5670,40 @@ ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, s ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); /*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+ - * Reference a prefix (single-usage dictionary) to decompress next frame. + * Reference a prefix (single-usage dictionary) for decompression. * This is the reverse operation of ZSTD_CCtx_refPrefix(), * and must use the same prefix as the one used during compression. - * Prefix is **only used once**. Reference is discarded at end of frame. - * End of frame is reached when ZSTD_decompressStream() returns 0. + * The prefix is **only used once**: + * - ZSTD_decompressDCtx() uses it for exactly one call, including all frames + * in concatenated input. The call consumes the prefix even if the input + * is empty, contains only skippable frames, or produces an error. + * - ZSTD_decompressStream() uses it until the first frame is completely + * decoded and flushed, as indicated by a return value of 0. This includes + * empty and skippable frames, even though they produce no output. + * The explicit-dictionary functions ZSTD_decompress_usingDict() and + * ZSTD_decompress_usingDDict() use their dictionary argument instead and + * do not consume the prefix configured on the DCtx. + * + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) preserves an unused prefix + * if streaming decompression has not started. Once streaming has started, + * even with an incomplete header, a session-only reset abandons the frame + * and discards the prefix. After a streaming error the DCtx may be in an + * undefined state and must be reset before streaming can resume. Errors + * returned before streaming starts may leave an unused prefix installed. + * To unconditionally discard it, use ZSTD_reset_session_and_parameters, + * or ZSTD_reset_parameters when no frame is active. The latter can fail + * with ZSTD_error_stage_wrong during decompression. * @result : 0, or an error code (which can be tested with ZSTD_isError()). - * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary + * Note 1 : Adding any prefix (including NULL or a zero-sized prefix) invalidates + * any previously set prefix or dictionary, + * including the multiple-DDict reference table. + * Successfully loading or referencing another dictionary, or calling + * ZSTD_initDStream(), also discards the prefix. * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. - * Prefix buffer must remain unmodified up to the end of frame, - * reached when ZSTD_decompressStream() returns 0. + * It must remain unmodified until the one-shot call returns, the + * streaming frame completes, or the prefix is explicitly discarded. * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). - * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) + * Use ZSTD_DCtx_refPrefix_advanced() to alter dictMode (Experimental section) * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. * A full dictionary is more costly, as it requires building tables. */ @@ -5668,17 +5882,6 @@ typedef struct { ZSTD_frameParameters fParams; } ZSTD_parameters; -typedef enum { - ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ - ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ - ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ -} ZSTD_dictContentType_e; - -typedef enum { - ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ - ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ -} ZSTD_dictLoadMethod_e; - typedef enum { ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. @@ -5791,9 +5994,10 @@ ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, * @return : - upper-bound for the decompressed size of all data in all successive frames * - if an error occurred: ZSTD_CONTENTSIZE_ERROR * - * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. + * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame, + * or the bound exceeds the largest returnable value, ZSTD_CONTENTSIZE_ERROR - 1. * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. - * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. + * When this exact size is representable, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: * upper-bound = # blocks * min(128 KB, Window_Size) */ @@ -5805,27 +6009,6 @@ ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size * or an error code (if srcSize is too small) */ ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); -typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; -#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ -typedef struct { - unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ - unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ - unsigned blockSizeMax; - ZSTD_FrameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ - unsigned headerSize; - unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ - unsigned checksumFlag; - unsigned _reserved1; - unsigned _reserved2; -} ZSTD_FrameHeader; -#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ - -/*! ZSTD_getFrameHeader() : - * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. - * @return : 0 => header is complete, `zfhPtr` is correctly filled, - * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, - * or an error code, which can be tested using ZSTD_isError() */ -ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); /*! ZSTD_getFrameHeader_advanced() : * same as ZSTD_getFrameHeader(), * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ @@ -5997,6 +6180,8 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * - @litBufCapacity is the size of the underlying buffer into which literals are written, starting at address @literals. * @litBufCapacity must be at least 8 bytes larger than @litSize. * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. + * - Each block must regenerate at most ZSTD_BLOCKSIZE_MAX bytes, or less with a smaller window or ZSTD_c_maxBlockSize. + * A larger block will generate an error. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t @@ -6111,6 +6296,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, si /*! ZSTD_estimate?DictSize() : * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). + * These estimates return an error code if dictSize is too large. + * Check the result with ZSTD_isError(). * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. */ ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); @@ -6134,7 +6321,10 @@ ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadM * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level * into its associated cParams. * Limitation 1 : currently not compatible with internal dictionary creation, triggered by - * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * ZSTD_CCtx_loadDictionary(), ZSTD_DCtx_loadDictionary(), ZSTD_DCtx_refPrefix(), + * ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * For one-shot decompression, ZSTD_decompress_usingDict() needs no allocation. + * Otherwise, use ZSTD_initStaticDDict() + ZSTD_DCtx_refDDict(). * Limitation 2 : static cctx currently not compatible with multi-threading. * Limitation 3 : static dctx is incompatible with legacy support. */ @@ -6166,15 +6356,14 @@ ZSTDLIB_STATIC_API const ZSTD_DDict* ZSTD_initStaticDDict( typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); typedef void (*ZSTD_freeFunction) (void* opaque, void* address); typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; -static -#ifdef __GNUC__ -__attribute__((__unused__)) -#endif - #if defined(__clang__) && __clang_major__ >= 5 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif +static +#ifdef __GNUC__ +__attribute__((__unused__)) +#endif ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ #if defined(__clang__) && __clang_major__ >= 5 #pragma clang diagnostic pop @@ -6196,9 +6385,10 @@ ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_ * This can limit resources for applications with multiple threads where each one uses * a threaded compression mode (via ZSTD_c_nbWorkers parameter). * ZSTD_createThreadPool creates a new thread pool with a given number of threads. + * ZSTD_c_nbWorkers does not change the number of threads of such a pool. * Note that the lifetime of such pool must exist while being used. * ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value - * to use an internal thread pool). + * to use an internal thread pool). The context then no longer uses its previous pool. * ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer. */ typedef struct POOL_ctx_s ZSTD_threadPool; @@ -6310,12 +6500,6 @@ size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); -/*! ZSTD_CCtx_loadDictionary_advanced() : - * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over - * how to load the dictionary (by copy ? by reference ?) - * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ -ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); - /*! ZSTD_CCtx_refPrefix_advanced() : * Same as ZSTD_CCtx_refPrefix(), but gives finer control over * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ @@ -6750,13 +6934,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs ( * Note 3 : Skippable Frame Identifiers are considered valid. */ ZSTDLIB_STATIC_API unsigned ZSTD_isFrame(const void* buffer, size_t size); -/*! ZSTD_createDDict_byReference() : - * Create a digested dictionary, ready to start decompression operation without startup delay. - * Dictionary content is referenced, and therefore stays in dictBuffer. - * It is important that dictBuffer outlives DDict, - * it must remain read accessible throughout the lifetime of DDict */ -ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); - /*! ZSTD_DCtx_loadDictionary_byReference() : * Same as ZSTD_DCtx_loadDictionary(), * but references `dict` content instead of copying it into `dctx`. @@ -6764,16 +6941,11 @@ ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuff * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); -/*! ZSTD_DCtx_loadDictionary_advanced() : - * Same as ZSTD_DCtx_loadDictionary(), - * but gives direct control over - * how to load the dictionary (by copy ? by reference ?) - * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ -ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); - /*! ZSTD_DCtx_refPrefix_advanced() : * Same as ZSTD_DCtx_refPrefix(), but gives finer control over - * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?). + * The prefix has the same single-use lifetime and reset behavior described + * by ZSTD_DCtx_refPrefix(). */ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); /*! ZSTD_DCtx_setMaxWindowSize() : @@ -6848,7 +7020,22 @@ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParamete * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict() * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead * store all references. At decompression time, the appropriate dictID is selected - * from the set of DDicts based on the dictID in the frame. + * from the set of DDicts based on the dictID in each frame. This applies to + * ZSTD_decompressDCtx() and ZSTD_decompressStream(); entry points taking an + * explicit dictionary use that dictionary instead. + * When a set exists, an ordinary Zstandard frame with a nonzero dictionary ID must + * have an exact match in the set; otherwise decompression returns + * ZSTD_error_dictionary_wrong. A frame with dictionary ID 0 (including an omitted + * ID) uses the registered ID-0 DDict if present, or no dictionary otherwise. + * There is no default dictionary in the set, and a lookup does not change the + * dictionary used by another frame. + * Skippable frames do not select a dictionary. Legacy formats are not supported + * by set-based decoding; use a single or explicitly supplied dictionary instead. + * Loading a dictionary or referencing a prefix discards the referenced set, + * without disabling this mode. Referencing a DDict discards any previously + * loaded dictionary or prefix. The two kinds of dictionary storage cannot coexist. + * Disabling this mode discards the entire set. No dictionary from the set is + * retained for subsequent decompression. * * Usage is simply calling ZSTD_refDDict() on multiple dict buffers. * @@ -7328,10 +7515,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const vo ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ -ZSTD_DEPRECATED("This function will likely be removed in a future release. It is misleading and has very limited utility.") -ZSTDLIB_STATIC_API -size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ - ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") ZSTDLIB_STATIC_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") @@ -7388,8 +7571,12 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ as long as the encoder and decoder progress in "lock-step", aka use exactly the same buffer sizes, break contiguity at the same place, etc. - Once buffers are setup, start decompression, with ZSTD_decompressBegin(). + Once buffers are set up and decompression parameters are configured, initialize the decoder with ZSTD_decompressBegin(). If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). + One of these initialization functions must be called before the first ZSTD_decompressContinue() call for every frame, + including when reusing a context or after calling ZSTD_DCtx_reset(). + ZSTD_DCtx_reset() does not replace this initialization, and ZSTD_decompressContinue() does not initialize the decoder itself. + After a session reset, an interrupted frame cannot be resumed : initialize the decoder again and restart from the frame's beginning. Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). @@ -7400,7 +7587,7 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ It can also be an error code, which can be tested with ZSTD_isError(). A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. - Context can then be reset to start a new decompression. + Before decoding another frame, call the appropriate ZSTD_decompressBegin*() function again. Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). This information is not required to properly decode a frame. @@ -7421,21 +7608,45 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ +/*! ZSTD_decompressBegin() : + * Initialize the bufferless decoder to start a new frame without a dictionary. + * Decompression parameters must be configured before calling this function. + * Call this function, ZSTD_decompressBegin_usingDict(), or ZSTD_decompressBegin_usingDDict() + * before the first ZSTD_decompressContinue() call for each frame, including after ZSTD_DCtx_reset(). + * Use the dictionary-taking variants when the frame requires a dictionary. + */ ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); + +/*! ZSTD_decompressContinue() : + * Decode the next part of a frame initialized with ZSTD_decompressBegin() + * or one of its dictionary-taking variants. This function does not initialize the decoder. + * After finishing a frame or resetting the session, initialize the decoder again + * before calling this function for a new frame. + */ ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); /* misc */ -ZSTD_DEPRECATED("This function will likely be removed in the next minor release. It is misleading and has very limited utility.") -ZSTDLIB_STATIC_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); +/*! ZSTD_isDeterministicBuild() : + * Returns 1 if the library is built using standard compilation flags, + * and participates in determinism guarantees with other builds of the + * same version. + * If this function returns 0, it means the library was compiled with + * non-standard compilation flags that change the output of the + * compressor. + * This is mainly used for Zstd's determinism test suite, which is only + * run when this function returns 1. + */ +ZSTDLIB_API int ZSTD_isDeterministicBuild(void); + /* ========================================= */ /** Block level API (DEPRECATED) */ @@ -7511,9 +7722,13 @@ MEM_STATIC void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem) MEM_STATIC void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem) { if (customMem.customAlloc) { - /* calloc implemented as malloc+memset; - * not as efficient as calloc, but next best guess for custom malloc */ + /* calloc implemented as malloc+memset */ void* const ptr = customMem.customAlloc(customMem.opaque, size); + + if (ptr == NULL) { + return NULL; + } + ZSTD_memset(ptr, 0, size); return ptr; } @@ -7745,19 +7960,17 @@ POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize, /* Allocate space for the thread handles */ ctx->threads = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), customMem); ctx->threadCapacity = 0; + ctx->threadLimit = numThreads; ctx->customMem = customMem; /* Check for errors */ if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; } /* Initialize the threads */ - { size_t i; - for (i = 0; i < numThreads; ++i) { - if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) { - ctx->threadCapacity = i; - POOL_free(ctx); - return NULL; - } } - ctx->threadCapacity = numThreads; - ctx->threadLimit = numThreads; + while (ctx->threadCapacity < numThreads) { + if (ZSTD_pthread_create(&ctx->threads[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) { + --ctx->threadCapacity; + POOL_free(ctx); + return NULL; + } } return ctx; } @@ -7823,23 +8036,22 @@ static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads) return 0; } /* numThreads > threadCapacity */ + ctx->threadLimit = numThreads; { ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem); if (!threadPool) return 1; - /* replace existing thread pool */ + /* extend existing thread pool */ ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t)); ZSTD_customFree(ctx->threads, ctx->customMem); ctx->threads = threadPool; /* Initialize additional threads */ - { size_t threadId; - for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) { - if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) { - ctx->threadCapacity = threadId; - return 1; - } } - } } + while (ctx->threadCapacity < numThreads) { + if (ZSTD_pthread_create(&threadPool[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) { + --ctx->threadCapacity; + return 1; + } + } + } /* successfully expanded */ - ctx->threadCapacity = numThreads; - ctx->threadLimit = numThreads; return 0; } @@ -15664,7 +15876,7 @@ static UNUSED_ATTR const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG; * Shared functions to include for inlining *********************************************/ static void ZSTD_copy8(void* dst, const void* src) { -#if defined(ZSTD_ARCH_ARM_NEON) +#if defined(ZSTD_ARCH_ARM_NEON) && !defined(__aarch64__) vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src)); #else ZSTD_memcpy(dst, src, 8); @@ -15681,6 +15893,8 @@ static void ZSTD_copy16(void* dst, const void* src) { vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src)); #elif defined(ZSTD_ARCH_X86_SSE2) _mm_storeu_si128((__m128i*)dst, _mm_loadu_si128((const __m128i*)src)); +#elif defined(ZSTD_ARCH_RISCV_RVV) + __riscv_vse8_v_u8m1((uint8_t*)dst, __riscv_vle8_v_u8m1((const uint8_t*)src, 16), 16); #elif defined(__clang__) ZSTD_memmove(dst, src, 16); #else @@ -15709,7 +15923,7 @@ typedef enum { * The src buffer must be before the dst buffer. */ MEM_STATIC FORCE_INLINE_ATTR -void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype) +void ZSTD_wildcopy(void* dst, const void* src, size_t length, ZSTD_overlap_e const ovtype) { ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src; const BYTE* ip = (const BYTE*)src; @@ -15849,6 +16063,15 @@ ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); } /*! ZSTD_getErrorString() : * provides error code string from enum */ const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); } + +int ZSTD_isDeterministicBuild(void) +{ +#if ZSTD_IS_DETERMINISTIC_BUILD + return 1; +#else + return 0; +#endif +} /**** ended inlining common/zstd_common.c ****/ /**** start inlining compress/fse_compress.c ****/ @@ -15910,7 +16133,11 @@ unsigned HIST_isError(size_t code); /**< tells if a return value is an error co /* --- advanced histogram functions --- */ +#if defined(__ARM_FEATURE_SVE2) +#define HIST_WKSP_SIZE_U32 0 +#else #define HIST_WKSP_SIZE_U32 1024 +#endif #define HIST_WKSP_SIZE (HIST_WKSP_SIZE_U32 * sizeof(unsigned)) /** HIST_count_wksp() : * Same as HIST_count(), but using an externally provided scratch buffer. @@ -16583,6 +16810,12 @@ size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); } /**** skipping file: ../common/error_private.h ****/ /**** skipping file: hist.h ****/ +#if defined(ZSTD_ARCH_ARM_SVE2) +#define HIST_FAST_THRESHOLD 500 +#else +#define HIST_FAST_THRESHOLD 1500 +#endif + /* --- Error management --- */ unsigned HIST_isError(size_t code) { return ERR_isError(code); } @@ -16629,6 +16862,286 @@ unsigned HIST_count_simple(unsigned* count, unsigned* maxSymbolValuePtr, typedef enum { trustInput, checkMaxSymbolValue } HIST_checkInput_e; +#if defined(ZSTD_ARCH_ARM_SVE2) +/* U16 counters must hold even an all-identical chunk. Round the limit down + * to 16 bytes so zero-padding the final vector cannot overflow them. */ +#define HIST_SVE2_MAX_CHUNK_SIZE ((1U << 16) - 16) +FORCE_INLINE_TEMPLATE size_t min_size(size_t a, size_t b) { return a < b ? a : b; } + +static +svuint16_t HIST_count_6_sve2(const BYTE* const src, size_t size, U32* const dst, + const svuint8_t c0, const svuint8_t c1, + const svuint8_t c2, const svuint8_t c3, + const svuint8_t c4, const svuint8_t c5, + const svuint16_t histmax, size_t maxCount) +{ + const svbool_t vl128 = svptrue_pat_b8(SV_VL16); + svuint16_t hh0 = svdup_n_u16(0); + svuint16_t hh1 = svdup_n_u16(0); + svuint16_t hh2 = svdup_n_u16(0); + svuint16_t hh3 = svdup_n_u16(0); + svuint16_t hh4 = svdup_n_u16(0); + svuint16_t hh5 = svdup_n_u16(0); + svuint16_t hh6 = svdup_n_u16(0); + svuint16_t hh7 = svdup_n_u16(0); + svuint16_t hh8 = svdup_n_u16(0); + svuint16_t hh9 = svdup_n_u16(0); + svuint16_t hha = svdup_n_u16(0); + svuint16_t hhb = svdup_n_u16(0); + + size_t i = 0; + while (i < size) { + /* We can only accumulate 15 (15 * 16 <= 255) iterations of histogram + * in 8-bit accumulators! */ + const size_t size240 = min_size(i + 240, size); + + svbool_t pred = svwhilelt_b8_u64(i, size); + svuint8_t c = svld1rq_u8(pred, src + i); + svuint8_t h0 = svhistseg_u8(c0, c); + svuint8_t h1 = svhistseg_u8(c1, c); + svuint8_t h2 = svhistseg_u8(c2, c); + svuint8_t h3 = svhistseg_u8(c3, c); + svuint8_t h4 = svhistseg_u8(c4, c); + svuint8_t h5 = svhistseg_u8(c5, c); + + for (i += 16; i < size240; i += 16) { + pred = svwhilelt_b8_u64(i, size); + c = svld1rq_u8(pred, src + i); + h0 = svadd_u8_x(vl128, h0, svhistseg_u8(c0, c)); + h1 = svadd_u8_x(vl128, h1, svhistseg_u8(c1, c)); + h2 = svadd_u8_x(vl128, h2, svhistseg_u8(c2, c)); + h3 = svadd_u8_x(vl128, h3, svhistseg_u8(c3, c)); + h4 = svadd_u8_x(vl128, h4, svhistseg_u8(c4, c)); + h5 = svadd_u8_x(vl128, h5, svhistseg_u8(c5, c)); + } + + hh0 = svaddwb_u16(hh0, h0); + hh1 = svaddwt_u16(hh1, h0); + hh2 = svaddwb_u16(hh2, h1); + hh3 = svaddwt_u16(hh3, h1); + hh4 = svaddwb_u16(hh4, h2); + hh5 = svaddwt_u16(hh5, h2); + hh6 = svaddwb_u16(hh6, h3); + hh7 = svaddwt_u16(hh7, h3); + hh8 = svaddwb_u16(hh8, h4); + hh9 = svaddwt_u16(hh9, h4); + hha = svaddwb_u16(hha, h5); + hhb = svaddwt_u16(hhb, h5); + } + + svst1_u32(svwhilelt_b32_u64( 0, maxCount), dst + 0, svshllb_n_u32(hh0, 0)); + svst1_u32(svwhilelt_b32_u64( 4, maxCount), dst + 4, svshllt_n_u32(hh0, 0)); + svst1_u32(svwhilelt_b32_u64( 8, maxCount), dst + 8, svshllb_n_u32(hh1, 0)); + svst1_u32(svwhilelt_b32_u64(12, maxCount), dst + 12, svshllt_n_u32(hh1, 0)); + svst1_u32(svwhilelt_b32_u64(16, maxCount), dst + 16, svshllb_n_u32(hh2, 0)); + svst1_u32(svwhilelt_b32_u64(20, maxCount), dst + 20, svshllt_n_u32(hh2, 0)); + svst1_u32(svwhilelt_b32_u64(24, maxCount), dst + 24, svshllb_n_u32(hh3, 0)); + svst1_u32(svwhilelt_b32_u64(28, maxCount), dst + 28, svshllt_n_u32(hh3, 0)); + svst1_u32(svwhilelt_b32_u64(32, maxCount), dst + 32, svshllb_n_u32(hh4, 0)); + svst1_u32(svwhilelt_b32_u64(36, maxCount), dst + 36, svshllt_n_u32(hh4, 0)); + svst1_u32(svwhilelt_b32_u64(40, maxCount), dst + 40, svshllb_n_u32(hh5, 0)); + svst1_u32(svwhilelt_b32_u64(44, maxCount), dst + 44, svshllt_n_u32(hh5, 0)); + svst1_u32(svwhilelt_b32_u64(48, maxCount), dst + 48, svshllb_n_u32(hh6, 0)); + svst1_u32(svwhilelt_b32_u64(52, maxCount), dst + 52, svshllt_n_u32(hh6, 0)); + svst1_u32(svwhilelt_b32_u64(56, maxCount), dst + 56, svshllb_n_u32(hh7, 0)); + svst1_u32(svwhilelt_b32_u64(60, maxCount), dst + 60, svshllt_n_u32(hh7, 0)); + svst1_u32(svwhilelt_b32_u64(64, maxCount), dst + 64, svshllb_n_u32(hh8, 0)); + svst1_u32(svwhilelt_b32_u64(68, maxCount), dst + 68, svshllt_n_u32(hh8, 0)); + svst1_u32(svwhilelt_b32_u64(72, maxCount), dst + 72, svshllb_n_u32(hh9, 0)); + svst1_u32(svwhilelt_b32_u64(76, maxCount), dst + 76, svshllt_n_u32(hh9, 0)); + svst1_u32(svwhilelt_b32_u64(80, maxCount), dst + 80, svshllb_n_u32(hha, 0)); + svst1_u32(svwhilelt_b32_u64(84, maxCount), dst + 84, svshllt_n_u32(hha, 0)); + svst1_u32(svwhilelt_b32_u64(88, maxCount), dst + 88, svshllb_n_u32(hhb, 0)); + svst1_u32(svwhilelt_b32_u64(92, maxCount), dst + 92, svshllt_n_u32(hhb, 0)); + + hh0 = svmax_u16_x(vl128, hh0, hh1); + hh2 = svmax_u16_x(vl128, hh2, hh3); + hh4 = svmax_u16_x(vl128, hh4, hh5); + hh6 = svmax_u16_x(vl128, hh6, hh7); + hh8 = svmax_u16_x(vl128, hh8, hh9); + hha = svmax_u16_x(vl128, hha, hhb); + hh0 = svmax_u16_x(vl128, hh0, hh2); + hh4 = svmax_u16_x(vl128, hh4, hh6); + hh8 = svmax_u16_x(vl128, hh8, hha); + hh0 = svmax_u16_x(vl128, hh0, hh4); + hh8 = svmax_u16_x(vl128, hh8, histmax); + return svmax_u16_x(vl128, hh0, hh8); +} + +static size_t HIST_count_sve2_chunk(unsigned* count, unsigned* maxSymbolValuePtr, + const void* source, size_t sourceSize, + HIST_checkInput_e check) +{ + const BYTE* ip = (const BYTE*)source; + const size_t maxCount = *maxSymbolValuePtr + 1; + + assert(*maxSymbolValuePtr <= 255); + assert(sourceSize <= HIST_SVE2_MAX_CHUNK_SIZE); + if (!sourceSize) { + ZSTD_memset(count, 0, maxCount * sizeof(*count)); + *maxSymbolValuePtr = 0; + return 0; + } + + { const svbool_t vl128 = svptrue_pat_b8(SV_VL16); + const svuint8_t c0 = svreinterpret_u8(svindex_u32(0x0C040800, 0x01010101)); + const svuint8_t c1 = svadd_n_u8_x(vl128, c0, 16); + const svuint8_t c2 = svadd_n_u8_x(vl128, c0, 32); + const svuint8_t c3 = svadd_n_u8_x(vl128, c1, 32); + + svuint8_t symbolMax = svdup_n_u8(0); + svuint16_t hh0 = svdup_n_u16(0); + svuint16_t hh1 = svdup_n_u16(0); + svuint16_t hh2 = svdup_n_u16(0); + svuint16_t hh3 = svdup_n_u16(0); + svuint16_t hh4 = svdup_n_u16(0); + svuint16_t hh5 = svdup_n_u16(0); + svuint16_t hh6 = svdup_n_u16(0); + svuint16_t hh7 = svdup_n_u16(0); + svuint16_t max; + size_t maxSymbolValue; + + size_t i = 0; + while (i < sourceSize) { + /* We can only accumulate 15 (15 * 16 <= 255) iterations of + * histogram in 8-bit accumulators! */ + const size_t size240 = min_size(i + 240, sourceSize); + + svbool_t pred = svwhilelt_b8_u64(i, sourceSize); + svuint8_t c = svld1rq_u8(pred, ip + i); + svuint8_t h0 = svhistseg_u8(c0, c); + svuint8_t h1 = svhistseg_u8(c1, c); + svuint8_t h2 = svhistseg_u8(c2, c); + svuint8_t h3 = svhistseg_u8(c3, c); + symbolMax = svmax_u8_x(vl128, symbolMax, c); + + for (i += 16; i < size240; i += 16) { + pred = svwhilelt_b8_u64(i, sourceSize); + c = svld1rq_u8(pred, ip + i); + h0 = svadd_u8_x(vl128, h0, svhistseg_u8(c0, c)); + h1 = svadd_u8_x(vl128, h1, svhistseg_u8(c1, c)); + h2 = svadd_u8_x(vl128, h2, svhistseg_u8(c2, c)); + h3 = svadd_u8_x(vl128, h3, svhistseg_u8(c3, c)); + symbolMax = svmax_u8_x(vl128, symbolMax, c); + } + + hh0 = svaddwb_u16(hh0, h0); + hh1 = svaddwt_u16(hh1, h0); + hh2 = svaddwb_u16(hh2, h1); + hh3 = svaddwt_u16(hh3, h1); + hh4 = svaddwb_u16(hh4, h2); + hh5 = svaddwt_u16(hh5, h2); + hh6 = svaddwb_u16(hh6, h3); + hh7 = svaddwt_u16(hh7, h3); + } + maxSymbolValue = svmaxv_u8(vl128, symbolMax); + + if (check && maxSymbolValue > *maxSymbolValuePtr) return ERROR(maxSymbolValue_tooSmall); + *maxSymbolValuePtr = maxSymbolValue; + + /* If the buffer size is not divisible by 16, the last elements of the final + * vector register read will be zeros, and these elements must be subtracted + * from the histogram. + */ + hh0 = svsub_n_u16_m(svptrue_pat_b32(SV_VL1), hh0, -sourceSize & 15); + + svst1_u32(svwhilelt_b32_u64( 0, maxCount), count + 0, svshllb_n_u32(hh0, 0)); + svst1_u32(svwhilelt_b32_u64( 4, maxCount), count + 4, svshllt_n_u32(hh0, 0)); + svst1_u32(svwhilelt_b32_u64( 8, maxCount), count + 8, svshllb_n_u32(hh1, 0)); + svst1_u32(svwhilelt_b32_u64(12, maxCount), count + 12, svshllt_n_u32(hh1, 0)); + svst1_u32(svwhilelt_b32_u64(16, maxCount), count + 16, svshllb_n_u32(hh2, 0)); + svst1_u32(svwhilelt_b32_u64(20, maxCount), count + 20, svshllt_n_u32(hh2, 0)); + svst1_u32(svwhilelt_b32_u64(24, maxCount), count + 24, svshllb_n_u32(hh3, 0)); + svst1_u32(svwhilelt_b32_u64(28, maxCount), count + 28, svshllt_n_u32(hh3, 0)); + svst1_u32(svwhilelt_b32_u64(32, maxCount), count + 32, svshllb_n_u32(hh4, 0)); + svst1_u32(svwhilelt_b32_u64(36, maxCount), count + 36, svshllt_n_u32(hh4, 0)); + svst1_u32(svwhilelt_b32_u64(40, maxCount), count + 40, svshllb_n_u32(hh5, 0)); + svst1_u32(svwhilelt_b32_u64(44, maxCount), count + 44, svshllt_n_u32(hh5, 0)); + svst1_u32(svwhilelt_b32_u64(48, maxCount), count + 48, svshllb_n_u32(hh6, 0)); + svst1_u32(svwhilelt_b32_u64(52, maxCount), count + 52, svshllt_n_u32(hh6, 0)); + svst1_u32(svwhilelt_b32_u64(56, maxCount), count + 56, svshllb_n_u32(hh7, 0)); + svst1_u32(svwhilelt_b32_u64(60, maxCount), count + 60, svshllt_n_u32(hh7, 0)); + + hh0 = svmax_u16_x(vl128, hh0, hh1); + hh2 = svmax_u16_x(vl128, hh2, hh3); + hh4 = svmax_u16_x(vl128, hh4, hh5); + hh6 = svmax_u16_x(vl128, hh6, hh7); + hh0 = svmax_u16_x(vl128, hh0, hh2); + hh4 = svmax_u16_x(vl128, hh4, hh6); + max = svmax_u16_x(vl128, hh0, hh4); + + maxSymbolValue = min_size(maxSymbolValue, maxCount); + if (maxSymbolValue >= 64) { + const svuint8_t c4 = svadd_n_u8_x(vl128, c0, 64); + const svuint8_t c5 = svadd_n_u8_x(vl128, c1, 64); + const svuint8_t c6 = svadd_n_u8_x(vl128, c2, 64); + const svuint8_t c7 = svadd_n_u8_x(vl128, c3, 64); + const svuint8_t c8 = svadd_n_u8_x(vl128, c0, 128); + const svuint8_t c9 = svadd_n_u8_x(vl128, c1, 128); + + max = HIST_count_6_sve2(ip, sourceSize, count + 64, c4, c5, c6, c7, + c8, c9, max, maxCount - 64); + + if (maxSymbolValue >= 160) { + const svuint8_t ca = svadd_n_u8_x(vl128, c2, 128); + const svuint8_t cb = svadd_n_u8_x(vl128, c3, 128); + const svuint8_t cc = svadd_n_u8_x(vl128, c4, 128); + const svuint8_t cd = svadd_n_u8_x(vl128, c5, 128); + const svuint8_t ce = svadd_n_u8_x(vl128, c6, 128); + const svuint8_t cf = svadd_n_u8_x(vl128, c7, 128); + + max = HIST_count_6_sve2(ip, sourceSize, count + 160, ca, cb, cc, + cd, ce, cf, max, maxCount - 160); + } else if (maxCount > 160) { + ZSTD_memset(count + 160, 0, (maxCount - 160) * sizeof(*count)); + } + } else if (maxCount > 64) { + ZSTD_memset(count + 64, 0, (maxCount - 64) * sizeof(*count)); + } + + return svmaxv_u16(vl128, max); + } +} + +static size_t HIST_count_sve2(unsigned* count, unsigned* maxSymbolValuePtr, + const void* source, size_t sourceSize, + HIST_checkInput_e check) +{ + if (sourceSize <= HIST_SVE2_MAX_CHUNK_SIZE) + return HIST_count_sve2_chunk(count, maxSymbolValuePtr, source, sourceSize, check); + + { const BYTE* const input = (const BYTE*)source; + unsigned const maxSymbolLimit = *maxSymbolValuePtr; + unsigned maxSymbolValue = maxSymbolLimit; + U32 chunkCounts[256]; + size_t largestCount = HIST_count_sve2_chunk(count, &maxSymbolValue, input, + HIST_SVE2_MAX_CHUNK_SIZE, check); + size_t offset = HIST_SVE2_MAX_CHUNK_SIZE; + if (HIST_isError(largestCount)) return largestCount; + + /* Merge each bounded histogram into U32 totals. Wrapping a present + * symbol to zero breaks Huffman coding, and undercounting breaks RLE. */ + while (offset < sourceSize) { + size_t const chunkSize = min_size(sourceSize - offset, HIST_SVE2_MAX_CHUNK_SIZE); + unsigned chunkMaxSymbol = maxSymbolLimit; + size_t const result = HIST_count_sve2_chunk(chunkCounts, &chunkMaxSymbol, + input + offset, chunkSize, check); + unsigned symbol; + if (HIST_isError(result)) return result; + if (chunkMaxSymbol > maxSymbolValue) maxSymbolValue = chunkMaxSymbol; + for (symbol = 0; symbol <= chunkMaxSymbol; ++symbol) { + count[symbol] += chunkCounts[symbol]; + if (count[symbol] > largestCount) largestCount = count[symbol]; + } + offset += chunkSize; + } + + *maxSymbolValuePtr = maxSymbolValue; + return largestCount; + } +} +#endif + /* HIST_count_parallel_wksp() : * store histogram into 4 intermediate tables, recombined at the end. * this design makes better use of OoO cpus, @@ -16637,8 +17150,8 @@ typedef enum { trustInput, checkMaxSymbolValue } HIST_checkInput_e; * `workSpace` must be a U32 table of size >= HIST_WKSP_SIZE_U32. * @return : largest histogram frequency, * or an error code (notably when histogram's alphabet is larger than *maxSymbolValuePtr) */ -static size_t HIST_count_parallel_wksp( - unsigned* count, unsigned* maxSymbolValuePtr, +static UNUSED_ATTR +size_t HIST_count_parallel_wksp(unsigned* count, unsigned* maxSymbolValuePtr, const void* source, size_t sourceSize, HIST_checkInput_e check, U32* const workSpace) @@ -16715,11 +17228,17 @@ size_t HIST_countFast_wksp(unsigned* count, unsigned* maxSymbolValuePtr, const void* source, size_t sourceSize, void* workSpace, size_t workSpaceSize) { - if (sourceSize < 1500) /* heuristic threshold */ + if (sourceSize < HIST_FAST_THRESHOLD) /* heuristic threshold */ return HIST_count_simple(count, maxSymbolValuePtr, source, sourceSize); +#if defined(ZSTD_ARCH_ARM_SVE2) + (void)workSpace; + (void)workSpaceSize; + return HIST_count_sve2(count, maxSymbolValuePtr, source, sourceSize, trustInput); +#else if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */ if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall); return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, trustInput, (U32*)workSpace); +#endif } /* HIST_count_wksp() : @@ -16729,10 +17248,15 @@ size_t HIST_count_wksp(unsigned* count, unsigned* maxSymbolValuePtr, const void* source, size_t sourceSize, void* workSpace, size_t workSpaceSize) { +#if defined(ZSTD_ARCH_ARM_SVE2) + if (*maxSymbolValuePtr < 255) + return HIST_count_sve2(count, maxSymbolValuePtr, source, sourceSize, checkMaxSymbolValue); +#else if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */ if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall); if (*maxSymbolValuePtr < 255) return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, checkMaxSymbolValue, (U32*)workSpace); +#endif *maxSymbolValuePtr = 255; return HIST_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, workSpace, workSpaceSize); } @@ -16781,6 +17305,7 @@ size_t HIST_count(unsigned* count, unsigned* maxSymbolValuePtr, * Includes ****************************************************************/ /**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/bmi2.h ****/ /**** skipping file: ../common/compiler.h ****/ /**** skipping file: ../common/bitstream.h ****/ /**** skipping file: hist.h ****/ @@ -17182,6 +17707,7 @@ static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 targetNbBits * gain back half the rank. */ U32 nBitsToDecrease = ZSTD_highbit32((U32)totalCost) + 1; + assert(nBitsToDecrease <= HUF_TABLELOG_MAX+1); for ( ; nBitsToDecrease > 1; nBitsToDecrease--) { U32 const highPos = rankLast[nBitsToDecrease]; U32 const lowPos = rankLast[nBitsToDecrease-1]; @@ -17897,9 +18423,10 @@ HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, const int flags) { - if (flags & HUF_flags_bmi2) { + if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) { return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable); } + (void)flags; return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable); } @@ -19053,6 +19580,7 @@ MEM_STATIC void ZSTD_cwksp_bump_oversized_duration( #define ZSTDMT_COMPRESS_H /* === Dependencies === */ +/**** skipping file: ../common/compiler.h ****/ /**** skipping file: ../common/zstd_deps.h ****/ #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_parameters */ /**** skipping file: ../zstd.h ****/ @@ -19073,8 +19601,8 @@ MEM_STATIC void ZSTD_cwksp_bump_oversized_duration( #ifndef ZSTDMT_JOBSIZE_MIN /* a different value can be selected at compile time */ # define ZSTDMT_JOBSIZE_MIN (512 KB) #endif -#define ZSTDMT_JOBLOG_MAX (MEM_32bits() ? 29 : 30) -#define ZSTDMT_JOBSIZE_MAX (MEM_32bits() ? (512 MB) : (1024 MB)) +#define ZSTDMT_JOBLOG_MAX (MEM_32bits() ? 28 : 30) +#define ZSTDMT_JOBSIZE_MAX (MEM_32bits() ? (256 MB) : (1024 MB)) /* ======================================================== @@ -19082,6 +19610,22 @@ MEM_STATIC void ZSTD_cwksp_bump_oversized_duration( * === Not exposed in libzstd. Never invoke directly === * ======================================================== */ +typedef struct { + void const* start; + size_t size; +} ZSTDMT_Range; + +/* Select the oldest input-ring range used by an unfinished job. */ +MEM_STATIC ZSTDMT_Range ZSTDMT_getJobInputRange(ZSTDMT_Range prefix, + ZSTDMT_Range src, + unsigned firstJob) +{ + /* The first job's prefix may be an external raw dictionary, which does + * not protect its source in the ring. Later prefixes are in the ring, + * immediately before the source, so protecting them also protects it. */ + return firstJob || prefix.size == 0 ? src : prefix; +} + /* === Memory management === */ typedef struct ZSTDMT_CCtx_s ZSTDMT_CCtx; /* Requires ZSTD_MULTITHREAD to be defined during compilation, otherwise it will return NULL. */ @@ -19090,12 +19634,23 @@ ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_threadPool *pool); size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx); +/*! ZSTDMT_waitForPendingJobs() : + * Waits for the jobs of an unfinished frame to complete, then releases their resources. + * Must be called before freeing anything these jobs reference, such as the dictionary. + * Does nothing if the last frame was completed. */ +void ZSTDMT_waitForPendingJobs(ZSTDMT_CCtx* mtctx); + size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx); /* === Streaming functions === */ size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx); +/*! ZSTDMT_isFrameEnded() : + * @return 1 once the last job of the current frame is created : + * remaining input then belongs to the next frame. */ +unsigned ZSTDMT_isFrameEnded(const ZSTDMT_CCtx* mtctx); + /*! ZSTDMT_initCStream_internal() : * Private use only. Init streaming operation. * expects params to be valid. @@ -19295,6 +19850,10 @@ MEM_STATIC ZSTD_SequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */ int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */ +/* Derives the half-open sequence range [startIdx, endIdx). */ +void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore, + const SeqStore_t* originalSeqStore, + size_t startIdx, size_t endIdx); /*********************************************** @@ -19619,14 +20178,19 @@ typedef struct { SeqStore_t currSeqStore; SeqStore_t nextSeqStore; - U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS]; + U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS + 1]; /* splits, followed by the end of the block */ ZSTD_entropyCTablesMetadata_t entropyMetadata; } ZSTD_blockSplitCtx; struct ZSTD_CCtx_s { ZSTD_compressionStage_e stage; int cParamsChanged; /* == 1 if cParams(except wlog) or compression level are changed in requestedParams. Triggers transmission of new params to ZSTDMT (if available) then reset to 0. */ - int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ +#if DYNAMIC_BMI2 + int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise when CPU state + * is cached per context. Never read this directly: use ZSTD_CCtx_get_bmi2(), + * which also handles builds + * where cached CPU state is not used. */ +#endif ZSTD_CCtx_params requestedParams; ZSTD_CCtx_params appliedParams; ZSTD_CCtx_params simpleApiParams; /* Param storage used by the simple API - not sticky. Must only be used in top-level simple API functions for storage. */ @@ -19699,6 +20263,26 @@ struct ZSTD_CCtx_s { size_t extSeqBufCapacity; }; +/** + * @returns the cached per-context BMI2 dispatch hint, or 0 when the build does + * not use cached CPU state. + * + * Beware: this is *not* a "does the CPU support BMI2" test. When BMI2 is enabled + * at compile time, DYNAMIC_BMI2 is 0: the whole library is already compiled with + * BMI2, no separate variant exists, and this returns 0 even though the CPU does + * support BMI2. Only use the result as a dispatch hint passed to a lower-level + * BMI2/default selector. Integrations may ignore the cached hint and consult + * their own CPU-feature policy at that selector. + */ +MEM_STATIC int ZSTD_CCtx_get_bmi2(const struct ZSTD_CCtx_s* cctx) { +#if DYNAMIC_BMI2 + return cctx->bmi2; +#else + (void)cctx; + return 0; +#endif +} + typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e; typedef enum { ZSTD_tfp_forCCtx, ZSTD_tfp_forCDict } ZSTD_tableFillPurpose_e; @@ -19861,7 +20445,7 @@ ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE con { assert(iend > ilimit_w); if (ip <= ilimit_w) { - ZSTD_wildcopy(op, ip, ilimit_w - ip, ZSTD_no_overlap); + ZSTD_wildcopy(op, ip, (size_t)(ilimit_w - ip), ZSTD_no_overlap); op += ilimit_w - ip; ip = ilimit_w; } @@ -19954,7 +20538,7 @@ ZSTD_storeSeq(SeqStore_t* seqStorePtr, ZSTD_STATIC_ASSERT(WILDCOPY_OVERLENGTH >= 16); ZSTD_copy16(seqStorePtr->lit, literals); if (litLength > 16) { - ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, (ptrdiff_t)litLength-16, ZSTD_no_overlap); + ZSTD_wildcopy(seqStorePtr->lit+16, literals+16, litLength-16, ZSTD_no_overlap); } } else { ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w); @@ -20670,14 +21254,14 @@ void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs); typedef struct { U32 idx; /* Index in array of ZSTD_Sequence */ - U32 posInSequence; /* Position within sequence at idx */ + U64 posInSequence; /* Position within sequence at idx. The sum of its lengths may exceed U32. */ size_t posInSrc; /* Number of bytes given by sequences provided so far */ } ZSTD_SequencePosition; /* for benchmark */ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, - int const repcodeResolution); + int repcodeResolution); typedef struct { size_t nbSequences; @@ -21051,6 +21635,7 @@ size_t ZSTD_compressLiterals ( /*-************************************* * Dependencies ***************************************/ +/**** skipping file: ../common/bmi2.h ****/ /**** start inlining zstd_compress_sequences.h ****/ /* * Copyright (c) Meta Platforms, Inc. and affiliates. @@ -21396,6 +21981,7 @@ ZSTD_encodeSequences_body( FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; + assert(MEM_32bits() || !longOffsets); RETURN_ERROR_IF( ERR_isError(BIT_initCStream(&blockStream, dst, dstCapacity)), dstSize_tooSmall, "not enough space remaining"); @@ -21411,7 +21997,7 @@ ZSTD_encodeSequences_body( if (MEM_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq-1].mlBase, ML_bits[mlCodeTable[nbSeq-1]]); if (MEM_32bits()) BIT_flushBits(&blockStream); - if (longOffsets) { + if (MEM_32bits() && longOffsets) { U32 const ofBits = ofCodeTable[nbSeq-1]; unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { @@ -21449,7 +22035,7 @@ ZSTD_encodeSequences_body( if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].mlBase, mlBits); if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); - if (longOffsets) { + if (MEM_32bits() && longOffsets) { unsigned const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offBase, extraBits); @@ -21510,6 +22096,10 @@ ZSTD_encodeSequences_bmi2( sequences, nbSeq, longOffsets); } +#else + +#define ZSTD_encodeSequences_bmi2 ZSTD_encodeSequences_default + #endif size_t ZSTD_encodeSequences( @@ -21520,15 +22110,13 @@ size_t ZSTD_encodeSequences( SeqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) { DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity); -#if DYNAMIC_BMI2 - if (bmi2) { + if (ZSTD_USE_BMI2(bmi2)) { return ZSTD_encodeSequences_bmi2(dst, dstCapacity, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets); } -#endif (void)bmi2; return ZSTD_encodeSequences_default(dst, dstCapacity, CTable_MatchLength, mlCodeTable, @@ -21622,7 +22210,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, size_t const lhSize = 3 + (litSize >= (1 KB - header)) + (litSize >= (16 KB - header)); BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstSize; - BYTE* op = ostart + lhSize; + BYTE* op = ostart; U32 const singleStream = lhSize == 3; SymbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat; size_t cLitSize = 0; @@ -21635,13 +22223,18 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, return ZSTD_noCompressLiterals(dst, dstSize, literals, litSize); } else if (hufMetadata->hType == set_rle) { DEBUGLOG(5, "ZSTD_compressSubBlock_literal using rle literal"); + RETURN_ERROR_IF(dstSize < 4, dstSize_tooSmall, ""); return ZSTD_compressRleLiteralsBlock(dst, dstSize, literals, litSize); } assert(litSize > 0); assert(hufMetadata->hType == set_compressed || hufMetadata->hType == set_repeat); + RETURN_ERROR_IF(dstSize < lhSize, dstSize_tooSmall, ""); + op += lhSize; if (writeEntropy && hufMetadata->hType == set_compressed) { + RETURN_ERROR_IF(hufMetadata->hufDesSize > (size_t)(oend-op), + dstSize_tooSmall, ""); ZSTD_memcpy(op, hufMetadata->hufDesBuffer, hufMetadata->hufDesSize); op += hufMetadata->hufDesSize; cLitSize += hufMetadata->hufDesSize; @@ -21651,12 +22244,12 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, { int const flags = bmi2 ? HUF_flags_bmi2 : 0; const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags) : HUF_compress4X_usingCTable(op, (size_t)(oend-op), literals, litSize, hufTable, flags); - op += cSize; - cLitSize += cSize; if (cSize == 0 || ERR_isError(cSize)) { DEBUGLOG(5, "Failed to write entropy tables %s", ZSTD_getErrorName(cSize)); return 0; } + op += cSize; + cLitSize += cSize; /* If we expand and we aren't writing a header then emit uncompressed */ if (!writeEntropy && cLitSize >= litSize) { DEBUGLOG(5, "ZSTD_compressSubBlock_literal using raw literal because uncompressible"); @@ -21773,6 +22366,8 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables, const U32 Offtype = fseMetadata->ofType; const U32 MLtype = fseMetadata->mlType; DEBUGLOG(5, "ZSTD_compressSubBlock_sequences (fseTablesSize=%zu)", fseMetadata->fseTablesSize); + RETURN_ERROR_IF(fseMetadata->fseTablesSize > (size_t)(oend-op), + dstSize_tooSmall, ""); *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2)); ZSTD_memcpy(op, fseMetadata->fseTablesBuffer, fseMetadata->fseTablesSize); op += fseMetadata->fseTablesSize; @@ -21847,9 +22442,11 @@ static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy, { BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstCapacity; - BYTE* op = ostart + ZSTD_blockHeaderSize; + BYTE* op = ostart; DEBUGLOG(5, "ZSTD_compressSubBlock (litSize=%zu, nbSeq=%zu, writeLitEntropy=%d, writeSeqEntropy=%d, lastBlock=%d)", litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock); + RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, ""); + op += ZSTD_blockHeaderSize; { size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable, &entropyMetadata->hufMetadata, literals, litSize, op, (size_t)(oend-op), @@ -22256,7 +22853,7 @@ size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc, &zc->appliedParams, dst, dstCapacity, src, srcSize, - zc->bmi2, lastBlock, + ZSTD_CCtx_get_bmi2(zc), lastBlock, zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */); } /**** ended inlining compress/zstd_compress_superblock.c ****/ @@ -22353,7 +22950,7 @@ ZSTD_GEN_RECORD_FINGERPRINT(11, 9) ZSTD_GEN_RECORD_FINGERPRINT(43, 8) -static U64 abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } +static U64 ZSTD_abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2, unsigned hashLog) { @@ -22362,7 +22959,7 @@ static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2, unsigned h assert(hashLog <= HASHLOG_MAX); for (n = 0; n < ((size_t)1 << hashLog); n++) { distance += - abs64((S64)fp1->events[n] * (S64)fp2->nbEvents - (S64)fp2->events[n] * (S64)fp1->nbEvents); + ZSTD_abs64((S64)fp1->events[n] * (S64)fp2->nbEvents - (S64)fp2->events[n] * (S64)fp1->nbEvents); } return distance; } @@ -22482,7 +23079,7 @@ static size_t ZSTD_splitBlock_fromBorders(const void* blockStart, size_t blockSi { U64 const distFromBegin = fpDistance(&fpstats->pastEvents, middleEvents, 8); U64 const distFromEnd = fpDistance(&fpstats->newEvents, middleEvents, 8); U64 const minDistance = SEGMENT_SIZE * SEGMENT_SIZE / 3; - if (abs64((S64)distFromBegin - (S64)distFromEnd) < minDistance) + if (ZSTD_abs64((S64)distFromBegin - (S64)distFromEnd) < minDistance) return 64 KB; return (distFromBegin > distFromEnd) ? 32 KB : 96 KB; } @@ -22516,6 +23113,7 @@ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, ***************************************/ /**** skipping file: ../common/allocations.h ****/ /**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/bmi2.h ****/ /**** skipping file: ../common/mem.h ****/ /**** skipping file: ../common/error_private.h ****/ /**** skipping file: hist.h ****/ @@ -22893,6 +23491,17 @@ size_t ZSTD_compressBlock_btultra2( #define ZSTD_LDM_DEFAULT_WINDOW_LOG ZSTD_WINDOWLOG_LIMIT_DEFAULT +typedef struct { + U64 rolling; + U64 stopMask; +} ldmRollingHashState_t; + +void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state, + BYTE const* data, size_t minMatchLength); +size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state, + BYTE const* data, size_t size, + size_t* splits, unsigned* numSplits); + void ZSTD_ldm_fillHashTable( ldmState_t* state, const BYTE* ip, const BYTE* iend, ldmParams_t const* params); @@ -23010,6 +23619,14 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, # define ZSTD_HASHLOG3_MAX 17 #endif + +/*-************************************* +* Forward declarations +***************************************/ +size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, + size_t nbSequences); + + /*-************************************* * Helper functions ***************************************/ @@ -23058,7 +23675,9 @@ static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager) assert(cctx != NULL); ZSTD_memset(cctx, 0, sizeof(*cctx)); cctx->customMem = memManager; - cctx->bmi2 = ZSTD_cpuSupportsBmi2(); +#if DYNAMIC_BMI2 + ZSTD_SET_BMI2(cctx->bmi2, ZSTD_cpuSupportsBmi2()); +#endif { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters); assert(!ZSTD_isError(err)); (void)err; @@ -23098,7 +23717,9 @@ ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize) cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE); cctx->tmpWkspSize = TMP_WORKSPACE_SIZE; - cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); +#if DYNAMIC_BMI2 + ZSTD_SET_BMI2(cctx->bmi2, ZSTD_cpuSupportsBmi2()); +#endif return cctx; } @@ -23125,10 +23746,10 @@ static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx) { assert(cctx != NULL); assert(cctx->staticSize == 0); - ZSTD_clearAllDicts(cctx); #ifdef ZSTD_MULTITHREAD - ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; + ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; /* pending jobs may use the dictionary */ #endif + ZSTD_clearAllDicts(cctx); ZSTD_cwksp_free(&cctx->workspace, cctx->customMem); } @@ -23191,10 +23812,18 @@ static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_Para /* Returns row matchfinder usage given an initial mode and cParams */ static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode, const ZSTD_compressionParameters* const cParams) { +#ifdef ZSTD_LINUX_KERNEL + /* The Linux Kernel does not use SIMD, and 128KB is a very common size, e.g. in BtrFS. + * The row match finder is slower for this size without SIMD, so disable it. + */ + const unsigned kWindowLogLowerBound = 17; +#else + const unsigned kWindowLogLowerBound = 14; +#endif if (mode != ZSTD_ps_auto) return mode; /* if requested enabled, but no SIMD, we still will use row matchfinder */ mode = ZSTD_ps_disable; if (!ZSTD_rowMatchFinderSupported(cParams->strategy)) return mode; - if (cParams->windowLog > 14) mode = ZSTD_ps_enable; + if (cParams->windowLog > kWindowLogLowerBound) mode = ZSTD_ps_enable; return mode; } @@ -24197,6 +24826,13 @@ static int ZSTD_dedicatedDictSearch_isSupported( const ZSTD_compressionParameters* cParams); static void ZSTD_dedicatedDictSearch_revertCParams( ZSTD_compressionParameters* cParams); +static size_t ZSTD_createCDict_advanced2_internal( + ZSTD_CDict** cdictPtr, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + const ZSTD_CCtx_params* originalCctxParams, + ZSTD_customMem customMem); /** * Initializes the local dictionary using requested parameters. @@ -24222,14 +24858,14 @@ static size_t ZSTD_initLocalDict(ZSTD_CCtx* cctx) assert(cctx->cdict == NULL); assert(cctx->prefixDict.dict == NULL); - dl->cdict = ZSTD_createCDict_advanced2( + FORWARD_IF_ERROR(ZSTD_createCDict_advanced2_internal( + &dl->cdict, dl->dict, dl->dictSize, ZSTD_dlm_byRef, dl->dictContentType, &cctx->requestedParams, - cctx->customMem); - RETURN_ERROR_IF(!dl->cdict, memory_allocation, "ZSTD_createCDict_advanced failed"); + cctx->customMem), ""); cctx->cdict = dl->cdict; return 0; } @@ -24293,6 +24929,15 @@ size_t ZSTD_CCtx_refThreadPool(ZSTD_CCtx* cctx, ZSTD_threadPool* pool) { RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong, "Can't ref a pool when ctx not in init stage."); +#ifdef ZSTD_MULTITHREAD + if (pool != cctx->pool) { + /* The MT context, created by the first multi-threaded frame and then reused, + * runs its jobs on the pool it was created with : without this, the next frames + * would still use the previous pool, which the caller may free. No job is running : + * the stage is zcss_init, and ZSTDMT_freeCCtx() waits for pending jobs. */ + ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL; + } +#endif cctx->pool = pool; return 0; } @@ -24322,8 +24967,13 @@ size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset) { if ( (reset == ZSTD_reset_session_only) || (reset == ZSTD_reset_session_and_parameters) ) { +#ifdef ZSTD_MULTITHREAD + /* jobs of an abandoned frame may still reference the dictionary */ + if (cctx->mtctx != NULL) ZSTDMT_waitForPendingJobs(cctx->mtctx); +#endif cctx->streamStage = zcss_init; cctx->pledgedSrcSizePlusOne = 0; + cctx->stableIn_notConsumed = 0; /* input pending in the abandoned frame */ } if ( (reset == ZSTD_reset_parameters) || (reset == ZSTD_reset_session_and_parameters) ) { @@ -24709,15 +25359,19 @@ size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params) { ZSTD_compressionParameters const cParams = ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict); + ldmParams_t ldmParams = params->ldmParams; ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, &cParams); RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only."); + if (ldmParams.enableLdm == ZSTD_ps_enable) { + ZSTD_ldm_adjustParameters(&ldmParams, &cParams); + } /* estimateCCtxSize is for one-shot compression. So no buffers should * be needed. However, we still allocate two 0-sized buffers, which can * take space under ASAN. */ return ZSTD_estimateCCtxSize_usingCCtxParams_internal( - &cParams, ¶ms->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize); + &cParams, &ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize); } size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams) @@ -24767,6 +25421,7 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params) RETURN_ERROR_IF(params->nbWorkers > 0, GENERIC, "Estimate CCtx size is supported for single-threaded compression only."); { ZSTD_compressionParameters const cParams = ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict); + ldmParams_t ldmParams = params->ldmParams; size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(params->maxBlockSize), (size_t)1 << cParams.windowLog); size_t const inBuffSize = (params->inBufferMode == ZSTD_bm_buffered) ? ((size_t)1 << cParams.windowLog) + blockSize @@ -24776,8 +25431,11 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params) : 0; ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, ¶ms->cParams); + if (ldmParams.enableLdm == ZSTD_ps_enable) { + ZSTD_ldm_adjustParameters(&ldmParams, &cParams); + } return ZSTD_estimateCCtxSize_usingCCtxParams_internal( - &cParams, ¶ms->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize, + &cParams, &ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize); } } @@ -25275,6 +25933,20 @@ static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict, * handled in _enforceMaxDist */ } +/* Check against the addressable content, which may be smaller than the full + * dictionary when only a suffix is loaded. */ +static size_t ZSTD_checkDictionaryRepCodes(const U32 rep[ZSTD_REP_NUM], size_t dictContentSize) +{ + U32 u; + for (u = 0; u < ZSTD_REP_NUM; ++u) { + RETURN_ERROR_IF(rep[u] == 0 || rep[u] > dictContentSize, + dictionary_corrupted, + "repcode %u exceeds dictionary content (%zu bytes)", + rep[u], dictContentSize); + } + return 0; +} + static size_t ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict, @@ -25314,6 +25986,9 @@ ZSTD_resetCCtx_byAttachingCDict(ZSTD_CCtx* cctx, /* don't even attach dictionaries with no contents */ DEBUGLOG(4, "skipping attaching empty dictionary"); } else { + /* Enforce the dictMatchState block compressors' repcode bounds + * before allowing them to search this dictionary. */ + FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(cdict->cBlockState.rep, cdictLen), ""); DEBUGLOG(4, "attaching dictionary into context"); cctx->blockState.matchState.dictMatchState = &cdict->matchState; @@ -25457,105 +26132,6 @@ static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx, } } -/*! ZSTD_copyCCtx_internal() : - * Duplicate an existing context `srcCCtx` into another one `dstCCtx`. - * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). - * The "context", in this case, refers to the hash and chain tables, - * entropy tables, and dictionary references. - * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx. - * @return : 0, or an error code */ -static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx, - const ZSTD_CCtx* srcCCtx, - ZSTD_frameParameters fParams, - U64 pledgedSrcSize, - ZSTD_buffered_policy_e zbuff) -{ - RETURN_ERROR_IF(srcCCtx->stage!=ZSTDcs_init, stage_wrong, - "Can't copy a ctx that's not in init stage."); - DEBUGLOG(5, "ZSTD_copyCCtx_internal"); - ZSTD_memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem)); - { ZSTD_CCtx_params params = dstCCtx->requestedParams; - /* Copy only compression parameters related to tables. */ - params.cParams = srcCCtx->appliedParams.cParams; - assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto); - assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto); - assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto); - params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder; - params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter; - params.ldmParams = srcCCtx->appliedParams.ldmParams; - params.fParams = fParams; - params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize; - ZSTD_resetCCtx_internal(dstCCtx, ¶ms, pledgedSrcSize, - /* loadedDictSize */ 0, - ZSTDcrp_leaveDirty, zbuff); - assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog); - assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy); - assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog); - assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog); - assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3); - } - - ZSTD_cwksp_mark_tables_dirty(&dstCCtx->workspace); - - /* copy tables */ - { size_t const chainSize = ZSTD_allocateChainTable(srcCCtx->appliedParams.cParams.strategy, - srcCCtx->appliedParams.useRowMatchFinder, - 0 /* forDDSDict */) - ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog) - : 0; - size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog; - U32 const h3log = srcCCtx->blockState.matchState.hashLog3; - size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0; - - ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable, - srcCCtx->blockState.matchState.hashTable, - hSize * sizeof(U32)); - ZSTD_memcpy(dstCCtx->blockState.matchState.chainTable, - srcCCtx->blockState.matchState.chainTable, - chainSize * sizeof(U32)); - ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable3, - srcCCtx->blockState.matchState.hashTable3, - h3Size * sizeof(U32)); - } - - ZSTD_cwksp_mark_tables_clean(&dstCCtx->workspace); - - /* copy dictionary offsets */ - { - const ZSTD_MatchState_t* srcMatchState = &srcCCtx->blockState.matchState; - ZSTD_MatchState_t* dstMatchState = &dstCCtx->blockState.matchState; - dstMatchState->window = srcMatchState->window; - dstMatchState->nextToUpdate = srcMatchState->nextToUpdate; - dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd; - } - dstCCtx->dictID = srcCCtx->dictID; - dstCCtx->dictContentSize = srcCCtx->dictContentSize; - - /* copy block state */ - ZSTD_memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock)); - - return 0; -} - -/*! ZSTD_copyCCtx() : - * Duplicate an existing context `srcCCtx` into another one `dstCCtx`. - * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). - * pledgedSrcSize==0 means "unknown". -* @return : 0, or an error code */ -size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize) -{ - ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ }; - ZSTD_buffered_policy_e const zbuff = srcCCtx->bufferedPolicy; - ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1); - if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; - fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN); - - return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx, - fParams, pledgedSrcSize, - zbuff); -} - - #define ZSTD_ROWSIZE 16 /*! ZSTD_reduceTable() : * reduce table indexes by `reducerValue`, or squash to zero. @@ -26952,7 +27528,7 @@ static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore) /* Derives the seqStore that is a chunk of the originalSeqStore from [startIdx, endIdx). * Stores the result in resultSeqStore. */ -static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore, +void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore, const SeqStore_t* originalSeqStore, size_t startIdx, size_t endIdx) { @@ -26964,7 +27540,7 @@ static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore, /* Move longLengthPos into the correct position if necessary */ if (originalSeqStore->longLengthType != ZSTD_llt_none) { - if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos > endIdx) { + if (originalSeqStore->longLengthPos < startIdx || originalSeqStore->longLengthPos >= endIdx) { resultSeqStore->longLengthType = ZSTD_llt_none; } else { resultSeqStore->longLengthPos -= (U32)startIdx; @@ -27082,7 +27658,7 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize, srcSize, zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */, - zc->bmi2); + ZSTD_CCtx_get_bmi2(zc)); FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!"); if (!zc->isFirstBlock && @@ -27144,8 +27720,8 @@ typedef struct { * In practice, recursion depth usually doesn't go beyond 4. * * Furthermore, the number of splits is capped by ZSTD_MAX_NB_BLOCK_SPLITS. - * At ZSTD_MAX_NB_BLOCK_SPLITS == 196 with the current existing blockSize - * maximum of 128 KB, this value is actually impossible to reach. + * A 128 KiB block containing many 3-byte matches can have enough sequences + * for more splits than this limit allows. */ static void ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx, @@ -27179,6 +27755,8 @@ ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t end if (estimatedFirstHalfSize + estimatedSecondHalfSize < estimatedOriginalSize) { DEBUGLOG(5, "split decided at seqNb:%zu", midIdx); ZSTD_deriveBlockSplitsHelper(splits, startIdx, midIdx, zc, origSeqStore); + if (splits->idx >= ZSTD_MAX_NB_BLOCK_SPLITS) + return; splits->splitLocations[splits->idx] = (U32)midIdx; splits->idx++; ZSTD_deriveBlockSplitsHelper(splits, midIdx, endIdx, zc, origSeqStore); @@ -27201,6 +27779,7 @@ static size_t ZSTD_deriveBlockSplits(ZSTD_CCtx* zc, U32 partitions[], U32 nbSeq) return 0; } ZSTD_deriveBlockSplitsHelper(&splits, 0, nbSeq, zc, &zc->seqStore); + assert(splits.idx <= ZSTD_MAX_NB_BLOCK_SPLITS); splits.splitLocations[splits.idx] = nbSeq; DEBUGLOG(5, "ZSTD_deriveBlockSplits: final nb partitions: %zu", splits.idx+1); return splits.idx; @@ -27222,7 +27801,7 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, BYTE* op = (BYTE*)dst; size_t i = 0; size_t srcBytesTotal = 0; - U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */ + U32* const partitions = zc->blockSplitCtx.partitions; /* includes the final block boundary */ SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore; SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore; size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq); @@ -27372,7 +27951,7 @@ ZSTD_compressBlock_internal(ZSTD_CCtx* zc, dst, dstCapacity, srcSize, zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */, - zc->bmi2); + ZSTD_CCtx_get_bmi2(zc)); if (frame && /* We don't want to emit our first block as a RLE even if it qualifies because @@ -28055,9 +28634,11 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, ""); RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, ""); + /* The optimal parser reads every symbol's cost, including absent ones. + * FSE_readNCount() zero-fills the omitted normalized counts. */ RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp( bs->entropy.fse.matchlengthCTable, - matchlengthNCount, matchlengthMaxValue, matchlengthLog, + matchlengthNCount, MaxML, matchlengthLog, workspace, HUF_WORKSPACE_SIZE)), dictionary_corrupted, ""); bs->entropy.fse.matchlength_repeatMode = ZSTD_dictNCountRepeat(matchlengthNCount, matchlengthMaxValue, MaxML); @@ -28069,9 +28650,10 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, (size_t)(dictEnd-dictPtr)); RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, ""); RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, ""); + /* As above, initialize costs for the full symbol range. */ RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp( bs->entropy.fse.litlengthCTable, - litlengthNCount, litlengthMaxValue, litlengthLog, + litlengthNCount, MaxLL, litlengthLog, workspace, HUF_WORKSPACE_SIZE)), dictionary_corrupted, ""); bs->entropy.fse.litlength_repeatMode = ZSTD_dictNCountRepeat(litlengthNCount, litlengthMaxValue, MaxLL); @@ -28093,12 +28675,9 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, /* All offset values <= dictContentSize + 128 KB must be representable for a valid table */ bs->entropy.fse.offcode_repeatMode = ZSTD_dictNCountRepeat(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)); - /* All repCodes must be <= dictContentSize and != 0 */ - { U32 u; - for (u=0; u<3; u++) { - RETURN_ERROR_IF(bs->rep[u] == 0, dictionary_corrupted, ""); - RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, ""); - } } } + /* The format permits nonzero repcodes up to the full content size. */ + FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(bs->rep, dictContentSize), ""); + } return (size_t)(dictPtr - (const BYTE*)dict); } @@ -28108,7 +28687,8 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#dictionary-format */ /*! ZSTD_loadZstdDictionary() : - * @return : dictID, or an error code + * @return : 0 on success, or an error code (check with ZSTD_isError()). + * On success, the dictionary's ID is written into @dictIDPtr. * assumptions : magic number supposed already checked * dictSize supposed >= 8 */ @@ -28119,11 +28699,12 @@ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs, const void* dict, size_t dictSize, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, - void* workspace) + void* workspace, + U32* dictIDPtr) { const BYTE* dictPtr = (const BYTE*)dict; const BYTE* const dictEnd = dictPtr + dictSize; - size_t dictID; + U32 dictID; size_t eSize; ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<= 8); @@ -28139,11 +28720,26 @@ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs, FORWARD_IF_ERROR(ZSTD_loadDictionaryContent( ms, NULL, ws, params, dictPtr, dictContentSize, dtlm, tfp), ""); } - return dictID; + if (tfp == ZSTD_tfp_forCDict) { + /* The matchfinder may retain only a suffix of a large dictionary. + * In particular, short-cache CDicts retain at most (1 << 24) - 2 + * bytes. Recheck the repcodes against the actual window so that + * dictMatchState searches cannot underflow their match indices. */ + U32 const loadedDictSize = (U32)(ms->window.nextSrc - ms->window.base) - ms->window.lowLimit; + assert((U32)(ms->window.nextSrc - ms->window.base) >= ms->window.lowLimit); + FORWARD_IF_ERROR(ZSTD_checkDictionaryRepCodes(bs->rep, loadedDictSize), ""); + } + *dictIDPtr = dictID; + return 0; } /** ZSTD_compress_insertDictionary() : -* @return : dictID, or an error code */ +* @return : 0 on success, or an error code (check with ZSTD_isError()). +* @dictIDPtr is always written: with the dictionary's ID on success, +* or 0 if there is no ID (or on error). +* The ID is reported through @dictIDPtr rather than the return value, +* because any value close to (size_t)-1 is interpreted as an error code, +* which would reject valid 32-bit dictIDs on 32-bit builds. */ static size_t ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs, ZSTD_MatchState_t* ms, @@ -28154,9 +28750,11 @@ ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs, ZSTD_dictContentType_e dictContentType, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp, - void* workspace) + void* workspace, + U32* dictIDPtr) { DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize); + *dictIDPtr = 0; if ((dict==NULL) || (dictSize<8)) { RETURN_ERROR_IF(dictContentType == ZSTD_dct_fullDict, dictionary_wrong, ""); return 0; @@ -28180,7 +28778,7 @@ ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs, /* dict as full zstd dictionary */ return ZSTD_loadZstdDictionary( - bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace); + bs, ms, ws, params, dict, dictSize, dtlm, tfp, workspace, dictIDPtr); } #define ZSTD_USE_CDICT_PARAMS_SRCSIZE_CUTOFF (128 KB) @@ -28218,19 +28816,19 @@ static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx, FORWARD_IF_ERROR( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize, dictContentSize, ZSTDcrp_makeClean, zbuff) , ""); - { size_t const dictID = cdict ? + { U32 dictID = 0; + size_t const dictStatus = cdict ? ZSTD_compress_insertDictionary( cctx->blockState.prevCBlock, &cctx->blockState.matchState, &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent, cdict->dictContentSize, cdict->dictContentType, dtlm, - ZSTD_tfp_forCCtx, cctx->tmpWorkspace) + ZSTD_tfp_forCCtx, cctx->tmpWorkspace, &dictID) : ZSTD_compress_insertDictionary( cctx->blockState.prevCBlock, &cctx->blockState.matchState, &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize, - dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace); - FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed"); - assert(dictID <= UINT_MAX); - cctx->dictID = (U32)dictID; + dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace, &dictID); + FORWARD_IF_ERROR(dictStatus, "ZSTD_compress_insertDictionary failed"); + cctx->dictID = dictID; cctx->dictContentSize = dictContentSize; } return 0; @@ -28470,6 +29068,29 @@ size_t ZSTD_compress(void* dst, size_t dstCapacity, /* ===== Dictionary API ===== */ +/* Returns the CDict workspace size, or an error if the dictionary copy would + * overflow while rounding, adding sanitizer redzones, or adding the workspace + * overhead. All by-copy CDict creation paths must use this calculation before + * reserving or copying the dictionary. */ +static size_t ZSTD_estimateCDictSize_internal(size_t dictSize, + size_t matchStateSize, + ZSTD_dictLoadMethod_e dictLoadMethod) +{ + size_t const baseSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) + + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) + + matchStateSize; + if (dictLoadMethod == ZSTD_dlm_byRef) return baseSize; + { + size_t const alignedDictSize = ZSTD_cwksp_align(dictSize, sizeof(void*)); + size_t const dictAllocSize = ZSTD_cwksp_alloc_size(alignedDictSize); + RETURN_ERROR_IF(alignedDictSize < dictSize || dictAllocSize < alignedDictSize, + memory_allocation, "CDict size overflow"); + RETURN_ERROR_IF(dictAllocSize > (size_t)-1 - baseSize, + memory_allocation, "CDict workspace size overflow"); + return baseSize + dictAllocSize; + } +} + /*! ZSTD_estimateCDictSize_advanced() : * Estimate amount of memory that will be needed to create a dictionary with following arguments */ size_t ZSTD_estimateCDictSize_advanced( @@ -28477,14 +29098,12 @@ size_t ZSTD_estimateCDictSize_advanced( ZSTD_dictLoadMethod_e dictLoadMethod) { DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict)); - return ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) - + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) - /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small - * in case we are using DDS with row-hash. */ - + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams), - /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0) - + (dictLoadMethod == ZSTD_dlm_byRef ? 0 - : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void *)))); + /* enableDedicatedDictSearch == 1 ensures that CDict estimation will not be too small + * in case we are using DDS with row-hash. */ + return ZSTD_estimateCDictSize_internal(dictSize, + ZSTD_sizeof_matchState(&cParams, ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams), + /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0), + dictLoadMethod); } size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel) @@ -28542,13 +29161,14 @@ static size_t ZSTD_initCDict_internal( */ { params.compressionLevel = ZSTD_CLEVEL_DEFAULT; params.fParams.contentSizeFlag = 1; - { size_t const dictID = ZSTD_compress_insertDictionary( + { U32 dictID = 0; + size_t const dictStatus = ZSTD_compress_insertDictionary( &cdict->cBlockState, &cdict->matchState, NULL, &cdict->workspace, ¶ms, cdict->dictContent, cdict->dictContentSize, - dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace); - FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed"); - assert(dictID <= (size_t)(U32)-1); - cdict->dictID = (U32)dictID; + dictContentType, ZSTD_dtlm_full, ZSTD_tfp_forCDict, cdict->entropyWorkspace, + &dictID); + FORWARD_IF_ERROR(dictStatus, "ZSTD_compress_insertDictionary failed"); + cdict->dictID = dictID; } } @@ -28566,16 +29186,15 @@ ZSTD_createCDict_advanced_internal(size_t dictSize, if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; DEBUGLOG(3, "ZSTD_createCDict_advanced_internal (dictSize=%u)", (unsigned)dictSize); - { size_t const workspaceSize = - ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) + - ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) + - ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0) + - (dictLoadMethod == ZSTD_dlm_byRef ? 0 - : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*)))); - void* const workspace = ZSTD_customMalloc(workspaceSize, customMem); + { size_t const workspaceSize = ZSTD_estimateCDictSize_internal(dictSize, + ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, enableDedicatedDictSearch, /* forCCtx */ 0), + dictLoadMethod); + void* workspace; ZSTD_cwksp ws; ZSTD_CDict* cdict; + if (ZSTD_isError(workspaceSize)) return NULL; + workspace = ZSTD_customMalloc(workspaceSize, customMem); if (!workspace) { ZSTD_customFree(workspace, customMem); return NULL; @@ -28611,7 +29230,10 @@ ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize, &cctxParams, customMem); } -ZSTD_CDict* ZSTD_createCDict_advanced2( +/* Preserve initialization errors for internal callers. The public constructors + * retain their pointer-or-NULL API. On failure, *cdictPtr remains NULL. */ +static size_t ZSTD_createCDict_advanced2_internal( + ZSTD_CDict** cdictPtr, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, @@ -28622,8 +29244,10 @@ ZSTD_CDict* ZSTD_createCDict_advanced2( ZSTD_compressionParameters cParams; ZSTD_CDict* cdict; + *cdictPtr = NULL; DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType); - if (!customMem.customAlloc ^ !customMem.customFree) return NULL; + RETURN_ERROR_IF((!customMem.customAlloc) ^ (!customMem.customFree), + parameter_combination_unsupported, "Invalid custom allocator"); if (cctxParams.enableDedicatedDictSearch) { cParams = ZSTD_dedicatedDictSearch_getCParams( @@ -28650,14 +29274,33 @@ ZSTD_CDict* ZSTD_createCDict_advanced2( cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch, customMem); - if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict, - dict, dictSize, - dictLoadMethod, dictContentType, - cctxParams) )) { - ZSTD_freeCDict(cdict); - return NULL; + RETURN_ERROR_IF(!cdict, memory_allocation, "Could not allocate CDict"); + { size_t const err = ZSTD_initCDict_internal(cdict, + dict, dictSize, + dictLoadMethod, dictContentType, + cctxParams); + if (ZSTD_isError(err)) { + ZSTD_freeCDict(cdict); + return err; + } } + *cdictPtr = cdict; + return 0; +} + +ZSTD_CDict* ZSTD_createCDict_advanced2( + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + const ZSTD_CCtx_params* originalCctxParams, + ZSTD_customMem customMem) +{ + ZSTD_CDict* cdict; + size_t const err = ZSTD_createCDict_advanced2_internal( + &cdict, dict, dictSize, dictLoadMethod, dictContentType, + originalCctxParams, customMem); + if (ZSTD_isError(err)) return NULL; return cdict; } @@ -28719,16 +29362,13 @@ const ZSTD_CDict* ZSTD_initStaticCDict( ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams); /* enableDedicatedDictSearch == 1 ensures matchstate is not too small in case this CDict will be used for DDS + row hash */ size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 1, /* forCCtx */ 0); - size_t const neededSize = ZSTD_cwksp_alloc_size(sizeof(ZSTD_CDict)) - + (dictLoadMethod == ZSTD_dlm_byRef ? 0 - : ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(dictSize, sizeof(void*)))) - + ZSTD_cwksp_alloc_size(HUF_WORKSPACE_SIZE) - + matchStateSize; + size_t const neededSize = ZSTD_estimateCDictSize_internal(dictSize, matchStateSize, dictLoadMethod); ZSTD_CDict* cdict; ZSTD_CCtx_params params; DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize); if ((size_t)workspace & 7) return NULL; /* 8-aligned */ + if (ZSTD_isError(neededSize) || workspaceSize < neededSize) return NULL; { ZSTD_cwksp ws; @@ -28738,8 +29378,6 @@ const ZSTD_CDict* ZSTD_initStaticCDict( ZSTD_cwksp_move(&cdict->workspace, &ws); } - if (workspaceSize < neededSize) return NULL; - ZSTD_CCtxParams_init(¶ms, 0); params.cParams = cParams; params.useRowMatchFinder = useRowMatchFinder; @@ -29414,14 +30052,15 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, if (cctx->streamStage == zcss_init) { size_t const inputSize = input->size - input->pos; /* no obligation to start from pos==0 */ size_t const totalInputSize = inputSize + cctx->stableIn_notConsumed; + if (cctx->stableIn_notConsumed) { /* not the first time */ + /* check stable source guarantees, including when this call starts compression */ + RETURN_ERROR_IF(cctx->requestedParams.inBufferMode != ZSTD_bm_stable, stabilityCondition_notRespected, "stableInBuffer condition not respected: disabled while input is pending"); + RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer"); + RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos"); + } if ( (cctx->requestedParams.inBufferMode == ZSTD_bm_stable) /* input is presumed stable, across invocations */ && (endOp == ZSTD_e_continue) /* no flush requested, more input to come */ && (totalInputSize < ZSTD_BLOCKSIZE_MAX) ) { /* not even reached one block yet */ - if (cctx->stableIn_notConsumed) { /* not the first time */ - /* check stable source guarantees */ - RETURN_ERROR_IF(input->src != cctx->expectedInBuffer.src, stabilityCondition_notRespected, "stableInBuffer condition not respected: wrong src pointer"); - RETURN_ERROR_IF(input->pos != cctx->expectedInBuffer.size, stabilityCondition_notRespected, "stableInBuffer condition not respected: externally modified pos"); - } /* pretend input was consumed, to give a sense forward progress */ input->pos = input->size; /* save stable inBuffer, for later control, and flush/end */ @@ -29441,6 +30080,21 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, #ifdef ZSTD_MULTITHREAD if (cctx->appliedParams.nbWorkers > 0) { size_t flushMin; + /* control src size before handing input to workers : + * once a job is posted, its output can no longer be withheld. + * Once the frame is ended, remaining input belongs to the next frame. */ + if ( (cctx->pledgedSrcSizePlusOne != 0) + && (!ZSTDMT_isFrameEnded(cctx->mtctx)) ) { + U64 const srcSizeIfAllConsumed = cctx->consumedSrcSize + cctx->stableIn_notConsumed + (U64)(input->size - input->pos); + ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1); + RETURN_ERROR_IF( + (srcSizeIfAllConsumed+1 > cctx->pledgedSrcSizePlusOne) + || ((endOp == ZSTD_e_end) && (srcSizeIfAllConsumed+1 != cctx->pledgedSrcSizePlusOne)), + srcSize_wrong, + "error : pledgedSrcSize = %u, while realSrcSize = %u", + (unsigned)cctx->pledgedSrcSizePlusOne-1, + (unsigned)srcSizeIfAllConsumed); + } if (cctx->cParamsChanged) { ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams); cctx->cParamsChanged = 0; @@ -29460,8 +30114,11 @@ size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, cctx->producedCSize += (U64)(output->pos - opos); if ( ZSTD_isError(flushMin) || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */ - if (flushMin == 0) + if (flushMin == 0) { + /* src size was controlled before handing input to workers */ + assert(cctx->pledgedSrcSizePlusOne == 0 || cctx->pledgedSrcSizePlusOne == cctx->consumedSrcSize+1); ZSTD_CCtx_trace(cctx, 0); + } ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only); } FORWARD_IF_ERROR(flushMin, "ZSTDMT_compressStream_generic failed"); @@ -29703,8 +30360,8 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, ZSTD_ParamSwitch_e externalRepSearch) { U32 idx = seqPos->idx; - U32 startPosInSequence = seqPos->posInSequence; - U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize; + U64 startPosInSequence = seqPos->posInSequence; + U64 endPosInSequence = seqPos->posInSequence + blockSize; size_t dictSize; const BYTE* const istart = (const BYTE*)(src); const BYTE* ip = istart; @@ -29723,40 +30380,41 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, } else { dictSize = 0; } - DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize); + DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %llu blockSize: %zu", idx, (unsigned long long)startPosInSequence, blockSize); DEBUGLOG(5, "Start seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength); ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t)); while (endPosInSequence && idx < inSeqsSize && !finalMatchSplit) { const ZSTD_Sequence currSeq = inSeqs[idx]; U32 litLength = currSeq.litLength; U32 matchLength = currSeq.matchLength; + U64 const sequenceLength = (U64)litLength + matchLength; U32 const rawOffset = currSeq.offset; U32 offBase; /* Modify the sequence depending on where endPosInSequence lies */ - if (endPosInSequence >= currSeq.litLength + currSeq.matchLength) { + if (endPosInSequence >= sequenceLength) { if (startPosInSequence >= litLength) { startPosInSequence -= litLength; litLength = 0; - matchLength -= startPosInSequence; + matchLength -= (U32)startPosInSequence; } else { - litLength -= startPosInSequence; + litLength -= (U32)startPosInSequence; } /* Move to the next sequence */ - endPosInSequence -= currSeq.litLength + currSeq.matchLength; + endPosInSequence -= sequenceLength; startPosInSequence = 0; } else { /* This is the final (partial) sequence we're adding from inSeqs, and endPosInSequence does not reach the end of the match. So, we have to split the sequence */ - DEBUGLOG(6, "Require a split: diff: %u, idx: %u PIS: %u", - currSeq.litLength + currSeq.matchLength - endPosInSequence, idx, endPosInSequence); + DEBUGLOG(6, "Require a split: diff: %llu, idx: %u PIS: %llu", + (unsigned long long)(sequenceLength - endPosInSequence), idx, (unsigned long long)endPosInSequence); if (endPosInSequence > litLength) { U32 firstHalfMatchLength; - litLength = startPosInSequence >= litLength ? 0 : litLength - startPosInSequence; - firstHalfMatchLength = endPosInSequence - startPosInSequence - litLength; + litLength = startPosInSequence >= litLength ? 0 : litLength - (U32)startPosInSequence; + firstHalfMatchLength = (U32)(endPosInSequence - startPosInSequence) - litLength; if (matchLength > blockSize && firstHalfMatchLength >= cctx->appliedParams.cParams.minMatch) { /* Only ever split the match if it is larger than the block size */ - U32 secondHalfMatchLength = currSeq.matchLength + currSeq.litLength - endPosInSequence; + U32 secondHalfMatchLength = (U32)(sequenceLength - endPosInSequence); if (secondHalfMatchLength < cctx->appliedParams.cParams.minMatch) { /* Move the endPosInSequence backward so that it creates match of minMatch length */ endPosInSequence -= cctx->appliedParams.cParams.minMatch - secondHalfMatchLength; @@ -29773,7 +30431,7 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, * should go. We prefer to do this whenever it is not necessary to split the match, or if doing so * would cause the first half of the match to be too small */ - bytesAdjustment = endPosInSequence - currSeq.litLength; + bytesAdjustment = (U32)(endPosInSequence - currSeq.litLength); endPosInSequence = currSeq.litLength; break; } @@ -29782,6 +30440,8 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, break; } } + /* The sequence now fits in this block, so its lengths can be added in U32. */ + assert((U64)litLength + matchLength <= blockSize); /* Check if this offset can be represented with a repcode */ { U32 const ll0 = (litLength == 0); offBase = ZSTD_finalizeOffBase(rawOffset, updatedRepcodes.rep, ll0); @@ -29803,7 +30463,7 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, idx++; /* Next Sequence */ } DEBUGLOG(5, "Ending seq: idx: %u (of: %u ml: %u ll: %u)", idx, inSeqs[idx].offset, inSeqs[idx].matchLength, inSeqs[idx].litLength); - assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength); + assert(idx == inSeqsSize || endPosInSequence <= (U64)inSeqs[idx].litLength + inSeqs[idx].matchLength); seqPos->idx = idx; seqPos->posInSequence = endPosInSequence; ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); @@ -29850,13 +30510,15 @@ static size_t blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos) { int end = 0; - size_t blockSize = 0; + U64 blockSize = 0; size_t spos = seqPos.idx; DEBUGLOG(6, "blockSize_explicitDelimiter : seq %zu / %zu", spos, inSeqsSize); assert(spos <= inSeqsSize); while (spos < inSeqsSize) { end = (inSeqs[spos].offset == 0); - blockSize += inSeqs[spos].litLength + inSeqs[spos].matchLength; + blockSize += (U64)inSeqs[spos].litLength + inSeqs[spos].matchLength; + RETURN_ERROR_IF(blockSize > ZSTD_BLOCKSIZE_MAX, externalSequences_invalid, + "sequences incorrectly define a too large block"); if (end) { if (inSeqs[spos].matchLength != 0) RETURN_ERROR(externalSequences_invalid, "delimiter format error : both matchlength and offset must be == 0"); @@ -29866,7 +30528,7 @@ blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD } if (!end) RETURN_ERROR(externalSequences_invalid, "Reached end of sequences without finding a block delimiter"); - return blockSize; + return (size_t)blockSize; } static size_t determine_blockSize(ZSTD_SequenceFormat_e mode, @@ -29959,7 +30621,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, blockSize, cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, - cctx->bmi2); + ZSTD_CCtx_get_bmi2(cctx)); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); @@ -30030,6 +30692,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, /* Begin writing output, starting with frame header */ { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID); + FORWARD_IF_ERROR(frameHeaderSize, "ZSTD_writeFrameHeader failed"); op += frameHeaderSize; assert(frameHeaderSize <= dstCapacity); dstCapacity -= frameHeaderSize; @@ -30064,7 +30727,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, } -#if defined(__AVX2__) +#if defined(ZSTD_ARCH_X86_AVX2) #include /* AVX2 intrinsics */ @@ -30084,7 +30747,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * @returns > 0 if there is one long length (> 65535), * indicating the position, and type. */ -static size_t convertSequences_noRepcodes( +size_t convertSequences_noRepcodes( SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) @@ -30230,13 +30893,378 @@ static size_t convertSequences_noRepcodes( return longLen; } +#elif defined (ZSTD_ARCH_RISCV_RVV) +#include +/* + * Convert `vl` sequences per iteration, using RVV intrinsics: + * - offset -> offBase = offset + 2 + * - litLength -> (U16) litLength + * - matchLength -> (U16)(matchLength - 3) + * - rep is ignored + * Store only 8 bytes per SeqDef (offBase[4], litLength[2], mlBase[2]). + * + * @returns 0 on succes, with no long length detected + * @returns > 0 if there is one long length (> 65535), + * indicating the position, and type. + */ +size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) { + size_t longLen = 0; + size_t vl = 0; + typedef uint32_t __attribute__((may_alias)) aliased_u32; + /* RVV depends on the specific definition of target structures */ + ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8); + ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6); + + for (size_t i = 0; i < nbSequences; i += vl) { + + vl = __riscv_vsetvl_e32m2(nbSequences-i); + { + // Loading structure member variables + vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4( + (const aliased_u32*)((const void*)&inSeqs[i]), + vl + ); + vuint32m2_t v_offset = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 0); + vuint32m2_t v_lit = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 1); + vuint32m2_t v_match = __riscv_vget_v_u32m2x4_u32m2(v_tuple, 2); + // offset + ZSTD_REP_NUM + vuint32m2_t v_offBase = __riscv_vadd_vx_u32m2(v_offset, ZSTD_REP_NUM, vl); + // Check for integer overflow + // Cast to a 16-bit variable + vbool16_t lit_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_lit, 65535, vl); + vuint16m1_t v_lit_clamped = __riscv_vncvt_x_x_w_u16m1(v_lit, vl); + + vbool16_t ml_overflow = __riscv_vmsgtu_vx_u32m2_b16(v_match, 65535+MINMATCH, vl); + vuint16m1_t v_ml_clamped = __riscv_vncvt_x_x_w_u16m1(__riscv_vsub_vx_u32m2(v_match, MINMATCH, vl), vl); + + // Pack two 16-bit fields into a 32-bit value (little-endian) + // The lower 16 bits contain litLength, and the upper 16 bits contain mlBase + vuint32m2_t v_lit_ml_combined = __riscv_vsll_vx_u32m2( + __riscv_vwcvtu_x_x_v_u32m2(v_ml_clamped, vl), // Convert matchLength to 32-bit + 16, + vl + ); + v_lit_ml_combined = __riscv_vor_vv_u32m2( + v_lit_ml_combined, + __riscv_vwcvtu_x_x_v_u32m2(v_lit_clamped, vl), + vl + ); + { + // Create a vector of SeqDef structures + // Store the offBase, litLength, and mlBase in a vector of SeqDef + vuint32m2x2_t store_data = __riscv_vcreate_v_u32m2x2( + v_offBase, + v_lit_ml_combined + ); + __riscv_vsseg2e32_v_u32m2x2( + (aliased_u32*)((void*)&dstSeqs[i]), + store_data, + vl + ); + } + { + // Find the first index where an overflow occurs + int first_ml = __riscv_vfirst_m_b16(ml_overflow, vl); + int first_lit = __riscv_vfirst_m_b16(lit_overflow, vl); + + if (UNLIKELY(first_ml != -1)) { + assert(longLen == 0); + longLen = i + first_ml + 1; + } + if (UNLIKELY(first_lit != -1)) { + assert(longLen == 0); + longLen = i + first_lit + 1 + nbSequences; + } + } + } + } + return longLen; +} + /* the vector implementation could also be ported to SSSE3, * but since this implementation is targeting modern systems (>= Sapphire Rapid), * it's not useful to develop and maintain code for older pre-AVX2 platforms */ -#else /* no AVX2 */ +#elif defined(ZSTD_ARCH_ARM_SVE2) + +/* + * Checks if any active element in a signed 8-bit integer vector is greater + * than zero. + * + * @param g Governing predicate selecting active lanes. + * @param a Input vector of signed 8-bit integers. + * + * @return True if any active element in `a` is > 0, false otherwise. + */ +FORCE_INLINE_TEMPLATE int cmpgtz_any_s8(svbool_t g, svint8_t a) +{ + svbool_t ptest = svcmpgt_n_s8(g, a, 0); + return svptest_any(ptest, ptest); +} -static size_t convertSequences_noRepcodes( +size_t convertSequences_noRepcodes( + SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) +{ + /* Process the input with `8 * VL / element` lanes. */ + const size_t lanes = 8 * svcntb() / sizeof(ZSTD_Sequence); + size_t longLen = 0; + size_t n = 0; + + /* SVE permutation depends on the specific definition of target structures. */ + ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8); + ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6); + + if (nbSequences >= lanes) { + const svbool_t ptrue = svptrue_b8(); + /* 16-bit of {ZSTD_REP_NUM, 0, -MINMATCH, 0} extended to 32-bit lanes. */ + const svuint32_t vaddition = svreinterpret_u32( + svunpklo_s32(svreinterpret_s16(svdup_n_u64(ZSTD_REP_NUM | (((U64)(U16)-MINMATCH) << 32))))); + /* For permutation of 16-bit units: 0, 1, 2, 4, 8, 9, 10, 12, ... */ + const svuint16_t vmask = svreinterpret_u16( + svindex_u64(0x0004000200010000, 0x0008000800080008)); + /* Upper bytes of `litLength` and `matchLength` will be packed into the + * middle of overflow check vector. */ + const svbool_t pmid = svcmpne_n_u8( + ptrue, svreinterpret_u8(svdup_n_u64(0x0000FFFFFFFF0000)), 0); + + do { + /* Load `lanes` number of `ZSTD_Sequence` into 8 vectors. */ + const svuint32_t vin0 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 0); + const svuint32_t vin1 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 1); + const svuint32_t vin2 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 2); + const svuint32_t vin3 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 3); + const svuint32_t vin4 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 4); + const svuint32_t vin5 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 5); + const svuint32_t vin6 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 6); + const svuint32_t vin7 = svld1_vnum_u32(ptrue, &inSeqs[n].offset, 7); + + /* Add {ZSTD_REP_NUM, 0, -MINMATCH, 0} to each structures. */ + const svuint16x2_t vadd01 = svcreate2_u16( + svreinterpret_u16(svadd_u32_x(ptrue, vin0, vaddition)), + svreinterpret_u16(svadd_u32_x(ptrue, vin1, vaddition))); + const svuint16x2_t vadd23 = svcreate2_u16( + svreinterpret_u16(svadd_u32_x(ptrue, vin2, vaddition)), + svreinterpret_u16(svadd_u32_x(ptrue, vin3, vaddition))); + const svuint16x2_t vadd45 = svcreate2_u16( + svreinterpret_u16(svadd_u32_x(ptrue, vin4, vaddition)), + svreinterpret_u16(svadd_u32_x(ptrue, vin5, vaddition))); + const svuint16x2_t vadd67 = svcreate2_u16( + svreinterpret_u16(svadd_u32_x(ptrue, vin6, vaddition)), + svreinterpret_u16(svadd_u32_x(ptrue, vin7, vaddition))); + + /* Shuffle and pack bytes so each vector contains SeqDef structures. */ + const svuint16_t vout01 = svtbl2_u16(vadd01, vmask); + const svuint16_t vout23 = svtbl2_u16(vadd23, vmask); + const svuint16_t vout45 = svtbl2_u16(vadd45, vmask); + const svuint16_t vout67 = svtbl2_u16(vadd67, vmask); + + /* Pack the upper 16-bits of 32-bit lanes for overflow check. */ + const svuint16_t voverflow01 = svuzp2_u16(svget2_u16(vadd01, 0), + svget2_u16(vadd01, 1)); + const svuint16_t voverflow23 = svuzp2_u16(svget2_u16(vadd23, 0), + svget2_u16(vadd23, 1)); + const svuint16_t voverflow45 = svuzp2_u16(svget2_u16(vadd45, 0), + svget2_u16(vadd45, 1)); + const svuint16_t voverflow67 = svuzp2_u16(svget2_u16(vadd67, 0), + svget2_u16(vadd67, 1)); + + /* We don't need the whole 16 bits of the overflow part. Only 1 bit + * is needed, so we pack tightly and merge multiple vectors to be + * able to use a single comparison to handle the overflow case. + * However, we also need to handle the possible negative values of + * matchLength parts, so we use signed comparison later. */ + const svint8_t voverflow = + svmax_s8_x(pmid, + svtrn1_s8(svreinterpret_s8(voverflow01), + svreinterpret_s8(voverflow23)), + svtrn1_s8(svreinterpret_s8(voverflow45), + svreinterpret_s8(voverflow67))); + + /* Store `lanes` number of `SeqDef` structures from 4 vectors. */ + svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 0, svreinterpret_u32(vout01)); + svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 1, svreinterpret_u32(vout23)); + svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 2, svreinterpret_u32(vout45)); + svst1_vnum_u32(ptrue, &dstSeqs[n].offBase, 3, svreinterpret_u32(vout67)); + + /* Check if any enabled lanes of the overflow vector is larger than + * zero, only one such may happen. */ + if (UNLIKELY(cmpgtz_any_s8(pmid, voverflow))) { + /* Scalar search for long match is needed because we merged + * multiple overflow bytes with `max`. */ + size_t i; + for (i = n; i < n + lanes; i++) { + if (inSeqs[i].matchLength > 65535 + MINMATCH) { + assert(longLen == 0); + longLen = i + 1; + } + if (inSeqs[i].litLength > 65535) { + assert(longLen == 0); + longLen = i + nbSequences + 1; + } + } + } + + n += lanes; + } while(n <= nbSequences - lanes); + } + + /* Handle remaining elements. */ + for (; n < nbSequences; n++) { + dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset); + dstSeqs[n].litLength = (U16)inSeqs[n].litLength; + dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); + /* Check for long length > 65535. */ + if (UNLIKELY(inSeqs[n].matchLength > 65535 + MINMATCH)) { + assert(longLen == 0); + longLen = n + 1; + } + if (UNLIKELY(inSeqs[n].litLength > 65535)) { + assert(longLen == 0); + longLen = n + nbSequences + 1; + } + } + return longLen; +} + +#elif defined(ZSTD_ARCH_ARM_NEON) && (defined(__aarch64__) || defined(_M_ARM64)) + +size_t convertSequences_noRepcodes( + SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) +{ + size_t longLen = 0; + size_t n = 0; + + /* Neon permutation depends on the specific definition of target structures. */ + ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, offset) == 0); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8); + ZSTD_STATIC_ASSERT(sizeof(SeqDef) == 8); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4); + ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6); + + if (nbSequences > 3) { + static const ZSTD_ALIGNED(16) U32 constAddition[4] = { + ZSTD_REP_NUM, 0, -MINMATCH, 0 + }; + static const ZSTD_ALIGNED(16) U8 constMask[16] = { + 0, 1, 2, 3, 4, 5, 8, 9, 16, 17, 18, 19, 20, 21, 24, 25 + }; + static const ZSTD_ALIGNED(16) U16 constCounter[8] = { + 1, 1, 1, 1, 2, 2, 2, 2 + }; + + const uint32x4_t vaddition = vld1q_u32(constAddition); + const uint8x16_t vmask = vld1q_u8(constMask); + uint16x8_t vcounter = vld1q_u16(constCounter); + uint16x8_t vindex01 = vdupq_n_u16(0); + uint16x8_t vindex23 = vdupq_n_u16(0); + + do { + /* Load 4 ZSTD_Sequence (64 bytes). */ + const uint32x4_t vin0 = vld1q_u32(&inSeqs[n + 0].offset); + const uint32x4_t vin1 = vld1q_u32(&inSeqs[n + 1].offset); + const uint32x4_t vin2 = vld1q_u32(&inSeqs[n + 2].offset); + const uint32x4_t vin3 = vld1q_u32(&inSeqs[n + 3].offset); + + /* Add {ZSTD_REP_NUM, 0, -MINMATCH, 0} to each vector. */ + const uint8x16x2_t vadd01 = { { + vreinterpretq_u8_u32(vaddq_u32(vin0, vaddition)), + vreinterpretq_u8_u32(vaddq_u32(vin1, vaddition)), + } }; + const uint8x16x2_t vadd23 = { { + vreinterpretq_u8_u32(vaddq_u32(vin2, vaddition)), + vreinterpretq_u8_u32(vaddq_u32(vin3, vaddition)), + } }; + + /* Shuffle and pack bytes so each vector contains 2 SeqDef structures. */ + const uint8x16_t vout01 = vqtbl2q_u8(vadd01, vmask); + const uint8x16_t vout23 = vqtbl2q_u8(vadd23, vmask); + + /* Pack the upper 16-bits of 32-bit lanes for overflow check. */ + uint16x8_t voverflow01 = vuzp2q_u16(vreinterpretq_u16_u8(vadd01.val[0]), + vreinterpretq_u16_u8(vadd01.val[1])); + uint16x8_t voverflow23 = vuzp2q_u16(vreinterpretq_u16_u8(vadd23.val[0]), + vreinterpretq_u16_u8(vadd23.val[1])); + + /* Store 4 SeqDef structures. */ + vst1q_u32(&dstSeqs[n + 0].offBase, vreinterpretq_u32_u8(vout01)); + vst1q_u32(&dstSeqs[n + 2].offBase, vreinterpretq_u32_u8(vout23)); + + /* Create masks in case of overflow. */ + voverflow01 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow01)); + voverflow23 = vcgtzq_s16(vreinterpretq_s16_u16(voverflow23)); + + /* Update overflow indices. */ + vindex01 = vbslq_u16(voverflow01, vcounter, vindex01); + vindex23 = vbslq_u16(voverflow23, vcounter, vindex23); + + /* Update counter for overflow check. */ + vcounter = vaddq_u16(vcounter, vdupq_n_u16(4)); + + n += 4; + } while(n < nbSequences - 3); + + /* Fixup indices in the second vector, we saved an additional counter + in the loop to update the second overflow index, we need to add 2 + here when the indices are not 0. */ + { uint16x8_t nonzero = vtstq_u16(vindex23, vindex23); + vindex23 = vsubq_u16(vindex23, nonzero); + vindex23 = vsubq_u16(vindex23, nonzero); + } + + /* Merge indices in the vectors, maximums are needed. */ + vindex01 = vmaxq_u16(vindex01, vindex23); + vindex01 = vmaxq_u16(vindex01, vextq_u16(vindex01, vindex01, 4)); + + /* Compute `longLen`, maximums of matchLength and litLength + with a preference on litLength. */ + { U64 maxLitMatchIndices = vgetq_lane_u64(vreinterpretq_u64_u16(vindex01), 0); + size_t maxLitIndex = (maxLitMatchIndices >> 16) & 0xFFFF; + size_t maxMatchIndex = (maxLitMatchIndices >> 32) & 0xFFFF; + longLen = maxLitIndex > maxMatchIndex ? maxLitIndex + nbSequences + : maxMatchIndex; + } + } + + /* Handle remaining elements. */ + for (; n < nbSequences; n++) { + dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset); + dstSeqs[n].litLength = (U16)inSeqs[n].litLength; + dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); + /* Check for long length > 65535. */ + if (UNLIKELY(inSeqs[n].matchLength > 65535 + MINMATCH)) { + assert(longLen == 0); + longLen = n + 1; + } + if (UNLIKELY(inSeqs[n].litLength > 65535)) { + assert(longLen == 0); + longLen = n + nbSequences + 1; + } + } + return longLen; +} + +#else /* No vectorization. */ + +size_t convertSequences_noRepcodes( SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) @@ -30247,7 +31275,7 @@ static size_t convertSequences_noRepcodes( dstSeqs[n].offBase = OFFSET_TO_OFFBASE(inSeqs[n].offset); dstSeqs[n].litLength = (U16)inSeqs[n].litLength; dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); - /* check for long length > 65535 */ + /* Check for long length > 65535. */ if (UNLIKELY(inSeqs[n].matchLength > 65535+MINMATCH)) { assert(longLen == 0); longLen = n + 1; @@ -30397,34 +31425,172 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) } } -#else +#elif defined (ZSTD_ARCH_RISCV_RVV) BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { size_t totalMatchSize = 0; size_t litSize = 0; - size_t n; - assert(seqs); - for (n=0; n= 0) { + // Find the first zero byte and set the effective length to that index + 1 to + // recompute the cumulative vector length of literals and matches + vl = first_zero + 1; + + // recompute the cumulative vector length of literals and matches + v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_lit, 0, vl), v_lit_sum, vl); + v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(__riscv_vslidedown_vx_u32m2(v_match, 0, vl), v_match_sum, vl); + + i += vl; + found_terminator = 1; + assert(seqs[i - 1].offset == 0); break; + } else { + + v_lit_sum = __riscv_vredsum_vs_u32m2_u32m1(v_lit, v_lit_sum, vl); + v_match_sum = __riscv_vredsum_vs_u32m2_u32m1(v_match, v_match_sum, vl); + i += vl; } } - if (n==nbSeqs) { + litSize = __riscv_vmv_x_s_u32m1_u32(v_lit_sum); + totalMatchSize = __riscv_vmv_x_s_u32m1_u32(v_match_sum); + + if (!found_terminator && i==nbSeqs) { BlockSummary bs; bs.nbSequences = ERROR(externalSequences_invalid); return bs; } { BlockSummary bs; - bs.nbSequences = n+1; + bs.nbSequences = i; bs.blockSize = litSize + totalMatchSize; bs.litSize = litSize; return bs; } } + +#else + +/* + * The function assumes `litMatchLength` is a packed 64-bit value where the + * lower 32 bits represent the match length. The check varies based on the + * system's endianness: + * - On little-endian systems, it verifies if the entire 64-bit value is at most + * 0xFFFFFFFF, indicating the match length (lower 32 bits) is zero. + * - On big-endian systems, it directly checks if the lower 32 bits are zero. + * + * @returns 1 if the match length is zero, 0 otherwise. + */ +FORCE_INLINE_TEMPLATE int matchLengthHalfIsZero(U64 litMatchLength) +{ + if (MEM_isLittleEndian()) { + return litMatchLength <= 0xFFFFFFFFULL; + } else { + return (U32)litMatchLength == 0; + } +} + +BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) +{ + /* Use multiple accumulators for efficient use of wide out-of-order machines. */ + U64 litMatchSize0 = 0; + U64 litMatchSize1 = 0; + U64 litMatchSize2 = 0; + U64 litMatchSize3 = 0; + size_t n = 0; + + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, litLength) + 4 == offsetof(ZSTD_Sequence, matchLength)); + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) + 4 == offsetof(ZSTD_Sequence, rep)); + assert(seqs); + + if (nbSeqs > 3) { + /* Process the input in 4 independent streams to reach high throughput. */ + do { + /* Load `litLength` and `matchLength` as a packed `U64`. It is safe + * to use 64-bit unsigned arithmetic here because the sum of `litLength` + * and `matchLength` cannot exceed the block size, so the 32-bit + * subparts will never overflow. */ + U64 litMatchLength = MEM_read64(&seqs[n].litLength); + litMatchSize0 += litMatchLength; + if (matchLengthHalfIsZero(litMatchLength)) { + assert(seqs[n].offset == 0); + goto _out; + } + + litMatchLength = MEM_read64(&seqs[n + 1].litLength); + litMatchSize1 += litMatchLength; + if (matchLengthHalfIsZero(litMatchLength)) { + n += 1; + assert(seqs[n].offset == 0); + goto _out; + } + + litMatchLength = MEM_read64(&seqs[n + 2].litLength); + litMatchSize2 += litMatchLength; + if (matchLengthHalfIsZero(litMatchLength)) { + n += 2; + assert(seqs[n].offset == 0); + goto _out; + } + + litMatchLength = MEM_read64(&seqs[n + 3].litLength); + litMatchSize3 += litMatchLength; + if (matchLengthHalfIsZero(litMatchLength)) { + n += 3; + assert(seqs[n].offset == 0); + goto _out; + } + + n += 4; + } while(n < nbSeqs - 3); + } + + for (; n < nbSeqs; n++) { + U64 litMatchLength = MEM_read64(&seqs[n].litLength); + litMatchSize0 += litMatchLength; + if (matchLengthHalfIsZero(litMatchLength)) { + assert(seqs[n].offset == 0); + goto _out; + } + } + /* At this point n == nbSeqs, so no end terminator. */ + { BlockSummary bs; + bs.nbSequences = ERROR(externalSequences_invalid); + return bs; + } +_out: + litMatchSize0 += litMatchSize1 + litMatchSize2 + litMatchSize3; + { BlockSummary bs; + bs.nbSequences = n + 1; + if (MEM_isLittleEndian()) { + bs.litSize = (U32)litMatchSize0; + bs.blockSize = bs.litSize + (litMatchSize0 >> 32); + } else { + bs.litSize = litMatchSize0 >> 32; + bs.blockSize = bs.litSize + (U32)litMatchSize0; + } + return bs; + } +} #endif @@ -30460,6 +31626,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block"); assert(block.nbSequences <= nbSequences); RETURN_ERROR_IF(block.litSize > litSize, externalSequences_invalid, "discrepancy: Sequences require more literals than present in buffer"); + RETURN_ERROR_IF(block.blockSize > cctx->blockSizeMax, externalSequences_invalid, "sequences incorrectly define a too large block"); ZSTD_resetSeqStore(&cctx->seqStore); conversionStatus = ZSTD_convertBlockSequences(cctx, @@ -30484,7 +31651,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, &cctx->appliedParams, cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, - cctx->bmi2); + ZSTD_CCtx_get_bmi2(cctx)); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); /* note: the spec forbids for any compressed block to be larger than maximum block size */ if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0; @@ -30548,7 +31715,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Transparent initialization stage, same as compressStream2() */ DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); assert(cctx != NULL); - if (litCapacity < litSize) { + if (litCapacity < litSize || litCapacity - litSize < 8) { RETURN_ERROR(workSpace_tooSmall, "literals buffer is not large enough: must be at least 8 bytes larger than litSize (risk of read out-of-bound)"); } FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, decompressedSize), "CCtx initialization failed"); @@ -30566,6 +31733,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Begin writing output, starting with frame header */ { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, decompressedSize, cctx->dictID); + FORWARD_IF_ERROR(frameHeaderSize, "ZSTD_writeFrameHeader failed"); op += frameHeaderSize; assert(frameHeaderSize <= dstCapacity); dstCapacity -= frameHeaderSize; @@ -30592,7 +31760,8 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs) { const ZSTD_inBuffer nullInput = { NULL, 0, 0 }; - const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable); + const int stableInput = (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) + || (zcs->stableIn_notConsumed > 0); /* pending input, parameters not applied yet */ return stableInput ? zcs->expectedInBuffer : nullInput; } @@ -31309,8 +32478,8 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( /* init */ ip += (dictAndPrefixLength == 0); - /* dictMatchState repCode checks don't currently handle repCode == 0 - * disabling. */ + /* Dictionary repcodes are validated when the CDict is attached. + * dictMatchState repCode checks don't handle repCode == 0 disabling. */ assert(offset_1 <= dictAndPrefixLength); assert(offset_2 <= dictAndPrefixLength); @@ -32246,8 +33415,8 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( /* init */ DEBUGLOG(5, "ZSTD_compressBlock_fast_dictMatchState_generic"); ip0 += (dictAndPrefixLength == 0); - /* dictMatchState repCode checks don't currently handle repCode == 0 - * disabling. */ + /* Dictionary repcodes are validated when the CDict is attached. + * dictMatchState repCode checks don't handle repCode == 0 disabling. */ assert(offset_1 <= dictAndPrefixLength); assert(offset_2 <= dictAndPrefixLength); @@ -33751,6 +34920,44 @@ ZSTD_row_getNEONMask(const U32 rowEntries, const BYTE* const src, const BYTE tag } } #endif +#if defined(ZSTD_ARCH_RISCV_RVV) && (__riscv_xlen == 64) +FORCE_INLINE_TEMPLATE ZSTD_VecMask +ZSTD_row_getRVVMask(int rowEntries, const BYTE* const src, const BYTE tag, const U32 head) +{ + ZSTD_VecMask matches; + size_t vl; + + if (rowEntries == 16) { + vl = __riscv_vsetvl_e8m1(16); + { + vuint8m1_t chunk = __riscv_vle8_v_u8m1(src, vl); + vbool8_t mask = __riscv_vmseq_vx_u8m1_b8(chunk, tag, vl); + vuint16m1_t mask_u16 = __riscv_vreinterpret_v_b8_u16m1(mask); + matches = __riscv_vmv_x_s_u16m1_u16(mask_u16); + return ZSTD_rotateRight_U16((U16)matches, head); + } + + } else if (rowEntries == 32) { + vl = __riscv_vsetvl_e8m2(32); + { + vuint8m2_t chunk = __riscv_vle8_v_u8m2(src, vl); + vbool4_t mask = __riscv_vmseq_vx_u8m2_b4(chunk, tag, vl); + vuint32m1_t mask_u32 = __riscv_vreinterpret_v_b4_u32m1(mask); + matches = __riscv_vmv_x_s_u32m1_u32(mask_u32); + return ZSTD_rotateRight_U32((U32)matches, head); + } + } else { // rowEntries = 64 + vl = __riscv_vsetvl_e8m4(64); + { + vuint8m4_t chunk = __riscv_vle8_v_u8m4(src, vl); + vbool2_t mask = __riscv_vmseq_vx_u8m4_b2(chunk, tag, vl); + vuint64m1_t mask_u64 = __riscv_vreinterpret_v_b2_u64m1(mask); + matches = __riscv_vmv_x_s_u64m1_u64(mask_u64); + return ZSTD_rotateRight_U64(matches, head); + } + } +} +#endif /* Returns a ZSTD_VecMask (U64) that has the nth group (determined by * ZSTD_row_matchMaskGroupWidth) of bits set to 1 if the newly-computed "tag" @@ -33770,14 +34977,20 @@ ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGr return ZSTD_row_getSSEMask(rowEntries / 16, src, tag, headGrouped); -#else /* SW or NEON-LE */ +#elif defined(ZSTD_ARCH_RISCV_RVV) && (__riscv_xlen == 64) -# if defined(ZSTD_ARCH_ARM_NEON) + return ZSTD_row_getRVVMask(rowEntries, src, tag, headGrouped); + +#else + +#if defined(ZSTD_ARCH_ARM_NEON) /* This NEON path only works for little endian - otherwise use SWAR below */ if (MEM_isLittleEndian()) { return ZSTD_row_getNEONMask(rowEntries, src, tag, headGrouped); } -# endif /* ZSTD_ARCH_ARM_NEON */ + + +#endif /* SWAR */ { const int chunkSize = sizeof(size_t); const size_t shiftAmount = ((chunkSize * 8) - chunkSize); @@ -34258,8 +35471,8 @@ size_t ZSTD_compressBlock_lazy_generic( if (offset_1 > maxRep) offsetSaved1 = offset_1, offset_1 = 0; } if (isDxS) { - /* dictMatchState repCode checks don't currently handle repCode == 0 - * disabling. */ + /* Dictionary repcodes are validated when the CDict is attached. + * dictMatchState repCode checks don't handle repCode == 0 disabling. */ assert(offset_1 <= dictAndPrefixLength); assert(offset_2 <= dictAndPrefixLength); } @@ -35029,11 +36242,6 @@ static UNUSED_ATTR const U64 ZSTD_ldm_gearTab[256] = { #define LDM_MIN_MATCH_LENGTH 64 #define LDM_HASH_RLOG 7 -typedef struct { - U64 rolling; - U64 stopMask; -} ldmRollingHashState_t; - /** ZSTD_ldm_gear_init(): * * Initializes the rolling hash state such that it will honor the @@ -35071,8 +36279,8 @@ static void ZSTD_ldm_gear_init(ldmRollingHashState_t* state, ldmParams_t const* * splits. This effectively resets the hash state. This is used when skipping * over data, either at the beginning of a block, or skipping sections. */ -static void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state, - BYTE const* data, size_t minMatchLength) +void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state, + BYTE const* data, size_t minMatchLength) { U64 hash = state->rolling; size_t n = 0; @@ -35091,6 +36299,7 @@ static void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state, GEAR_ITER_ONCE(); } #undef GEAR_ITER_ONCE + state->rolling = hash; } /** ZSTD_ldm_gear_feed(): @@ -35102,9 +36311,9 @@ static void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state, * * Precondition: The splits array must not be full. * Returns: The number of bytes processed. */ -static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state, - BYTE const* data, size_t size, - size_t* splits, unsigned* numSplits) +size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state, + BYTE const* data, size_t size, + size_t* splits, unsigned* numSplits) { size_t n; U64 hash, mask; @@ -35161,7 +36370,11 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, } } if (params->hashLog == 0) { - params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX); + if (params->windowLog <= params->hashRateLog) { + params->hashLog = ZSTD_HASHLOG_MIN; + } else { + params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX); + } } if (params->minMatchLength == 0) { params->minMatchLength = LDM_MIN_MATCH_LENGTH; @@ -35886,6 +37099,16 @@ static U32 ZSTD_scaleStats(unsigned* table, U32 lastEltIndex, U32 logTarget) return ZSTD_downscaleStats(table, lastEltIndex, ZSTD_highbit32(factor), base_1guaranteed); } +/* Dictionary tables can assign costs at or above the frequency scale: + * absent FSE symbols cost tableLog+1, and the Huffman reader accepts tables + * deeper than LitHufLog. Keep a minimum frequency of 1 without underflowing + * the shift. A zero cost also retains its historical minimum frequency. */ +static U32 ZSTD_freqFromBitCost(U32 bitCost, U32 scaleLog) +{ + assert(scaleLog < 31); + return bitCost > 0 && bitCost < scaleLog ? 1U << (scaleLog - bitCost) : 1; +} + /* ZSTD_rescaleFreqs() : * if first block (detected by optPtr->litLengthSum == 0) : init statistics * take hints from dictionary if there is one @@ -35924,8 +37147,7 @@ ZSTD_rescaleFreqs(optState_t* const optPtr, for (lit=0; lit<=MaxLit; lit++) { U32 const scaleLog = 11; /* scale to 2K */ U32 const bitCost = HUF_getNbBitsFromCTable(optPtr->symbolCosts->huf.CTable, lit); - assert(bitCost <= scaleLog); - optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; + optPtr->litFreq[lit] = ZSTD_freqFromBitCost(bitCost, scaleLog); optPtr->litSum += optPtr->litFreq[lit]; } } @@ -35936,8 +37158,7 @@ ZSTD_rescaleFreqs(optState_t* const optPtr, for (ll=0; ll<=MaxLL; ll++) { U32 const scaleLog = 10; /* scale to 1K */ U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll); - assert(bitCost < scaleLog); - optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; + optPtr->litLengthFreq[ll] = ZSTD_freqFromBitCost(bitCost, scaleLog); optPtr->litLengthSum += optPtr->litLengthFreq[ll]; } } @@ -35948,8 +37169,7 @@ ZSTD_rescaleFreqs(optState_t* const optPtr, for (ml=0; ml<=MaxML; ml++) { U32 const scaleLog = 10; U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml); - assert(bitCost < scaleLog); - optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; + optPtr->matchLengthFreq[ml] = ZSTD_freqFromBitCost(bitCost, scaleLog); optPtr->matchLengthSum += optPtr->matchLengthFreq[ml]; } } @@ -35960,8 +37180,7 @@ ZSTD_rescaleFreqs(optState_t* const optPtr, for (of=0; of<=MaxOff; of++) { U32 const scaleLog = 10; U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of); - assert(bitCost < scaleLog); - optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/; + optPtr->offCodeFreq[of] = ZSTD_freqFromBitCost(bitCost, scaleLog); optPtr->offCodeSum += optPtr->offCodeFreq[of]; } } @@ -37138,16 +38357,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, assert(storeEnd < ZSTD_OPT_SIZE); DEBUGLOG(6, "last stretch copied into pos=%u (llen=%u,mlen=%u,ofc=%u)", storeEnd, lastStretch.litlen, lastStretch.mlen, lastStretch.off); - if (lastStretch.litlen > 0) { - /* last "sequence" is unfinished: just a bunch of literals */ - opt[storeEnd].litlen = lastStretch.litlen; - opt[storeEnd].mlen = 0; - storeStart = storeEnd-1; - opt[storeStart] = lastStretch; - } { - opt[storeEnd] = lastStretch; /* note: litlen will be fixed */ - storeStart = storeEnd; - } + opt[storeEnd] = lastStretch; /* note: litlen will be fixed */ + storeStart = storeEnd; while (1) { ZSTD_optimal_t nextStretch = opt[stretchPos]; opt[storeStart].litlen = nextStretch.litlen; @@ -37802,10 +39013,7 @@ static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx) /* ==== Serial State ==== */ -typedef struct { - void const* start; - size_t size; -} Range; +typedef ZSTDMT_Range Range; typedef struct { /* All variables in the struct are protected by mutex. */ @@ -38001,6 +39209,7 @@ static const Range kNullRange = { NULL, 0 }; typedef struct { size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */ size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */ + unsigned completed; /* SHARED - set0 by mtctx, then set1 by worker when it no longer uses the job */ ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */ ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */ ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */ @@ -38153,7 +39362,8 @@ static void ZSTDMT_compressionJob(void* jobDescription) ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0); job->cSize += lastCBlockSize; - job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */ + job->consumed = job->src.size; + job->completed = 1; /* also true for an empty job, unlike consumed == src.size */ ZSTD_pthread_cond_signal(&job->job_cond); ZSTD_pthread_mutex_unlock(&job->job_mutex); } @@ -38347,21 +39557,24 @@ static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx) { unsigned jobID; DEBUGLOG(3, "ZSTDMT_releaseAllJobResources"); - for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) { - /* Copy the mutex/cond out */ - ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex; - ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond; - - DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start); - ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff); - - /* Clear the job description, but keep the mutex/cond */ - ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID])); - mtctx->jobs[jobID].job_mutex = mutex; - mtctx->jobs[jobID].job_cond = cond; + if (mtctx->jobs) { + for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) { + /* Copy the mutex/cond out */ + ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex; + ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond; + + DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start); + ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff); + + /* Clear the job description, but keep the mutex/cond */ + ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID])); + mtctx->jobs[jobID].job_mutex = mutex; + mtctx->jobs[jobID].job_cond = cond; + } } mtctx->inBuff.buffer = g_nullBuffer; mtctx->inBuff.filled = 0; + mtctx->jobReady = 0; /* the prepared job was cleared above */ mtctx->allJobsCompleted = 1; } @@ -38371,7 +39584,7 @@ static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx) while (mtctx->doneJobID < mtctx->nextJobID) { unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask; ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex); - while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) { + while (!mtctx->jobs[jobID].completed) { DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */ ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex); } @@ -38380,9 +39593,18 @@ static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx) } } +void ZSTDMT_waitForPendingJobs(ZSTDMT_CCtx* mtctx) +{ + if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */ + ZSTDMT_waitForAllJobsCompleted(mtctx); + ZSTDMT_releaseAllJobResources(mtctx); /* Will set allJobsCompleted to 1 */ + } +} + size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx) { if (mtctx==NULL) return 0; /* compatible with free on NULL */ + ZSTDMT_waitForPendingJobs(mtctx); /* a shared pool is not stopped below */ if (!mtctx->providedFactory) POOL_free(mtctx->factory); /* stop and free worker threads */ ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */ @@ -38416,7 +39638,9 @@ size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx) * @return : error code if fails, 0 on success */ static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers) { - if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation); + if (!mtctx->providedFactory) { /* a pool provided by the application keeps its size */ + if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation); + } FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , ""); mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, BUF_POOL_MAX_NB_BUFFERS(nbWorkers)); if (mtctx->bufPool == NULL) return ERROR(memory_allocation); @@ -38599,18 +39823,13 @@ size_t ZSTDMT_initCStream_internal( assert(!((dict) && (cdict))); /* either dict or cdict, not both */ /* init */ + ZSTDMT_waitForPendingJobs(mtctx); /* before resizing the pools they use */ if (params.nbWorkers != mtctx->params.nbWorkers) FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, (unsigned)params.nbWorkers) , ""); if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN; if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX; - if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */ - ZSTDMT_waitForAllJobsCompleted(mtctx); - ZSTDMT_releaseAllJobResources(mtctx); - mtctx->allJobsCompleted = 1; - } - mtctx->params = params; mtctx->frameContentSize = pledgedSrcSize; ZSTD_freeCDict(mtctx->cdictLocal); @@ -38659,11 +39878,19 @@ size_t ZSTDMT_initCStream_internal( * with the LDM window. */ size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0); - size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers; + U64 const slackSize = (U64)mtctx->targetSectionSize * nbSlackBuffers; /* Compute the total size, and always have enough slack */ - size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1); - size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers; - size_t const capacity = MAX(windowSize, sectionsSize) + slackSize; + U64 const nbWorkers = MAX(mtctx->params.nbWorkers, 1); + U64 const sectionsSize = (U64)mtctx->targetSectionSize * nbWorkers; + U64 const capacity64 = MAX((U64)windowSize, sectionsSize) + slackSize; + size_t capacity; + /* The totals are computed in 64 bits because on 32-bit builds they + * can exceed the range of size_t. They would wrap, and the round + * buffer would be too small (or not allocated at all), letting + * input be copied past its end. Reject such sizes instead. */ + capacity = (size_t)capacity64; + RETURN_ERROR_IF((U64)capacity != capacity64, + memory_allocation, "round buffer size overflow"); if (mtctx->roundBuff.capacity < capacity) { if (mtctx->roundBuff.buffer) ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem); @@ -38727,6 +39954,7 @@ static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job) assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */ assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */ assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */ + job->completed = 1; /* written here, never posted to a worker */ job->dstBuff = ZSTDMT_getBuffer(job->bufPool); if (job->dstBuff.start == NULL) { job->cSize = ERROR(memory_allocation); @@ -38760,6 +39988,7 @@ static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZS mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix; mtctx->jobs[jobID].consumed = 0; mtctx->jobs[jobID].cSize = 0; + mtctx->jobs[jobID].completed = 0; mtctx->jobs[jobID].params = mtctx->params; mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL; mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize; @@ -38911,9 +40140,8 @@ static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, u } /** - * Returns the range of data used by the earliest job that is not yet complete. - * If the data of the first job is broken up into two segments, we cover both - * sections. + * Returns the oldest input-ring range used by a job that is not yet complete. + * Protecting this range prevents ring reuse from reaching the job's source. */ static Range ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) { @@ -38935,11 +40163,10 @@ static Range ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex); if (consumed < mtctx->jobs[wJobID].src.size) { - Range range = mtctx->jobs[wJobID].prefix; - if (range.size == 0) { - /* Empty prefix */ - range = mtctx->jobs[wJobID].src; - } + Range const range = ZSTDMT_getJobInputRange( + mtctx->jobs[wJobID].prefix, + mtctx->jobs[wJobID].src, + mtctx->jobs[wJobID].firstJob); /* Job source in multiple segments not supported yet */ assert(range.start <= mtctx->jobs[wJobID].src.start); return range; @@ -39185,6 +40412,11 @@ size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx) return hintInSize; } +unsigned ZSTDMT_isFrameEnded(const ZSTDMT_CCtx* mtctx) +{ + return mtctx->frameEnded; +} + /** ZSTDMT_compressStream_generic() : * internal use only - exposed to be invoked from zstd_compress.c * assumption : output and input are valid (pos <= size) @@ -39205,8 +40437,12 @@ size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx, return ERROR(stage_wrong); } - /* fill input buffer */ + /* fill input buffer. + * Once the last job of the frame is created, remaining input belongs to the next frame : + * it is left untouched, like the single-thread path does. No job can follow the last one : + * it could wait forever at the serial gate, behind an empty last job written inline. */ if ( (!mtctx->jobReady) + && (!mtctx->frameEnded) && (input->size > input->pos) ) { /* support NULL input */ if (mtctx->inBuff.buffer.start == NULL) { assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */ @@ -39255,7 +40491,7 @@ size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx, /* check for potential compressed data ready to be flushed */ { size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */ - if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */ + if ((input->pos < input->size) && (!mtctx->frameEnded)) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */ DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush); return remainingToFlush; } @@ -39281,7 +40517,9 @@ size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx, /* ************************************************************** * Dependencies ****************************************************************/ +#include /* size_t */ /**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/bmi2.h ****/ /**** skipping file: ../common/compiler.h ****/ /**** skipping file: ../common/bitstream.h ****/ /**** skipping file: ../common/fse.h ****/ @@ -39382,9 +40620,10 @@ typedef size_t (*HUF_DecompressUsingDTableFn)(void *dst, size_t dstSize, static size_t fn(void* dst, size_t dstSize, void const* cSrc, \ size_t cSrcSize, HUF_DTable const* DTable, int flags) \ { \ - if (flags & HUF_flags_bmi2) { \ + if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) { \ return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable); \ } \ + (void)flags; \ return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable); \ } @@ -39461,7 +40700,7 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds const BYTE* const istart = (const BYTE*)src; - BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)dstSize); /* The fast decoding loop assumes 64-bit little-endian. * This condition is false on x32. @@ -39549,12 +40788,13 @@ static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArg /* Validate that we haven't overwritten. */ if (args->op[stream] > segmentEnd) return ERROR(corruption_detected); - /* Validate that we haven't read beyond iend[]. - * Note that ip[] may be < iend[] because the MSB is - * the next bit to read, and we may have consumed 100% - * of the stream, so down to iend[i] - 8 is valid. - */ - if (args->ip[stream] < args->iend[stream] - 8) + /* The MSB is the next bit to read, so ip[] may be up to 8 bytes before + * iend[] when the stream is fully consumed. Compare distances rather than + * forming iend[0] - 8, which can be before the compressed input. + * No loaded word may precede ilowest. */ + if (args->ip[stream] < args->ilowest + || (args->ip[stream] < args->iend[stream] + && (size_t)(args->iend[stream] - args->ip[stream]) > 8)) return ERROR(corruption_detected); /* Construct the BIT_DStream_t. */ @@ -39844,7 +41084,7 @@ HUF_decompress1X1_usingDTable_internal_body( const HUF_DTable* DTable) { BYTE* op = (BYTE*)dst; - BYTE* const oend = ZSTD_maybeNullPtrAdd(op, dstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(op, (ptrdiff_t)dstSize); const void* dtPtr = DTable + 1; const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr; BIT_DStream_t bitD; @@ -39969,6 +41209,8 @@ size_t HUF_decompress4X1_usingDTable_internal_bmi2(void* dst, size_t dstSize, vo size_t cSrcSize, HUF_DTable const* DTable) { return HUF_decompress4X1_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); } +#else +#define HUF_decompress4X1_usingDTable_internal_bmi2 HUF_decompress4X1_usingDTable_internal_default #endif static @@ -40050,19 +41292,19 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* } #endif -#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol) \ - do { \ - int const index = (int)(bits[(_stream)] >> 53); \ - int const entry = (int)dtable[index]; \ - bits[(_stream)] <<= (entry & 0x3F); \ - op[(_stream)][(_symbol)] = (BYTE)((entry >> 8) & 0xFF); \ +#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol) \ + do { \ + U64 const index = bits[(_stream)] >> 53; \ + U16 const entry = dtable[index]; \ + bits[(_stream)] <<= entry & 0x3F; \ + op[(_stream)][(_symbol)] = (BYTE)(entry >> 8); \ } while (0) -#define HUF_4X1_RELOAD_STREAM(_stream) \ +#define HUF_5X1_RELOAD_STREAM(_stream) \ do { \ - int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ - int const nbBits = ctz & 7; \ - int const nbBytes = ctz >> 3; \ + U64 const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ + U64 const nbBits = ctz & 7; \ + U64 const nbBytes = ctz >> 3; \ op[(_stream)] += 5; \ ip[(_stream)] -= nbBytes; \ bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \ @@ -40081,11 +41323,11 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 4); /* Reload each of the 4 the bitstreams */ - HUF_4X_FOR_EACH_STREAM(HUF_4X1_RELOAD_STREAM); + HUF_4X_FOR_EACH_STREAM(HUF_5X1_RELOAD_STREAM); } while (op[3] < olimit); #undef HUF_4X1_DECODE_SYMBOL -#undef HUF_4X1_RELOAD_STREAM +#undef HUF_5X1_RELOAD_STREAM } _out: @@ -40111,7 +41353,7 @@ HUF_decompress4X1_usingDTable_internal_fast( { void const* dt = DTable + 1; BYTE const* const ilowest = (BYTE const*)cSrc; - BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)dstSize); HUF_DecompressFastArgs args; { size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable); FORWARD_IF_ERROR(ret, "Failed to init fast loop args"); @@ -40166,18 +41408,16 @@ static size_t HUF_decompress4X1_usingDTable_internal(void* dst, size_t dstSize, HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X1_usingDTable_internal_default; HUF_DecompressFastLoopFn loopFn = HUF_decompress4X1_usingDTable_internal_fast_c_loop; -#if DYNAMIC_BMI2 - if (flags & HUF_flags_bmi2) { + if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) { fallbackFn = HUF_decompress4X1_usingDTable_internal_bmi2; # if ZSTD_ENABLE_ASM_X86_64_BMI2 if (!(flags & HUF_flags_disableAsm)) { loopFn = HUF_decompress4X1_usingDTable_internal_fast_asm_loop; } # endif - } else { + } else if (DYNAMIC_BMI2) { return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); } -#endif #if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__) if (!(flags & HUF_flags_disableAsm)) { @@ -40580,7 +41820,9 @@ HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, if ((size_t)(pEnd - p) >= sizeof(bitDPtr->bitContainer)) { if (dtLog <= 11 && MEM_64bits()) { /* up to 10 symbols at a time */ - while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-9)) { + /* For an 8-byte output, pEnd - 9 would precede the buffer. */ + BYTE* const pLimit = (size_t)(pEnd - p) >= 10 ? pEnd - 9 : p; + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pLimit)) { HUF_DECODE_SYMBOLX2_0(p, bitDPtr); HUF_DECODE_SYMBOLX2_0(p, bitDPtr); HUF_DECODE_SYMBOLX2_0(p, bitDPtr); @@ -40628,7 +41870,7 @@ HUF_decompress1X2_usingDTable_internal_body( /* decode */ { BYTE* const ostart = (BYTE*) dst; - BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, dstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)dstSize); const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */ const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr; DTableDesc const dtd = HUF_getDTableDesc(DTable); @@ -40772,6 +42014,8 @@ size_t HUF_decompress4X2_usingDTable_internal_bmi2(void* dst, size_t dstSize, vo size_t cSrcSize, HUF_DTable const* DTable) { return HUF_decompress4X2_usingDTable_internal_body(dst, dstSize, cSrc, cSrcSize, DTable); } +#else +#define HUF_decompress4X2_usingDTable_internal_bmi2 HUF_decompress4X2_usingDTable_internal_default #endif static @@ -40868,57 +42112,65 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs* } #endif -#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3) \ - do { \ - if ((_decode3) || (_stream) != 3) { \ - int const index = (int)(bits[(_stream)] >> 53); \ - HUF_DEltX2 const entry = dtable[index]; \ - MEM_write16(op[(_stream)], entry.sequence); \ - bits[(_stream)] <<= (entry.nbBits) & 0x3F; \ - op[(_stream)] += (entry.length); \ - } \ +#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3) \ + do { \ + if ((_decode3) || (_stream) != 3) { \ + U64 const index = bits[(_stream)] >> 53; \ + size_t const entry = MEM_readLE32(&dtable[index]); \ + MEM_write16(op[(_stream)], (U16)entry); \ + bits[(_stream)] <<= (entry >> 16) & 0x3F; \ + op[(_stream)] += entry >> 24; \ + } \ } while (0) -#define HUF_4X2_RELOAD_STREAM(_stream) \ +#define HUF_5X2_RELOAD_STREAM(_stream, _decode3) \ do { \ - HUF_4X2_DECODE_SYMBOL(3, 1); \ + if (_decode3) HUF_4X2_DECODE_SYMBOL(3, 1); \ { \ - int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ - int const nbBits = ctz & 7; \ - int const nbBytes = ctz >> 3; \ + U64 const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \ + U64 const nbBits = ctz & 7; \ + U64 const nbBytes = ctz >> 3; \ ip[(_stream)] -= nbBytes; \ bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1; \ bits[(_stream)] <<= nbBits; \ } \ } while (0) +#if defined(__aarch64__) +# define HUF_4X2_4WAY 1 +#else +# define HUF_4X2_4WAY 0 +#endif +#define HUF_4X2_3WAY !HUF_4X2_4WAY + /* Manually unroll the loop because compilers don't consistently * unroll the inner loops, which destroys performance. */ do { - /* Decode 5 symbols from each of the first 3 streams. - * The final stream will be decoded during the reload phase - * to reduce register pressure. + /* Decode 5 symbols from each of the first 3 or 4 streams. + * In the 3-way case the final stream will be decoded during + * the reload phase to reduce register pressure. */ - HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); - HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); - HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); - HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); - HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, 0); - - /* Decode one symbol from the final stream */ - HUF_4X2_DECODE_SYMBOL(3, 1); - - /* Decode 4 symbols from the final stream & reload bitstreams. - * The final stream is reloaded last, meaning that all 5 symbols - * are decoded from the final stream before it is reloaded. + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, HUF_4X2_4WAY); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, HUF_4X2_4WAY); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, HUF_4X2_4WAY); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, HUF_4X2_4WAY); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X2_DECODE_SYMBOL, HUF_4X2_4WAY); + + /* In the 3-way case decode one symbol from the final stream. */ + HUF_4X2_DECODE_SYMBOL(3, HUF_4X2_3WAY); + + /* In the 3-way case decode 4 symbols from the final stream & + * reload bitstreams. The final stream is reloaded last, meaning + * that all 5 symbols are decoded from the final stream before + * it is reloaded. */ - HUF_4X_FOR_EACH_STREAM(HUF_4X2_RELOAD_STREAM); + HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_5X2_RELOAD_STREAM, HUF_4X2_3WAY); } while (op[3] < olimit); } #undef HUF_4X2_DECODE_SYMBOL -#undef HUF_4X2_RELOAD_STREAM +#undef HUF_5X2_RELOAD_STREAM _out: @@ -40937,7 +42189,7 @@ HUF_decompress4X2_usingDTable_internal_fast( HUF_DecompressFastLoopFn loopFn) { void const* dt = DTable + 1; const BYTE* const ilowest = (const BYTE*)cSrc; - BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)dstSize); HUF_DecompressFastArgs args; { size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable); @@ -40988,18 +42240,16 @@ static size_t HUF_decompress4X2_usingDTable_internal(void* dst, size_t dstSize, HUF_DecompressUsingDTableFn fallbackFn = HUF_decompress4X2_usingDTable_internal_default; HUF_DecompressFastLoopFn loopFn = HUF_decompress4X2_usingDTable_internal_fast_c_loop; -#if DYNAMIC_BMI2 - if (flags & HUF_flags_bmi2) { + if (ZSTD_USE_BMI2(flags & HUF_flags_bmi2)) { fallbackFn = HUF_decompress4X2_usingDTable_internal_bmi2; # if ZSTD_ENABLE_ASM_X86_64_BMI2 if (!(flags & HUF_flags_disableAsm)) { loopFn = HUF_decompress4X2_usingDTable_internal_fast_asm_loop; } # endif - } else { + } else if (DYNAMIC_BMI2) { return fallbackFn(dst, dstSize, cSrc, cSrcSize, DTable); } -#endif #if ZSTD_ENABLE_ASM_X86_64_BMI2 && defined(__BMI2__) if (!(flags & HUF_flags_disableAsm)) { @@ -41391,12 +42641,15 @@ struct ZSTD_DCtx_s size_t staticSize; int isFrameDecompression; #if DYNAMIC_BMI2 - int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ + int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise when CPU state + * is cached per context. Never read this directly: use ZSTD_DCtx_get_bmi2(), + * which also handles builds + * where cached CPU state is not used. */ #endif /* dictionary */ ZSTD_DDict* ddictLocal; - const ZSTD_DDict* ddict; /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */ + const ZSTD_DDict* ddict; /* single-DDict state; NULL while ddictSet exists */ U32 dictID; int ddictIsCold; /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */ ZSTD_dictUses_e dictUses; @@ -41443,9 +42696,21 @@ struct ZSTD_DCtx_s /* Tracing */ #if ZSTD_TRACE ZSTD_TraceCtx traceCtx; + size_t traceDictSize; /* size of the dictionary installed for this frame */ #endif }; /* typedef'd to ZSTD_DCtx within "zstd.h" */ +/** + * @returns the cached per-context BMI2 dispatch hint, or 0 when the build does + * not use cached CPU state. + * + * Beware: this is *not* a "does the CPU support BMI2" test. When BMI2 is enabled + * at compile time, DYNAMIC_BMI2 is 0: the whole library is already compiled with + * BMI2, no separate variant exists, and this returns 0 even though the CPU does + * support BMI2. Only use the result as a dispatch hint passed to a lower-level + * BMI2/default selector. Integrations may ignore the cached hint and consult + * their own CPU-feature policy at that selector. + */ MEM_STATIC int ZSTD_DCtx_get_bmi2(const struct ZSTD_DCtx_s *dctx) { #if DYNAMIC_BMI2 return dctx->bmi2; @@ -41469,6 +42734,8 @@ size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy, * check if next `dst` follows previous position, where decompression ended. * If yes, do nothing (continue on current segment). * If not, classify previous segment as "external dictionary", and start a new segment. + * A zero dstSize leaves history unchanged. Callers must only advance + * previousDstEnd when bytes are actually produced or inserted. * This function cannot fail. */ void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize); @@ -41512,11 +42779,22 @@ void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize); * ZSTD_getDictID_fromDict() */ +/* The complete dictionary blob, including its header. Legacy decoders need + * the original bytes; ZSTD_copyDDictParameters() excludes the header from + * modern match history. */ const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict); size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict); void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); +/* Same as ZSTD_createDDict_advanced(), but returns the error code on failure, + * in which case *ddictPtr is set to NULL. */ +size_t ZSTD_createDDict_advanced_internal(ZSTD_DDict** ddictPtr, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem); + #endif /* ZSTD_DDICT_H */ @@ -42936,8 +44214,9 @@ MEM_STATIC size_t ZSTD_decompressLegacyStream(void* legacyContext, U32 version, *********************************************************/ struct ZSTD_DDict_s { void* dictBuffer; - const void* dictContent; + const void* dictContent; /* complete dictionary, including any header */ size_t dictSize; + size_t dictHeaderSize; /* excluded from matchable history */ ZSTD_entropyDTables_t entropy; U32 dictID; U32 entropyPresent; @@ -42958,13 +44237,20 @@ size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict) void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) { + const void* content; DEBUGLOG(4, "ZSTD_copyDDictParameters"); assert(dctx != NULL); assert(ddict != NULL); + content = ddict->dictHeaderSize != 0 + ? (const BYTE*)ddict->dictContent + ddict->dictHeaderSize + : ddict->dictContent; dctx->dictID = ddict->dictID; - dctx->prefixStart = ddict->dictContent; - dctx->virtualStart = ddict->dictContent; - dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize; + dctx->prefixStart = content; + dctx->virtualStart = content; + /* An empty DDict may have NULL content. */ + dctx->dictEnd = ddict->dictSize != 0 + ? (const BYTE*)ddict->dictContent + ddict->dictSize + : ddict->dictContent; dctx->previousDstEnd = dctx->dictEnd; #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION dctx->dictContentBeginForFuzzing = dctx->prefixStart; @@ -42992,6 +44278,7 @@ ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict, ZSTD_dictContentType_e dictContentType) { ddict->dictID = 0; + ddict->dictHeaderSize = 0; ddict->entropyPresent = 0; if (dictContentType == ZSTD_dct_rawContent) return 0; @@ -43010,9 +44297,12 @@ ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict, ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE); /* load entropy tables */ - RETURN_ERROR_IF(ZSTD_isError(ZSTD_loadDEntropy( - &ddict->entropy, ddict->dictContent, ddict->dictSize)), - dictionary_corrupted, ""); + { size_t const headerSize = ZSTD_loadDEntropy( + &ddict->entropy, ddict->dictContent, ddict->dictSize); + RETURN_ERROR_IF(ZSTD_isError(headerSize), dictionary_corrupted, ""); + assert(headerSize <= ddict->dictSize); + ddict->dictHeaderSize = headerSize; + } ddict->entropyPresent = 1; return 0; } @@ -43023,6 +44313,8 @@ static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType) { + /* An empty dictionary has no referenced storage, even in by-copy mode. */ + if (dictSize == 0) dict = NULL; if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) { ddict->dictBuffer = NULL; ddict->dictContent = dict; @@ -43043,25 +44335,41 @@ static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict, return 0; } +size_t ZSTD_createDDict_advanced_internal(ZSTD_DDict** ddictPtr, + const void* dict, size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_dictContentType_e dictContentType, + ZSTD_customMem customMem) +{ + ZSTD_DDict* ddict; + *ddictPtr = NULL; + RETURN_ERROR_IF((!customMem.customAlloc) ^ (!customMem.customFree), + parameter_combination_unsupported, "Invalid custom allocator"); + + ddict = (ZSTD_DDict*) ZSTD_customMalloc(sizeof(ZSTD_DDict), customMem); + RETURN_ERROR_IF(ddict == NULL, memory_allocation, ""); + ddict->cMem = customMem; + { size_t const initResult = ZSTD_initDDict_internal(ddict, + dict, dictSize, + dictLoadMethod, dictContentType); + if (ZSTD_isError(initResult)) { + ZSTD_freeDDict(ddict); + return initResult; + } } + *ddictPtr = ddict; + return 0; +} + ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType, ZSTD_customMem customMem) { - if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; - - { ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_customMalloc(sizeof(ZSTD_DDict), customMem); - if (ddict == NULL) return NULL; - ddict->cMem = customMem; - { size_t const initResult = ZSTD_initDDict_internal(ddict, - dict, dictSize, - dictLoadMethod, dictContentType); - if (ZSTD_isError(initResult)) { - ZSTD_freeDDict(ddict); - return NULL; - } } - return ddict; - } + ZSTD_DDict* ddict; + size_t const err = ZSTD_createDDict_advanced_internal(&ddict, + dict, dictSize, dictLoadMethod, dictContentType, customMem); + if (ZSTD_isError(err)) return NULL; + return ddict; } /*! ZSTD_createDDict() : @@ -43091,14 +44399,13 @@ const ZSTD_DDict* ZSTD_initStaticDDict( ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType) { - size_t const neededSpace = sizeof(ZSTD_DDict) - + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); + size_t const neededSpace = ZSTD_estimateDDictSize(dictSize, dictLoadMethod); ZSTD_DDict* const ddict = (ZSTD_DDict*)sBuffer; assert(sBuffer != NULL); - assert(dict != NULL); + assert(dict != NULL || dictSize == 0); if ((size_t)sBuffer & 7) return NULL; /* 8-aligned */ - if (sBufferSize < neededSpace) return NULL; - if (dictLoadMethod == ZSTD_dlm_byCopy) { + if (ZSTD_isError(neededSpace) || sBufferSize < neededSpace) return NULL; + if (dictLoadMethod == ZSTD_dlm_byCopy && dictSize != 0) { ZSTD_memcpy(ddict+1, dict, dictSize); /* local copy */ dict = ddict+1; } @@ -43125,7 +44432,10 @@ size_t ZSTD_freeDDict(ZSTD_DDict* ddict) * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */ size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod) { - return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize); + if (dictLoadMethod == ZSTD_dlm_byRef) return sizeof(ZSTD_DDict); + RETURN_ERROR_IF(dictSize > (size_t)-1 - sizeof(ZSTD_DDict), + memory_allocation, "DDict size overflow"); + return sizeof(ZSTD_DDict) + dictSize; } size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict) @@ -43204,6 +44514,7 @@ unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict) *********************************************************/ /**** skipping file: ../common/zstd_deps.h ****/ /**** skipping file: ../common/allocations.h ****/ +/**** skipping file: ../common/bmi2.h ****/ /**** skipping file: ../common/error_private.h ****/ /**** skipping file: ../common/zstd_internal.h ****/ /**** skipping file: ../common/mem.h ****/ @@ -43303,7 +44614,7 @@ size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, #define DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT 4 #define DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT 3 /* These two constants represent SIZE_MULT/COUNT_MULT load factor without using a float. * Currently, that means a 0.75 load factor. - * So, if count * COUNT_MULT / size * SIZE_MULT != 0, then we've exceeded + * So, if count * COUNT_MULT >= size * SIZE_MULT, then we've reached * the load factor of the ddict hash set. */ @@ -43336,8 +44647,7 @@ static size_t ZSTD_DDictHashSet_emplaceDDict(ZSTD_DDictHashSet* hashSet, const Z hashSet->ddictPtrTable[idx] = ddict; return 0; } - idx &= idxRangeMask; - idx++; + idx = (idx + 1) & idxRangeMask; } DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); hashSet->ddictPtrTable[idx] = ddict; @@ -43374,19 +44684,15 @@ static size_t ZSTD_DDictHashSet_expand(ZSTD_DDictHashSet* hashSet, ZSTD_customMe /* Fetches a DDict with the given dictID * Returns the ZSTD_DDict* with the requested dictID. If it doesn't exist, then returns NULL. */ -static const ZSTD_DDict* ZSTD_DDictHashSet_getDDict(ZSTD_DDictHashSet* hashSet, U32 dictID) { +static const ZSTD_DDict* ZSTD_DDictHashSet_getDDict(const ZSTD_DDictHashSet* hashSet, U32 dictID) { size_t idx = ZSTD_DDictHashSet_getIndex(hashSet, dictID); const size_t idxRangeMask = hashSet->ddictPtrTableSize - 1; DEBUGLOG(4, "Hashed index: for dictID: %u is %zu", dictID, idx); - for (;;) { - size_t currDictID = ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]); - if (currDictID == dictID || currDictID == 0) { - /* currDictID == 0 implies a NULL ddict entry */ + while (hashSet->ddictPtrTable[idx] != NULL) { + if (ZSTD_getDictID_fromDDict(hashSet->ddictPtrTable[idx]) == dictID) break; - } else { - idx &= idxRangeMask; /* Goes to start of table when we reach the end */ - idx++; - } + /* ID 0 is valid for raw-content dictionaries, not an empty slot. */ + idx = (idx + 1) & idxRangeMask; } DEBUGLOG(4, "Final idx after probing for dictID %u is: %zu", dictID, idx); return hashSet->ddictPtrTable[idx]; @@ -43429,7 +44735,7 @@ static void ZSTD_freeDDictHashSet(ZSTD_DDictHashSet* hashSet, ZSTD_customMem cus */ static size_t ZSTD_DDictHashSet_addDDict(ZSTD_DDictHashSet* hashSet, const ZSTD_DDict* ddict, ZSTD_customMem customMem) { DEBUGLOG(4, "Adding dict ID: %u to hashset with - Count: %zu Tablesize: %zu", ZSTD_getDictID_fromDDict(ddict), hashSet->ddictPtrCount, hashSet->ddictPtrTableSize); - if (hashSet->ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT / hashSet->ddictPtrTableSize * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT != 0) { + if (hashSet->ddictPtrCount * DDICT_HASHSET_MAX_LOAD_FACTOR_COUNT_MULT >= hashSet->ddictPtrTableSize * DDICT_HASHSET_MAX_LOAD_FACTOR_SIZE_MULT) { FORWARD_IF_ERROR(ZSTD_DDictHashSet_expand(hashSet, customMem), ""); } FORWARD_IF_ERROR(ZSTD_DDictHashSet_emplaceDDict(hashSet, ddict), ""); @@ -43470,8 +44776,9 @@ static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx) dctx->maxBlockSizeParam = 0; } -static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) +static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx, ZSTD_customMem customMem) { + dctx->customMem = customMem; dctx->staticSize = 0; dctx->ddict = NULL; dctx->ddictLocal = NULL; @@ -43482,6 +44789,8 @@ static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) dctx->inBuffSize = 0; dctx->outBuffSize = 0; dctx->streamStage = zdss_init; + dctx->stage = ZSTDds_getFrameHeaderSize; + dctx->expected = 0; /* ZSTD_decompressContinue() requires ZSTD_decompressBegin() first */ #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) dctx->legacyContext = NULL; dctx->previousLegacyVersion = 0; @@ -43490,7 +44799,7 @@ static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) dctx->oversizedDuration = 0; dctx->isFrameDecompression = 1; #if DYNAMIC_BMI2 - dctx->bmi2 = ZSTD_cpuSupportsBmi2(); + ZSTD_SET_BMI2(dctx->bmi2, ZSTD_cpuSupportsBmi2()); #endif dctx->ddictSet = NULL; ZSTD_DCtx_resetParameters(dctx); @@ -43506,7 +44815,7 @@ ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize) if ((size_t)workspace & 7) return NULL; /* 8-aligned */ if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */ - ZSTD_initDCtx_internal(dctx); + ZSTD_initDCtx_internal(dctx, ZSTD_defaultCMem); dctx->staticSize = workspaceSize; dctx->inBuff = (char*)(dctx+1); return dctx; @@ -43517,8 +44826,7 @@ static ZSTD_DCtx* ZSTD_createDCtx_internal(ZSTD_customMem customMem) { { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_customMalloc(sizeof(*dctx), customMem); if (!dctx) return NULL; - dctx->customMem = customMem; - ZSTD_initDCtx_internal(dctx); + ZSTD_initDCtx_internal(dctx, customMem); return dctx; } } @@ -43542,6 +44850,32 @@ static void ZSTD_clearDict(ZSTD_DCtx* dctx) dctx->dictUses = ZSTD_dont_use; } +/* Abandon any active or failed streaming session. + * This is the implementation of ZSTD_reset_session_only. + * Single-shot entry points call it first, so that a DCtx left mid-stream + * (or in an undefined state after a streaming error) can be reused, and + * so that it is returned to a clean streaming state afterwards. */ +static void ZSTD_DCtx_resetSession(ZSTD_DCtx* dctx) +{ + /* A prefix is only used once : if a frame was started, it is abandoned now, + * so the prefix must not leak into the next frame */ + if (dctx->streamStage != zdss_init && dctx->dictUses == ZSTD_use_once) + ZSTD_clearDict(dctx); + dctx->streamStage = zdss_init; + dctx->noForwardProgress = 0; + dctx->isFrameDecompression = 1; +} + +/* Discard borrowed dictionary references without freeing the DDicts. */ +static void ZSTD_clearDDictSet(ZSTD_DCtx* dctx) +{ + if (dctx->ddictSet != NULL) { + assert(!dctx->staticSize); + ZSTD_freeDDictHashSet(dctx->ddictSet, dctx->customMem); + dctx->ddictSet = NULL; + } +} + size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) { if (dctx==NULL) return 0; /* support free on NULL */ @@ -43554,43 +44888,34 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx) if (dctx->legacyContext) ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion); #endif - if (dctx->ddictSet) { - ZSTD_freeDDictHashSet(dctx->ddictSet, cMem); - dctx->ddictSet = NULL; - } + ZSTD_clearDDictSet(dctx); ZSTD_customFree(dctx, cMem); return 0; } } -/* no longer useful */ -void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx) -{ - size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx); - ZSTD_memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */ -} - -/* Given a dctx with a digested frame params, re-selects the correct ZSTD_DDict based on - * the requested dict ID from the frame. If there exists a reference to the correct ZSTD_DDict, then - * accordingly sets the ddict to be used to decompress the frame. +/* Look up the DDict for a complete, valid Zstandard frame header. + * The result is for this frame only; it does not change the single-DDict state. * - * If no DDict is found, then no action is taken, and the ZSTD_DCtx::ddict remains as-is. + * Returns dictionary_wrong if the set does not contain a requested nonzero ID. + * For ID 0, returns the registered DDict, or NULL to use no dictionary. * + * Must be called before installing the dictionary's decoding state. * ZSTD_d_refMultipleDDicts must be enabled for this function to be called. */ -static void ZSTD_DCtx_selectFrameDDict(ZSTD_DCtx* dctx) { +static size_t ZSTD_DCtx_getFrameDDict(const ZSTD_DCtx* dctx, U32 dictID, + const ZSTD_DDict** ddict) { + const ZSTD_DDict* frameDDict; assert(dctx->refMultipleDDicts && dctx->ddictSet); - DEBUGLOG(4, "Adjusting DDict based on requested dict ID from frame"); - if (dctx->ddict) { - const ZSTD_DDict* frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dctx->fParams.dictID); - if (frameDDict) { - DEBUGLOG(4, "DDict found!"); - ZSTD_clearDict(dctx); - dctx->dictID = dctx->fParams.dictID; - dctx->ddict = frameDDict; - dctx->dictUses = ZSTD_use_indefinitely; - } - } + assert(dctx->ddictLocal == NULL && dctx->ddict == NULL); + assert(dctx->dictUses == ZSTD_dont_use); + DEBUGLOG(4, "Looking up requested dict ID from frame"); + frameDDict = ZSTD_DDictHashSet_getDDict(dctx->ddictSet, dictID); + RETURN_ERROR_IF(frameDDict == NULL && dictID != 0, dictionary_wrong, "No matching DDict in the set"); + DEBUGLOG(4, "DDict lookup complete"); + assert(frameDDict == NULL || ZSTD_getDictID_fromDDict(frameDDict) == dictID); + *ddict = frameDDict; + return 0; } @@ -43918,7 +45243,7 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize) /** ZSTD_decodeFrameHeader() : * `headerSize` must be the size provided by ZSTD_frameHeaderSize(). - * If multiple DDict references are enabled, also will choose the correct DDict to use. + * The dictionary's decoding state must already be installed. * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */ static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize) { @@ -43926,11 +45251,6 @@ static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t he if (ZSTD_isError(result)) return result; /* invalid header */ RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small"); - /* Reference DDict requested by frame if dctx references multiple ddicts */ - if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts && dctx->ddictSet) { - ZSTD_DCtx_selectFrameDDict(dctx); - } - #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* Skip the dictID check in fuzzing mode, because it makes the search * harder. @@ -43940,7 +45260,6 @@ static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t he #endif dctx->validateChecksum = (dctx->fParams.checksumFlag && !dctx->forceIgnoreChecksum) ? 1 : 0; if (dctx->validateChecksum) XXH64_reset(&dctx->xxhState, 0); - dctx->processedCSize += headerSize; return 0; } @@ -44048,6 +45367,11 @@ unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize) unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) return ZSTD_CONTENTSIZE_ERROR; + /* Invariant: bound < ZSTD_CONTENTSIZE_ERROR, so this subtraction + * cannot underflow. Keep the sum below both reserved values, which + * also prevents unsigned overflow. */ + if (decompressedBound >= ZSTD_CONTENTSIZE_ERROR - bound) + return ZSTD_CONTENTSIZE_ERROR; assert(srcSize >= compressedSize); src = (const BYTE*)src + compressedSize; srcSize -= compressedSize; @@ -44109,7 +45433,9 @@ size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSiz { DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize); ZSTD_checkContinuity(dctx, blockStart, blockSize); - dctx->previousDstEnd = (const char*)blockStart + blockSize; + /* An empty insertion must not replace the current history endpoint. */ + if (blockSize != 0) + dctx->previousDstEnd = (const char*)blockStart + blockSize; return blockSize; } @@ -44148,9 +45474,9 @@ static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 ZSTD_memset(&trace, 0, sizeof(trace)); trace.version = ZSTD_VERSION_NUMBER; trace.streaming = streaming; - if (dctx->ddict) { - trace.dictionaryID = ZSTD_getDictID_fromDDict(dctx->ddict); - trace.dictionarySize = ZSTD_DDict_dictSize(dctx->ddict); + if (dctx->traceDictSize != 0) { + trace.dictionaryID = dctx->dictID; + trace.dictionarySize = dctx->traceDictSize; trace.dictionaryIsCold = dctx->ddictIsCold; } trace.uncompressedSize = (size_t)uncompressedSize; @@ -44250,6 +45576,7 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, RETURN_ERROR(corruption_detected, "invalid block type"); } FORWARD_IF_ERROR(decodedSize, "Block decompression failure"); + RETURN_ERROR_IF(decodedSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum"); DEBUGLOG(5, "Decompressed block of dSize = %u", (unsigned)decodedSize); if (dctx->validateChecksum) { XXH64_update(&dctx->xxhState, op, decodedSize); @@ -44292,7 +45619,8 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, const void* dict, size_t dictSize, - const ZSTD_DDict* ddict) + const ZSTD_DDict* ddict, + int useDDictSet) { void* const dststart = dst; int moreThan1Frame = 0; @@ -44300,22 +45628,27 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, DEBUGLOG(5, "ZSTD_decompressMultiFrame"); assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */ - if (ddict) { - dict = ZSTD_DDict_dictContent(ddict); - dictSize = ZSTD_DDict_dictSize(ddict); - } + assert(!useDDictSet || (dctx->refMultipleDDicts && dctx->ddictSet + && dctx->ddictLocal == NULL && dctx->ddict == NULL + && dict == NULL && ddict == NULL)); while (srcSize >= ZSTD_startingInputLength(dctx->format)) { + const ZSTD_DDict* frameDDict = ddict; #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) if (dctx->format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) { size_t decodedSize; - size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); + const void* const legacyDict = ddict ? ZSTD_DDict_dictContent(ddict) : dict; + size_t const legacyDictSize = ddict ? ZSTD_DDict_dictSize(ddict) : dictSize; + size_t frameSize; + RETURN_ERROR_IF(useDDictSet, parameter_unsupported, + "DDict-set selection is not supported for legacy frames"); + frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); if (ZSTD_isError(frameSize)) return frameSize; RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "legacy support is not compatible with static dctx"); - decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize); + decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, legacyDict, legacyDictSize); if (ZSTD_isError(decodedSize)) return decodedSize; { @@ -44352,9 +45685,17 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, continue; /* check next frame */ } } - if (ddict) { - /* we were called from ZSTD_decompress_usingDDict */ - FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), ""); + if (useDDictSet) { + ZSTD_FrameHeader zfh; + size_t const hSize = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, dctx->format); + /* Invalid/incomplete headers must not change dictionary selection. + * ZSTD_decompressFrame() will report the header error. */ + if (hSize == 0 && zfh.frameType == ZSTD_frame) + FORWARD_IF_ERROR(ZSTD_DCtx_getFrameDDict(dctx, zfh.dictID, &frameDDict), ""); + } + if (frameDDict) { + /* Use either the explicit DDict or the one selected from the set. */ + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, frameDDict), ""); } else { /* this will initialize correctly with no dict if dict == NULL, so * use this in all cases but ddict */ @@ -44394,12 +45735,14 @@ size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, const void* src, size_t srcSize, const void* dict, size_t dictSize) { - return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL); + ZSTD_DCtx_resetSession(dctx); + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL, 0); } static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx) { + assert(dctx->ddictSet == NULL); switch (dctx->dictUses) { default: assert(0 /* Impossible */); @@ -44417,7 +45760,16 @@ static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx) size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) { - return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx)); + /* Reset first: this may discard a prefix abandoned by an unfinished + * stream, which must happen before the dictionary is resolved. */ + ZSTD_DCtx_resetSession(dctx); + if (dctx->refMultipleDDicts && dctx->ddictSet) + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, + NULL, 0, NULL, 1); + /* Preserve the single-dictionary behavior: resolve once for the entire + * call, including concatenated frames and single-use prefixes. */ + return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, + NULL, 0, ZSTD_getDDict(dctx), 0); } @@ -44432,7 +45784,7 @@ size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t sr return regenSize; #else /* stack mode */ ZSTD_DCtx dctx; - ZSTD_initDCtx_internal(&dctx); + ZSTD_initDCtx_internal(&dctx, ZSTD_defaultCMem); return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize); #endif } @@ -44490,12 +45842,17 @@ ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) { static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; } /** ZSTD_decompressContinue() : + * The frame must first be initialized with ZSTD_decompressBegin() or one of its dictionary-taking variants. + * ZSTD_DCtx_reset() does not replace this initialization. * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress()) * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity) * or an error code, which can be tested using ZSTD_isError() */ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize); + /* The previous frame is finished, or the context was never initialized */ + RETURN_ERROR_IF(dctx->stage == ZSTDds_getFrameHeaderSize && dctx->expected == 0, + stage_wrong, "missing init (ZSTD_decompressBegin)"); /* Sanity check */ RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed"); ZSTD_checkContinuity(dctx, dst, dstCapacity); @@ -44541,12 +45898,22 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, c dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock; return 0; } + RETURN_ERROR_IF(bp.blockType != bt_raw, corruption_detected, + "Only raw blocks can have an empty payload"); /* empty block */ if (bp.lastBlock) { + /* An empty last block ends the frame here, so the content size + * check that normally runs in ZSTDds_decompressLastBlock must + * be performed at this point as well. */ + RETURN_ERROR_IF( + dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + && dctx->decodedSize != dctx->fParams.frameContentSize, + corruption_detected, ""); if (dctx->fParams.checksumFlag) { dctx->expected = 4; dctx->stage = ZSTDds_checkChecksum; } else { + ZSTD_DCtx_trace_end(dctx, dctx->decodedSize, dctx->processedCSize, /* streaming */ 1); dctx->expected = 0; /* end of frame */ dctx->stage = ZSTDds_getFrameHeaderSize; } @@ -44589,7 +45956,9 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, c DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize); dctx->decodedSize += rSize; if (dctx->validateChecksum) XXH64_update(&dctx->xxhState, dst, rSize); - dctx->previousDstEnd = (char*)dst + rSize; + /* No output means no new history; dst may be NULL. */ + if (rSize != 0) + dctx->previousDstEnd = (char*)dst + rSize; /* Stay on the same stage until we are finished streaming the block. */ if (dctx->expected > 0) { @@ -44783,6 +46152,7 @@ size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) assert(dctx != NULL); #if ZSTD_TRACE dctx->traceCtx = (ZSTD_trace_decompress_begin != NULL) ? ZSTD_trace_decompress_begin(dctx) : 0; + dctx->traceDictSize = 0; #endif dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */ dctx->stage = ZSTDds_getFrameHeaderSize; @@ -44813,6 +46183,9 @@ size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t RETURN_ERROR_IF( ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)), dictionary_corrupted, ""); +#if ZSTD_TRACE + dctx->traceDictSize = dict ? dictSize : 0; +#endif return 0; } @@ -44826,7 +46199,8 @@ size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) if (ddict) { const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict); size_t const dictSize = ZSTD_DDict_dictSize(ddict); - const void* const dictEnd = dictStart + dictSize; + /* An empty DDict may have NULL content. */ + const void* const dictEnd = dictSize != 0 ? dictStart + dictSize : dictStart; dctx->ddictIsCold = (dctx->dictEnd != dictEnd); DEBUGLOG(4, "DDict is %s", dctx->ddictIsCold ? "~cold~" : "hot!"); @@ -44834,6 +46208,9 @@ size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , ""); if (ddict) { /* NULL ddict is equivalent to no dictionary */ ZSTD_copyDDictParameters(dctx, ddict); +#if ZSTD_TRACE + dctx->traceDictSize = ZSTD_DDict_dictSize(ddict); +#endif } return 0; } @@ -44879,10 +46256,10 @@ size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, const void* src, size_t srcSize, const ZSTD_DDict* ddict) { - /* pass content and size in case legacy frames are encountered */ + ZSTD_DCtx_resetSession(dctx); return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, NULL, 0, - ddict); + ddict, 0); } @@ -44924,9 +46301,12 @@ size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, { RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); ZSTD_clearDict(dctx); + ZSTD_clearDDictSet(dctx); if (dict && dictSize != 0) { - dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem); - RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!"); + RETURN_ERROR_IF(dctx->staticSize, memory_allocation, + "static DCtx can't allocate an internal DDict"); + FORWARD_IF_ERROR(ZSTD_createDDict_advanced_internal(&dctx->ddictLocal, + dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem), ""); dctx->ddict = dctx->ddictLocal; dctx->dictUses = ZSTD_use_indefinitely; } @@ -45003,8 +46383,6 @@ size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); ZSTD_clearDict(dctx); if (ddict) { - dctx->ddict = ddict; - dctx->dictUses = ZSTD_use_indefinitely; if (dctx->refMultipleDDicts == ZSTD_rmd_refMultipleDDicts) { if (dctx->ddictSet == NULL) { dctx->ddictSet = ZSTD_createDDictHashSet(dctx->customMem); @@ -45014,7 +46392,13 @@ size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict) } assert(!dctx->staticSize); /* Impossible: ddictSet cannot have been allocated if static dctx */ FORWARD_IF_ERROR(ZSTD_DDictHashSet_addDDict(dctx->ddictSet, ddict, dctx->customMem), ""); + } else { + assert(dctx->ddictSet == NULL); + dctx->ddict = ddict; + dctx->dictUses = ZSTD_use_indefinitely; } + } else { + ZSTD_clearDDictSet(dctx); } return 0; } @@ -45150,6 +46534,12 @@ size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value if (dctx->staticSize != 0) { RETURN_ERROR(parameter_unsupported, "Static dctx does not support multiple DDicts!"); } + if (value == ZSTD_rmd_refSingleDDict && dctx->ddictSet != NULL) { + /* No dictionary from the set is inherited by single-DDict mode. */ + assert(dctx->ddict == NULL && dctx->ddictLocal == NULL); + assert(dctx->dictUses == ZSTD_dont_use); + ZSTD_clearDDictSet(dctx); + } dctx->refMultipleDDicts = (ZSTD_refMultipleDDicts_e)value; return 0; case ZSTD_d_disableHuffmanAssembly: @@ -45169,14 +46559,13 @@ size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) { if ( (reset == ZSTD_reset_session_only) || (reset == ZSTD_reset_session_and_parameters) ) { - dctx->streamStage = zdss_init; - dctx->noForwardProgress = 0; - dctx->isFrameDecompression = 1; + ZSTD_DCtx_resetSession(dctx); } if ( (reset == ZSTD_reset_parameters) || (reset == ZSTD_reset_session_and_parameters) ) { RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, ""); ZSTD_clearDict(dctx); + ZSTD_clearDDictSet(dctx); ZSTD_DCtx_resetParameters(dctx); } return 0; @@ -45295,7 +46684,7 @@ static size_t ZSTD_decompressContinueStream( size_t const dstSize = isSkipFrame ? 0 : (size_t)(oend - *op); size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize); FORWARD_IF_ERROR(decodedSize, ""); - *op += decodedSize; + *op = (char*)ZSTD_maybeNullPtrAdd(*op, (ptrdiff_t)decodedSize); /* Flushing is not needed. */ zds->streamStage = zdss_read; assert(*op <= oend); @@ -45306,6 +46695,8 @@ static size_t ZSTD_decompressContinueStream( size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input) { + const ZSTD_DDict* frameDDict = NULL; + int const useDDictSet = zds->refMultipleDDicts && zds->ddictSet != NULL; const char* const src = (const char*)input->src; const char* const istart = input->pos != 0 ? src + input->pos : src; const char* const iend = input->size != 0 ? src + input->size : src; @@ -45345,7 +46736,12 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB zds->expectedOutBuffer = *output; ZSTD_FALLTHROUGH; - case zdss_loadHeader : + case zdss_loadHeader : { + /* Legacy dispatch and the one-shot decoder both start at istart. + * Equality means no header bytes came from an earlier call. + * Check istart first to avoid subtracting NULL on empty input. */ + int const headerFromThisCall = istart != NULL + && (size_t)(ip - istart) == zds->lhSize; DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip)); #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) if (zds->legacyVersion) { @@ -45357,16 +46753,16 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB } } #endif { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format); - if (zds->refMultipleDDicts && zds->ddictSet) { - ZSTD_DCtx_selectFrameDDict(zds); - } if (ZSTD_isError(hSize)) { #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1) - U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart); + U32 const legacyVersion = headerFromThisCall + ? ZSTD_isLegacy(istart, (size_t)(iend-istart)) : 0; if (legacyVersion) { - ZSTD_DDict const* const ddict = ZSTD_getDDict(zds); + ZSTD_DDict const* const ddict = useDDictSet ? NULL : ZSTD_getDDict(zds); const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL; size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0; + RETURN_ERROR_IF(useDDictSet, parameter_unsupported, + "DDict-set selection is not supported for legacy frames"); DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion); RETURN_ERROR_IF(zds->staticSize, memory_allocation, "legacy support is incompatible with static dctx"); @@ -45403,17 +46799,27 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB break; } } - /* check for single-pass mode opportunity */ - if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN + /* Select only after a complete ordinary frame header is available, + * before any dictionary-backed decoding state is installed. */ + frameDDict = NULL; + if (useDDictSet && zds->fParams.frameType == ZSTD_frame) { + FORWARD_IF_ERROR(ZSTD_DCtx_getFrameDDict(zds, zds->fParams.dictID, &frameDDict), ""); + } + + /* A split header needs buffered decoding even if the rest of + * the frame is contiguous in this input. */ + if (headerFromThisCall + && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN && zds->fParams.frameType != ZSTD_skippableFrame && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) { size_t const cSize = ZSTD_findFrameCompressedSize_advanced(istart, (size_t)(iend-istart), zds->format); if (cSize <= (size_t)(iend-istart)) { /* shortcut : using single-pass mode */ - size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, (size_t)(oend-op), istart, cSize, ZSTD_getDDict(zds)); + /* Not ZSTD_decompress_usingDDict(), which resets the streaming session */ + size_t const decompressedSize = ZSTD_decompressMultiFrame(zds, op, (size_t)(oend-op), istart, cSize, + NULL, 0, useDDictSet ? frameDDict : ZSTD_getDDict(zds), 0); if (ZSTD_isError(decompressedSize)) return decompressedSize; - DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()"); - assert(istart != NULL); + DEBUGLOG(4, "shortcut to single-pass ZSTD_decompressMultiFrame()"); ip = istart + cSize; op = op ? op + decompressedSize : op; /* can occur if frameContentSize = 0 (empty frame) */ zds->expected = 0; @@ -45432,7 +46838,8 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB /* Consume header (see ZSTDds_decodeFrameHeader) */ DEBUGLOG(4, "Consume header"); - FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), ""); + FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, + useDDictSet ? frameDDict : ZSTD_getDDict(zds)), ""); if (zds->format == ZSTD_f_zstd1 && (MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ @@ -45440,6 +46847,9 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB zds->stage = ZSTDds_skipFrame; } else { FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), ""); + /* Unlike the bufferless API, this path reads the frame header + * without passing it through ZSTD_decompressContinue(). */ + zds->processedCSize = zds->lhSize; zds->expected = ZSTD_blockHeaderSize; zds->stage = ZSTDds_decodeBlockHeader; } @@ -45489,6 +46899,7 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB zds->outBuffSize = neededOutBuffSize; } } } zds->streamStage = zdss_read; + } ZSTD_FALLTHROUGH; case zdss_read: @@ -45648,15 +47059,15 @@ size_t ZSTD_decompressStream_simpleArgs ( * Dependencies *********************************************************/ /**** skipping file: ../common/zstd_deps.h ****/ +/**** skipping file: ../common/bmi2.h ****/ /**** skipping file: ../common/compiler.h ****/ -/**** skipping file: ../common/cpu.h ****/ /**** skipping file: ../common/mem.h ****/ +#include #define FSE_STATIC_LINKING_ONLY /**** skipping file: ../common/fse.h ****/ /**** skipping file: ../common/huf.h ****/ /**** skipping file: ../common/zstd_internal.h ****/ /**** skipping file: zstd_decompress_internal.h ****/ -/**** skipping file: zstd_ddict.h ****/ /**** skipping file: zstd_decompress_block.h ****/ /**** skipping file: ../common/bits.h ****/ @@ -45756,6 +47167,25 @@ static void ZSTD_allocateLiteralsBuffer(ZSTD_DCtx* dctx, void* const dst, const } } +/** + * Zeros the bytes directly after the decompressed literals so that over-reads + * only read zeros, rather than potentially uninitialized memory, or bytes from + * prior decompressions. + */ +static void ZSTD_zeroLiteralsBufferPadding(ZSTD_DCtx* dctx, size_t litSize) +{ + if (dctx->litBufferLocation == ZSTD_split) { + BYTE* const litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE; + assert(litBufferEnd == dctx->litBufferEnd); + ZSTD_memset(litBufferEnd, 0, WILDCOPY_OVERLENGTH); + ZSTD_memset(dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE, 0, WILDCOPY_OVERLENGTH); + } else { + BYTE* const litBufferEnd = dctx->litBuffer + litSize; + assert(litBufferEnd == dctx->litBufferEnd); + ZSTD_memset(litBufferEnd, 0, WILDCOPY_OVERLENGTH); + } +} + /*! ZSTD_decodeLiteralsBlock() : * Where it is possible to do so without being stomped by the output during decompression, the literals block will be stored * in the dstBuffer. If there is room to do so, it will be stored in full in the excess dst space after where the current @@ -45843,8 +47273,10 @@ static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, } } else { if (singleStream) { + /* Compressed literals must use the table-reading variant; + * the generic decoder also accepts raw/RLE data. */ #if defined(HUF_FORCE_DECOMPRESS_X2) - hufSuccess = HUF_decompress1X_DCtx_wksp( + hufSuccess = HUF_decompress1X2_DCtx_wksp( dctx->entropy.hufTable, dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->workspace, sizeof(dctx->workspace), flags); @@ -45873,6 +47305,7 @@ static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, ""); + ZSTD_zeroLiteralsBufferPadding(dctx, litSize); dctx->litPtr = dctx->litBuffer; dctx->litSize = litSize; dctx->litEntropy = 1; @@ -45916,6 +47349,7 @@ static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, { ZSTD_memcpy(dctx->litBuffer, istart + lhSize, litSize); } + ZSTD_zeroLiteralsBufferPadding(dctx, litSize); dctx->litPtr = dctx->litBuffer; dctx->litSize = litSize; return lhSize+litSize; @@ -45962,6 +47396,7 @@ static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, { ZSTD_memset(dctx->litBuffer, istart[lhSize], litSize); } + ZSTD_zeroLiteralsBufferPadding(dctx, litSize); dctx->litPtr = dctx->litBuffer; dctx->litSize = litSize; return lhSize+1; @@ -46254,6 +47689,8 @@ BMI2_TARGET_ATTRIBUTE static void ZSTD_buildFSETable_body_bmi2(ZSTD_seqSymbol* d ZSTD_buildFSETable_body(dt, normalizedCounter, maxSymbolValue, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize); } +#else +#define ZSTD_buildFSETable_body_bmi2 ZSTD_buildFSETable_body_default #endif void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, @@ -46261,13 +47698,11 @@ void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, const U32* baseValue, const U8* nbAdditionalBits, unsigned tableLog, void* wksp, size_t wkspSize, int bmi2) { -#if DYNAMIC_BMI2 - if (bmi2) { + if (ZSTD_USE_BMI2(bmi2)) { ZSTD_buildFSETable_body_bmi2(dt, normalizedCounter, maxSymbolValue, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize); return; } -#endif (void)bmi2; ZSTD_buildFSETable_body_default(dt, normalizedCounter, maxSymbolValue, baseValue, nbAdditionalBits, tableLog, wksp, wkspSize); @@ -46367,9 +47802,10 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, ip++; /* Build DTables */ + assert(ip <= iend); { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr, LLtype, MaxLL, LLFSELog, - ip, iend-ip, + ip, (size_t)(iend-ip), LL_base, LL_bits, LL_defaultDTable, dctx->fseEntropy, dctx->ddictIsCold, nbSeq, @@ -46379,9 +47815,10 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, ip += llhSize; } + assert(ip <= iend); { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr, OFtype, MaxOff, OffFSELog, - ip, iend-ip, + ip, (size_t)(iend-ip), OF_base, OF_bits, OF_defaultDTable, dctx->fseEntropy, dctx->ddictIsCold, nbSeq, @@ -46391,9 +47828,10 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, ip += ofhSize; } + assert(ip <= iend); { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr, MLtype, MaxML, MLFSELog, - ip, iend-ip, + ip, (size_t)(iend-ip), ML_base, ML_bits, ML_defaultDTable, dctx->fseEntropy, dctx->ddictIsCold, nbSeq, @@ -46404,7 +47842,7 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, } } - return ip-istart; + return (size_t)(ip-istart); } @@ -46434,7 +47872,8 @@ typedef struct { * Precondition: *ip <= *op * Postcondition: *op - *op >= 8 */ -HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) { +HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) +{ assert(*ip <= *op); if (offset < 8) { /* close range match, overlap */ @@ -46467,7 +47906,9 @@ HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) { * - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart. * The src buffer must be before the dst buffer. */ -static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) { +static void +ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, size_t length, ZSTD_overlap_e ovtype) +{ ptrdiff_t const diff = op - ip; BYTE* const oend = op + length; @@ -46482,7 +47923,8 @@ static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, pt if (ovtype == ZSTD_overlap_src_before_dst) { /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */ assert(length >= 8); - ZSTD_overlapCopy8(&op, &ip, diff); + assert(diff > 0); + ZSTD_overlapCopy8(&op, &ip, (size_t)diff); length -= 8; assert(op - ip >= 8); assert(op <= oend); @@ -46496,7 +47938,7 @@ static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, pt if (op <= oend_w) { /* Wildcopy until we get close to the end. */ assert(oend > oend_w); - ZSTD_wildcopy(op, ip, oend_w - op, ovtype); + ZSTD_wildcopy(op, ip, (size_t)(oend_w - op), ovtype); ip += oend_w - op; op += oend_w - op; } @@ -46507,7 +47949,8 @@ static void ZSTD_safecopy(BYTE* op, const BYTE* const oend_w, BYTE const* ip, pt /* ZSTD_safecopyDstBeforeSrc(): * This version allows overlap with dst before src, or handles the non-overlap case with dst after src * Kept separate from more common ZSTD_safecopy case to avoid performance impact to the safecopy common case */ -static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length) { +static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, size_t length) +{ ptrdiff_t const diff = op - ip; BYTE* const oend = op + length; @@ -46517,8 +47960,11 @@ static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length return; } - if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) { - ZSTD_wildcopy(op, ip, oend - WILDCOPY_OVERLENGTH - op, ZSTD_no_overlap); + /* ZSTD_wildcopy() may write up to WILDCOPY_OVERLENGTH-1 bytes past its length. + * Those bytes must not land on source bytes the leftover loop has yet to read, + * so src must be at least WILDCOPY_OVERLENGTH bytes ahead of dst. */ + if (op <= oend - WILDCOPY_OVERLENGTH && diff <= -WILDCOPY_OVERLENGTH) { + ZSTD_wildcopy(op, ip, (size_t)(oend - WILDCOPY_OVERLENGTH - op), ZSTD_no_overlap); ip += oend - WILDCOPY_OVERLENGTH - op; op += oend - WILDCOPY_OVERLENGTH - op; } @@ -46569,11 +48015,11 @@ size_t ZSTD_execSequenceEnd(BYTE* op, return sequenceLength; } /* span extDict & currentPrefixSegment */ - { size_t const length1 = dictEnd - match; - ZSTD_memmove(oLitEnd, match, length1); - op = oLitEnd + length1; - sequence.matchLength -= length1; - match = prefixStart; + { size_t const length1 = (size_t)(dictEnd - match); + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; } } ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); @@ -46602,8 +48048,11 @@ size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op, assert(op < op + sequenceLength); assert(oLitEnd < op + sequenceLength); + /* The literals still to be read live in dst at [*litPtr, litLimit). + * The output of this sequence must not run past the literals it consumes. */ + RETURN_ERROR_IF(op + sequenceLength > iLitEnd, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer"); + /* copy literals */ - RETURN_ERROR_IF(op > *litPtr && op < *litPtr + sequence.litLength, dstSize_tooSmall, "output should not catch up to and overwrite literal buffer"); ZSTD_safecopyDstBeforeSrc(op, *litPtr, sequence.litLength); op = oLitEnd; *litPtr = iLitEnd; @@ -46618,11 +48067,11 @@ size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op, return sequenceLength; } /* span extDict & currentPrefixSegment */ - { size_t const length1 = dictEnd - match; - ZSTD_memmove(oLitEnd, match, length1); - op = oLitEnd + length1; - sequence.matchLength -= length1; - match = prefixStart; + { size_t const length1 = (size_t)(dictEnd - match); + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; } } ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst); @@ -46691,11 +48140,11 @@ size_t ZSTD_execSequence(BYTE* op, return sequenceLength; } /* span extDict & currentPrefixSegment */ - { size_t const length1 = dictEnd - match; - ZSTD_memmove(oLitEnd, match, length1); - op = oLitEnd + length1; - sequence.matchLength -= length1; - match = prefixStart; + { size_t const length1 = (size_t)(dictEnd - match); + ZSTD_memmove(oLitEnd, match, length1); + op = oLitEnd + length1; + sequence.matchLength -= length1; + match = prefixStart; } } /* Match within prefix of 1 or more bytes */ @@ -46712,7 +48161,7 @@ size_t ZSTD_execSequence(BYTE* op, * longer than literals (in general). In silesia, ~10% of matches are longer * than 16 bytes. */ - ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap); return sequenceLength; } assert(sequence.offset < WILDCOPY_VECLEN); @@ -46723,7 +48172,7 @@ size_t ZSTD_execSequence(BYTE* op, /* If the match length is > 8 bytes, then continue with the wildcopy. */ if (sequence.matchLength > 8) { assert(op < oMatchEnd); - ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength - 8, ZSTD_overlap_src_before_dst); + ZSTD_wildcopy(op, match, sequence.matchLength - 8, ZSTD_overlap_src_before_dst); } return sequenceLength; } @@ -46784,7 +48233,7 @@ size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op, return sequenceLength; } /* span extDict & currentPrefixSegment */ - { size_t const length1 = dictEnd - match; + { size_t const length1 = (size_t)(dictEnd - match); ZSTD_memmove(oLitEnd, match, length1); op = oLitEnd + length1; sequence.matchLength -= length1; @@ -46804,7 +48253,7 @@ size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op, * longer than literals (in general). In silesia, ~10% of matches are longer * than 16 bytes. */ - ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap); + ZSTD_wildcopy(op, match, sequence.matchLength, ZSTD_no_overlap); return sequenceLength; } assert(sequence.offset < WILDCOPY_VECLEN); @@ -46815,7 +48264,7 @@ size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op, /* If the match length is > 8 bytes, then continue with the wildcopy. */ if (sequence.matchLength > 8) { assert(op < oMatchEnd); - ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst); + ZSTD_wildcopy(op, match, sequence.matchLength-8, ZSTD_overlap_src_before_dst); } return sequenceLength; } @@ -46862,6 +48311,10 @@ FORCE_INLINE_TEMPLATE seq_t ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq) { seq_t seq; +#if defined(__aarch64__) + size_t prevOffset0 = seqState->prevOffset[0]; + size_t prevOffset1 = seqState->prevOffset[1]; + size_t prevOffset2 = seqState->prevOffset[2]; /* * ZSTD_seqSymbol is a 64 bits wide structure. * It can be loaded in one operation @@ -46870,7 +48323,7 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c * operations that cause performance drop. This can be avoided by using this * ZSTD_memcpy hack. */ -#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__)) +# if defined(__GNUC__) && !defined(__clang__) ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS; ZSTD_seqSymbol* const llDInfo = &llDInfoS; ZSTD_seqSymbol* const mlDInfo = &mlDInfoS; @@ -46878,11 +48331,12 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c ZSTD_memcpy(llDInfo, seqState->stateLL.table + seqState->stateLL.state, sizeof(ZSTD_seqSymbol)); ZSTD_memcpy(mlDInfo, seqState->stateML.table + seqState->stateML.state, sizeof(ZSTD_seqSymbol)); ZSTD_memcpy(ofDInfo, seqState->stateOffb.table + seqState->stateOffb.state, sizeof(ZSTD_seqSymbol)); -#else +# else const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state; const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state; const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state; -#endif +# endif + (void)longOffsets; seq.matchLength = mlDInfo->baseValue; seq.litLength = llDInfo->baseValue; { U32 const ofBase = ofDInfo->baseValue; @@ -46901,12 +48355,85 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c assert(llBits <= MaxLLBits); assert(mlBits <= MaxMLBits); assert(ofBits <= MaxOff); - /* - * As gcc has better branch and block analyzers, sometimes it is only - * valuable to mark likeliness for clang, it gives around 3-4% of - * performance. - */ + /* sequence */ + { size_t offset; + if (ofBits > 1) { + ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1); + ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5); + ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 > LONG_OFFSETS_MAX_EXTRA_BITS_32); + ZSTD_STATIC_ASSERT(STREAM_ACCUMULATOR_MIN_32 - LONG_OFFSETS_MAX_EXTRA_BITS_32 >= MaxMLBits); + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ + prevOffset2 = prevOffset1; + prevOffset1 = prevOffset0; + prevOffset0 = offset; + } else { + U32 const ll0 = (llDInfo->baseValue == 0); + if (LIKELY((ofBits == 0))) { + if (ll0) { + offset = prevOffset1; + prevOffset1 = prevOffset0; + prevOffset0 = offset; + } else { + offset = prevOffset0; + } + } else { + offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1); + { size_t temp = (offset == 1) ? prevOffset1 + : (offset == 3) ? prevOffset0 - 1 + : (offset >= 2) ? prevOffset2 + : prevOffset0; + /* 0 is not valid: input corrupted => force offset to -1 => + * corruption detected at execSequence. + */ + temp -= !temp; + prevOffset2 = (offset == 1) ? prevOffset2 : prevOffset1; + prevOffset1 = prevOffset0; + prevOffset0 = offset = temp; + } } } + seq.offset = offset; + } + + if (mlBits > 0) + seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); + + if (UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog))) + BIT_reloadDStream(&seqState->DStream); + + /* Ensure there are enough bits to read the rest of data in 64-bit mode. */ + ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64); + + if (llBits > 0) + seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/); + + DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + + if (!isLastSeq) { + /* Don't update FSE state for last sequence. */ + ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ + BIT_reloadDStream(&seqState->DStream); + } + } + seqState->prevOffset[0] = prevOffset0; + seqState->prevOffset[1] = prevOffset1; + seqState->prevOffset[2] = prevOffset2; +#else /* !defined(__aarch64__) */ + const ZSTD_seqSymbol* const llDInfo = seqState->stateLL.table + seqState->stateLL.state; + const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state; + const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state; + seq.matchLength = mlDInfo->baseValue; + seq.litLength = llDInfo->baseValue; + { U32 const ofBase = ofDInfo->baseValue; + BYTE const llBits = llDInfo->nbAdditionalBits; + BYTE const mlBits = mlDInfo->nbAdditionalBits; + BYTE const ofBits = ofDInfo->nbAdditionalBits; + BYTE const totalBits = llBits+mlBits+ofBits; + assert(llBits <= MaxLLBits); + assert(mlBits <= MaxMLBits); + assert(ofBits <= MaxOff); /* sequence */ { size_t offset; if (ofBits > 1) { @@ -46966,14 +48493,18 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); if (!isLastSeq) { - /* don't update FSE state for last Sequence */ - ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */ - ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */ + /* Don't update FSE state for last sequence. */ + ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, + llDInfo->nextState, llDInfo->nbBits); /* <= 9 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, + mlDInfo->nextState, mlDInfo->nbBits); /* <= 9 bits */ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ - ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, + ofDInfo->nextState, ofDInfo->nbBits); /* <= 8 bits */ BIT_reloadDStream(&seqState->DStream); } } +#endif /* defined(__aarch64__) */ return seq; } @@ -47038,10 +48569,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, const void* seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset) { - const BYTE* ip = (const BYTE*)seqStart; - const BYTE* const iend = ip + seqSize; BYTE* const ostart = (BYTE*)dst; - BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, maxDstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -47056,7 +48585,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, dctx->fseEntropy = 1; { U32 i; for (i=0; ientropy.rep[i]; } RETURN_ERROR_IF( - ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)), corruption_detected, ""); ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); @@ -47148,7 +48677,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */ if (nbSeq > 0) { - const size_t leftoverLit = dctx->litBufferEnd - litPtr; + const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr); + assert(dctx->litBufferEnd >= litPtr); DEBUGLOG(6, "There are %i sequences left, and %zu/%zu literals left in buffer", nbSeq, leftoverLit, sequence.litLength); if (leftoverLit) { RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); @@ -47250,10 +48780,10 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, const void* seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset) { - const BYTE* ip = (const BYTE*)seqStart; - const BYTE* const iend = ip + seqSize; BYTE* const ostart = (BYTE*)dst; - BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ZSTD_maybeNullPtrAdd(ostart, maxDstSize) : dctx->litBuffer; + BYTE* const oend = (dctx->litBufferLocation == ZSTD_not_in_dst) ? + (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) : + dctx->litBuffer; BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* const litEnd = litPtr + dctx->litSize; @@ -47268,7 +48798,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, dctx->fseEntropy = 1; { U32 i; for (i = 0; i < ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; } RETURN_ERROR_IF( - ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend - ip)), + ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)), corruption_detected, ""); ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); @@ -47352,8 +48882,8 @@ size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence, { const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart; /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted. * No consequence though : memory address is only used for prefetching, not for dereferencing */ - const BYTE* const match = ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, prefetchPos), sequence.offset); - PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ + const BYTE* const match = (const BYTE*)ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset); + PREFETCH_L1(match); PREFETCH_L1(ZSTD_wrappedPtrAdd(match, CACHELINE_SIZE)); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ } return prefetchPos + sequence.matchLength; } @@ -47369,10 +48899,10 @@ ZSTD_decompressSequencesLong_body( const void* seqStart, size_t seqSize, int nbSeq, const ZSTD_longOffset_e isLongOffset) { - const BYTE* ip = (const BYTE*)seqStart; - const BYTE* const iend = ip + seqSize; BYTE* const ostart = (BYTE*)dst; - BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ZSTD_maybeNullPtrAdd(ostart, maxDstSize); + BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ? + dctx->litBuffer : + (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -47394,9 +48924,8 @@ ZSTD_decompressSequencesLong_body( dctx->fseEntropy = 1; { int i; for (i=0; ientropy.rep[i]; } assert(dst != NULL); - assert(iend >= ip); RETURN_ERROR_IF( - ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)), + ERR_isError(BIT_initDStream(&seqState.DStream, seqStart, seqSize)), corruption_detected, ""); ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr); ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr); @@ -47415,9 +48944,9 @@ ZSTD_decompressSequencesLong_body( if (dctx->litBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) { /* lit buffer is reaching split point, empty out the first buffer and transition to litExtraBuffer */ - const size_t leftoverLit = dctx->litBufferEnd - litPtr; - if (leftoverLit) - { + const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr); + assert(dctx->litBufferEnd >= litPtr); + if (leftoverLit) { RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength -= leftoverLit; @@ -47461,7 +48990,8 @@ ZSTD_decompressSequencesLong_body( for ( ; seqNblitBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) { - const size_t leftoverLit = dctx->litBufferEnd - litPtr; + const size_t leftoverLit = (size_t)(dctx->litBufferEnd - litPtr); + assert(dctx->litBufferEnd >= litPtr); if (leftoverLit) { RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); @@ -47500,7 +49030,8 @@ ZSTD_decompressSequencesLong_body( /* last literal segment */ if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */ - size_t const lastLLSize = litBufferEnd - litPtr; + size_t const lastLLSize = (size_t)(litBufferEnd - litPtr); + assert(litBufferEnd >= litPtr); RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, ""); if (op != NULL) { ZSTD_memmove(op, litPtr, lastLLSize); @@ -47509,7 +49040,8 @@ ZSTD_decompressSequencesLong_body( litPtr = dctx->litExtraBuffer; litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; } - { size_t const lastLLSize = litBufferEnd - litPtr; + { size_t const lastLLSize = (size_t)(litBufferEnd - litPtr); + assert(litBufferEnd >= litPtr); RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); if (op != NULL) { ZSTD_memmove(op, litPtr, lastLLSize); @@ -47566,6 +49098,16 @@ ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx, } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ +#else + +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG +#define ZSTD_decompressSequences_bmi2 ZSTD_decompressSequences_default +#define ZSTD_decompressSequencesSplitLitBuffer_bmi2 ZSTD_decompressSequencesSplitLitBuffer_default +#endif +#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT +#define ZSTD_decompressSequencesLong_bmi2 ZSTD_decompressSequencesLong_default +#endif + #endif /* DYNAMIC_BMI2 */ #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG @@ -47575,11 +49117,9 @@ ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequences"); -#if DYNAMIC_BMI2 - if (ZSTD_DCtx_get_bmi2(dctx)) { + if (ZSTD_USE_BMI2(ZSTD_DCtx_get_bmi2(dctx))) { return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } -#endif return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } static size_t @@ -47588,11 +49128,9 @@ ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDst const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer"); -#if DYNAMIC_BMI2 - if (ZSTD_DCtx_get_bmi2(dctx)) { + if (ZSTD_USE_BMI2(ZSTD_DCtx_get_bmi2(dctx))) { return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } -#endif return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ @@ -47611,11 +49149,9 @@ ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx, const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequencesLong"); -#if DYNAMIC_BMI2 - if (ZSTD_DCtx_get_bmi2(dctx)) { + if (ZSTD_USE_BMI2(ZSTD_DCtx_get_bmi2(dctx))) { return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } -#endif return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ @@ -47626,9 +49162,9 @@ ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx, * both the prefix and the extDict. At @p op any offset larger than this * is invalid. */ -static size_t ZSTD_totalHistorySize(BYTE* op, BYTE const* virtualStart) +static size_t ZSTD_totalHistorySize(void* curPtr, const void* virtualStart) { - return (size_t)(op - virtualStart); + return (size_t)ZSTD_wrappedPtrDiff((const BYTE*)curPtr, (const BYTE*)virtualStart); } typedef struct { @@ -47727,7 +49263,7 @@ ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t. */ size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx)); - size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd((BYTE*)dst, blockSizeMax), (BYTE const*)dctx->virtualStart); + size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd(dst, (ptrdiff_t)blockSizeMax), (BYTE const*)dctx->virtualStart); /* isLongOffset must be true if there are long offsets. * Offsets are long if they are larger than ZSTD_maxShortOffset(). * We don't expect that to be the case in 64-bit mode. @@ -47816,6 +49352,19 @@ void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize) dctx->prefixStart = dst; dctx->previousDstEnd = dst; } + /* The external dictionary and current prefix share the frame window. + * As the prefix grows after a wrap, retaining a full external window + * could let corrupt offsets alias the destination and expose stale literals. + * decodedSize > 0 ensures the frame header has initialized windowSize. + * Only kicks in after decoding windowSize bytes because the entire dictionary is + * valid as long as a single byte of the dictionary is in the window. + */ + if (dstSize > 0 && dctx->isFrameDecompression && dctx->decodedSize > 0 && dctx->decodedSize >= dctx->fParams.windowSize) { + size_t const prefixSize = (size_t)((const char*)dctx->previousDstEnd - (const char*)dctx->prefixStart); + size_t const extDictSize = (size_t)((const char*)dctx->prefixStart - (const char*)dctx->virtualStart); + U64 const maxExtDictSize = prefixSize < dctx->fParams.windowSize ? dctx->fParams.windowSize - prefixSize : 0; + dctx->virtualStart = (const char*)dctx->prefixStart - (size_t)MIN((U64)extDictSize, maxExtDictSize); + } } @@ -47828,7 +49377,9 @@ size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, ZSTD_checkContinuity(dctx, dst, dstCapacity); dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming); FORWARD_IF_ERROR(dSize, ""); - dctx->previousDstEnd = (char*)dst + dSize; + /* No output means no new history; dst may be NULL. */ + if (dSize != 0) + dctx->previousDstEnd = (char*)dst + dSize; return dSize; } @@ -48573,38 +50124,30 @@ void COVER_dictSelectionFree(COVER_dictSelection_t selection); /*-************************************* * Console display +* +* Captures the `displayLevel` variable in the local scope. ***************************************/ -#ifndef LOCALDISPLAYLEVEL -static int g_displayLevel = 0; -#endif #undef DISPLAY #define DISPLAY(...) \ { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ } -#undef LOCALDISPLAYLEVEL -#define LOCALDISPLAYLEVEL(displayLevel, l, ...) \ +#undef DISPLAYLEVEL +#define DISPLAYLEVEL(l, ...) \ if (displayLevel >= l) { \ DISPLAY(__VA_ARGS__); \ } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */ -#undef DISPLAYLEVEL -#define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__) -#ifndef LOCALDISPLAYUPDATE -static const clock_t g_refreshRate = CLOCKS_PER_SEC * 15 / 100; -static clock_t g_time = 0; -#endif -#undef LOCALDISPLAYUPDATE -#define LOCALDISPLAYUPDATE(displayLevel, l, ...) \ +#undef DISPLAYUPDATE +#define DISPLAYUPDATE(lastUpdateTime, l, ...) \ if (displayLevel >= l) { \ - if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) { \ - g_time = clock(); \ + const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100; \ + if ((clock() - lastUpdateTime > refreshRate) || (displayLevel >= 4)) { \ + lastUpdateTime = clock(); \ DISPLAY(__VA_ARGS__); \ } \ } -#undef DISPLAYUPDATE -#define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__) /*-************************************* * Hash table @@ -48750,6 +50293,7 @@ typedef struct { U32 *freqs; U32 *dmerAt; unsigned d; + int displayLevel; } COVER_ctx_t; #if ZDICT_QSORT == ZDICT_QSORT_C90 @@ -48797,7 +50341,7 @@ static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) { } /** - * Same as COVER_cmp() except ties are broken by pointer value + * Same as COVER_cmp() except ties are broken by the position each element holds */ #if (ZDICT_QSORT == ZDICT_QSORT_MSVC) || (ZDICT_QSORT == ZDICT_QSORT_APPLE) static int WIN_CDECL COVER_strict_cmp(void* g_coverCtx, const void* lp, const void* rp) { @@ -48808,7 +50352,9 @@ static int COVER_strict_cmp(const void *lp, const void *rp) { #endif int result = COVER_cmp((COVER_ctx_t*)g_coverCtx, lp, rp); if (result == 0) { - result = lp < rp ? -1 : 1; + U32 const lpos = *(const U32 *)lp; + U32 const rpos = *(const U32 *)rp; + result = (lpos < rpos) ? -1 : (lpos > rpos) ? 1 : 0; } return result; } @@ -48824,7 +50370,9 @@ static int COVER_strict_cmp8(const void *lp, const void *rp) { #endif int result = COVER_cmp8((COVER_ctx_t*)g_coverCtx, lp, rp); if (result == 0) { - result = lp < rp ? -1 : 1; + U32 const lpos = *(const U32 *)lp; + U32 const rpos = *(const U32 *)rp; + result = (lpos < rpos) ? -1 : (lpos > rpos) ? 1 : 0; } return result; } @@ -49114,7 +50662,7 @@ static void COVER_ctx_destroy(COVER_ctx_t *ctx) { */ static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, - unsigned d, double splitPoint) + unsigned d, double splitPoint, int displayLevel) { const BYTE *const samples = (const BYTE *)samplesBuffer; const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples); @@ -49123,13 +50671,25 @@ static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples; const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize; const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize; + const size_t readLength = MAX(d, sizeof(U64)); + ctx->displayLevel = displayLevel; /* Checks */ - if (totalSamplesSize < MAX(d, sizeof(U64)) || + if (totalSamplesSize < readLength || totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) { DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n", (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20)); return ERROR(srcSize_wrong); } + /* The training set must be large enough for the partial suffix array, whose + * size is `trainingSamplesSize - MAX(d, sizeof(U64)) + 1`. When splitPoint + * < 1.0 the training set is a subset of the corpus, so it can be smaller + * than the total even after the check above. Guard against the size_t + * subtraction underflowing into a huge allocation. */ + if (trainingSamplesSize < MAX(d, sizeof(U64))) { + DISPLAYLEVEL(1, "Training samples size is too small (%u), minimum size is %u\n", + (unsigned)trainingSamplesSize, (unsigned)MAX(d, sizeof(U64))); + return ERROR(srcSize_wrong); + } /* Check if there are at least 5 training samples */ if (nbTrainSamples < 5) { DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples); @@ -49152,7 +50712,7 @@ static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, ctx->nbTrainSamples = nbTrainSamples; ctx->nbTestSamples = nbTestSamples; /* Partial suffix array */ - ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1; + ctx->suffixSize = trainingSamplesSize - readLength + 1; ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32)); /* Maps index to the dmerID */ ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32)); @@ -49178,7 +50738,7 @@ static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, { /* suffix is a partial suffix array. * It only sorts suffixes by their first parameters.d bytes. - * The sort is stable, so each dmer group is sorted by position in input. + * Ties are broken by position, so each group is sorted by input position. */ U32 i; for (i = 0; i < ctx->suffixSize; ++i) { @@ -49207,14 +50767,14 @@ void COVER_warnOnSmallCorpus(size_t maxDictSize, size_t nbDmers, int displayLeve if (ratio >= 10) { return; } - LOCALDISPLAYLEVEL(displayLevel, 1, - "WARNING: The maximum dictionary size %u is too large " - "compared to the source size %u! " - "size(source)/size(dictionary) = %f, but it should be >= " - "10! This may lead to a subpar dictionary! We recommend " - "training on sources at least 10x, and preferably 100x " - "the size of the dictionary! \n", (U32)maxDictSize, - (U32)nbDmers, ratio); + DISPLAYLEVEL(1, + "WARNING: The maximum dictionary size %u is too large " + "compared to the source size %u! " + "size(source)/size(dictionary) = %f, but it should be >= " + "10! This may lead to a subpar dictionary! We recommend " + "training on sources at least 10x, and preferably 100x " + "the size of the dictionary! \n", (U32)maxDictSize, + (U32)nbDmers, ratio); } COVER_epoch_info_t COVER_computeEpochs(U32 maxDictSize, @@ -49249,6 +50809,8 @@ static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs, const size_t maxZeroScoreRun = MAX(10, MIN(100, epochs.num >> 3)); size_t zeroScoreRun = 0; size_t epoch; + clock_t lastUpdateTime = 0; + const int displayLevel = ctx->displayLevel; DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n", (U32)epochs.num, (U32)epochs.size); /* Loop through the epochs until there are no more segments or the dictionary @@ -49282,6 +50844,7 @@ static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs, tail -= segmentSize; memcpy(dict + tail, ctx->samples + segment.begin, segmentSize); DISPLAYUPDATE( + lastUpdateTime, 2, "\r%u%% ", (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity)); } @@ -49297,9 +50860,8 @@ ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover( BYTE* const dict = (BYTE*)dictBuffer; COVER_ctx_t ctx; COVER_map_t activeDmers; + const int displayLevel = (int)parameters.zParams.notificationLevel; parameters.splitPoint = 1.0; - /* Initialize global data */ - g_displayLevel = (int)parameters.zParams.notificationLevel; /* Checks */ if (!COVER_checkParameters(parameters, dictBufferCapacity)) { DISPLAYLEVEL(1, "Cover parameters incorrect\n"); @@ -49317,12 +50879,12 @@ ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover( /* Initialize context and activeDmers */ { size_t const initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, - parameters.d, parameters.splitPoint); + parameters.d, parameters.splitPoint, displayLevel); if (ZSTD_isError(initVal)) { return initVal; } } - COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, g_displayLevel); + COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.suffixSize, displayLevel); if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) { DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n"); COVER_ctx_destroy(&ctx); @@ -49536,6 +51098,8 @@ COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBuffe size_t largestDict = 0; size_t largestCompressed = 0; + size_t candidateContentSize = 0; + size_t candidateDict = 0; BYTE* customDictContentEnd = customDictContent + dictContentSize; BYTE* largestDictbuffer = (BYTE*)malloc(dictBufferCapacity); @@ -49550,20 +51114,20 @@ COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBuffe /* Initial dictionary size and compressed size */ memcpy(largestDictbuffer, customDictContent, dictContentSize); - dictContentSize = ZDICT_finalizeDictionary( + largestDict = ZDICT_finalizeDictionary( largestDictbuffer, dictBufferCapacity, customDictContent, dictContentSize, samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams); - if (ZDICT_isError(dictContentSize)) { + if (ZDICT_isError(largestDict)) { free(largestDictbuffer); free(candidateDictBuffer); - return COVER_dictSelectionError(dictContentSize); + return COVER_dictSelectionError(largestDict); } totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes, samplesBuffer, offsets, nbCheckSamples, nbSamples, - largestDictbuffer, dictContentSize); + largestDictbuffer, largestDict); if (ZSTD_isError(totalCompressedSize)) { free(largestDictbuffer); @@ -49573,31 +51137,29 @@ COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBuffe if (params.shrinkDict == 0) { free(candidateDictBuffer); - return setDictSelection(largestDictbuffer, dictContentSize, totalCompressedSize); + return setDictSelection(largestDictbuffer, largestDict, totalCompressedSize); } - largestDict = dictContentSize; largestCompressed = totalCompressedSize; - dictContentSize = ZDICT_DICTSIZE_MIN; + candidateContentSize = ZDICT_DICTSIZE_MIN; - /* Largest dict is initially at least ZDICT_DICTSIZE_MIN */ - while (dictContentSize < largestDict) { + while (candidateContentSize < dictContentSize) { memcpy(candidateDictBuffer, largestDictbuffer, largestDict); - dictContentSize = ZDICT_finalizeDictionary( - candidateDictBuffer, dictBufferCapacity, customDictContentEnd - dictContentSize, dictContentSize, + candidateDict = ZDICT_finalizeDictionary( + candidateDictBuffer, dictBufferCapacity, customDictContentEnd - candidateContentSize, candidateContentSize, samplesBuffer, samplesSizes, nbFinalizeSamples, params.zParams); - if (ZDICT_isError(dictContentSize)) { + if (ZDICT_isError(candidateDict)) { free(largestDictbuffer); free(candidateDictBuffer); - return COVER_dictSelectionError(dictContentSize); + return COVER_dictSelectionError(candidateDict); } totalCompressedSize = COVER_checkTotalCompressedSize(params, samplesSizes, samplesBuffer, offsets, nbCheckSamples, nbSamples, - candidateDictBuffer, dictContentSize); + candidateDictBuffer, candidateDict); if (ZSTD_isError(totalCompressedSize)) { free(largestDictbuffer); @@ -49607,14 +51169,13 @@ COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBuffe if ((double)totalCompressedSize <= (double)largestCompressed * regressionTolerance) { free(largestDictbuffer); - return setDictSelection( candidateDictBuffer, dictContentSize, totalCompressedSize ); + return setDictSelection( candidateDictBuffer, candidateDict, totalCompressedSize ); } - dictContentSize *= 2; + candidateContentSize *= 2; } - dictContentSize = largestDict; totalCompressedSize = largestCompressed; free(candidateDictBuffer); - return setDictSelection( largestDictbuffer, dictContentSize, totalCompressedSize ); + return setDictSelection( largestDictbuffer, largestDict, totalCompressedSize ); } /** @@ -49645,6 +51206,7 @@ static void COVER_tryParameters(void *opaque) BYTE* const dict = (BYTE*)malloc(dictBufferCapacity); COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC)); U32* const freqs = (U32*)malloc(ctx->suffixSize * sizeof(U32)); + const int displayLevel = ctx->displayLevel; if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) { DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n"); goto _cleanup; @@ -49696,21 +51258,22 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize); const unsigned shrinkDict = 0; /* Local variables */ - const int displayLevel = parameters->zParams.notificationLevel; + int displayLevel = (int)parameters->zParams.notificationLevel; unsigned iteration = 1; unsigned d; unsigned k; COVER_best_t best; POOL_ctx *pool = NULL; int warned = 0; + clock_t lastUpdateTime = 0; /* Checks */ if (splitPoint <= 0 || splitPoint > 1) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n"); + DISPLAYLEVEL(1, "Incorrect parameters\n"); return ERROR(parameter_outOfBound); } if (kMinK < kMaxD || kMaxK < kMinK) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n"); + DISPLAYLEVEL(1, "Incorrect parameters\n"); return ERROR(parameter_outOfBound); } if (nbSamples == 0) { @@ -49730,19 +51293,19 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( } /* Initialization */ COVER_best_init(&best); - /* Turn down global display level to clean up display at level 2 and below */ - g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1; /* Loop through d first because each new value needs a new context */ - LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n", + DISPLAYLEVEL(2, "Trying %u different sets of parameters\n", kIterations); for (d = kMinD; d <= kMaxD; d += 2) { /* Initialize the context for this value of d */ COVER_ctx_t ctx; - LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d); + DISPLAYLEVEL(3, "d=%u\n", d); { - const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint); + /* Turn down global display level to clean up display at level 2 and below */ + const int childDisplayLevel = (displayLevel == 0) ? 0 : displayLevel - 1; + const size_t initVal = COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, childDisplayLevel); if (ZSTD_isError(initVal)) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n"); + DISPLAYLEVEL(1, "Failed to initialize context\n"); COVER_best_destroy(&best); POOL_free(pool); return initVal; @@ -49757,9 +51320,9 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( /* Prepare the arguments */ COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc( sizeof(COVER_tryParameters_data_t)); - LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k); + DISPLAYLEVEL(3, "k=%u\n", k); if (!data) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n"); + DISPLAYLEVEL(1, "Failed to allocate parameters\n"); COVER_best_destroy(&best); COVER_ctx_destroy(&ctx); POOL_free(pool); @@ -49774,7 +51337,7 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( data->parameters.splitPoint = splitPoint; data->parameters.steps = kSteps; data->parameters.shrinkDict = shrinkDict; - data->parameters.zParams.notificationLevel = g_displayLevel; + data->parameters.zParams.notificationLevel = (unsigned)ctx.displayLevel; /* Check the parameters */ if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) { DISPLAYLEVEL(1, "Cover parameters incorrect\n"); @@ -49789,14 +51352,14 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( COVER_tryParameters(data); } /* Print status */ - LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ", - (unsigned)((iteration * 100) / kIterations)); + DISPLAYUPDATE(lastUpdateTime, 2, "\r%u%% ", + (unsigned)((iteration * 100) / kIterations)); ++iteration; } COVER_best_wait(&best); COVER_ctx_destroy(&ctx); } - LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", ""); + DISPLAYLEVEL(2, "\r%79s\r", ""); /* Fill the output buffer and parameters with output of the best parameters */ { const size_t dictSize = best.dictSize; @@ -49842,18 +51405,15 @@ ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( */ /*- Compiler specifics -*/ -#ifdef __clang__ -#pragma clang diagnostic ignored "-Wshorten-64-to-32" -#endif - #if defined(_MSC_VER) -# pragma warning(disable : 4244) # pragma warning(disable : 4127) /* C4127 : Condition expression is constant */ #endif /*- Dependencies -*/ #include +#include +#include #include #include @@ -49917,6 +51477,8 @@ divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * #endif /* _DIVSUFSORT_H */ /**** ended inlining divsufsort.h ****/ +#define PTRDIFF_TO_INT(x) (assert((x) <= INT_MAX && (x) >= INT_MIN), (int)(x)) + /*- Constants -*/ #if defined(INLINE) # undef INLINE @@ -50074,8 +51636,8 @@ ss_isqrt(int x) { int y, e; if(x >= (SS_BLOCKSIZE * SS_BLOCKSIZE)) { return SS_BLOCKSIZE; } - e = (x & 0xffff0000) ? - ((x & 0xff000000) ? + e = ((unsigned)x & 0xffff0000) ? + (((unsigned)x & 0xff000000) ? 24 + lg_table[(x >> 24) & 0xff] : 16 + lg_table[(x >> 16) & 0xff]) : ((x & 0x0000ff00) ? @@ -50229,7 +51791,7 @@ ss_pivot(const unsigned char *Td, const int *PA, int *first, int *last) { int *middle; int t; - t = last - first; + t = PTRDIFF_TO_INT(last - first); middle = first + t / 2; if(t <= 512) { @@ -50284,7 +51846,7 @@ ss_mintrosort(const unsigned char *T, const int *PA, int limit; int v, x = 0; - for(ssize = 0, limit = ss_ilg(last - first);;) { + for(ssize = 0, limit = ss_ilg(PTRDIFF_TO_INT(last - first));;) { if((last - first) <= SS_INSERTIONSORT_THRESHOLD) { #if 1 < SS_INSERTIONSORT_THRESHOLD @@ -50295,7 +51857,7 @@ ss_mintrosort(const unsigned char *T, const int *PA, } Td = T + depth; - if(limit-- == 0) { ss_heapsort(Td, PA, first, last - first); } + if(limit-- == 0) { ss_heapsort(Td, PA, first, PTRDIFF_TO_INT(last - first)); } if(limit < 0) { for(a = first + 1, v = Td[PA[*first]]; a < last; ++a) { if((x = Td[PA[*a]]) != v) { @@ -50310,16 +51872,16 @@ ss_mintrosort(const unsigned char *T, const int *PA, if((a - first) <= (last - a)) { if(1 < (a - first)) { STACK_PUSH(a, last, depth, -1); - last = a, depth += 1, limit = ss_ilg(a - first); + last = a, depth += 1, limit = ss_ilg(PTRDIFF_TO_INT(a - first)); } else { first = a, limit = -1; } } else { if(1 < (last - a)) { - STACK_PUSH(first, a, depth + 1, ss_ilg(a - first)); + STACK_PUSH(first, a, depth + 1, ss_ilg(PTRDIFF_TO_INT(a - first))); first = a, limit = -1; } else { - last = a, depth += 1, limit = ss_ilg(a - first); + last = a, depth += 1, limit = ss_ilg(PTRDIFF_TO_INT(a - first)); } } continue; @@ -50356,9 +51918,9 @@ ss_mintrosort(const unsigned char *T, const int *PA, if(a <= d) { c = b - 1; - if((s = a - first) > (t = b - a)) { s = t; } + if((s = PTRDIFF_TO_INT(a - first)) > (t = PTRDIFF_TO_INT(b - a))) { s = t; } for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } - if((s = d - c) > (t = last - d - 1)) { s = t; } + if((s = PTRDIFF_TO_INT(d - c)) > (t = PTRDIFF_TO_INT(last - d - 1))) { s = t; } for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } a = first + (b - a), c = last - (d - c); @@ -50366,38 +51928,38 @@ ss_mintrosort(const unsigned char *T, const int *PA, if((a - first) <= (last - c)) { if((last - c) <= (c - b)) { - STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); + STACK_PUSH(b, c, depth + 1, ss_ilg(PTRDIFF_TO_INT(c - b))); STACK_PUSH(c, last, depth, limit); last = a; } else if((a - first) <= (c - b)) { STACK_PUSH(c, last, depth, limit); - STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); + STACK_PUSH(b, c, depth + 1, ss_ilg(PTRDIFF_TO_INT(c - b))); last = a; } else { STACK_PUSH(c, last, depth, limit); STACK_PUSH(first, a, depth, limit); - first = b, last = c, depth += 1, limit = ss_ilg(c - b); + first = b, last = c, depth += 1, limit = ss_ilg(PTRDIFF_TO_INT(c - b)); } } else { if((a - first) <= (c - b)) { - STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); + STACK_PUSH(b, c, depth + 1, ss_ilg(PTRDIFF_TO_INT(c - b))); STACK_PUSH(first, a, depth, limit); first = c; } else if((last - c) <= (c - b)) { STACK_PUSH(first, a, depth, limit); - STACK_PUSH(b, c, depth + 1, ss_ilg(c - b)); + STACK_PUSH(b, c, depth + 1, ss_ilg(PTRDIFF_TO_INT(c - b))); first = c; } else { STACK_PUSH(first, a, depth, limit); STACK_PUSH(c, last, depth, limit); - first = b, last = c, depth += 1, limit = ss_ilg(c - b); + first = b, last = c, depth += 1, limit = ss_ilg(PTRDIFF_TO_INT(c - b)); } } } else { limit += 1; if(Td[PA[*first] - 1] < v) { first = ss_partition(PA, first, last, depth); - limit = ss_ilg(last - first); + limit = ss_ilg(PTRDIFF_TO_INT(last - first)); } depth += 1; } @@ -50426,7 +51988,8 @@ void ss_rotate(int *first, int *middle, int *last) { int *a, *b, t; int l, r; - l = middle - first, r = last - middle; + l = PTRDIFF_TO_INT(middle - first); + r = PTRDIFF_TO_INT(last - middle); for(; (0 < l) && (0 < r);) { if(l == r) { ss_blockswap(first, middle, l); break; } if(l < r) { @@ -50476,7 +52039,7 @@ ss_inplacemerge(const unsigned char *T, const int *PA, for(;;) { if(*(last - 1) < 0) { x = 1; p = PA + ~*(last - 1); } else { x = 0; p = PA + *(last - 1); } - for(a = first, len = middle - first, half = len >> 1, r = -1; + for(a = first, len = PTRDIFF_TO_INT(middle - first), half = len >> 1, r = -1; 0 < len; len = half, half >>= 1) { b = a + half; @@ -50515,7 +52078,7 @@ ss_mergeforward(const unsigned char *T, const int *PA, int r; bufend = buf + (middle - first) - 1; - ss_blockswap(buf, first, middle - first); + ss_blockswap(buf, first, PTRDIFF_TO_INT(middle - first)); for(t = *(a = first), b = buf, c = middle;;) { r = ss_compare(T, PA + *b, PA + *c, depth); @@ -50567,7 +52130,7 @@ ss_mergebackward(const unsigned char *T, const int *PA, int x; bufend = buf + (last - middle) - 1; - ss_blockswap(buf, middle, last - middle); + ss_blockswap(buf, middle, PTRDIFF_TO_INT(last - middle)); x = 0; if(*bufend < 0) { p1 = PA + ~*bufend; x |= 1; } @@ -50656,7 +52219,7 @@ ss_swapmerge(const unsigned char *T, const int *PA, continue; } - for(m = 0, len = MIN(middle - first, last - middle), half = len >> 1; + for(m = 0, len = PTRDIFF_TO_INT(MIN(middle - first, last - middle)), half = len >> 1; 0 < len; len = half, half >>= 1) { if(ss_compare(T, PA + GETIDX(*(middle + m + half)), @@ -50725,8 +52288,8 @@ sssort(const unsigned char *T, const int *PA, ss_mintrosort(T, PA, first, last, depth); #else if((bufsize < SS_BLOCKSIZE) && - (bufsize < (last - first)) && - (bufsize < (limit = ss_isqrt(last - first)))) { + (bufsize < PTRDIFF_TO_INT(last - first)) && + (bufsize < (limit = ss_isqrt(PTRDIFF_TO_INT(last - first))))) { if(SS_BLOCKSIZE < limit) { limit = SS_BLOCKSIZE; } buf = middle = last - limit, bufsize = limit; } else { @@ -50738,7 +52301,7 @@ sssort(const unsigned char *T, const int *PA, #elif 1 < SS_BLOCKSIZE ss_insertionsort(T, PA, a, a + SS_BLOCKSIZE, depth); #endif - curbufsize = last - (a + SS_BLOCKSIZE); + curbufsize = PTRDIFF_TO_INT(last - (a + SS_BLOCKSIZE)); curbuf = a + SS_BLOCKSIZE; if(curbufsize <= bufsize) { curbufsize = bufsize, curbuf = buf; } for(b = a, k = SS_BLOCKSIZE, j = i; j & 1; b -= k, k <<= 1, j >>= 1) { @@ -50891,7 +52454,7 @@ tr_pivot(const int *ISAd, int *first, int *last) { int *middle; int t; - t = last - first; + t = PTRDIFF_TO_INT(last - first); middle = first + t / 2; if(t <= 512) { @@ -50973,9 +52536,9 @@ tr_partition(const int *ISAd, if(a <= d) { c = b - 1; - if((s = a - first) > (t = b - a)) { s = t; } + if((s = PTRDIFF_TO_INT(a - first)) > (t = PTRDIFF_TO_INT(b - a))) { s = t; } for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } - if((s = d - c) > (t = last - d - 1)) { s = t; } + if((s = PTRDIFF_TO_INT(d - c)) > (t = PTRDIFF_TO_INT(last - d - 1))) { s = t; } for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); } first += (b - a), last -= (d - c); } @@ -50992,17 +52555,17 @@ tr_copy(int *ISA, const int *SA, int *c, *d, *e; int s, v; - v = b - SA - 1; + v = PTRDIFF_TO_INT(b - SA - 1); for(c = first, d = a - 1; c <= d; ++c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *++d = s; - ISA[s] = d - SA; + ISA[s] = PTRDIFF_TO_INT(d - SA); } } for(c = last - 1, e = d + 1, d = b; e < d; --c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *--d = s; - ISA[s] = d - SA; + ISA[s] = PTRDIFF_TO_INT(d - SA); } } } @@ -51016,13 +52579,13 @@ tr_partialcopy(int *ISA, const int *SA, int s, v; int rank, lastrank, newrank = -1; - v = b - SA - 1; + v = PTRDIFF_TO_INT(b - SA - 1); lastrank = -1; for(c = first, d = a - 1; c <= d; ++c) { if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *++d = s; rank = ISA[s + depth]; - if(lastrank != rank) { lastrank = rank; newrank = d - SA; } + if(lastrank != rank) { lastrank = rank; newrank = PTRDIFF_TO_INT(d - SA); } ISA[s] = newrank; } } @@ -51030,7 +52593,7 @@ tr_partialcopy(int *ISA, const int *SA, lastrank = -1; for(e = d; first <= e; --e) { rank = ISA[*e]; - if(lastrank != rank) { lastrank = rank; newrank = e - SA; } + if(lastrank != rank) { lastrank = rank; newrank = PTRDIFF_TO_INT(e - SA); } if(newrank != rank) { ISA[*e] = newrank; } } @@ -51039,7 +52602,7 @@ tr_partialcopy(int *ISA, const int *SA, if((0 <= (s = *c - depth)) && (ISA[s] == v)) { *--d = s; rank = ISA[s + depth]; - if(lastrank != rank) { lastrank = rank; newrank = d - SA; } + if(lastrank != rank) { lastrank = rank; newrank = PTRDIFF_TO_INT(d - SA); } ISA[s] = newrank; } } @@ -51055,23 +52618,23 @@ tr_introsort(int *ISA, const int *ISAd, int *a, *b, *c; int t; int v, x = 0; - int incr = ISAd - ISA; + int incr = PTRDIFF_TO_INT(ISAd - ISA); int limit, next; int ssize, trlink = -1; - for(ssize = 0, limit = tr_ilg(last - first);;) { + for(ssize = 0, limit = tr_ilg(PTRDIFF_TO_INT(last - first));;) { if(limit < 0) { if(limit == -1) { /* tandem repeat partition */ - tr_partition(ISAd - incr, first, first, last, &a, &b, last - SA - 1); + tr_partition(ISAd - incr, first, first, last, &a, &b, PTRDIFF_TO_INT(last - SA - 1)); /* update ranks */ if(a < last) { - for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; } + for(c = first, v = PTRDIFF_TO_INT(a - SA - 1); c < a; ++c) { ISA[*c] = v; } } if(b < last) { - for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } + for(c = a, v = PTRDIFF_TO_INT(b - SA - 1); c < b; ++c) { ISA[*c] = v; } } /* push */ @@ -51082,19 +52645,19 @@ tr_introsort(int *ISA, const int *ISAd, } if((a - first) <= (last - b)) { if(1 < (a - first)) { - STACK_PUSH5(ISAd, b, last, tr_ilg(last - b), trlink); - last = a, limit = tr_ilg(a - first); + STACK_PUSH5(ISAd, b, last, tr_ilg(PTRDIFF_TO_INT(last - b)), trlink); + last = a, limit = tr_ilg(PTRDIFF_TO_INT(a - first)); } else if(1 < (last - b)) { - first = b, limit = tr_ilg(last - b); + first = b, limit = tr_ilg(PTRDIFF_TO_INT(last - b)); } else { STACK_POP5(ISAd, first, last, limit, trlink); } } else { if(1 < (last - b)) { - STACK_PUSH5(ISAd, first, a, tr_ilg(a - first), trlink); - first = b, limit = tr_ilg(last - b); + STACK_PUSH5(ISAd, first, a, tr_ilg(PTRDIFF_TO_INT(a - first)), trlink); + first = b, limit = tr_ilg(PTRDIFF_TO_INT(last - b)); } else if(1 < (a - first)) { - last = a, limit = tr_ilg(a - first); + last = a, limit = tr_ilg(PTRDIFF_TO_INT(a - first)); } else { STACK_POP5(ISAd, first, last, limit, trlink); } @@ -51103,26 +52666,26 @@ tr_introsort(int *ISA, const int *ISAd, /* tandem repeat copy */ a = stack[--ssize].b, b = stack[ssize].c; if(stack[ssize].d == 0) { - tr_copy(ISA, SA, first, a, b, last, ISAd - ISA); + tr_copy(ISA, SA, first, a, b, last, PTRDIFF_TO_INT(ISAd - ISA)); } else { if(0 <= trlink) { stack[trlink].d = -1; } - tr_partialcopy(ISA, SA, first, a, b, last, ISAd - ISA); + tr_partialcopy(ISA, SA, first, a, b, last, PTRDIFF_TO_INT(ISAd - ISA)); } STACK_POP5(ISAd, first, last, limit, trlink); } else { /* sorted partition */ if(0 <= *first) { a = first; - do { ISA[*a] = a - SA; } while((++a < last) && (0 <= *a)); + do { ISA[*a] = PTRDIFF_TO_INT(a - SA); } while((++a < last) && (0 <= *a)); first = a; } if(first < last) { a = first; do { *a = ~*a; } while(*++a < 0); - next = (ISA[*a] != ISAd[*a]) ? tr_ilg(a - first + 1) : -1; - if(++a < last) { for(b = first, v = a - SA - 1; b < a; ++b) { ISA[*b] = v; } } + next = (ISA[*a] != ISAd[*a]) ? tr_ilg(PTRDIFF_TO_INT(a - first + 1)) : -1; + if(++a < last) { for(b = first, v = PTRDIFF_TO_INT(a - SA - 1); b < a; ++b) { ISA[*b] = v; } } /* push */ - if(trbudget_check(budget, a - first)) { + if(trbudget_check(budget, PTRDIFF_TO_INT(a - first))) { if((a - first) <= (last - a)) { STACK_PUSH5(ISAd, a, last, -3, trlink); ISAd += incr, last = a, limit = next; @@ -51156,7 +52719,7 @@ tr_introsort(int *ISA, const int *ISAd, } if(limit-- == 0) { - tr_heapsort(ISAd, first, last - first); + tr_heapsort(ISAd, first, PTRDIFF_TO_INT(last - first)); for(a = last - 1; first < a; a = b) { for(x = ISAd[*a], b = a - 1; (first <= b) && (ISAd[*b] == x); --b) { *b = ~*b; } } @@ -51172,14 +52735,14 @@ tr_introsort(int *ISA, const int *ISAd, /* partition */ tr_partition(ISAd, first, first + 1, last, &a, &b, v); if((last - first) != (b - a)) { - next = (ISA[*a] != v) ? tr_ilg(b - a) : -1; + next = (ISA[*a] != v) ? tr_ilg(PTRDIFF_TO_INT(b - a)) : -1; /* update ranks */ - for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; } - if(b < last) { for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } } + for(c = first, v = PTRDIFF_TO_INT(a - SA - 1); c < a; ++c) { ISA[*c] = v; } + if(b < last) { for(c = a, v = PTRDIFF_TO_INT(b - SA - 1); c < b; ++c) { ISA[*c] = v; } } /* push */ - if((1 < (b - a)) && (trbudget_check(budget, b - a))) { + if((1 < (b - a)) && (trbudget_check(budget, PTRDIFF_TO_INT(b - a)))) { if((a - first) <= (last - b)) { if((last - b) <= (b - a)) { if(1 < (a - first)) { @@ -51256,8 +52819,8 @@ tr_introsort(int *ISA, const int *ISAd, } } } else { - if(trbudget_check(budget, last - first)) { - limit = tr_ilg(last - first), ISAd += incr; + if(trbudget_check(budget, PTRDIFF_TO_INT(last - first))) { + limit = tr_ilg(PTRDIFF_TO_INT(last - first)), ISAd += incr; } else { if(0 <= trlink) { stack[trlink].d = -1; } STACK_POP5(ISAd, first, last, limit, trlink); @@ -51295,7 +52858,7 @@ trsort(int *ISA, int *SA, int n, int depth) { budget.count = 0; tr_introsort(ISA, ISAd, SA, first, last, &budget); if(budget.count != 0) { unsorted += budget.count; } - else { skip = first - last; } + else { skip = PTRDIFF_TO_INT(first - last); } } else if((last - first) == 1) { skip = -1; } @@ -51509,7 +53072,7 @@ construct_SA(const unsigned char *T, int *SA, c0 = T[--s]; if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { - if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } + if(0 <= c2) { BUCKET_B(c2, c1) = PTRDIFF_TO_INT(k - SA); } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); assert(k != NULL); @@ -51533,7 +53096,7 @@ construct_SA(const unsigned char *T, int *SA, c0 = T[--s]; if((s == 0) || (T[s - 1] < c0)) { s = ~s; } if(c0 != c2) { - BUCKET_A(c2) = k - SA; + BUCKET_A(c2) = PTRDIFF_TO_INT(k - SA); k = SA + BUCKET_A(c2 = c0); } assert(i < k); @@ -51573,7 +53136,7 @@ construct_BWT(const unsigned char *T, int *SA, *j = ~((int)c0); if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { - if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } + if(0 <= c2) { BUCKET_B(c2, c1) = PTRDIFF_TO_INT(k - SA); } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); assert(k != NULL); @@ -51601,7 +53164,7 @@ construct_BWT(const unsigned char *T, int *SA, *i = c0; if((0 < s) && (T[s - 1] < c0)) { s = ~((int)T[s - 1]); } if(c0 != c2) { - BUCKET_A(c2) = k - SA; + BUCKET_A(c2) = PTRDIFF_TO_INT(k - SA); k = SA + BUCKET_A(c2 = c0); } assert(i < k); @@ -51613,7 +53176,7 @@ construct_BWT(const unsigned char *T, int *SA, } } - return orig - SA; + return PTRDIFF_TO_INT(orig - SA); } /* Constructs the burrows-wheeler transformed string directly @@ -51651,13 +53214,13 @@ construct_BWT_indexes(const unsigned char *T, int *SA, assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); - if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = j - SA; + if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = PTRDIFF_TO_INT(j - SA); c0 = T[--s]; *j = ~((int)c0); if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { - if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; } + if(0 <= c2) { BUCKET_B(c2, c1) = PTRDIFF_TO_INT(k - SA); } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); assert(k != NULL); @@ -51677,7 +53240,7 @@ construct_BWT_indexes(const unsigned char *T, int *SA, the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); if (T[n - 2] < c2) { - if (((n - 1) & mod) == 0) indexes[(n - 1) / (mod + 1) - 1] = k - SA; + if (((n - 1) & mod) == 0) indexes[(n - 1) / (mod + 1) - 1] = PTRDIFF_TO_INT(k - SA); *k++ = ~((int)T[n - 2]); } else { @@ -51689,17 +53252,17 @@ construct_BWT_indexes(const unsigned char *T, int *SA, if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); - if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = i - SA; + if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = PTRDIFF_TO_INT(i - SA); c0 = T[--s]; *i = c0; if(c0 != c2) { - BUCKET_A(c2) = k - SA; + BUCKET_A(c2) = PTRDIFF_TO_INT(k - SA); k = SA + BUCKET_A(c2 = c0); } assert(i < k); if((0 < s) && (T[s - 1] < c0)) { - if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = k - SA; + if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = PTRDIFF_TO_INT(k - SA); *k++ = ~((int)T[s - 1]); } else *k++ = s; @@ -51710,7 +53273,7 @@ construct_BWT_indexes(const unsigned char *T, int *SA, } } - return orig - SA; + return PTRDIFF_TO_INT(orig - SA); } @@ -51839,38 +53402,30 @@ divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * /*-************************************* * Console display +* +* Captures the `displayLevel` variable in the local scope. ***************************************/ -#ifndef LOCALDISPLAYLEVEL -static int g_displayLevel = 0; -#endif #undef DISPLAY #define DISPLAY(...) \ { \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ } -#undef LOCALDISPLAYLEVEL -#define LOCALDISPLAYLEVEL(displayLevel, l, ...) \ +#undef DISPLAYLEVEL +#define DISPLAYLEVEL(l, ...) \ if (displayLevel >= l) { \ DISPLAY(__VA_ARGS__); \ } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */ -#undef DISPLAYLEVEL -#define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__) -#ifndef LOCALDISPLAYUPDATE -static const clock_t g_refreshRate = CLOCKS_PER_SEC * 15 / 100; -static clock_t g_time = 0; -#endif -#undef LOCALDISPLAYUPDATE -#define LOCALDISPLAYUPDATE(displayLevel, l, ...) \ +#undef DISPLAYUPDATE +#define DISPLAYUPDATE(lastUpdateTime, l, ...) \ if (displayLevel >= l) { \ - if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) { \ - g_time = clock(); \ + const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100; \ + if ((clock() - lastUpdateTime > refreshRate) || (displayLevel >= 4)) { \ + lastUpdateTime = clock(); \ DISPLAY(__VA_ARGS__); \ } \ } -#undef DISPLAYUPDATE -#define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__) /*-************************************* @@ -51926,6 +53481,7 @@ typedef struct { unsigned d; unsigned f; FASTCOVER_accel_t accelParams; + int displayLevel; } FASTCOVER_ctx_t; @@ -52104,7 +53660,8 @@ FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx, const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples, unsigned d, double splitPoint, unsigned f, - FASTCOVER_accel_t accelParams) + FASTCOVER_accel_t accelParams, + int displayLevel) { const BYTE* const samples = (const BYTE*)samplesBuffer; const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples); @@ -52113,9 +53670,11 @@ FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx, const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples; const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize; const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize; + const size_t readLength = MAX(d, sizeof(U64)); + ctx->displayLevel = displayLevel; /* Checks */ - if (totalSamplesSize < MAX(d, sizeof(U64)) || + if (totalSamplesSize < readLength || totalSamplesSize >= (size_t)FASTCOVER_MAX_SAMPLES_SIZE) { DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n", (unsigned)(totalSamplesSize >> 20), (FASTCOVER_MAX_SAMPLES_SIZE >> 20)); @@ -52134,6 +53693,12 @@ FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx, return ERROR(srcSize_wrong); } + /* Check the training set can hold at least one dmer, otherwise nbDmers underflows below */ + if (trainingSamplesSize < readLength) { + DISPLAYLEVEL(1, "Total training samples size is %u and is invalid.\n", (unsigned)trainingSamplesSize); + return ERROR(srcSize_wrong); + } + /* Zero the context */ memset(ctx, 0, sizeof(*ctx)); DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples, @@ -52146,7 +53711,7 @@ FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx, ctx->nbSamples = nbSamples; ctx->nbTrainSamples = nbTrainSamples; ctx->nbTestSamples = nbTestSamples; - ctx->nbDmers = trainingSamplesSize - MAX(d, sizeof(U64)) + 1; + ctx->nbDmers = trainingSamplesSize - readLength + 1; ctx->d = d; ctx->f = f; ctx->accelParams = accelParams; @@ -52199,7 +53764,9 @@ FASTCOVER_buildDictionary(const FASTCOVER_ctx_t* ctx, const COVER_epoch_info_t epochs = COVER_computeEpochs( (U32)dictBufferCapacity, (U32)ctx->nbDmers, parameters.k, 1); const size_t maxZeroScoreRun = 10; + const int displayLevel = ctx->displayLevel; size_t zeroScoreRun = 0; + clock_t lastUpdateTime = 0; size_t epoch; DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n", (U32)epochs.num, (U32)epochs.size); @@ -52237,6 +53804,7 @@ FASTCOVER_buildDictionary(const FASTCOVER_ctx_t* ctx, tail -= segmentSize; memcpy(dict + tail, ctx->samples + segment.begin, segmentSize); DISPLAYUPDATE( + lastUpdateTime, 2, "\r%u%% ", (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity)); } @@ -52274,6 +53842,7 @@ static void FASTCOVER_tryParameters(void* opaque) BYTE *const dict = (BYTE*)malloc(dictBufferCapacity); COVER_dictSelection_t selection = COVER_dictSelectionError(ERROR(GENERIC)); U32* freqs = (U32*) malloc(((U64)1 << ctx->f) * sizeof(U32)); + const int displayLevel = ctx->displayLevel; if (!segmentFreqs || !dict || !freqs) { DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n"); goto _cleanup; @@ -52345,8 +53914,7 @@ ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity, FASTCOVER_ctx_t ctx; ZDICT_cover_params_t coverParams; FASTCOVER_accel_t accelParams; - /* Initialize global data */ - g_displayLevel = (int)parameters.zParams.notificationLevel; + const int displayLevel = (int)parameters.zParams.notificationLevel; /* Assign splitPoint and f if not provided */ parameters.splitPoint = 1.0; parameters.f = parameters.f == 0 ? DEFAULT_F : parameters.f; @@ -52375,13 +53943,13 @@ ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity, { size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, coverParams.d, parameters.splitPoint, parameters.f, - accelParams); + accelParams, displayLevel); if (ZSTD_isError(initVal)) { DISPLAYLEVEL(1, "Failed to initialize context\n"); return initVal; } } - COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, g_displayLevel); + COVER_warnOnSmallCorpus(dictBufferCapacity, ctx.nbDmers, displayLevel); /* Build the dictionary */ DISPLAYLEVEL(2, "Building dictionary\n"); { @@ -52436,25 +54004,26 @@ ZDICT_optimizeTrainFromBuffer_fastCover( COVER_best_t best; POOL_ctx *pool = NULL; int warned = 0; + clock_t lastUpdateTime = 0; /* Checks */ if (splitPoint <= 0 || splitPoint > 1) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect splitPoint\n"); + DISPLAYLEVEL(1, "Incorrect splitPoint\n"); return ERROR(parameter_outOfBound); } if (accel == 0 || accel > FASTCOVER_MAX_ACCEL) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect accel\n"); + DISPLAYLEVEL(1, "Incorrect accel\n"); return ERROR(parameter_outOfBound); } if (kMinK < kMaxD || kMaxK < kMinK) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect k\n"); + DISPLAYLEVEL(1, "Incorrect k\n"); return ERROR(parameter_outOfBound); } if (nbSamples == 0) { - LOCALDISPLAYLEVEL(displayLevel, 1, "FASTCOVER must have at least one input file\n"); + DISPLAYLEVEL(1, "FASTCOVER must have at least one input file\n"); return ERROR(srcSize_wrong); } if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) { - LOCALDISPLAYLEVEL(displayLevel, 1, "dictBufferCapacity must be at least %u\n", + DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n", ZDICT_DICTSIZE_MIN); return ERROR(dstSize_tooSmall); } @@ -52469,19 +54038,18 @@ ZDICT_optimizeTrainFromBuffer_fastCover( memset(&coverParams, 0 , sizeof(coverParams)); FASTCOVER_convertToCoverParams(*parameters, &coverParams); accelParams = FASTCOVER_defaultAccelParameters[accel]; - /* Turn down global display level to clean up display at level 2 and below */ - g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1; /* Loop through d first because each new value needs a new context */ - LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n", - kIterations); + DISPLAYLEVEL(2, "Trying %u different sets of parameters\n", kIterations); for (d = kMinD; d <= kMaxD; d += 2) { /* Initialize the context for this value of d */ FASTCOVER_ctx_t ctx; - LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d); + DISPLAYLEVEL(3, "d=%u\n", d); { - size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, f, accelParams); + /* Turn down global display level to clean up display at level 2 and below */ + const int childDisplayLevel = displayLevel == 0 ? 0 : displayLevel - 1; + size_t const initVal = FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, f, accelParams, childDisplayLevel); if (ZSTD_isError(initVal)) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n"); + DISPLAYLEVEL(1, "Failed to initialize context\n"); COVER_best_destroy(&best); POOL_free(pool); return initVal; @@ -52496,9 +54064,9 @@ ZDICT_optimizeTrainFromBuffer_fastCover( /* Prepare the arguments */ FASTCOVER_tryParameters_data_t *data = (FASTCOVER_tryParameters_data_t *)malloc( sizeof(FASTCOVER_tryParameters_data_t)); - LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k); + DISPLAYLEVEL(3, "k=%u\n", k); if (!data) { - LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n"); + DISPLAYLEVEL(1, "Failed to allocate parameters\n"); COVER_best_destroy(&best); FASTCOVER_ctx_destroy(&ctx); POOL_free(pool); @@ -52513,7 +54081,7 @@ ZDICT_optimizeTrainFromBuffer_fastCover( data->parameters.splitPoint = splitPoint; data->parameters.steps = kSteps; data->parameters.shrinkDict = shrinkDict; - data->parameters.zParams.notificationLevel = (unsigned)g_displayLevel; + data->parameters.zParams.notificationLevel = (unsigned)ctx.displayLevel; /* Check the parameters */ if (!FASTCOVER_checkParameters(data->parameters, dictBufferCapacity, data->ctx->f, accel)) { @@ -52529,14 +54097,15 @@ ZDICT_optimizeTrainFromBuffer_fastCover( FASTCOVER_tryParameters(data); } /* Print status */ - LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ", - (unsigned)((iteration * 100) / kIterations)); + DISPLAYUPDATE(lastUpdateTime, + 2, "\r%u%% ", + (unsigned)((iteration * 100) / kIterations)); ++iteration; } COVER_best_wait(&best); FASTCOVER_ctx_destroy(&ctx); } - LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", ""); + DISPLAYLEVEL(2, "\r%79s\r", ""); /* Fill the output buffer and parameters with output of the best parameters */ { const size_t dictSize = best.dictSize; @@ -52726,7 +54295,7 @@ static void ZDICT_initDictItem(dictItem* d) #define MINMATCHLENGTH 7 /* heuristic determined experimentally */ static dictItem ZDICT_analyzePos( BYTE* doneMarks, - const int* suffix, U32 start, + const unsigned* suffix, U32 start, const void* buffer, U32 minRatio, U32 notificationLevel) { U32 lengthList[LLIMIT] = {0}; @@ -52851,8 +54420,10 @@ static dictItem ZDICT_analyzePos( for (i=(int)(maxLength-2); i>=0; i--) cumulLength[i] = cumulLength[i+1] + lengthList[i]; - for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break; - maxLength = i; + { unsigned u; + for (u=LLIMIT-1; u>=MINMATCHLENGTH; u--) if (cumulLength[u]>=minRatio) break; + maxLength = u; + } /* reduce maxLength in case of final into repetitive data */ { U32 l = (U32)maxLength; @@ -52864,8 +54435,10 @@ static dictItem ZDICT_analyzePos( /* calculate savings */ savings[5] = 0; - for (i=MINMATCHLENGTH; i<=(int)maxLength; i++) - savings[i] = savings[i-1] + (lengthList[i] * (i-3)); + { unsigned u; + for (u=MINMATCHLENGTH; u<=maxLength; u++) + savings[u] = savings[u-1] + (lengthList[u] * (u-3)); + } DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f) \n", (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / (double)maxLength); @@ -52941,11 +54514,11 @@ static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) { /* overlap, existing < new */ /* append */ - int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length); + int const addedLength = (int)eltEnd - (int)(table[u].pos + table[u].length); /* note: can be negative */ table[u].savings += elt.length / 8; /* rough approx bonus */ if (addedLength > 0) { /* otherwise, elt fully included into existing */ - table[u].length += addedLength; - table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */ + table[u].length += (unsigned)addedLength; + table[u].savings += elt.savings * (unsigned)addedLength / elt.length; /* rough approx */ } /* sort : improve rank */ elt = table[u]; @@ -52957,7 +54530,7 @@ static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) { if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) { - size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 ); + size_t const addedLength = MAX( elt.length - table[u].length , 1 ); table[u].pos = elt.pos; table[u].savings += (U32)(elt.savings * addedLength / elt.length); table[u].length = MIN(elt.length, table[u].length + 1); @@ -53025,8 +54598,8 @@ static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize, const size_t* fileSizes, unsigned nbFiles, unsigned minRatio, U32 notificationLevel) { - int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0)); - int* const suffix = suffix0+1; + unsigned* const suffix0 = (unsigned*)malloc((bufferSize+2)*sizeof(*suffix0)); + unsigned* const suffix = suffix0+1; U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix)); BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks)); /* +16 for overflow security */ U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos)); @@ -53061,11 +54634,11 @@ static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize, /* sort */ DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20)); - { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0); + { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, (int*)suffix, (int)bufferSize, 0); if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; } } - suffix[bufferSize] = (int)bufferSize; /* leads into noise */ - suffix0[0] = (int)bufferSize; /* leads into noise */ + suffix[bufferSize] = (unsigned)bufferSize; /* leads into noise */ + suffix0[0] = (unsigned)bufferSize; /* leads into noise */ /* build reverse suffix sort */ { size_t pos; for (pos=0; pos < bufferSize; pos++) diff --git a/zstd/zstd.h b/zstd/zstd.h index b8c0644a..00b516f6 100644 --- a/zstd/zstd.h +++ b/zstd/zstd.h @@ -110,8 +110,8 @@ extern "C" { /*------ Version ------*/ #define ZSTD_VERSION_MAJOR 1 -#define ZSTD_VERSION_MINOR 5 -#define ZSTD_VERSION_RELEASE 7 +#define ZSTD_VERSION_MINOR 6 +#define ZSTD_VERSION_RELEASE 0 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) /*! ZSTD_versionNumber() : @@ -176,30 +176,30 @@ ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, /*====== Decompression helper functions ======*/ -/*! ZSTD_getFrameContentSize() : requires v1.3.0+ - * `src` should point to the start of a ZSTD encoded frame. - * `srcSize` must be at least as large as the frame header. - * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough. - * @return : - decompressed size of `src` frame content, if known - * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined - * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) - * note 1 : a 0 return value means the frame is valid but "empty". - * When invoking this method on a skippable frame, it will return 0. - * note 2 : decompressed size is an optional field, it may not be present (typically in streaming mode). - * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size. - * In which case, it's necessary to use streaming mode to decompress data. - * Optionally, application can rely on some implicit limit, - * as ZSTD_decompress() only needs an upper bound of decompressed size. - * (For example, data could be necessarily cut into blocks <= 16 KB). - * note 3 : decompressed size is always present when compression is completed using single-pass functions, - * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict(). - * note 4 : decompressed size can be very large (64-bits value), - * potentially larger than what local system can handle as a single memory segment. - * In which case, it's necessary to use streaming mode to decompress data. - * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified. - * Always ensure return value fits within application's authorized limits. - * Each application can set its own limits. - * note 6 : This function replaces ZSTD_getDecompressedSize() */ +/*! @brief Returns the decompressed content size stored in a ZSTD frame header. + * + * @since v1.3.0 + * + * @param src Pointer to the beginning of a ZSTD encoded frame. + * @param srcSize Size of the buffer pointed to by @p src. It must be at least as large as the frame header. + * Any value greater than or equal to `ZSTD_frameHeaderSize_max` is sufficient. + * @return The decompressed size in bytes when the value is available in the frame header. + * @retval ZSTD_CONTENTSIZE_UNKNOWN The frame does not encode a decompressed size (typical for streaming). + * @retval ZSTD_CONTENTSIZE_ERROR An error occurred (e.g. invalid magic number, @p srcSize too small). + * + * @note The return value is not compatible with `ZSTD_isError()`. + * @note A return value of 0 denotes a valid but empty frame. Skippable frames also report 0. + * @note The decompressed size field is optional. When it is absent (the function returns @c ZSTD_CONTENTSIZE_UNKNOWN), + * the caller must rely on streaming decompression or an application-specific upper bound. `ZSTD_decompress()` + * only requires an upper bound, so applications may enforce their own block limits (for example 16 KB). + * @note The decompressed size is guaranteed to be present when compression was performed with single-pass APIs such as + * `ZSTD_compress()`, `ZSTD_compressCCtx()`, `ZSTD_compress_usingDict()`, or `ZSTD_compress_usingCDict()`. + * @note The decompressed size is a 64-bit value and may exceed the addressable space of the system. Use streaming + * decompression when the value is too large to materialize in contiguous memory. + * @warning When processing untrusted input, validate the returned size against the application's limits; attackers may + * forge an arbitrarily large value. + * @note This function replaces `ZSTD_getDecompressedSize()`. + */ #define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1) #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); @@ -226,6 +226,28 @@ ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t * which is always equal to its content size + 8 bytes for headers. */ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); +typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; +#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ +typedef struct { + unsigned long long frameContentSize; /**< if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ + unsigned long long windowSize; /**< can be very large, up to <= frameContentSize */ + unsigned blockSizeMax; + ZSTD_FrameType_e frameType; /**< if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ + unsigned headerSize; + unsigned dictID; /**< for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ + unsigned checksumFlag; + unsigned _reserved1; + unsigned _reserved2; +} ZSTD_FrameHeader; +#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ + +/*! ZSTD_getFrameHeader() : Requires v1.6.0+ + * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. + * @return : 0 => header is complete, `zfhPtr` is correctly filled, + * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, + * or an error code, which can be tested using ZSTD_isError() */ +ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); + /*====== Compression helper functions ======*/ @@ -308,6 +330,9 @@ ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer * * Same as ZSTD_decompress(), * requires an allocated ZSTD_DCtx. * Compatible with sticky parameters (see below). + * The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). + * See ZSTD_DCtx_refPrefix() for the effect on a referenced prefix. */ ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, @@ -597,6 +622,7 @@ typedef enum { * - The session : will stop compressing current frame, and make CCtx ready to start a new one. * Useful after an error, or to interrupt any ongoing compression. * Any internal data not yet flushed is cancelled. + * With nbWorkers >= 1, it waits for the jobs already started to complete. * Compression parameters and dictionary remain unchanged. * They will be used to compress next frame. * Resetting session never fails. @@ -688,7 +714,11 @@ ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param /*! ZSTD_DCtx_reset() : * Return a DCtx to clean state. * Session and parameters can be reset jointly or separately. - * Parameters can only be reset when no active frame is being decompressed. + * ZSTD_reset_parameters can only be used when no frame is being decompressed; + * otherwise it returns ZSTD_error_stage_wrong without resetting the parameters. + * ZSTD_reset_session_and_parameters also abandons any active frame. + * A successful parameter reset discards any referenced prefix or dictionary. + * See ZSTD_DCtx_refPrefix() for the effect of a session-only reset on a prefix. * @return : 0, or an error code, which can be tested with ZSTD_isError() */ ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset); @@ -942,8 +972,11 @@ ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); * Note: when an operation returns with an error code, the @zds state may be left in undefined state. * It's UB to invoke `ZSTD_decompressStream()` on such a state. * In order to re-use such a state, it must be first reset, - * which can be done explicitly (`ZSTD_DCtx_reset()`), - * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) + * which can be done explicitly (`ZSTD_DCtx_reset(zds, ZSTD_reset_session_only)`), + * or is implied for operations starting some new decompression job + * (`ZSTD_initDStream()`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`, `ZSTD_decompress_usingDDict()`). + * The single-shot functions also leave the session clean: + * streaming can start a new frame afterwards without an explicit reset. */ ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); @@ -972,7 +1005,9 @@ ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx, * Dictionary must be identical to the one used during compression. * Note : This function loads the dictionary, resulting in significant startup delay. * It's intended for a dictionary used only once. - * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */ + * Note : When `dict == NULL || dictSize < 8` no dictionary is used. + * Note : The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). */ ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, @@ -1022,6 +1057,13 @@ typedef struct ZSTD_DDict_s ZSTD_DDict; * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */ ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize); +/*! ZSTD_createDDict_byReference() : Requires v1.6.0+ + * Create a digested dictionary, ready to start decompression operation without startup delay. + * Dictionary content is referenced, and therefore stays in dictBuffer. + * It is important that dictBuffer outlives DDict, + * it must remain read accessible throughout the lifetime of DDict */ +ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); + /*! ZSTD_freeDDict() : * Function frees memory allocated with ZSTD_createDDict() * If a NULL pointer is passed, no operation is performed. */ @@ -1029,7 +1071,10 @@ ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict); /*! ZSTD_decompress_usingDDict() : * Decompression using a digested Dictionary. - * Recommended when same dictionary is used multiple times. */ + * Recommended when same dictionary is used multiple times. + * Uses the supplied DDict, regardless of dictionaries referenced in dctx. + * The streaming session of @dctx is reset first, as with + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only). */ ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, @@ -1107,6 +1152,23 @@ ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize); */ ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); +typedef enum { + ZSTD_dct_auto = 0, /**< dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ + ZSTD_dct_rawContent = 1, /**< ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ + ZSTD_dct_fullDict = 2 /**< refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ +} ZSTD_dictContentType_e; + +typedef enum { + ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ + ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ +} ZSTD_dictLoadMethod_e; + +/*! ZSTD_CCtx_loadDictionary_advanced() : Requires v1.6.0+ + * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ +ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + /*! ZSTD_CCtx_refCDict() : Requires v1.4.0+ * Reference a prepared dictionary, to be used for all future compressed frames. * Note that compression parameters are enforced from within CDict, @@ -1150,6 +1212,8 @@ ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, * @result : 0, or an error code (which can be tested with ZSTD_isError()). * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary, * meaning "return to no-dictionary mode". + * Loading any dictionary also discards the multiple-DDict reference table, + * without disabling ZSTD_d_refMultipleDDicts. * Note 1 : Loading a dictionary involves building tables, * which has a non-negligible impact on CPU usage and latency. * It's recommended to "load once, use many times", to amortize the cost @@ -1160,15 +1224,29 @@ ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, */ ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); +/*! ZSTD_DCtx_loadDictionary_advanced() : Requires v1.6.0+ + * Same as ZSTD_DCtx_loadDictionary(), + * but gives direct control over + * how to load the dictionary (by copy ? by reference ?) + * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ +ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); + /*! ZSTD_DCtx_refDDict() : Requires v1.4.0+ * Reference a prepared dictionary, to be used to decompress next frames. - * The dictionary remains active for decompression of future frames using same DCtx. + * In single-DDict mode, the dictionary remains active for decompression of + * future frames using the same DCtx. * * If called with ZSTD_d_refMultipleDDicts enabled, repeated calls of this function * will store the DDict references in a table, and the DDict used for decompression * will be determined at decompression time, as per the dict ID in the frame. - * The memory for the table is allocated on the first call to refDDict, and can be - * freed with ZSTD_freeDCtx(). + * The memory for the table is allocated on the first call to refDDict. + * The table is freed by ZSTD_DCtx_refDDict(dctx, NULL), by ZSTD_DCtx_reset() + * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters, by any + * ZSTD_DCtx_loadDictionary() or ZSTD_DCtx_refPrefix() call, by disabling + * multiple-DDict mode, and by ZSTD_freeDCtx(). + * Disabling multiple-DDict mode releases all dictionary references from the set; + * no dictionary from the set is retained for subsequent decompression. + * Referencing a DDict invalidates any previously loaded dictionary or prefix. * * If called with ZSTD_d_refMultipleDDicts disabled (the default), only one dictionary * will be managed, and referencing a dictionary effectively "discards" any previous one. @@ -1180,18 +1258,40 @@ ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, s ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); /*! ZSTD_DCtx_refPrefix() : Requires v1.4.0+ - * Reference a prefix (single-usage dictionary) to decompress next frame. + * Reference a prefix (single-usage dictionary) for decompression. * This is the reverse operation of ZSTD_CCtx_refPrefix(), * and must use the same prefix as the one used during compression. - * Prefix is **only used once**. Reference is discarded at end of frame. - * End of frame is reached when ZSTD_decompressStream() returns 0. + * The prefix is **only used once**: + * - ZSTD_decompressDCtx() uses it for exactly one call, including all frames + * in concatenated input. The call consumes the prefix even if the input + * is empty, contains only skippable frames, or produces an error. + * - ZSTD_decompressStream() uses it until the first frame is completely + * decoded and flushed, as indicated by a return value of 0. This includes + * empty and skippable frames, even though they produce no output. + * The explicit-dictionary functions ZSTD_decompress_usingDict() and + * ZSTD_decompress_usingDDict() use their dictionary argument instead and + * do not consume the prefix configured on the DCtx. + * + * ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) preserves an unused prefix + * if streaming decompression has not started. Once streaming has started, + * even with an incomplete header, a session-only reset abandons the frame + * and discards the prefix. After a streaming error the DCtx may be in an + * undefined state and must be reset before streaming can resume. Errors + * returned before streaming starts may leave an unused prefix installed. + * To unconditionally discard it, use ZSTD_reset_session_and_parameters, + * or ZSTD_reset_parameters when no frame is active. The latter can fail + * with ZSTD_error_stage_wrong during decompression. * @result : 0, or an error code (which can be tested with ZSTD_isError()). - * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary + * Note 1 : Adding any prefix (including NULL or a zero-sized prefix) invalidates + * any previously set prefix or dictionary, + * including the multiple-DDict reference table. + * Successfully loading or referencing another dictionary, or calling + * ZSTD_initDStream(), also discards the prefix. * Note 2 : Prefix buffer is referenced. It **must** outlive decompression. - * Prefix buffer must remain unmodified up to the end of frame, - * reached when ZSTD_decompressStream() returns 0. + * It must remain unmodified until the one-shot call returns, the + * streaming frame completes, or the prefix is explicitly discarded. * Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent). - * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section) + * Use ZSTD_DCtx_refPrefix_advanced() to alter dictMode (Experimental section) * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost. * A full dictionary is more costly, as it requires building tables. */ @@ -1370,17 +1470,6 @@ typedef struct { ZSTD_frameParameters fParams; } ZSTD_parameters; -typedef enum { - ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */ - ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */ - ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */ -} ZSTD_dictContentType_e; - -typedef enum { - ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */ - ZSTD_dlm_byRef = 1 /**< Reference dictionary content -- the dictionary buffer must outlive its users. */ -} ZSTD_dictLoadMethod_e; - typedef enum { ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */ ZSTD_f_zstd1_magicless = 1 /* Variant of zstd frame format, without initial 4-bytes magic number. @@ -1493,9 +1582,10 @@ ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, * @return : - upper-bound for the decompressed size of all data in all successive frames * - if an error occurred: ZSTD_CONTENTSIZE_ERROR * - * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame. + * note 1 : an error can occur if `src` contains an invalid or incorrectly formatted frame, + * or the bound exceeds the largest returnable value, ZSTD_CONTENTSIZE_ERROR - 1. * note 2 : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`. - * in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. + * When this exact size is representable, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value. * note 3 : when the decompressed size field isn't available, the upper-bound for that frame is calculated by: * upper-bound = # blocks * min(128 KB, Window_Size) */ @@ -1507,27 +1597,6 @@ ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size * or an error code (if srcSize is too small) */ ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); -typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e; -#define ZSTD_frameType_e ZSTD_FrameType_e /* old name */ -typedef struct { - unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */ - unsigned long long windowSize; /* can be very large, up to <= frameContentSize */ - unsigned blockSizeMax; - ZSTD_FrameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ - unsigned headerSize; - unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ - unsigned checksumFlag; - unsigned _reserved1; - unsigned _reserved2; -} ZSTD_FrameHeader; -#define ZSTD_frameHeader ZSTD_FrameHeader /* old name */ - -/*! ZSTD_getFrameHeader() : - * decode Frame Header into `zfhPtr`, or requires larger `srcSize`. - * @return : 0 => header is complete, `zfhPtr` is correctly filled, - * >0 => `srcSize` is too small, @return value is the wanted `srcSize` amount, `zfhPtr` is not filled, - * or an error code, which can be tested using ZSTD_isError() */ -ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize); /*! ZSTD_getFrameHeader_advanced() : * same as ZSTD_getFrameHeader(), * with added capability to select a format (like ZSTD_f_zstd1_magicless) */ @@ -1699,6 +1768,8 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * - @litBufCapacity is the size of the underlying buffer into which literals are written, starting at address @literals. * @litBufCapacity must be at least 8 bytes larger than @litSize. * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. + * - Each block must regenerate at most ZSTD_BLOCKSIZE_MAX bytes, or less with a smaller window or ZSTD_c_maxBlockSize. + * A larger block will generate an error. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t @@ -1813,6 +1884,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, si /*! ZSTD_estimate?DictSize() : * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict(). * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced(). + * These estimates return an error code if dictSize is too large. + * Check the result with ZSTD_isError(). * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller. */ ZSTDLIB_STATIC_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel); @@ -1836,7 +1909,10 @@ ZSTDLIB_STATIC_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadM * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level * into its associated cParams. * Limitation 1 : currently not compatible with internal dictionary creation, triggered by - * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * ZSTD_CCtx_loadDictionary(), ZSTD_DCtx_loadDictionary(), ZSTD_DCtx_refPrefix(), + * ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict(). + * For one-shot decompression, ZSTD_decompress_usingDict() needs no allocation. + * Otherwise, use ZSTD_initStaticDDict() + ZSTD_DCtx_refDDict(). * Limitation 2 : static cctx currently not compatible with multi-threading. * Limitation 3 : static dctx is incompatible with legacy support. */ @@ -1868,15 +1944,14 @@ ZSTDLIB_STATIC_API const ZSTD_DDict* ZSTD_initStaticDDict( typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size); typedef void (*ZSTD_freeFunction) (void* opaque, void* address); typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem; -static -#ifdef __GNUC__ -__attribute__((__unused__)) -#endif - #if defined(__clang__) && __clang_major__ >= 5 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif +static +#ifdef __GNUC__ +__attribute__((__unused__)) +#endif ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ #if defined(__clang__) && __clang_major__ >= 5 #pragma clang diagnostic pop @@ -1898,9 +1973,10 @@ ZSTDLIB_STATIC_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_ * This can limit resources for applications with multiple threads where each one uses * a threaded compression mode (via ZSTD_c_nbWorkers parameter). * ZSTD_createThreadPool creates a new thread pool with a given number of threads. + * ZSTD_c_nbWorkers does not change the number of threads of such a pool. * Note that the lifetime of such pool must exist while being used. * ZSTD_CCtx_refThreadPool assigns a thread pool to a context (use NULL argument value - * to use an internal thread pool). + * to use an internal thread pool). The context then no longer uses its previous pool. * ZSTD_freeThreadPool frees a thread pool, accepts NULL pointer. */ typedef struct POOL_ctx_s ZSTD_threadPool; @@ -2012,12 +2088,6 @@ size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx, * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize); -/*! ZSTD_CCtx_loadDictionary_advanced() : - * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over - * how to load the dictionary (by copy ? by reference ?) - * and how to interpret it (automatic ? force raw mode ? full mode only ?) */ -ZSTDLIB_STATIC_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); - /*! ZSTD_CCtx_refPrefix_advanced() : * Same as ZSTD_CCtx_refPrefix(), but gives finer control over * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ @@ -2452,13 +2522,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressStream2_simpleArgs ( * Note 3 : Skippable Frame Identifiers are considered valid. */ ZSTDLIB_STATIC_API unsigned ZSTD_isFrame(const void* buffer, size_t size); -/*! ZSTD_createDDict_byReference() : - * Create a digested dictionary, ready to start decompression operation without startup delay. - * Dictionary content is referenced, and therefore stays in dictBuffer. - * It is important that dictBuffer outlives DDict, - * it must remain read accessible throughout the lifetime of DDict */ -ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize); - /*! ZSTD_DCtx_loadDictionary_byReference() : * Same as ZSTD_DCtx_loadDictionary(), * but references `dict` content instead of copying it into `dctx`. @@ -2466,16 +2529,11 @@ ZSTDLIB_STATIC_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuff * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); -/*! ZSTD_DCtx_loadDictionary_advanced() : - * Same as ZSTD_DCtx_loadDictionary(), - * but gives direct control over - * how to load the dictionary (by copy ? by reference ?) - * and how to interpret it (automatic ? force raw mode ? full mode only ?). */ -ZSTDLIB_STATIC_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType); - /*! ZSTD_DCtx_refPrefix_advanced() : * Same as ZSTD_DCtx_refPrefix(), but gives finer control over - * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */ + * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?). + * The prefix has the same single-use lifetime and reset behavior described + * by ZSTD_DCtx_refPrefix(). */ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType); /*! ZSTD_DCtx_setMaxWindowSize() : @@ -2550,7 +2608,22 @@ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParamete * to store references to multiple ZSTD_DDict. That is, multiple calls of ZSTD_refDDict() * using a given ZSTD_DCtx, rather than overwriting the previous DDict reference, will instead * store all references. At decompression time, the appropriate dictID is selected - * from the set of DDicts based on the dictID in the frame. + * from the set of DDicts based on the dictID in each frame. This applies to + * ZSTD_decompressDCtx() and ZSTD_decompressStream(); entry points taking an + * explicit dictionary use that dictionary instead. + * When a set exists, an ordinary Zstandard frame with a nonzero dictionary ID must + * have an exact match in the set; otherwise decompression returns + * ZSTD_error_dictionary_wrong. A frame with dictionary ID 0 (including an omitted + * ID) uses the registered ID-0 DDict if present, or no dictionary otherwise. + * There is no default dictionary in the set, and a lookup does not change the + * dictionary used by another frame. + * Skippable frames do not select a dictionary. Legacy formats are not supported + * by set-based decoding; use a single or explicitly supplied dictionary instead. + * Loading a dictionary or referencing a prefix discards the referenced set, + * without disabling this mode. Referencing a DDict discards any previously + * loaded dictionary or prefix. The two kinds of dictionary storage cannot coexist. + * Disabling this mode discards the entire set. No dictionary from the set is + * retained for subsequent decompression. * * Usage is simply calling ZSTD_refDDict() on multiple dict buffers. * @@ -3030,10 +3103,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const vo ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */ -ZSTD_DEPRECATED("This function will likely be removed in a future release. It is misleading and has very limited utility.") -ZSTDLIB_STATIC_API -size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */ - ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") ZSTDLIB_STATIC_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.") @@ -3090,8 +3159,12 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ as long as the encoder and decoder progress in "lock-step", aka use exactly the same buffer sizes, break contiguity at the same place, etc. - Once buffers are setup, start decompression, with ZSTD_decompressBegin(). + Once buffers are set up and decompression parameters are configured, initialize the decoder with ZSTD_decompressBegin(). If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict(). + One of these initialization functions must be called before the first ZSTD_decompressContinue() call for every frame, + including when reusing a context or after calling ZSTD_DCtx_reset(). + ZSTD_DCtx_reset() does not replace this initialization, and ZSTD_decompressContinue() does not initialize the decoder itself. + After a session reset, an interrupted frame cannot be resumed : initialize the decoder again and restart from the frame's beginning. Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively. ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue(). @@ -3102,7 +3175,7 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ It can also be an error code, which can be tested with ZSTD_isError(). A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero. - Context can then be reset to start a new decompression. + Before decoding another frame, call the appropriate ZSTD_decompressBegin*() function again. Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType(). This information is not required to properly decode a frame. @@ -3123,21 +3196,45 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ ZSTDLIB_STATIC_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */ +/*! ZSTD_decompressBegin() : + * Initialize the bufferless decoder to start a new frame without a dictionary. + * Decompression parameters must be configured before calling this function. + * Call this function, ZSTD_decompressBegin_usingDict(), or ZSTD_decompressBegin_usingDDict() + * before the first ZSTD_decompressContinue() call for each frame, including after ZSTD_DCtx_reset(). + * Use the dictionary-taking variants when the frame requires a dictionary. + */ ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx); ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize); ZSTDLIB_STATIC_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict); ZSTDLIB_STATIC_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx); + +/*! ZSTD_decompressContinue() : + * Decode the next part of a frame initialized with ZSTD_decompressBegin() + * or one of its dictionary-taking variants. This function does not initialize the decoder. + * After finishing a frame or resetting the session, initialize the decoder again + * before calling this function for a new frame. + */ ZSTDLIB_STATIC_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); /* misc */ -ZSTD_DEPRECATED("This function will likely be removed in the next minor release. It is misleading and has very limited utility.") -ZSTDLIB_STATIC_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx); typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e; ZSTDLIB_STATIC_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx); +/*! ZSTD_isDeterministicBuild() : + * Returns 1 if the library is built using standard compilation flags, + * and participates in determinism guarantees with other builds of the + * same version. + * If this function returns 0, it means the library was compiled with + * non-standard compilation flags that change the output of the + * compressor. + * This is mainly used for Zstd's determinism test suite, which is only + * run when this function returns 1. + */ +ZSTDLIB_API int ZSTD_isDeterministicBuild(void); + /* ========================================= */ /** Block level API (DEPRECATED) */