From 68a4a034531df5bf2b895a2ca76c1bf629ee3415 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Apr 2023 06:00:54 +0000 Subject: [PATCH 001/937] Bump github/codeql-action from 2.2.8 to 2.2.9 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.2.8 to 2.2.9. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/67a35a08586135a9573f4327e904ecbf517a882d...04df1262e6247151b5ac09cd2c303ac36ad3f62b) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 8a693fa20..63b76554b 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@67a35a08586135a9573f4327e904ecbf517a882d # tag=v2.2.8 + uses: github/codeql-action/upload-sarif@04df1262e6247151b5ac09cd2c303ac36ad3f62b # tag=v2.2.9 with: sarif_file: results.sarif From da41d1d401fade89b868ec5306b2805460bcd909 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Apr 2023 06:00:58 +0000 Subject: [PATCH 002/937] Bump ossf/scorecard-action from 2.1.2 to 2.1.3 Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.1.2 to 2.1.3. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/e38b1902ae4f44df626f11ba0734b14fb91f8f86...80e868c13c90f172d68d1f4501dee99e2479f7af) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 8a693fa20..a88ec9494 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -32,7 +32,7 @@ jobs: persist-credentials: false - name: "Run analysis" - uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # tag=v2.1.2 + uses: ossf/scorecard-action@80e868c13c90f172d68d1f4501dee99e2479f7af # tag=v2.1.3 with: results_file: results.sarif results_format: sarif From 520843d8ffeaed2f57035b7ec3c24d2dbe2e342f Mon Sep 17 00:00:00 2001 From: Kim Date: Wed, 5 Apr 2023 18:35:58 +1200 Subject: [PATCH 003/937] Add win32 to windows-artifacts.yml --- .github/workflows/windows-artifacts.yml | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 7d73b4b05..ddbeaa756 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -49,3 +49,39 @@ jobs: with: path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-win64.zip name: zstd-${{ github.ref_name }}-win64.zip + + windows-32-artifacts: + # see https://ariya.io/2020/07/on-github-actions-with-msys2 + runs-on: windows-latest + defaults: + run: + shell: msys2 {0} + steps: + - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2 + with: + msystem: MINGW32 + install: make zlib git p7zip mingw-w64-i686-gcc + update: true + - name: display versions + run: | + make -v + cc -v + - name: Building zlib to static link + run: | + git clone --depth 1 --branch v1.2.11 https://github.com/madler/zlib + make -C zlib -f win32/Makefile.gcc libz.a + - name: Building zstd programs + run: | + CPPFLAGS=-I../zlib LDFLAGS=../zlib/libz.a make -j allzstd MOREFLAGS=-static V=1 + - name: Create artifacts + run: | + ./lib/dll/example/build_package.bat + mv bin/ zstd-${{ github.ref_name }}-win32/ + 7z a -tzip -mx9 zstd-${{ github.ref_name }}-win32.zip zstd-${{ github.ref_name }}-win32/ + cd .. + - name: Publish zstd-$VERSION-win32.zip + uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3 + with: + path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-win32.zip + name: zstd-${{ github.ref_name }}-win32.zip From a4fff8e0e81cb2e5ab44816b62b490cea3d4de0d Mon Sep 17 00:00:00 2001 From: Kim Date: Wed, 5 Apr 2023 20:22:29 +1200 Subject: [PATCH 004/937] Change to use strategy.matrix --- .github/workflows/windows-artifacts.yml | 63 +++++++------------------ 1 file changed, 17 insertions(+), 46 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index ddbeaa756..4c15e54c1 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -10,9 +10,15 @@ on: permissions: read-all jobs: - windows-64-artifacts: + windows-artifacts: # see https://ariya.io/2020/07/on-github-actions-with-msys2 runs-on: windows-latest + # see https://github.com/msys2/setup-msys2 + strategy: + matrix: + include: + - { msystem: mingw64, env: x86_64, ziparch: win64 } + - { msystem: mingw32, env: i686, ziparch: win32 } defaults: run: shell: msys2 {0} @@ -20,9 +26,10 @@ jobs: - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2 with: - msystem: MINGW64 - install: make zlib git p7zip mingw-w64-x86_64-gcc + msystem: ${{ matrix.msystem }} + install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc update: true + - name: display versions run: | make -v @@ -33,55 +40,19 @@ jobs: git clone --depth 1 --branch v1.2.11 https://github.com/madler/zlib make -C zlib -f win32/Makefile.gcc libz.a - - name: Building zstd programs in 64-bit mode - run: | - CPPFLAGS=-I../zlib LDFLAGS=../zlib/libz.a make -j allzstd MOREFLAGS=-static V=1 - - - name: Create artifacts - run: | - ./lib/dll/example/build_package.bat - mv bin/ zstd-${{ github.ref_name }}-win64/ - 7z a -tzip -mx9 zstd-${{ github.ref_name }}-win64.zip zstd-${{ github.ref_name }}-win64/ - cd .. - - - name: Publish zstd-$VERSION-win64.zip - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3 - with: - path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-win64.zip - name: zstd-${{ github.ref_name }}-win64.zip - - windows-32-artifacts: - # see https://ariya.io/2020/07/on-github-actions-with-msys2 - runs-on: windows-latest - defaults: - run: - shell: msys2 {0} - steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 - - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2 - with: - msystem: MINGW32 - install: make zlib git p7zip mingw-w64-i686-gcc - update: true - - name: display versions - run: | - make -v - cc -v - - name: Building zlib to static link - run: | - git clone --depth 1 --branch v1.2.11 https://github.com/madler/zlib - make -C zlib -f win32/Makefile.gcc libz.a - name: Building zstd programs run: | CPPFLAGS=-I../zlib LDFLAGS=../zlib/libz.a make -j allzstd MOREFLAGS=-static V=1 + - name: Create artifacts run: | ./lib/dll/example/build_package.bat - mv bin/ zstd-${{ github.ref_name }}-win32/ - 7z a -tzip -mx9 zstd-${{ github.ref_name }}-win32.zip zstd-${{ github.ref_name }}-win32/ + mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + 7z a -tzip -mx9 zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ cd .. - - name: Publish zstd-$VERSION-win32.zip + + - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3 with: - path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-win32.zip - name: zstd-${{ github.ref_name }}-win32.zip + path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip + name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip From c28031df8f1809621407b5bc9c4b3e052872409f Mon Sep 17 00:00:00 2001 From: daniellerozenblit <48103643+daniellerozenblit@users.noreply.github.com> Date: Thu, 6 Apr 2023 13:01:58 -0400 Subject: [PATCH 005/937] Add new line + [no-] to mmap-dict help output (#3601) --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index d2465456b..66952aa82 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -254,7 +254,7 @@ static void usage_advanced(const char* programName) DISPLAYOUT("\n"); DISPLAYOUT(" --format=zstd Compress files to the `.zst` format. [Default]\n"); - DISPLAYOUT(" --mmap-dict Memory-map dictionary file rather than mallocing and loading all at once"); + DISPLAYOUT(" --[no-]mmap-dict Memory-map dictionary file rather than mallocing and loading all at once\n"); #ifdef ZSTD_GZCOMPRESS DISPLAYOUT(" --format=gzip Compress files to the `.gz` format.\n"); #endif From dc88f7b8a0c154a555c3af997e18ec174cf2d3e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Apr 2023 06:00:15 +0000 Subject: [PATCH 006/937] Bump github/codeql-action from 2.2.9 to 2.2.11 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.2.9 to 2.2.11. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/04df1262e6247151b5ac09cd2c303ac36ad3f62b...d186a2a36cc67bfa1b860e6170d37fb9634742c7) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index fe33ed278..9ece5ba51 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@04df1262e6247151b5ac09cd2c303ac36ad3f62b # tag=v2.2.9 + uses: github/codeql-action/upload-sarif@d186a2a36cc67bfa1b860e6170d37fb9634742c7 # tag=v2.2.11 with: sarif_file: results.sarif From d9582a0cb8070c78e8a53fba56b94a41936914aa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Apr 2023 06:00:18 +0000 Subject: [PATCH 007/937] Bump cygwin/cygwin-install-action from 3 to 4 Bumps [cygwin/cygwin-install-action](https://github.com/cygwin/cygwin-install-action) from 3 to 4. - [Release notes](https://github.com/cygwin/cygwin-install-action/releases) - [Commits](https://github.com/cygwin/cygwin-install-action/compare/f5e0f048310c425e84bc789f493a828c6dc80a25...006ad0b0946ca6d0a3ea2d4437677fa767392401) --- updated-dependencies: - dependency-name: cygwin/cygwin-install-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index e0e23f292..940d883a5 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -503,7 +503,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 - - uses: cygwin/cygwin-install-action@f5e0f048310c425e84bc789f493a828c6dc80a25 # tag=master + - uses: cygwin/cygwin-install-action@006ad0b0946ca6d0a3ea2d4437677fa767392401 # tag=master with: platform: x86_64 packages: >- From e72e13ac6c1dc373a0826df0de6f9bf13ee02ee4 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Wed, 12 Apr 2023 16:00:28 -0700 Subject: [PATCH 008/937] [oss-fuzz] Fix simple_round_trip fuzzer with overlapping decompression When `ZSTD_c_maxBlockSize` is set, we weren't computing the decompression margin correctly, leading to `dstSize_tooSmall` errors. Fix that computation. This is just a bug in the fuzzer, not a bug in the library itself. Credit to OSS-Fuzz --- tests/fuzz/simple_round_trip.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/fuzz/simple_round_trip.c b/tests/fuzz/simple_round_trip.c index 8b1231975..0fe463917 100644 --- a/tests/fuzz/simple_round_trip.c +++ b/tests/fuzz/simple_round_trip.c @@ -27,7 +27,7 @@ static ZSTD_CCtx *cctx = NULL; static ZSTD_DCtx *dctx = NULL; -static size_t getDecompressionMargin(void const* compressed, size_t cSize, size_t srcSize, int hasSmallBlocks) +static size_t getDecompressionMargin(void const* compressed, size_t cSize, size_t srcSize, int hasSmallBlocks, int maxBlockSize) { size_t margin = ZSTD_decompressionMargin(compressed, cSize); if (!hasSmallBlocks) { @@ -37,7 +37,12 @@ static size_t getDecompressionMargin(void const* compressed, size_t cSize, size_ ZSTD_frameHeader zfh; size_t marginM; FUZZ_ZASSERT(ZSTD_getFrameHeader(&zfh, compressed, cSize)); - marginM = ZSTD_DECOMPRESSION_MARGIN(srcSize, zfh.blockSizeMax); + if (maxBlockSize == 0) { + maxBlockSize = zfh.blockSizeMax; + } else { + maxBlockSize = MIN(maxBlockSize, (int)zfh.blockSizeMax); + } + marginM = ZSTD_DECOMPRESSION_MARGIN(srcSize, maxBlockSize); if (marginM < margin) margin = marginM; } @@ -52,12 +57,14 @@ static size_t roundTripTest(void *result, size_t resultCapacity, size_t cSize; size_t dSize; int targetCBlockSize = 0; + int maxBlockSize = 0; if (FUZZ_dataProducer_uint32Range(producer, 0, 1)) { size_t const remainingBytes = FUZZ_dataProducer_remainingBytes(producer); FUZZ_setRandomParameters(cctx, srcSize, producer); cSize = ZSTD_compress2(cctx, compressed, compressedCapacity, src, srcSize); FUZZ_ZASSERT(cSize); FUZZ_ZASSERT(ZSTD_CCtx_getParameter(cctx, ZSTD_c_targetCBlockSize, &targetCBlockSize)); + FUZZ_ZASSERT(ZSTD_CCtx_getParameter(cctx, ZSTD_c_maxBlockSize, &maxBlockSize)); // Compress a second time and check for determinism { size_t const cSize0 = cSize; @@ -89,7 +96,7 @@ static size_t roundTripTest(void *result, size_t resultCapacity, FUZZ_ASSERT_MSG(!FUZZ_memcmp(src, result, dSize), "Corruption!"); { - size_t margin = getDecompressionMargin(compressed, cSize, srcSize, targetCBlockSize); + size_t margin = getDecompressionMargin(compressed, cSize, srcSize, targetCBlockSize, maxBlockSize); size_t const outputSize = srcSize + margin; char* const output = (char*)FUZZ_malloc(outputSize); char* const input = output + outputSize - cSize; From 0a794163f4feccf2c408c206f37da5f5b0eab4de Mon Sep 17 00:00:00 2001 From: Michael Redig Date: Thu, 13 Apr 2023 18:43:06 -0500 Subject: [PATCH 009/937] add makefile entry to build fat binary on macos --- Makefile | 9 +++++++++ programs/.gitignore | 2 ++ 2 files changed, 11 insertions(+) diff --git a/Makefile b/Makefile index 3b2e3999f..72a9480aa 100644 --- a/Makefile +++ b/Makefile @@ -197,6 +197,15 @@ uninstall: travis-install: $(MAKE) install PREFIX=~/install_test_dir +.PHONY: clangbuild-darwin-fat +clangbuild-darwin-fat: clean + clang -v + CXX=clang++ CC=clang CFLAGS="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch arm64" $(MAKE) zstd-release + mv programs/zstd programs/zstd_arm64 + CXX=clang++ CC=clang CFLAGS="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch x86_64" $(MAKE) zstd-release + mv programs/zstd programs/zstd_x64 + lipo -create programs/zstd_x64 programs/zstd_arm64 -output programs/zstd + .PHONY: gcc5build gcc6build gcc7build clangbuild m32build armbuild aarch64build ppcbuild ppc64build gcc5build: clean gcc-5 -v diff --git a/programs/.gitignore b/programs/.gitignore index 2d4edbe45..42a7e30dc 100644 --- a/programs/.gitignore +++ b/programs/.gitignore @@ -9,6 +9,8 @@ zstd-small zstd-nolegacy zstd-dictBuilder zstd-dll +zstd_arm64 +zstd_x64 # Object files *.o From 803e65f935d0e0faefb268341aa67124336bdb58 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Apr 2023 06:02:27 +0000 Subject: [PATCH 010/937] Bump actions/checkout from 3.5.0 to 3.5.2 Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.0 to 3.5.2. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/8f4b7f84864484a7bf31766abe9204da3cbe65b3...8e5e7e5ab8b370d6c329ec480221332ada57f0ab) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 50 ++++++------- .github/workflows/dev-short-tests.yml | 74 +++++++++---------- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 5 files changed, 65 insertions(+), 65 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 16202260d..deef9f780 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -15,7 +15,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: make all run: make all @@ -26,7 +26,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: make test run: make test @@ -34,7 +34,7 @@ jobs: make-test-osx: runs-on: macos-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: OS-X test run: make test # make -c lib all doesn't work because of the fact that it's not a tty @@ -45,7 +45,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: make test run: | sudo apt-get -qqq update @@ -55,21 +55,21 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream ubsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: undefined behavior sanitizer zstreamtest run: CC=clang make uasan-test-zstream @@ -77,7 +77,7 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest @@ -85,7 +85,7 @@ jobs: big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -96,7 +96,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -108,14 +108,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # tag=v3 + - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Mon, 17 Apr 2023 15:43:27 -0700 Subject: [PATCH 011/937] added decoder errata paragraph for compressed blocks of size exactly 128 KB which used to be disallowed by the spec but have become allowed in more recent version of the spec. While this limitation is fixed in decoders v1.5.4+, implementers should refrain from generating such block with their custom encoder as they could be misclassified as corrupted by older decoder versions. --- doc/decompressor_errata.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/doc/decompressor_errata.md b/doc/decompressor_errata.md index b162e7fd6..6c99cb01f 100644 --- a/doc/decompressor_errata.md +++ b/doc/decompressor_errata.md @@ -6,12 +6,29 @@ Each entry will contain: 1. The last affected decompressor versions. 2. The decompressor components affected. 2. Whether the compressed frame could ever be produced by the reference compressor. -3. An example frame. +3. An example frame when it can be short enough to be displayed as hexadecimal 4. A description of the bug. The document is in reverse chronological order, with the bugs that affect the most recent zstd decompressor versions listed first. +Compressed block with a size of exactly 128 KB +------------------------------------------------ + +**Last affected version**: v1.5.2 + +**Affected decompressor component(s)**: Library & CLI + +**Produced by the reference compressor**: No + +The zstd decoder incorrectly rejected blocks of type `Compressed_Block` when their size was exactly 128 KB. + +This type of block was never generated by the reference compressor. + +These blocks used to be disallowed by the spec up until spec version 0.3.2 when the restriction was lifted by [PR#1689](https://github.com/facebook/zstd/pull/1689). + +> A Compressed_Block has the extra restriction that Block_Size is always strictly less than the decompressed size. If this condition cannot be respected, the block must be sent uncompressed instead (Raw_Block). + Compressed block with 0 literals and 0 sequences ------------------------------------------------ From 05434fe9a5d0d55650596e43171efcf1208c5c84 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 17 Apr 2023 15:50:31 -0700 Subject: [PATCH 012/937] removed travis & appveyor scripts we don't employ these CI systems anymore --- .travis.yml | 128 -------------------------------- appveyor.yml | 205 --------------------------------------------------- 2 files changed, 333 deletions(-) delete mode 100644 .travis.yml delete mode 100644 appveyor.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b96bf8ba2..000000000 --- a/.travis.yml +++ /dev/null @@ -1,128 +0,0 @@ -# Travis CI is used to test platforms that github-actions currently doesn't support -# without either self-hosting or some finnicky work-around. Also, some tests -# are troublesome to migrate since GH Actions runs tests not in a tty. -language: c - -git: - depth: 1 - -branches: - only: - - dev - - release - - master - - travisTest - -addons: - apt: - update: true - -env: - global: - - FUZZERTEST=-T1mn - ZSTREAM_TESTTIME=-T1mn - DECODECORPUS_TESTTIME=-T1mn - -matrix: - fast_finish: true - include: - - name: S390X (big endian) + Fuzz test - dist: trusty - arch: s390x - script: - - FUZZER_FLAGS=--no-big-tests make -C tests fuzztest - - - name: S390X (big endian) + Fuzz test + no intrinsics - dist: trusty - arch: s390x - script: - - MOREFLAGS="-DZSTD_NO_INTRINSICS" FUZZER_FLAGS=--no-big-tests make -C tests fuzztest - - - name: arm64 # ~2.5 mn - os: linux - arch: arm64 - script: - - make check - - - name: arm64fuzz - os: linux - arch: arm64 - script: - - make -C tests fuzztest - - # TODO: migrate to GH Actions once newest clang staticanalyze warnings are fixed - - name: static analyzer scanbuild # ~8mn - dist: trusty # note : it's important to pin down a version of static analyzer, since different versions report different false positives - script: - - make staticAnalyze - - # GH actions can't run this command on OS-X, non-tty issues - - name: OS-X make all lib - os: osx - script: - - make -C lib all - - # Introduced to check compat with old toolchains, to prevent e.g. #1872 - - name: ARM Build Test (on Trusty) - dist: trusty - script: - - make arminstall - - make armbuild - - # check release number (release/new tag only) - - name: Tag-Specific Test - if: tag =~ ^v[0-9]\.[0-9] - script: - - make -C tests checkTag - - tests/checkTag "$TRAVIS_BRANCH" - - - name: PPC64LE + Fuzz test # ~13mn - arch: ppc64le - env: - - FUZZER_FLAGS=--no-big-tests - - MOREFLAGS="-static" - script: - - cat /proc/cpuinfo - - make -C tests fuzztest - - # This test currently fails on GA specifically, for no obvious reason - # (it works fine on travisCI, and on local test platforms). - - name: Versions Compatibility Test # ~6mn - script: - - make -C tests versionsTest - - # meson dedicated test - - name: Focal (Meson + clang) # ~15mn - dist: focal - language: cpp - compiler: clang - install: - - sudo apt-get install -qq liblz4-dev valgrind tree - - | - travis_retry curl -o ~/ninja.zip -L 'https://github.com/ninja-build/ninja/releases/download/v1.9.0/ninja-linux.zip' && - unzip ~/ninja.zip -d ~/.local/bin - - | - travis_retry curl -o ~/get-pip.py -L 'https://bootstrap.pypa.io/pip/3.6/get-pip.py' && - python3 ~/get-pip.py --user && - pip3 install --user meson - script: - - | - meson setup \ - --buildtype=debugoptimized \ - -Db_lundef=false \ - -Dauto_features=enabled \ - -Dbin_programs=true \ - -Dbin_tests=true \ - -Dbin_contrib=true \ - -Ddefault_library=both \ - build/meson builddir - - pushd builddir - - ninja - - meson test --verbose --no-rebuild - - DESTDIR=./staging ninja install - - tree ./staging - after_failure: - - cat "$TRAVIS_BUILD_DIR"/builddir/meson-logs/testlog.txt - - allow_failures: - - env: ALLOW_FAILURES=true diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index c58ef91a1..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,205 +0,0 @@ -# Following tests are run _only_ on `release` branch -# and on selected feature branch named `appveyorTest` or `visual*` - -- - version: 1.0.{build} - branches: - only: - - release - - master - - /appveyor*/ - - /visual*/ - environment: - matrix: - - COMPILER: "gcc" - HOST: "mingw" - PLATFORM: "x64" - SCRIPT: "make allzstd MOREFLAGS=-static" - ARTIFACT: "true" - BUILD: "true" - - COMPILER: "gcc" - HOST: "mingw" - PLATFORM: "x86" - SCRIPT: "make allzstd MOREFLAGS=-static" - ARTIFACT: "true" - BUILD: "true" - - - COMPILER: "clang-cl" - HOST: "cmake-visual" - PLATFORM: "x64" - CONFIGURATION: "Release" - CMAKE_GENERATOR: "Visual Studio 15 2017" - CMAKE_GENERATOR_PLATFORM: "x64" - CMAKE_GENERATOR_TOOLSET: "LLVM" - APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017" - - install: - - ECHO Installing %COMPILER% %PLATFORM% %CONFIGURATION% - - SET PATH_ORIGINAL=%PATH% - - if [%HOST%]==[mingw] ( - SET "PATH_MINGW32=C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin" && - SET "PATH_MINGW64=C:\mingw-w64\x86_64-6.3.0-posix-seh-rt_v5-rev1\mingw64\bin" && - COPY C:\msys64\usr\bin\make.exe C:\mingw-w64\i686-6.3.0-posix-dwarf-rt_v5-rev1\mingw32\bin\make.exe && - COPY C:\msys64\usr\bin\make.exe C:\mingw-w64\x86_64-6.3.0-posix-seh-rt_v5-rev1\mingw64\bin\make.exe - ) - - IF [%HOST%]==[visual] IF [%PLATFORM%]==[x64] ( - SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;" - ) - - build_script: - - if [%HOST%]==[mingw] ( - ( if [%PLATFORM%]==[x64] ( - SET "PATH=%PATH_MINGW64%;%PATH_ORIGINAL%" - ) else if [%PLATFORM%]==[x86] ( - SET "PATH=%PATH_MINGW32%;%PATH_ORIGINAL%" - ) ) - ) - - if [%HOST%]==[mingw] if [%BUILD%]==[true] ( - make -v && - sh -c "%COMPILER% -v" && - ECHO Building zlib to static link && - SET "CC=%COMPILER%" && - sh -c "cd .. && git clone --depth 1 --branch v1.2.11 https://github.com/madler/zlib" && - sh -c "cd ../zlib && make -f win32/Makefile.gcc libz.a" - ECHO Building zstd && - SET "CPPFLAGS=-I../../zlib" && - SET "LDFLAGS=../../zlib/libz.a" && - sh -c "%SCRIPT%" && - ( if [%COMPILER%]==[gcc] if [%ARTIFACT%]==[true] - ECHO Creating artifacts && - ECHO %cd% && - lib\dll\example\build_package.bat && - make -C programs DEBUGFLAGS= clean zstd && - cd programs\ && 7z a -tzip -mx9 zstd-win-binary-%PLATFORM%.zip zstd.exe && - appveyor PushArtifact zstd-win-binary-%PLATFORM%.zip && - cp zstd.exe ..\bin\zstd.exe && - git clone --depth 1 --branch release https://github.com/facebook/zstd && - cd zstd && - git archive --format=tar release -o zstd-src.tar && - ..\zstd -19 zstd-src.tar && - appveyor PushArtifact zstd-src.tar.zst && - certUtil -hashfile zstd-src.tar.zst SHA256 > zstd-src.tar.zst.sha256.sig && - appveyor PushArtifact zstd-src.tar.zst.sha256.sig && - cd ..\..\bin\ && - 7z a -tzip -mx9 zstd-win-release-%PLATFORM%.zip * && - appveyor PushArtifact zstd-win-release-%PLATFORM%.zip - ) - ) - - if [%HOST%]==[cmake-visual] ( - ECHO *** && - ECHO *** Building %CMAKE_GENERATOR% ^(%CMAKE_GENERATOR_TOOLSET%^) %PLATFORM%\%CONFIGURATION% && - PUSHD build\cmake && - cmake -DBUILD_TESTING=ON . && - cmake --build . --config %CONFIGURATION% -j4 && - POPD && - ECHO *** - ) - - test_script: - - ECHO Testing %COMPILER% %PLATFORM% %CONFIGURATION% - - SET "CC=gcc" - - SET "CXX=g++" - - if [%TEST%]==[cmake] ( - mkdir build\cmake\build && - cd build\cmake\build && - SET FUZZERTEST=-T2mn && - SET ZSTREAM_TESTTIME=-T2mn && - cmake -G "Visual Studio 14 2015 Win64" .. && - cd ..\..\.. && - make clean - ) - - -# The following tests are for regular pushes -# into `dev` or some feature branch -# There run less tests, for shorter feedback loop - -- - version: 1.0.{build} - environment: - matrix: - - COMPILER: "visual" - HOST: "visual" - PLATFORM: "x64" - CONFIGURATION: "Debug" - - COMPILER: "visual" - HOST: "visual" - PLATFORM: "Win32" - CONFIGURATION: "Debug" - - COMPILER: "visual" - HOST: "visual" - PLATFORM: "x64" - CONFIGURATION: "Release" - - COMPILER: "visual" - HOST: "visual" - PLATFORM: "Win32" - CONFIGURATION: "Release" - - - COMPILER: "gcc" - HOST: "cygwin" - PLATFORM: "x64" - - - COMPILER: "clang-cl" - HOST: "cmake-visual" - PLATFORM: "x64" - CONFIGURATION: "Release" - CMAKE_GENERATOR: "Visual Studio 15 2017" - CMAKE_GENERATOR_PLATFORM: "x64" - CMAKE_GENERATOR_TOOLSET: "LLVM" - APPVEYOR_BUILD_WORKER_IMAGE: "Visual Studio 2017" - - install: - - ECHO Installing %COMPILER% %PLATFORM% %CONFIGURATION% - - SET PATH_ORIGINAL=%PATH% - - if [%HOST%]==[cygwin] ( - ECHO Installing Cygwin Packages && - C:\cygwin64\setup-x86_64.exe -qnNdO -R "C:\cygwin64" -g -P ^ - gcc,^ - cmake,^ - make - ) - - IF [%HOST%]==[visual] IF [%PLATFORM%]==[x64] ( - SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;" - ) - - build_script: - - ECHO Building %COMPILER% %PLATFORM% %CONFIGURATION% - - if [%HOST%]==[cygwin] ( - set CHERE_INVOKING=yes && - set CC=%COMPILER% && - C:\cygwin64\bin\bash --login -c " - set -e; - cd build/cmake; - CFLAGS='-Werror' cmake -G 'Unix Makefiles' -DCMAKE_BUILD_TYPE=Debug -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_FUZZER_FLAGS=-T20s -DZSTD_ZSTREAM_FLAGS=-T20s -DZSTD_FULLBENCH_FLAGS=-i0 .; - make VERBOSE=1 -j; - ctest -V -L Medium; - " - ) - - if [%HOST%]==[cmake-visual] ( - ECHO *** && - ECHO *** Building %CMAKE_GENERATOR% ^(%CMAKE_GENERATOR_TOOLSET%^) %PLATFORM%\%CONFIGURATION% && - PUSHD build\cmake && - cmake -DBUILD_TESTING=ON . && - cmake --build . --config %CONFIGURATION% -j4 && - POPD && - ECHO *** - ) - - if [%HOST%]==[visual] ( - ECHO *** && - ECHO *** Building Visual Studio 2012 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "build\VS2010\zstd.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /p:ForceImportBeforeCppTargets=%APPVEYOR_BUILD_FOLDER%\build\VS2010\CompileAsCpp.props /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - DIR build\VS2010\bin\%PLATFORM%_%CONFIGURATION%\*.exe && - msbuild "build\VS2010\zstd.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - DIR build\VS2010\bin\%PLATFORM%_%CONFIGURATION%\*.exe - ) - - - test_script: - - ECHO Testing %COMPILER% %PLATFORM% %CONFIGURATION% - - SET "FUZZERTEST=-T10s" - - if [%HOST%]==[mingw] ( - set "CC=%COMPILER%" && - make clean && - make check - ) \ No newline at end of file From 0abf2baef925fed4dac13d551c35d817e3206fdd Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 14 Apr 2023 14:27:06 -0700 Subject: [PATCH 013/937] Reduce streaming decompression memory by 128KB The split literals buffer patch increased streaming decompression memory by 64KB (shrunk lit buffer from 128KB to 64KB, and added 128KB). This patch removes the added 128KB buffer, because it isn't necessary. The buffer was there because the literals compression code didn't know the true `blockSizeMax` of the frame, and always put split literals so they ended 128KB - 32 from the beginning of the block. Instead, we can pass down the true `blockSizeMax` and ensure that the split literals end up at `blockSizeMax - 32` from the beginning of the block. We already reserve a full `blockSizeMax` bytes in streaming mode, so we won't be overwriting the extDict window. --- lib/decompress/zstd_decompress.c | 21 ++- lib/decompress/zstd_decompress_block.c | 220 ++++++++++++---------- lib/decompress/zstd_decompress_block.h | 2 +- lib/decompress/zstd_decompress_internal.h | 1 + tests/fullbench.c | 13 +- 5 files changed, 143 insertions(+), 114 deletions(-) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 7bc271342..94b90481b 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -265,6 +265,7 @@ static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) #endif dctx->noForwardProgress = 0; dctx->oversizedDuration = 0; + dctx->isFrameDecompression = 1; #if DYNAMIC_BMI2 dctx->bmi2 = ZSTD_cpuSupportsBmi2(); #endif @@ -1003,7 +1004,8 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, switch(blockProperties.blockType) { case bt_compressed: - decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oBlockEnd-op), ip, cBlockSize, /* frame */ 1, not_streaming); + assert(dctx->isFrameDecompression == 1); + decodedSize = ZSTD_decompressBlock_internal(dctx, op, (size_t)(oBlockEnd-op), ip, cBlockSize, not_streaming); break; case bt_raw : /* Use oend instead of oBlockEnd because this function is safe to overlap. It uses memmove. */ @@ -1319,7 +1321,8 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, c { case bt_compressed: DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed"); - rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1, is_streaming); + assert(dctx->isFrameDecompression == 1); + rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, is_streaming); dctx->expected = 0; /* Streaming not supported */ break; case bt_raw : @@ -1548,6 +1551,7 @@ size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) dctx->litEntropy = dctx->fseEntropy = 0; dctx->dictID = 0; dctx->bType = bt_reserved; + dctx->isFrameDecompression = 1; ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue)); ZSTD_memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */ dctx->LLTptr = dctx->entropy.LLTable; @@ -1911,6 +1915,7 @@ size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset) || (reset == ZSTD_reset_session_and_parameters) ) { dctx->streamStage = zdss_init; dctx->noForwardProgress = 0; + dctx->isFrameDecompression = 1; } if ( (reset == ZSTD_reset_parameters) || (reset == ZSTD_reset_session_and_parameters) ) { @@ -1929,9 +1934,15 @@ size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) { - size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX); - /* space is needed to store the litbuffer after the output of a given block without stomping the extDict of a previous run, as well as to cover both windows against wildcopy*/ - unsigned long long const neededRBSize = windowSize + blockSize + ZSTD_BLOCKSIZE_MAX + (WILDCOPY_OVERLENGTH * 2); + size_t const blockSize = (size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + /* We need blockSize + WILDCOPY_OVERLENGTH worth of buffer so that if a block + * ends at windowSize + WILDCOPY_OVERLENGTH + 1 bytes, we can start writing + * the block at the beginning of the output buffer, and maintain a full window. + * + * We need another blockSize worth of buffer so that we can store split + * literals at the end of the block without overwriting the extDict window. + */ + unsigned long long const neededRBSize = windowSize + (blockSize * 2) + (WILDCOPY_OVERLENGTH * 2); unsigned long long const neededSize = MIN(frameContentSize, neededRBSize); size_t const minRBSize = (size_t) neededSize; RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize, diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 09896a931..5028a52f1 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -51,6 +51,13 @@ static void ZSTD_copy4(void* dst, const void* src) { ZSTD_memcpy(dst, src, 4); } * Block decoding ***************************************************************/ +static size_t ZSTD_blockSizeMax(ZSTD_DCtx const* dctx) +{ + size_t const blockSizeMax = dctx->isFrameDecompression ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX; + assert(blockSizeMax <= ZSTD_BLOCKSIZE_MAX); + return blockSizeMax; +} + /*! ZSTD_getcBlockSize() : * Provides the size of compressed block from block header `src` */ size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, @@ -73,41 +80,49 @@ size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, static void ZSTD_allocateLiteralsBuffer(ZSTD_DCtx* dctx, void* const dst, const size_t dstCapacity, const size_t litSize, const streaming_operation streaming, const size_t expectedWriteSize, const unsigned splitImmediately) { - if (streaming == not_streaming && dstCapacity > ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) - { - /* room for litbuffer to fit without read faulting */ - dctx->litBuffer = (BYTE*)dst + ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH; + size_t const blockSizeMax = ZSTD_blockSizeMax(dctx); + assert(litSize <= blockSizeMax); + assert(dctx->isFrameDecompression || streaming == not_streaming); + assert(expectedWriteSize <= blockSizeMax); + if (streaming == not_streaming && dstCapacity > blockSizeMax + WILDCOPY_OVERLENGTH + litSize + WILDCOPY_OVERLENGTH) { + /* If we aren't streaming, we can just put the literals after the output + * of the current block. We don't need to worry about overwriting the + * extDict of our window, because it doesn't exist. + * So if we have space after the end of the block, just put it there. + */ + dctx->litBuffer = (BYTE*)dst + blockSizeMax + WILDCOPY_OVERLENGTH; dctx->litBufferEnd = dctx->litBuffer + litSize; dctx->litBufferLocation = ZSTD_in_dst; - } - else if (litSize > ZSTD_LITBUFFEREXTRASIZE) - { - /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */ + } else if (litSize <= ZSTD_LITBUFFEREXTRASIZE) { + /* Literals fit entirely within the extra buffer, put them there to avoid + * having to split the literals. + */ + dctx->litBuffer = dctx->litExtraBuffer; + dctx->litBufferEnd = dctx->litBuffer + litSize; + dctx->litBufferLocation = ZSTD_not_in_dst; + } else { + assert(blockSizeMax > ZSTD_LITBUFFEREXTRASIZE); + /* Literals must be split between the output block and the extra lit + * buffer. We fill the extra lit buffer with the tail of the literals, + * and put the rest of the literals at the end of the block, with + * WILDCOPY_OVERLENGTH of buffer room to allow for overreads. + * This MUST not write more than our maxBlockSize beyond dst, because in + * streaming mode, that could overwrite part of our extDict window. + */ if (splitImmediately) { /* won't fit in litExtraBuffer, so it will be split between end of dst and extra buffer */ dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH; dctx->litBufferEnd = dctx->litBuffer + litSize - ZSTD_LITBUFFEREXTRASIZE; - } - else { + } else { /* initially this will be stored entirely in dst during huffman decoding, it will partially be shifted to litExtraBuffer after */ dctx->litBuffer = (BYTE*)dst + expectedWriteSize - litSize; dctx->litBufferEnd = (BYTE*)dst + expectedWriteSize; } dctx->litBufferLocation = ZSTD_split; - } - else - { - /* fits entirely within litExtraBuffer, so no split is necessary */ - dctx->litBuffer = dctx->litExtraBuffer; - dctx->litBufferEnd = dctx->litBuffer + litSize; - dctx->litBufferLocation = ZSTD_not_in_dst; + assert(dctx->litBufferEnd <= (BYTE*)dst + expectedWriteSize); } } -/* Hidden declaration for fullbench */ -size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, - const void* src, size_t srcSize, - void* dst, size_t dstCapacity, const streaming_operation streaming); /*! 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 @@ -116,7 +131,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, * * @return : nb of bytes read from src (< srcSize ) * note : symbol not declared but exposed for fullbench */ -size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, +static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, const void* src, size_t srcSize, /* note : srcSize < BLOCKSIZE */ void* dst, size_t dstCapacity, const streaming_operation streaming) { @@ -125,6 +140,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, { const BYTE* const istart = (const BYTE*) src; symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3); + size_t const blockSizeMax = ZSTD_blockSizeMax(dctx); switch(litEncType) { @@ -140,7 +156,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, U32 const lhlCode = (istart[0] >> 2) & 3; U32 const lhc = MEM_readLE32(istart); size_t hufSuccess; - size_t expectedWriteSize = MIN(ZSTD_BLOCKSIZE_MAX, dstCapacity); + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); int const flags = 0 | (ZSTD_DCtx_get_bmi2(dctx) ? HUF_flags_bmi2 : 0) | (dctx->disableHufAsm ? HUF_flags_disableAsm : 0); @@ -167,7 +183,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, break; } RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); - RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, ""); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); if (!singleStream) RETURN_ERROR_IF(litSize < MIN_LITERALS_FOR_4_STREAMS, literals_headerWrong, "Not enough literals (%zu) for the 4-streams mode (min %u)", @@ -214,10 +230,12 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, } if (dctx->litBufferLocation == ZSTD_split) { + assert(litSize > ZSTD_LITBUFFEREXTRASIZE); ZSTD_memcpy(dctx->litExtraBuffer, dctx->litBufferEnd - ZSTD_LITBUFFEREXTRASIZE, ZSTD_LITBUFFEREXTRASIZE); ZSTD_memmove(dctx->litBuffer + ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH, dctx->litBuffer, litSize - ZSTD_LITBUFFEREXTRASIZE); dctx->litBuffer += ZSTD_LITBUFFEREXTRASIZE - WILDCOPY_OVERLENGTH; dctx->litBufferEnd -= WILDCOPY_OVERLENGTH; + assert(dctx->litBufferEnd <= (BYTE*)dst + blockSizeMax); } RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, ""); @@ -232,7 +250,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, case set_basic: { size_t litSize, lhSize; U32 const lhlCode = ((istart[0]) >> 2) & 3; - size_t expectedWriteSize = MIN(ZSTD_BLOCKSIZE_MAX, dstCapacity); + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); switch(lhlCode) { case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ @@ -251,6 +269,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, } RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, ""); ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1); if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */ @@ -279,7 +298,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, case set_rle: { U32 const lhlCode = ((istart[0]) >> 2) & 3; size_t litSize, lhSize; - size_t expectedWriteSize = MIN(ZSTD_BLOCKSIZE_MAX, dstCapacity); + size_t expectedWriteSize = MIN(blockSizeMax, dstCapacity); switch(lhlCode) { case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */ @@ -298,7 +317,7 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, break; } RETURN_ERROR_IF(litSize > 0 && dst == NULL, dstSize_tooSmall, "NULL not handled"); - RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, ""); + RETURN_ERROR_IF(litSize > blockSizeMax, corruption_detected, ""); RETURN_ERROR_IF(expectedWriteSize < litSize, dstSize_tooSmall, ""); ZSTD_allocateLiteralsBuffer(dctx, dst, dstCapacity, litSize, streaming, expectedWriteSize, 1); if (dctx->litBufferLocation == ZSTD_split) @@ -320,6 +339,18 @@ size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, } } +/* Hidden declaration for fullbench */ +size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, + void* dst, size_t dstCapacity); +size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, + void* dst, size_t dstCapacity) +{ + dctx->isFrameDecompression = 0; + return ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, not_streaming); +} + /* Default FSE distribution tables. * These are pre-calculated FSE decoding tables using default distributions as defined in specification : * https://github.com/facebook/zstd/blob/release/doc/zstd_compression_format.md#default-distributions @@ -1320,22 +1351,24 @@ MEM_STATIC void ZSTD_assertValidSequence( BYTE const* prefixStart, BYTE const* virtualStart) { #if DEBUGLEVEL >= 1 - size_t const windowSize = dctx->fParams.windowSize; - size_t const sequenceSize = seq.litLength + seq.matchLength; - BYTE const* const oLitEnd = op + seq.litLength; - DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u", - (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); - assert(op <= oend); - assert((size_t)(oend - op) >= sequenceSize); - assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX); - if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) { - size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing); - /* Offset must be within the dictionary. */ - assert(seq.offset <= (size_t)(oLitEnd - virtualStart)); - assert(seq.offset <= windowSize + dictSize); - } else { - /* Offset must be within our window. */ - assert(seq.offset <= windowSize); + if (dctx->isFrameDecompression) { + size_t const windowSize = dctx->fParams.windowSize; + size_t const sequenceSize = seq.litLength + seq.matchLength; + BYTE const* const oLitEnd = op + seq.litLength; + DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u", + (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); + assert(op <= oend); + assert((size_t)(oend - op) >= sequenceSize); + assert(sequenceSize <= ZSTD_blockSizeMax(dctx)); + if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) { + size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing); + /* Offset must be within the dictionary. */ + assert(seq.offset <= (size_t)(oLitEnd - virtualStart)); + assert(seq.offset <= windowSize + dictSize); + } else { + /* Offset must be within our window. */ + assert(seq.offset <= windowSize); + } } #else (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart; @@ -1351,8 +1384,7 @@ DONT_VECTORIZE ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { const BYTE* ip = (const BYTE*)seqStart; const BYTE* const iend = ip + seqSize; @@ -1365,7 +1397,6 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, const BYTE* const vBase = (const BYTE*) (dctx->virtualStart); const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer"); - (void)frame; /* Regen sequences */ if (nbSeq) { @@ -1453,7 +1484,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); #endif if (UNLIKELY(ZSTD_isError(oneSeqSize))) return oneSeqSize; @@ -1482,7 +1513,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); #endif if (UNLIKELY(ZSTD_isError(oneSeqSize))) return oneSeqSize; @@ -1519,7 +1550,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); #endif if (UNLIKELY(ZSTD_isError(oneSeqSize))) return oneSeqSize; @@ -1568,8 +1599,7 @@ DONT_VECTORIZE ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { const BYTE* ip = (const BYTE*)seqStart; const BYTE* const iend = ip + seqSize; @@ -1582,7 +1612,6 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, const BYTE* const vBase = (const BYTE*)(dctx->virtualStart); const BYTE* const dictEnd = (const BYTE*)(dctx->dictEnd); DEBUGLOG(5, "ZSTD_decompressSequences_body: nbSeq = %d", nbSeq); - (void)frame; /* Regen sequences */ if (nbSeq) { @@ -1621,7 +1650,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); #endif if (UNLIKELY(ZSTD_isError(oneSeqSize))) return oneSeqSize; @@ -1656,20 +1685,18 @@ static size_t ZSTD_decompressSequences_default(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } static size_t ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ @@ -1697,8 +1724,7 @@ ZSTD_decompressSequencesLong_body( ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { const BYTE* ip = (const BYTE*)seqStart; const BYTE* const iend = ip + seqSize; @@ -1710,7 +1736,6 @@ ZSTD_decompressSequencesLong_body( const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart); const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); - (void)frame; /* Regen sequences */ if (nbSeq) { @@ -1764,7 +1789,7 @@ ZSTD_decompressSequencesLong_body( oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); + ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); #endif if (ZSTD_isError(oneSeqSize)) return oneSeqSize; @@ -1780,7 +1805,7 @@ ZSTD_decompressSequencesLong_body( ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); + ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); #endif if (ZSTD_isError(oneSeqSize)) return oneSeqSize; @@ -1812,7 +1837,7 @@ ZSTD_decompressSequencesLong_body( size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); + ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); #endif if (ZSTD_isError(oneSeqSize)) return oneSeqSize; op += oneSeqSize; @@ -1825,7 +1850,7 @@ ZSTD_decompressSequencesLong_body( ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); - if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); + ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); #endif if (ZSTD_isError(oneSeqSize)) return oneSeqSize; op += oneSeqSize; @@ -1863,10 +1888,9 @@ static size_t ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ @@ -1880,20 +1904,18 @@ DONT_VECTORIZE ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } static BMI2_TARGET_ATTRIBUTE size_t DONT_VECTORIZE ZSTD_decompressSequencesSplitLitBuffer_bmi2(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_bodySplitLitBuffer(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ @@ -1902,10 +1924,9 @@ static BMI2_TARGET_ATTRIBUTE size_t ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { - return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ @@ -1915,37 +1936,34 @@ typedef size_t (*ZSTD_decompressSequences_t)( ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame); + const ZSTD_longOffset_e isLongOffset); #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG static size_t ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequences"); #if DYNAMIC_BMI2 if (ZSTD_DCtx_get_bmi2(dctx)) { - return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif - return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } static size_t ZSTD_decompressSequencesSplitLitBuffer(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequencesSplitLitBuffer"); #if DYNAMIC_BMI2 if (ZSTD_DCtx_get_bmi2(dctx)) { - return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesSplitLitBuffer_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif - return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesSplitLitBuffer_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */ @@ -1960,16 +1978,15 @@ static size_t ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset, - const int frame) + const ZSTD_longOffset_e isLongOffset) { DEBUGLOG(5, "ZSTD_decompressSequencesLong"); #if DYNAMIC_BMI2 if (ZSTD_DCtx_get_bmi2(dctx)) { - return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif - return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset); } #endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */ @@ -2051,20 +2068,20 @@ static size_t ZSTD_maxShortOffset(void) size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, - const void* src, size_t srcSize, const int frame, const streaming_operation streaming) + const void* src, size_t srcSize, const streaming_operation streaming) { /* blockType == blockCompressed */ const BYTE* ip = (const BYTE*)src; DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize); /* Note : the wording of the specification - * allows compressed block to be sized exactly ZSTD_BLOCKSIZE_MAX. + * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx). * This generally does not happen, as it makes little sense, * since an uncompressed block would feature same size and have no decompression cost. * Also, note that decoder from reference libzstd before < v1.5.4 * would consider this edge case as an error. - * As a consequence, avoid generating compressed blocks of size ZSTD_BLOCKSIZE_MAX + * As a consequence, avoid generating compressed blocks of size ZSTD_blockSizeMax(dctx) * for broader compatibility with the deployed ecosystem of zstd decoders */ - RETURN_ERROR_IF(srcSize > ZSTD_BLOCKSIZE_MAX, srcSize_wrong, ""); + RETURN_ERROR_IF(srcSize > ZSTD_blockSizeMax(dctx), srcSize_wrong, ""); /* Decode literals section */ { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize, dst, dstCapacity, streaming); @@ -2079,7 +2096,7 @@ ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, /* Compute the maximum block size, which must also work when !frame and fParams are unset. * Additionally, take the min with dstCapacity to ensure that the totalHistorySize fits in a size_t. */ - size_t const blockSizeMax = MIN(dstCapacity, (frame ? dctx->fParams.blockSizeMax : ZSTD_BLOCKSIZE_MAX)); + size_t const blockSizeMax = MIN(dstCapacity, ZSTD_blockSizeMax(dctx)); size_t const totalHistorySize = ZSTD_totalHistorySize((BYTE*)dst + blockSizeMax, (BYTE const*)dctx->virtualStart); /* isLongOffset must be true if there are long offsets. * Offsets are long if they are larger than ZSTD_maxShortOffset(). @@ -2145,16 +2162,16 @@ ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, { #endif #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT - return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); #endif } #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG /* else */ if (dctx->litBufferLocation == ZSTD_split) - return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequencesSplitLitBuffer(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); else - return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame); + return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset); #endif } } @@ -2176,8 +2193,9 @@ size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx, const void* src, size_t srcSize) { size_t dSize; + dctx->isFrameDecompression = 0; ZSTD_checkContinuity(dctx, dst, dstCapacity); - dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0, not_streaming); + dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, not_streaming); dctx->previousDstEnd = (char*)dst + dSize; return dSize; } diff --git a/lib/decompress/zstd_decompress_block.h b/lib/decompress/zstd_decompress_block.h index 9d1318882..ab152404b 100644 --- a/lib/decompress/zstd_decompress_block.h +++ b/lib/decompress/zstd_decompress_block.h @@ -47,7 +47,7 @@ typedef enum { */ size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, - const void* src, size_t srcSize, const int frame, const streaming_operation streaming); + const void* src, size_t srcSize, const streaming_operation streaming); /* ZSTD_buildFSETable() : * generate FSE decoding table for one symbol (ll, ml or off) diff --git a/lib/decompress/zstd_decompress_internal.h b/lib/decompress/zstd_decompress_internal.h index c2ec5d9fb..25aaebe50 100644 --- a/lib/decompress/zstd_decompress_internal.h +++ b/lib/decompress/zstd_decompress_internal.h @@ -153,6 +153,7 @@ struct ZSTD_DCtx_s size_t litSize; size_t rleSize; size_t staticSize; + int isFrameDecompression; #if DYNAMIC_BMI2 != 0 int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ #endif diff --git a/tests/fullbench.c b/tests/fullbench.c index 41bd26d04..0391107b9 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -141,15 +141,14 @@ static size_t local_ZSTD_decompress(const void* src, size_t srcSize, static ZSTD_DCtx* g_zdc = NULL; #ifndef ZSTD_DLL_IMPORT -typedef enum { - not_streaming = 0, - is_streaming = 1 -} streaming_operation; -extern size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* ctx, const void* src, size_t srcSize, void* dst, size_t dstCapacity, const streaming_operation streaming); + +extern size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, + const void* src, size_t srcSize, + void* dst, size_t dstCapacity); static size_t local_ZSTD_decodeLiteralsBlock(const void* src, size_t srcSize, void* dst, size_t dstSize, void* buff2) { (void)src; (void)srcSize; (void)dst; (void)dstSize; - return ZSTD_decodeLiteralsBlock(g_zdc, buff2, g_cSize, dst, dstSize, not_streaming); + return ZSTD_decodeLiteralsBlock_wrapper(g_zdc, buff2, g_cSize, dst, dstSize); } static size_t local_ZSTD_decodeSeqHeaders(const void* src, size_t srcSize, void* dst, size_t dstSize, void* buff2) @@ -606,7 +605,7 @@ static int benchMem(unsigned benchNb, ip += ZSTD_blockHeaderSize; /* skip block header */ ZSTD_decompressBegin(g_zdc); CONTROL(iend > ip); - ip += ZSTD_decodeLiteralsBlock(g_zdc, ip, (size_t)(iend-ip), dstBuff, dstBuffSize, not_streaming); /* skip literal segment */ + ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dstBuff, dstBuffSize); /* skip literal segment */ g_cSize = (size_t)(iend-ip); memcpy(dstBuff2, ip, g_cSize); /* copy rest of block (it starts by SeqHeader) */ srcSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ From 61efb2a047b308b6f0c265e1eae9ca8a062268e4 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 14 Apr 2023 17:06:24 -0700 Subject: [PATCH 014/937] Add ZSTD_d_maxBlockSize parameter Reduces memory when blocks are guaranteed to be smaller than allowed by the format. This is useful for streaming compression in conjunction with ZSTD_c_maxBlockSize. This PR saves 2 * (formatMaxBlockSize - paramMaxBlockSize) when streaming. Once it is rebased on top of PR #3616 it will save 3 * (formatMaxBlockSize - paramMaxBlockSize). --- lib/decompress/zstd_decompress.c | 29 ++++++++- lib/decompress/zstd_decompress_internal.h | 1 + lib/zstd.h | 20 +++++- tests/fuzz/simple_round_trip.c | 3 + tests/fuzz/stream_round_trip.c | 24 +++++++- tests/fuzzer.c | 19 ++++++ tests/zstreamtest.c | 75 +++++++++++++++++++++++ 7 files changed, 165 insertions(+), 6 deletions(-) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 94b90481b..94eb95151 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -245,6 +245,7 @@ static void ZSTD_DCtx_resetParameters(ZSTD_DCtx* dctx) dctx->forceIgnoreChecksum = ZSTD_d_validateChecksum; dctx->refMultipleDDicts = ZSTD_rmd_refSingleDDict; dctx->disableHufAsm = 0; + dctx->maxBlockSizeParam = 0; } static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx) @@ -972,6 +973,10 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize; } + /* Shrink the blockSizeMax if enabled */ + if (dctx->maxBlockSizeParam != 0) + dctx->fParams.blockSizeMax = MIN(dctx->fParams.blockSizeMax, (unsigned)dctx->maxBlockSizeParam); + /* Loop on each block */ while (1) { BYTE* oBlockEnd = oend; @@ -1823,6 +1828,10 @@ ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam) bounds.lowerBound = 0; bounds.upperBound = 1; return bounds; + case ZSTD_d_maxBlockSize: + bounds.lowerBound = ZSTD_BLOCKSIZE_MAX_MIN; + bounds.upperBound = ZSTD_BLOCKSIZE_MAX; + return bounds; default:; } @@ -1867,6 +1876,9 @@ size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int* value case ZSTD_d_disableHuffmanAssembly: *value = (int)dctx->disableHufAsm; return 0; + case ZSTD_d_maxBlockSize: + *value = dctx->maxBlockSizeParam; + return 0; default:; } RETURN_ERROR(parameter_unsupported, ""); @@ -1904,6 +1916,10 @@ size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value CHECK_DBOUNDS(ZSTD_d_disableHuffmanAssembly, value); dctx->disableHufAsm = value != 0; return 0; + case ZSTD_d_maxBlockSize: + if (value != 0) CHECK_DBOUNDS(ZSTD_d_maxBlockSize, value); + dctx->maxBlockSizeParam = value; + return 0; default:; } RETURN_ERROR(parameter_unsupported, ""); @@ -1932,9 +1948,9 @@ size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx) return ZSTD_sizeof_DCtx(dctx); } -size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) +static size_t ZSTD_decodingBufferSize_internal(unsigned long long windowSize, unsigned long long frameContentSize, size_t blockSizeMax) { - size_t const blockSize = (size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX); + size_t const blockSize = MIN((size_t)MIN(windowSize, ZSTD_BLOCKSIZE_MAX), blockSizeMax); /* We need blockSize + WILDCOPY_OVERLENGTH worth of buffer so that if a block * ends at windowSize + WILDCOPY_OVERLENGTH + 1 bytes, we can start writing * the block at the beginning of the output buffer, and maintain a full window. @@ -1950,6 +1966,11 @@ size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long return minRBSize; } +size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize) +{ + return ZSTD_decodingBufferSize_internal(windowSize, frameContentSize, ZSTD_BLOCKSIZE_MAX); +} + size_t ZSTD_estimateDStreamSize(size_t windowSize) { size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX); @@ -2188,11 +2209,13 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN); RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize, frameParameter_windowTooLarge, ""); + if (zds->maxBlockSizeParam != 0) + zds->fParams.blockSizeMax = MIN(zds->fParams.blockSizeMax, (unsigned)zds->maxBlockSizeParam); /* Adapt buffer sizes to frame header instructions */ { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */); size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_bm_buffered - ? ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize) + ? ZSTD_decodingBufferSize_internal(zds->fParams.windowSize, zds->fParams.frameContentSize, zds->fParams.blockSizeMax) : 0; ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize); diff --git a/lib/decompress/zstd_decompress_internal.h b/lib/decompress/zstd_decompress_internal.h index 25aaebe50..83a7a0115 100644 --- a/lib/decompress/zstd_decompress_internal.h +++ b/lib/decompress/zstd_decompress_internal.h @@ -167,6 +167,7 @@ struct ZSTD_DCtx_s ZSTD_DDictHashSet* ddictSet; /* Hash set for multiple ddicts */ ZSTD_refMultipleDDicts_e refMultipleDDicts; /* User specified: if == 1, will allow references to multiple DDicts. Default == 0 (disabled) */ int disableHufAsm; + int maxBlockSizeParam; /* streaming */ ZSTD_dStreamStage streamStage; diff --git a/lib/zstd.h b/lib/zstd.h index e5c3f8b68..e94f10189 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -618,6 +618,7 @@ typedef enum { * ZSTD_d_forceIgnoreChecksum * ZSTD_d_refMultipleDDicts * ZSTD_d_disableHuffmanAssembly + * ZSTD_d_maxBlockSize * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. * note : never ever use experimentalParam? names directly */ @@ -625,7 +626,8 @@ typedef enum { ZSTD_d_experimentalParam2=1001, ZSTD_d_experimentalParam3=1002, ZSTD_d_experimentalParam4=1003, - ZSTD_d_experimentalParam5=1004 + ZSTD_d_experimentalParam5=1004, + ZSTD_d_experimentalParam6=1005 } ZSTD_dParameter; @@ -2430,6 +2432,22 @@ ZSTDLIB_STATIC_API size_t ZSTD_DCtx_getParameter(ZSTD_DCtx* dctx, ZSTD_dParamete */ #define ZSTD_d_disableHuffmanAssembly ZSTD_d_experimentalParam5 +/* ZSTD_d_maxBlockSize + * Allowed values are between 1KB and ZSTD_BLOCKSIZE_MAX (128KB). + * The default is ZSTD_BLOCKSIZE_MAX, and setting to 0 will set to the default. + * + * Forces the decompressor to reject blocks whose content size is + * larger than the configured maxBlockSize. When maxBlockSize is + * larger than the windowSize, the windowSize is used instead. + * This saves memory on the decoder when you know all blocks are small. + * + * This option is typically used in conjunction with ZSTD_c_maxBlockSize. + * + * WARNING: This causes the decoder to reject otherwise valid frames + * that have block sizes larger than the configured maxBlockSize. + */ +#define ZSTD_d_maxBlockSize ZSTD_d_experimentalParam6 + /*! ZSTD_DCtx_setFormat() : * This function is REDUNDANT. Prefer ZSTD_DCtx_setParameter(). diff --git a/tests/fuzz/simple_round_trip.c b/tests/fuzz/simple_round_trip.c index 0fe463917..660092e61 100644 --- a/tests/fuzz/simple_round_trip.c +++ b/tests/fuzz/simple_round_trip.c @@ -90,6 +90,9 @@ static size_t roundTripTest(void *result, size_t resultCapacity, FUZZ_ASSERT(XXH64(compressed, cSize, 0) == hash0); } } + if (FUZZ_dataProducer_uint32Range(producer, 0, 1)) { + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, maxBlockSize)); + } dSize = ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize); FUZZ_ZASSERT(dSize); FUZZ_ASSERT_MSG(dSize == srcSize, "Incorrect regenerated size"); diff --git a/tests/fuzz/stream_round_trip.c b/tests/fuzz/stream_round_trip.c index 7d277a857..c2d6707a1 100644 --- a/tests/fuzz/stream_round_trip.c +++ b/tests/fuzz/stream_round_trip.c @@ -63,6 +63,8 @@ static size_t compress(uint8_t *dst, size_t capacity, size_t dstSize = 0; ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only); FUZZ_setRandomParameters(cctx, srcSize, producer); + int maxBlockSize; + FUZZ_ZASSERT(ZSTD_CCtx_getParameter(cctx, ZSTD_c_maxBlockSize, &maxBlockSize)); while (srcSize > 0) { ZSTD_inBuffer in = makeInBuffer(&src, &srcSize, producer); @@ -93,6 +95,8 @@ static size_t compress(uint8_t *dst, size_t capacity, if (FUZZ_dataProducer_uint32Range(producer, 0, 7) == 0) { size_t const remaining = in.size - in.pos; FUZZ_setRandomParameters(cctx, remaining, producer); + /* Always use the same maxBlockSize */ + FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_maxBlockSize, maxBlockSize)); } mode = -1; } @@ -132,6 +136,23 @@ static size_t compress(uint8_t *dst, size_t capacity, return dstSize; } +size_t decompress(void* dst, size_t dstCapacity, void const* src, size_t srcSize, FUZZ_dataProducer_t* producer) +{ + ZSTD_inBuffer in = {src, srcSize, 0}; + ZSTD_outBuffer out = {dst, dstCapacity, 0}; + int maxBlockSize; + FUZZ_ZASSERT(ZSTD_CCtx_getParameter(cctx, ZSTD_c_maxBlockSize, &maxBlockSize)); + if (FUZZ_dataProducer_uint32Range(producer, 0, 1)) { + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, maxBlockSize)); + } + while (in.pos < in.size) { + size_t const ret = ZSTD_decompressStream(dctx, &out, &in); + FUZZ_ZASSERT(ret); + FUZZ_ASSERT(ret == 0); + } + return out.pos; +} + int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) { FUZZ_SEQ_PROD_SETUP(); @@ -163,8 +184,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) { size_t const cSize = compress(cBuf, neededBufSize, src, size, producer); - size_t const rSize = - ZSTD_decompressDCtx(dctx, rBuf, neededBufSize, cBuf, cSize); + size_t const rSize = decompress(rBuf, neededBufSize, cBuf, cSize, producer); FUZZ_ZASSERT(rSize); FUZZ_ASSERT_MSG(rSize == size, "Incorrect regenerated size"); FUZZ_ASSERT_MSG(!FUZZ_memcmp(src, rBuf, size), "Corruption!"); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 07ddfefd6..b049a9e09 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -952,6 +952,25 @@ static int basicUnitTests(U32 const seed, double compressibility) ZSTD_freeCDict(cdict); ZSTD_freeCCtx(cctx); } + + DISPLAYLEVEL(3, "test%3i : maxBlockSize = 2K", testNb++); + { + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_maxBlockSize, 2048)); + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, 2048)); + + cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize); + CHECK_Z(cSize); + CHECK_Z(ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize)); + + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, 1024)); + CHECK(ZSTD_isError(ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize))); + + ZSTD_freeDCtx(dctx); + ZSTD_freeCCtx(cctx); + } DISPLAYLEVEL(3, "test%3i : ldm fill dict out-of-bounds check", testNb++); { diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 14c4af82f..85d0fc81f 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -722,6 +722,67 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : maxBlockSize = 2KB : ", testNb++); + { + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + size_t singlePassSize, streamingSize, streaming2KSize; + + { + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 18)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_contentSizeFlag, 0)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_maxBlockSize, 2048)); + cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBufferSize); + CHECK_Z(cSize); + ZSTD_freeCCtx(cctx); + } + + CHECK_Z(ZSTD_decompressDCtx(dctx, decodedBuffer, CNBufferSize, compressedBuffer, cSize)); + singlePassSize = ZSTD_sizeof_DCtx(dctx); + CHECK_Z(singlePassSize); + + inBuff.src = compressedBuffer; + inBuff.size = cSize; + + outBuff.dst = decodedBuffer; + outBuff.size = decodedBufferSize; + + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, 2048)); + inBuff.pos = 0; + outBuff.pos = 0; + { + size_t const r = ZSTD_decompressStream(dctx, &outBuff, &inBuff); + CHECK_Z(r); + CHECK(r != 0, "Entire frame must be decompressed"); + } + streaming2KSize = ZSTD_sizeof_DCtx(dctx); + CHECK_Z(streaming2KSize); + + CHECK_Z(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); + inBuff.pos = 0; + outBuff.pos = 0; + { + size_t const r = ZSTD_decompressStream(dctx, &outBuff, &inBuff); + CHECK_Z(r); + CHECK(r != 0, "Entire frame must be decompressed"); + } + streamingSize = ZSTD_sizeof_DCtx(dctx); + CHECK_Z(streamingSize); + + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, 1024)); + inBuff.pos = 0; + outBuff.pos = 0; + CHECK(!ZSTD_isError(ZSTD_decompressStream(dctx, &outBuff, &inBuff)), "decompression must fail"); + + CHECK(streamingSize < singlePassSize + (1 << 18) + 3 * ZSTD_BLOCKSIZE_MAX, "Streaming doesn't use the right amount of memory"); + CHECK(streamingSize != streaming2KSize + 3 * (ZSTD_BLOCKSIZE_MAX - 2048), "ZSTD_d_blockSizeMax didn't save the right amount of memory"); + DISPLAYLEVEL(3, "| %zu | %zu | %zu | ", singlePassSize, streaming2KSize, streamingSize); + + ZSTD_freeDCtx(dctx); + } + DISPLAYLEVEL(3, "OK \n"); + /* Decompression with ZSTD_d_stableOutBuffer */ cSize = ZSTD_compress(compressedBuffer, compressedBufferSize, CNBuffer, CNBufferSize, 1); CHECK_Z(cSize); @@ -2845,6 +2906,13 @@ static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest, if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_forceMaxWindow, FUZ_rand(&lseed) & 1, opaqueAPI) ); if (FUZ_rand(&lseed) & 1) CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_deterministicRefPrefix, FUZ_rand(&lseed) & 1, opaqueAPI) ); + /* Set max block size parameters */ + if (FUZ_rand(&lseed) & 1) { + int maxBlockSize = (int)(FUZ_rand(&lseed) % ZSTD_BLOCKSIZE_MAX); + maxBlockSize = MAX(1024, maxBlockSize); + CHECK_Z( setCCtxParameter(zc, cctxParams, ZSTD_c_maxBlockSize, maxBlockSize, opaqueAPI) ); + } + /* Apply parameters */ if (opaqueAPI) { DISPLAYLEVEL(5, "t%u: applying CCtxParams \n", testNb); @@ -2976,6 +3044,13 @@ static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest, if (FUZ_rand(&lseed) & 1) { CHECK_Z(ZSTD_DCtx_setParameter(zd, ZSTD_d_disableHuffmanAssembly, FUZ_rand(&lseed) & 1)); } + if (FUZ_rand(&lseed) & 1) { + int maxBlockSize; + CHECK_Z(ZSTD_CCtx_getParameter(zc, ZSTD_c_maxBlockSize, &maxBlockSize)); + CHECK_Z(ZSTD_DCtx_setParameter(zd, ZSTD_d_maxBlockSize, maxBlockSize)); + } else { + CHECK_Z(ZSTD_DCtx_setParameter(zd, ZSTD_d_maxBlockSize, 0)); + } { size_t decompressionResult = 1; ZSTD_inBuffer inBuff = { cBuffer, cSize, 0 }; ZSTD_outBuffer outBuff= { dstBuffer, dstBufferSize, 0 }; From 0d6954b4cc309b430dd010dbeb20b112e7092644 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 19 Apr 2023 00:24:35 -0700 Subject: [PATCH 015/937] added golden file for the new decompressor erratum --- doc/decompressor_errata.md | 5 ++++- doc/educational_decoder/zstd_decompress.c | 2 +- tests/golden-decompression/block-128k.zst | Bin 0 -> 131081 bytes 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 tests/golden-decompression/block-128k.zst diff --git a/doc/decompressor_errata.md b/doc/decompressor_errata.md index 6c99cb01f..e170a62c1 100644 --- a/doc/decompressor_errata.md +++ b/doc/decompressor_errata.md @@ -6,7 +6,7 @@ Each entry will contain: 1. The last affected decompressor versions. 2. The decompressor components affected. 2. Whether the compressed frame could ever be produced by the reference compressor. -3. An example frame when it can be short enough to be displayed as hexadecimal +3. An example frame (hexadecimal string when it can be short enough, link to golden file otherwise) 4. A description of the bug. The document is in reverse chronological order, with the bugs that affect the most recent zstd decompressor versions listed first. @@ -21,7 +21,10 @@ Compressed block with a size of exactly 128 KB **Produced by the reference compressor**: No +**Example Frame**: see zstd/tests/golden-decompression/block-128k.zst + The zstd decoder incorrectly rejected blocks of type `Compressed_Block` when their size was exactly 128 KB. +Note that `128 KB - 1` was accepted, and `128 KB + 1` is forbidden by the spec. This type of block was never generated by the reference compressor. diff --git a/doc/educational_decoder/zstd_decompress.c b/doc/educational_decoder/zstd_decompress.c index 9ade76502..3196b78dc 100644 --- a/doc/educational_decoder/zstd_decompress.c +++ b/doc/educational_decoder/zstd_decompress.c @@ -1399,7 +1399,7 @@ size_t ZSTD_get_decompressed_size(const void *src, const size_t src_len) { /******* END OUTPUT SIZE COUNTING *********************************************/ /******* DICTIONARY PARSING ***************************************************/ -dictionary_t* create_dictionary() { +dictionary_t* create_dictionary(void) { dictionary_t* const dict = calloc(1, sizeof(dictionary_t)); if (!dict) { BAD_ALLOC(); diff --git a/tests/golden-decompression/block-128k.zst b/tests/golden-decompression/block-128k.zst new file mode 100644 index 0000000000000000000000000000000000000000..cdaeae39d106fa58bd60e8b167bd4d7704bd493c GIT binary patch literal 131081 zcmeIuu@L|e00gja^fu7yv=+C8l^kb}WQ6oJPG(8nw*>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK zfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5 zV8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM z7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b* z1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd z0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwA zz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEj zFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r z3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@ z0|pEjFkrxd0RsjM7%*VKfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM7%*VK mfB^#r3>YwAz<>b*1`HT5V8DO@0|pEjFkrxd0RsjM{DB9JumnK> literal 0 HcmV?d00001 From 4c25ea329b851e1d2e45c2a91e0d5d79a3ad3be0 Mon Sep 17 00:00:00 2001 From: Daniel Kutenin Date: Thu, 20 Apr 2023 11:14:08 +0100 Subject: [PATCH 016/937] Disable unused variable warning in msan configurations --- lib/compress/zstd_cwksp.h | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index cc7fb1c71..cfe808f15 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -192,6 +192,7 @@ MEM_STATIC void ZSTD_cwksp_assert_internal_consistency(ZSTD_cwksp* ws) { { intptr_t const offset = __msan_test_shadow(ws->initOnceStart, (U8*)ZSTD_cwksp_initialAllocStart(ws) - (U8*)ws->initOnceStart); + (void)offset; #if defined(ZSTD_MSAN_PRINT) if(offset!=-1) { __msan_print_shadow((U8*)ws->initOnceStart + offset - 8, 32); From be489f78df642cf8fd40fcfa59ec700cb494a1b5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Apr 2023 06:03:24 +0000 Subject: [PATCH 017/937] Bump github/codeql-action from 2.2.11 to 2.3.0 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.2.11 to 2.3.0. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/d186a2a36cc67bfa1b860e6170d37fb9634742c7...b2c19fb9a2a485599ccf4ed5d65527d94bc57226) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 5083378f4..e5f31fbac 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@d186a2a36cc67bfa1b860e6170d37fb9634742c7 # tag=v2.2.11 + uses: github/codeql-action/upload-sarif@b2c19fb9a2a485599ccf4ed5d65527d94bc57226 # tag=v2.3.0 with: sarif_file: results.sarif From 6ec18aed31a955ce7ce04403538f7539cd57eb56 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Apr 2023 12:45:23 -0700 Subject: [PATCH 018/937] minor : update streaming_compression example display a warning when requesting multi-threading while linking to a library that doesn't support multi-threading. --- examples/streaming_compression.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/examples/streaming_compression.c b/examples/streaming_compression.c index ed0a3a69c..063aa82a2 100644 --- a/examples/streaming_compression.c +++ b/examples/streaming_compression.c @@ -42,7 +42,13 @@ static void compressFile_orDie(const char* fname, const char* outName, int cLeve */ CHECK_ZSTD( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, cLevel) ); CHECK_ZSTD( ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1) ); - ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads); + if (nbThreads > 1) { + size_t const r = ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads); + if (ZSTD_isError(r)) { + fprintf (stderr, "Note: the linked libzstd library doesn't support multithreading. " + "Reverting to single-thread mode. \n"); + } + } /* This loop read from the input file, compresses that entire chunk, * and writes all output produced to the output file. @@ -117,7 +123,7 @@ int main(int argc, const char** argv) } int cLevel = 1; - int nbThreads = 4; + int nbThreads = 1; if (argc >= 3) { cLevel = atoi (argv[2]); From 2a5076d26481fddb22f1e589c1d1666b0a7456d6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 May 2023 06:04:02 +0000 Subject: [PATCH 019/937] Bump github/codeql-action from 2.3.0 to 2.3.2 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.3.0 to 2.3.2. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/b2c19fb9a2a485599ccf4ed5d65527d94bc57226...f3feb00acb00f31a6f60280e6ace9ca31d91c76a) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index e5f31fbac..58a273728 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@b2c19fb9a2a485599ccf4ed5d65527d94bc57226 # tag=v2.3.0 + uses: github/codeql-action/upload-sarif@f3feb00acb00f31a6f60280e6ace9ca31d91c76a # tag=v2.3.2 with: sarif_file: results.sarif From cbf3e263160e0bfc9499f55f34c3759a14c0c1cc Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 19 Apr 2023 11:41:51 -0400 Subject: [PATCH 020/937] Allow `ZSTD_selectBlockCompressor()` to Return NULL Return an error rather than segfaulting. --- lib/compress/zstd_compress.c | 17 +++++++++++------ lib/compress/zstd_ldm.c | 2 ++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d6133e70b..c28b43456 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3280,22 +3280,27 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) } /* Fallback to software matchfinder */ - { ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, - zc->appliedParams.useRowMatchFinder, - dictMode); + { ZSTD_blockCompressor const blockCompressor = + ZSTD_selectBlockCompressor( + zc->appliedParams.cParams.strategy, + zc->appliedParams.useRowMatchFinder, + dictMode); ms->ldmSeqStore = NULL; DEBUGLOG( 5, "External sequence producer returned error code %lu. Falling back to internal parser.", (unsigned long)nbExternalSeqs ); + RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize); } } } else { /* not long range mode and no external matchfinder */ - ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, - zc->appliedParams.useRowMatchFinder, - dictMode); + ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor( + zc->appliedParams.cParams.strategy, + zc->appliedParams.useRowMatchFinder, + dictMode); ms->ldmSeqStore = NULL; + RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize); } { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize; diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 3d74ff19e..ec0690ccb 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -672,6 +672,8 @@ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, /* Input positions */ BYTE const* ip = istart; + RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); + DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize); /* If using opt parser, use LDMs only as candidates rather than always accepting them */ if (cParams->strategy >= ZSTD_btopt) { From 81b86a2024c80c1fc69bb6a76407628e063917ed Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 19 Apr 2023 12:19:56 -0400 Subject: [PATCH 021/937] NULL Out Block Compressor Table Entries When Excluded Don't check about excluding `ZSTD_fast`. It's always included so that we know we can resolve downwards and hit a strategy that's present. --- lib/compress/zstd_compress.c | 191 ++++++++++++++++++++++++++++++++--- 1 file changed, 176 insertions(+), 15 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c28b43456..08bfd54c3 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2992,40 +2992,145 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { { ZSTD_compressBlock_fast /* default for 0 */, ZSTD_compressBlock_fast, +#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_doubleFast, +#endif +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_greedy, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy2, +#endif +#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btlazy2, +#endif +#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btopt, +#endif +#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btultra, - ZSTD_compressBlock_btultra2 }, +#endif +#ifdef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR + NULL +#else + ZSTD_compressBlock_btultra2 +#endif + }, { ZSTD_compressBlock_fast_extDict /* default for 0 */, ZSTD_compressBlock_fast_extDict, +#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_doubleFast_extDict, +#endif +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_greedy_extDict, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy_extDict, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy2_extDict, +#endif +#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btlazy2_extDict, +#endif +#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btopt_extDict, +#endif +#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR + NULL, + NULL +#else ZSTD_compressBlock_btultra_extDict, - ZSTD_compressBlock_btultra_extDict }, + ZSTD_compressBlock_btultra_extDict +#endif + }, { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */, ZSTD_compressBlock_fast_dictMatchState, +#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_doubleFast_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_greedy_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy2_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btlazy2_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_btopt_dictMatchState, +#endif +#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR + NULL, + NULL +#else ZSTD_compressBlock_btultra_dictMatchState, - ZSTD_compressBlock_btultra_dictMatchState }, + ZSTD_compressBlock_btultra_dictMatchState +#endif + }, { NULL /* default for 0 */, NULL, NULL, +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_greedy_dedicatedDictSearch, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy_dedicatedDictSearch, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else ZSTD_compressBlock_lazy2_dedicatedDictSearch, +#endif NULL, NULL, NULL, @@ -3038,18 +3143,74 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder); if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) { static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = { - { ZSTD_compressBlock_greedy_row, - ZSTD_compressBlock_lazy_row, - ZSTD_compressBlock_lazy2_row }, - { ZSTD_compressBlock_greedy_extDict_row, - ZSTD_compressBlock_lazy_extDict_row, - ZSTD_compressBlock_lazy2_extDict_row }, - { ZSTD_compressBlock_greedy_dictMatchState_row, - ZSTD_compressBlock_lazy_dictMatchState_row, - ZSTD_compressBlock_lazy2_dictMatchState_row }, - { ZSTD_compressBlock_greedy_dedicatedDictSearch_row, - ZSTD_compressBlock_lazy_dedicatedDictSearch_row, - ZSTD_compressBlock_lazy2_dedicatedDictSearch_row } + { +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_greedy_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy2_row +#endif + }, + { +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_greedy_extDict_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy_extDict_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy2_extDict_row +#endif + }, + { +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_greedy_dictMatchState_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy_dictMatchState_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy2_dictMatchState_row +#endif + }, + { +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_greedy_dedicatedDictSearch_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy_dedicatedDictSearch_row, +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + NULL, +#else + ZSTD_compressBlock_lazy2_dedicatedDictSearch_row +#endif + } }; DEBUGLOG(4, "Selecting a row-based matchfinder"); assert(useRowMatchFinder != ZSTD_ps_auto); From 50cdf84f58e1d8f989877db453fdfe9d63c1925e Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 19 Apr 2023 15:38:04 -0400 Subject: [PATCH 022/937] Macro-Exclude Block Compressors from Declaration/Definition --- lib/compress/zstd_compress.c | 11 ++++++ lib/compress/zstd_double_fast.c | 4 ++ lib/compress/zstd_double_fast.h | 3 ++ lib/compress/zstd_lazy.c | 68 +++++++++++++++++++++++++++++++-- lib/compress/zstd_lazy.h | 59 ++++++++++++++++++++++++++++ lib/compress/zstd_ldm.c | 2 + lib/compress/zstd_opt.c | 22 +++++++++++ lib/compress/zstd_opt.h | 19 +++++++++ 8 files changed, 185 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 08bfd54c3..52d1c1963 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4926,12 +4926,17 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, ZSTD_fillHashTable(ms, iend, dtlm, tfp); break; case ZSTD_dfast: +#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp); +#endif break; case ZSTD_greedy: case ZSTD_lazy: case ZSTD_lazy2: +#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) assert(srcSize >= HASH_READ_SIZE); if (ms->dedicatedDictSearch) { assert(ms->chainTable != NULL); @@ -4948,14 +4953,20 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, DEBUGLOG(4, "Using chain-based hash table for lazy dict"); } } +#endif break; case ZSTD_btlazy2: /* we want the dictionary table fully sorted */ case ZSTD_btopt: case ZSTD_btultra: case ZSTD_btultra2: +#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) assert(srcSize >= HASH_READ_SIZE); ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend); +#endif break; default: diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 0ad88ffc7..d4544b390 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -11,6 +11,8 @@ #include "zstd_compress_internal.h" #include "zstd_double_fast.h" +#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + static void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm) { @@ -756,3 +758,5 @@ size_t ZSTD_compressBlock_doubleFast_extDict( return ZSTD_compressBlock_doubleFast_extDict_7(ms, seqStore, rep, src, srcSize); } } + +#endif /* ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR */ diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h index 6f0047c4b..f1a86d5c4 100644 --- a/lib/compress/zstd_double_fast.h +++ b/lib/compress/zstd_double_fast.h @@ -18,6 +18,8 @@ extern "C" { #include "../common/mem.h" /* U32 */ #include "zstd_compress_internal.h" /* ZSTD_CCtx, size_t */ +#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp); @@ -31,6 +33,7 @@ size_t ZSTD_compressBlock_doubleFast_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif /* ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR */ #if defined (__cplusplus) } diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 5ba88e867..7a0affbd0 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -12,6 +12,11 @@ #include "zstd_lazy.h" #include "../common/bits.h" /* ZSTD_countTrailingZeros64 */ +#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) + #define kLazySkippingStep 8 @@ -1754,151 +1759,194 @@ _storeSequence: /* Return the last literals size */ return (size_t)(iend - anchor); } +#endif /* build exclusions */ +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState); } +#endif - +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch); } +#endif /* Row-based matchfinder */ +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState); } +#endif - +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch); } +#endif +#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) FORCE_INLINE_TEMPLATE size_t ZSTD_compressBlock_lazy_extDict_generic( ZSTD_matchState_t* ms, seqStore_t* seqStore, @@ -2101,15 +2149,18 @@ _storeSequence: /* Return the last literals size */ return (size_t)(iend - anchor); } +#endif /* build exclusions */ - +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) @@ -2117,7 +2168,9 @@ size_t ZSTD_compressBlock_lazy_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) @@ -2125,7 +2178,9 @@ size_t ZSTD_compressBlock_lazy2_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2); } +#endif +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) @@ -2133,14 +2188,18 @@ size_t ZSTD_compressBlock_btlazy2_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2); } +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) @@ -2148,10 +2207,13 @@ size_t ZSTD_compressBlock_lazy_extDict_row( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1); } +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2); } +#endif diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h index 3bde67331..7e11d0cf1 100644 --- a/lib/compress/zstd_lazy.h +++ b/lib/compress/zstd_lazy.h @@ -27,97 +27,156 @@ extern "C" { #define ZSTD_ROW_HASH_TAG_BITS 8 /* nb bits to use for the tag */ +#if !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip); void ZSTD_row_update(ZSTD_matchState_t* const ms, const BYTE* ip); void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const BYTE* const ip); void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const reducerValue); /*! used in ZSTD_reduceIndex(). preemptively increase value of ZSTD_DUBT_UNSORTED_MARK */ +#endif +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif #if defined (__cplusplus) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index ec0690ccb..8581e2356 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -246,7 +246,9 @@ static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms, break; case ZSTD_dfast: +#ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx); +#endif break; case ZSTD_greedy: diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index f02a76094..4b0fbfafe 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -12,6 +12,10 @@ #include "hist.h" #include "zstd_opt.h" +#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) #define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */ #define ZSTD_MAX_PRICE (1<<30) @@ -1360,7 +1364,9 @@ static size_t ZSTD_compressBlock_opt2( { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); } +#endif /* build exclusions */ +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1368,10 +1374,13 @@ size_t ZSTD_compressBlock_btopt( DEBUGLOG(5, "ZSTD_compressBlock_btopt"); return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_noDict); } +#endif +#if !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) /* ZSTD_initStats_ultra(): * make a first compression pass, just to seed stats with more accurate starting values. * only works on first block, with no dictionary and no ldm. @@ -1402,7 +1411,9 @@ ZSTD_initStats_ultra(ZSTD_matchState_t* ms, ms->nextToUpdate = ms->window.dictLimit; } +#endif /* build exclusions */ +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1410,7 +1421,9 @@ size_t ZSTD_compressBlock_btultra( DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize); return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1438,34 +1451,43 @@ size_t ZSTD_compressBlock_btultra2( return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict); } +#endif +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } +#endif +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict); } +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict); } +#endif /* note : no btultra2 variant for extDict nor dictMatchState, * because btultra2 is not meant to work with dictionaries diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index 342e5a311..141981da0 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -17,33 +17,52 @@ extern "C" { #include "zstd_compress_internal.h" +#if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) /* used in ZSTD_loadDictionaryContent() */ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); +#endif +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#endif /* note : no btultra2 variant for extDict nor dictMatchState, * because btultra2 is not meant to work with dictionaries From 5a75956001efbde704eedad755daae2816273a74 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 19 Apr 2023 17:53:40 -0400 Subject: [PATCH 023/937] Adjust Strategy in CParams to Avoid Using Excluded Block Compressors --- lib/compress/zstd_compress.c | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 52d1c1963..cbe10aa98 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1467,6 +1467,50 @@ ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1); assert(ZSTD_checkCParams(cPar)==0); + /* Cascade the selected strategy down to the next-highest one built into + * this binary. */ +#ifdef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_btultra2) { + cPar.strategy = ZSTD_btultra; + } +#endif +#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_btultra) { + cPar.strategy = ZSTD_btopt; + } +#endif +#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_btopt) { + cPar.strategy = ZSTD_btlazy2; + } +#endif +#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_btlazy2) { + cPar.strategy = ZSTD_lazy2; + } +#endif +#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_lazy2) { + cPar.strategy = ZSTD_lazy; + } +#endif +#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_lazy) { + cPar.strategy = ZSTD_greedy; + } +#endif +#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_greedy) { + cPar.strategy = ZSTD_dfast; + } +#endif +#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR + if (cPar.strategy == ZSTD_dfast) { + cPar.strategy = ZSTD_fast; + cPar.targetLength = 0; + } +#endif + switch (mode) { case ZSTD_cpm_unknown: case ZSTD_cpm_noAttachDict: From 16bbd7437cf67a748ac22349a3ff974a518a3d66 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Thu, 20 Apr 2023 11:46:04 -0400 Subject: [PATCH 024/937] Avoid Ratio Regression Tests When Compressors are Excluded --- tests/fuzzer.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index b049a9e09..c17cdcd4a 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -2426,6 +2426,15 @@ static int basicUnitTests(U32 const seed, double compressibility) } } DISPLAYLEVEL(3, "OK \n"); +#if !defined(ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR) \ + && !defined(ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR) \ + && !defined(ZSTD_EXCLUDE_DFAST_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) \ + && !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) /* Note : these tests should be replaced by proper regression tests, * but existing ones do not focus on small data + dictionary + all levels. */ @@ -2524,6 +2533,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(4, "compression efficiency tests OK \n"); } +#endif ZSTD_freeCCtx(ctxOrig); ZSTD_freeCCtx(ctxDuplicated); From 6761e1c949b99050f79a90a333c3432ba7cf3f22 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Thu, 20 Apr 2023 11:46:29 -0400 Subject: [PATCH 025/937] Tweak Ultra/Opt Guards --- lib/compress/zstd_opt.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 4b0fbfafe..2856398cf 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1350,21 +1350,26 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ /* Return the last literals size */ return (size_t)(iend - anchor); } +#endif /* build exclusions */ +#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt0( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode); } +#endif +#if !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ + || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) static size_t ZSTD_compressBlock_opt2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); } -#endif /* build exclusions */ +#endif #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( @@ -1379,8 +1384,7 @@ size_t ZSTD_compressBlock_btopt( -#if !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) +#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR /* ZSTD_initStats_ultra(): * make a first compression pass, just to seed stats with more accurate starting values. * only works on first block, with no dictionary and no ldm. From b12e8cb3e73c2eb0d176eb9b4dd0ff943b766242 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Thu, 20 Apr 2023 11:53:23 -0400 Subject: [PATCH 026/937] Merge Ultra and Ultra2 Exclusion Ultra2 does not exist for dict compression, and so uses ultra. So ultra must be present if ultra2 is. --- lib/compress/zstd_compress.c | 12 +++--------- lib/compress/zstd_opt.c | 10 +++------- lib/compress/zstd_opt.h | 5 +---- tests/fuzzer.c | 3 +-- 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index cbe10aa98..c51151980 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1469,12 +1469,10 @@ ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar, /* Cascade the selected strategy down to the next-highest one built into * this binary. */ -#ifdef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR +#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR if (cPar.strategy == ZSTD_btultra2) { cPar.strategy = ZSTD_btultra; } -#endif -#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR if (cPar.strategy == ZSTD_btultra) { cPar.strategy = ZSTD_btopt; } @@ -3068,12 +3066,9 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS #endif #ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR NULL, -#else - ZSTD_compressBlock_btultra, -#endif -#ifdef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR NULL #else + ZSTD_compressBlock_btultra, ZSTD_compressBlock_btultra2 #endif }, @@ -5006,8 +5001,7 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, case ZSTD_btultra2: #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) assert(srcSize >= HASH_READ_SIZE); ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend); #endif diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 2856398cf..edcd65e21 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -14,8 +14,7 @@ #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) #define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */ #define ZSTD_MAX_PRICE (1<<30) @@ -1361,8 +1360,7 @@ static size_t ZSTD_compressBlock_opt0( } #endif -#if !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) @@ -1384,7 +1382,7 @@ size_t ZSTD_compressBlock_btopt( -#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR +#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR /* ZSTD_initStats_ultra(): * make a first compression pass, just to seed stats with more accurate starting values. * only works on first block, with no dictionary and no ldm. @@ -1425,9 +1423,7 @@ size_t ZSTD_compressBlock_btultra( DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize); return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict); } -#endif -#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index 141981da0..e503df32b 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -19,8 +19,7 @@ extern "C" { #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - || !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) + || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) /* used in ZSTD_loadDictionaryContent() */ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); #endif @@ -34,8 +33,6 @@ size_t ZSTD_compressBlock_btopt( size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#endif -#ifndef ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index c17cdcd4a..4a68ff731 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -2433,8 +2433,7 @@ static int basicUnitTests(U32 const seed, double compressibility) && !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ && !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \ && !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ - && !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) \ - && !defined(ZSTD_EXCLUDE_BTULTRA2_BLOCK_COMPRESSOR) + && !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) /* Note : these tests should be replaced by proper regression tests, * but existing ones do not focus on small data + dictionary + all levels. */ From 39b7946b95dc4359d7a9546ede906489682dd0d9 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Fri, 21 Apr 2023 11:32:41 -0400 Subject: [PATCH 027/937] Define Macros for Possibly-Present Functions; Use Them Rather than Ifdef Guards --- lib/compress/zstd_compress.c | 225 ++++++-------------------------- lib/compress/zstd_double_fast.h | 8 ++ lib/compress/zstd_lazy.h | 81 ++++++++++++ lib/compress/zstd_opt.h | 21 +++ 4 files changed, 149 insertions(+), 186 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c51151980..541b776f1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3034,142 +3034,43 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { { ZSTD_compressBlock_fast /* default for 0 */, ZSTD_compressBlock_fast, -#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_doubleFast, -#endif -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2, -#endif -#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btlazy2, -#endif -#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btopt, -#endif -#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR - NULL, - NULL -#else - ZSTD_compressBlock_btultra, - ZSTD_compressBlock_btultra2 -#endif + ZSTD_COMPRESSBLOCK_DOUBLEFAST, + ZSTD_COMPRESSBLOCK_GREEDY, + ZSTD_COMPRESSBLOCK_LAZY, + ZSTD_COMPRESSBLOCK_LAZY2, + ZSTD_COMPRESSBLOCK_BTLAZY2, + ZSTD_COMPRESSBLOCK_BTOPT, + ZSTD_COMPRESSBLOCK_BTULTRA, + ZSTD_COMPRESSBLOCK_BTULTRA2 }, { ZSTD_compressBlock_fast_extDict /* default for 0 */, ZSTD_compressBlock_fast_extDict, -#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_doubleFast_extDict, -#endif -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_extDict, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_extDict, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_extDict, -#endif -#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btlazy2_extDict, -#endif -#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btopt_extDict, -#endif -#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR - NULL, - NULL -#else - ZSTD_compressBlock_btultra_extDict, - ZSTD_compressBlock_btultra_extDict -#endif + ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT, + ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT, + ZSTD_COMPRESSBLOCK_LAZY_EXTDICT, + ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT, + ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT, + ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT, + ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT, + ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT }, { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */, ZSTD_compressBlock_fast_dictMatchState, -#ifdef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_doubleFast_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btlazy2_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_btopt_dictMatchState, -#endif -#ifdef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR - NULL, - NULL -#else - ZSTD_compressBlock_btultra_dictMatchState, - ZSTD_compressBlock_btultra_dictMatchState -#endif + ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE, + ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE }, { NULL /* default for 0 */, NULL, NULL, -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_dedicatedDictSearch, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_dedicatedDictSearch, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_dedicatedDictSearch, -#endif + ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH, + ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH, + ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH, NULL, NULL, NULL, @@ -3183,72 +3084,24 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) { static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = { { -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_row -#endif + ZSTD_COMPRESSBLOCK_GREEDY_ROW, + ZSTD_COMPRESSBLOCK_LAZY_ROW, + ZSTD_COMPRESSBLOCK_LAZY2_ROW }, { -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_extDict_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_extDict_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_extDict_row -#endif + ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW, + ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW, + ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW }, { -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_dictMatchState_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_dictMatchState_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_dictMatchState_row -#endif + ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW, + ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW, + ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW }, { -#ifdef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_greedy_dedicatedDictSearch_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy_dedicatedDictSearch_row, -#endif -#ifdef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR - NULL, -#else - ZSTD_compressBlock_lazy2_dedicatedDictSearch_row -#endif + ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW, + ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW, + ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW } }; DEBUGLOG(4, "Selecting a row-based matchfinder"); diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h index f1a86d5c4..ce6ed8c97 100644 --- a/lib/compress/zstd_double_fast.h +++ b/lib/compress/zstd_double_fast.h @@ -23,6 +23,7 @@ extern "C" { void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp); + size_t ZSTD_compressBlock_doubleFast( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); @@ -33,6 +34,13 @@ size_t ZSTD_compressBlock_doubleFast_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST ZSTD_compressBlock_doubleFast +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE ZSTD_compressBlock_doubleFast_dictMatchState +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT ZSTD_compressBlock_doubleFast_extDict +#else +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST NULL +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT NULL #endif /* ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR */ #if defined (__cplusplus) diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h index 7e11d0cf1..da320030f 100644 --- a/lib/compress/zstd_lazy.h +++ b/lib/compress/zstd_lazy.h @@ -43,139 +43,220 @@ void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const redu size_t ZSTD_compressBlock_btlazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTLAZY2 ZSTD_compressBlock_btlazy2 +#else +#define ZSTD_COMPRESSBLOCK_BTLAZY2 NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2 ZSTD_compressBlock_lazy2 +#else +#define ZSTD_COMPRESSBLOCK_LAZY2 NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY ZSTD_compressBlock_lazy +#else +#define ZSTD_COMPRESSBLOCK_LAZY NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY ZSTD_compressBlock_greedy +#else +#define ZSTD_COMPRESSBLOCK_GREEDY NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_ROW ZSTD_compressBlock_lazy2_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_ROW ZSTD_compressBlock_lazy_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY_ROW NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_ROW ZSTD_compressBlock_greedy_row +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_ROW NULL #endif #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE ZSTD_compressBlock_btlazy2_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE ZSTD_compressBlock_lazy2_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE ZSTD_compressBlock_lazy_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE ZSTD_compressBlock_greedy_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy2_dictMatchState_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy_dictMatchState_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW ZSTD_compressBlock_greedy_dictMatchState_row +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy2_dedicatedDictSearch +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy_dedicatedDictSearch +#else +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH ZSTD_compressBlock_greedy_dedicatedDictSearch +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy2_dedicatedDictSearch_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy_dedicatedDictSearch_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_greedy_dedicatedDictSearch_row +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT ZSTD_compressBlock_greedy_extDict +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT ZSTD_compressBlock_lazy_extDict +#else +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT ZSTD_compressBlock_lazy2_extDict +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT NULL #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW ZSTD_compressBlock_greedy_extDict_row +#else +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW ZSTD_compressBlock_lazy_extDict_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW NULL #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW ZSTD_compressBlock_lazy2_extDict_row +#else +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW NULL #endif #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT ZSTD_compressBlock_btlazy2_extDict +#else +#define ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT NULL #endif diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index e503df32b..694e31765 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -28,14 +28,23 @@ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); size_t ZSTD_compressBlock_btopt( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTOPT ZSTD_compressBlock_btopt +#else +#define ZSTD_COMPRESSBLOCK_BTOPT NULL #endif + #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTULTRA ZSTD_compressBlock_btultra size_t ZSTD_compressBlock_btultra2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTULTRA2 ZSTD_compressBlock_btultra2 +#else +#define ZSTD_COMPRESSBLOCK_BTULTRA NULL +#define ZSTD_COMPRESSBLOCK_BTULTRA2 NULL #endif @@ -43,22 +52,34 @@ size_t ZSTD_compressBlock_btultra2( size_t ZSTD_compressBlock_btopt_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE ZSTD_compressBlock_btopt_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE ZSTD_compressBlock_btultra_dictMatchState +#else +#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE NULL #endif #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT ZSTD_compressBlock_btopt_extDict +#else +#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT NULL #endif #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT ZSTD_compressBlock_btultra_extDict +#else +#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT NULL #endif /* note : no btultra2 variant for extDict nor dictMatchState, From bae174960b4abd8cefadf23f323b2c82829538e6 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Fri, 21 Apr 2023 16:14:11 -0400 Subject: [PATCH 028/937] Add ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP Build Variable --- lib/libzstd.mk | 6 ++++++ tests/playTests.sh | 10 ++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index 5e11d5d29..0b1e03907 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -47,6 +47,8 @@ endif # Assembly support ZSTD_NO_ASM ?= 0 +ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP ?= 0 + ################################################################## # libzstd helpers ################################################################## @@ -178,6 +180,10 @@ ifneq ($(ZSTD_LEGACY_MULTITHREADED_API), 0) CFLAGS += -DZSTD_LEGACY_MULTITHREADED_API endif +ifneq ($(ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP), 0) + CFLAGS += -DZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR +endif + ifneq ($(ZSTD_LEGACY_SUPPORT), 0) ifeq ($(shell test $(ZSTD_LEGACY_SUPPORT) -lt 8; echo $$?), 0) ZSTD_LEGACY_FILES += $(shell ls $(LIBZSTD)/legacy/*.c | $(GREP) 'v0[$(ZSTD_LEGACY_SUPPORT)-7]') diff --git a/tests/playTests.sh b/tests/playTests.sh index 5f595f611..718398f82 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1708,8 +1708,14 @@ zstd --patch-from=tmp_dict -r tmp_dir && die rm -rf tmp* println "\n===> patch-from long mode trigger larger file test" -datagen -g5000000 > tmp_dict -datagen -g5000000 > tmp_patch +if [ "$ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP" -eq "1" ]; then + # if binary tree strategies are excluded, the threshold is different + datagen -g10000000 > tmp_dict + datagen -g10000000 > tmp_patch +else + datagen -g5000000 > tmp_dict + datagen -g5000000 > tmp_patch +fi zstd -15 --patch-from=tmp_dict tmp_patch 2>&1 | grep "long mode automatically triggered" rm -rf tmp* From 698af84fcf8bdcfa3db4936a88e84c354331a84a Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Fri, 21 Apr 2023 16:14:27 -0400 Subject: [PATCH 029/937] Add CI Test for Excluding Matchfinders --- .github/workflows/dev-short-tests.yml | 1 + tests/playTests.sh | 34 ++++++++++++++------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index d6f2db886..566c84d01 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -348,6 +348,7 @@ jobs: make clean && make check MOREFLAGS="-Werror -DHUF_FORCE_DECOMPRESS_X2 -DZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG" make clean && make -j all MOREFLAGS="-Werror -DZSTD_NO_INLINE -DZSTD_STRIP_ERROR_STRINGS" make clean && make check MOREFLAGS="-Werror -DZSTD_NO_INLINE -DZSTD_STRIP_ERROR_STRINGS" + make clean && make check ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP=1 MOREFLAGS="-Werror" dynamic-bmi2: runs-on: ubuntu-latest diff --git a/tests/playTests.sh b/tests/playTests.sh index 718398f82..f51776170 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1602,22 +1602,24 @@ roundTripTest -g1M -P50 "1 --single-thread --long=29" " --long=28 --memory=512MB roundTripTest -g1M -P50 "1 --single-thread --long=29" " --zstd=wlog=28 --memory=512MB" -println "\n===> zstd long distance matching with optimal parser compressed size tests " -optCSize16=$(datagen -g511K | zstd -16 -c | wc -c) -longCSize16=$(datagen -g511K | zstd -16 --long -c | wc -c) -optCSize19=$(datagen -g2M | zstd -19 -c | wc -c) -longCSize19=$(datagen -g2M | zstd -19 --long -c | wc -c) -optCSize19wlog23=$(datagen -g2M | zstd -19 -c --zstd=wlog=23 | wc -c) -longCSize19wlog23=$(datagen -g2M | zstd -19 -c --long=23 | wc -c) -if [ "$longCSize16" -gt "$optCSize16" ]; then - echo using --long on compression level 16 should not cause compressed size regression - exit 1 -elif [ "$longCSize19" -gt "$optCSize19" ]; then - echo using --long on compression level 19 should not cause compressed size regression - exit 1 -elif [ "$longCSize19wlog23" -gt "$optCSize19wlog23" ]; then - echo using --long on compression level 19 with wLog=23 should not cause compressed size regression - exit 1 +if [ "$ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP" -ne "1" ]; then + println "\n===> zstd long distance matching with optimal parser compressed size tests " + optCSize16=$(datagen -g511K | zstd -16 -c | wc -c) + longCSize16=$(datagen -g511K | zstd -16 --long -c | wc -c) + optCSize19=$(datagen -g2M | zstd -19 -c | wc -c) + longCSize19=$(datagen -g2M | zstd -19 --long -c | wc -c) + optCSize19wlog23=$(datagen -g2M | zstd -19 -c --zstd=wlog=23 | wc -c) + longCSize19wlog23=$(datagen -g2M | zstd -19 -c --long=23 | wc -c) + if [ "$longCSize16" -gt "$optCSize16" ]; then + echo using --long on compression level 16 should not cause compressed size regression + exit 1 + elif [ "$longCSize19" -gt "$optCSize19" ]; then + echo using --long on compression level 19 should not cause compressed size regression + exit 1 + elif [ "$longCSize19wlog23" -gt "$optCSize19wlog23" ]; then + echo using --long on compression level 19 with wLog=23 should not cause compressed size regression + exit 1 + fi fi println "\n===> zstd asyncio tests " From f242f5be8f0d57fb9b49f22f35032953072471cc Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 24 Apr 2023 10:40:52 -0400 Subject: [PATCH 030/937] Re-Order Lazy Declarations; Minimize ifndefs --- lib/compress/zstd_lazy.h | 267 +++++++++++++++------------------------ 1 file changed, 101 insertions(+), 166 deletions(-) diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h index da320030f..3635813bd 100644 --- a/lib/compress/zstd_lazy.h +++ b/lib/compress/zstd_lazy.h @@ -39,223 +39,158 @@ void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const B void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const reducerValue); /*! used in ZSTD_reduceIndex(). preemptively increase value of ZSTD_DUBT_UNSORTED_MARK */ #endif -#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btlazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTLAZY2 ZSTD_compressBlock_btlazy2 -#else -#define ZSTD_COMPRESSBLOCK_BTLAZY2 NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2 ZSTD_compressBlock_lazy2 -#else -#define ZSTD_COMPRESSBLOCK_LAZY2 NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY ZSTD_compressBlock_lazy -#else -#define ZSTD_COMPRESSBLOCK_LAZY NULL -#endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY ZSTD_compressBlock_greedy -#else -#define ZSTD_COMPRESSBLOCK_GREEDY NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_ROW ZSTD_compressBlock_lazy2_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_ROW ZSTD_compressBlock_lazy_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_ROW ZSTD_compressBlock_greedy_row -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_ROW NULL -#endif - -#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE ZSTD_compressBlock_btlazy2_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE ZSTD_compressBlock_lazy2_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE ZSTD_compressBlock_lazy_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE ZSTD_compressBlock_greedy_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy2_dictMatchState_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy_dictMatchState_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW ZSTD_compressBlock_greedy_dictMatchState_row -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW NULL -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy2_dedicatedDictSearch -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy_dedicatedDictSearch -#else -#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH ZSTD_compressBlock_greedy_dedicatedDictSearch -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy2_dedicatedDictSearch_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy_dedicatedDictSearch_row -#else -#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_greedy_dedicatedDictSearch_row -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW NULL -#endif - -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT ZSTD_compressBlock_greedy_extDict -#else -#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT ZSTD_compressBlock_lazy_extDict -#else -#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT NULL -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT ZSTD_compressBlock_lazy2_extDict -#else -#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT NULL -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); + +#define ZSTD_COMPRESSBLOCK_GREEDY ZSTD_compressBlock_greedy +#define ZSTD_COMPRESSBLOCK_GREEDY_ROW ZSTD_compressBlock_greedy_row +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE ZSTD_compressBlock_greedy_dictMatchState +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW ZSTD_compressBlock_greedy_dictMatchState_row +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH ZSTD_compressBlock_greedy_dedicatedDictSearch +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_greedy_dedicatedDictSearch_row +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT ZSTD_compressBlock_greedy_extDict #define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW ZSTD_compressBlock_greedy_extDict_row #else +#define ZSTD_COMPRESSBLOCK_GREEDY NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_ROW NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_DICTMATCHSTATE_ROW NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_DEDICATEDDICTSEARCH_ROW NULL +#define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT NULL #define ZSTD_COMPRESSBLOCK_GREEDY_EXTDICT_ROW NULL #endif + #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_lazy( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_dictMatchState_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy_extDict( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); + +#define ZSTD_COMPRESSBLOCK_LAZY ZSTD_compressBlock_lazy +#define ZSTD_COMPRESSBLOCK_LAZY_ROW ZSTD_compressBlock_lazy_row +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE ZSTD_compressBlock_lazy_dictMatchState +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy_dictMatchState_row +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy_dedicatedDictSearch +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy_dedicatedDictSearch_row +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT ZSTD_compressBlock_lazy_extDict #define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW ZSTD_compressBlock_lazy_extDict_row #else +#define ZSTD_COMPRESSBLOCK_LAZY NULL +#define ZSTD_COMPRESSBLOCK_LAZY_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_LAZY_DICTMATCHSTATE_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH NULL +#define ZSTD_COMPRESSBLOCK_LAZY_DEDICATEDDICTSEARCH_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT NULL #define ZSTD_COMPRESSBLOCK_LAZY_EXTDICT_ROW NULL #endif + #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_lazy2( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_dictMatchState_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_lazy2_extDict( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_extDict_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); + +#define ZSTD_COMPRESSBLOCK_LAZY2 ZSTD_compressBlock_lazy2 +#define ZSTD_COMPRESSBLOCK_LAZY2_ROW ZSTD_compressBlock_lazy2_row +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE ZSTD_compressBlock_lazy2_dictMatchState +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW ZSTD_compressBlock_lazy2_dictMatchState_row +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH ZSTD_compressBlock_lazy2_dedicatedDictSearch +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW ZSTD_compressBlock_lazy2_dedicatedDictSearch_row +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT ZSTD_compressBlock_lazy2_extDict #define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW ZSTD_compressBlock_lazy2_extDict_row #else +#define ZSTD_COMPRESSBLOCK_LAZY2 NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_DICTMATCHSTATE_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW NULL +#define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT NULL #define ZSTD_COMPRESSBLOCK_LAZY2_EXTDICT_ROW NULL #endif + #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_btlazy2( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_btlazy2_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); size_t ZSTD_compressBlock_btlazy2_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); + +#define ZSTD_COMPRESSBLOCK_BTLAZY2 ZSTD_compressBlock_btlazy2 +#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE ZSTD_compressBlock_btlazy2_dictMatchState #define ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT ZSTD_compressBlock_btlazy2_extDict #else +#define ZSTD_COMPRESSBLOCK_BTLAZY2 NULL +#define ZSTD_COMPRESSBLOCK_BTLAZY2_DICTMATCHSTATE NULL #define ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT NULL #endif From b7add1dd67f24124f2ebc722effb322fb77ee92b Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 24 Apr 2023 11:50:01 -0400 Subject: [PATCH 031/937] Abort if Unsupported Parameters Used --- lib/compress/zstd_compress.c | 6 ++++++ lib/compress/zstd_ldm.c | 2 ++ 2 files changed, 8 insertions(+) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 541b776f1..09f048239 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4820,6 +4820,8 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, case ZSTD_dfast: #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR ZSTD_fillDoubleHashTable(ms, iend, dtlm, tfp); +#else + assert(0); /* shouldn't be called: cparams should've been adjusted. */ #endif break; @@ -4845,6 +4847,8 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, DEBUGLOG(4, "Using chain-based hash table for lazy dict"); } } +#else + assert(0); /* shouldn't be called: cparams should've been adjusted. */ #endif break; @@ -4857,6 +4861,8 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) assert(srcSize >= HASH_READ_SIZE); ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend); +#else + assert(0); /* shouldn't be called: cparams should've been adjusted. */ #endif break; diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 8581e2356..eda45816e 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -248,6 +248,8 @@ static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms, case ZSTD_dfast: #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx); +#else + assert(0); /* shouldn't be called: cparams should've been adjusted. */ #endif break; From d09f195ceb774bc0b3b7c764ddb907bc3de8c69e Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 24 Apr 2023 14:50:54 -0400 Subject: [PATCH 032/937] Remove blockCompressor NULL Checks --- lib/compress/zstd_compress.c | 2 -- lib/compress/zstd_ldm.c | 2 -- 2 files changed, 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 09f048239..521e5e5d6 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3344,7 +3344,6 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) "External sequence producer returned error code %lu. Falling back to internal parser.", (unsigned long)nbExternalSeqs ); - RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize); } } } else { /* not long range mode and no external matchfinder */ @@ -3353,7 +3352,6 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) zc->appliedParams.useRowMatchFinder, dictMode); ms->ldmSeqStore = NULL; - RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize); } { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize; diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index eda45816e..01c1f75aa 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -676,8 +676,6 @@ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, /* Input positions */ BYTE const* ip = istart; - RETURN_ERROR_IF(blockCompressor == NULL, parameter_combination_unsupported, "Got NULL block compressor!"); - DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize); /* If using opt parser, use LDMs only as candidates rather than always accepting them */ if (cParams->strategy >= ZSTD_btopt) { From eb9227935ead3eff349dcdde296543ff097deae0 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 24 Apr 2023 16:53:30 -0400 Subject: [PATCH 033/937] Also Reorganize Zstd Opt Declarations --- lib/compress/zstd_opt.h | 63 ++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 38 deletions(-) diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index 694e31765..d4e711315 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -28,63 +28,50 @@ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); size_t ZSTD_compressBlock_btopt( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); +size_t ZSTD_compressBlock_btopt_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); +size_t ZSTD_compressBlock_btopt_extDict( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); + #define ZSTD_COMPRESSBLOCK_BTOPT ZSTD_compressBlock_btopt +#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE ZSTD_compressBlock_btopt_dictMatchState +#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT ZSTD_compressBlock_btopt_extDict #else #define ZSTD_COMPRESSBLOCK_BTOPT NULL +#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT NULL #endif #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTULTRA ZSTD_compressBlock_btultra -size_t ZSTD_compressBlock_btultra2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTULTRA2 ZSTD_compressBlock_btultra2 -#else -#define ZSTD_COMPRESSBLOCK_BTULTRA NULL -#define ZSTD_COMPRESSBLOCK_BTULTRA2 NULL -#endif - - -#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btopt_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE ZSTD_compressBlock_btopt_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_BTOPT_DICTMATCHSTATE NULL -#endif -#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE ZSTD_compressBlock_btultra_dictMatchState -#else -#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE NULL -#endif - -#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btopt_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT ZSTD_compressBlock_btopt_extDict -#else -#define ZSTD_COMPRESSBLOCK_BTOPT_EXTDICT NULL -#endif -#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT ZSTD_compressBlock_btultra_extDict -#else -#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT NULL -#endif /* note : no btultra2 variant for extDict nor dictMatchState, * because btultra2 is not meant to work with dictionaries * and is only specific for the first block (no prefix) */ +size_t ZSTD_compressBlock_btultra2( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize); + +#define ZSTD_COMPRESSBLOCK_BTULTRA ZSTD_compressBlock_btultra +#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE ZSTD_compressBlock_btultra_dictMatchState +#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT ZSTD_compressBlock_btultra_extDict +#define ZSTD_COMPRESSBLOCK_BTULTRA2 ZSTD_compressBlock_btultra2 +#else +#define ZSTD_COMPRESSBLOCK_BTULTRA NULL +#define ZSTD_COMPRESSBLOCK_BTULTRA_DICTMATCHSTATE NULL +#define ZSTD_COMPRESSBLOCK_BTULTRA_EXTDICT NULL +#define ZSTD_COMPRESSBLOCK_BTULTRA2 NULL +#endif #if defined (__cplusplus) } From cc1ffe0bd6561128f39cc6c673aa75c91a925b68 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Thu, 4 May 2023 12:20:02 -0400 Subject: [PATCH 034/937] Add Documentation to lib/README.md --- lib/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/README.md b/lib/README.md index c3b5d1817..2da16647a 100644 --- a/lib/README.md +++ b/lib/README.md @@ -119,6 +119,12 @@ The file structure is designed to make this selection manually achievable for an binary is achieved by using `HUF_FORCE_DECOMPRESS_X1` and `ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT` (implied by `ZSTD_LIB_MINIFY`). + On the compressor side, Zstd's compression levels map to several internal + strategies. In environments where the higher compression levels aren't used, + it is possible to exclude all but the fastest strategy with + `ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP=1`. (Note that this will change + the behavior of the default compression level.) + For squeezing the last ounce of size out, you can also define `ZSTD_NO_INLINE`, which disables inlining, and `ZSTD_STRIP_ERROR_STRINGS`, which removes the error messages that are otherwise returned by From 5490c75ddaae98010985618832ab55ed7b98dbed Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Thu, 4 May 2023 12:31:41 -0400 Subject: [PATCH 035/937] Also Allow/Document/Test Excluding dfast and Up --- .github/workflows/dev-short-tests.yml | 1 + lib/README.md | 5 ++++- lib/libzstd.mk | 5 +++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 566c84d01..9474190ff 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -349,6 +349,7 @@ jobs: make clean && make -j all MOREFLAGS="-Werror -DZSTD_NO_INLINE -DZSTD_STRIP_ERROR_STRINGS" make clean && make check MOREFLAGS="-Werror -DZSTD_NO_INLINE -DZSTD_STRIP_ERROR_STRINGS" make clean && make check ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP=1 MOREFLAGS="-Werror" + make clean && make check ZSTD_LIB_EXCLUDE_COMPRESSORS_GREEDY_AND_UP=1 MOREFLAGS="-Werror" dynamic-bmi2: runs-on: ubuntu-latest diff --git a/lib/README.md b/lib/README.md index 2da16647a..479820933 100644 --- a/lib/README.md +++ b/lib/README.md @@ -123,7 +123,10 @@ The file structure is designed to make this selection manually achievable for an strategies. In environments where the higher compression levels aren't used, it is possible to exclude all but the fastest strategy with `ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP=1`. (Note that this will change - the behavior of the default compression level.) + the behavior of the default compression level.) Or if you want to retain the + default compressor as well, you can set + `ZSTD_LIB_EXCLUDE_COMPRESSORS_GREEDY_AND_UP=1`, at the cost of an additional + ~20KB or so. For squeezing the last ounce of size out, you can also define `ZSTD_NO_INLINE`, which disables inlining, and `ZSTD_STRIP_ERROR_STRINGS`, diff --git a/lib/libzstd.mk b/lib/libzstd.mk index 0b1e03907..2c47ecdfa 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -48,6 +48,7 @@ endif ZSTD_NO_ASM ?= 0 ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP ?= 0 +ZSTD_LIB_EXCLUDE_COMPRESSORS_GREEDY_AND_UP ?= 0 ################################################################## # libzstd helpers @@ -182,6 +183,10 @@ endif ifneq ($(ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP), 0) CFLAGS += -DZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR +else +ifneq ($(ZSTD_LIB_EXCLUDE_COMPRESSORS_GREEDY_AND_UP), 0) + CFLAGS += -DZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR -DZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR +endif endif ifneq ($(ZSTD_LEGACY_SUPPORT), 0) From 59c7b2a49247de8d2335e3a492135e9396ce8e84 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 22 May 2023 12:37:03 -0400 Subject: [PATCH 036/937] Reorder Definitions in zstd_lazy.c to Group Under Macro Guards --- lib/compress/zstd_lazy.c | 257 +++++++++++++++++---------------------- 1 file changed, 109 insertions(+), 148 deletions(-) diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 7a0affbd0..834520fd7 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1762,21 +1762,47 @@ _storeSequence: #endif /* build exclusions */ -#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btlazy2( +#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_greedy( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict); + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict); } -#endif -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2( +size_t ZSTD_compressBlock_greedy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict); + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState); +} + +size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch); +} + +size_t ZSTD_compressBlock_greedy_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict); +} + +size_t ZSTD_compressBlock_greedy_dictMatchState_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState); +} + +size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch); } #endif @@ -1787,145 +1813,35 @@ size_t ZSTD_compressBlock_lazy( { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict); } -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict); -} -#endif - -#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState); } -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch); } -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch); -} -#endif - -/* Row-based matchfinder */ -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict); } -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dictMatchState_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState); } -#endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) @@ -1934,12 +1850,63 @@ size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( } #endif -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( +#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_lazy2( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { - return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch); + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict); +} + +size_t ZSTD_compressBlock_lazy2_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState); +} + +size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch); +} + +size_t ZSTD_compressBlock_lazy2_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict); +} + +size_t ZSTD_compressBlock_lazy2_dictMatchState_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState); +} + +size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch); +} +#endif + +#ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_btlazy2( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict); +} + +size_t ZSTD_compressBlock_btlazy2_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState); } #endif @@ -2158,6 +2125,13 @@ size_t ZSTD_compressBlock_greedy_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0); } + +size_t ZSTD_compressBlock_greedy_extDict_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0); +} #endif #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR @@ -2168,6 +2142,14 @@ size_t ZSTD_compressBlock_lazy_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1); } + +size_t ZSTD_compressBlock_lazy_extDict_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) + +{ + return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1); +} #endif #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR @@ -2178,6 +2160,13 @@ size_t ZSTD_compressBlock_lazy2_extDict( { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2); } + +size_t ZSTD_compressBlock_lazy2_extDict_row( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + void const* src, size_t srcSize) +{ + return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2); +} #endif #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR @@ -2189,31 +2178,3 @@ size_t ZSTD_compressBlock_btlazy2_extDict( return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2); } #endif - -#ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_greedy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) - -{ - return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1); -} -#endif - -#ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_lazy2_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - void const* src, size_t srcSize) -{ - return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2); -} -#endif From 1b65803fe7f506f5551d3946dc74f9fef8b87f71 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Mon, 22 May 2023 12:41:48 -0400 Subject: [PATCH 037/937] Reorder Definitions in zstd_opt.c to Group Under Macro Guards (Slightly) --- lib/compress/zstd_opt.c | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index edcd65e21..3d54e21ae 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1413,9 +1413,7 @@ ZSTD_initStats_ultra(ZSTD_matchState_t* ms, ms->nextToUpdate = ms->window.dictLimit; } -#endif /* build exclusions */ -#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1460,18 +1458,7 @@ size_t ZSTD_compressBlock_btopt_dictMatchState( { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } -#endif -#ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR -size_t ZSTD_compressBlock_btultra_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - const void* src, size_t srcSize) -{ - return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); -} -#endif - -#ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1481,6 +1468,13 @@ size_t ZSTD_compressBlock_btopt_extDict( #endif #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR +size_t ZSTD_compressBlock_btultra_dictMatchState( + ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + const void* src, size_t srcSize) +{ + return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); +} + size_t ZSTD_compressBlock_btultra_extDict( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) From 1b994cbc57869cc73e6434acb639aab648fcc678 Mon Sep 17 00:00:00 2001 From: Duncan Horn Date: Mon, 1 May 2023 14:29:52 -0700 Subject: [PATCH 038/937] Get zstd working with ARM64EC on Windows --- lib/common/compiler.h | 2 +- lib/common/xxhash.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 73f8d0199..79e773c0f 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -112,7 +112,7 @@ # define PREFETCH_L1(ptr) (void)(ptr) /* disabled */ # define PREFETCH_L2(ptr) (void)(ptr) /* disabled */ #else -# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) /* _mm_prefetch() is not defined outside of x86/x64 */ +# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) && !defined(_M_ARM64EC) /* _mm_prefetch() is not defined outside of x86/x64 */ # include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ # define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) # define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1) diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h index b8b73290b..69572117a 100644 --- a/lib/common/xxhash.h +++ b/lib/common/xxhash.h @@ -3166,7 +3166,7 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b) #if defined(XXH_NO_PREFETCH) # define XXH_PREFETCH(ptr) (void)(ptr) /* disabled */ #else -# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) /* _mm_prefetch() not defined outside of x86/x64 */ +# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) && !defined(_M_ARM64EC) /* _mm_prefetch() not defined outside of x86/x64 */ # include /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */ # define XXH_PREFETCH(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0) # elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) ) From d01a2c69296cff9bd052b797b2be1055a96cd644 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 25 May 2023 14:35:49 -0700 Subject: [PATCH 039/937] Fix UBSAN issue (zero addition to NULL) Fix UBSAN issue that came up internally. --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 521e5e5d6..19446b63f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -5951,7 +5951,7 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, if (zcs->appliedParams.inBufferMode == ZSTD_bm_stable) { assert(input->pos >= zcs->stableIn_notConsumed); input->pos -= zcs->stableIn_notConsumed; - ip -= zcs->stableIn_notConsumed; + if (ip) ip -= zcs->stableIn_notConsumed; zcs->stableIn_notConsumed = 0; } if (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered) { From 5059618295bc67f4f70eb6f12e6cf57b8d3de141 Mon Sep 17 00:00:00 2001 From: Tao He Date: Thu, 25 May 2023 22:48:01 +0800 Subject: [PATCH 040/937] Add options in Makefile to cmake Signed-off-by: Tao He --- build/cmake/lib/CMakeLists.txt | 64 +++++++++++++++++++++++++++------- 1 file changed, 51 insertions(+), 13 deletions(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 30349586b..457b54797 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -12,6 +12,22 @@ project(libzstd C ASM) set(CMAKE_INCLUDE_CURRENT_DIR TRUE) option(ZSTD_BUILD_STATIC "BUILD STATIC LIBRARIES" ON) option(ZSTD_BUILD_SHARED "BUILD SHARED LIBRARIES" ON) +option(ZSTD_BUILD_COMPRESSION "BUILD COMPRESSION MODULE" ON) +option(ZSTD_BUILD_DECOMPRESSION "BUILD DECOMPRESSION MODUEL" ON) +option(ZSTD_BUILD_DICTBUILDER "BUILD DICTBUILDER MODULE" ON) +option(ZSTD_BUILD_DEPRECATED "BUILD DEPRECATED MODULE" OFF) + +set(ZSTDLIB_VISIBLE "" CACHE STRING "Visiblity for ZSTDLIB API") +set(ZSTDERRORLIB_VISIBLE "" CACHE STRING "Visiblity for ZSTDERRORLIB_VISIBLE API") +set(ZDICTLIB_VISIBLE "" CACHE STRING "Visiblity for ZDICTLIB_VISIBLE API") +set(ZSTDLIB_STATIC_API "" CACHE STRING "Visiblity for ZSTDLIB_STATIC_API API") +set(ZDICTLIB_STATIC_API "" CACHE STRING "Visiblity for ZDICTLIB_STATIC_API API") + +set_property(CACHE ZSTDLIB_VISIBLE PROPERTY STRINGS "" "hidden" "default" "protected" "internal") +set_property(CACHE ZSTDERRORLIB_VISIBLE PROPERTY STRINGS "" "hidden" "default" "protected" "internal") +set_property(CACHE ZDICTLIB_VISIBLE PROPERTY STRINGS "" "hidden" "default" "protected" "internal") +set_property(CACHE ZSTDLIB_STATIC_API PROPERTY STRINGS "" "hidden" "default" "protected" "internal") +set_property(CACHE ZDICTLIB_STATIC_API PROPERTY STRINGS "" "hidden" "default" "protected" "internal") if(NOT ZSTD_BUILD_SHARED AND NOT ZSTD_BUILD_STATIC) message(SEND_ERROR "You need to build at least one flavor of libzstd") @@ -29,24 +45,32 @@ else () file(GLOB DecompressSources ${LIBRARY_DIR}/decompress/*.c ${LIBRARY_DIR}/decompress/*.S) endif () file(GLOB DictBuilderSources ${LIBRARY_DIR}/dictBuilder/*.c) - -set(Sources - ${CommonSources} - ${CompressSources} - ${DecompressSources} - ${DictBuilderSources}) +file(GLOB DeprecatedSources ${LIBRARY_DIR}/deprecated/*.c) file(GLOB CommonHeaders ${LIBRARY_DIR}/common/*.h) file(GLOB CompressHeaders ${LIBRARY_DIR}/compress/*.h) file(GLOB DecompressHeaders ${LIBRARY_DIR}/decompress/*.h) file(GLOB DictBuilderHeaders ${LIBRARY_DIR}/dictBuilder/*.h) +file(GLOB DeprecatedHeaders ${LIBRARY_DIR}/deprecated/*.h) -set(Headers - ${LIBRARY_DIR}/zstd.h - ${CommonHeaders} - ${CompressHeaders} - ${DecompressHeaders} - ${DictBuilderHeaders}) +set(Sources ${CommonSources}) +set(Headers ${LIBRARY_DIR}/zstd.h ${CommonHeaders}) +if (ZSTD_BUILD_COMPRESSION) + set(Sources ${Sources} ${CompressSources}) + set(Headers ${Headers} ${CompressHeaders}) +endif() +if (ZSTD_BUILD_DECOMPRESSION) + set(Sources ${Sources} ${DecompressSources}) + set(Headers ${Headers} ${DecompressHeaders}) +endif() +if (ZSTD_BUILD_DICTBUILDER) + set(Sources ${Sources} ${DictBuilderSources}) + set(Headers ${Headers} ${DictBuilderHeaders}) +endif() +if (ZSTD_BUILD_DEPRECATED) + set(Sources ${Sources} ${DeprecatedSources}) + set(Headers ${Headers} ${DeprecatedHeaders}) +endif() if (ZSTD_LEGACY_SUPPORT) set(LIBRARY_LEGACY_DIR ${LIBRARY_DIR}/legacy) @@ -83,6 +107,12 @@ endif () # macros. set_source_files_properties(${Sources} PROPERTIES LANGUAGE C) +macro (add_definition target var) + if (NOT ("${${var}}" STREQUAL "")) + set_property(TARGET ${target} APPEND PROPERTY COMPILE_DEFINITIONS "${var}=__attribute__((visibility(\"${${var}}\")))") + endif () +endmacro () + # Split project to static and shared libraries build set(library_targets) if (ZSTD_BUILD_SHARED) @@ -93,7 +123,10 @@ if (ZSTD_BUILD_SHARED) if (UNIX) target_link_libraries(libzstd_shared ${THREADS_LIBS}) endif () - endif() + endif () + add_definition(libzstd_shared ZSTDLIB_VISIBLE) + add_definition(libzstd_shared ZSTDERRORLIB_VISIBLE) + add_definition(libzstd_shared ZDICTLIB_VISIBLE) endif () if (ZSTD_BUILD_STATIC) add_library(libzstd_static STATIC ${Sources} ${Headers}) @@ -104,6 +137,11 @@ if (ZSTD_BUILD_STATIC) target_link_libraries(libzstd_static ${THREADS_LIBS}) endif () endif () + add_definition(libzstd_static ZSTDLIB_VISIBLE) + add_definition(libzstd_static ZSTDERRORLIB_VISIBLE) + add_definition(libzstd_static ZDICTLIB_VISIBLE) + add_definition(libzstd_static ZSTDLIB_STATIC_API) + add_definition(libzstd_static ZDICTLIB_STATIC_API) endif () # Add specific compile definitions for MSVC project From 5108c9ac975b5e4ff62418584cc6c8934d747b38 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 27 May 2023 11:22:30 -0700 Subject: [PATCH 041/937] Fixed a bug in the educational decoder Credit to Igor Pavlov --- doc/educational_decoder/zstd_decompress.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/educational_decoder/zstd_decompress.c b/doc/educational_decoder/zstd_decompress.c index 3196b78dc..1da7c528d 100644 --- a/doc/educational_decoder/zstd_decompress.c +++ b/doc/educational_decoder/zstd_decompress.c @@ -997,7 +997,8 @@ static void decompress_sequences(frame_context_t *const ctx, const size_t num_sequences); static sequence_command_t decode_sequence(sequence_states_t *const state, const u8 *const src, - i64 *const offset); + i64 *const offset, + int lastSequence); static void decode_seq_table(FSE_dtable *const table, istream_t *const in, const seq_part_t type, const seq_mode_t mode); @@ -1114,7 +1115,7 @@ static void decompress_sequences(frame_context_t *const ctx, istream_t *in, for (size_t i = 0; i < num_sequences; i++) { // Decode sequences one by one - sequences[i] = decode_sequence(&states, src, &bit_offset); + sequences[i] = decode_sequence(&states, src, &bit_offset, i==num_sequences-1); } if (bit_offset != 0) { @@ -1125,7 +1126,8 @@ static void decompress_sequences(frame_context_t *const ctx, istream_t *in, // Decode a single sequence and update the state static sequence_command_t decode_sequence(sequence_states_t *const states, const u8 *const src, - i64 *const offset) { + i64 *const offset, + int lastSequence) { // "Each symbol is a code in its own context, which specifies Baseline and // Number_of_Bits to add. Codes are FSE compressed, and interleaved with raw // additional bits in the same bitstream." @@ -1160,7 +1162,7 @@ static sequence_command_t decode_sequence(sequence_states_t *const states, // Literals_Length_State is updated, followed by Match_Length_State, and // then Offset_State." // If the stream is complete don't read bits to update state - if (*offset != 0) { + if (!lastSequence) { FSE_update_state(&states->ll_table, &states->ll_state, src, offset); FSE_update_state(&states->ml_table, &states->ml_state, src, offset); FSE_update_state(&states->of_table, &states->of_state, src, offset); From 94a2f2791f313d27b6a2c0293971954cdd66035b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 31 May 2023 13:29:53 -0700 Subject: [PATCH 042/937] changed LLU suffix into ULL for Visual 2012 and lower both suffixes are supposed to be valid, but for some reason, Visual 2012 and lower only support ULL. --- lib/zstd.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/zstd.h b/lib/zstd.h index e94f10189..148f112d1 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -228,7 +228,7 @@ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize) * for example to size a static array on stack. * Will produce constant value 0 if srcSize too large. */ -#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00LLU : 0xFF00FF00U) +#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U) #define ZSTD_COMPRESSBOUND(srcSize) (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0)) /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */ ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */ /* ZSTD_isError() : From 7e09f07b325b6e2a95e11776f23ff97716b7b924 Mon Sep 17 00:00:00 2001 From: Gregor Jasny Date: Fri, 2 Jun 2023 12:34:56 +0200 Subject: [PATCH 043/937] Fix Intel Xcode builds with assembly When forcing the source file language to `C`, Xcode enforces the file to be compiled as `C` by appending `-x c` to the compiler command line. For now try to limit the damage and only enforce the language if the ASM and C compilers differ. Reproducer (CMake `3.26.4`, Xcode `14.3`): ``` cmake -S build/cmake -B _b -GXcode -DCMAKE_OSX_ARCHITECTURES=x86_64 cmake --build _b ``` Fix: #3622 --- build/cmake/lib/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 457b54797..3cab017a7 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -105,7 +105,9 @@ endif () # Our assembly expects to be compiled by a C compiler, and is only enabled for # __GNUC__ compatible compilers. Otherwise all the ASM code is disabled by # macros. -set_source_files_properties(${Sources} PROPERTIES LANGUAGE C) +if(NOT CMAKE_ASM_COMPILER STREQUAL CMAKE_C_COMPILER) + set_source_files_properties(${Sources} PROPERTIES LANGUAGE C) +endif() macro (add_definition target var) if (NOT ("${${var}}" STREQUAL "")) From 1f83b7cfc459c2dbef00dc6276f790370e17aef6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 5 Jun 2023 09:51:52 -0700 Subject: [PATCH 044/937] fix a minor inefficiency in compress_superblock and in `decodecorpus`: the specific case `nbSeq=127` can be represented using the 1-byte format. Note that both the 1-byte and the 2-bytes formats are valid to represent this case, so there was no "error", produced data remains valid, it's just that the 1-byte format is more efficient. fix #3667 Credit to @ip7z for finding this issue. --- doc/zstd_compression_format.md | 5 +++-- lib/compress/zstd_compress_superblock.c | 2 +- tests/decodecorpus.c | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 3843bf390..2a69c4c30 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -655,8 +655,9 @@ Let's call its first byte `byte0`. Decompressed content is defined entirely as Literals Section content. The FSE tables used in `Repeat_Mode` aren't updated. - `if (byte0 < 128)` : `Number_of_Sequences = byte0` . Uses 1 byte. -- `if (byte0 < 255)` : `Number_of_Sequences = ((byte0-128) << 8) + byte1` . Uses 2 bytes. -- `if (byte0 == 255)`: `Number_of_Sequences = byte1 + (byte2<<8) + 0x7F00` . Uses 3 bytes. +- `if (byte0 < 255)` : `Number_of_Sequences = ((byte0 - 0x80) << 8) + byte1`. Uses 2 bytes. + Note that the 2 bytes format fully overlaps the 1 byte format. +- `if (byte0 == 255)`: `Number_of_Sequences = byte1 + (byte2<<8) + 0x7F00`. Uses 3 bytes. __Symbol compression modes__ diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index 638c4acbe..dacaf85db 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -180,7 +180,7 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables, /* Sequences Header */ RETURN_ERROR_IF((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/, dstSize_tooSmall, ""); - if (nbSeq < 0x7F) + if (nbSeq < 128) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c index e48eccd6d..a440ae38a 100644 --- a/tests/decodecorpus.c +++ b/tests/decodecorpus.c @@ -825,7 +825,7 @@ static size_t writeSequences(U32* seed, frame_t* frame, seqStore_t* seqStorePtr, /* Sequences Header */ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead */) return ERROR(dstSize_tooSmall); - if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; + if (nbSeq < 128) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3; From 3732a08f5b82ed87a744e65daa2f11f77dabe954 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 5 Jun 2023 16:03:00 -0700 Subject: [PATCH 045/937] fixed decoder behavior when nbSeqs==0 is encoded using 2 bytes The sequence section starts with a number, which tells how sequences are present in the section. If this number if 0, the section automatically ends. The number 0 can be represented using the 1 byte or the 2 bytes formats. That's because the 2-bytes formats fully overlaps the 1 byte format. However, when 0 is represented using the 2-bytes format, the decoder was expecting the sequence section to continue, and was looking for FSE tables, which is incorrect. Fixed this behavior, in both the reference decoder and the educational behavior. In practice, this behavior never happens, because the encoder will always select the 1-byte format to represent 0, since this is more efficient. Completed the fix with a new golden sample for tests, a clarification of the specification, and a decoder errata paragraph. --- doc/decompressor_errata.md | 23 ++++++++++++++++++++++ doc/educational_decoder/zstd_decompress.c | 13 ++++++------ doc/zstd_compression_format.md | 12 ++++++----- lib/common/zstd_internal.h | 4 ++-- lib/decompress/zstd_decompress_block.c | 10 +++++----- tests/golden-decompression/zeroSeq_2B.zst | Bin 0 -> 25 bytes 6 files changed, 44 insertions(+), 18 deletions(-) create mode 100644 tests/golden-decompression/zeroSeq_2B.zst diff --git a/doc/decompressor_errata.md b/doc/decompressor_errata.md index e170a62c1..83d4071cb 100644 --- a/doc/decompressor_errata.md +++ b/doc/decompressor_errata.md @@ -12,6 +12,26 @@ Each entry will contain: The document is in reverse chronological order, with the bugs that affect the most recent zstd decompressor versions listed first. +No sequence using the 2-bytes format +------------------------------------------------ + +**Last affected version**: v1.5.5 + +**Affected decompressor component(s)**: Library & CLI + +**Produced by the reference compressor**: No + +**Example Frame**: see zstd/tests/golden-decompression/zeroSeq_2B.zst + +The zstd decoder incorrectly expects FSE tables when there are 0 sequences present in the block +if the value 0 is encoded using the 2-bytes format. +Instead, it should immediately end the sequence section, and move on to next block. + +This situation was never generated by the reference compressor, +because representing 0 sequences with the 2-bytes format is inefficient +(the 1-byte format is always used in this case). + + Compressed block with a size of exactly 128 KB ------------------------------------------------ @@ -32,6 +52,7 @@ These blocks used to be disallowed by the spec up until spec version 0.3.2 when > A Compressed_Block has the extra restriction that Block_Size is always strictly less than the decompressed size. If this condition cannot be respected, the block must be sent uncompressed instead (Raw_Block). + Compressed block with 0 literals and 0 sequences ------------------------------------------------ @@ -51,6 +72,7 @@ Additionally, these blocks were disallowed by the spec up until spec version 0.3 > A Compressed_Block has the extra restriction that Block_Size is always strictly less than the decompressed size. If this condition cannot be respected, the block must be sent uncompressed instead (Raw_Block). + First block is RLE block ------------------------ @@ -72,6 +94,7 @@ block. https://github.com/facebook/zstd/blob/8814aa5bfa74f05a86e55e9d508da177a893ceeb/lib/compress/zstd_compress.c#L3527-L3535 + Tiny FSE Table & Block ---------------------- diff --git a/doc/educational_decoder/zstd_decompress.c b/doc/educational_decoder/zstd_decompress.c index 1da7c528d..921c8f54c 100644 --- a/doc/educational_decoder/zstd_decompress.c +++ b/doc/educational_decoder/zstd_decompress.c @@ -1018,12 +1018,7 @@ static size_t decode_sequences(frame_context_t *const ctx, istream_t *in, // This is a variable size field using between 1 and 3 bytes. Let's call its // first byte byte0." u8 header = IO_read_bits(in, 8); - if (header == 0) { - // "There are no sequences. The sequence section stops there. - // Regenerated content is defined entirely by literals section." - *sequences = NULL; - return 0; - } else if (header < 128) { + if (header < 128) { // "Number_of_Sequences = byte0 . Uses 1 byte." num_sequences = header; } else if (header < 255) { @@ -1034,6 +1029,12 @@ static size_t decode_sequences(frame_context_t *const ctx, istream_t *in, num_sequences = IO_read_bits(in, 16) + 0x7F00; } + if (num_sequences == 0) { + // "There are no sequences. The sequence section stops there." + *sequences = NULL; + return 0; + } + *sequences = malloc(num_sequences * sizeof(sequence_command_t)); if (!*sequences) { BAD_ALLOC(); diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 2a69c4c30..cd7308de1 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -0.3.9 (2023-03-08) +0.4.0 (2023-06-05) Introduction @@ -650,15 +650,16 @@ __`Number_of_Sequences`__ This is a variable size field using between 1 and 3 bytes. Let's call its first byte `byte0`. -- `if (byte0 == 0)` : there are no sequences. - The sequence section stops there. - Decompressed content is defined entirely as Literals Section content. - The FSE tables used in `Repeat_Mode` aren't updated. - `if (byte0 < 128)` : `Number_of_Sequences = byte0` . Uses 1 byte. - `if (byte0 < 255)` : `Number_of_Sequences = ((byte0 - 0x80) << 8) + byte1`. Uses 2 bytes. Note that the 2 bytes format fully overlaps the 1 byte format. - `if (byte0 == 255)`: `Number_of_Sequences = byte1 + (byte2<<8) + 0x7F00`. Uses 3 bytes. +`if (Number_of_Sequences == 0)` : there are no sequences. + The sequence section stops immediately, + FSE tables used in `Repeat_Mode` aren't updated. + Block's decompressed content is defined solely by the Literals Section content. + __Symbol compression modes__ This is a single byte, defining the compression mode of each symbol type. @@ -1698,6 +1699,7 @@ or at least provide a meaningful error code explaining for which reason it canno Version changes --------------- +- 0.4.0 : fixed imprecise behavior for nbSeq==0, detected by Igor Pavlov - 0.3.9 : clarifications for Huffman-compressed literal sizes. - 0.3.8 : clarifications for Huffman Blocks and Huffman Tree descriptions. - 0.3.7 : clarifications for Repeat_Offsets, matching RFC8878 diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index 1f942f27b..f7c57a028 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -366,13 +366,13 @@ typedef struct { /*! ZSTD_getcBlockSize() : * Provides the size of compressed block from block header `src` */ -/* Used by: decompress, fullbench (does not get its definition from here) */ +/* Used by: decompress, fullbench */ size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr); /*! ZSTD_decodeSeqHeaders() : * decode sequence header from src */ -/* Used by: decompress, fullbench (does not get its definition from here) */ +/* Used by: zstd_decompress_block, fullbench */ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, const void* src, size_t srcSize); diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 5028a52f1..c63d06d6a 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -706,11 +706,6 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, /* SeqHead */ nbSeq = *ip++; - if (!nbSeq) { - *nbSeqPtr=0; - RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, ""); - return 1; - } if (nbSeq > 0x7F) { if (nbSeq == 0xFF) { RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, ""); @@ -723,6 +718,11 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, } *nbSeqPtr = nbSeq; + if (nbSeq == 0) { + /* No sequence : section ends immediately */ + return (size_t)(ip - istart); + } + /* FSE table descriptors */ RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */ { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6); diff --git a/tests/golden-decompression/zeroSeq_2B.zst b/tests/golden-decompression/zeroSeq_2B.zst new file mode 100644 index 0000000000000000000000000000000000000000..f9f3520a6eb823709594cbe57df3c1b497984f48 GIT binary patch literal 25 gcmdPcs{faPp_PFl!y`2(Cto2vzbGd~k*k3L0BK Date: Mon, 12 Jun 2023 06:00:14 +0000 Subject: [PATCH 046/937] Bump actions/checkout from 3.5.2 to 3.5.3 Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.2 to 3.5.3. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/8e5e7e5ab8b370d6c329ec480221332ada57f0ab...c85c95e3d7251135ab7dc9ce3241c5835cc595a9) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 50 ++++++------- .github/workflows/dev-short-tests.yml | 74 +++++++++---------- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 5 files changed, 65 insertions(+), 65 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index deef9f780..6a0e338f0 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -15,7 +15,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: make all run: make all @@ -26,7 +26,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: make test run: make test @@ -34,7 +34,7 @@ jobs: make-test-osx: runs-on: macos-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: OS-X test run: make test # make -c lib all doesn't work because of the fact that it's not a tty @@ -45,7 +45,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: make test run: | sudo apt-get -qqq update @@ -55,21 +55,21 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream ubsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: undefined behavior sanitizer zstreamtest run: CC=clang make uasan-test-zstream @@ -77,7 +77,7 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest @@ -85,7 +85,7 @@ jobs: big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -96,7 +96,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -108,14 +108,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # tag=v3 + - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Tue, 13 Jun 2023 11:43:45 -0700 Subject: [PATCH 047/937] detect extraneous bytes in the Sequences section when nbSeq == 0. Reported by @ip7z --- lib/decompress/zstd_decompress_block.c | 2 ++ tests/cli-tests/decompression/detectErrors.sh | 11 +++++++++++ tests/playTests.sh | 5 +++++ 3 files changed, 18 insertions(+) create mode 100755 tests/cli-tests/decompression/detectErrors.sh diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index c63d06d6a..93947ba58 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -720,6 +720,8 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, if (nbSeq == 0) { /* No sequence : section ends immediately */ + RETURN_ERROR_IF(ip != iend, corruption_detected, + "extraneous data present in the Sequences section"); return (size_t)(ip - istart); } diff --git a/tests/cli-tests/decompression/detectErrors.sh b/tests/cli-tests/decompression/detectErrors.sh new file mode 100755 index 000000000..300cde364 --- /dev/null +++ b/tests/cli-tests/decompression/detectErrors.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +set -e + +GOLDEN_DIR="$ZSTD_REPO_DIR/tests/golden-decompression-errors/" + +for file in "$GOLDEN_DIR"/*; do + zstd -t $file && die "should have detected an error" +done +exit 0 + diff --git a/tests/playTests.sh b/tests/playTests.sh index f51776170..05dc00429 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -444,6 +444,11 @@ $DIFF -s tmp1 tmp touch tmp_empty zstd -d -o tmp2 "$TESTDIR/golden-decompression/empty-block.zst" $DIFF -s tmp2 tmp_empty + +zstd -t "$TESTDIR/golden-decompression/zeroSeq_2B.zst" + +zstd -t "$TESTDIR/golden-decompression-errors/zeroSeq_extraneous.zst" && die "invalid Sequences section should have been detected" + rm -f tmp* println "\n===> compress multiple files" From ba508070299b4ab7ae1e22b659557489122cdcd7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 14 Jun 2023 15:42:37 -0700 Subject: [PATCH 048/937] make the bitstream generate only 0-value bits after an overflow --- lib/common/bitstream.h | 67 ++++++++++++++++++++++++------------------ lib/common/compiler.h | 19 ++++++++++++ lib/common/mem.h | 9 ------ lib/legacy/zstd_v06.c | 9 ------ lib/legacy/zstd_v07.c | 9 ------ 5 files changed, 57 insertions(+), 56 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 72b0b3df2..374f2b689 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -90,19 +90,20 @@ MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); /*-******************************************** * bitStream decoding API (read backward) **********************************************/ +typedef size_t BitContainerType; typedef struct { - size_t bitContainer; + BitContainerType bitContainer; unsigned bitsConsumed; const char* ptr; const char* start; const char* limitPtr; } BIT_DStream_t; -typedef enum { BIT_DStream_unfinished = 0, - BIT_DStream_endOfBuffer = 1, - BIT_DStream_completed = 2, - BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */ - /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */ +typedef enum { BIT_DStream_unfinished = 0, /* fully refilled */ + BIT_DStream_endOfBuffer = 1, /* still some bits left in bitstream */ + BIT_DStream_completed = 2, /* bitstream entirely consumed, bit-exact */ + BIT_DStream_overflow = 3 /* user requested more bits than present in bitstream */ + } 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 size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); @@ -112,7 +113,7 @@ MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); /* Start by invoking BIT_initDStream(). * A chunk of the bitStream is then stored into a local register. -* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t). +* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (BitContainerType). * You can then retrieve bitFields stored into the local register, **in reverse order**. * Local register is explicitly reloaded from memory by the BIT_reloadDStream() method. * A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished. @@ -162,7 +163,7 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, return 0; } -MEM_STATIC FORCE_INLINE_ATTR size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) +FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) return _bzhi_u64(bitContainer, nbBits); @@ -267,22 +268,22 @@ MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, si bitD->bitContainer = *(const BYTE*)(bitD->start); switch(srcSize) { - case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16); + case 7: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16); ZSTD_FALLTHROUGH; - case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24); + case 6: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24); ZSTD_FALLTHROUGH; - case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32); + case 5: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32); ZSTD_FALLTHROUGH; - case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24; + case 4: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[3]) << 24; ZSTD_FALLTHROUGH; - case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16; + case 3: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[2]) << 16; ZSTD_FALLTHROUGH; - case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8; + case 2: bitD->bitContainer += (BitContainerType)(((const BYTE*)(srcBuffer))[1]) << 8; ZSTD_FALLTHROUGH; default: break; @@ -297,12 +298,12 @@ MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, si return srcSize; } -MEM_STATIC FORCE_INLINE_ATTR size_t BIT_getUpperBits(size_t bitContainer, U32 const start) +FORCE_INLINE_TEMPLATE size_t BIT_getUpperBits(BitContainerType bitContainer, U32 const start) { return bitContainer >> start; } -MEM_STATIC FORCE_INLINE_ATTR size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits) +FORCE_INLINE_TEMPLATE size_t BIT_getMiddleBits(BitContainerType bitContainer, U32 const start, U32 const nbBits) { U32 const regMask = sizeof(bitContainer)*8 - 1; /* if start > regMask, bitstream is corrupted, and result is undefined */ @@ -325,7 +326,7 @@ MEM_STATIC FORCE_INLINE_ATTR size_t BIT_getMiddleBits(size_t bitContainer, U32 c * On 32-bits, maxNbBits==24. * On 64-bits, maxNbBits==56. * @return : value extracted */ -MEM_STATIC FORCE_INLINE_ATTR size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) +FORCE_INLINE_TEMPLATE size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) { /* arbitrate between double-shift and shift+mask */ #if 1 @@ -348,7 +349,7 @@ MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits) return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask); } -MEM_STATIC FORCE_INLINE_ATTR void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) +FORCE_INLINE_TEMPLATE void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) { bitD->bitsConsumed += nbBits; } @@ -357,7 +358,7 @@ MEM_STATIC FORCE_INLINE_ATTR void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) * Read (consume) next n bits from local register and update. * Pay attention to not read more than nbBits contained into local register. * @return : extracted value. */ -MEM_STATIC FORCE_INLINE_ATTR size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) +FORCE_INLINE_TEMPLATE size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) { size_t const value = BIT_lookBits(bitD, nbBits); BIT_skipBits(bitD, nbBits); @@ -375,16 +376,16 @@ MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) } /*! BIT_reloadDStreamFast() : - * Similar to BIT_reloadDStream(), but with two differences: - * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold! - * 2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this - * point you must use BIT_reloadDStream() to reload. + * Simple variant of BIT_reloadDStream(), with two conditions: + * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 + * 2. bitD->ptr >= bitD->limitPtr + * These conditions guarantee that bitstream is in a valid state, + * and shifting the position of the look window is safe. */ MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) { - if (UNLIKELY(bitD->ptr < bitD->limitPtr)) - return BIT_DStream_overflow; assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8); + assert(bitD->ptr >= bitD->limitPtr); bitD->ptr -= bitD->bitsConsumed >> 3; bitD->bitsConsumed &= 7; bitD->bitContainer = MEM_readLEST(bitD->ptr); @@ -393,22 +394,30 @@ MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) /*! BIT_reloadDStream() : * Refill `bitD` from buffer previously set in BIT_initDStream() . - * This function is safe, it guarantees it will not read beyond src buffer. + * This function is safe, it guarantees it will not never beyond src buffer. * @return : status of `BIT_DStream_t` internal register. * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */ -MEM_STATIC FORCE_INLINE_ATTR BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) +FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) { - if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* overflow detected, like end of stream */ + /* note : once in overflow mode, a bitstream remains in this mode until it's reset */ + if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) { + static const BitContainerType zeroFilled = 0; + bitD->ptr = (const char*)&zeroFilled; /* aliasing is allowed for char */ + /* overflow detected, erroneous scenario or end of stream: no update */ return BIT_DStream_overflow; + } + + assert(bitD->ptr >= bitD->start); if (bitD->ptr >= bitD->limitPtr) { return BIT_reloadDStreamFast(bitD); } if (bitD->ptr == bitD->start) { + /* reached end of bitStream => no update */ if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer; return BIT_DStream_completed; } - /* start < ptr < limitPtr */ + /* start < ptr < limitPtr => cautious update */ { U32 nbBytes = bitD->bitsConsumed >> 3; BIT_DStream_status result = BIT_DStream_unfinished; if (bitD->ptr - nbBytes < bitD->start) { diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 79e773c0f..1cde912f9 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -81,6 +81,25 @@ # define UNUSED_ATTR #endif +/* "soft" inline : + * The compiler is free to select if it's a good idea to inline or not. + * The main objective is to silence compiler warnings + * when a defined function in included but not used. + * + * Note : this macro is prefixed `MEM_` because it used to be provided by `mem.h` unit. + * Updating the prefix is probably preferable, but requires a fairly large codemod, + * since this name is used everywhere. + */ +#if defined(__GNUC__) +# define MEM_STATIC static __inline UNUSED_ATTR +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define MEM_STATIC static inline +#elif defined(_MSC_VER) +# define MEM_STATIC static __inline +#else +# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + /* force no inlining */ #ifdef _MSC_VER # define FORCE_NOINLINE static __declspec(noinline) diff --git a/lib/common/mem.h b/lib/common/mem.h index 98dd47a04..096f4be51 100644 --- a/lib/common/mem.h +++ b/lib/common/mem.h @@ -31,15 +31,6 @@ extern "C" { # include /* _byteswap_ulong */ # include /* _byteswap_* */ #endif -#if defined(__GNUC__) -# define MEM_STATIC static __inline __attribute__((unused)) -#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define MEM_STATIC static inline -#elif defined(_MSC_VER) -# define MEM_STATIC static __inline -#else -# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ -#endif /*-************************************************************** * Basic Types diff --git a/lib/legacy/zstd_v06.c b/lib/legacy/zstd_v06.c index 175f7cc42..ac9ae987c 100644 --- a/lib/legacy/zstd_v06.c +++ b/lib/legacy/zstd_v06.c @@ -67,15 +67,6 @@ extern "C" { # include /* _byteswap_ulong */ # include /* _byteswap_* */ #endif -#if defined(__GNUC__) -# define MEM_STATIC static __attribute__((unused)) -#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define MEM_STATIC static inline -#elif defined(_MSC_VER) -# define MEM_STATIC static __inline -#else -# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ -#endif /*-************************************************************** diff --git a/lib/legacy/zstd_v07.c b/lib/legacy/zstd_v07.c index 15dc3ef79..b214ec08b 100644 --- a/lib/legacy/zstd_v07.c +++ b/lib/legacy/zstd_v07.c @@ -227,15 +227,6 @@ extern "C" { # include /* _byteswap_ulong */ # include /* _byteswap_* */ #endif -#if defined(__GNUC__) -# define MEM_STATIC static __attribute__((unused)) -#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define MEM_STATIC static inline -#elif defined(_MSC_VER) -# define MEM_STATIC static __inline -#else -# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ -#endif /*-************************************************************** From 74c901bbedd4584190f0cd93d573cf7e014b76d1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 14 Jun 2023 16:32:51 -0700 Subject: [PATCH 049/937] fix : unused attribute for FORCE_INLINE functions fix2 : reloadDStreamFast is used by decompress4x2, modified the entry point, so that it works fine in this case too. --- lib/common/bitstream.h | 27 +++++++++++++++++++-------- lib/common/compiler.h | 18 +++++++++--------- lib/legacy/zstd_v04.c | 9 --------- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 374f2b689..a737f011c 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -375,23 +375,34 @@ MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) return value; } -/*! BIT_reloadDStreamFast() : +/*! BIT_reloadDStream_internal() : * Simple variant of BIT_reloadDStream(), with two conditions: - * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 - * 2. bitD->ptr >= bitD->limitPtr - * These conditions guarantee that bitstream is in a valid state, - * and shifting the position of the look window is safe. + * 1. bitstream is valid : bitsConsumed <= sizeof(bitD->bitContainer)*8 + * 2. look window is valid after shifted down : bitD->ptr >= bitD->start */ -MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) +MEM_STATIC BIT_DStream_status BIT_reloadDStream_internal(BIT_DStream_t* bitD) { assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8); - assert(bitD->ptr >= bitD->limitPtr); bitD->ptr -= bitD->bitsConsumed >> 3; + assert(bitD->ptr >= bitD->start); bitD->bitsConsumed &= 7; bitD->bitContainer = MEM_readLEST(bitD->ptr); return BIT_DStream_unfinished; } +/*! BIT_reloadDStreamFast() : + * Similar to BIT_reloadDStream(), but with two differences: + * 1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold! + * 2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this + * point you must use BIT_reloadDStream() to reload. + */ +MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) +{ + if (UNLIKELY(bitD->ptr < bitD->limitPtr)) + return BIT_DStream_overflow; + return BIT_reloadDStream_internal(bitD); +} + /*! BIT_reloadDStream() : * Refill `bitD` from buffer previously set in BIT_initDStream() . * This function is safe, it guarantees it will not never beyond src buffer. @@ -410,7 +421,7 @@ FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) assert(bitD->ptr >= bitD->start); if (bitD->ptr >= bitD->limitPtr) { - return BIT_reloadDStreamFast(bitD); + return BIT_reloadDStream_internal(bitD); } if (bitD->ptr == bitD->start) { /* reached end of bitStream => no update */ diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 1cde912f9..35b9c1387 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -51,12 +51,19 @@ # define WIN_CDECL #endif +/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ +#if defined(__GNUC__) +# define UNUSED_ATTR __attribute__((unused)) +#else +# define UNUSED_ATTR +#endif + /** * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant * parameters. They must be inlined for the compiler to eliminate the constant * branches. */ -#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR +#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR UNUSED_ATTR /** * HINT_INLINE is used to help the compiler generate better code. It is *not* * used for "templates", so it can be tweaked based on the compilers @@ -71,14 +78,7 @@ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5 # define HINT_INLINE static INLINE_KEYWORD #else -# define HINT_INLINE static INLINE_KEYWORD FORCE_INLINE_ATTR -#endif - -/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ -#if defined(__GNUC__) -# define UNUSED_ATTR __attribute__((unused)) -#else -# define UNUSED_ATTR +# define HINT_INLINE FORCE_INLINE_TEMPLATE #endif /* "soft" inline : diff --git a/lib/legacy/zstd_v04.c b/lib/legacy/zstd_v04.c index 57be832bd..fa65160bc 100644 --- a/lib/legacy/zstd_v04.c +++ b/lib/legacy/zstd_v04.c @@ -37,15 +37,6 @@ extern "C" { # include /* _byteswap_ulong */ # include /* _byteswap_* */ #endif -#if defined(__GNUC__) -# define MEM_STATIC static __attribute__((unused)) -#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define MEM_STATIC static inline -#elif defined(_MSC_VER) -# define MEM_STATIC static __inline -#else -# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ -#endif /**************************************************************** From d9645327b3b6d18b04ac1dd0bc4346a2af87bb9b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 14 Jun 2023 20:03:39 -0700 Subject: [PATCH 050/937] fixed MEM_STATIC already defined in Linux Kernel mode --- contrib/linux-kernel/mem.h | 1 + lib/common/allocations.h | 2 +- lib/common/compiler.h | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/contrib/linux-kernel/mem.h b/contrib/linux-kernel/mem.h index a7231822b..2e91e7780 100644 --- a/contrib/linux-kernel/mem.h +++ b/contrib/linux-kernel/mem.h @@ -24,6 +24,7 @@ /*-**************************************** * Compiler specifics ******************************************/ +#undef MEM_STATIC /* may be already defined from common/compiler.h */ #define MEM_STATIC static inline /*-************************************************************** diff --git a/lib/common/allocations.h b/lib/common/allocations.h index a3153c4ba..5e8995501 100644 --- a/lib/common/allocations.h +++ b/lib/common/allocations.h @@ -14,7 +14,7 @@ #define ZSTD_DEPS_NEED_MALLOC #include "zstd_deps.h" /* ZSTD_malloc, ZSTD_calloc, ZSTD_free, ZSTD_memset */ -#include "mem.h" /* MEM_STATIC */ +#include "compiler.h" /* MEM_STATIC */ #define ZSTD_STATIC_LINKING_ONLY #include "../zstd.h" /* ZSTD_customMem */ diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 35b9c1387..bcaa575dd 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -90,6 +90,7 @@ * Updating the prefix is probably preferable, but requires a fairly large codemod, * since this name is used everywhere. */ +#ifndef MEM_STATIC /* already defined in Linux Kernel mem.h */ #if defined(__GNUC__) # define MEM_STATIC static __inline UNUSED_ATTR #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) @@ -99,6 +100,7 @@ #else # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ #endif +#endif /* force no inlining */ #ifdef _MSC_VER From 02134fad123a26e17bcb48edc2868b5968ed76d5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 16 Jun 2023 11:56:22 -0700 Subject: [PATCH 051/937] changed (partially) the decodeSequences flow logic this allows detecting overflow events without a checksum. --- lib/decompress/zstd_decompress_block.c | 160 ++++++++++++++++++++++--- 1 file changed, 145 insertions(+), 15 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 93947ba58..2d0220043 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1214,14 +1214,20 @@ ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e; +/** + * ZSTD_decodeSequence_old(): + * @p longOffsets : tells the decoder to reload more bit while decoding large offsets + * only used in 32-bit mode + * @return : Sequence (litL + matchL + offset) + */ FORCE_INLINE_TEMPLATE seq_t -ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets) +ZSTD_decodeSequence_old(seqState_t* seqState, const ZSTD_longOffset_e longOffsets) { seq_t seq; /* - * ZSTD_seqSymbol is a structure with a total of 64 bits wide. So it can be - * loaded in one operation and extracted its fields by simply shifting or - * bit-extracting on aarch64. + * ZSTD_seqSymbol is a 64 bits wide structure. + * It can be loaded in one operation + * and its fields extracted by simply shifting or bit-extracting on aarch64. * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh * operations that cause performance drop. This can be avoided by using this * ZSTD_memcpy hack. @@ -1330,6 +1336,132 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets) return seq; } +/** + * ZSTD_decodeSequence(): + * @p longOffsets : tells the decoder to reload more bit while decoding large offsets + * only used in 32-bit mode + * @return : Sequence (litL + matchL + offset) + */ +FORCE_INLINE_TEMPLATE seq_t +ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const int isLastSeq) +{ + seq_t seq; + /* + * ZSTD_seqSymbol is a 64 bits wide structure. + * It can be loaded in one operation + * and its fields extracted by simply shifting or bit-extracting on aarch64. + * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh + * operations that cause performance drop. This can be avoided by using this + * ZSTD_memcpy hack. + */ +#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__)) + ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS; + ZSTD_seqSymbol* const llDInfo = &llDInfoS; + ZSTD_seqSymbol* const mlDInfo = &mlDInfoS; + ZSTD_seqSymbol* const ofDInfo = &ofDInfoS; + 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 + 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 + 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; + + U16 const llNext = llDInfo->nextState; + U16 const mlNext = mlDInfo->nextState; + U16 const ofNext = ofDInfo->nextState; + U32 const llnbBits = llDInfo->nbBits; + U32 const mlnbBits = mlDInfo->nbBits; + U32 const ofnbBits = ofDInfo->nbBits; + + 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); + if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { + /* Always read extra bits, this keeps the logic simple, + * avoids branches, and avoids accidentally reading 0 bits. + */ + U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32; + offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); + BIT_reloadDStream(&seqState->DStream); + offset += BIT_readBitsFast(&seqState->DStream, extraBits); + } else { + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); + } + seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset; + } else { + U32 const ll0 = (llDInfo->baseValue == 0); + if (LIKELY((ofBits == 0))) { + offset = seqState->prevOffset[ll0]; + seqState->prevOffset[1] = seqState->prevOffset[!ll0]; + seqState->prevOffset[0] = offset; + } else { + offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1); + { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset]; + temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */ + if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1]; + seqState->prevOffset[1] = seqState->prevOffset[0]; + seqState->prevOffset[0] = offset = temp; + } } } + seq.offset = offset; + } + + if (mlBits > 0) + seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); + + if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) + BIT_reloadDStream(&seqState->DStream); + if (MEM_64bits() && 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*/); + + if (MEM_32bits()) + BIT_reloadDStream(&seqState->DStream); + + 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 */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ + ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ + BIT_reloadDStream(&seqState->DStream); + } + } + + return seq; +} + #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd) { @@ -1420,7 +1552,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, /* decompress without overrunning litPtr begins */ { - seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset); + seq_t sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); /* Align the decompression loop to 32 + 16 bytes. * * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression @@ -1495,7 +1627,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, if (UNLIKELY(!--nbSeq)) break; BIT_reloadDStream(&(seqState.DStream)); - sequence = ZSTD_decodeSequence(&seqState, isLongOffset); + sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); } /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */ @@ -1548,7 +1680,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, #endif for (; ; ) { - seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset); + seq_t const sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); @@ -1647,8 +1779,8 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, # endif #endif - for ( ; ; ) { - seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset); + for ( ; nbSeq ; nbSeq--) { + seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); @@ -1658,15 +1790,13 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, return oneSeqSize; DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); op += oneSeqSize; - if (UNLIKELY(!--nbSeq)) - break; - BIT_reloadDStream(&(seqState.DStream)); } /* check if reached exact end */ DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq); RETURN_ERROR_IF(nbSeq, corruption_detected, ""); - RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, ""); + DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed); + RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); /* save reps for next block */ { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } } @@ -1763,7 +1893,7 @@ ZSTD_decompressSequencesLong_body( /* prepare in advance */ for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNblitBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) From 84e898a76c50aa31bd05b37a370c674250706254 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 16 Jun 2023 12:31:23 -0700 Subject: [PATCH 052/937] removed _old variant from splitLit --- lib/common/bitstream.h | 2 +- lib/decompress/zstd_decompress_block.c | 30 +++++++++++--------------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index a737f011c..676044989 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -411,7 +411,7 @@ MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD) FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) { /* note : once in overflow mode, a bitstream remains in this mode until it's reset */ - if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) { + if (UNLIKELY(bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))) { static const BitContainerType zeroFilled = 0; bitD->ptr = (const char*)&zeroFilled; /* aliasing is allowed for char */ /* overflow detected, erroneous scenario or end of stream: no update */ diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 2d0220043..24fc490b2 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -873,7 +873,7 @@ 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, BYTE const* ip, ptrdiff_t length) { +static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length) { ptrdiff_t const diff = op - ip; BYTE* const oend = op + length; @@ -1530,7 +1530,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart); const BYTE* const vBase = (const BYTE*) (dctx->virtualStart); const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); - DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer"); + DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq); /* Regen sequences */ if (nbSeq) { @@ -1552,7 +1552,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, /* decompress without overrunning litPtr begins */ { - seq_t sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); + seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); /* Align the decompression loop to 32 + 16 bytes. * * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression @@ -1626,15 +1626,15 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, op += oneSeqSize; if (UNLIKELY(!--nbSeq)) break; - BIT_reloadDStream(&(seqState.DStream)); - sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); + sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); } + DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)"); /* 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; - if (leftoverLit) - { + 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"); ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); sequence.litLength -= leftoverLit; @@ -1643,8 +1643,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, litPtr = dctx->litExtraBuffer; litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; dctx->litBufferLocation = ZSTD_not_in_dst; - { - size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); @@ -1653,9 +1652,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, return oneSeqSize; DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); op += oneSeqSize; - if (--nbSeq) - BIT_reloadDStream(&(seqState.DStream)); } + nbSeq--; } } @@ -1679,8 +1677,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, # endif #endif - for (; ; ) { - seq_t const sequence = ZSTD_decodeSequence_old(&seqState, isLongOffset); + for ( ; nbSeq ; nbSeq--) { + seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); @@ -1690,16 +1688,14 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, return oneSeqSize; DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); op += oneSeqSize; - if (UNLIKELY(!--nbSeq)) - break; - BIT_reloadDStream(&(seqState.DStream)); } } /* check if reached exact end */ DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer: after decode loop, remaining nbSeq : %i", nbSeq); RETURN_ERROR_IF(nbSeq, corruption_detected, ""); - RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, ""); + DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed); + RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); /* save reps for next block */ { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } } From 33fca19dd4b8cc9d68feb3daa129297b31680e47 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 16 Jun 2023 15:32:07 -0700 Subject: [PATCH 053/937] changed ZSTD_decompressSequences_bodySplitLitBuffer() decoding loop to behave more like the regular decoding loop. --- lib/decompress/zstd_decompress_block.c | 42 ++++++++++++-------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 24fc490b2..4a7d8ec40 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1532,7 +1532,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd); DEBUGLOG(5, "ZSTD_decompressSequences_bodySplitLitBuffer (%i seqs)", nbSeq); - /* Regen sequences */ + /* Literals are split between internal buffer & output buffer */ if (nbSeq) { seqState_t seqState; dctx->fseEntropy = 1; @@ -1551,8 +1551,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, BIT_DStream_completed < BIT_DStream_overflow); /* decompress without overrunning litPtr begins */ - { - seq_t sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); + { seq_t sequence; /* Align the decompression loop to 32 + 16 bytes. * * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression @@ -1614,20 +1613,19 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, #endif /* Handle the initial state where litBuffer is currently split between dst and litExtraBuffer */ - for (; litPtr + sequence.litLength <= dctx->litBufferEnd; ) { - size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); -#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) - assert(!ZSTD_isError(oneSeqSize)); - ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); -#endif - if (UNLIKELY(ZSTD_isError(oneSeqSize))) - return oneSeqSize; - DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); - op += oneSeqSize; - if (UNLIKELY(!--nbSeq)) - break; + for ( ; nbSeq; nbSeq--) { sequence = ZSTD_decodeSequence(&seqState, isLongOffset, nbSeq==1); - } + if (litPtr + sequence.litLength > dctx->litBufferEnd) break; + { size_t const oneSeqSize = ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequence.litLength - WILDCOPY_OVERLENGTH, sequence, &litPtr, litBufferEnd, prefixStart, vBase, dictEnd); +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase); +#endif + if (UNLIKELY(ZSTD_isError(oneSeqSize))) + return oneSeqSize; + DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize); + op += oneSeqSize; + } } DEBUGLOG(6, "reached: (litPtr + sequence.litLength > dctx->litBufferEnd)"); /* If there are more sequences, they will need to read literals from litExtraBuffer; copy over the remainder from dst and update litPtr and litEnd */ @@ -1657,8 +1655,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, } } - if (nbSeq > 0) /* there is remaining lit from extra buffer */ - { + if (nbSeq > 0) { + /* there is remaining lit from extra buffer */ #if defined(__GNUC__) && defined(__x86_64__) __asm__(".p2align 6"); @@ -1701,8 +1699,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, } /* last literal segment */ - if (dctx->litBufferLocation == ZSTD_split) /* split hasn't been reached yet, first get dst then copy litExtraBuffer */ - { + if (dctx->litBufferLocation == ZSTD_split) { + /* split hasn't been reached yet, first get dst then copy litExtraBuffer */ size_t const lastLLSize = litBufferEnd - litPtr; RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, ""); if (op != NULL) { @@ -1713,13 +1711,13 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; dctx->litBufferLocation = ZSTD_not_in_dst; } + /* copy last literals from interal buffer */ { size_t const lastLLSize = litBufferEnd - litPtr; RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, ""); if (op != NULL) { ZSTD_memcpy(op, litPtr, lastLLSize); op += lastLLSize; - } - } + } } return op-ostart; } From c60dcedcc91da9bb7550f237f79ee001ca6d1a75 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 16 Jun 2023 15:52:00 -0700 Subject: [PATCH 054/937] adapted long decoder to new decodeSequences removed older decodeSequences --- lib/decompress/zstd_decompress_block.c | 179 +++---------------------- 1 file changed, 21 insertions(+), 158 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 4a7d8ec40..0d6c2e011 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1214,128 +1214,6 @@ ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, U16 typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e; -/** - * ZSTD_decodeSequence_old(): - * @p longOffsets : tells the decoder to reload more bit while decoding large offsets - * only used in 32-bit mode - * @return : Sequence (litL + matchL + offset) - */ -FORCE_INLINE_TEMPLATE seq_t -ZSTD_decodeSequence_old(seqState_t* seqState, const ZSTD_longOffset_e longOffsets) -{ - seq_t seq; - /* - * ZSTD_seqSymbol is a 64 bits wide structure. - * It can be loaded in one operation - * and its fields extracted by simply shifting or bit-extracting on aarch64. - * GCC doesn't recognize this and generates more unnecessary ldr/ldrb/ldrh - * operations that cause performance drop. This can be avoided by using this - * ZSTD_memcpy hack. - */ -#if defined(__aarch64__) && (defined(__GNUC__) && !defined(__clang__)) - ZSTD_seqSymbol llDInfoS, mlDInfoS, ofDInfoS; - ZSTD_seqSymbol* const llDInfo = &llDInfoS; - ZSTD_seqSymbol* const mlDInfo = &mlDInfoS; - ZSTD_seqSymbol* const ofDInfo = &ofDInfoS; - 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 - 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 - 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; - - U16 const llNext = llDInfo->nextState; - U16 const mlNext = mlDInfo->nextState; - U16 const ofNext = ofDInfo->nextState; - U32 const llnbBits = llDInfo->nbBits; - U32 const mlnbBits = mlDInfo->nbBits; - U32 const ofnbBits = ofDInfo->nbBits; - - 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); - if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { - /* Always read extra bits, this keeps the logic simple, - * avoids branches, and avoids accidentally reading 0 bits. - */ - U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32; - offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); - BIT_reloadDStream(&seqState->DStream); - offset += BIT_readBitsFast(&seqState->DStream, extraBits); - } else { - offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ - if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); - } - seqState->prevOffset[2] = seqState->prevOffset[1]; - seqState->prevOffset[1] = seqState->prevOffset[0]; - seqState->prevOffset[0] = offset; - } else { - U32 const ll0 = (llDInfo->baseValue == 0); - if (LIKELY((ofBits == 0))) { - offset = seqState->prevOffset[ll0]; - seqState->prevOffset[1] = seqState->prevOffset[!ll0]; - seqState->prevOffset[0] = offset; - } else { - offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1); - { size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset]; - temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */ - if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1]; - seqState->prevOffset[1] = seqState->prevOffset[0]; - seqState->prevOffset[0] = offset = temp; - } } } - seq.offset = offset; - } - - if (mlBits > 0) - seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); - - if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) - BIT_reloadDStream(&seqState->DStream); - if (MEM_64bits() && 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*/); - - if (MEM_32bits()) - BIT_reloadDStream(&seqState->DStream); - - DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u", - (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); - - ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llNext, llnbBits); /* <= 9 bits */ - ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlNext, mlnbBits); /* <= 9 bits */ - if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ - ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ - } - - return seq; -} - /** * ZSTD_decodeSequence(): * @p longOffsets : tells the decoder to reload more bit while decoding large offsets @@ -1754,11 +1632,6 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); assert(dst != NULL); - ZSTD_STATIC_ASSERT( - BIT_DStream_unfinished < BIT_DStream_completed && - BIT_DStream_endOfBuffer < BIT_DStream_completed && - BIT_DStream_completed < BIT_DStream_overflow); - #if defined(__GNUC__) && defined(__x86_64__) __asm__(".p2align 6"); __asm__("nop"); @@ -1787,9 +1660,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, } /* check if reached exact end */ - DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq); - RETURN_ERROR_IF(nbSeq, corruption_detected, ""); - DEBUGLOG(5, "bitStream : start=%p, ptr=%p, bitsConsumed=%u", seqState.DStream.start, seqState.DStream.ptr, seqState.DStream.bitsConsumed); + assert(nbSeq == 0); RETURN_ERROR_IF(!BIT_endOfDStream(&seqState.DStream), corruption_detected, ""); /* save reps for next block */ { U32 i; for (i=0; ientropy.rep[i] = (U32)(seqState.prevOffset[i]); } @@ -1801,8 +1672,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, if (op != NULL) { ZSTD_memcpy(op, litPtr, lastLLSize); op += lastLLSize; - } - } + } } return op-ostart; } @@ -1886,20 +1756,17 @@ ZSTD_decompressSequencesLong_body( ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr); /* prepare in advance */ - for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNblitBufferLocation == ZSTD_split && litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength > dctx->litBufferEnd) - { + 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) @@ -1912,21 +1779,21 @@ ZSTD_decompressSequencesLong_body( litPtr = dctx->litExtraBuffer; litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; dctx->litBufferLocation = ZSTD_not_in_dst; - oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) - assert(!ZSTD_isError(oneSeqSize)); - ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); + assert(!ZSTD_isError(oneSeqSize)); + ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart); #endif - if (ZSTD_isError(oneSeqSize)) return oneSeqSize; + if (ZSTD_isError(oneSeqSize)) return oneSeqSize; - prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd); - sequences[seqNb & STORED_SEQS_MASK] = sequence; - op += oneSeqSize; - } + prefetchPos = ZSTD_prefetchMatch(prefetchPos, sequence, prefixStart, dictEnd); + sequences[seqNb & STORED_SEQS_MASK] = sequence; + op += oneSeqSize; + } } else { /* lit buffer is either wholly contained in first or second split, or not split at all*/ - oneSeqSize = dctx->litBufferLocation == ZSTD_split ? + size_t const oneSeqSize = dctx->litBufferLocation == ZSTD_split ? ZSTD_execSequenceSplitLitBuffer(op, oend, litPtr + sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK].litLength - WILDCOPY_OVERLENGTH, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd) : ZSTD_execSequence(op, oend, sequences[(seqNb - ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) @@ -1940,17 +1807,15 @@ ZSTD_decompressSequencesLong_body( op += oneSeqSize; } } - RETURN_ERROR_IF(seqNblitBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) - { + if (dctx->litBufferLocation == ZSTD_split && litPtr + sequence->litLength > dctx->litBufferEnd) { const size_t leftoverLit = dctx->litBufferEnd - litPtr; - if (leftoverLit) - { + if (leftoverLit) { RETURN_ERROR_IF(leftoverLit > (size_t)(oend - op), dstSize_tooSmall, "remaining lit must fit within dstBuffer"); ZSTD_safecopyDstBeforeSrc(op, litPtr, leftoverLit); sequence->litLength -= leftoverLit; @@ -1959,8 +1824,7 @@ ZSTD_decompressSequencesLong_body( litPtr = dctx->litExtraBuffer; litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE; dctx->litBufferLocation = ZSTD_not_in_dst; - { - size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); + { size_t const oneSeqSize = ZSTD_execSequence(op, oend, *sequence, &litPtr, litBufferEnd, prefixStart, dictStart, dictEnd); #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) assert(!ZSTD_isError(oneSeqSize)); ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart); @@ -1988,8 +1852,7 @@ ZSTD_decompressSequencesLong_body( } /* last literal segment */ - if (dctx->litBufferLocation == ZSTD_split) /* first deplete literal buffer in dst, then copy litExtraBuffer */ - { + if (dctx->litBufferLocation == ZSTD_split) { /* first deplete literal buffer in dst, then copy litExtraBuffer */ size_t const lastLLSize = litBufferEnd - litPtr; RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, ""); if (op != NULL) { From c123e69ad087cea5b779ce2a26b0845810783d12 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 16 Jun 2023 16:24:48 -0700 Subject: [PATCH 055/937] fixed static analyzer false positive regarding @sequence initialization make a mock initialization to please the tool --- lib/decompress/zstd_decompress_block.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 0d6c2e011..c90536ad7 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1429,7 +1429,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, BIT_DStream_completed < BIT_DStream_overflow); /* decompress without overrunning litPtr begins */ - { seq_t sequence; + { seq_t sequence = {0,0,0}; /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one interation) */ /* Align the decompression loop to 32 + 16 bytes. * * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression From e4aeaebc201ba49fec50b087aeb15343c63712e5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 20 Jun 2023 08:34:26 -0700 Subject: [PATCH 056/937] fixed incorrect test in Win32 pthread wrapper reported by @Banzai24-yht in #3683 --- .gitignore | 1 + lib/common/threading.c | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index a136ea394..e95a8d07c 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ build-* _codelite/ _zstdbench/ .clang_complete +compile_flags.txt *.idea *.swp .DS_Store diff --git a/lib/common/threading.c b/lib/common/threading.c index ca155b9b9..25bb8b981 100644 --- a/lib/common/threading.c +++ b/lib/common/threading.c @@ -73,10 +73,12 @@ int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused, ZSTD_thread_params_t thread_param; (void)unused; + if (thread==NULL) return -1; + *thread = NULL; + thread_param.start_routine = start_routine; thread_param.arg = arg; thread_param.initialized = 0; - *thread = NULL; /* Setup thread initialization synchronization */ if(ZSTD_pthread_cond_init(&thread_param.initialized_cond, NULL)) { @@ -91,7 +93,7 @@ int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused, /* Spawn thread */ *thread = (HANDLE)_beginthreadex(NULL, 0, worker, &thread_param, 0, NULL); - if (!thread) { + if (*thread==NULL) { ZSTD_pthread_mutex_destroy(&thread_param.initialized_mutex); ZSTD_pthread_cond_destroy(&thread_param.initialized_cond); return errno; @@ -137,6 +139,7 @@ int ZSTD_pthread_join(ZSTD_pthread_t thread) int ZSTD_pthread_mutex_init(ZSTD_pthread_mutex_t* mutex, pthread_mutexattr_t const* attr) { + assert(mutex != NULL); *mutex = (pthread_mutex_t*)ZSTD_malloc(sizeof(pthread_mutex_t)); if (!*mutex) return 1; @@ -145,6 +148,7 @@ int ZSTD_pthread_mutex_init(ZSTD_pthread_mutex_t* mutex, pthread_mutexattr_t con int ZSTD_pthread_mutex_destroy(ZSTD_pthread_mutex_t* mutex) { + assert(mutex != NULL); if (!*mutex) return 0; { @@ -156,6 +160,7 @@ int ZSTD_pthread_mutex_destroy(ZSTD_pthread_mutex_t* mutex) int ZSTD_pthread_cond_init(ZSTD_pthread_cond_t* cond, pthread_condattr_t const* attr) { + assert(cond != NULL); *cond = (pthread_cond_t*)ZSTD_malloc(sizeof(pthread_cond_t)); if (!*cond) return 1; @@ -164,6 +169,7 @@ int ZSTD_pthread_cond_init(ZSTD_pthread_cond_t* cond, pthread_condattr_t const* int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond) { + assert(cond != NULL); if (!*cond) return 0; { From f307493711b74ddfdbf9da711f75c4e07bcc93a3 Mon Sep 17 00:00:00 2001 From: Ed Maste Date: Wed, 21 Jun 2023 12:16:26 -0400 Subject: [PATCH 057/937] Update FreeBSD CI images to latest supported releases --- .cirrus.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index 27ca65e8d..047e77f69 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -2,8 +2,8 @@ task: name: FreeBSD (shortest) freebsd_instance: matrix: - image_family: freebsd-13-0 - image_family: freebsd-12-2 + image_family: freebsd-13-2 + image_family: freebsd-12-4 install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From c6a888c073a0a6693026e67e8db3813ba6b78850 Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Wed, 21 Jun 2023 18:52:50 -0700 Subject: [PATCH 058/937] suppress false error message in LDM mode --- lib/compress/zstd_compress.c | 10 +++------- lib/compress/zstd_compress_internal.h | 3 +-- lib/compress/zstdmt_compress.c | 5 +---- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 19446b63f..48cee4db7 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4609,19 +4609,15 @@ size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity) } } -size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq) +void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq) { - RETURN_ERROR_IF(cctx->stage != ZSTDcs_init, stage_wrong, - "wrong cctx stage"); - RETURN_ERROR_IF(cctx->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable, - parameter_unsupported, - "incompatible with ldm"); + assert(cctx->stage == ZSTDcs_init); + assert(nbSeq == 0 || cctx->appliedParams.ldmParams.enableLdm != ZSTD_ps_enable); cctx->externSeqStore.seq = seq; cctx->externSeqStore.size = nbSeq; cctx->externSeqStore.capacity = nbSeq; cctx->externSeqStore.pos = 0; cctx->externSeqStore.posInSequence = 0; - return 0; } diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 10f68d010..ac8dfb71a 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1467,11 +1467,10 @@ size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity); * This cannot be used when long range matching is enabled. * Zstd will use these sequences, and pass the literals to a secondary block * compressor. - * @return : An error code on failure. * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory * access and data corruption. */ -size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq); +void ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq); /** ZSTD_cycleLog() : * condition for correct operation : hashLog > 1 */ diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 678607556..add99d769 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -601,11 +601,8 @@ static void ZSTDMT_serialState_update(serialState_t* serialState, ZSTD_pthread_mutex_unlock(&serialState->mutex); if (seqStore.size > 0) { - size_t const err = ZSTD_referenceExternalSequences( - jobCCtx, seqStore.seq, seqStore.size); + ZSTD_referenceExternalSequences(jobCCtx, seqStore.seq, seqStore.size); assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable); - assert(!ZSTD_isError(err)); - (void)err; } } From b1a30e2b4a69e6fcca9c2a6f9d4e43e8e3b243c8 Mon Sep 17 00:00:00 2001 From: Nidhi Jaju Date: Mon, 26 Jun 2023 00:07:30 +0000 Subject: [PATCH 059/937] hide asm functions on apple platforms --- lib/common/portability_macros.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index 8fd6ea82d..e50314a78 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -68,6 +68,8 @@ /* Mark the internal assembly functions as hidden */ #ifdef __ELF__ # define ZSTD_HIDE_ASM_FUNCTION(func) .hidden func +#elif defined(__APPLE__) +# define ZSTD_HIDE_ASM_FUNCTION(func) .private_extern func #else # define ZSTD_HIDE_ASM_FUNCTION(func) #endif From 1a6278c82d3b35cd8abd82db7bc5dc0907b838dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Jun 2023 05:59:38 +0000 Subject: [PATCH 060/937] Bump github/codeql-action from 2.3.2 to 2.20.1 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.3.2 to 2.20.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/f3feb00acb00f31a6f60280e6ace9ca31d91c76a...f6e388ebf0efc915c6c5b165b019ee61a6746a38) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index d9aea8adb..42579d250 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@f3feb00acb00f31a6f60280e6ace9ca31d91c76a # tag=v2.3.2 + uses: github/codeql-action/upload-sarif@f6e388ebf0efc915c6c5b165b019ee61a6746a38 # tag=v2.20.1 with: sarif_file: results.sarif From 2c97f5dbedb0b581c733eb658665a9cc886eccef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Jun 2023 05:59:43 +0000 Subject: [PATCH 061/937] Bump ossf/scorecard-action from 2.1.3 to 2.2.0 Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.1.3 to 2.2.0. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/80e868c13c90f172d68d1f4501dee99e2479f7af...08b4669551908b1024bb425080c797723083c031) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index d9aea8adb..4edb140fe 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -32,7 +32,7 @@ jobs: persist-credentials: false - name: "Run analysis" - uses: ossf/scorecard-action@80e868c13c90f172d68d1f4501dee99e2479f7af # tag=v2.1.3 + uses: ossf/scorecard-action@08b4669551908b1024bb425080c797723083c031 # tag=v2.2.0 with: results_file: results.sarif results_format: sarif From 065ea9274fbbf794616df86a6376cd1c7f0dd5ca Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 05:37:59 +0000 Subject: [PATCH 062/937] Bump github/codeql-action from 2.20.1 to 2.20.3 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.20.1 to 2.20.3. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/f6e388ebf0efc915c6c5b165b019ee61a6746a38...46ed16ded91731b2df79a2893d3aea8e9f03b5c4) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 0dd1e59fa..5737abc8d 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@f6e388ebf0efc915c6c5b165b019ee61a6746a38 # tag=v2.20.1 + uses: github/codeql-action/upload-sarif@46ed16ded91731b2df79a2893d3aea8e9f03b5c4 # tag=v2.20.3 with: sarif_file: results.sarif From a1b9a5ad0e1a10bea2315132bef21de3ed9cebc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20Hoffr=C3=A9n?= Date: Wed, 19 Jul 2023 21:49:43 +0300 Subject: [PATCH 063/937] Fix typographical error in README.md --- CONTRIBUTING.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f5e747ae1..47f5bb8f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -171,8 +171,8 @@ who want earlier signal. | Cirrus CI | Used for testing on FreeBSD | https://github.com/marketplace/cirrus-ci/ | `.cirrus.yml` | | Circle CI | Historically was used to provide faster signal,
but we may be able to migrate these to Github Actions | https://circleci.com/docs/2.0/getting-started/#setting-up-circleci
https://youtu.be/Js3hMUsSZ2c
https://circleci.com/docs/2.0/enable-checks/ | `.circleci/config.yml` | -Note: the instructions linked above mostly cover how to set up a repository with CI from scratch. -The general idea should be the same for setting up CI on your fork of zstd, but you may have to +Note: the instructions linked above mostly cover how to set up a repository with CI from scratch. +The general idea should be the same for setting up CI on your fork of zstd, but you may have to follow slightly different steps. In particular, please ignore any instructions related to setting up config files (since zstd already has configs for each of these services). @@ -216,7 +216,7 @@ will typically not be stable enough to obtain reliable benchmark results. If you hands on a desktop, this is usually a better scenario. Of course, benchmarking can be done on non-hyper-stable machines as well. You will just have to -do a little more work to ensure that you are in fact measuring the changes you've made not and +do a little more work to ensure that you are in fact measuring the changes you've made and not noise. Here are some things you can do to make your benchmarks more stable: 1. The most simple thing you can do to drastically improve the stability of your benchmark is From 55ff3e4e17ea42a7c3726e51945c483a18d8c4c8 Mon Sep 17 00:00:00 2001 From: Jacob Greenfield Date: Tue, 18 Jul 2023 10:48:46 -0400 Subject: [PATCH 064/937] Save one byte on the frame epilogue --- lib/compress/zstd_compress.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 48cee4db7..209f3b0ee 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -5192,8 +5192,9 @@ static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity) if (cctx->stage != ZSTDcs_ending) { /* write one last empty block, make it the "last" block */ U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0; - RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for epilogue"); - MEM_writeLE32(op, cBlockHeader24); + ZSTD_STATIC_ASSERT(ZSTD_BLOCKHEADERSIZE == 3); + RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "no room for epilogue"); + MEM_writeLE24(op, cBlockHeader24); op += ZSTD_blockHeaderSize; dstCapacity -= ZSTD_blockHeaderSize; } From de6b46dfc80d950a32176c7eca79bb229d47f501 Mon Sep 17 00:00:00 2001 From: Gianfranco Costamagna Date: Fri, 7 Jul 2023 09:26:30 +0200 Subject: [PATCH 065/937] Update fileio.c: fix build failure with enabled LTO MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For some reasons when LTO is enabled, the compiler complains about statbuf variable not being correctly initialized, even though the variable has an assert != NULL just few lines below (FIO_getDictFileStat) This is the fixed build failure: x86_64-linux-gnu-gcc -g -O2 -ffile-prefix-map=/<>=. -flto=auto -ffat-lto-objects -fstack-protector-strong -Wformat -Werror=format-security -fdebug-prefix-map=/<>=/usr/src/libzstd-1.5.5+dfsg2-1 -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow -Wstrict-aliasing=1 -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes -Wundef -Wpointer-arith -Wvla -Wformat=2 -Winit-self -Wfloat-equal -Wwrite-strings -Wredundant-decls -Wmissing-prototypes -Wc++-compat -g -Werror -Wa,--noexecstack -Wdate-time -D_FORTIFY_SOURCE=2 -DXXH_NAMESPACE=ZSTD_ -DDEBUGLEVEL=1 -DZSTD_LEGACY_SUPPORT=5 -DZSTD_MULTITHREAD -DZSTD_GZCOMPRESS -DZSTD_GZDECOMPRESS -DZSTD_LZMACOMPRESS -DZSTD_LZMADECOMPRESS -DZSTD_LZ4COMPRESS -DZSTD_LZ4DECOMPRESS -DZSTD_LEGACY_SUPPORT=5 -c -MT obj/conf_086c46a51a716b674719b8acb8484eb8/zstdcli_trace.o -MMD -MP -MF obj/conf_086c46a51a716b674719b8acb8484eb8/zstdcli_trace.d -o obj/conf_086c46a51a716b674719b8acb8484eb8/zstdcli_trace.o zstdcli_trace.c In function ‘UTIL_isRegularFileStat’, inlined from ‘UTIL_getFileSizeStat’ at util.c:524:10, inlined from ‘FIO_createDResources’ at fileio.c:2230:30: util.c:209:12: error: ‘statbuf.st_mode’ may be used uninitialized [-Werror=maybe-uninitialized] 209 | return S_ISREG(statbuf->st_mode) != 0; | ^ fileio.c: In function ‘FIO_createDResources’: fileio.c:2223:12: note: ‘statbuf’ declared here 2223 | stat_t statbuf; | ^ lto1: all warnings being treated as errors --- programs/fileio.c | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/fileio.c b/programs/fileio.c index 84a0f48f7..217232542 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -2222,6 +2222,7 @@ static dRess_t FIO_createDResources(FIO_prefs_t* const prefs, const char* dictFi int forceNoUseMMap = prefs->mmapDict == ZSTD_ps_disable; stat_t statbuf; dRess_t ress; + memset(&statbuf, 0, sizeof(statbuf)); memset(&ress, 0, sizeof(ress)); FIO_getDictFileStat(dictFileName, &statbuf); From 4d267f3d4f9f85eecf98d1a2353408b8e840f1a3 Mon Sep 17 00:00:00 2001 From: void0red <30990023+void0red@users.noreply.github.com> Date: Fri, 21 Jul 2023 12:17:03 +0800 Subject: [PATCH 066/937] fileio_asyncio: handle malloc fails in AIO_ReadPool_create --- programs/fileio_asyncio.c | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/fileio_asyncio.c b/programs/fileio_asyncio.c index fe9cca95d..dbf0c7564 100644 --- a/programs/fileio_asyncio.c +++ b/programs/fileio_asyncio.c @@ -551,6 +551,7 @@ ReadPoolCtx_t* AIO_ReadPool_create(const FIO_prefs_t* prefs, size_t bufferSize) AIO_IOPool_init(&ctx->base, prefs, AIO_ReadPool_executeReadJob, bufferSize); ctx->coalesceBuffer = (U8*) malloc(bufferSize * 2); + if(!ctx->coalesceBuffer) EXM_THROW(100, "Allocation error : not enough memory"); ctx->srcBuffer = ctx->coalesceBuffer; ctx->srcBufferLoaded = 0; ctx->completedJobsCount = 0; From e99d554903643e8dda22d664bbba62e8a9d5b0b0 Mon Sep 17 00:00:00 2001 From: jysh1214 Date: Tue, 1 Aug 2023 10:43:33 +0800 Subject: [PATCH 067/937] Fixed typo --- tests/playTests.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/playTests.sh b/tests/playTests.sh index 05dc00429..bdbd00142 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -16,18 +16,18 @@ datagen() { } zstd() { - if [ -z "$EXEC_PREFIX" ]; then + if [ -z "$EXE_PREFIX" ]; then "$ZSTD_BIN" "$@" else - "$EXEC_PREFIX" "$ZSTD_BIN" "$@" + "$EXE_PREFIX" "$ZSTD_BIN" "$@" fi } sudoZstd() { - if [ -z "$EXEC_PREFIX" ]; then + if [ -z "$EXE_PREFIX" ]; then sudo "$ZSTD_BIN" "$@" else - sudo "$EXEC_PREFIX" "$ZSTD_BIN" "$@" + sudo "$EXE_PREFIX" "$ZSTD_BIN" "$@" fi } From 78dbba76b81ea1d8713900b57bc5d5f5f43bf74b Mon Sep 17 00:00:00 2001 From: Quentin Boswank Date: Sun, 13 Aug 2023 19:44:15 +0200 Subject: [PATCH 068/937] Updated Makefiles for full MSYS2 and Cygwin installation and testing support. They are Linux-like environments under Windows and have all the tools needed to support staged installation and testing. Beware: this only affects the make build system. --- Makefile | 2 +- lib/Makefile | 2 +- programs/Makefile | 2 +- tests/Makefile | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 72a9480aa..fd95c3890 100644 --- a/Makefile +++ b/Makefile @@ -151,7 +151,7 @@ clean: #------------------------------------------------------------------------------ # make install is validated only for Linux, macOS, Hurd and some BSD targets #------------------------------------------------------------------------------ -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT Haiku AIX)) +ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT CYGWIN_NT Haiku AIX)) HOST_OS = POSIX diff --git a/lib/Makefile b/lib/Makefile index a4cf61ab1..6d349a3b4 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -249,7 +249,7 @@ clean: #----------------------------------------------------------------------------- # make install is validated only for below listed environments #----------------------------------------------------------------------------- -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX)) +ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT CYGWIN_NT)) lib: libzstd.pc diff --git a/programs/Makefile b/programs/Makefile index 8507abef3..be83c2493 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -346,7 +346,7 @@ include $(wildcard $(DEPFILES)) #----------------------------------------------------------------------------- # make install is validated only for Linux, macOS, BSD, Hurd and Solaris targets #----------------------------------------------------------------------------- -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX)) +ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT CYGWIN_NT)) HAVE_COLORNEVER = $(shell echo a | egrep --color=never a > /dev/null 2> /dev/null && echo 1 || echo 0) EGREP_OPTIONS ?= diff --git a/tests/Makefile b/tests/Makefile index 778c7d675..c31e75005 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -263,7 +263,7 @@ clean: # valgrind tests validated only for some posix platforms #---------------------------------------------------------------------------------- UNAME := $(shell uname) -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS AIX)) +ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS AIX CYGWIN_NT)) HOST_OS = POSIX .PHONY: test-valgrind From 969e54f26ee5e03677d47b6449be02fe48e6d349 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 11 Aug 2023 17:09:07 -0700 Subject: [PATCH 069/937] Improve dual license wording in README We are licensed under BSD or GPLv2. It is clear in our headers, but not in the README. Fixes #3717 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f91e68fdb..89857bf9b 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ targeting real-time compression scenarios at zlib-level and better compression r It's backed by a very fast entropy stage, provided by [Huff0 and FSE library](https://github.com/Cyan4973/FiniteStateEntropy). Zstandard's format is stable and documented in [RFC8878](https://datatracker.ietf.org/doc/html/rfc8878). Multiple independent implementations are already available. -This repository represents the reference implementation, provided as an open-source dual [BSD](LICENSE) and [GPLv2](COPYING) licensed **C** library, +This repository represents the reference implementation, provided as an open-source dual [BSD](LICENSE) OR [GPLv2](COPYING) licensed **C** library, and a command line utility producing and decoding `.zst`, `.gz`, `.xz` and `.lz4` files. Should your project require another programming language, a list of known ports and bindings is provided on [Zstandard homepage](https://facebook.github.io/zstd/#other-languages). @@ -213,7 +213,7 @@ Zstandard is considered safe for production environments. ## License -Zstandard is dual-licensed under [BSD](LICENSE) and [GPLv2](COPYING). +Zstandard is dual-licensed under [BSD](LICENSE) OR [GPLv2](COPYING). ## Contributing From 5f5bdc1e5d23544391df1c47cec3a69b96a09f5b Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 16 Aug 2023 12:08:52 -0400 Subject: [PATCH 070/937] Easy: Move Helper Functions Up --- lib/compress/zstd_cwksp.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index cfe808f15..9aeed1943 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -636,6 +636,15 @@ MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) { ZSTD_cwksp_assert_internal_consistency(ws); } +MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) { + return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace); +} + +MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) { + return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace) + + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart); +} + /** * The provided workspace takes ownership of the buffer [start, start+size). * Any existing values in the workspace are ignored (the previously managed @@ -680,15 +689,6 @@ MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) { ZSTD_memset(src, 0, sizeof(ZSTD_cwksp)); } -MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) { - return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace); -} - -MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) { - return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace) - + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart); -} - MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) { return ws->allocFailed; } From 9987d2f5942a7701b388eec4307be71a121e5652 Mon Sep 17 00:00:00 2001 From: "W. Felix Handte" Date: Wed, 16 Aug 2023 12:09:12 -0400 Subject: [PATCH 071/937] Unpoison Workspace Memory Before Freeing to Custom Free MSAN is hooked into the system malloc, but when the user provides a custom allocator, it may not provide the same cleansing behavior. So if we leave memory poisoned and return it to the user's allocator, where it is re-used elsewhere, our poisoning can blow up in some other context. --- lib/compress/zstd_cwksp.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index 9aeed1943..a3efc56e5 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -676,6 +676,11 @@ MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) { void *ptr = ws->workspace; DEBUGLOG(4, "cwksp: freeing workspace"); +#if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE) + if (ptr != NULL && customMem.customFree != NULL) { + __msan_unpoison(ptr, ZSTD_cwksp_sizeof(ws)); + } +#endif ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp)); ZSTD_customFree(ptr, customMem); } From a07d7c4e29f9329a1c98fbecc2e54ed6b663caef Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 16 Aug 2023 10:43:39 -0700 Subject: [PATCH 072/937] added ZSTD_decompressDCtx() benchmark option to fullbench useful to compare the difference between ZSTD_decompress and ZSTD_decompressDCtx(). --- tests/fullbench.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 0391107b9..c8f0c0af1 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -138,7 +138,14 @@ static size_t local_ZSTD_decompress(const void* src, size_t srcSize, return ZSTD_decompress(dst, dstSize, buff2, g_cSize); } -static ZSTD_DCtx* g_zdc = NULL; +static ZSTD_DCtx* g_zdc = NULL; /* will be initialized within benchMem */ +static size_t local_ZSTD_decompressDCtx(const void* src, size_t srcSize, + void* dst, size_t dstSize, + void* buff2) +{ + (void)src; (void)srcSize; + return ZSTD_decompressDCtx(g_zdc, dst, dstSize, buff2, g_cSize); +} #ifndef ZSTD_DLL_IMPORT @@ -452,6 +459,9 @@ static int benchMem(unsigned benchNb, case 3: benchFunction = local_ZSTD_compress_freshCCtx; benchName = "compress_freshCCtx"; break; + case 4: + benchFunction = local_ZSTD_decompressDCtx; benchName = "decompressDCtx"; + break; #ifndef ZSTD_DLL_IMPORT case 11: benchFunction = local_ZSTD_compressContinue; benchName = "compressContinue"; @@ -551,6 +561,9 @@ static int benchMem(unsigned benchNb, case 3: payload = &cparams; break; + case 4: + g_cSize = ZSTD_compress(dstBuff2, dstBuffSize, src, srcSize, cLevel); + break; #ifndef ZSTD_DLL_IMPORT case 11: payload = &cparams; From a02d81f944c24aca2ccca2f16a6a96474f97e18b Mon Sep 17 00:00:00 2001 From: Mustafa UZUN Date: Sat, 19 Aug 2023 15:44:53 +0300 Subject: [PATCH 073/937] fix: ZSTD_BUILD_DECOMPRESSION message --- build/cmake/lib/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 3cab017a7..cf1252e19 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -13,7 +13,7 @@ set(CMAKE_INCLUDE_CURRENT_DIR TRUE) option(ZSTD_BUILD_STATIC "BUILD STATIC LIBRARIES" ON) option(ZSTD_BUILD_SHARED "BUILD SHARED LIBRARIES" ON) option(ZSTD_BUILD_COMPRESSION "BUILD COMPRESSION MODULE" ON) -option(ZSTD_BUILD_DECOMPRESSION "BUILD DECOMPRESSION MODUEL" ON) +option(ZSTD_BUILD_DECOMPRESSION "BUILD DECOMPRESSION MODULE" ON) option(ZSTD_BUILD_DICTBUILDER "BUILD DICTBUILDER MODULE" ON) option(ZSTD_BUILD_DEPRECATED "BUILD DEPRECATED MODULE" OFF) From db0ae65436c6aa977b60b8a7fd7d4522a3cd14ae Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Aug 2023 05:51:56 +0000 Subject: [PATCH 074/937] Bump github/codeql-action from 2.20.3 to 2.21.4 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.20.3 to 2.21.4. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/46ed16ded91731b2df79a2893d3aea8e9f03b5c4...a09933a12a80f87b87005513f0abb1494c27a716) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 5737abc8d..0d2838118 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@46ed16ded91731b2df79a2893d3aea8e9f03b5c4 # tag=v2.20.3 + uses: github/codeql-action/upload-sarif@a09933a12a80f87b87005513f0abb1494c27a716 # tag=v2.21.4 with: sarif_file: results.sarif From bd02c9be6e3708c6dd53f4df1f4dc13d29441e89 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Mon, 21 Aug 2023 11:33:29 -0700 Subject: [PATCH 075/937] No longer reject dictionaries with literals maxSymbolValue < 255 We already have logic in our Huffman encoder to validate Huffman tables with missing symbols. We use this for higher compression levels to re-use the previous blocks statistics, or when the dictionaries table has zero-weighted symbols. This check was leftover as an oversight from before we added validation for Huffman tables. I validated that the `dictionary_loader` fuzzer has coverage of every line in the `ZSTD_loadCEntropy()` function to validate that it is correctly testing this function. --- lib/compress/zstd_compress.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 209f3b0ee..36c1f99e8 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4904,11 +4904,10 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, /* We only set the loaded table as valid if it contains all non-zero * weights. Otherwise, we set it to check */ - if (!hasZeroWeights) + if (!hasZeroWeights && maxSymbolValue == 255) bs->entropy.huf.repeatMode = HUF_repeat_valid; RETURN_ERROR_IF(HUF_isError(hufHeaderSize), dictionary_corrupted, ""); - RETURN_ERROR_IF(maxSymbolValue < 255, dictionary_corrupted, ""); dictPtr += hufHeaderSize; } From ecb86d82868d60517453151127b229c96ff89fec Mon Sep 17 00:00:00 2001 From: "Dmitry V. Levin" Date: Tue, 8 Aug 2023 08:00:00 +0000 Subject: [PATCH 076/937] zdictlib: fix prototype mismatch Fix the following warnings reported by the compiler when ZDICTLIB_STATIC_API is not defined to ZDICTLIB_API: lib/dictBuilder/cover.c:1122:21: warning: redeclaration of 'ZDICT_optimizeTrainFromBuffer_cover' with different visibility (old visibility preserved) lib/dictBuilder/cover.c:736:21: warning: redeclaration of 'ZDICT_trainFromBuffer_cover' with different visibility (old visibility +preserved) lib/dictBuilder/fastcover.c:549:1: warning: redeclaration of 'ZDICT_trainFromBuffer_fastCover' with different visibility (old visibility preserved) lib/dictBuilder/fastcover.c:618:1: warning: redeclaration of 'ZDICT_optimizeTrainFromBuffer_fastCover' with different visibility (old visibility preserved) --- lib/dictBuilder/cover.c | 4 ++-- lib/dictBuilder/fastcover.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 9e5e7d5b5..e7fcfd209 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -733,7 +733,7 @@ static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs, return tail; } -ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover( +ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover( void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples, ZDICT_cover_params_t parameters) @@ -1119,7 +1119,7 @@ _cleanup: free(freqs); } -ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover( +ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover( void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples, ZDICT_cover_params_t* parameters) diff --git a/lib/dictBuilder/fastcover.c b/lib/dictBuilder/fastcover.c index 46bba0120..a958eb337 100644 --- a/lib/dictBuilder/fastcover.c +++ b/lib/dictBuilder/fastcover.c @@ -545,7 +545,7 @@ FASTCOVER_convertToFastCoverParams(ZDICT_cover_params_t coverParams, } -ZDICTLIB_API size_t +ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples, @@ -614,7 +614,7 @@ ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity, } -ZDICTLIB_API size_t +ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_fastCover( void* dictBuffer, size_t dictBufferCapacity, const void* samplesBuffer, From c27fa399042f466080e79bb4fd8a4871bc0bcf28 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 24 Aug 2023 16:33:42 -0700 Subject: [PATCH 077/937] Work around nullptr-with-nonzero-offset warning See comment. --- lib/decompress/zstd_decompress.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 94eb95151..ccfd84fa4 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -1548,6 +1548,12 @@ size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx) dctx->stage = ZSTDds_getFrameHeaderSize; dctx->processedCSize = 0; dctx->decodedSize = 0; + /* Set to non-null because ZSTD_prefetchMatch() may end up doing addition + * with this value for corrupted frames. However, it then just passes the + * pointer to PREFETCH_L1(), which doesn't require valid pointers. But, + * if it is NULL we get nullptr-with-nonzero-offset UBSAN warnings. + */ + dctx->previousDstEnd = ""; dctx->previousDstEnd = NULL; dctx->prefixStart = NULL; dctx->virtualStart = NULL; From 396ef5b434e5e7f15773a7495f374a99a6377778 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 24 Aug 2023 14:41:21 -0700 Subject: [PATCH 078/937] Fix & refactor Huffman repeat tables for dictionaries The Huffman repeat mode checker assumed that the CTable was zeroed in the region `[maxSymbolValue + 1, 256)`. This assumption didn't hold for tables built in the dictionaries, because it didn't go through the same codepath. Since this code was originally written, we added a header to the CTable that specifies the `tableLog`. Add `maxSymbolValue` to that header, and check that the table's `maxSymbolValue` is at least the block's `maxSymbolValue`. This solution is cleaner because we write this header for every CTable we build, so it can't be missed in any code path. Credit to OSS-Fuzz --- lib/common/huf.h | 15 ++++++++- lib/compress/huf_compress.c | 61 ++++++++++++++++++++++++++----------- 2 files changed, 58 insertions(+), 18 deletions(-) diff --git a/lib/common/huf.h b/lib/common/huf.h index 73d1ee565..99bf85d6f 100644 --- a/lib/common/huf.h +++ b/lib/common/huf.h @@ -197,9 +197,22 @@ size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void /** HUF_getNbBitsFromCTable() : * Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX - * Note 1 : is not inlined, as HUF_CElt definition is private */ + * Note 1 : If symbolValue > HUF_readCTableHeader(symbolTable).maxSymbolValue, returns 0 + * Note 2 : is not inlined, as HUF_CElt definition is private + */ U32 HUF_getNbBitsFromCTable(const HUF_CElt* symbolTable, U32 symbolValue); +typedef struct { + BYTE tableLog; + BYTE maxSymbolValue; + BYTE unused[sizeof(size_t) - 2]; +} HUF_CTableHeader; + +/** HUF_readCTableHeader() : + * @returns The header from the CTable specifying the tableLog and the maxSymbolValue. + */ +HUF_CTableHeader HUF_readCTableHeader(HUF_CElt const* ctable); + /* * HUF_decompress() does the following: * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics diff --git a/lib/compress/huf_compress.c b/lib/compress/huf_compress.c index 29871877a..3fe257896 100644 --- a/lib/compress/huf_compress.c +++ b/lib/compress/huf_compress.c @@ -220,6 +220,25 @@ static void HUF_setValue(HUF_CElt* elt, size_t value) } } +HUF_CTableHeader HUF_readCTableHeader(HUF_CElt const* ctable) +{ + HUF_CTableHeader header; + ZSTD_memcpy(&header, ctable, sizeof(header)); + return header; +} + +static void HUF_writeCTableHeader(HUF_CElt* ctable, U32 tableLog, U32 maxSymbolValue) +{ + HUF_CTableHeader header; + HUF_STATIC_ASSERT(sizeof(ctable[0]) == sizeof(header)); + ZSTD_memset(&header, 0, sizeof(header)); + assert(tableLog < 256); + header.tableLog = (BYTE)tableLog; + assert(maxSymbolValue < 256); + header.maxSymbolValue = (BYTE)maxSymbolValue; + ZSTD_memcpy(ctable, &header, sizeof(header)); +} + typedef struct { HUF_CompressWeightsWksp wksp; BYTE bitsToWeight[HUF_TABLELOG_MAX + 1]; /* precomputed conversion table */ @@ -237,6 +256,9 @@ size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize, HUF_STATIC_ASSERT(HUF_CTABLE_WORKSPACE_SIZE >= sizeof(HUF_WriteCTableWksp)); + assert(HUF_readCTableHeader(CTable).maxSymbolValue == maxSymbolValue); + assert(HUF_readCTableHeader(CTable).tableLog == huffLog); + /* check conditions */ if (workspaceSize < sizeof(HUF_WriteCTableWksp)) return ERROR(GENERIC); if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge); @@ -283,7 +305,9 @@ size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge); if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall); - CTable[0] = tableLog; + *maxSymbolValuePtr = nbSymbols - 1; + + HUF_writeCTableHeader(CTable, tableLog, *maxSymbolValuePtr); /* Prepare base value per rank */ { U32 n, nextRankStart = 0; @@ -315,7 +339,6 @@ size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void { U32 n; for (n=0; n HUF_readCTableHeader(CTable).maxSymbolValue) + return 0; return (U32)HUF_getNbBits(ct[symbolValue]); } @@ -723,7 +748,8 @@ static void HUF_buildCTableFromTree(HUF_CElt* CTable, nodeElt const* huffNode, i HUF_setNbBits(ct + huffNode[n].byte, huffNode[n].nbBits); /* push nbBits per symbol, symbol order */ for (n=0; nCTable + 1, maxSymbolValue+1)); } - /* Zero unused symbols in CTable, so we can check it for validity */ - { - size_t const ctableSize = HUF_CTABLE_SIZE_ST(maxSymbolValue); - size_t const unusedSize = sizeof(table->CTable) - ctableSize * sizeof(HUF_CElt); - ZSTD_memset(table->CTable + ctableSize, 0, unusedSize); - } /* Write table description header */ { CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog, From 253873220f26c0fd43aef740751355f91f40b750 Mon Sep 17 00:00:00 2001 From: Johan Mabille Date: Sat, 26 Aug 2023 00:40:35 +0200 Subject: [PATCH 079/937] Fixed zstd cmake shared build on windows --- build/cmake/programs/CMakeLists.txt | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/build/cmake/programs/CMakeLists.txt b/build/cmake/programs/CMakeLists.txt index 58d998e42..6a8165866 100644 --- a/build/cmake/programs/CMakeLists.txt +++ b/build/cmake/programs/CMakeLists.txt @@ -32,7 +32,17 @@ if (MSVC) set(PlatformDependResources ${MSVC_RESOURCE_DIR}/zstd.rc) endif () -add_executable(zstd ${PROGRAMS_DIR}/zstdcli.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/fileio.c ${PROGRAMS_DIR}/fileio_asyncio.c ${PROGRAMS_DIR}/benchfn.c ${PROGRAMS_DIR}/benchzstd.c ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/dibio.c ${PROGRAMS_DIR}/zstdcli_trace.c ${PlatformDependResources}) +set(ZSTD_PROGRAM_SRCS ${PROGRAMS_DIR}/zstdcli.c ${PROGRAMS_DIR}/util.c + ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/fileio.c + ${PROGRAMS_DIR}/fileio_asyncio.c ${PROGRAMS_DIR}/benchfn.c + ${PROGRAMS_DIR}/benchzstd.c ${PROGRAMS_DIR}/datagen.c + ${PROGRAMS_DIR}/dibio.c ${PROGRAMS_DIR}/zstdcli_trace.c + ${PlatformDependResources}) +if (MSVC AND ZSTD_PROGRAMS_LINK_SHARED) + list(APPEND ZSTD_PROGRAM_SRCS ${LIBRARY_DIR}/common/pool.c ${LIBRARY_DIR}/common/threading.c) +endif () + +add_executable(zstd ${ZSTD_PROGRAM_SRCS}) target_link_libraries(zstd ${PROGRAMS_ZSTD_LINK_TARGET}) if (CMAKE_SYSTEM_NAME MATCHES "(Solaris|SunOS)") target_link_libraries(zstd rt) @@ -75,7 +85,9 @@ if (UNIX) ${CMAKE_CURRENT_BINARY_DIR}/zstdless.1 DESTINATION "${MAN_INSTALL_DIR}") - add_executable(zstd-frugal ${PROGRAMS_DIR}/zstdcli.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/fileio.c ${PROGRAMS_DIR}/fileio_asyncio.c) + add_executable(zstd-frugal ${PROGRAMS_DIR}/zstdcli.c + ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c + ${PROGRAMS_DIR}/fileio.c ${PROGRAMS_DIR}/fileio_asyncio.c) target_link_libraries(zstd-frugal ${PROGRAMS_ZSTD_LINK_TARGET}) set_property(TARGET zstd-frugal APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_NOBENCH;ZSTD_NODICT;ZSTD_NOTRACE") endif () From 839c7939e825d9a6a24eea4122b5cfd4ab8b5243 Mon Sep 17 00:00:00 2001 From: klausholstjacobsen Date: Sun, 3 Sep 2023 10:10:23 +0200 Subject: [PATCH 080/937] Added qnx in the posix test section of platform.h --- programs/platform.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/platform.h b/programs/platform.h index 18a3587bf..43c5dc969 100644 --- a/programs/platform.h +++ b/programs/platform.h @@ -89,7 +89,7 @@ extern "C" { */ # elif !defined(_WIN32) \ && ( defined(__unix__) || defined(__unix) \ - || defined(__midipix__) || defined(__VMS) || defined(__HAIKU__) ) + || defined(_QNX_SOURCE) || defined(__midipix__) || defined(__VMS) || defined(__HAIKU__) ) # if defined(__linux__) || defined(__linux) || defined(__CYGWIN__) # ifndef _POSIX_C_SOURCE From e0e309f27cf73f407f77cfce485203636678a46a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 11 Sep 2023 05:09:02 +0000 Subject: [PATCH 081/937] Bump actions/checkout from 3.5.3 to 4.0.0 Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.3 to 4.0.0. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/c85c95e3d7251135ab7dc9ce3241c5835cc595a9...3df4ab11eba7bda6032a0b82a6bb43b11571feac) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 50 ++++++------- .github/workflows/dev-short-tests.yml | 74 +++++++++---------- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 5 files changed, 65 insertions(+), 65 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 6a0e338f0..34ace919c 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -15,7 +15,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: make all run: make all @@ -26,7 +26,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: make test run: make test @@ -34,7 +34,7 @@ jobs: make-test-osx: runs-on: macos-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: OS-X test run: make test # make -c lib all doesn't work because of the fact that it's not a tty @@ -45,7 +45,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: make test run: | sudo apt-get -qqq update @@ -55,21 +55,21 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream ubsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: undefined behavior sanitizer zstreamtest run: CC=clang make uasan-test-zstream @@ -77,7 +77,7 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest @@ -85,7 +85,7 @@ jobs: big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -96,7 +96,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -108,14 +108,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # tag=v3 + - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Mon, 11 Sep 2023 05:09:05 +0000 Subject: [PATCH 082/937] Bump actions/upload-artifact from 3.1.2 to 3.1.3 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3.1.2 to 3.1.3. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/0b7f8abb1508181956e8e162db84b466c27e18ce...a8a3f3ad30e3422c9c7b888a15615d19a852ae32) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 6a0e338f0..23d6fd116 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -290,7 +290,7 @@ jobs: dry-run: false sanitizer: ${{ matrix.sanitizer }} - name: Upload Crash - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3.1.2 + uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3.1.3 if: failure() && steps.build.outcome == 'success' with: name: ${{ matrix.sanitizer }}-artifacts diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 0d2838118..8ec591725 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -51,7 +51,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3.1.2 + uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3.1.3 with: name: SARIF file path: results.sarif diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index aec722bc5..262847d54 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -52,7 +52,7 @@ jobs: cd .. - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3 + uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3 with: path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip From d55ebb5718a1c7eaff65a720932aa628ccf4f66e Mon Sep 17 00:00:00 2001 From: Paul Menzel Date: Tue, 12 Sep 2023 19:12:19 +0200 Subject: [PATCH 083/937] [pzstd]: Fix `DESTDIR` handling to allow setting `BINDIR` Currently, setting `BINDIR` and `DESTDIR` separately is not possible, so the command below fails, as BINDIR is set explicitly: $ make -j80 install PREFIX=/usr EPREFIX=/usr BINDIR=/usr/bin SBINDIR=/usr/sbin LIBEXECDIR=/usr/libexec SYSCONFDIR=/etc SHAREDSTATEDIR=/var LOCALST ATEDIR=/var LIBDIR=/usr/lib INCLUDEDIR=/usr/include DATAROOTDIR=/usr/share DATADIR=/usr/share INFODIR=/usr/share/info LOCALEDIR=/usr/share/locale MAND IR=/usr/share/man DOCDIR=/usr/share/doc/zstd DESTDIR=/dev/shm/bee-pmenzel/zstd/zstd-1.5.5-0/image -C contrib/pzstd DESTDIR=/dev/shm/bee-pmenzel/zstd/zstd-1.5.5-0/image make: Entering directory '/dev/shm/bee-pmenzel/zstd/zstd-1.5.5-0/source/contrib/pzstd' CFLAGS=" -I../../lib -I../../lib/common -I../../programs -I. -DNDEBUG -O3 -Wall -Wextra -Wno-deprecated-declarations " LDFLAGS=" -O3 -Wall -Wextra -pedantic " make -C ../../lib libzstd.a make[1]: Entering directory '/dev/shm/bee-pmenzel/zstd/zstd-1.5.5-0/source/lib' make[1]: Leaving directory '/dev/shm/bee-pmenzel/zstd/zstd-1.5.5-0/source/lib' g++ main.o ../../programs/util.o Options.o Pzstd.o SkippableFrame.o ../../lib/libzstd.a -O3 -Wall -Wextra -pedantic -pthread -o pzstd install -d -m 755 /usr/bin/ install -m 755 pzstd /usr/bin/pzstd install: cannot create regular file '/usr/bin/pzstd': Permission denied make: *** [Makefile:116: install] Error 1 So, do not prefix `BINDIR` with `DESTDIR`, and adapt all paths for installation. This is more common, and, for example, `programs/Makefile` does the same. Fixes: 8b4e84249b ("[pzstd] Fix Makefile") --- contrib/pzstd/Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/pzstd/Makefile b/contrib/pzstd/Makefile index e62f8e873..9604eb243 100644 --- a/contrib/pzstd/Makefile +++ b/contrib/pzstd/Makefile @@ -10,7 +10,7 @@ # Standard variables for installation DESTDIR ?= PREFIX ?= /usr/local -BINDIR := $(DESTDIR)$(PREFIX)/bin +BINDIR := $(PREFIX)/bin ZSTDDIR = ../../lib PROGDIR = ../../programs @@ -112,12 +112,12 @@ check: .PHONY: install install: PZSTD_CPPFLAGS += -DNDEBUG install: pzstd$(EXT) - install -d -m 755 $(BINDIR)/ - install -m 755 pzstd$(EXT) $(BINDIR)/pzstd$(EXT) + install -d -m 755 $(DESTDIR)$(BINDIR)/ + install -m 755 pzstd$(EXT) $(DESTDIR)$(BINDIR)/pzstd$(EXT) .PHONY: uninstall uninstall: - $(RM) $(BINDIR)/pzstd$(EXT) + $(RM) $(DESTDIR)$(BINDIR)/pzstd$(EXT) # Targets for many different builds .PHONY: all From b69d06a8102f0e04cde0bda2e34984099a0dfba4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 27 Aug 2023 16:12:06 -0700 Subject: [PATCH 084/937] add include guards alleviate risks of double inclusion (typically via transitive includes) --- lib/libzstd.mk | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index 2c47ecdfa..ce6e11375 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -8,6 +8,10 @@ # You may select, at your option, one of the above-listed licenses. # ################################################################ +# Ensure the file is not included twice +ifndef LIBZSTD_MK_INCLUDED +LIBZSTD_MK_INCLUDED := 1 + ################################################################## # Input Variables ################################################################## @@ -223,3 +227,5 @@ endif # BUILD_DIR ZSTD_SUBDIR := $(LIBZSTD)/common $(LIBZSTD)/compress $(LIBZSTD)/decompress $(LIBZSTD)/dictBuilder $(LIBZSTD)/legacy $(LIBZSTD)/deprecated vpath %.c $(ZSTD_SUBDIR) vpath %.S $(ZSTD_SUBDIR) + +endif # LIBZSTD_MK_INCLUDED From 4edfaa93b7631e5fcb2911869ab77c833d73d142 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 27 Aug 2023 16:24:59 -0700 Subject: [PATCH 085/937] default targets of lib/ and programs/ have different names avoid risks on overlapping in case of include --- programs/Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/programs/Makefile b/programs/Makefile index be83c2493..99e004c94 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -15,8 +15,9 @@ # zstd-decompress : decompressor-only version of zstd # ########################################################################## -.PHONY: default -default: zstd-release +# default target (when runing `make` with no argument) +.PHONY: zstd-release +zstd-release: LIBZSTD := ../lib From feaa8ac50d4e0299f652a436e72cc64f9b504c38 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 27 Aug 2023 16:28:56 -0700 Subject: [PATCH 086/937] renamed STATLIB into STATICLIB for improved clarity --- lib/Makefile | 38 ++++++++++++++++++++------------------ lib/libzstd.mk | 2 ++ 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/lib/Makefile b/lib/Makefile index 6d349a3b4..9591cff0f 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -8,6 +8,9 @@ # You may select, at your option, one of the above-listed licenses. # ################################################################ +# default target (when runing `make` with no argument) +lib-release: + # Modules ZSTD_LIB_COMPRESSION ?= 1 ZSTD_LIB_DECOMPRESSION ?= 1 @@ -54,12 +57,11 @@ VERSION := $(ZSTD_VERSION) # Note: by default, the static library is built single-threaded and dynamic library is built # multi-threaded. It is possible to force multi or single threaded builds by appending # -mt or -nomt to the build target (like lib-mt for multi-threaded, lib-nomt for single-threaded). -.PHONY: default -default: lib-release + CPPFLAGS_DYNLIB += -DZSTD_MULTITHREAD # dynamic library build defaults to multi-threaded LDFLAGS_DYNLIB += -pthread -CPPFLAGS_STATLIB += # static library build defaults to single-threaded +CPPFLAGS_STATICLIB += # static library build defaults to single-threaded ifeq ($(findstring GCC,$(CCVER)),GCC) @@ -91,7 +93,7 @@ all: lib .PHONY: libzstd.a # must be run every time -libzstd.a: CPPFLAGS += $(CPPFLAGS_STATLIB) +libzstd.a: CPPFLAGS += $(CPPFLAGS_STATICLIB) SET_CACHE_DIRECTORY = \ +$(MAKE) --no-print-directory $@ \ @@ -109,19 +111,19 @@ libzstd.a: else # BUILD_DIR is defined -ZSTD_STATLIB_DIR := $(BUILD_DIR)/static -ZSTD_STATLIB := $(ZSTD_STATLIB_DIR)/libzstd.a -ZSTD_STATLIB_OBJ := $(addprefix $(ZSTD_STATLIB_DIR)/,$(ZSTD_LOCAL_OBJ)) -$(ZSTD_STATLIB): ARFLAGS = rcs -$(ZSTD_STATLIB): | $(ZSTD_STATLIB_DIR) -$(ZSTD_STATLIB): $(ZSTD_STATLIB_OBJ) +ZSTD_STATICLIB_DIR := $(BUILD_DIR)/static +ZSTD_STATICLIB := $(ZSTD_STATICLIB_DIR)/libzstd.a +ZSTD_STATICLIB_OBJ := $(addprefix $(ZSTD_STATICLIB_DIR)/,$(ZSTD_LOCAL_OBJ)) +$(ZSTD_STATICLIB): ARFLAGS = rcs +$(ZSTD_STATICLIB): | $(ZSTD_STATICLIB_DIR) +$(ZSTD_STATICLIB): $(ZSTD_STATICLIB_OBJ) # Check for multithread flag at target execution time $(if $(filter -DZSTD_MULTITHREAD,$(CPPFLAGS)),\ @echo compiling multi-threaded static library $(LIBVER),\ @echo compiling single-threaded static library $(LIBVER)) $(AR) $(ARFLAGS) $@ $^ -libzstd.a: $(ZSTD_STATLIB) +libzstd.a: $(ZSTD_STATICLIB) cp -f $< $@ endif @@ -182,14 +184,14 @@ lib : libzstd.a libzstd # make does not consider implicit pattern rule for .PHONY target %-mt : CPPFLAGS_DYNLIB := -DZSTD_MULTITHREAD -%-mt : CPPFLAGS_STATLIB := -DZSTD_MULTITHREAD +%-mt : CPPFLAGS_STATICLIB := -DZSTD_MULTITHREAD %-mt : LDFLAGS_DYNLIB := -pthread %-mt : % @echo multi-threaded build completed %-nomt : CPPFLAGS_DYNLIB := %-nomt : LDFLAGS_DYNLIB := -%-nomt : CPPFLAGS_STATLIB := +%-nomt : CPPFLAGS_STATICLIB := %-nomt : % @echo single-threaded build completed @@ -206,23 +208,23 @@ $(ZSTD_DYNLIB_DIR)/%.o : %.c $(ZSTD_DYNLIB_DIR)/%.d | $(ZSTD_DYNLIB_DIR) @echo CC $@ $(COMPILE.c) $(DEPFLAGS) $(ZSTD_DYNLIB_DIR)/$*.d $(OUTPUT_OPTION) $< -$(ZSTD_STATLIB_DIR)/%.o : %.c $(ZSTD_STATLIB_DIR)/%.d | $(ZSTD_STATLIB_DIR) +$(ZSTD_STATICLIB_DIR)/%.o : %.c $(ZSTD_STATICLIB_DIR)/%.d | $(ZSTD_STATICLIB_DIR) @echo CC $@ - $(COMPILE.c) $(DEPFLAGS) $(ZSTD_STATLIB_DIR)/$*.d $(OUTPUT_OPTION) $< + $(COMPILE.c) $(DEPFLAGS) $(ZSTD_STATICLIB_DIR)/$*.d $(OUTPUT_OPTION) $< $(ZSTD_DYNLIB_DIR)/%.o : %.S | $(ZSTD_DYNLIB_DIR) @echo AS $@ $(COMPILE.S) $(OUTPUT_OPTION) $< -$(ZSTD_STATLIB_DIR)/%.o : %.S | $(ZSTD_STATLIB_DIR) +$(ZSTD_STATICLIB_DIR)/%.o : %.S | $(ZSTD_STATICLIB_DIR) @echo AS $@ $(COMPILE.S) $(OUTPUT_OPTION) $< MKDIR ?= mkdir -$(BUILD_DIR) $(ZSTD_DYNLIB_DIR) $(ZSTD_STATLIB_DIR): +$(BUILD_DIR) $(ZSTD_DYNLIB_DIR) $(ZSTD_STATICLIB_DIR): $(MKDIR) -p $@ -DEPFILES := $(ZSTD_DYNLIB_OBJ:.o=.d) $(ZSTD_STATLIB_OBJ:.o=.d) +DEPFILES := $(ZSTD_DYNLIB_OBJ:.o=.d) $(ZSTD_STATICLIB_OBJ:.o=.d) $(DEPFILES): include $(wildcard $(DEPFILES)) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index ce6e11375..fb3c36265 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -9,6 +9,7 @@ # ################################################################ # Ensure the file is not included twice +# Note : must be included after setting the default target ifndef LIBZSTD_MK_INCLUDED LIBZSTD_MK_INCLUDED := 1 @@ -64,6 +65,7 @@ VOID ?= /dev/null NUM_SYMBOL := \# # define silent mode as default (verbose mode with V=1 or VERBOSE=1) +# Note : must be defined _after_ the default target $(V)$(VERBOSE).SILENT: # When cross-compiling from linux to windows, From f4dbfce79cb2b82fb496fcd2518ecd3315051b7d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 27 Aug 2023 18:35:41 -0700 Subject: [PATCH 087/937] define LIB_SRCDIR and LIB_BINDIR --- lib/libzstd.mk | 26 ++++++++++-------- programs/Makefile | 8 +++--- tests/Makefile | 64 ++++++++++++++++++++++----------------------- tests/fuzz/Makefile | 53 ++++++++++++++++++------------------- 4 files changed, 75 insertions(+), 76 deletions(-) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index fb3c36265..a308a6ef6 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -8,6 +8,9 @@ # You may select, at your option, one of the above-listed licenses. # ################################################################ +# This included Makefile provides the following variables : +# LIB_SRCDIR, LIB_BINDIR + # Ensure the file is not included twice # Note : must be included after setting the default target ifndef LIBZSTD_MK_INCLUDED @@ -17,8 +20,9 @@ LIBZSTD_MK_INCLUDED := 1 # Input Variables ################################################################## -# Zstd lib directory -LIBZSTD ?= ./ +# By default, library's directory is same as this included makefile +LIB_SRCDIR ?= $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) +LIB_BINDIR ?= $(LIBSRC_DIR) # ZSTD_LIB_MINIFY is a helper variable that # configures a bunch of other variables to space-optimized defaults. @@ -75,7 +79,7 @@ $(V)$(VERBOSE).SILENT: TARGET_SYSTEM ?= $(OS) # Version numbers -LIBVER_SRC := $(LIBZSTD)/zstd.h +LIBVER_SRC := $(LIB_SRCDIR)/zstd.h LIBVER_MAJOR_SCRIPT:=`sed -n '/define ZSTD_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` LIBVER_MINOR_SCRIPT:=`sed -n '/define ZSTD_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` LIBVER_PATCH_SCRIPT:=`sed -n '/define ZSTD_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` @@ -142,14 +146,14 @@ ifeq ($(HAVE_COLORNEVER), 1) endif GREP = grep $(GREP_OPTIONS) -ZSTD_COMMON_FILES := $(sort $(wildcard $(LIBZSTD)/common/*.c)) -ZSTD_COMPRESS_FILES := $(sort $(wildcard $(LIBZSTD)/compress/*.c)) -ZSTD_DECOMPRESS_FILES := $(sort $(wildcard $(LIBZSTD)/decompress/*.c)) -ZSTD_DICTBUILDER_FILES := $(sort $(wildcard $(LIBZSTD)/dictBuilder/*.c)) -ZSTD_DEPRECATED_FILES := $(sort $(wildcard $(LIBZSTD)/deprecated/*.c)) +ZSTD_COMMON_FILES := $(sort $(wildcard $(LIB_SRCDIR)/common/*.c)) +ZSTD_COMPRESS_FILES := $(sort $(wildcard $(LIB_SRCDIR)/compress/*.c)) +ZSTD_DECOMPRESS_FILES := $(sort $(wildcard $(LIB_SRCDIR)/decompress/*.c)) +ZSTD_DICTBUILDER_FILES := $(sort $(wildcard $(LIB_SRCDIR)/dictBuilder/*.c)) +ZSTD_DEPRECATED_FILES := $(sort $(wildcard $(LIB_SRCDIR)/deprecated/*.c)) ZSTD_LEGACY_FILES := -ZSTD_DECOMPRESS_AMD64_ASM_FILES := $(sort $(wildcard $(LIBZSTD)/decompress/*_amd64.S)) +ZSTD_DECOMPRESS_AMD64_ASM_FILES := $(sort $(wildcard $(LIB_SRCDIR)/decompress/*_amd64.S)) ifneq ($(ZSTD_NO_ASM), 0) CPPFLAGS += -DZSTD_DISABLE_ASM @@ -197,7 +201,7 @@ endif ifneq ($(ZSTD_LEGACY_SUPPORT), 0) ifeq ($(shell test $(ZSTD_LEGACY_SUPPORT) -lt 8; echo $$?), 0) - ZSTD_LEGACY_FILES += $(shell ls $(LIBZSTD)/legacy/*.c | $(GREP) 'v0[$(ZSTD_LEGACY_SUPPORT)-7]') + ZSTD_LEGACY_FILES += $(shell ls $(LIB_SRCDIR)/legacy/*.c | $(GREP) 'v0[$(ZSTD_LEGACY_SUPPORT)-7]') endif endif CPPFLAGS += -DZSTD_LEGACY_SUPPORT=$(ZSTD_LEGACY_SUPPORT) @@ -226,7 +230,7 @@ ifeq ($(HAVE_HASH),0) endif endif # BUILD_DIR -ZSTD_SUBDIR := $(LIBZSTD)/common $(LIBZSTD)/compress $(LIBZSTD)/decompress $(LIBZSTD)/dictBuilder $(LIBZSTD)/legacy $(LIBZSTD)/deprecated +ZSTD_SUBDIR := $(LIB_SRCDIR)/common $(LIB_SRCDIR)/compress $(LIB_SRCDIR)/decompress $(LIB_SRCDIR)/dictBuilder $(LIB_SRCDIR)/legacy $(LIB_SRCDIR)/deprecated vpath %.c $(ZSTD_SUBDIR) vpath %.S $(ZSTD_SUBDIR) diff --git a/programs/Makefile b/programs/Makefile index 99e004c94..6cd5c1eee 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -16,12 +16,10 @@ # ########################################################################## # default target (when runing `make` with no argument) -.PHONY: zstd-release zstd-release: -LIBZSTD := ../lib - -include $(LIBZSTD)/libzstd.mk +LIBZSTD_MK_DIR = ../lib +include $(LIBZSTD_MK_DIR)/libzstd.mk ifeq ($(shell $(CC) -v 2>&1 | $(GREP) -c "gcc version "), 1) ALIGN_LOOP = -falign-loops=32 @@ -224,7 +222,7 @@ zstd-noxz : zstd ## zstd-dll: zstd executable linked to dynamic library libzstd (must have same version) .PHONY: zstd-dll -zstd-dll : LDFLAGS+= -L$(LIBZSTD) +zstd-dll : LDFLAGS+= -L$(LIB_BINDIR) zstd-dll : LDLIBS += -lzstd zstd-dll : ZSTDLIB_LOCAL_SRC = xxhash.c pool.c threading.c zstd-dll : zstd diff --git a/tests/Makefile b/tests/Makefile index c31e75005..740bb5959 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -20,23 +20,21 @@ # zstreamtest32: Same as zstreamtest, but forced to compile in 32-bits mode # ########################################################################## -LIBZSTD = ../lib - ZSTD_LEGACY_SUPPORT ?= 0 DEBUGLEVEL ?= 2 export DEBUGLEVEL # transmit value to sub-makefiles -include $(LIBZSTD)/libzstd.mk +LIBZSTD_MK_DIR := ../lib +include $(LIBZSTD_MK_DIR)/libzstd.mk -ZSTDDIR = $(LIBZSTD) PRGDIR = ../programs PYTHON ?= python3 TESTARTEFACT := versionsTest DEBUGFLAGS += -g -Wno-c++-compat -CPPFLAGS += -I$(ZSTDDIR) -I$(ZSTDDIR)/common -I$(ZSTDDIR)/compress \ - -I$(ZSTDDIR)/dictBuilder -I$(ZSTDDIR)/deprecated -I$(PRGDIR) \ +CPPFLAGS += -I$(LIB_SRCDIR) -I$(LIB_SRCDIR)/common -I$(LIB_SRCDIR)/compress \ + -I$(LIB_SRCDIR)/dictBuilder -I$(LIB_SRCDIR)/deprecated -I$(PRGDIR) \ -DZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY=1 ZSTDCOMMON_FILES := $(sort $(ZSTD_COMMON_FILES)) @@ -46,15 +44,15 @@ ZSTD_FILES := $(ZSTDDECOMP_FILES) $(ZSTDCOMMON_FILES) $(ZSTDCOMP_FILES) ZDICT_FILES := $(sort $(ZSTD_DICTBUILDER_FILES)) ZSTD_F1 := $(sort $(wildcard $(ZSTD_FILES))) -ZSTD_OBJ1 := $(subst $(ZSTDDIR)/common/,zstdm_,$(ZSTD_F1)) -ZSTD_OBJ2 := $(subst $(ZSTDDIR)/compress/,zstdc_,$(ZSTD_OBJ1)) -ZSTD_OBJ3 := $(subst $(ZSTDDIR)/decompress/,zstdd_,$(ZSTD_OBJ2)) +ZSTD_OBJ1 := $(subst $(LIB_SRCDIR)/common/,zstdm_,$(ZSTD_F1)) +ZSTD_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,zstdc_,$(ZSTD_OBJ1)) +ZSTD_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,zstdd_,$(ZSTD_OBJ2)) ZSTD_OBJ4 := $(ZSTD_OBJ3:.c=.o) ZSTD_OBJECTS := $(ZSTD_OBJ4:.S=.o) -ZSTDMT_OBJ1 := $(subst $(ZSTDDIR)/common/,zstdmt_m_,$(ZSTD_F1)) -ZSTDMT_OBJ2 := $(subst $(ZSTDDIR)/compress/,zstdmt_c_,$(ZSTDMT_OBJ1)) -ZSTDMT_OBJ3 := $(subst $(ZSTDDIR)/decompress/,zstdmt_d_,$(ZSTDMT_OBJ2)) +ZSTDMT_OBJ1 := $(subst $(LIB_SRCDIR)/common/,zstdmt_m_,$(ZSTD_F1)) +ZSTDMT_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,zstdmt_c_,$(ZSTDMT_OBJ1)) +ZSTDMT_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,zstdmt_d_,$(ZSTDMT_OBJ2)) ZSTDMT_OBJ4 := $(ZSTDMT_OBJ3:.c=.o) ZSTDMT_OBJECTS := $(ZSTDMT_OBJ4:.S=.o) @@ -100,38 +98,38 @@ zstd zstd32 zstd-nolegacy zstd-dll: .PHONY: libzstd libzstd : - $(MAKE) -C $(ZSTDDIR) libzstd MOREFLAGS+="$(DEBUGFLAGS)" + $(MAKE) -C $(LIB_SRCDIR) libzstd MOREFLAGS+="$(DEBUGFLAGS)" %-dll : libzstd -%-dll : LDFLAGS += -L$(ZSTDDIR) -lzstd +%-dll : LDFLAGS += -L$(LIB_BINDIR) -lzstd -$(ZSTDDIR)/libzstd.a : - $(MAKE) -C $(ZSTDDIR) libzstd.a +$(LIB_BINDIR)/libzstd.a : + $(MAKE) -C $(LIB_SRCDIR) libzstd.a -zstdm_%.o : $(ZSTDDIR)/common/%.c +zstdm_%.o : $(LIB_SRCDIR)/common/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdc_%.o : $(ZSTDDIR)/compress/%.c +zstdc_%.o : $(LIB_SRCDIR)/compress/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdd_%.o : $(ZSTDDIR)/decompress/%.c +zstdd_%.o : $(LIB_SRCDIR)/decompress/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdd_%.o : $(ZSTDDIR)/decompress/%.S +zstdd_%.o : $(LIB_SRCDIR)/decompress/%.S $(CC) -c $(CPPFLAGS) $(ASFLAGS) $< -o $@ zstdmt%.o : CPPFLAGS += $(MULTITHREAD_CPP) -zstdmt_m_%.o : $(ZSTDDIR)/common/%.c +zstdmt_m_%.o : $(LIB_SRCDIR)/common/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdmt_c_%.o : $(ZSTDDIR)/compress/%.c +zstdmt_c_%.o : $(LIB_SRCDIR)/compress/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdmt_d_%.o : $(ZSTDDIR)/decompress/%.c +zstdmt_d_%.o : $(LIB_SRCDIR)/decompress/%.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@ -zstdmt_d_%.o : $(ZSTDDIR)/decompress/%.S +zstdmt_d_%.o : $(LIB_SRCDIR)/decompress/%.S $(CC) -c $(CPPFLAGS) $(ASFLAGS) $< -o $@ FULLBENCHS := fullbench fullbench32 @@ -146,12 +144,12 @@ $(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR CLEAN += fullbench-lib fullbench-lib : CPPFLAGS += -DXXH_NAMESPACE=ZSTD_ -fullbench-lib : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(ZSTDDIR)/libzstd.a fullbench.c +fullbench-lib : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(LIB_SRCDIR)/libzstd.a fullbench.c $(LINK.c) $^ -o $@$(EXT) # note : broken : requires symbols unavailable from dynamic library fullbench-dll: $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/benchfn.c $(PRGDIR)/timefn.c fullbench.c -# $(CC) $(FLAGS) $(filter %.c,$^) -o $@$(EXT) -DZSTD_DLL_IMPORT=1 $(ZSTDDIR)/dll/libzstd.dll +# $(CC) $(FLAGS) $(filter %.c,$^) -o $@$(EXT) -DZSTD_DLL_IMPORT=1 $(LIB_SRCDIR)/dll/libzstd.dll $(LINK.c) $^ $(LDLIBS) -o $@$(EXT) CLEAN += fuzzer fuzzer32 @@ -165,7 +163,7 @@ fuzzer32 : $(ZSTD_FILES) $(LINK.c) $^ -o $@$(EXT) # note : broken : requires symbols unavailable from dynamic library -fuzzer-dll : $(ZSTDDIR)/common/xxhash.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/datagen.c fuzzer.c +fuzzer-dll : $(LIB_SRCDIR)/common/xxhash.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/datagen.c fuzzer.c $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) $(LDFLAGS) -o $@$(EXT) CLEAN += zstreamtest zstreamtest32 @@ -196,7 +194,7 @@ zstreamtest_ubsan : $(ZSTREAMFILES) $(LINK.c) $(MULTITHREAD) $^ -o $@$(EXT) # note : broken : requires symbols unavailable from dynamic library -zstreamtest-dll : $(ZSTDDIR)/common/xxhash.c # xxh symbols not exposed from dll +zstreamtest-dll : $(LIB_SRCDIR)/common/xxhash.c # xxh symbols not exposed from dll zstreamtest-dll : $(ZSTREAM_LOCAL_FILES) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) $(LDFLAGS) -o $@$(EXT) @@ -224,15 +222,15 @@ CLEAN += invalidDictionaries invalidDictionaries : $(ZSTD_OBJECTS) invalidDictionaries.c CLEAN += legacy -legacy : CPPFLAGS += -I$(ZSTDDIR)/legacy -UZSTD_LEGACY_SUPPORT -DZSTD_LEGACY_SUPPORT=4 -legacy : $(ZSTD_FILES) $(sort $(wildcard $(ZSTDDIR)/legacy/*.c)) legacy.c +legacy : CPPFLAGS += -I$(LIB_SRCDIR)/legacy -UZSTD_LEGACY_SUPPORT -DZSTD_LEGACY_SUPPORT=4 +legacy : $(ZSTD_FILES) $(sort $(wildcard $(LIB_SRCDIR)/legacy/*.c)) legacy.c CLEAN += decodecorpus decodecorpus : LDLIBS += -lm decodecorpus : $(filter-out zstdc_zstd_compress.o, $(ZSTD_OBJECTS)) $(ZDICT_FILES) $(PRGDIR)/util.c $(PRGDIR)/timefn.c decodecorpus.c CLEAN += poolTests -poolTests : $(PRGDIR)/util.c $(PRGDIR)/timefn.c poolTests.c $(ZSTDDIR)/common/pool.c $(ZSTDDIR)/common/threading.c $(ZSTDDIR)/common/zstd_common.c $(ZSTDDIR)/common/error_private.c +poolTests : $(PRGDIR)/util.c $(PRGDIR)/timefn.c poolTests.c $(LIB_SRCDIR)/common/pool.c $(LIB_SRCDIR)/common/threading.c $(LIB_SRCDIR)/common/zstd_common.c $(LIB_SRCDIR)/common/error_private.c $(LINK.c) $(MULTITHREAD) $^ -o $@$(EXT) .PHONY: versionsTest @@ -245,11 +243,11 @@ automated_benchmarking: clean # make checkTag : check that release tag corresponds to release version CLEAN += checkTag -checkTag.o : $(ZSTDDIR)/zstd.h +checkTag.o : $(LIB_SRCDIR)/zstd.h .PHONY: clean clean: - $(MAKE) -C $(ZSTDDIR) clean + $(MAKE) -C $(LIB_SRCDIR) clean $(MAKE) -C $(PRGDIR) clean $(RM) -fR $(TESTARTEFACT) $(RM) -rf tmp* # some test directories are named tmp* diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index 525e396bc..cc6e15e31 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -24,13 +24,12 @@ else endif CORPORA_URL_PREFIX:=https://github.com/facebook/zstd/releases/download/fuzz-corpora/ -LIBZSTD = ../../lib +LIBZSTD_MK_DIR = ../../lib DEBUGLEVEL ?= 2 ZSTD_LEGACY_SUPPORT ?= 1 -include $(LIBZSTD)/libzstd.mk +include $(LIBZSTD_MK_DIR)/libzstd.mk -ZSTDDIR = ../../lib PRGDIR = ../../programs CONTRIBDIR = ../../contrib @@ -38,8 +37,8 @@ DEFAULT_SEQ_PROD_DIR = $(CONTRIBDIR)/externalSequenceProducer DEFAULT_SEQ_PROD_SRC = $(DEFAULT_SEQ_PROD_DIR)/sequence_producer.c THIRD_PARTY_SEQ_PROD_OBJ ?= -FUZZ_CPPFLAGS := -I$(ZSTDDIR) -I$(ZSTDDIR)/common -I$(ZSTDDIR)/compress \ - -I$(ZSTDDIR)/dictBuilder -I$(ZSTDDIR)/deprecated -I$(ZSTDDIR)/legacy \ +FUZZ_CPPFLAGS := -I$(LIB_SRCDIR) -I$(LIB_SRCDIR)/common -I$(LIB_SRCDIR)/compress \ + -I$(LIB_SRCDIR)/dictBuilder -I$(LIB_SRCDIR)/deprecated -I$(LIB_SRCDIR)/legacy \ -I$(CONTRIBDIR)/seekable_format -I$(PRGDIR) -I$(DEFAULT_SEQ_PROD_DIR) \ -DZSTD_MULTITHREAD -DZSTD_LEGACY_SUPPORT=1 $(CPPFLAGS) FUZZ_EXTRA_FLAGS := -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow \ @@ -78,11 +77,11 @@ FUZZ_SRC := \ $(DEFAULT_SEQ_PROD_SRC) FUZZ_SRC := $(sort $(wildcard $(FUZZ_SRC))) -FUZZ_D_OBJ1 := $(subst $(ZSTDDIR)/common/,d_lib_common_,$(FUZZ_SRC)) -FUZZ_D_OBJ2 := $(subst $(ZSTDDIR)/compress/,d_lib_compress_,$(FUZZ_D_OBJ1)) -FUZZ_D_OBJ3 := $(subst $(ZSTDDIR)/decompress/,d_lib_decompress_,$(FUZZ_D_OBJ2)) -FUZZ_D_OBJ4 := $(subst $(ZSTDDIR)/dictBuilder/,d_lib_dictBuilder_,$(FUZZ_D_OBJ3)) -FUZZ_D_OBJ5 := $(subst $(ZSTDDIR)/legacy/,d_lib_legacy_,$(FUZZ_D_OBJ4)) +FUZZ_D_OBJ1 := $(subst $(LIB_SRCDIR)/common/,d_lib_common_,$(FUZZ_SRC)) +FUZZ_D_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,d_lib_compress_,$(FUZZ_D_OBJ1)) +FUZZ_D_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,d_lib_decompress_,$(FUZZ_D_OBJ2)) +FUZZ_D_OBJ4 := $(subst $(LIB_SRCDIR)/dictBuilder/,d_lib_dictBuilder_,$(FUZZ_D_OBJ3)) +FUZZ_D_OBJ5 := $(subst $(LIB_SRCDIR)/legacy/,d_lib_legacy_,$(FUZZ_D_OBJ4)) FUZZ_D_OBJ6 := $(subst $(PRGDIR)/,d_prg_,$(FUZZ_D_OBJ5)) FUZZ_D_OBJ7 := $(subst $(DEFAULT_SEQ_PROD_DIR)/,d_default_seq_prod_,$(FUZZ_D_OBJ6)) FUZZ_D_OBJ8 := $(subst $\./,d_fuzz_,$(FUZZ_D_OBJ7)) @@ -90,11 +89,11 @@ FUZZ_D_OBJ9 := $(FUZZ_D_OBJ8:.c=.o) FUZZ_D_OBJ10 := $(THIRD_PARTY_SEQ_PROD_OBJ) $(FUZZ_D_OBJ9) FUZZ_DECOMPRESS_OBJ := $(FUZZ_D_OBJ10:.S=.o) -FUZZ_RT_OBJ1 := $(subst $(ZSTDDIR)/common/,rt_lib_common_,$(FUZZ_SRC)) -FUZZ_RT_OBJ2 := $(subst $(ZSTDDIR)/compress/,rt_lib_compress_,$(FUZZ_RT_OBJ1)) -FUZZ_RT_OBJ3 := $(subst $(ZSTDDIR)/decompress/,rt_lib_decompress_,$(FUZZ_RT_OBJ2)) -FUZZ_RT_OBJ4 := $(subst $(ZSTDDIR)/dictBuilder/,rt_lib_dictBuilder_,$(FUZZ_RT_OBJ3)) -FUZZ_RT_OBJ5 := $(subst $(ZSTDDIR)/legacy/,rt_lib_legacy_,$(FUZZ_RT_OBJ4)) +FUZZ_RT_OBJ1 := $(subst $(LIB_SRCDIR)/common/,rt_lib_common_,$(FUZZ_SRC)) +FUZZ_RT_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,rt_lib_compress_,$(FUZZ_RT_OBJ1)) +FUZZ_RT_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,rt_lib_decompress_,$(FUZZ_RT_OBJ2)) +FUZZ_RT_OBJ4 := $(subst $(LIB_SRCDIR)/dictBuilder/,rt_lib_dictBuilder_,$(FUZZ_RT_OBJ3)) +FUZZ_RT_OBJ5 := $(subst $(LIB_SRCDIR)/legacy/,rt_lib_legacy_,$(FUZZ_RT_OBJ4)) FUZZ_RT_OBJ6 := $(subst $(PRGDIR)/,rt_prg_,$(FUZZ_RT_OBJ5)) FUZZ_RT_OBJ7 := $(subst $(DEFAULT_SEQ_PROD_DIR)/,rt_default_seq_prod_,$(FUZZ_RT_OBJ6)) FUZZ_RT_OBJ8 := $(subst $\./,rt_fuzz_,$(FUZZ_RT_OBJ7)) @@ -129,22 +128,22 @@ FUZZ_TARGETS := \ all: libregression.a $(FUZZ_TARGETS) -rt_lib_common_%.o: $(ZSTDDIR)/common/%.c +rt_lib_common_%.o: $(LIB_SRCDIR)/common/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -rt_lib_compress_%.o: $(ZSTDDIR)/compress/%.c +rt_lib_compress_%.o: $(LIB_SRCDIR)/compress/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -rt_lib_decompress_%.o: $(ZSTDDIR)/decompress/%.c +rt_lib_decompress_%.o: $(LIB_SRCDIR)/decompress/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -rt_lib_decompress_%.o: $(ZSTDDIR)/decompress/%.S +rt_lib_decompress_%.o: $(LIB_SRCDIR)/decompress/%.S $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_ASFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -rt_lib_dictBuilder_%.o: $(ZSTDDIR)/dictBuilder/%.c +rt_lib_dictBuilder_%.o: $(LIB_SRCDIR)/dictBuilder/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -rt_lib_legacy_%.o: $(ZSTDDIR)/legacy/%.c +rt_lib_legacy_%.o: $(LIB_SRCDIR)/legacy/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ rt_prg_%.o: $(PRGDIR)/%.c @@ -156,22 +155,22 @@ rt_fuzz_%.o: %.c rt_default_seq_prod_%.o: $(DEFAULT_SEQ_PROD_DIR)/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $(FUZZ_ROUND_TRIP_FLAGS) $< -c -o $@ -d_lib_common_%.o: $(ZSTDDIR)/common/%.c +d_lib_common_%.o: $(LIB_SRCDIR)/common/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $< -c -o $@ -d_lib_compress_%.o: $(ZSTDDIR)/compress/%.c +d_lib_compress_%.o: $(LIB_SRCDIR)/compress/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $< -c -o $@ -d_lib_decompress_%.o: $(ZSTDDIR)/decompress/%.c +d_lib_decompress_%.o: $(LIB_SRCDIR)/decompress/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $< -c -o $@ -d_lib_decompress_%.o: $(ZSTDDIR)/decompress/%.S +d_lib_decompress_%.o: $(LIB_SRCDIR)/decompress/%.S $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_ASFLAGS) $< -c -o $@ -d_lib_dictBuilder_%.o: $(ZSTDDIR)/dictBuilder/%.c +d_lib_dictBuilder_%.o: $(LIB_SRCDIR)/dictBuilder/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $< -c -o $@ -d_lib_legacy_%.o: $(ZSTDDIR)/legacy/%.c +d_lib_legacy_%.o: $(LIB_SRCDIR)/legacy/%.c $(CC) $(FUZZ_CPPFLAGS) $(FUZZ_CFLAGS) $< -c -o $@ d_prg_%.o: $(PRGDIR)/%.c From 607933a2ff41f985ec9f05f2a0fc3b5b74f52b48 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 27 Aug 2023 21:33:32 -0700 Subject: [PATCH 088/937] minor simplification for dependency generation also : fix zstd-nomt exclusion and test --- lib/Makefile | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/Makefile b/lib/Makefile index 9591cff0f..754c90960 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -202,15 +202,18 @@ lib : libzstd.a libzstd # Generate .h dependencies automatically -DEPFLAGS = -MT $@ -MMD -MP -MF +# -MMD: compiler generates dependency information as a side-effect of compilation, without system headers +# -MP: adds phony target for each dependency other than main file. +DEPFLAGS = -MMD -MP -$(ZSTD_DYNLIB_DIR)/%.o : %.c $(ZSTD_DYNLIB_DIR)/%.d | $(ZSTD_DYNLIB_DIR) +# ensure that ZSTD_DYNLIB_DIR exists prior to generating %.o +$(ZSTD_DYNLIB_DIR)/%.o : %.c | $(ZSTD_DYNLIB_DIR) @echo CC $@ - $(COMPILE.c) $(DEPFLAGS) $(ZSTD_DYNLIB_DIR)/$*.d $(OUTPUT_OPTION) $< + $(COMPILE.c) $(DEPFLAGS) $(OUTPUT_OPTION) $< -$(ZSTD_STATICLIB_DIR)/%.o : %.c $(ZSTD_STATICLIB_DIR)/%.d | $(ZSTD_STATICLIB_DIR) +$(ZSTD_STATICLIB_DIR)/%.o : %.c | $(ZSTD_STATICLIB_DIR) @echo CC $@ - $(COMPILE.c) $(DEPFLAGS) $(ZSTD_STATICLIB_DIR)/$*.d $(OUTPUT_OPTION) $< + $(COMPILE.c) $(DEPFLAGS) $(OUTPUT_OPTION) $< $(ZSTD_DYNLIB_DIR)/%.o : %.S | $(ZSTD_DYNLIB_DIR) @echo AS $@ @@ -220,24 +223,31 @@ $(ZSTD_STATICLIB_DIR)/%.o : %.S | $(ZSTD_STATICLIB_DIR) @echo AS $@ $(COMPILE.S) $(OUTPUT_OPTION) $< -MKDIR ?= mkdir +MKDIR ?= mkdir -p $(BUILD_DIR) $(ZSTD_DYNLIB_DIR) $(ZSTD_STATICLIB_DIR): - $(MKDIR) -p $@ + $(MKDIR) $@ DEPFILES := $(ZSTD_DYNLIB_OBJ:.o=.d) $(ZSTD_STATICLIB_OBJ:.o=.d) $(DEPFILES): -include $(wildcard $(DEPFILES)) +# The leading '-' means: do not fail is include fails (ex: directory does not exist yet) +-include $(wildcard $(DEPFILES)) -# Special case : building library in single-thread mode _and_ without zstdmt_compress.c -ZSTDMT_FILES = compress/zstdmt_compress.c -ZSTD_NOMT_FILES = $(filter-out $(ZSTDMT_FILES),$(ZSTD_FILES)) +# Special case : build library in single-thread mode _and_ without zstdmt_compress.c +# Note : we still need threading.c and pool.c for the dictionary builder, +# but they will correctly behave single-threaded. +ZSTDMT_FILES = zstdmt_compress.c +ZSTD_NOMT_FILES = $(filter-out $(ZSTDMT_FILES),$(notdir $(ZSTD_FILES))) libzstd-nomt: CFLAGS += -fPIC -fvisibility=hidden libzstd-nomt: LDFLAGS += -shared libzstd-nomt: $(ZSTD_NOMT_FILES) @echo compiling single-thread dynamic library $(LIBVER) @echo files : $(ZSTD_NOMT_FILES) + @if echo "$(ZSTD_NOMT_FILES)" | tr ' ' '\n' | $(GREP) -q zstdmt; then \ + echo "Error: Found zstdmt in list."; \ + exit 1; \ + fi $(CC) $(FLAGS) $^ $(LDFLAGS) $(SONAME_FLAGS) -o $@ .PHONY: clean From 3fc14e411b18869e333732ceedad4f1052d73b86 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 13 Sep 2023 11:35:19 -0700 Subject: [PATCH 089/937] added some documentation on ZSTD_estimate*Size() variants as a follow up for #3747 --- lib/zstd.h | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 148f112d1..c3cf05643 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1642,19 +1642,23 @@ ZSTDLIB_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); /*! ZSTD_estimate*() : * These functions make it possible to estimate memory usage * of a future {D,C}Ctx, before its creation. + * This is useful in combination with ZSTD_initStatic(), + * which makes it possible to employ a static buffer for ZSTD_CCtx* state. * * ZSTD_estimateCCtxSize() will provide a memory budget large enough - * for any compression level up to selected one. - * Note : Unlike ZSTD_estimateCStreamSize*(), this estimate - * does not include space for a window buffer. - * Therefore, the estimation is only guaranteed for single-shot compressions, not streaming. + * to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2() + * associated with any compression level up to max specified one. * The estimate will assume the input may be arbitrarily large, * which is the worst case. * + * Note that the size estimation is specific for one-shot compression, + * it is not valid for streaming (see ZSTD_estimateCStreamSize*()) + * nor other potential ways of using a ZSTD_CCtx* state. + * * When srcSize can be bound by a known and rather "small" value, - * this fact can be used to provide a tighter estimation - * because the CCtx compression context will need less memory. - * This tighter estimation can be provided by more advanced functions + * this knowledge can be used to provide a tighter budget estimation + * because the ZSTD_CCtx* state will need less memory for small inputs. + * This tighter estimation can be provided by employing more advanced functions * ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), * and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). * Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. @@ -1665,33 +1669,35 @@ ZSTDLIB_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); * Note 2 : ZSTD_estimateCCtxSize* functions are not compatible with the Block-Level Sequence Producer API at this time. * Size estimates assume that no external sequence producer is registered. */ -ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int compressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel); ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams); ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params); ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize(void); /*! ZSTD_estimateCStreamSize() : - * ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one. - * It will also consider src size to be arbitrarily "large", which is worst case. + * ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression + * using any compression level up to the max specified one. + * It will also consider src size to be arbitrarily "large", which is a worst case scenario. * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. * Note : CStream size estimation is only correct for single-threaded compression. - * ZSTD_DStream memory budget depends on window Size. + * ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + * Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. + * Size estimates assume that no external sequence producer is registered. + * + * ZSTD_DStream memory budget depends on frame's window Size. * This information can be passed manually, using ZSTD_estimateDStreamSize, * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); + * Any frame requesting a window size larger than max specified one will be rejected. * Note : if streaming is init with function ZSTD_init?Stream_usingDict(), * an internal ?Dict will be created, which additional size is not estimated here. * In this case, get total size by adding ZSTD_estimate?DictSize - * Note 2 : only single-threaded compression is supported. - * ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. - * Note 3 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. - * Size estimates assume that no external sequence producer is registered. */ -ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int compressionLevel); +ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int maxCompressionLevel); ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams); ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params); -ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t windowSize); +ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t maxWindowSize); ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize); /*! ZSTD_estimate?DictSize() : From 48b5a7bd8bedcfcaf22631d45c61c2f544315053 Mon Sep 17 00:00:00 2001 From: Dominik Loidolt Date: Tue, 19 Sep 2023 16:22:47 +0200 Subject: [PATCH 090/937] Fix a very small formatting typo in the lib/README.md file --- lib/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/README.md b/lib/README.md index 479820933..572b7df78 100644 --- a/lib/README.md +++ b/lib/README.md @@ -88,7 +88,7 @@ The file structure is designed to make this selection manually achievable for an For example, advanced API for version `v0.4` is exposed in `lib/legacy/zstd_v04.h` . - While invoking `make libzstd`, it's possible to define build macros - `ZSTD_LIB_COMPRESSION, ZSTD_LIB_DECOMPRESSION`, `ZSTD_LIB_DICTBUILDER`, + `ZSTD_LIB_COMPRESSION`, `ZSTD_LIB_DECOMPRESSION`, `ZSTD_LIB_DICTBUILDER`, and `ZSTD_LIB_DEPRECATED` as `0` to forgo compilation of the corresponding features. This will also disable compilation of all dependencies (e.g. `ZSTD_LIB_COMPRESSION=0` will also disable From cdceb0fce59785c841bf697e00067163106064e1 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 22 Sep 2023 11:51:15 -0700 Subject: [PATCH 091/937] Improve macro guards for ZSTD_assertValidSequence Refine the macro guards to define the functions exactly when they are needed. This fixes the chromium build with zstd. Thanks to @GregTho for reporting! --- lib/decompress/zstd_decompress_block.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index c90536ad7..9e5c5144b 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1340,8 +1340,9 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c return seq; } -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION -MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd) +#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE) +#if DEBUGLEVEL >= 1 +static int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd) { size_t const windowSize = dctx->fParams.windowSize; /* No dictionary used. */ @@ -1355,8 +1356,9 @@ MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefix /* Dictionary is active. */ return 1; } +#endif -MEM_STATIC void ZSTD_assertValidSequence( +static void ZSTD_assertValidSequence( ZSTD_DCtx const* dctx, BYTE const* op, BYTE const* oend, seq_t const seq, From fe34776c207f3f879f386ed4158a38d927ff6d10 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 23 Sep 2023 18:56:01 +0200 Subject: [PATCH 092/937] Fix new typos found by codespell --- build/cmake/lib/CMakeLists.txt | 10 +++++----- doc/educational_decoder/zstd_decompress.c | 2 +- doc/zstd_manual.html | 22 +++++++++++----------- lib/common/pool.h | 2 +- lib/compress/huf_compress.c | 2 +- lib/compress/zstd_compress.c | 2 +- lib/compress/zstd_compress_internal.h | 4 ++-- lib/compress/zstd_cwksp.h | 8 ++++---- lib/decompress/zstd_decompress_block.c | 4 ++-- lib/zstd.h | 22 +++++++++++----------- tests/fuzz/fuzz_third_party_seq_prod.h | 4 ++-- tests/fuzzer.c | 8 ++++---- tests/zstreamtest.c | 8 ++++---- 13 files changed, 49 insertions(+), 49 deletions(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index cf1252e19..2b64a07e2 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -17,11 +17,11 @@ option(ZSTD_BUILD_DECOMPRESSION "BUILD DECOMPRESSION MODULE" ON) option(ZSTD_BUILD_DICTBUILDER "BUILD DICTBUILDER MODULE" ON) option(ZSTD_BUILD_DEPRECATED "BUILD DEPRECATED MODULE" OFF) -set(ZSTDLIB_VISIBLE "" CACHE STRING "Visiblity for ZSTDLIB API") -set(ZSTDERRORLIB_VISIBLE "" CACHE STRING "Visiblity for ZSTDERRORLIB_VISIBLE API") -set(ZDICTLIB_VISIBLE "" CACHE STRING "Visiblity for ZDICTLIB_VISIBLE API") -set(ZSTDLIB_STATIC_API "" CACHE STRING "Visiblity for ZSTDLIB_STATIC_API API") -set(ZDICTLIB_STATIC_API "" CACHE STRING "Visiblity for ZDICTLIB_STATIC_API API") +set(ZSTDLIB_VISIBLE "" CACHE STRING "Visibility for ZSTDLIB API") +set(ZSTDERRORLIB_VISIBLE "" CACHE STRING "Visibility for ZSTDERRORLIB_VISIBLE API") +set(ZDICTLIB_VISIBLE "" CACHE STRING "Visibility for ZDICTLIB_VISIBLE API") +set(ZSTDLIB_STATIC_API "" CACHE STRING "Visibility for ZSTDLIB_STATIC_API API") +set(ZDICTLIB_STATIC_API "" CACHE STRING "Visibility for ZDICTLIB_STATIC_API API") set_property(CACHE ZSTDLIB_VISIBLE PROPERTY STRINGS "" "hidden" "default" "protected" "internal") set_property(CACHE ZSTDERRORLIB_VISIBLE PROPERTY STRINGS "" "hidden" "default" "protected" "internal") diff --git a/doc/educational_decoder/zstd_decompress.c b/doc/educational_decoder/zstd_decompress.c index 921c8f54c..839e085b4 100644 --- a/doc/educational_decoder/zstd_decompress.c +++ b/doc/educational_decoder/zstd_decompress.c @@ -1213,7 +1213,7 @@ static void decode_seq_table(FSE_dtable *const table, istream_t *const in, break; } case seq_repeat: - // "Repeat_Mode : re-use distribution table from previous compressed + // "Repeat_Mode : reuse distribution table from previous compressed // block." // Nothing to do here, table will be unchanged if (!table->symbols) { diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index dcc10208d..d72eacc34 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -174,7 +174,7 @@ int ZSTD_defaultCLevel(void); /*!< default compression lev

Compression context

  When compressing many times,
   it is recommended to allocate a context just once,
-  and re-use it for each successive compression operation.
+  and reuse it for each successive compression operation.
   This will make workload friendlier for system's memory.
   Note : re-using context is just a speed / resource optimization.
          It doesn't change the compression ratio, which remains identical.
@@ -200,7 +200,7 @@ size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* accept NULL pointer */
 
 

Decompression context

  When decompressing many times,
   it is recommended to allocate a context only once,
-  and re-use it for each successive compression operation.
+  and reuse it for each successive compression operation.
   This will make workload friendlier for system's memory.
   Use one context per thread for parallel execution. 
 
typedef struct ZSTD_DCtx_s ZSTD_DCtx;
@@ -568,14 +568,14 @@ size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);  /* accept NULL pointer */
   A ZSTD_CStream object is required to track streaming operation.
   Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
   ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
-  It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
+  It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
 
   For parallel execution, use one separate ZSTD_CStream per thread.
 
   note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
 
   Parameters are sticky : when starting a new compression on the same context,
-  it will re-use the same sticky parameters as previous compression session.
+  it will reuse the same sticky parameters as previous compression session.
   When in doubt, it's recommended to fully initialize the context before usage.
   Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),
   ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to
@@ -698,7 +698,7 @@ size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
 

Streaming decompression - HowTo

   A ZSTD_DStream object is required to track streaming operations.
   Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
-  ZSTD_DStream objects can be re-used multiple times.
+  ZSTD_DStream objects can be reused multiple times.
 
   Use ZSTD_initDStream() to start a new decompression operation.
  @return : recommended first input size
@@ -869,7 +869,7 @@ size_t ZSTD_freeDStream(ZSTD_DStream* zds);  /* accept NULL pointer */
 

Advanced dictionary and prefix API (Requires v1.4.0+)

  This API allows dictionaries to be used with ZSTD_compress2(),
  ZSTD_compressStream2(), and ZSTD_decompressDCtx().
- Dictionaries are sticky, they remain valid when same context is re-used,
+ Dictionaries are sticky, they remain valid when same context is reused,
  they only reset when the context is reset
  with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.
  In contrast, Prefixes are single-use.
@@ -1857,7 +1857,7 @@ size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);
        explicitly specified.
 
   start a new frame, using same parameters from previous frame.
-  This is typically useful to skip dictionary loading stage, since it will re-use it in-place.
+  This is typically useful to skip dictionary loading stage, since it will reuse it in-place.
   Note that zcs must be init at least once before using ZSTD_resetCStream().
   If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.
   If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
@@ -1918,7 +1918,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);
 

ZSTD_DCtx_reset(zds, ZSTD_reset_session_only); - re-use decompression parameters from previous init; saves dictionary loading + reuse decompression parameters from previous init; saves dictionary loading


@@ -1964,7 +1964,7 @@ ZSTD_registerSequenceProducer(

Buffer-less streaming compression (synchronous mode)

   A ZSTD_CCtx object is required to track streaming operations.
   Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
-  ZSTD_CCtx object can be re-used multiple times within successive compression operations.
+  ZSTD_CCtx object can be reused multiple times within successive compression operations.
 
   Start by initializing a context.
   Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression.
@@ -1985,7 +1985,7 @@ ZSTD_registerSequenceProducer(
   It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
   Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.
 
-  `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again.
+  `ZSTD_CCtx` object can be reused (ZSTD_compressBegin()) to compress again.
 

Buffer-less streaming compression functions

ZSTD_DEPRECATED("The buffer-less API is deprecated in favor of the normal streaming API. See docs.")
@@ -2002,7 +2002,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const Z
 

Buffer-less streaming decompression (synchronous mode)

   A ZSTD_DCtx object is required to track streaming operations.
   Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
-  A ZSTD_DCtx object can be re-used multiple times.
+  A ZSTD_DCtx object can be reused multiple times.
 
   First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
   Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
diff --git a/lib/common/pool.h b/lib/common/pool.h
index eb22ff509..cca4de73a 100644
--- a/lib/common/pool.h
+++ b/lib/common/pool.h
@@ -47,7 +47,7 @@ void POOL_joinJobs(POOL_ctx* ctx);
 /*! POOL_resize() :
  *  Expands or shrinks pool's number of threads.
  *  This is more efficient than releasing + creating a new context,
- *  since it tries to preserve and re-use existing threads.
+ *  since it tries to preserve and reuse existing threads.
  * `numThreads` must be at least 1.
  * @return : 0 when resize was successful,
  *           !0 (typically 1) if there is an error.
diff --git a/lib/compress/huf_compress.c b/lib/compress/huf_compress.c
index 3fe257896..1097d13d8 100644
--- a/lib/compress/huf_compress.c
+++ b/lib/compress/huf_compress.c
@@ -1447,7 +1447,7 @@ size_t HUF_compress1X_repeat (void* dst, size_t dstSize,
 /* HUF_compress4X_repeat():
  * compress input using 4 streams.
  * consider skipping quickly
- * re-use an existing huffman compression table */
+ * reuse an existing huffman compression table */
 size_t HUF_compress4X_repeat (void* dst, size_t dstSize,
                       const void* src, size_t srcSize,
                       unsigned maxSymbolValue, unsigned huffLog,
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 36c1f99e8..a51c00792 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -2606,7 +2606,7 @@ ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerVa
     assert(size < (1U<<31));   /* can be casted to int */
 
 #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
-    /* To validate that the table re-use logic is sound, and that we don't
+    /* To validate that the table reuse logic is sound, and that we don't
      * access table space that we haven't cleaned, we re-"poison" the table
      * space every time we mark it dirty.
      *
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index ac8dfb71a..ce4242c8d 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -39,7 +39,7 @@ extern "C" {
                                        It's not a big deal though : candidate will just be sorted again.
                                        Additionally, candidate position 1 will be lost.
                                        But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.
-                                       The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table re-use with a different strategy.
+                                       The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be mishandled after table reuse with a different strategy.
                                        This constant is required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */
 
 
@@ -228,7 +228,7 @@ struct ZSTD_matchState_t {
     U32 rowHashLog;                          /* For row-based matchfinder: Hashlog based on nb of rows in the hashTable.*/
     BYTE* tagTable;                          /* For row-based matchFinder: A row-based table containing the hashes and head index. */
     U32 hashCache[ZSTD_ROW_HASH_CACHE_SIZE]; /* For row-based matchFinder: a cache of hashes to improve speed */
-    U64 hashSalt;                            /* For row-based matchFinder: salts the hash for re-use of tag table */
+    U64 hashSalt;                            /* For row-based matchFinder: salts the hash for reuse of tag table */
     U32 hashSaltEntropy;                     /* For row-based matchFinder: collects entropy for salt generation */
 
     U32* hashTable;
diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h
index a3efc56e5..3eddbd334 100644
--- a/lib/compress/zstd_cwksp.h
+++ b/lib/compress/zstd_cwksp.h
@@ -434,7 +434,7 @@ MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes)
 
 /**
  * Aligned on 64 bytes. These buffers have the special property that
- * their values remain constrained, allowing us to re-use them without
+ * their values remain constrained, allowing us to reuse them without
  * memset()-ing them.
  */
 MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes)
@@ -526,7 +526,7 @@ MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws)
     DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
 
 #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
-    /* To validate that the table re-use logic is sound, and that we don't
+    /* To validate that the table reuse logic is sound, and that we don't
      * access table space that we haven't cleaned, we re-"poison" the table
      * space every time we mark it dirty.
      * Since tableValidEnd space and initOnce space may overlap we don't poison
@@ -603,9 +603,9 @@ MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
     DEBUGLOG(4, "cwksp: clearing!");
 
 #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
-    /* To validate that the context re-use logic is sound, and that we don't
+    /* To validate that the context reuse logic is sound, and that we don't
      * access stuff that this compression hasn't initialized, we re-"poison"
-     * the workspace except for the areas in which we expect memory re-use
+     * the workspace except for the areas in which we expect memory reuse
      * without initialization (objects, valid tables area and init once
      * memory). */
     {
diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 9e5c5144b..aa506be20 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -1431,7 +1431,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
                 BIT_DStream_completed < BIT_DStream_overflow);
 
         /* decompress without overrunning litPtr begins */
-        {   seq_t sequence = {0,0,0};  /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one interation) */
+        {   seq_t sequence = {0,0,0};  /* some static analyzer believe that @sequence is not initialized (it necessarily is, since for(;;) loop as at least one iteration) */
             /* Align the decompression loop to 32 + 16 bytes.
                 *
                 * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
@@ -1591,7 +1591,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
         litBufferEnd = dctx->litExtraBuffer + ZSTD_LITBUFFEREXTRASIZE;
         dctx->litBufferLocation = ZSTD_not_in_dst;
     }
-    /* copy last literals from interal buffer */
+    /* copy last literals from internal buffer */
     {   size_t const lastLLSize = litBufferEnd - litPtr;
         RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
         if (op != NULL) {
diff --git a/lib/zstd.h b/lib/zstd.h
index c3cf05643..c33dab3cd 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -249,7 +249,7 @@ ZSTDLIB_API int         ZSTD_defaultCLevel(void);           /*!< default compres
 /*= Compression context
  *  When compressing many times,
  *  it is recommended to allocate a context just once,
- *  and re-use it for each successive compression operation.
+ *  and reuse it for each successive compression operation.
  *  This will make workload friendlier for system's memory.
  *  Note : re-using context is just a speed / resource optimization.
  *         It doesn't change the compression ratio, which remains identical.
@@ -276,7 +276,7 @@ ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
 /*= Decompression context
  *  When decompressing many times,
  *  it is recommended to allocate a context only once,
- *  and re-use it for each successive compression operation.
+ *  and reuse it for each successive compression operation.
  *  This will make workload friendlier for system's memory.
  *  Use one context per thread for parallel execution. */
 typedef struct ZSTD_DCtx_s ZSTD_DCtx;
@@ -682,14 +682,14 @@ typedef struct ZSTD_outBuffer_s {
 *  A ZSTD_CStream object is required to track streaming operation.
 *  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
 *  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
-*  It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
+*  It is recommended to reuse ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
 *
 *  For parallel execution, use one separate ZSTD_CStream per thread.
 *
 *  note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
 *
 *  Parameters are sticky : when starting a new compression on the same context,
-*  it will re-use the same sticky parameters as previous compression session.
+*  it will reuse the same sticky parameters as previous compression session.
 *  When in doubt, it's recommended to fully initialize the context before usage.
 *  Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),
 *  ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to
@@ -837,7 +837,7 @@ ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
 *
 *  A ZSTD_DStream object is required to track streaming operations.
 *  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
-*  ZSTD_DStream objects can be re-used multiple times.
+*  ZSTD_DStream objects can be reused multiple times.
 *
 *  Use ZSTD_initDStream() to start a new decompression operation.
 * @return : recommended first input size
@@ -1023,7 +1023,7 @@ ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);
  *
  * This API allows dictionaries to be used with ZSTD_compress2(),
  * ZSTD_compressStream2(), and ZSTD_decompressDCtx().
- * Dictionaries are sticky, they remain valid when same context is re-used,
+ * Dictionaries are sticky, they remain valid when same context is reused,
  * they only reset when the context is reset
  * with ZSTD_reset_parameters or ZSTD_reset_session_and_parameters.
  * In contrast, Prefixes are single-use.
@@ -2581,7 +2581,7 @@ size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
  *       explicitly specified.
  *
  *  start a new frame, using same parameters from previous frame.
- *  This is typically useful to skip dictionary loading stage, since it will re-use it in-place.
+ *  This is typically useful to skip dictionary loading stage, since it will reuse it in-place.
  *  Note that zcs must be init at least once before using ZSTD_resetCStream().
  *  If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.
  *  If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
@@ -2657,7 +2657,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const Z
  *
  *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
  *
- * re-use decompression parameters from previous init; saves dictionary loading
+ * reuse decompression parameters from previous init; saves dictionary loading
  */
 ZSTD_DEPRECATED("use ZSTD_DCtx_reset, see zstd.h for detailed instructions")
 ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);
@@ -2844,7 +2844,7 @@ ZSTD_registerSequenceProducer(
 
   A ZSTD_CCtx object is required to track streaming operations.
   Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
-  ZSTD_CCtx object can be re-used multiple times within successive compression operations.
+  ZSTD_CCtx object can be reused multiple times within successive compression operations.
 
   Start by initializing a context.
   Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression.
@@ -2865,7 +2865,7 @@ ZSTD_registerSequenceProducer(
   It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
   Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.
 
-  `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again.
+  `ZSTD_CCtx` object can be reused (ZSTD_compressBegin()) to compress again.
 */
 
 /*=====   Buffer-less streaming compression functions  =====*/
@@ -2897,7 +2897,7 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_
 
   A ZSTD_DCtx object is required to track streaming operations.
   Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
-  A ZSTD_DCtx object can be re-used multiple times.
+  A ZSTD_DCtx object can be reused multiple times.
 
   First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
   Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
diff --git a/tests/fuzz/fuzz_third_party_seq_prod.h b/tests/fuzz/fuzz_third_party_seq_prod.h
index f04ad31ad..f0771e47b 100644
--- a/tests/fuzz/fuzz_third_party_seq_prod.h
+++ b/tests/fuzz/fuzz_third_party_seq_prod.h
@@ -52,7 +52,7 @@ extern "C" {
 size_t FUZZ_seqProdSetup(void);
 
 /* The fuzzer will call this function after each test-case. It should free
- * resources aquired by FUZZ_seqProdSetup() to prevent leaks across test-cases.
+ * resources acquired by FUZZ_seqProdSetup() to prevent leaks across test-cases.
  *
  * The fuzzer will assert() that the return value is zero. To signal an error,
  * please return a non-zero value. */
@@ -72,7 +72,7 @@ size_t FUZZ_seqProdTearDown(void);
 void* FUZZ_createSeqProdState(void);
 
 /* The fuzzer will call this function after each test-case. It should free any
- * resources aquired by FUZZ_createSeqProdState().
+ * resources acquired by FUZZ_createSeqProdState().
  *
  * The fuzzer will assert() that the return value is zero. To signal an error,
  * please return a non-zero value. */
diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index 4a68ff731..eaf7ee500 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -376,7 +376,7 @@ static int threadPoolTests(void) {
 
     RDG_genBuffer(CNBuffer, CNBuffSize, 0.5, 0.5, 0);
 
-    DISPLAYLEVEL(3, "thread pool test : threadPool re-use roundtrips: ");
+    DISPLAYLEVEL(3, "thread pool test : threadPool reuse roundtrips: ");
     {
         ZSTD_CCtx* cctx = ZSTD_createCCtx();
         ZSTD_threadPool* pool = ZSTD_createThreadPool(kPoolNumThreads);
@@ -1525,14 +1525,14 @@ static int basicUnitTests(U32 const seed, double compressibility)
     }
     DISPLAYLEVEL(3, "OK \n");
 
-    DISPLAYLEVEL(3, "test%3d : re-use CCtx with expanding block size : ", testNb++);
+    DISPLAYLEVEL(3, "test%3d : reuse CCtx with expanding block size : ", testNb++);
     {   ZSTD_CCtx* const cctx = ZSTD_createCCtx();
         ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
         assert(params.fParams.contentSizeFlag == 1);  /* block size will be adapted if pledgedSrcSize is enabled */
         CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
         CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
 
-        CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* re-use same parameters */
+        CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* reuse same parameters */
         {   size_t const inSize = 2* 128 KB;
             size_t const outSize = ZSTD_compressBound(inSize);
             CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
@@ -1827,7 +1827,7 @@ static int basicUnitTests(U32 const seed, double compressibility)
         params.cParams.windowLog = ZSTD_WINDOWLOG_MAX;
         for (cnb = 0; cnb < nbCompressions; ++cnb) {
             DISPLAYLEVEL(6, "run %zu / %zu \n", cnb, nbCompressions);
-            CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* re-use same parameters */
+            CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) );  /* reuse same parameters */
             CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) );
         }
         ZSTD_freeCCtx(cctx);
diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c
index 85d0fc81f..04f1f8b0e 100644
--- a/tests/zstreamtest.c
+++ b/tests/zstreamtest.c
@@ -408,8 +408,8 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests)
     if (inBuff.pos != inBuff.size) goto _output_error;   /* should have read the entire frame */
     DISPLAYLEVEL(3, "OK \n");
 
-    /* Re-use without init */
-    DISPLAYLEVEL(3, "test%3i : decompress again without init (re-use previous settings): ", testNb++);
+    /* Reuse without init */
+    DISPLAYLEVEL(3, "test%3i : decompress again without init (reuse previous settings): ", testNb++);
     outBuff.pos = 0;
     { size_t const remaining = ZSTD_decompressStream(zd, &outBuff, &inBuff2);
       if (remaining != 0) goto _output_error; }  /* should reach end of frame == 0; otherwise, some data left, or an error */
@@ -653,8 +653,8 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests)
             DISPLAYLEVEL(3, "OK (error detected : %s) \n", ZSTD_getErrorName(r));
     }   }
 
-    /* Compression state re-use scenario */
-    DISPLAYLEVEL(3, "test%3i : context re-use : ", testNb++);
+    /* Compression state reuse scenario */
+    DISPLAYLEVEL(3, "test%3i : context reuse : ", testNb++);
     ZSTD_freeCStream(zc);
     zc = ZSTD_createCStream();
     if (zc==NULL) goto _output_error;   /* memory allocation issue */

From 585aaa0ed324a858226908fc1f00d78ed92b0f4b Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 23 Sep 2023 19:03:18 +0200
Subject: [PATCH 093/937] Do not test WIN32, instead test _WIN32

To the best of my knowledge:
* `_WIN32` and `_WIN64` are defined by the compiler,
* `WIN32` and `WIN64` are defined by the user, to indicate whatever
  the user chooses them to indicate. They mean 32-bit and 64-bit Windows
  compilation by convention only.

See:
https://accu.org/journals/overload/24/132/wilson_2223/

Windows compilers in general, and MSVC in particular, have been defining
`_WIN32` and `_WIN64` for a long time, provably at least since Visual Studio
2015, and in practice as early as in the days of 16-bit Windows.

See:
https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-140
https://learn.microsoft.com/en-us/windows/win32/winprog64/the-tools

Tests used to be inconsistent, sometimes testing `_WIN32`, sometimes
`_WIN32` and `WIN32`. This brings consistency to Windows detection.
---
 contrib/seekable_format/examples/parallel_processing.c | 2 +-
 programs/fileio.c                                      | 2 +-
 programs/platform.h                                    | 4 ++--
 programs/util.h                                        | 2 +-
 zlibWrapper/examples/minigzip.c                        | 4 ++--
 5 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/contrib/seekable_format/examples/parallel_processing.c b/contrib/seekable_format/examples/parallel_processing.c
index 356561e5a..928371025 100644
--- a/contrib/seekable_format/examples/parallel_processing.c
+++ b/contrib/seekable_format/examples/parallel_processing.c
@@ -19,7 +19,7 @@
 #define ZSTD_STATIC_LINKING_ONLY
 #include       // presumes zstd library is installed
 #include 
-#if defined(WIN32) || defined(_WIN32)
+#if defined(_WIN32)
 #  include 
 #  define SLEEP(x) Sleep(x)
 #else
diff --git a/programs/fileio.c b/programs/fileio.c
index 217232542..81d343023 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -527,7 +527,7 @@ static int FIO_removeFile(const char* path)
         DISPLAYLEVEL(2, "zstd: Refusing to remove non-regular file %s\n", path);
         return 0;
     }
-#if defined(_WIN32) || defined(WIN32)
+#if defined(_WIN32)
     /* windows doesn't allow remove read-only files,
      * so try to make it writable first */
     if (!(statbuf.st_mode & _S_IWRITE)) {
diff --git a/programs/platform.h b/programs/platform.h
index 43c5dc969..bbe0965ae 100644
--- a/programs/platform.h
+++ b/programs/platform.h
@@ -141,7 +141,7 @@ extern "C" {
 #elif defined(MSDOS) || defined(OS2)
 #  include        /* _isatty */
 #  define IS_CONSOLE(stdStream) _isatty(_fileno(stdStream))
-#elif defined(WIN32) || defined(_WIN32)
+#elif defined(_WIN32)
 #  include       /* _isatty */
 #  include  /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
 #  include    /* FILE */
@@ -157,7 +157,7 @@ static __inline int IS_CONSOLE(FILE* stdStream) {
 /******************************
 *  OS-specific IO behaviors
 ******************************/
-#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32)
+#if defined(MSDOS) || defined(OS2) || defined(_WIN32)
 #  include    /* _O_BINARY */
 #  include       /* _setmode, _fileno, _get_osfhandle */
 #  if !defined(__DJGPP__)
diff --git a/programs/util.h b/programs/util.h
index 8234646bf..571d39421 100644
--- a/programs/util.h
+++ b/programs/util.h
@@ -338,7 +338,7 @@ void UTIL_refFilename(FileNamesTable* fnt, const char* filename);
 FileNamesTable*
 UTIL_createExpandedFNT(const char* const* filenames, size_t nbFilenames, int followLinks);
 
-#if defined(_WIN32) || defined(WIN32)
+#if defined(_WIN32)
 DWORD CountSetBits(ULONG_PTR bitMask);
 #endif
 
diff --git a/zlibWrapper/examples/minigzip.c b/zlibWrapper/examples/minigzip.c
index 717a94df9..67a17907b 100644
--- a/zlibWrapper/examples/minigzip.c
+++ b/zlibWrapper/examples/minigzip.c
@@ -34,7 +34,7 @@
 #  include 
 #endif
 
-#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
+#if defined(MSDOS) || defined(OS2) || defined(_WIN32) || defined(__CYGWIN__)
 #  include 
 #  include 
 #  ifdef UNDER_CE
@@ -63,7 +63,7 @@
 #endif
 
 #if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE)
-#ifndef WIN32 /* unlink already in stdio.h for WIN32 */
+#ifndef _WIN32 /* unlink already in stdio.h for WIN32 */
   extern int unlink _Z_OF((const char *));
 #endif
 #endif

From d5cbae7c50835b84114efd3c80ff8bbe99080fe8 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 25 Sep 2023 05:18:07 +0000
Subject: [PATCH 094/937] Bump actions/checkout from 4.0.0 to 4.1.0

Bumps [actions/checkout](https://github.com/actions/checkout) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/3df4ab11eba7bda6032a0b82a6bb43b11571feac...8ade135a41bc03ea155e62e844d188df1ea18608)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml          | 50 ++++++-------
 .github/workflows/dev-short-tests.yml         | 74 +++++++++----------
 .../workflows/publish-release-artifacts.yml   |  2 +-
 .github/workflows/scorecards.yml              |  2 +-
 .github/workflows/windows-artifacts.yml       |  2 +-
 5 files changed, 65 insertions(+), 65 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index e2081ee46..2f2793bcd 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -15,7 +15,7 @@ jobs:
   make-all:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: make all
       run: make all
 
@@ -26,7 +26,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: make test
       run: make test
 
@@ -34,7 +34,7 @@ jobs:
   make-test-osx:
     runs-on: macos-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: OS-X test
       run: make test # make -c lib all doesn't work because of the fact that it's not a tty
 
@@ -45,7 +45,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: make test
       run: |
         sudo apt-get -qqq update
@@ -55,21 +55,21 @@ jobs:
   no-intrinsics-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: no intrinsics fuzztest
       run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest
 
   tsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: thread sanitizer zstreamtest
       run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream
 
   ubsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: undefined behavior sanitizer zstreamtest
       run: CC=clang make uasan-test-zstream
 
@@ -77,7 +77,7 @@ jobs:
   tsan-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: thread sanitizer fuzztest
       run: CC=clang make tsan-fuzztest
 
@@ -85,7 +85,7 @@ jobs:
   big-tests-zstreamtest32:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: zstream tests in 32bit mode, with big tests
       run: |
         sudo apt-get -qqq update
@@ -96,7 +96,7 @@ jobs:
   gcc-8-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: gcc-8 + ASan + UBSan + Test Zstd
       # See https://askubuntu.com/a/1428822
       run: |
@@ -108,14 +108,14 @@ jobs:
   clang-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # tag=v3
+    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: clang + ASan + UBSan + Test Zstd
       run: CC=clang make -j uasan-test-zstd 
Date: Wed, 27 Sep 2023 21:18:20 -0700
Subject: [PATCH 095/937] fix x32 tests on Github CI

ubuntu-22.04 seems to have problems with x32 recently
switching to ubuntu-20.04 which seems to work fine so far

https://github.com/actions/runner-images/issues/8397
---
 .github/workflows/dev-short-tests.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index fd0ed79db..2da03e98a 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -38,7 +38,7 @@ jobs:
         CFLAGS="-m32 -O1 -fstack-protector" make check V=1
 
   check-x32:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-20.04  # ubuntu-latest == ubuntu-22.04 have issues currently with x32
     steps:
     - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
     - name: make check on x32 ABI # https://en.wikipedia.org/wiki/X32_ABI

From 3daed7017af2f015dc34e88ff4ac1cac8cd7e511 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Fri, 25 Aug 2023 11:18:56 -0700
Subject: [PATCH 096/937] Revert "Work around nullptr-with-nonzero-offset
 warning"

This reverts commit c27fa399042f466080e79bb4fd8a4871bc0bcf28.
---
 lib/decompress/zstd_decompress.c | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index ccfd84fa4..94eb95151 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -1548,12 +1548,6 @@ size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
     dctx->stage = ZSTDds_getFrameHeaderSize;
     dctx->processedCSize = 0;
     dctx->decodedSize = 0;
-    /* Set to non-null because ZSTD_prefetchMatch() may end up doing addition
-     * with this value for corrupted frames. However, it then just passes the
-     * pointer to PREFETCH_L1(), which doesn't require valid pointers. But,
-     * if it is NULL we get nullptr-with-nonzero-offset UBSAN warnings.
-     */
-    dctx->previousDstEnd = "";
     dctx->previousDstEnd = NULL;
     dctx->prefixStart = NULL;
     dctx->virtualStart = NULL;

From 43118da8a7fb51e660bfa7e958639c5cc8285580 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Tue, 26 Sep 2023 17:53:26 -0700
Subject: [PATCH 097/937] Stop suppressing pointer-overflow UBSAN errors

* Remove all pointer-overflow suppressions from our UBSAN builds/tests.
* Add `ZSTD_ALLOW_POINTER_OVERFLOW_ATTR` macro to suppress
  pointer-overflow at a per-function level. This is a superior approach
  because it also applies to users who build zstd with UBSAN.
* Add `ZSTD_wrappedPtr{Diff,Add,Sub}()` that use these suppressions.
  The end goal is to only tag these functions with
  `ZSTD_ALLOW_POINTER_OVERFLOW`. But we can start by annoting functions
  that rely on pointer overflow, and gradually transition to using
  these.
* Add `ZSTD_maybeNullPtrAdd()` to simplify pointer addition when the
  pointer may be `NULL`.
* Fix all the fuzzer issues that came up. I'm sure there will be a lot
  more, but these are the ones that came up within a few minutes of
  running the fuzzers, and while running GitHub CI.
---
 Makefile                               |  6 +--
 lib/common/compiler.h                  | 70 ++++++++++++++++++++++++++
 lib/compress/zstd_compress_internal.h  |  8 ++-
 lib/compress/zstd_double_fast.c        | 14 ++++--
 lib/compress/zstd_fast.c               | 18 +++++--
 lib/compress/zstd_lazy.c               | 63 +++++++++++++++--------
 lib/compress/zstd_ldm.c                |  4 +-
 lib/compress/zstd_opt.c                | 36 ++++++++-----
 lib/decompress/huf_decompress.c        | 16 +++---
 lib/decompress/zstd_decompress.c       |  4 +-
 lib/decompress/zstd_decompress_block.c | 24 ++++++---
 lib/legacy/zstd_legacy.h               | 30 +++++++++++
 lib/legacy/zstd_v01.c                  |  2 +
 lib/legacy/zstd_v02.c                  | 16 +-----
 lib/legacy/zstd_v03.c                  | 16 +-----
 lib/legacy/zstd_v04.c                  |  6 ++-
 lib/legacy/zstd_v05.c                  |  1 +
 lib/legacy/zstd_v06.c                  |  2 +
 lib/legacy/zstd_v07.c                  |  3 +-
 tests/decodecorpus.c                   |  2 +-
 tests/fuzz/fuzz.py                     |  8 ++-
 tests/fuzz/sequence_compression_api.c  |  2 +-
 tests/fuzzer.c                         |  4 +-
 23 files changed, 252 insertions(+), 103 deletions(-)

diff --git a/Makefile b/Makefile
index fd95c3890..7bc7ec5bf 100644
--- a/Makefile
+++ b/Makefile
@@ -317,7 +317,7 @@ update_regressionResults:
 # run UBsan with -fsanitize-recover=pointer-overflow
 # this only works with recent compilers such as gcc 8+
 usan: clean
-	$(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=undefined -Werror $(MOREFLAGS)"
+	$(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=undefined -Werror $(MOREFLAGS)"
 
 asan: clean
 	$(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=address -Werror $(MOREFLAGS)"
@@ -335,10 +335,10 @@ asan32: clean
 	$(MAKE) -C $(TESTDIR) test32 CC=clang MOREFLAGS="-g -fsanitize=address $(MOREFLAGS)"
 
 uasan: clean
-	$(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=address,undefined -Werror $(MOREFLAGS)"
+	$(MAKE) test CC=clang MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=address,undefined -Werror $(MOREFLAGS)"
 
 uasan-%: clean
-	LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize-recover=pointer-overflow -fsanitize=address,undefined -Werror $(MOREFLAGS)" $(MAKE) -C $(TESTDIR) $*
+	LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=address,undefined -Werror $(MOREFLAGS)" $(MAKE) -C $(TESTDIR) $*
 
 tsan-%: clean
 	LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=thread -Werror $(MOREFLAGS)" $(MAKE) -C $(TESTDIR) $* FUZZER_FLAGS="--no-big-tests $(FUZZER_FLAGS)"
diff --git a/lib/common/compiler.h b/lib/common/compiler.h
index bcaa575dd..df39d91c6 100644
--- a/lib/common/compiler.h
+++ b/lib/common/compiler.h
@@ -11,6 +11,8 @@
 #ifndef ZSTD_COMPILER_H
 #define ZSTD_COMPILER_H
 
+#include 
+
 #include "portability_macros.h"
 
 /*-*******************************************************
@@ -302,6 +304,74 @@
 *  Sanitizer
 *****************************************************************/
 
+/**
+ * Zstd relies on pointer overflow in its decompressor.
+ * We add this attribute to functions that rely on pointer overflow.
+ */
+#ifndef ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+#  if __has_attribute(no_sanitize)
+#    if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 8
+       /* gcc < 8 only has signed-integer-overlow which triggers on pointer overflow */
+#      define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("signed-integer-overflow")))
+#    else
+       /* older versions of clang [3.7, 5.0) will warn that pointer-overflow is ignored. */
+#      define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("pointer-overflow")))
+#    endif
+#  else
+#    define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+#  endif
+#endif
+
+/**
+ * Helper function to perform a wrapped pointer difference without trigging
+ * UBSAN.
+ *
+ * @returns lhs - rhs with wrapping
+ */
+MEM_STATIC
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+ptrdiff_t ZSTD_wrappedPtrDiff(unsigned char const* lhs, unsigned char const* rhs)
+{
+    return lhs - rhs;
+}
+
+/**
+ * Helper function to perform a wrapped pointer add without triggering UBSAN.
+ *
+ * @return ptr + add with wrapping
+ */
+MEM_STATIC
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add)
+{
+    return ptr + add;
+}
+
+/**
+ * Helper function to perform a wrapped pointer subtraction without triggering
+ * UBSAN.
+ *
+ * @return ptr - sub with wrapping
+ */
+MEM_STATIC
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub)
+{
+    return ptr - sub;
+}
+
+/**
+ * Helper function to add to a pointer that works around C's undefined behavior
+ * of adding 0 to NULL.
+ *
+ * @returns `ptr + add` except it defines `NULL + 0 == NULL`.
+ */
+MEM_STATIC
+unsigned char* ZSTD_maybeNullPtrAdd(unsigned char* ptr, ptrdiff_t add)
+{
+    return add > 0 ? ptr + add : ptr;
+}
+
 /* Issue #3240 reports an ASAN failure on an llvm-mingw build. Out of an
  * abundance of caution, disable our custom poisoning on mingw. */
 #ifdef __MINGW32__
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index ac8dfb71a..b7c5c3c1a 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -1053,7 +1053,9 @@ MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
  * The least significant cycleLog bits of the indices must remain the same,
  * which may be 0. Every index up to maxDist in the past must be valid.
  */
-MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
+MEM_STATIC
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
                                            U32 maxDist, void const* src)
 {
     /* preemptive overflow correction:
@@ -1246,7 +1248,9 @@ MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) {
  * forget about the extDict. Handles overlap of the prefix and extDict.
  * Returns non-zero if the segment is contiguous.
  */
-MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
+MEM_STATIC
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_window_update(ZSTD_window_t* window,
                                   void const* src, size_t srcSize,
                                   int forceNonContiguous)
 {
diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c
index d4544b390..aaa6f3d3d 100644
--- a/lib/compress/zstd_double_fast.c
+++ b/lib/compress/zstd_double_fast.c
@@ -13,7 +13,9 @@
 
 #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
 
-static void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms,
                               void const* end, ZSTD_dictTableLoadMethod_e dtlm)
 {
     const ZSTD_compressionParameters* const cParams = &ms->cParams;
@@ -49,7 +51,9 @@ static void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms,
     }   }
 }
 
-static void ZSTD_fillDoubleHashTableForCCtx(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_fillDoubleHashTableForCCtx(ZSTD_matchState_t* ms,
                               void const* end, ZSTD_dictTableLoadMethod_e dtlm)
 {
     const ZSTD_compressionParameters* const cParams = &ms->cParams;
@@ -97,6 +101,7 @@ void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms,
 
 
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_compressBlock_doubleFast_noDict_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize, U32 const mls /* template */)
@@ -307,6 +312,7 @@ _match_stored:
 
 
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize,
@@ -591,7 +597,9 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState(
 }
 
 
-static size_t ZSTD_compressBlock_doubleFast_extDict_generic(
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_compressBlock_doubleFast_extDict_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize,
         U32 const mls /* template */)
diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c
index 5f2c6a2ed..fb1ef60c1 100644
--- a/lib/compress/zstd_fast.c
+++ b/lib/compress/zstd_fast.c
@@ -11,7 +11,9 @@
 #include "zstd_compress_internal.h"  /* ZSTD_hashPtr, ZSTD_count, ZSTD_storeSeq */
 #include "zstd_fast.h"
 
-static void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms,
                         const void* const end,
                         ZSTD_dictTableLoadMethod_e dtlm)
 {
@@ -46,7 +48,9 @@ static void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms,
                 }   }   }   }
 }
 
-static void ZSTD_fillHashTableForCCtx(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_fillHashTableForCCtx(ZSTD_matchState_t* ms,
                         const void* const end,
                         ZSTD_dictTableLoadMethod_e dtlm)
 {
@@ -139,8 +143,9 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
  *
  * This is also the work we do at the beginning to enter the loop initially.
  */
-FORCE_INLINE_TEMPLATE size_t
-ZSTD_compressBlock_fast_noDict_generic(
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_compressBlock_fast_noDict_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize,
         U32 const mls, U32 const hasStep)
@@ -456,6 +461,7 @@ size_t ZSTD_compressBlock_fast(
 }
 
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_compressBlock_fast_dictMatchState_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize, U32 const mls, U32 const hasStep)
@@ -681,7 +687,9 @@ size_t ZSTD_compressBlock_fast_dictMatchState(
 }
 
 
-static size_t ZSTD_compressBlock_fast_extDict_generic(
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_compressBlock_fast_extDict_generic(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize, U32 const mls, U32 const hasStep)
 {
diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c
index 834520fd7..3aba83c6f 100644
--- a/lib/compress/zstd_lazy.c
+++ b/lib/compress/zstd_lazy.c
@@ -24,8 +24,9 @@
 *  Binary Tree search
 ***************************************/
 
-static void
-ZSTD_updateDUBT(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_updateDUBT(ZSTD_matchState_t* ms,
                 const BYTE* ip, const BYTE* iend,
                 U32 mls)
 {
@@ -68,8 +69,9 @@ ZSTD_updateDUBT(ZSTD_matchState_t* ms,
  *  sort one already inserted but unsorted position
  *  assumption : curr >= btlow == (curr - btmask)
  *  doesn't fail */
-static void
-ZSTD_insertDUBT1(const ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_insertDUBT1(const ZSTD_matchState_t* ms,
                  U32 curr, const BYTE* inputEnd,
                  U32 nbCompares, U32 btLow,
                  const ZSTD_dictMode_e dictMode)
@@ -157,8 +159,9 @@ ZSTD_insertDUBT1(const ZSTD_matchState_t* ms,
 }
 
 
-static size_t
-ZSTD_DUBT_findBetterDictMatch (
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_DUBT_findBetterDictMatch (
         const ZSTD_matchState_t* ms,
         const BYTE* const ip, const BYTE* const iend,
         size_t* offsetPtr,
@@ -235,8 +238,9 @@ ZSTD_DUBT_findBetterDictMatch (
 }
 
 
-static size_t
-ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms,
                         const BYTE* const ip, const BYTE* const iend,
                         size_t* offBasePtr,
                         U32 const mls,
@@ -386,8 +390,9 @@ ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms,
 
 
 /** ZSTD_BtFindBestMatch() : Tree updater, providing best match */
-FORCE_INLINE_TEMPLATE size_t
-ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms,
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms,
                 const BYTE* const ip, const BYTE* const iLimit,
                       size_t* offBasePtr,
                 const U32 mls /* template */,
@@ -622,7 +627,9 @@ size_t ZSTD_dedicatedDictSearch_lazy_search(size_t* offsetPtr, size_t ml, U32 nb
 
 /* Update chains up to ip (excluded)
    Assumption : always within prefix (i.e. not within extDict) */
-FORCE_INLINE_TEMPLATE U32 ZSTD_insertAndFindFirstIndex_internal(
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_insertAndFindFirstIndex_internal(
                         ZSTD_matchState_t* ms,
                         const ZSTD_compressionParameters* const cParams,
                         const BYTE* ip, U32 const mls, U32 const lazySkipping)
@@ -656,6 +663,7 @@ U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip) {
 
 /* inlining is important to hardwire a hot branch (template emulation) */
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_HcFindBestMatch(
                         ZSTD_matchState_t* ms,
                         const BYTE* const ip, const BYTE* const iLimit,
@@ -824,7 +832,9 @@ FORCE_INLINE_TEMPLATE void ZSTD_row_prefetch(U32 const* hashTable, BYTE const* t
  * Fill up the hash cache starting at idx, prefetching up to ZSTD_ROW_HASH_CACHE_SIZE entries,
  * but not beyond iLimit.
  */
-FORCE_INLINE_TEMPLATE void ZSTD_row_fillHashCache(ZSTD_matchState_t* ms, const BYTE* base,
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_row_fillHashCache(ZSTD_matchState_t* ms, const BYTE* base,
                                    U32 const rowLog, U32 const mls,
                                    U32 idx, const BYTE* const iLimit)
 {
@@ -850,7 +860,9 @@ FORCE_INLINE_TEMPLATE void ZSTD_row_fillHashCache(ZSTD_matchState_t* ms, const B
  * Returns the hash of base + idx, and replaces the hash in the hash cache with the byte at
  * base + idx + ZSTD_ROW_HASH_CACHE_SIZE. Also prefetches the appropriate rows from hashTable and tagTable.
  */
-FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTable,
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTable,
                                                   BYTE const* tagTable, BYTE const* base,
                                                   U32 idx, U32 const hashLog,
                                                   U32 const rowLog, U32 const mls,
@@ -868,10 +880,12 @@ FORCE_INLINE_TEMPLATE U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTab
 /* ZSTD_row_update_internalImpl():
  * Updates the hash table with positions starting from updateStartIdx until updateEndIdx.
  */
-FORCE_INLINE_TEMPLATE void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms,
-                                                        U32 updateStartIdx, U32 const updateEndIdx,
-                                                        U32 const mls, U32 const rowLog,
-                                                        U32 const rowMask, U32 const useCache)
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms,
+                                  U32 updateStartIdx, U32 const updateEndIdx,
+                                  U32 const mls, U32 const rowLog,
+                                  U32 const rowMask, U32 const useCache)
 {
     U32* const hashTable = ms->hashTable;
     BYTE* const tagTable = ms->tagTable;
@@ -897,9 +911,11 @@ FORCE_INLINE_TEMPLATE void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms,
  * Inserts the byte at ip into the appropriate position in the hash table, and updates ms->nextToUpdate.
  * Skips sections of long matches as is necessary.
  */
-FORCE_INLINE_TEMPLATE void ZSTD_row_update_internal(ZSTD_matchState_t* ms, const BYTE* ip,
-                                                    U32 const mls, U32 const rowLog,
-                                                    U32 const rowMask, U32 const useCache)
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_row_update_internal(ZSTD_matchState_t* ms, const BYTE* ip,
+                              U32 const mls, U32 const rowLog,
+                              U32 const rowMask, U32 const useCache)
 {
     U32 idx = ms->nextToUpdate;
     const BYTE* const base = ms->window.base;
@@ -1121,6 +1137,7 @@ ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGr
  * - Pick the longest match.
  */
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_RowFindBestMatch(
                         ZSTD_matchState_t* ms,
                         const BYTE* const ip, const BYTE* const iLimit,
@@ -1494,8 +1511,9 @@ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax(
 *  Common parser - lazy strategy
 *********************************/
 
-FORCE_INLINE_TEMPLATE size_t
-ZSTD_compressBlock_lazy_generic(
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_compressBlock_lazy_generic(
                         ZSTD_matchState_t* ms, seqStore_t* seqStore,
                         U32 rep[ZSTD_REP_NUM],
                         const void* src, size_t srcSize,
@@ -1915,6 +1933,7 @@ size_t ZSTD_compressBlock_btlazy2_dictMatchState(
  || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \
  || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR)
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_compressBlock_lazy_extDict_generic(
                         ZSTD_matchState_t* ms, seqStore_t* seqStore,
                         U32 rep[ZSTD_REP_NUM],
diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c
index 01c1f75aa..7a0792ee4 100644
--- a/lib/compress/zstd_ldm.c
+++ b/lib/compress/zstd_ldm.c
@@ -322,7 +322,9 @@ static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor)
     }
 }
 
-static size_t ZSTD_ldm_generateSequences_internal(
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_ldm_generateSequences_internal(
         ldmState_t* ldmState, rawSeqStore_t* rawSeqStore,
         ldmParams_t const* params, void const* src, size_t srcSize)
 {
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 3d54e21ae..11d460c60 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -405,9 +405,11 @@ MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)
 
 /* Update hashTable3 up to ip (excluded)
    Assumption : always within prefix (i.e. not within extDict) */
-static U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms,
-                                              U32* nextToUpdate3,
-                                              const BYTE* const ip)
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms,
+                                       U32* nextToUpdate3,
+                                       const BYTE* const ip)
 {
     U32* const hashTable3 = ms->hashTable3;
     U32 const hashLog3 = ms->hashLog3;
@@ -434,7 +436,9 @@ static U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms,
  * @param ip assumed <= iend-8 .
  * @param target The target of ZSTD_updateTree_internal() - we are filling to this position
  * @return : nb of positions added */
-static U32 ZSTD_insertBt1(
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_insertBt1(
                 const ZSTD_matchState_t* ms,
                 const BYTE* const ip, const BYTE* const iend,
                 U32 const target,
@@ -553,6 +557,7 @@ static U32 ZSTD_insertBt1(
 }
 
 FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 void ZSTD_updateTree_internal(
                 ZSTD_matchState_t* ms,
                 const BYTE* const ip, const BYTE* const iend,
@@ -578,7 +583,9 @@ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {
     ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
 }
 
-FORCE_INLINE_TEMPLATE U32
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32
 ZSTD_insertBtAndGetAllMatches (
                 ZSTD_match_t* matches,  /* store result (found matches) in this table (presumed large enough) */
                 ZSTD_matchState_t* ms,
@@ -819,7 +826,9 @@ typedef U32 (*ZSTD_getAllMatchesFn)(
     U32 const ll0,
     U32 const lengthToBeat);
 
-FORCE_INLINE_TEMPLATE U32 ZSTD_btGetAllMatches_internal(
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+U32 ZSTD_btGetAllMatches_internal(
         ZSTD_match_t* matches,
         ZSTD_matchState_t* ms,
         U32* nextToUpdate3,
@@ -1060,7 +1069,9 @@ listStats(const U32* table, int lastEltID)
 
 #endif
 
-FORCE_INLINE_TEMPLATE size_t
+FORCE_INLINE_TEMPLATE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t
 ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                                seqStore_t* seqStore,
                                U32 rep[ZSTD_REP_NUM],
@@ -1388,11 +1399,12 @@ size_t ZSTD_compressBlock_btopt(
  * only works on first block, with no dictionary and no ldm.
  * this function cannot error out, its narrow contract must be respected.
  */
-static void
-ZSTD_initStats_ultra(ZSTD_matchState_t* ms,
-                     seqStore_t* seqStore,
-                     U32 rep[ZSTD_REP_NUM],
-               const void* src, size_t srcSize)
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+void ZSTD_initStats_ultra(ZSTD_matchState_t* ms,
+                          seqStore_t* seqStore,
+                          U32 rep[ZSTD_REP_NUM],
+                    const void* src, size_t srcSize)
 {
     U32 tmpRep[ZSTD_REP_NUM];  /* updated rep codes will sink here */
     ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));
diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index 5b217ac58..15e420402 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -188,7 +188,7 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
 
     const BYTE* const ilimit = (const BYTE*)src + 6 + 8;
 
-    BYTE* const oend = (BYTE*)dst + dstSize;
+    BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
 
     /* The fast decoding loop assumes 64-bit little-endian.
      * This condition is false on x32.
@@ -546,7 +546,7 @@ HUF_decompress1X1_usingDTable_internal_body(
     const HUF_DTable* DTable)
 {
     BYTE* op = (BYTE*)dst;
-    BYTE* const oend = op + dstSize;
+    BYTE* const oend = ZSTD_maybeNullPtrAdd(op, dstSize);
     const void* dtPtr = DTable + 1;
     const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
     BIT_DStream_t bitD;
@@ -574,6 +574,7 @@ HUF_decompress4X1_usingDTable_internal_body(
 {
     /* Check */
     if (cSrcSize < 10) return ERROR(corruption_detected);  /* strict minimum : jump table + 1 byte per stream */
+    if (dstSize < 6) return ERROR(corruption_detected);         /* stream 4-split doesn't work */
 
     {   const BYTE* const istart = (const BYTE*) cSrc;
         BYTE* const ostart = (BYTE*) dst;
@@ -609,7 +610,7 @@ HUF_decompress4X1_usingDTable_internal_body(
 
         if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
         if (opStart4 > oend) return ERROR(corruption_detected);      /* overflow */
-        if (dstSize < 6) return ERROR(corruption_detected);         /* stream 4-split doesn't work */
+        assert(dstSize >= 6); /* validated above */
         CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
         CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
         CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
@@ -798,7 +799,7 @@ HUF_decompress4X1_usingDTable_internal_fast(
 {
     void const* dt = DTable + 1;
     const BYTE* const iend = (const BYTE*)cSrc + 6;
-    BYTE* const oend = (BYTE*)dst + dstSize;
+    BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, 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");
@@ -1307,7 +1308,7 @@ HUF_decompress1X2_usingDTable_internal_body(
 
     /* decode */
     {   BYTE* const ostart = (BYTE*) dst;
-        BYTE* const oend = ostart + dstSize;
+        BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, 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);
@@ -1332,6 +1333,7 @@ HUF_decompress4X2_usingDTable_internal_body(
     const HUF_DTable* DTable)
 {
     if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */
+    if (dstSize < 6) return ERROR(corruption_detected);         /* stream 4-split doesn't work */
 
     {   const BYTE* const istart = (const BYTE*) cSrc;
         BYTE* const ostart = (BYTE*) dst;
@@ -1367,7 +1369,7 @@ HUF_decompress4X2_usingDTable_internal_body(
 
         if (length4 > cSrcSize) return ERROR(corruption_detected);  /* overflow */
         if (opStart4 > oend) return ERROR(corruption_detected);     /* overflow */
-        if (dstSize < 6) return ERROR(corruption_detected);         /* stream 4-split doesn't work */
+        assert(dstSize >= 6 /* validated above */);
         CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
         CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
         CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
@@ -1612,7 +1614,7 @@ HUF_decompress4X2_usingDTable_internal_fast(
     HUF_DecompressFastLoopFn loopFn) {
     void const* dt = DTable + 1;
     const BYTE* const iend = (const BYTE*)cSrc + 6;
-    BYTE* const oend = (BYTE*)dst + dstSize;
+    BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
     HUF_DecompressFastArgs args;
     {
         size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index 94eb95151..027a0f8cc 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -1058,7 +1058,9 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
     return (size_t)(op-ostart);
 }
 
-static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
+static
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
+size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
                                         void* dst, size_t dstCapacity,
                                   const void* src, size_t srcSize,
                                   const void* dict, size_t dictSize,
diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 9e5c5144b..a4e5c859d 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -902,6 +902,7 @@ static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length
  * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
  */
 FORCE_NOINLINE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_execSequenceEnd(BYTE* op,
     BYTE* const oend, seq_t sequence,
     const BYTE** litPtr, const BYTE* const litLimit,
@@ -949,6 +950,7 @@ size_t ZSTD_execSequenceEnd(BYTE* op,
  * This version is intended to be used during instances where the litBuffer is still split.  It is kept separate to avoid performance impact for the good case.
  */
 FORCE_NOINLINE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op,
     BYTE* const oend, const BYTE* const oend_w, seq_t sequence,
     const BYTE** litPtr, const BYTE* const litLimit,
@@ -994,6 +996,7 @@ size_t ZSTD_execSequenceEndSplitLitBuffer(BYTE* op,
 }
 
 HINT_INLINE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_execSequence(BYTE* op,
     BYTE* const oend, seq_t sequence,
     const BYTE** litPtr, const BYTE* const litLimit,
@@ -1092,6 +1095,7 @@ size_t ZSTD_execSequence(BYTE* op,
 }
 
 HINT_INLINE
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t ZSTD_execSequenceSplitLitBuffer(BYTE* op,
     BYTE* const oend, const BYTE* const oend_w, seq_t sequence,
     const BYTE** litPtr, const BYTE* const litLimit,
@@ -1403,7 +1407,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
     const BYTE* ip = (const BYTE*)seqStart;
     const BYTE* const iend = ip + seqSize;
     BYTE* const ostart = (BYTE*)dst;
-    BYTE* const oend = ostart + maxDstSize;
+    BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, maxDstSize);
     BYTE* op = ostart;
     const BYTE* litPtr = dctx->litPtr;
     const BYTE* litBufferEnd = dctx->litBufferEnd;
@@ -1612,7 +1616,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,
     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 ? ostart + maxDstSize : dctx->litBuffer;
+    BYTE* const oend = dctx->litBufferLocation == ZSTD_not_in_dst ? ZSTD_maybeNullPtrAdd(ostart, maxDstSize) : dctx->litBuffer;
     BYTE* op = ostart;
     const BYTE* litPtr = dctx->litPtr;
     const BYTE* const litEnd = litPtr + dctx->litSize;
@@ -1700,14 +1704,16 @@ ZSTD_decompressSequencesSplitLitBuffer_default(ZSTD_DCtx* dctx,
 
 #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
 
-FORCE_INLINE_TEMPLATE size_t
-ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
+FORCE_INLINE_TEMPLATE
+
+size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence,
                    const BYTE* const prefixStart, const BYTE* const dictEnd)
 {
     prefetchPos += sequence.litLength;
     {   const BYTE* const matchBase = (sequence.offset > prefetchPos) ? dictEnd : prefixStart;
-        const BYTE* const match = matchBase + prefetchPos - sequence.offset; /* 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 */
+        /* 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 */
     }
     return prefetchPos + sequence.matchLength;
@@ -1727,7 +1733,7 @@ ZSTD_decompressSequencesLong_body(
     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 : ostart + maxDstSize;
+    BYTE* const oend = dctx->litBufferLocation == ZSTD_in_dst ? dctx->litBuffer : ZSTD_maybeNullPtrAdd(ostart, maxDstSize);
     BYTE* op = ostart;
     const BYTE* litPtr = dctx->litPtr;
     const BYTE* litBufferEnd = dctx->litBufferEnd;
@@ -2088,7 +2094,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((BYTE*)dst + blockSizeMax, (BYTE const*)dctx->virtualStart);
+        size_t const totalHistorySize = ZSTD_totalHistorySize(ZSTD_maybeNullPtrAdd((BYTE*)dst, 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.
@@ -2168,6 +2174,7 @@ ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
 }
 
 
+ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst, size_t dstSize)
 {
     if (dst != dctx->previousDstEnd && dstSize > 0) {   /* not contiguous */
@@ -2187,6 +2194,7 @@ size_t ZSTD_decompressBlock_deprecated(ZSTD_DCtx* dctx,
     dctx->isFrameDecompression = 0;
     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;
     return dSize;
 }
diff --git a/lib/legacy/zstd_legacy.h b/lib/legacy/zstd_legacy.h
index dd173251d..7a8a04e59 100644
--- a/lib/legacy/zstd_legacy.h
+++ b/lib/legacy/zstd_legacy.h
@@ -124,6 +124,20 @@ MEM_STATIC size_t ZSTD_decompressLegacy(
                const void* dict,size_t dictSize)
 {
     U32 const version = ZSTD_isLegacy(src, compressedSize);
+    char x;
+    /* Avoid passing NULL to legacy decoding. */
+    if (dst == NULL) {
+        assert(dstCapacity == 0);
+        dst = &x;
+    }
+    if (src == NULL) {
+        assert(compressedSize == 0);
+        src = &x;
+    }
+    if (dict == NULL) {
+        assert(dictSize == 0);
+        dict = &x;
+    }
     (void)dst; (void)dstCapacity; (void)dict; (void)dictSize;  /* unused when ZSTD_LEGACY_SUPPORT >= 8 */
     switch(version)
     {
@@ -287,6 +301,12 @@ MEM_STATIC size_t ZSTD_freeLegacyStreamContext(void* legacyContext, U32 version)
 MEM_STATIC size_t ZSTD_initLegacyStream(void** legacyContext, U32 prevVersion, U32 newVersion,
                                         const void* dict, size_t dictSize)
 {
+    char x;
+    /* Avoid passing NULL to legacy decoding. */
+    if (dict == NULL) {
+        assert(dictSize == 0);
+        dict = &x;
+    }
     DEBUGLOG(5, "ZSTD_initLegacyStream for v0.%u", newVersion);
     if (prevVersion != newVersion) ZSTD_freeLegacyStreamContext(*legacyContext, prevVersion);
     switch(newVersion)
@@ -346,6 +366,16 @@ MEM_STATIC size_t ZSTD_initLegacyStream(void** legacyContext, U32 prevVersion, U
 MEM_STATIC size_t ZSTD_decompressLegacyStream(void* legacyContext, U32 version,
                                               ZSTD_outBuffer* output, ZSTD_inBuffer* input)
 {
+    static char x;
+    /* Avoid passing NULL to legacy decoding. */
+    if (output->dst == NULL) {
+        assert(output->size == 0);
+        output->dst = &x;
+    }
+    if (input->src == NULL) {
+        assert(input->size == 0);
+        input->src = &x;
+    }
     DEBUGLOG(5, "ZSTD_decompressLegacyStream for v0.%u", version);
     switch(version)
     {
diff --git a/lib/legacy/zstd_v01.c b/lib/legacy/zstd_v01.c
index 1a3aad07e..6cf51234a 100644
--- a/lib/legacy/zstd_v01.c
+++ b/lib/legacy/zstd_v01.c
@@ -14,6 +14,7 @@
 ******************************************/
 #include     /* size_t, ptrdiff_t */
 #include "zstd_v01.h"
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -2118,6 +2119,7 @@ size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSi
         }
         ctx->phase = 1;
         ctx->expected = ZSTD_blockHeaderSize;
+        if (ZSTDv01_isError(rSize)) return rSize;
         ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
         return rSize;
     }
diff --git a/lib/legacy/zstd_v02.c b/lib/legacy/zstd_v02.c
index e09bb4a24..80615e556 100644
--- a/lib/legacy/zstd_v02.c
+++ b/lib/legacy/zstd_v02.c
@@ -11,6 +11,7 @@
 
 #include     /* size_t, ptrdiff_t */
 #include "zstd_v02.h"
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -71,20 +72,6 @@ extern "C" {
 #include     /* memcpy */
 
 
-/******************************************
-*  Compiler-specific
-******************************************/
-#if defined(__GNUC__)
-#  define MEM_STATIC static __attribute__((unused))
-#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
-#  define MEM_STATIC static inline
-#elif defined(_MSC_VER)
-#  define MEM_STATIC static __inline
-#else
-#  define MEM_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
-#endif
-
-
 /****************************************************************
 *  Basic Types
 *****************************************************************/
@@ -3431,6 +3418,7 @@ static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSi
         }
         ctx->phase = 1;
         ctx->expected = ZSTD_blockHeaderSize;
+        if (ZSTD_isError(rSize)) return rSize;
         ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
         return rSize;
     }
diff --git a/lib/legacy/zstd_v03.c b/lib/legacy/zstd_v03.c
index b0d7f521e..082fe8705 100644
--- a/lib/legacy/zstd_v03.c
+++ b/lib/legacy/zstd_v03.c
@@ -11,6 +11,7 @@
 
 #include     /* size_t, ptrdiff_t */
 #include "zstd_v03.h"
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -72,20 +73,6 @@ extern "C" {
 #include     /* memcpy */
 
 
-/******************************************
-*  Compiler-specific
-******************************************/
-#if defined(__GNUC__)
-#  define MEM_STATIC static __attribute__((unused))
-#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
-#  define MEM_STATIC static inline
-#elif defined(_MSC_VER)
-#  define MEM_STATIC static __inline
-#else
-#  define MEM_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
-#endif
-
-
 /****************************************************************
 *  Basic Types
 *****************************************************************/
@@ -3071,6 +3058,7 @@ static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSi
         }
         ctx->phase = 1;
         ctx->expected = ZSTD_blockHeaderSize;
+        if (ZSTD_isError(rSize)) return rSize;
         ctx->previousDstEnd = (void*)( ((char*)dst) + rSize);
         return rSize;
     }
diff --git a/lib/legacy/zstd_v04.c b/lib/legacy/zstd_v04.c
index fa65160bc..0da316c15 100644
--- a/lib/legacy/zstd_v04.c
+++ b/lib/legacy/zstd_v04.c
@@ -16,6 +16,7 @@
 #include     /* memcpy */
 
 #include "zstd_v04.h"
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -3209,6 +3210,7 @@ static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSi
             }
             ctx->stage = ZSTDds_decodeBlockHeader;
             ctx->expected = ZSTD_blockHeaderSize;
+            if (ZSTD_isError(rSize)) return rSize;
             ctx->previousDstEnd = (char*)dst + rSize;
             return rSize;
         }
@@ -3536,8 +3538,8 @@ static size_t ZBUFF_decompressContinue(ZBUFF_DCtx* zbc, void* dst, size_t* maxDs
 unsigned ZBUFFv04_isError(size_t errorCode) { return ERR_isError(errorCode); }
 const char* ZBUFFv04_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
 
-size_t ZBUFFv04_recommendedDInSize()  { return BLOCKSIZE + 3; }
-size_t ZBUFFv04_recommendedDOutSize() { return BLOCKSIZE; }
+size_t ZBUFFv04_recommendedDInSize(void)  { return BLOCKSIZE + 3; }
+size_t ZBUFFv04_recommendedDOutSize(void) { return BLOCKSIZE; }
 
 
 
diff --git a/lib/legacy/zstd_v05.c b/lib/legacy/zstd_v05.c
index 93a1169f3..44a877bf1 100644
--- a/lib/legacy/zstd_v05.c
+++ b/lib/legacy/zstd_v05.c
@@ -3600,6 +3600,7 @@ size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t maxDstSi
             }
             dctx->stage = ZSTDv05ds_decodeBlockHeader;
             dctx->expected = ZSTDv05_blockHeaderSize;
+            if (ZSTDv05_isError(rSize)) return rSize;
             dctx->previousDstEnd = (char*)dst + rSize;
             return rSize;
         }
diff --git a/lib/legacy/zstd_v06.c b/lib/legacy/zstd_v06.c
index ac9ae987c..00d6ef79a 100644
--- a/lib/legacy/zstd_v06.c
+++ b/lib/legacy/zstd_v06.c
@@ -14,6 +14,7 @@
 #include     /* size_t, ptrdiff_t */
 #include     /* memcpy */
 #include     /* malloc, free, qsort */
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -3736,6 +3737,7 @@ size_t ZSTDv06_decompressContinue(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapac
             }
             dctx->stage = ZSTDds_decodeBlockHeader;
             dctx->expected = ZSTDv06_blockHeaderSize;
+            if (ZSTDv06_isError(rSize)) return rSize;
             dctx->previousDstEnd = (char*)dst + rSize;
             return rSize;
         }
diff --git a/lib/legacy/zstd_v07.c b/lib/legacy/zstd_v07.c
index b214ec08b..8778f079c 100644
--- a/lib/legacy/zstd_v07.c
+++ b/lib/legacy/zstd_v07.c
@@ -24,6 +24,7 @@
 #define HUFv07_STATIC_LINKING_ONLY   /* HUFv07_TABLELOG_ABSOLUTEMAX */
 #define ZSTDv07_STATIC_LINKING_ONLY
 
+#include "../common/compiler.h"
 #include "../common/error_private.h"
 
 
@@ -4006,8 +4007,8 @@ size_t ZSTDv07_decompressContinue(ZSTDv07_DCtx* dctx, void* dst, size_t dstCapac
             }
             dctx->stage = ZSTDds_decodeBlockHeader;
             dctx->expected = ZSTDv07_blockHeaderSize;
-            dctx->previousDstEnd = (char*)dst + rSize;
             if (ZSTDv07_isError(rSize)) return rSize;
+            dctx->previousDstEnd = (char*)dst + rSize;
             if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
             return rSize;
         }
diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c
index a440ae38a..1abc7df8b 100644
--- a/tests/decodecorpus.c
+++ b/tests/decodecorpus.c
@@ -732,7 +732,7 @@ generateSequences(U32* seed, frame_t* frame, seqStore_t* seqStore,
             }
         } while (((!info.useDict) && (offset > (size_t)((BYTE*)srcPtr - (BYTE*)frame->srcStart))) || offset == 0);
 
-        {   BYTE* const dictEnd = info.dictContent + info.dictContentSize;
+        {   BYTE* const dictEnd = ZSTD_maybeNullPtrAdd(info.dictContent, info.dictContentSize);
             size_t j;
             for (j = 0; j < matchLen; j++) {
                 if ((U32)((BYTE*)srcPtr - (BYTE*)frame->srcStart) < offset) {
diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py
index 8e0a9eaad..058fca813 100755
--- a/tests/fuzz/fuzz.py
+++ b/tests/fuzz/fuzz.py
@@ -250,10 +250,10 @@ def build_parser(args):
         action='store_true',
         help='Enable UBSAN')
     parser.add_argument(
-        '--enable-ubsan-pointer-overflow',
+        '--disable-ubsan-pointer-overflow',
         dest='ubsan_pointer_overflow',
-        action='store_true',
-        help='Enable UBSAN pointer overflow check (known failure)')
+        action='store_false',
+        help='Disable UBSAN pointer overflow check (known failure)')
     parser.add_argument(
         '--enable-msan', dest='msan', action='store_true', help='Enable MSAN')
     parser.add_argument(
@@ -383,8 +383,6 @@ def build_parser(args):
         raise RuntimeError('MSAN may not be used with any other sanitizers')
     if args.msan_track_origins and not args.msan:
         raise RuntimeError('--enable-msan-track-origins requires MSAN')
-    if args.ubsan_pointer_overflow and not args.ubsan:
-        raise RuntimeError('--enable-ubsan-pointer-overflow requires UBSAN')
     if args.sanitize_recover and not args.sanitize:
         raise RuntimeError('--enable-sanitize-recover but no sanitizers used')
 
diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c
index ede7080e3..ec0106c18 100644
--- a/tests/fuzz/sequence_compression_api.c
+++ b/tests/fuzz/sequence_compression_api.c
@@ -116,7 +116,7 @@ static size_t decodeSequences(void* dst, size_t nbSequences,
                 }
             }
             for (; j < matchLength; ++j) {
-                op[j] = op[j - generatedSequences[i].offset];
+                op[j] = op[(ptrdiff_t)(j - generatedSequences[i].offset)];
             }
             op += j;
             FUZZ_ASSERT(generatedSequences[i].matchLength == j + k);
diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index 4a68ff731..4a540270f 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -328,7 +328,7 @@ static void FUZ_decodeSequences(BYTE* dst, ZSTD_Sequence* seqs, size_t seqsSize,
 
         if (seqs[i].offset != 0) {
             for (j = 0; j < seqs[i].matchLength; ++j)
-                dst[j] = dst[j - seqs[i].offset];
+                dst[j] = dst[(ptrdiff_t)(j - seqs[i].offset)];
             dst += seqs[i].matchLength;
             src += seqs[i].matchLength;
             size -= seqs[i].matchLength;
@@ -3684,11 +3684,13 @@ static int basicUnitTests(U32 const seed, double compressibility)
 
         /* Test with block delimiters roundtrip */
         seqsSize = ZSTD_generateSequences(cctx, seqs, srcSize, src, srcSize);
+        CHECK_Z(seqsSize);
         FUZ_decodeSequences(decoded, seqs, seqsSize, src, srcSize, ZSTD_sf_explicitBlockDelimiters);
         assert(!memcmp(CNBuffer, compressedBuffer, srcSize));
 
         /* Test no block delimiters roundtrip */
         seqsSize = ZSTD_mergeBlockDelimiters(seqs, seqsSize);
+        CHECK_Z(seqsSize);
         FUZ_decodeSequences(decoded, seqs, seqsSize, src, srcSize, ZSTD_sf_noBlockDelimiters);
         assert(!memcmp(CNBuffer, compressedBuffer, srcSize));
 

From e8ff7d18ebdb7af55ad73f92c5192e74bdc85ca2 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 7 Oct 2023 20:19:45 -0700
Subject: [PATCH 098/937] removed FlexArray pattern from CCtxPool

within ZSTDMT_.
This pattern is flagged by less forgiving variants of ubsan
notably used during compilation of the Linux Kernel.

There are 2 other places in the code where this pattern is used.
This fixes just one of them.
---
 lib/compress/zstd_compress.c   |  1 +
 lib/compress/zstdmt_compress.c | 29 ++++++++++++++++++-----------
 tests/fuzzer.c                 | 14 ++++++++------
 3 files changed, 27 insertions(+), 17 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index a51c00792..b79266fdb 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -178,6 +178,7 @@ static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
 
 size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
 {
+    DEBUGLOG(3, "ZSTD_freeCCtx (address: %p)", (void*)cctx);
     if (cctx==NULL) return 0;   /* support free on NULL */
     RETURN_ERROR_IF(cctx->staticSize, memory_allocation,
                     "not compatible with static CCtx");
diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index add99d769..236daab26 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -350,15 +350,16 @@ typedef struct {
     int totalCCtx;
     int availCCtx;
     ZSTD_customMem cMem;
-    ZSTD_CCtx* cctx[1];   /* variable size */
+    ZSTD_CCtx** cctxs;
 } ZSTDMT_CCtxPool;
 
-/* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
+/* note : all CCtx borrowed from the pool must be reverted back to the pool _before_ freeing the pool */
 static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
 {
     int cid;
     for (cid=0; cidtotalCCtx; cid++)
-        ZSTD_freeCCtx(pool->cctx[cid]);  /* note : compatible with free on NULL */
+        ZSTD_freeCCtx(pool->cctxs[cid]);  /* note : compatible with free on NULL */
+    ZSTD_customFree(pool->cctxs, pool->cMem);
     ZSTD_pthread_mutex_destroy(&pool->poolMutex);
     ZSTD_customFree(pool, pool->cMem);
 }
@@ -373,14 +374,19 @@ static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
     assert(nbWorkers > 0);
     if (!cctxPool) return NULL;
     if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
+        ZSTDMT_freeCCtxPool(cctxPool);
+        return NULL;
+    }
+    cctxPool->totalCCtx = nbWorkers;
+    cctxPool->cctxs = (ZSTD_CCtx**)ZSTD_customCalloc(nbWorkers * sizeof(ZSTD_CCtx*), cMem);
+    if (!cctxPool->cctxs) {
         ZSTD_customFree(cctxPool, cMem);
         return NULL;
     }
     cctxPool->cMem = cMem;
-    cctxPool->totalCCtx = nbWorkers;
+    cctxPool->cctxs[0] = ZSTD_createCCtx_advanced(cMem);
+    if (!cctxPool->cctxs[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
     cctxPool->availCCtx = 1;   /* at least one cctx for single-thread mode */
-    cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
-    if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
     DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
     return cctxPool;
 }
@@ -404,14 +410,15 @@ static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
     {   unsigned const nbWorkers = cctxPool->totalCCtx;
         size_t const poolSize = sizeof(*cctxPool)
                                 + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
-        unsigned u;
+        size_t const arraySize = cctxPool->totalCCtx * sizeof(ZSTD_CCtx*);
         size_t totalCCtxSize = 0;
+        unsigned u;
         for (u=0; ucctx[u]);
+            totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctxs[u]);
         }
         ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
         assert(nbWorkers > 0);
-        return poolSize + totalCCtxSize;
+        return poolSize + arraySize + totalCCtxSize;
     }
 }
 
@@ -421,7 +428,7 @@ static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
     ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
     if (cctxPool->availCCtx) {
         cctxPool->availCCtx--;
-        {   ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
+        {   ZSTD_CCtx* const cctx = cctxPool->cctxs[cctxPool->availCCtx];
             ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
             return cctx;
     }   }
@@ -435,7 +442,7 @@ static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
     if (cctx==NULL) return;   /* compatibility with release on NULL */
     ZSTD_pthread_mutex_lock(&pool->poolMutex);
     if (pool->availCCtx < pool->totalCCtx)
-        pool->cctx[pool->availCCtx++] = cctx;
+        pool->cctxs[pool->availCCtx++] = cctx;
     else {
         /* pool overflow : should not happen, since totalCCtx==nbWorkers */
         DEBUGLOG(4, "CCtx pool overflow : free cctx");
diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index c920fbb13..d70a66904 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -1119,6 +1119,9 @@ static int basicUnitTests(U32 const seed, double compressibility)
         size_t const srcSize1 = kWindowSize / 2;
         size_t const srcSize2 = kWindowSize * 10;
 
+        CHECK(cctx!=NULL);
+        CHECK(dctx!=NULL);
+        CHECK(dict!=NULL);
         if (CNBuffSize < dictSize) goto _output_error;
 
         RDG_genBuffer(dict, dictSize, 0.5, 0.5, seed);
@@ -1140,6 +1143,7 @@ static int basicUnitTests(U32 const seed, double compressibility)
         cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, srcSize1);
         CHECK_Z(cSize);
         CHECK_Z(ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, dict, dictSize));
+
         cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, srcSize2);
         /* Streaming decompression to catch out of bounds offsets. */
         {
@@ -1153,24 +1157,22 @@ static int basicUnitTests(U32 const seed, double compressibility)
         CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 2));
         /* Round trip once with a dictionary. */
         CHECK_Z(ZSTD_CCtx_refPrefix(cctx, dict, dictSize));
-        {
-            ZSTD_inBuffer in = {CNBuffer, srcSize1, 0};
+        {   ZSTD_inBuffer in = {CNBuffer, srcSize1, 0};
             ZSTD_outBuffer out = {compressedBuffer, compressedBufferSize, 0};
             CHECK_Z(ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_flush));
             CHECK_Z(ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end));
             cSize = out.pos;
         }
         CHECK_Z(ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, dict, dictSize));
-        {
-            ZSTD_inBuffer in = {CNBuffer, srcSize2, 0};
+
+        {   ZSTD_inBuffer in = {CNBuffer, srcSize2, 0};
             ZSTD_outBuffer out = {compressedBuffer, compressedBufferSize, 0};
             CHECK_Z(ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_flush));
             CHECK_Z(ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end));
             cSize = out.pos;
         }
         /* Streaming decompression to catch out of bounds offsets. */
-        {
-            ZSTD_inBuffer in = {compressedBuffer, cSize, 0};
+        {   ZSTD_inBuffer in = {compressedBuffer, cSize, 0};
             ZSTD_outBuffer out = {decodedBuffer, CNBuffSize, 0};
             size_t const dSize = ZSTD_decompressStream(dctx, &out, &in);
             CHECK_Z(dSize);

From c87ad5bdb59c95c16871ff99d83ec3b09bd742c8 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 7 Oct 2023 23:29:42 -0700
Subject: [PATCH 099/937] fixes suggested by @ebiggers

---
 lib/compress/zstdmt_compress.c | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)

diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index 236daab26..1b47734c2 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -369,18 +369,18 @@ static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
 static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
                                               ZSTD_customMem cMem)
 {
-    ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_customCalloc(
-        sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);
+    ZSTDMT_CCtxPool* const cctxPool = 
+        (ZSTDMT_CCtxPool*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtxPool), cMem);
     assert(nbWorkers > 0);
     if (!cctxPool) return NULL;
     if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
-        ZSTDMT_freeCCtxPool(cctxPool);
+        ZSTD_customFree(cctxPool, cMem);
         return NULL;
     }
     cctxPool->totalCCtx = nbWorkers;
     cctxPool->cctxs = (ZSTD_CCtx**)ZSTD_customCalloc(nbWorkers * sizeof(ZSTD_CCtx*), cMem);
     if (!cctxPool->cctxs) {
-        ZSTD_customFree(cctxPool, cMem);
+        ZSTDMT_freeCCtxPool(cctxPool);
         return NULL;
     }
     cctxPool->cMem = cMem;
@@ -408,8 +408,7 @@ static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
 {
     ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
     {   unsigned const nbWorkers = cctxPool->totalCCtx;
-        size_t const poolSize = sizeof(*cctxPool)
-                                + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
+        size_t const poolSize = sizeof(*cctxPool);
         size_t const arraySize = cctxPool->totalCCtx * sizeof(ZSTD_CCtx*);
         size_t totalCCtxSize = 0;
         unsigned u;

From ea4027c003d31bb75d24a2284d06ed4c06300f59 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 7 Oct 2023 23:32:22 -0700
Subject: [PATCH 100/937] removed unused macro constant

---
 lib/compress/zstdmt_compress.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)

diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index 1b47734c2..529fb6158 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -15,17 +15,13 @@
 #endif
 
 
-/* ======   Constants   ====== */
-#define ZSTDMT_OVERLAPLOG_DEFAULT 0
-
-
 /* ======   Dependencies   ====== */
-#include "../common/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
+#include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
 #include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memset, INT_MAX, UINT_MAX */
 #include "../common/mem.h"         /* MEM_STATIC */
 #include "../common/pool.h"        /* threadpool */
 #include "../common/threading.h"   /* mutex */
-#include "zstd_compress_internal.h"  /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
+#include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
 #include "zstd_ldm.h"
 #include "zstdmt_compress.h"
 

From 6bb1688c1a13a9368d7c1b6f992e0a0fa7c1cbba Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 8 Oct 2023 00:25:17 -0700
Subject: [PATCH 101/937] extended the fix to ZSTDMT's Buffer Pool

---
 lib/compress/zstdmt_compress.c | 65 ++++++++++++++++++++--------------
 1 file changed, 38 insertions(+), 27 deletions(-)

diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index 529fb6158..6b3391a0f 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -96,18 +96,39 @@ typedef struct ZSTDMT_bufferPool_s {
     unsigned totalBuffers;
     unsigned nbBuffers;
     ZSTD_customMem cMem;
-    buffer_t bTable[1];   /* variable size */
+    buffer_t* buffers;
 } ZSTDMT_bufferPool;
 
+static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
+{
+    unsigned u;
+    DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
+    if (!bufPool) return;   /* compatibility with free on NULL */
+    if (bufPool->buffers) {
+        for (u=0; utotalBuffers; u++) {
+            DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->buffers[u].start);
+            ZSTD_customFree(bufPool->buffers[u].start, bufPool->cMem);
+        }
+        ZSTD_customFree(bufPool->buffers, bufPool->cMem);
+    }
+    ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
+    ZSTD_customFree(bufPool, bufPool->cMem);
+}
+
 static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_customMem cMem)
 {
-    ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_customCalloc(
-        sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);
+    ZSTDMT_bufferPool* const bufPool = 
+        (ZSTDMT_bufferPool*)ZSTD_customCalloc(sizeof(ZSTDMT_bufferPool), cMem);
     if (bufPool==NULL) return NULL;
     if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
         ZSTD_customFree(bufPool, cMem);
         return NULL;
     }
+    bufPool->buffers = (buffer_t*)ZSTD_customCalloc(maxNbBuffers * sizeof(buffer_t), cMem);
+    if (bufPool->buffers==NULL) {
+        ZSTDMT_freeBufferPool(bufPool);
+        return NULL;
+    }
     bufPool->bufferSize = 64 KB;
     bufPool->totalBuffers = maxNbBuffers;
     bufPool->nbBuffers = 0;
@@ -115,32 +136,19 @@ static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_cu
     return bufPool;
 }
 
-static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
-{
-    unsigned u;
-    DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
-    if (!bufPool) return;   /* compatibility with free on NULL */
-    for (u=0; utotalBuffers; u++) {
-        DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);
-        ZSTD_customFree(bufPool->bTable[u].start, bufPool->cMem);
-    }
-    ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
-    ZSTD_customFree(bufPool, bufPool->cMem);
-}
-
 /* only works at initialization, not during compression */
 static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)
 {
-    size_t const poolSize = sizeof(*bufPool)
-                          + (bufPool->totalBuffers - 1) * sizeof(buffer_t);
+    size_t const poolSize = sizeof(*bufPool);
+    size_t const arraySize = bufPool->totalBuffers * sizeof(buffer_t);
     unsigned u;
     size_t totalBufferSize = 0;
     ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
     for (u=0; utotalBuffers; u++)
-        totalBufferSize += bufPool->bTable[u].capacity;
+        totalBufferSize += bufPool->buffers[u].capacity;
     ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
 
-    return poolSize + totalBufferSize;
+    return poolSize + arraySize + totalBufferSize;
 }
 
 /* ZSTDMT_setBufferSize() :
@@ -183,9 +191,9 @@ static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)
     DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);
     ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
     if (bufPool->nbBuffers) {   /* try to use an existing buffer */
-        buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];
+        buffer_t const buf = bufPool->buffers[--(bufPool->nbBuffers)];
         size_t const availBufferSize = buf.capacity;
-        bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;
+        bufPool->buffers[bufPool->nbBuffers] = g_nullBuffer;
         if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {
             /* large enough, but not too much */
             DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",
@@ -246,14 +254,14 @@ static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
     if (buf.start == NULL) return;   /* compatible with release on NULL */
     ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
     if (bufPool->nbBuffers < bufPool->totalBuffers) {
-        bufPool->bTable[bufPool->nbBuffers++] = buf;  /* stored for later use */
+        bufPool->buffers[bufPool->nbBuffers++] = buf;  /* stored for later use */
         DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",
                     (U32)buf.capacity, (U32)(bufPool->nbBuffers-1));
         ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
         return;
     }
     ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
-    /* Reached bufferPool capacity (should not happen) */
+    /* Reached bufferPool capacity (note: should not happen) */
     DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");
     ZSTD_customFree(buf.start, bufPool->cMem);
 }
@@ -353,10 +361,13 @@ typedef struct {
 static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
 {
     int cid;
-    for (cid=0; cidtotalCCtx; cid++)
-        ZSTD_freeCCtx(pool->cctxs[cid]);  /* note : compatible with free on NULL */
-    ZSTD_customFree(pool->cctxs, pool->cMem);
+    if (!pool) return;
     ZSTD_pthread_mutex_destroy(&pool->poolMutex);
+    if (pool->cctxs) {
+        for (cid=0; cidtotalCCtx; cid++)
+            ZSTD_freeCCtx(pool->cctxs[cid]);  /* free compatible with NULL */
+        ZSTD_customFree(pool->cctxs, pool->cMem);
+    }
     ZSTD_customFree(pool, pool->cMem);
 }
 

From e590c8a0e3b2ecdde5f63d385fa7f9bd759721d3 Mon Sep 17 00:00:00 2001
From: Xavier Mitault 
Date: Wed, 18 Oct 2023 13:22:15 +0200
Subject: [PATCH 102/937] Add doc on how to use it with cmake FetchContent

---
 build/cmake/README.md | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/build/cmake/README.md b/build/cmake/README.md
index a460dd161..022e61688 100644
--- a/build/cmake/README.md
+++ b/build/cmake/README.md
@@ -41,6 +41,31 @@ cmake -DZSTD_BUILD_TESTS=ON -DZSTD_LEGACY_SUPPORT=OFF ..
 make
 ```
 
+### how to use it with CMake FetchContent
+
+For all options available, you can see it on 
+```cmake
+include(FetchContent)
+
+set(ZSTD_BUILD_STATIC ON)
+set(ZSTD_BUILD_SHARED OFF)
+
+FetchContent_Declare(
+    zstd
+    URL "https://github.com/facebook/zstd/releases/download/v1.5.5/zstd-1.5.5.tar.gz"
+    DOWNLOAD_EXTRACT_TIMESTAMP TRUE
+    SOURCE_SUBDIR build/cmake
+)
+
+FetchContent_MakeAvailable(zstd)
+
+target_link_libraries(
+    ${PROJECT_NAME}
+    PRIVATE
+    libzstd_static
+)
+```
+
 ### referring
 [Looking for a 'cmake clean' command to clear up CMake output](https://stackoverflow.com/questions/9680420/looking-for-a-cmake-clean-command-to-clear-up-cmake-output)
 

From d988e00a7fe551785bc8c3de8cd5e4266280ce6d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 9 Oct 2023 16:47:52 -0700
Subject: [PATCH 103/937] baby-step towards solving flexArray issue #3785

the flexArray in structure FSE_DecompressWksp
is just a way to derive a pointer easily,
without risk/complexity of calculating it manually.

Not sure if this change is good enough to avoid ubsan warnings though.
---
 lib/common/fse_decompress.c | 28 ++++++++++++++--------------
 lib/compress/fse_compress.c | 13 +++++++------
 2 files changed, 21 insertions(+), 20 deletions(-)

diff --git a/lib/common/fse_decompress.c b/lib/common/fse_decompress.c
index 1e1c9f92d..f9bee931f 100644
--- a/lib/common/fse_decompress.c
+++ b/lib/common/fse_decompress.c
@@ -84,7 +84,7 @@ static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCo
                     symbolNext[s] = 1;
                 } else {
                     if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
-                    symbolNext[s] = normalizedCounter[s];
+                    symbolNext[s] = (U16)normalizedCounter[s];
         }   }   }
         ZSTD_memcpy(dt, &DTableH, sizeof(DTableH));
     }
@@ -99,8 +99,7 @@ static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCo
          * all symbols have counts <= 8. We ensure we have 8 bytes at the end of
          * our buffer to handle the over-write.
          */
-        {
-            U64 const add = 0x0101010101010101ull;
+        {   U64 const add = 0x0101010101010101ull;
             size_t pos = 0;
             U64 sv = 0;
             U32 s;
@@ -111,9 +110,8 @@ static size_t FSE_buildDTable_internal(FSE_DTable* dt, const short* normalizedCo
                 for (i = 8; i < n; i += 8) {
                     MEM_write64(spread + pos + i, sv);
                 }
-                pos += n;
-            }
-        }
+                pos += (size_t)n;
+        }   }
         /* Now we spread those positions across the table.
          * The benefit of doing it in two stages is that we avoid the
          * variable size inner loop, which caused lots of branch misses.
@@ -232,12 +230,13 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
             break;
     }   }
 
-    return op-ostart;
+    assert(op >= ostart);
+    return (size_t)(op-ostart);
 }
 
 typedef struct {
     short ncount[FSE_MAX_SYMBOL_VALUE + 1];
-    FSE_DTable dtable[1]; /* Dynamically sized */
+    FSE_DTable dtable[1]; /* actual size is dynamic - member just helps get a pointer easily */
 } FSE_DecompressWksp;
 
 
@@ -252,13 +251,14 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body(
     unsigned tableLog;
     unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
     FSE_DecompressWksp* const wksp = (FSE_DecompressWksp*)workSpace;
+    FSE_DTable* const dtable = wksp->dtable;
 
     DEBUG_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0);
     if (wkspSize < sizeof(*wksp)) return ERROR(GENERIC);
 
     /* normal FSE decoding mode */
-    {
-        size_t const NCountLength = FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2);
+    {   size_t const NCountLength =
+            FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2);
         if (FSE_isError(NCountLength)) return NCountLength;
         if (tableLog > maxLog) return ERROR(tableLog_tooLarge);
         assert(NCountLength <= cSrcSize);
@@ -271,16 +271,16 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body(
     workSpace = (BYTE*)workSpace + sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
     wkspSize -= sizeof(*wksp) + FSE_DTABLE_SIZE(tableLog);
 
-    CHECK_F( FSE_buildDTable_internal(wksp->dtable, wksp->ncount, maxSymbolValue, tableLog, workSpace, wkspSize) );
+    CHECK_F( FSE_buildDTable_internal(dtable, wksp->ncount, maxSymbolValue, tableLog, workSpace, wkspSize) );
 
     {
-        const void* ptr = wksp->dtable;
+        const void* ptr = dtable;
         const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
         const U32 fastMode = DTableH->fastMode;
 
         /* select fast mode (static) */
-        if (fastMode) return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, wksp->dtable, 1);
-        return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, wksp->dtable, 0);
+        if (fastMode) return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 1);
+        return FSE_decompress_usingDTable_generic(dst, dstCapacity, ip, cSrcSize, dtable, 0);
     }
 }
 
diff --git a/lib/compress/fse_compress.c b/lib/compress/fse_compress.c
index 5d3770808..158ba80ca 100644
--- a/lib/compress/fse_compress.c
+++ b/lib/compress/fse_compress.c
@@ -225,8 +225,8 @@ size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
     size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog
                                    + 4 /* bitCount initialized at 4 */
                                    + 2 /* first two symbols may use one additional bit each */) / 8)
-                                    + 1 /* round up to whole nb bytes */
-                                    + 2 /* additional two bytes for bitstream flush */;
+                                   + 1 /* round up to whole nb bytes */
+                                   + 2 /* additional two bytes for bitstream flush */;
     return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND;  /* maxSymbolValue==0 ? use default */
 }
 
@@ -255,7 +255,7 @@ FSE_writeNCount_generic (void* header, size_t headerBufferSize,
     /* Init */
     remaining = tableSize+1;   /* +1 for extra accuracy */
     threshold = tableSize;
-    nbBits = tableLog+1;
+    nbBits = (int)tableLog+1;
 
     while ((symbol < alphabetSize) && (remaining>1)) {  /* stops at 1 */
         if (previousIs0) {
@@ -274,7 +274,7 @@ FSE_writeNCount_generic (void* header, size_t headerBufferSize,
             }
             while (symbol >= start+3) {
                 start+=3;
-                bitStream += 3 << bitCount;
+                bitStream += 3U << bitCount;
                 bitCount += 2;
             }
             bitStream += (symbol-start) << bitCount;
@@ -294,7 +294,7 @@ FSE_writeNCount_generic (void* header, size_t headerBufferSize,
             count++;   /* +1 for extra accuracy */
             if (count>=threshold)
                 count += max;   /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
-            bitStream += count << bitCount;
+            bitStream += (U32)count << bitCount;
             bitCount  += nbBits;
             bitCount  -= (count>8);
     out+= (bitCount+7) /8;
 
-    return (out-ostart);
+    assert(out >= ostart);
+    return (size_t)(out-ostart);
 }
 
 

From 24dabde507c8d141e282e568be21e648987a7d77 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 18 Oct 2023 22:45:57 -0700
Subject: [PATCH 104/937] revert to manually defining DTable

thus avoiding the analyzer and ubsan to associate DTable to a size of 1.
---
 lib/common/fse.h            |  5 +++--
 lib/common/fse_decompress.c | 12 +++++++-----
 2 files changed, 10 insertions(+), 7 deletions(-)

diff --git a/lib/common/fse.h b/lib/common/fse.h
index 02a1f0bc5..2ae128e60 100644
--- a/lib/common/fse.h
+++ b/lib/common/fse.h
@@ -229,6 +229,7 @@ If there is an error, the function will return an error code, which can be teste
 
 #endif  /* FSE_H */
 
+
 #if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
 #define FSE_H_FSE_STATIC_LINKING_ONLY
 
@@ -464,13 +465,13 @@ MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, un
     FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
     const U16* const stateTable = (const U16*)(statePtr->stateTable);
     U32 const nbBitsOut  = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
-    BIT_addBits(bitC, statePtr->value, nbBitsOut);
+    BIT_addBits(bitC,  (size_t)statePtr->value, nbBitsOut);
     statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
 }
 
 MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)
 {
-    BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
+    BIT_addBits(bitC, (size_t)statePtr->value, statePtr->stateLog);
     BIT_flushBits(bitC);
 }
 
diff --git a/lib/common/fse_decompress.c b/lib/common/fse_decompress.c
index f9bee931f..0dcc4640d 100644
--- a/lib/common/fse_decompress.c
+++ b/lib/common/fse_decompress.c
@@ -22,8 +22,7 @@
 #define FSE_STATIC_LINKING_ONLY
 #include "fse.h"
 #include "error_private.h"
-#define ZSTD_DEPS_NEED_MALLOC
-#include "zstd_deps.h"
+#include "zstd_deps.h"  /* ZSTD_memcpy */
 #include "bits.h"       /* ZSTD_highbit32 */
 
 
@@ -236,7 +235,6 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
 
 typedef struct {
     short ncount[FSE_MAX_SYMBOL_VALUE + 1];
-    FSE_DTable dtable[1]; /* actual size is dynamic - member just helps get a pointer easily */
 } FSE_DecompressWksp;
 
 
@@ -251,11 +249,15 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_wksp_body(
     unsigned tableLog;
     unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
     FSE_DecompressWksp* const wksp = (FSE_DecompressWksp*)workSpace;
-    FSE_DTable* const dtable = wksp->dtable;
+    size_t const dtablePos = sizeof(FSE_DecompressWksp) / sizeof(FSE_DTable);
+    FSE_DTable* const dtable = (FSE_DTable*)workSpace + dtablePos;
 
-    DEBUG_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0);
+    FSE_STATIC_ASSERT((FSE_MAX_SYMBOL_VALUE + 1) % 2 == 0);
     if (wkspSize < sizeof(*wksp)) return ERROR(GENERIC);
 
+    /* correct offset to dtable depends on this property */
+    FSE_STATIC_ASSERT(sizeof(FSE_DecompressWksp) % sizeof(FSE_DTable) == 0);
+
     /* normal FSE decoding mode */
     {   size_t const NCountLength =
             FSE_readNCount_bmi2(wksp->ncount, &maxSymbolValue, &tableLog, istart, cSrcSize, bmi2);

From af971cec6572e156e26bc403cb42396e7d908ba1 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 23 Oct 2023 05:56:05 +0000
Subject: [PATCH 105/937] Bump actions/checkout from 4.1.0 to 4.1.1

Bumps [actions/checkout](https://github.com/actions/checkout) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/8ade135a41bc03ea155e62e844d188df1ea18608...b4ffde65f46336ab88eb53be808477a3936bae11)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml          | 50 ++++++-------
 .github/workflows/dev-short-tests.yml         | 74 +++++++++----------
 .../workflows/publish-release-artifacts.yml   |  2 +-
 .github/workflows/scorecards.yml              |  2 +-
 .github/workflows/windows-artifacts.yml       |  2 +-
 5 files changed, 65 insertions(+), 65 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 2f2793bcd..dbef98982 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -15,7 +15,7 @@ jobs:
   make-all:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: make all
       run: make all
 
@@ -26,7 +26,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: make test
       run: make test
 
@@ -34,7 +34,7 @@ jobs:
   make-test-osx:
     runs-on: macos-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: OS-X test
       run: make test # make -c lib all doesn't work because of the fact that it's not a tty
 
@@ -45,7 +45,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: make test
       run: |
         sudo apt-get -qqq update
@@ -55,21 +55,21 @@ jobs:
   no-intrinsics-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: no intrinsics fuzztest
       run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest
 
   tsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: thread sanitizer zstreamtest
       run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream
 
   ubsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: undefined behavior sanitizer zstreamtest
       run: CC=clang make uasan-test-zstream
 
@@ -77,7 +77,7 @@ jobs:
   tsan-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: thread sanitizer fuzztest
       run: CC=clang make tsan-fuzztest
 
@@ -85,7 +85,7 @@ jobs:
   big-tests-zstreamtest32:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: zstream tests in 32bit mode, with big tests
       run: |
         sudo apt-get -qqq update
@@ -96,7 +96,7 @@ jobs:
   gcc-8-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: gcc-8 + ASan + UBSan + Test Zstd
       # See https://askubuntu.com/a/1428822
       run: |
@@ -108,14 +108,14 @@ jobs:
   clang-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: clang + ASan + UBSan + Test Zstd
       run: CC=clang make -j uasan-test-zstd 
Date: Mon, 23 Oct 2023 17:38:09 +0200
Subject: [PATCH 106/937] Add target_include_directories because windows and
 macos need it for me

---
 build/cmake/README.md | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/build/cmake/README.md b/build/cmake/README.md
index 022e61688..4c9d3a08b 100644
--- a/build/cmake/README.md
+++ b/build/cmake/README.md
@@ -64,6 +64,13 @@ target_link_libraries(
     PRIVATE
     libzstd_static
 )
+
+# On windows and macos this is needed
+target_include_directories(
+    ${PROJECT_NAME}
+    PRIVATE
+    ${zstd_SOURCE_DIR}/lib
+)
 ```
 
 ### referring

From 9446b1910cab25dd2eb93d76ca5e6168a6e70a51 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 30 Oct 2023 05:53:19 +0000
Subject: [PATCH 107/937] Bump ossf/scorecard-action from 2.2.0 to 2.3.1

Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.2.0 to 2.3.1.
- [Release notes](https://github.com/ossf/scorecard-action/releases)
- [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md)
- [Commits](https://github.com/ossf/scorecard-action/compare/08b4669551908b1024bb425080c797723083c031...0864cf19026789058feabb7e87baa5f140aac736)

---
updated-dependencies:
- dependency-name: ossf/scorecard-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/scorecards.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index b536c54eb..f8f1f2d80 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -32,7 +32,7 @@ jobs:
           persist-credentials: false
 
       - name: "Run analysis"
-        uses: ossf/scorecard-action@08b4669551908b1024bb425080c797723083c031 # tag=v2.2.0
+        uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # tag=v2.3.1
         with:
           results_file: results.sarif
           results_format: sarif

From b38d87b476b804d7948928d298c784deb875a93c Mon Sep 17 00:00:00 2001
From: elasota 
Date: Tue, 31 Oct 2023 01:17:23 -0400
Subject: [PATCH 108/937] Clarify that the log2 of the largest possible symbol
 is the maximum number of bits consumed

---
 doc/zstd_compression_format.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index cd7308de1..7b29ccec6 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1083,7 +1083,7 @@ It depends on :
   Presuming an `Accuracy_Log` of 8,
   and presuming 100 probabilities points have already been distributed,
   the decoder may read any value from `0` to `256 - 100 + 1 == 157` (inclusive).
-  Therefore, it must read `log2sup(157) == 8` bits.
+  Therefore, it may read up to `log2sup(157) == 8` bits.
 
 - Value decoded : small values use 1 less bit :
   __example__ :

From 324cce4996d24af7b2cd86cf5eb1b9bd80de0a47 Mon Sep 17 00:00:00 2001
From: elasota 
Date: Tue, 31 Oct 2023 11:42:00 -0400
Subject: [PATCH 109/937] Add definition of "log2sup" function

---
 doc/zstd_compression_format.md | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 7b29ccec6..0532a846f 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1083,7 +1083,8 @@ It depends on :
   Presuming an `Accuracy_Log` of 8,
   and presuming 100 probabilities points have already been distributed,
   the decoder may read any value from `0` to `256 - 100 + 1 == 157` (inclusive).
-  Therefore, it may read up to `log2sup(157) == 8` bits.
+  Therefore, it may read up to `log2sup(157) == 8` bits, where `log2sup(N)`
+  is the smallest integer `T` that satisfies `(1 << T) > N`.
 
 - Value decoded : small values use 1 less bit :
   __example__ :

From 4502ca5f422a4e3f0b8980d5a365fcc3f62e97e0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Christoph=20Gr=C3=BCninger?= 
Date: Tue, 31 Oct 2023 23:30:43 +0100
Subject: [PATCH 110/937] [cmake] Require CMake version 3.5 or newer

More recent versions of CMake emit the following warning:
CMake Deprecation Warning at cmake/CMakeLists.txt:10 (cmake_minimum_required):
  Compatibility with CMake < 3.5 will be removed from a future version of
  CMake.

  Update the VERSION argument  value or use a ... suffix to tell
  CMake that the project does not need compatibility with older versions.
---
 build/cmake/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 0bffc87d9..7377d4550 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -7,7 +7,7 @@
 # in the COPYING file in the root directory of this source tree).
 # ################################################################
 
-cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR)
+cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
 
 # As of 2018-12-26 ZSTD has been validated to build with cmake version 3.13.2 new policies.
 # Set and use the newest cmake policies that are validated to work

From f013b1b504cc2065e8860cf90461cef9364d96b0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Christoph=20Gr=C3=BCninger?= 
Date: Wed, 1 Nov 2023 08:51:45 +0100
Subject: [PATCH 111/937] [cmake] Remove code for compatibility with CMake <
 3.0

The required version of CMake is now 3.5.
---
 build/cmake/CMakeLists.txt | 31 +++++++++----------------------
 1 file changed, 9 insertions(+), 22 deletions(-)

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 7377d4550..023b998f5 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -13,10 +13,8 @@ cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
 # Set and use the newest cmake policies that are validated to work
 set(ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION "3")
 set(ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION "13") #Policies never changed at PATCH level
-if("${CMAKE_MAJOR_VERSION}" LESS 3)
-  set(ZSTD_CMAKE_POLICY_VERSION "${CMAKE_VERSION}")
-elseif( "${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}" EQUAL "${CMAKE_MAJOR_VERSION}" AND
-        "${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}" GREATER "${CMAKE_MINOR_VERSION}")
+if("${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}" EQUAL "${CMAKE_MAJOR_VERSION}" AND
+       "${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}" GREATER "${CMAKE_MINOR_VERSION}")
     set(ZSTD_CMAKE_POLICY_VERSION "${CMAKE_VERSION}")
 else()
     set(ZSTD_CMAKE_POLICY_VERSION "${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}.${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}.0")
@@ -32,24 +30,13 @@ set(LIBRARY_DIR ${ZSTD_SOURCE_DIR}/lib)
 include(GetZstdLibraryVersion)
 GetZstdLibraryVersion(${LIBRARY_DIR}/zstd.h zstd_VERSION_MAJOR zstd_VERSION_MINOR zstd_VERSION_PATCH)
 
-if( CMAKE_MAJOR_VERSION LESS 3 )
-  ## Provide cmake 3+ behavior for older versions of cmake
-  project(zstd)
-  set(PROJECT_VERSION_MAJOR ${zstd_VERSION_MAJOR})
-  set(PROJECT_VERSION_MINOR ${zstd_VERSION_MINOR})
-  set(PROJECT_VERSION_PATCH ${zstd_VERSION_PATCH})
-  set(PROJECT_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}")
-  enable_language(C)   # Main library is in C
-  enable_language(ASM) # And ASM
-  enable_language(CXX) # Testing contributed code also utilizes CXX
-else()
-  project(zstd
-    VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}"
-    LANGUAGES C   # Main library is in C
-              ASM # And ASM
-              CXX # Testing contributed code also utilizes CXX
-    )
-endif()
+project(zstd
+  VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}"
+  LANGUAGES C   # Main library is in C
+            ASM # And ASM
+            CXX # Testing contributed code also utilizes CXX
+  )
+
 message(STATUS "ZSTD VERSION: ${zstd_VERSION}")
 set(zstd_HOMEPAGE_URL "https://facebook.github.io/zstd")
 set(zstd_DESCRIPTION  "Zstandard is a real-time compression algorithm, providing high compression ratios.")

From c53d650d9a047ab12b2c7e5808878aff37d3cfc5 Mon Sep 17 00:00:00 2001
From: Theodore Tsirpanis 
Date: Tue, 7 Nov 2023 14:35:43 +0200
Subject: [PATCH 112/937] Export a `zstd::libzstd` target if only static or
 dynamic linkage is specified.

---
 build/cmake/CMakeLists.txt      | 11 ++++++-----
 build/cmake/zstdConfig.cmake    |  1 -
 build/cmake/zstdConfig.cmake.in | 16 ++++++++++++++++
 3 files changed, 22 insertions(+), 6 deletions(-)
 delete mode 100644 build/cmake/zstdConfig.cmake
 create mode 100644 build/cmake/zstdConfig.cmake.in

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 0bffc87d9..6f68bc425 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -193,10 +193,6 @@ export(EXPORT zstdExports
     FILE "${CMAKE_CURRENT_BINARY_DIR}/zstdTargets.cmake"
     NAMESPACE zstd::
     )
-configure_file(zstdConfig.cmake
-    "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake"
-    COPYONLY
-    )
 
 # A Package Config file that works from the installation directory
 set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/zstd)
@@ -205,8 +201,13 @@ install(EXPORT zstdExports
     NAMESPACE zstd::
     DESTINATION ${ConfigPackageLocation}
     )
+configure_package_config_file(
+    zstdConfig.cmake.in
+    "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake"
+    INSTALL_DESTINATION ${ConfigPackageLocation}
+)
 install(FILES
-    zstdConfig.cmake
+    "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake"
     "${CMAKE_CURRENT_BINARY_DIR}/zstdConfigVersion.cmake"
     DESTINATION ${ConfigPackageLocation}
     )
diff --git a/build/cmake/zstdConfig.cmake b/build/cmake/zstdConfig.cmake
deleted file mode 100644
index ebbfcc38f..000000000
--- a/build/cmake/zstdConfig.cmake
+++ /dev/null
@@ -1 +0,0 @@
-include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets.cmake")
diff --git a/build/cmake/zstdConfig.cmake.in b/build/cmake/zstdConfig.cmake.in
new file mode 100644
index 000000000..752f3ab11
--- /dev/null
+++ b/build/cmake/zstdConfig.cmake.in
@@ -0,0 +1,16 @@
+@PACKAGE_INIT@
+
+include(CMakeFindDependencyMacro)
+if(@ZSTD_MULTITHREAD_SUPPORT@ AND "@UNIX@")
+  find_dependency(Threads)
+endif()
+
+include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets.cmake")
+
+if(@ZSTD_BUILD_SHARED@ AND NOT @ZSTD_BUILD_STATIC@)
+  add_library(zstd::libzstd ALIAS zstd::libzstd_shared)
+elseif(NOT @ZSTD_BUILD_SHARED@ AND @ZSTD_BUILD_STATIC@)
+  add_library(zstd::libzstd ALIAS zstd::libzstd_static)
+endif()
+
+check_required_components("zstd")

From 98d8ad27a2b2a2fc75e0594bae992824c470f61c Mon Sep 17 00:00:00 2001
From: John Hughes 
Date: Wed, 8 Nov 2023 09:08:21 +0000
Subject: [PATCH 113/937] Add Bazel module instructions to README.md

---
 README.md | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/README.md b/README.md
index 89857bf9b..0f7478e10 100644
--- a/README.md
+++ b/README.md
@@ -198,6 +198,10 @@ Going into `build` directory, you will find additional possibilities:
 You can build the zstd binary via buck by executing: `buck build programs:zstd` from the root of the repo.
 The output binary will be in `buck-out/gen/programs/`.
 
+### Bazel
+
+You easily can integrate zstd into your Bazel project by using the module hosted on the [Bazel Central Repository](https://registry.bazel.build/modules/zstd).
+
 ## Testing
 
 You can run quick local smoke tests by running `make check`.

From e61e3ff15208432cecf09ede09e8ebcf1d126bdd Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Wed, 8 Nov 2023 20:06:58 -0500
Subject: [PATCH 114/937] Clarify that decoding too many Huffman weights is a
 failure condition

---
 doc/zstd_compression_format.md | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 0532a846f..b64ddc3bf 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1353,6 +1353,9 @@ If updating state after decoding a symbol would require more bits than
 remain in the stream, it is assumed that extra bits are 0.  Then,
 symbols for each of the final states are decoded and the process is complete.
 
+If this process would produce more weights than the maximum number of decoded
+weights (255), then the data is considered corrupted.
+
 #### Conversion from weights to Huffman prefix codes
 
 All present symbols shall now have a `Weight` value.

From 52e41b9ac8010da90bbe97421cca533afd6914c0 Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Thu, 9 Nov 2023 12:22:27 -0500
Subject: [PATCH 115/937] Fix malformed state table

---
 doc/zstd_compression_format.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 0532a846f..b362b206d 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1187,9 +1187,9 @@ Baseline is assigned starting from the higher states using fewer bits,
 increasing at each state, then resuming at the first state,
 each state takes its allocated width from Baseline.
 
-| state value      |   1   |  39   |   77   |  84  |  122   |
 | state order      |   0   |   1   |    2   |   3  |    4   |
 | ---------------- | ----- | ----- | ------ | ---- | ------ |
+| state value      |   1   |  39   |   77   |  84  |  122   |
 | width            |  32   |  32   |   32   |  16  |   16   |
 | `Number_of_Bits` |   5   |   5   |    5   |   4  |    4   |
 | range number     |   2   |   4   |    6   |   0  |    1   |

From c5bf96fb74378aaefec44f30f67f88f3f70f8e4e Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Mon, 13 Nov 2023 00:03:56 -0500
Subject: [PATCH 116/937] Clarify that a non-zero probability for an invalid
 symbol is invalid

---
 doc/zstd_compression_format.md | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 0532a846f..216d89ed1 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1124,6 +1124,9 @@ When last symbol reaches cumulated total of `1 << Accuracy_Log`,
 decoding is complete.
 If the last symbol makes cumulated total go above `1 << Accuracy_Log`,
 distribution is considered corrupted.
+If this process results in a non-zero probability for a value outside of the
+valid range of values that the FSE table is defined for, even if that value is
+not used, then the data is considered corrupted.
 
 Then the decoder can tell how many bytes were used in this process,
 and how many symbols are present.

From 592b1acb1804f18e42412607a81c636dc1d4e850 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 13 Nov 2023 15:42:07 -0800
Subject: [PATCH 117/937] update xxhash to v0.8.2

List of updates : https://github.com/Cyan4973/xxHash/releases/tag/v0.8.2

This is also a preparation task before taking care of #3819
---
 lib/common/xxhash.c |   41 +-
 lib/common/xxhash.h | 3358 ++++++++++++++++++++++++++++++-------------
 2 files changed, 2395 insertions(+), 1004 deletions(-)

diff --git a/lib/common/xxhash.c b/lib/common/xxhash.c
index fd237c906..1a8f735ba 100644
--- a/lib/common/xxhash.c
+++ b/lib/common/xxhash.c
@@ -1,17 +1,36 @@
 /*
- *  xxHash - Fast Hash algorithm
- *  Copyright (c) Meta Platforms, Inc. and affiliates.
+ * xxHash - Extremely Fast Hash algorithm
+ * Copyright (C) 2012-2023 Yann Collet
  *
- *  You can contact the author at :
- *  - xxHash homepage: https://cyan4973.github.io/xxHash/
- *  - xxHash source repository : https://github.com/Cyan4973/xxHash
+ * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
  *
- * 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.
-*/
-
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following disclaimer
+ *      in the documentation and/or other materials provided with the
+ *      distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * You can contact the author at:
+ *   - xxHash homepage: https://www.xxhash.com
+ *   - xxHash source repository: https://github.com/Cyan4973/xxHash
+ */
 
 
 /*
diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 69572117a..fe3abc1b4 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -1,17 +1,39 @@
 /*
- *  xxHash - Fast Hash algorithm
- *  Copyright (c) Meta Platforms, Inc. and affiliates.
+ * xxHash - Extremely Fast Hash algorithm
+ * Header File
+ * Copyright (C) 2012-2023 Yann Collet
  *
- *  You can contact the author at :
- *  - xxHash homepage: https://cyan4973.github.io/xxHash/
- *  - xxHash source repository : https://github.com/Cyan4973/xxHash
+ * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
  *
- * 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.
-*/
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *    * Redistributions of source code must retain the above copyright
+ *      notice, this list of conditions and the following disclaimer.
+ *    * Redistributions in binary form must reproduce the above
+ *      copyright notice, this list of conditions and the following disclaimer
+ *      in the documentation and/or other materials provided with the
+ *      distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * You can contact the author at:
+ *   - xxHash homepage: https://www.xxhash.com
+ *   - xxHash source repository: https://github.com/Cyan4973/xxHash
+ */
 
+/* Local adaptations for Zstandard */
 
 #ifndef XXH_NO_XXH3
 # define XXH_NO_XXH3
@@ -24,46 +46,210 @@
 /*!
  * @mainpage xxHash
  *
+ * xxHash is an extremely fast non-cryptographic hash algorithm, working at RAM speed
+ * limits.
+ *
+ * It is proposed in four flavors, in three families:
+ * 1. @ref XXH32_family
+ *   - Classic 32-bit hash function. Simple, compact, and runs on almost all
+ *     32-bit and 64-bit systems.
+ * 2. @ref XXH64_family
+ *   - Classic 64-bit adaptation of XXH32. Just as simple, and runs well on most
+ *     64-bit systems (but _not_ 32-bit systems).
+ * 3. @ref XXH3_family
+ *   - Modern 64-bit and 128-bit hash function family which features improved
+ *     strength and performance across the board, especially on smaller data.
+ *     It benefits greatly from SIMD and 64-bit without requiring it.
+ *
+ * Benchmarks
+ * ---
+ * The reference system uses an Intel i7-9700K CPU, and runs Ubuntu x64 20.04.
+ * The open source benchmark program is compiled with clang v10.0 using -O3 flag.
+ *
+ * | Hash Name            | ISA ext | Width | Large Data Speed | Small Data Velocity |
+ * | -------------------- | ------- | ----: | ---------------: | ------------------: |
+ * | XXH3_64bits()        | @b AVX2 |    64 |        59.4 GB/s |               133.1 |
+ * | MeowHash             | AES-NI  |   128 |        58.2 GB/s |                52.5 |
+ * | XXH3_128bits()       | @b AVX2 |   128 |        57.9 GB/s |               118.1 |
+ * | CLHash               | PCLMUL  |    64 |        37.1 GB/s |                58.1 |
+ * | XXH3_64bits()        | @b SSE2 |    64 |        31.5 GB/s |               133.1 |
+ * | XXH3_128bits()       | @b SSE2 |   128 |        29.6 GB/s |               118.1 |
+ * | RAM sequential read  |         |   N/A |        28.0 GB/s |                 N/A |
+ * | ahash                | AES-NI  |    64 |        22.5 GB/s |               107.2 |
+ * | City64               |         |    64 |        22.0 GB/s |                76.6 |
+ * | T1ha2                |         |    64 |        22.0 GB/s |                99.0 |
+ * | City128              |         |   128 |        21.7 GB/s |                57.7 |
+ * | FarmHash             | AES-NI  |    64 |        21.3 GB/s |                71.9 |
+ * | XXH64()              |         |    64 |        19.4 GB/s |                71.0 |
+ * | SpookyHash           |         |    64 |        19.3 GB/s |                53.2 |
+ * | Mum                  |         |    64 |        18.0 GB/s |                67.0 |
+ * | CRC32C               | SSE4.2  |    32 |        13.0 GB/s |                57.9 |
+ * | XXH32()              |         |    32 |         9.7 GB/s |                71.9 |
+ * | City32               |         |    32 |         9.1 GB/s |                66.0 |
+ * | Blake3*              | @b AVX2 |   256 |         4.4 GB/s |                 8.1 |
+ * | Murmur3              |         |    32 |         3.9 GB/s |                56.1 |
+ * | SipHash*             |         |    64 |         3.0 GB/s |                43.2 |
+ * | Blake3*              | @b SSE2 |   256 |         2.4 GB/s |                 8.1 |
+ * | HighwayHash          |         |    64 |         1.4 GB/s |                 6.0 |
+ * | FNV64                |         |    64 |         1.2 GB/s |                62.7 |
+ * | Blake2*              |         |   256 |         1.1 GB/s |                 5.1 |
+ * | SHA1*                |         |   160 |         0.8 GB/s |                 5.6 |
+ * | MD5*                 |         |   128 |         0.6 GB/s |                 7.8 |
+ * @note
+ *   - Hashes which require a specific ISA extension are noted. SSE2 is also noted,
+ *     even though it is mandatory on x64.
+ *   - Hashes with an asterisk are cryptographic. Note that MD5 is non-cryptographic
+ *     by modern standards.
+ *   - Small data velocity is a rough average of algorithm's efficiency for small
+ *     data. For more accurate information, see the wiki.
+ *   - More benchmarks and strength tests are found on the wiki:
+ *         https://github.com/Cyan4973/xxHash/wiki
+ *
+ * Usage
+ * ------
+ * All xxHash variants use a similar API. Changing the algorithm is a trivial
+ * substitution.
+ *
+ * @pre
+ *    For functions which take an input and length parameter, the following
+ *    requirements are assumed:
+ *    - The range from [`input`, `input + length`) is valid, readable memory.
+ *      - The only exception is if the `length` is `0`, `input` may be `NULL`.
+ *    - For C++, the objects must have the *TriviallyCopyable* property, as the
+ *      functions access bytes directly as if it was an array of `unsigned char`.
+ *
+ * @anchor single_shot_example
+ * **Single Shot**
+ *
+ * These functions are stateless functions which hash a contiguous block of memory,
+ * immediately returning the result. They are the easiest and usually the fastest
+ * option.
+ *
+ * XXH32(), XXH64(), XXH3_64bits(), XXH3_128bits()
+ *
+ * @code{.c}
+ *   #include 
+ *   #include "xxhash.h"
+ *
+ *   // Example for a function which hashes a null terminated string with XXH32().
+ *   XXH32_hash_t hash_string(const char* string, XXH32_hash_t seed)
+ *   {
+ *       // NULL pointers are only valid if the length is zero
+ *       size_t length = (string == NULL) ? 0 : strlen(string);
+ *       return XXH32(string, length, seed);
+ *   }
+ * @endcode
+ *
+ *
+ * @anchor streaming_example
+ * **Streaming**
+ *
+ * These groups of functions allow incremental hashing of unknown size, even
+ * more than what would fit in a size_t.
+ *
+ * XXH32_reset(), XXH64_reset(), XXH3_64bits_reset(), XXH3_128bits_reset()
+ *
+ * @code{.c}
+ *   #include 
+ *   #include 
+ *   #include "xxhash.h"
+ *   // Example for a function which hashes a FILE incrementally with XXH3_64bits().
+ *   XXH64_hash_t hashFile(FILE* f)
+ *   {
+ *       // Allocate a state struct. Do not just use malloc() or new.
+ *       XXH3_state_t* state = XXH3_createState();
+ *       assert(state != NULL && "Out of memory!");
+ *       // Reset the state to start a new hashing session.
+ *       XXH3_64bits_reset(state);
+ *       char buffer[4096];
+ *       size_t count;
+ *       // Read the file in chunks
+ *       while ((count = fread(buffer, 1, sizeof(buffer), f)) != 0) {
+ *           // Run update() as many times as necessary to process the data
+ *           XXH3_64bits_update(state, buffer, count);
+ *       }
+ *       // Retrieve the finalized hash. This will not change the state.
+ *       XXH64_hash_t result = XXH3_64bits_digest(state);
+ *       // Free the state. Do not use free().
+ *       XXH3_freeState(state);
+ *       return result;
+ *   }
+ * @endcode
+ *
+ * Streaming functions generate the xxHash value from an incremental input.
+ * This method is slower than single-call functions, due to state management.
+ * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.
+ *
+ * An XXH state must first be allocated using `XXH*_createState()`.
+ *
+ * Start a new hash by initializing the state with a seed using `XXH*_reset()`.
+ *
+ * Then, feed the hash state by calling `XXH*_update()` as many times as necessary.
+ *
+ * The function returns an error code, with 0 meaning OK, and any other value
+ * meaning there is an error.
+ *
+ * Finally, a hash value can be produced anytime, by using `XXH*_digest()`.
+ * This function returns the nn-bits hash as an int or long long.
+ *
+ * It's still possible to continue inserting input into the hash state after a
+ * digest, and generate new hash values later on by invoking `XXH*_digest()`.
+ *
+ * When done, release the state using `XXH*_freeState()`.
+ *
+ *
+ * @anchor canonical_representation_example
+ * **Canonical Representation**
+ *
+ * The default return values from XXH functions are unsigned 32, 64 and 128 bit
+ * integers.
+ * This the simplest and fastest format for further post-processing.
+ *
+ * However, this leaves open the question of what is the order on the byte level,
+ * since little and big endian conventions will store the same number differently.
+ *
+ * The canonical representation settles this issue by mandating big-endian
+ * convention, the same convention as human-readable numbers (large digits first).
+ *
+ * When writing hash values to storage, sending them over a network, or printing
+ * them, it's highly recommended to use the canonical representation to ensure
+ * portability across a wider range of systems, present and future.
+ *
+ * The following functions allow transformation of hash values to and from
+ * canonical format.
+ *
+ * XXH32_canonicalFromHash(), XXH32_hashFromCanonical(),
+ * XXH64_canonicalFromHash(), XXH64_hashFromCanonical(),
+ * XXH128_canonicalFromHash(), XXH128_hashFromCanonical(),
+ *
+ * @code{.c}
+ *   #include 
+ *   #include "xxhash.h"
+ *
+ *   // Example for a function which prints XXH32_hash_t in human readable format
+ *   void printXxh32(XXH32_hash_t hash)
+ *   {
+ *       XXH32_canonical_t cano;
+ *       XXH32_canonicalFromHash(&cano, hash);
+ *       size_t i;
+ *       for(i = 0; i < sizeof(cano.digest); ++i) {
+ *           printf("%02x", cano.digest[i]);
+ *       }
+ *       printf("\n");
+ *   }
+ *
+ *   // Example for a function which converts XXH32_canonical_t to XXH32_hash_t
+ *   XXH32_hash_t convertCanonicalToXxh32(XXH32_canonical_t cano)
+ *   {
+ *       XXH32_hash_t hash = XXH32_hashFromCanonical(&cano);
+ *       return hash;
+ *   }
+ * @endcode
+ *
+ *
  * @file xxhash.h
  * xxHash prototypes and implementation
  */
-/* TODO: update */
-/* Notice extracted from xxHash homepage:
-
-xxHash is an extremely fast hash algorithm, running at RAM speed limits.
-It also successfully passes all tests from the SMHasher suite.
-
-Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)
-
-Name            Speed       Q.Score   Author
-xxHash          5.4 GB/s     10
-CrapWow         3.2 GB/s      2       Andrew
-MurmurHash 3a   2.7 GB/s     10       Austin Appleby
-SpookyHash      2.0 GB/s     10       Bob Jenkins
-SBox            1.4 GB/s      9       Bret Mulvey
-Lookup3         1.2 GB/s      9       Bob Jenkins
-SuperFastHash   1.2 GB/s      1       Paul Hsieh
-CityHash64      1.05 GB/s    10       Pike & Alakuijala
-FNV             0.55 GB/s     5       Fowler, Noll, Vo
-CRC32           0.43 GB/s     9
-MD5-32          0.33 GB/s    10       Ronald L. Rivest
-SHA1-32         0.28 GB/s    10
-
-Q.Score is a measure of quality of the hash function.
-It depends on successfully passing SMHasher test set.
-10 is a perfect score.
-
-Note: SMHasher's CRC32 implementation is not the fastest one.
-Other speed-oriented implementations can be faster,
-especially in combination with PCLMUL instruction:
-https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html?showComment=1552696407071#c3490092340461170735
-
-A 64-bit version, named XXH64, is available since r35.
-It offers much better speed, but for 64-bit applications only.
-Name     Speed on 64 bits    Speed on 32 bits
-XXH64       13.8 GB/s            1.9 GB/s
-XXH32        6.8 GB/s            6.0 GB/s
-*/
 
 #if defined (__cplusplus)
 extern "C" {
@@ -73,21 +259,80 @@ extern "C" {
  *  INLINE mode
  ******************************/
 /*!
- * XXH_INLINE_ALL (and XXH_PRIVATE_API)
+ * @defgroup public Public API
+ * Contains details on the public xxHash functions.
+ * @{
+ */
+#ifdef XXH_DOXYGEN
+/*!
+ * @brief Gives access to internal state declaration, required for static allocation.
+ *
+ * Incompatible with dynamic linking, due to risks of ABI changes.
+ *
+ * Usage:
+ * @code{.c}
+ *     #define XXH_STATIC_LINKING_ONLY
+ *     #include "xxhash.h"
+ * @endcode
+ */
+#  define XXH_STATIC_LINKING_ONLY
+/* Do not undef XXH_STATIC_LINKING_ONLY for Doxygen */
+
+/*!
+ * @brief Gives access to internal definitions.
+ *
+ * Usage:
+ * @code{.c}
+ *     #define XXH_STATIC_LINKING_ONLY
+ *     #define XXH_IMPLEMENTATION
+ *     #include "xxhash.h"
+ * @endcode
+ */
+#  define XXH_IMPLEMENTATION
+/* Do not undef XXH_IMPLEMENTATION for Doxygen */
+
+/*!
+ * @brief Exposes the implementation and marks all functions as `inline`.
+ *
  * Use these build macros to inline xxhash into the target unit.
  * Inlining improves performance on small inputs, especially when the length is
  * expressed as a compile-time constant:
  *
- *      https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html
+ *  https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html
  *
  * It also keeps xxHash symbols private to the unit, so they are not exported.
  *
  * Usage:
+ * @code{.c}
  *     #define XXH_INLINE_ALL
  *     #include "xxhash.h"
- *
+ * @endcode
  * Do not compile and link xxhash.o as a separate object, as it is not useful.
  */
+#  define XXH_INLINE_ALL
+#  undef XXH_INLINE_ALL
+/*!
+ * @brief Exposes the implementation without marking functions as inline.
+ */
+#  define XXH_PRIVATE_API
+#  undef XXH_PRIVATE_API
+/*!
+ * @brief Emulate a namespace by transparently prefixing all symbols.
+ *
+ * If you want to include _and expose_ xxHash functions from within your own
+ * library, but also want to avoid symbol collisions with other libraries which
+ * may also include xxHash, you can use @ref XXH_NAMESPACE to automatically prefix
+ * any public symbol from xxhash library with the value of @ref XXH_NAMESPACE
+ * (therefore, avoid empty or numeric values).
+ *
+ * Note that no change is required within the calling program as long as it
+ * includes `xxhash.h`: Regular symbol names will be automatically translated
+ * by this header.
+ */
+#  define XXH_NAMESPACE /* YOUR NAME HERE */
+#  undef XXH_NAMESPACE
+#endif
+
 #if (defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)) \
     && !defined(XXH_INLINE_ALL_31684351384)
    /* this section should be traversed only once */
@@ -202,21 +447,13 @@ extern "C" {
 #  undef XXHASH_H_STATIC_13879238742
 #endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */
 
-
-
 /* ****************************************************************
  *  Stable API
  *****************************************************************/
 #ifndef XXHASH_H_5627135585666179
 #define XXHASH_H_5627135585666179 1
 
-
-/*!
- * @defgroup public Public API
- * Contains details on the public xxHash functions.
- * @{
- */
-/* specific declaration modes for Windows */
+/*! @brief Marks a global symbol. */
 #if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API)
 #  if defined(WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT))
 #    ifdef XXH_EXPORT
@@ -229,24 +466,6 @@ extern "C" {
 #  endif
 #endif
 
-#ifdef XXH_DOXYGEN
-/*!
- * @brief Emulate a namespace by transparently prefixing all symbols.
- *
- * If you want to include _and expose_ xxHash functions from within your own
- * library, but also want to avoid symbol collisions with other libraries which
- * may also include xxHash, you can use XXH_NAMESPACE to automatically prefix
- * any public symbol from xxhash library with the value of XXH_NAMESPACE
- * (therefore, avoid empty or numeric values).
- *
- * Note that no change is required within the calling program as long as it
- * includes `xxhash.h`: Regular symbol names will be automatically translated
- * by this header.
- */
-#  define XXH_NAMESPACE /* YOUR NAME HERE */
-#  undef XXH_NAMESPACE
-#endif
-
 #ifdef XXH_NAMESPACE
 #  define XXH_CAT(A,B) A##B
 #  define XXH_NAME2(A,B) XXH_CAT(A,B)
@@ -306,12 +525,40 @@ extern "C" {
 #endif
 
 
+/* *************************************
+*  Compiler specifics
+***************************************/
+
+/* specific declaration modes for Windows */
+#if !defined(XXH_INLINE_ALL) && !defined(XXH_PRIVATE_API)
+#  if defined(WIN32) && defined(_MSC_VER) && (defined(XXH_IMPORT) || defined(XXH_EXPORT))
+#    ifdef XXH_EXPORT
+#      define XXH_PUBLIC_API __declspec(dllexport)
+#    elif XXH_IMPORT
+#      define XXH_PUBLIC_API __declspec(dllimport)
+#    endif
+#  else
+#    define XXH_PUBLIC_API   /* do nothing */
+#  endif
+#endif
+
+#if defined (__GNUC__)
+# define XXH_CONSTF  __attribute__((const))
+# define XXH_PUREF   __attribute__((pure))
+# define XXH_MALLOCF __attribute__((malloc))
+#else
+# define XXH_CONSTF  /* disable */
+# define XXH_PUREF
+# define XXH_MALLOCF
+#endif
+
 /* *************************************
 *  Version
 ***************************************/
 #define XXH_VERSION_MAJOR    0
 #define XXH_VERSION_MINOR    8
-#define XXH_VERSION_RELEASE  1
+#define XXH_VERSION_RELEASE  2
+/*! @brief Version number, encoded as two digits each */
 #define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
 
 /*!
@@ -320,16 +567,22 @@ extern "C" {
  * This is mostly useful when xxHash is compiled as a shared library,
  * since the returned value comes from the library, as opposed to header file.
  *
- * @return `XXH_VERSION_NUMBER` of the invoked library.
+ * @return @ref XXH_VERSION_NUMBER of the invoked library.
  */
-XXH_PUBLIC_API unsigned XXH_versionNumber (void);
+XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void);
 
 
 /* ****************************
 *  Common basic types
 ******************************/
 #include    /* size_t */
-typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;
+/*!
+ * @brief Exit code for the streaming API.
+ */
+typedef enum {
+    XXH_OK = 0, /*!< OK */
+    XXH_ERROR   /*!< Error */
+} XXH_errorcode;
 
 
 /*-**********************************************************************
@@ -353,37 +606,33 @@ typedef uint32_t XXH32_hash_t;
 #   include 
 #   if UINT_MAX == 0xFFFFFFFFUL
       typedef unsigned int XXH32_hash_t;
+#   elif ULONG_MAX == 0xFFFFFFFFUL
+      typedef unsigned long XXH32_hash_t;
 #   else
-#     if ULONG_MAX == 0xFFFFFFFFUL
-        typedef unsigned long XXH32_hash_t;
-#     else
-#       error "unsupported platform: need a 32-bit type"
-#     endif
+#     error "unsupported platform: need a 32-bit type"
 #   endif
 #endif
 
 /*!
  * @}
  *
- * @defgroup xxh32_family XXH32 family
+ * @defgroup XXH32_family XXH32 family
  * @ingroup public
  * Contains functions used in the classic 32-bit xxHash algorithm.
  *
  * @note
  *   XXH32 is useful for older platforms, with no or poor 64-bit performance.
- *   Note that @ref xxh3_family provides competitive speed
- *   for both 32-bit and 64-bit systems, and offers true 64/128 bit hash results.
+ *   Note that the @ref XXH3_family provides competitive speed for both 32-bit
+ *   and 64-bit systems, and offers true 64/128 bit hash results.
  *
- * @see @ref xxh64_family, @ref xxh3_family : Other xxHash families
- * @see @ref xxh32_impl for implementation details
+ * @see @ref XXH64_family, @ref XXH3_family : Other xxHash families
+ * @see @ref XXH32_impl for implementation details
  * @{
  */
 
 /*!
  * @brief Calculates the 32-bit hash of @p input using xxHash32.
  *
- * Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark): 5.4 GB/s
- *
  * @param input The block of data to be hashed, at least @p length bytes in size.
  * @param length The length of @p input, in bytes.
  * @param seed The 32-bit seed to alter the hash's output predictably.
@@ -393,87 +642,44 @@ typedef uint32_t XXH32_hash_t;
  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
  *
- * @return The calculated 32-bit hash value.
+ * @return The calculated 32-bit xxHash32 value.
  *
- * @see
- *    XXH64(), XXH3_64bits_withSeed(), XXH3_128bits_withSeed(), XXH128():
- *    Direct equivalents for the other variants of xxHash.
- * @see
- *    XXH32_createState(), XXH32_update(), XXH32_digest(): Streaming version.
- */
-XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, XXH32_hash_t seed);
-
-/*!
- * Streaming functions generate the xxHash value from an incremental input.
- * This method is slower than single-call functions, due to state management.
- * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.
- *
- * An XXH state must first be allocated using `XXH*_createState()`.
- *
- * Start a new hash by initializing the state with a seed using `XXH*_reset()`.
- *
- * Then, feed the hash state by calling `XXH*_update()` as many times as necessary.
- *
- * The function returns an error code, with 0 meaning OK, and any other value
- * meaning there is an error.
- *
- * Finally, a hash value can be produced anytime, by using `XXH*_digest()`.
- * This function returns the nn-bits hash as an int or long long.
- *
- * It's still possible to continue inserting input into the hash state after a
- * digest, and generate new hash values later on by invoking `XXH*_digest()`.
- *
- * When done, release the state using `XXH*_freeState()`.
- *
- * Example code for incrementally hashing a file:
- * @code{.c}
- *    #include 
- *    #include 
- *    #define BUFFER_SIZE 256
- *
- *    // Note: XXH64 and XXH3 use the same interface.
- *    XXH32_hash_t
- *    hashFile(FILE* stream)
- *    {
- *        XXH32_state_t* state;
- *        unsigned char buf[BUFFER_SIZE];
- *        size_t amt;
- *        XXH32_hash_t hash;
- *
- *        state = XXH32_createState();       // Create a state
- *        assert(state != NULL);             // Error check here
- *        XXH32_reset(state, 0xbaad5eed);    // Reset state with our seed
- *        while ((amt = fread(buf, 1, sizeof(buf), stream)) != 0) {
- *            XXH32_update(state, buf, amt); // Hash the file in chunks
- *        }
- *        hash = XXH32_digest(state);        // Finalize the hash
- *        XXH32_freeState(state);            // Clean up
- *        return hash;
- *    }
- * @endcode
+ * @see @ref single_shot_example "Single Shot Example" for an example.
  */
+XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32 (const void* input, size_t length, XXH32_hash_t seed);
 
+#ifndef XXH_NO_STREAM
 /*!
  * @typedef struct XXH32_state_s XXH32_state_t
  * @brief The opaque state struct for the XXH32 streaming API.
  *
  * @see XXH32_state_s for details.
+ * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH32_state_s XXH32_state_t;
 
 /*!
  * @brief Allocates an @ref XXH32_state_t.
  *
- * Must be freed with XXH32_freeState().
- * @return An allocated XXH32_state_t on success, `NULL` on failure.
+ * @return An allocated pointer of @ref XXH32_state_t on success.
+ * @return `NULL` on failure.
+ *
+ * @note Must be freed with XXH32_freeState().
+ *
+ * @see @ref streaming_example "Streaming Example"
  */
-XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void);
+XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t* XXH32_createState(void);
 /*!
  * @brief Frees an @ref XXH32_state_t.
  *
- * Must be allocated with XXH32_createState().
  * @param statePtr A pointer to an @ref XXH32_state_t allocated with @ref XXH32_createState().
- * @return XXH_OK.
+ *
+ * @return @ref XXH_OK.
+ *
+ * @note @p statePtr must be allocated with XXH32_createState().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ *
  */
 XXH_PUBLIC_API XXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);
 /*!
@@ -489,23 +695,24 @@ XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_
 /*!
  * @brief Resets an @ref XXH32_state_t to begin a new hash.
  *
- * This function resets and seeds a state. Call it before @ref XXH32_update().
- *
  * @param statePtr The state struct to reset.
  * @param seed The 32-bit seed to alter the hash result predictably.
  *
  * @pre
  *   @p statePtr must not be `NULL`.
  *
- * @return @ref XXH_OK on success, @ref XXH_ERROR on failure.
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note This function resets and seeds a state. Call it before @ref XXH32_update().
+ *
+ * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, XXH32_hash_t seed);
 
 /*!
  * @brief Consumes a block of @p input to an @ref XXH32_state_t.
  *
- * Call this to incrementally consume blocks of data.
- *
  * @param statePtr The state struct to update.
  * @param input The block of data to be hashed, at least @p length bytes in size.
  * @param length The length of @p input, in bytes.
@@ -517,47 +724,36 @@ XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, XXH32_hash_t
  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
  *
- * @return @ref XXH_OK on success, @ref XXH_ERROR on failure.
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note Call this to incrementally consume blocks of data.
+ *
+ * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
 
 /*!
  * @brief Returns the calculated hash value from an @ref XXH32_state_t.
  *
- * @note
- *   Calling XXH32_digest() will not affect @p statePtr, so you can update,
- *   digest, and update again.
- *
  * @param statePtr The state struct to calculate the hash from.
  *
  * @pre
  *  @p statePtr must not be `NULL`.
  *
- * @return The calculated xxHash32 value from that state.
+ * @return The calculated 32-bit xxHash32 value from that state.
+ *
+ * @note
+ *   Calling XXH32_digest() will not affect @p statePtr, so you can update,
+ *   digest, and update again.
+ *
+ * @see @ref streaming_example "Streaming Example"
  */
-XXH_PUBLIC_API XXH32_hash_t  XXH32_digest (const XXH32_state_t* statePtr);
+XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr);
+#endif /* !XXH_NO_STREAM */
 
 /*******   Canonical representation   *******/
 
-/*
- * The default return values from XXH functions are unsigned 32 and 64 bit
- * integers.
- * This the simplest and fastest format for further post-processing.
- *
- * However, this leaves open the question of what is the order on the byte level,
- * since little and big endian conventions will store the same number differently.
- *
- * The canonical representation settles this issue by mandating big-endian
- * convention, the same convention as human-readable numbers (large digits first).
- *
- * When writing hash values to storage, sending them over a network, or printing
- * them, it's highly recommended to use the canonical representation to ensure
- * portability across a wider range of systems, present and future.
- *
- * The following functions allow transformation of hash values to and from
- * canonical format.
- */
-
 /*!
  * @brief Canonical (big endian) representation of @ref XXH32_hash_t.
  */
@@ -568,11 +764,13 @@ typedef struct {
 /*!
  * @brief Converts an @ref XXH32_hash_t to a big endian @ref XXH32_canonical_t.
  *
- * @param dst The @ref XXH32_canonical_t pointer to be stored to.
+ * @param dst  The @ref XXH32_canonical_t pointer to be stored to.
  * @param hash The @ref XXH32_hash_t to be converted.
  *
  * @pre
  *   @p dst must not be `NULL`.
+ *
+ * @see @ref canonical_representation_example "Canonical Representation Example"
  */
 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash);
 
@@ -585,44 +783,75 @@ XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t
  *   @p src must not be `NULL`.
  *
  * @return The converted hash.
+ *
+ * @see @ref canonical_representation_example "Canonical Representation Example"
  */
-XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);
+XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);
 
 
+/*! @cond Doxygen ignores this part */
 #ifdef __has_attribute
 # define XXH_HAS_ATTRIBUTE(x) __has_attribute(x)
 #else
 # define XXH_HAS_ATTRIBUTE(x) 0
 #endif
+/*! @endcond */
 
+/*! @cond Doxygen ignores this part */
+/*
+ * C23 __STDC_VERSION__ number hasn't been specified yet. For now
+ * leave as `201711L` (C17 + 1).
+ * TODO: Update to correct value when its been specified.
+ */
+#define XXH_C23_VN 201711L
+/*! @endcond */
+
+/*! @cond Doxygen ignores this part */
 /* C-language Attributes are added in C23. */
-#if defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201710L) && defined(__has_c_attribute)
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= XXH_C23_VN) && defined(__has_c_attribute)
 # define XXH_HAS_C_ATTRIBUTE(x) __has_c_attribute(x)
 #else
 # define XXH_HAS_C_ATTRIBUTE(x) 0
 #endif
+/*! @endcond */
 
+/*! @cond Doxygen ignores this part */
 #if defined(__cplusplus) && defined(__has_cpp_attribute)
 # define XXH_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
 #else
 # define XXH_HAS_CPP_ATTRIBUTE(x) 0
 #endif
+/*! @endcond */
 
+/*! @cond Doxygen ignores this part */
 /*
-Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute
-introduced in CPP17 and C23.
-CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough
-C23   : https://en.cppreference.com/w/c/language/attributes/fallthrough
-*/
-#if XXH_HAS_C_ATTRIBUTE(x)
-# define XXH_FALLTHROUGH [[fallthrough]]
-#elif XXH_HAS_CPP_ATTRIBUTE(x)
+ * Define XXH_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute
+ * introduced in CPP17 and C23.
+ * CPP17 : https://en.cppreference.com/w/cpp/language/attributes/fallthrough
+ * C23   : https://en.cppreference.com/w/c/language/attributes/fallthrough
+ */
+#if XXH_HAS_C_ATTRIBUTE(fallthrough) || XXH_HAS_CPP_ATTRIBUTE(fallthrough)
 # define XXH_FALLTHROUGH [[fallthrough]]
 #elif XXH_HAS_ATTRIBUTE(__fallthrough__)
-# define XXH_FALLTHROUGH __attribute__ ((fallthrough))
+# define XXH_FALLTHROUGH __attribute__ ((__fallthrough__))
 #else
-# define XXH_FALLTHROUGH
+# define XXH_FALLTHROUGH /* fallthrough */
 #endif
+/*! @endcond */
+
+/*! @cond Doxygen ignores this part */
+/*
+ * Define XXH_NOESCAPE for annotated pointers in public API.
+ * https://clang.llvm.org/docs/AttributeReference.html#noescape
+ * As of writing this, only supported by clang.
+ */
+#if XXH_HAS_ATTRIBUTE(noescape)
+# define XXH_NOESCAPE __attribute__((noescape))
+#else
+# define XXH_NOESCAPE
+#endif
+/*! @endcond */
+
 
 /*!
  * @}
@@ -660,7 +889,7 @@ typedef uint64_t XXH64_hash_t;
 /*!
  * @}
  *
- * @defgroup xxh64_family XXH64 family
+ * @defgroup XXH64_family XXH64 family
  * @ingroup public
  * @{
  * Contains functions used in the classic 64-bit xxHash algorithm.
@@ -671,13 +900,9 @@ typedef uint64_t XXH64_hash_t;
  *   It provides better speed for systems with vector processing capabilities.
  */
 
-
 /*!
  * @brief Calculates the 64-bit hash of @p input using xxHash64.
  *
- * This function usually runs faster on 64-bit systems, but slower on 32-bit
- * systems (see benchmark).
- *
  * @param input The block of data to be hashed, at least @p length bytes in size.
  * @param length The length of @p input, in bytes.
  * @param seed The 64-bit seed to alter the hash's output predictably.
@@ -687,41 +912,156 @@ typedef uint64_t XXH64_hash_t;
  *   readable, contiguous memory. However, if @p length is `0`, @p input may be
  *   `NULL`. In C++, this also must be *TriviallyCopyable*.
  *
- * @return The calculated 64-bit hash.
+ * @return The calculated 64-bit xxHash64 value.
  *
- * @see
- *    XXH32(), XXH3_64bits_withSeed(), XXH3_128bits_withSeed(), XXH128():
- *    Direct equivalents for the other variants of xxHash.
- * @see
- *    XXH64_createState(), XXH64_update(), XXH64_digest(): Streaming version.
+ * @see @ref single_shot_example "Single Shot Example" for an example.
  */
-XXH_PUBLIC_API XXH64_hash_t XXH64(const void* input, size_t length, XXH64_hash_t seed);
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed);
 
 /*******   Streaming   *******/
+#ifndef XXH_NO_STREAM
 /*!
  * @brief The opaque state struct for the XXH64 streaming API.
  *
  * @see XXH64_state_s for details.
+ * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */
-XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void);
+
+/*!
+ * @brief Allocates an @ref XXH64_state_t.
+ *
+ * @return An allocated pointer of @ref XXH64_state_t on success.
+ * @return `NULL` on failure.
+ *
+ * @note Must be freed with XXH64_freeState().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t* XXH64_createState(void);
+
+/*!
+ * @brief Frees an @ref XXH64_state_t.
+ *
+ * @param statePtr A pointer to an @ref XXH64_state_t allocated with @ref XXH64_createState().
+ *
+ * @return @ref XXH_OK.
+ *
+ * @note @p statePtr must be allocated with XXH64_createState().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
 XXH_PUBLIC_API XXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);
-XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state);
 
-XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH64_state_t* statePtr, XXH64_hash_t seed);
-XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
-XXH_PUBLIC_API XXH64_hash_t  XXH64_digest (const XXH64_state_t* statePtr);
+/*!
+ * @brief Copies one @ref XXH64_state_t to another.
+ *
+ * @param dst_state The state to copy to.
+ * @param src_state The state to copy from.
+ * @pre
+ *   @p dst_state and @p src_state must not be `NULL` and must not overlap.
+ */
+XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dst_state, const XXH64_state_t* src_state);
 
+/*!
+ * @brief Resets an @ref XXH64_state_t to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ * @param seed The 64-bit seed to alter the hash result predictably.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note This function resets and seeds a state. Call it before @ref XXH64_update().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed);
+
+/*!
+ * @brief Consumes a block of @p input to an @ref XXH64_state_t.
+ *
+ * @param statePtr The state struct to update.
+ * @param input The block of data to be hashed, at least @p length bytes in size.
+ * @param length The length of @p input, in bytes.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ * @pre
+ *   The memory between @p input and @p input + @p length must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p input may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note Call this to incrementally consume blocks of data.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH_NOESCAPE XXH64_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length);
+
+/*!
+ * @brief Returns the calculated hash value from an @ref XXH64_state_t.
+ *
+ * @param statePtr The state struct to calculate the hash from.
+ *
+ * @pre
+ *  @p statePtr must not be `NULL`.
+ *
+ * @return The calculated 64-bit xxHash64 value from that state.
+ *
+ * @note
+ *   Calling XXH64_digest() will not affect @p statePtr, so you can update,
+ *   digest, and update again.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_digest (XXH_NOESCAPE const XXH64_state_t* statePtr);
+#endif /* !XXH_NO_STREAM */
 /*******   Canonical representation   *******/
+
+/*!
+ * @brief Canonical (big endian) representation of @ref XXH64_hash_t.
+ */
 typedef struct { unsigned char digest[sizeof(XXH64_hash_t)]; } XXH64_canonical_t;
-XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash);
-XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src);
+
+/*!
+ * @brief Converts an @ref XXH64_hash_t to a big endian @ref XXH64_canonical_t.
+ *
+ * @param dst The @ref XXH64_canonical_t pointer to be stored to.
+ * @param hash The @ref XXH64_hash_t to be converted.
+ *
+ * @pre
+ *   @p dst must not be `NULL`.
+ *
+ * @see @ref canonical_representation_example "Canonical Representation Example"
+ */
+XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash);
+
+/*!
+ * @brief Converts an @ref XXH64_canonical_t to a native @ref XXH64_hash_t.
+ *
+ * @param src The @ref XXH64_canonical_t to convert.
+ *
+ * @pre
+ *   @p src must not be `NULL`.
+ *
+ * @return The converted hash.
+ *
+ * @see @ref canonical_representation_example "Canonical Representation Example"
+ */
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src);
 
 #ifndef XXH_NO_XXH3
+
 /*!
  * @}
  * ************************************************************************
- * @defgroup xxh3_family XXH3 family
+ * @defgroup XXH3_family XXH3 family
  * @ingroup public
  * @{
  *
@@ -741,16 +1081,26 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
  *
  * XXH3's speed benefits greatly from SIMD and 64-bit arithmetic,
  * but does not require it.
- * Any 32-bit and 64-bit targets that can run XXH32 smoothly
- * can run XXH3 at competitive speeds, even without vector support.
- * Further details are explained in the implementation.
+ * Most 32-bit and 64-bit targets that can run XXH32 smoothly can run XXH3
+ * at competitive speeds, even without vector support. Further details are
+ * explained in the implementation.
  *
- * Optimized implementations are provided for AVX512, AVX2, SSE2, NEON, POWER8,
- * ZVector and scalar targets. This can be controlled via the XXH_VECTOR macro.
+ * XXH3 has a fast scalar implementation, but it also includes accelerated SIMD
+ * implementations for many common platforms:
+ *   - AVX512
+ *   - AVX2
+ *   - SSE2
+ *   - ARM NEON
+ *   - WebAssembly SIMD128
+ *   - POWER8 VSX
+ *   - s390x ZVector
+ * This can be controlled via the @ref XXH_VECTOR macro, but it automatically
+ * selects the best version according to predefined macros. For the x86 family, an
+ * automatic runtime dispatcher is included separately in @ref xxh_x86dispatch.c.
  *
  * XXH3 implementation is portable:
  * it has a generic C90 formulation that can be compiled on any platform,
- * all implementations generage exactly the same hash value on all platforms.
+ * all implementations generate exactly the same hash value on all platforms.
  * Starting from v0.8.0, it's also labelled "stable", meaning that
  * any future version will also generate the same hash value.
  *
@@ -762,24 +1112,59 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
  *
  * The API supports one-shot hashing, streaming mode, and custom secrets.
  */
-
 /*-**********************************************************************
 *  XXH3 64-bit variant
 ************************************************************************/
 
-/* XXH3_64bits():
- * default 64-bit variant, using default secret and default seed of 0.
- * It's the fastest variant. */
-XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* data, size_t len);
-
-/*
- * XXH3_64bits_withSeed():
- * This variant generates a custom secret on the fly
- * based on default secret altered using the `seed` value.
- * While this operation is decently fast, note that it's not completely free.
- * Note: seed==0 produces the same results as XXH3_64bits().
+/*!
+ * @brief Calculates 64-bit unseeded variant of XXH3 hash of @p input.
+ *
+ * @param input  The block of data to be hashed, at least @p length bytes in size.
+ * @param length The length of @p input, in bytes.
+ *
+ * @pre
+ *   The memory between @p input and @p input + @p length must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p input may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ * @return The calculated 64-bit XXH3 hash value.
+ *
+ * @note
+ *   This is equivalent to @ref XXH3_64bits_withSeed() with a seed of `0`, however
+ *   it may have slightly better performance due to constant propagation of the
+ *   defaults.
+ *
+ * @see
+ *    XXH3_64bits_withSeed(), XXH3_64bits_withSecret(): other seeding variants
+ * @see @ref single_shot_example "Single Shot Example" for an example.
  */
-XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(const void* data, size_t len, XXH64_hash_t seed);
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length);
+
+/*!
+ * @brief Calculates 64-bit seeded variant of XXH3 hash of @p input.
+ *
+ * @param input  The block of data to be hashed, at least @p length bytes in size.
+ * @param length The length of @p input, in bytes.
+ * @param seed   The 64-bit seed to alter the hash result predictably.
+ *
+ * @pre
+ *   The memory between @p input and @p input + @p length must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p input may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ * @return The calculated 64-bit XXH3 hash value.
+ *
+ * @note
+ *    seed == 0 produces the same results as @ref XXH3_64bits().
+ *
+ * This variant generates a custom secret on the fly based on default secret
+ * altered using the @p seed value.
+ *
+ * While this operation is decently fast, note that it's not completely free.
+ *
+ * @see @ref single_shot_example "Single Shot Example" for an example.
+ */
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed);
 
 /*!
  * The bare minimum size for a custom secret.
@@ -790,27 +1175,43 @@ XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed(const void* data, size_t len, X
  */
 #define XXH3_SECRET_SIZE_MIN 136
 
-/*
- * XXH3_64bits_withSecret():
+/*!
+ * @brief Calculates 64-bit variant of XXH3 with a custom "secret".
+ *
+ * @param data       The block of data to be hashed, at least @p len bytes in size.
+ * @param len        The length of @p data, in bytes.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ *
+ * @return The calculated 64-bit XXH3 hash value.
+ *
+ * @pre
+ *   The memory between @p data and @p data + @p len must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p data may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
  * It's possible to provide any blob of bytes as a "secret" to generate the hash.
  * This makes it more difficult for an external actor to prepare an intentional collision.
- * The main condition is that secretSize *must* be large enough (>= XXH3_SECRET_SIZE_MIN).
+ * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN).
  * However, the quality of the secret impacts the dispersion of the hash algorithm.
  * Therefore, the secret _must_ look like a bunch of random bytes.
  * Avoid "trivial" or structured data such as repeated sequences or a text document.
  * Whenever in doubt about the "randomness" of the blob of bytes,
- * consider employing "XXH3_generateSecret()" instead (see below).
+ * consider employing @ref XXH3_generateSecret() instead (see below).
  * It will generate a proper high entropy secret derived from the blob of bytes.
  * Another advantage of using XXH3_generateSecret() is that
  * it guarantees that all bits within the initial blob of bytes
  * will impact every bit of the output.
  * This is not necessarily the case when using the blob of bytes directly
  * because, when hashing _small_ inputs, only a portion of the secret is employed.
+ *
+ * @see @ref single_shot_example "Single Shot Example" for an example.
  */
-XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(const void* data, size_t len, const void* secret, size_t secretSize);
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize);
 
 
 /*******   Streaming   *******/
+#ifndef XXH_NO_STREAM
 /*
  * Streaming requires state maintenance.
  * This operation costs memory and CPU.
@@ -819,40 +1220,135 @@ XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret(const void* data, size_t len,
  */
 
 /*!
- * @brief The state struct for the XXH3 streaming API.
+ * @brief The opaque state struct for the XXH3 streaming API.
  *
  * @see XXH3_state_s for details.
+ * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH3_state_s XXH3_state_t;
-XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void);
+XXH_PUBLIC_API XXH_MALLOCF XXH3_state_t* XXH3_createState(void);
 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr);
-XXH_PUBLIC_API void XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state);
 
-/*
- * XXH3_64bits_reset():
- * Initialize with default parameters.
- * digest will be equivalent to `XXH3_64bits()`.
+/*!
+ * @brief Copies one @ref XXH3_state_t to another.
+ *
+ * @param dst_state The state to copy to.
+ * @param src_state The state to copy from.
+ * @pre
+ *   @p dst_state and @p src_state must not be `NULL` and must not overlap.
  */
-XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH3_state_t* statePtr);
-/*
- * XXH3_64bits_reset_withSeed():
- * Generate a custom secret from `seed`, and store it into `statePtr`.
- * digest will be equivalent to `XXH3_64bits_withSeed()`.
+XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state);
+
+/*!
+ * @brief Resets an @ref XXH3_state_t to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   - This function resets `statePtr` and generate a secret with default parameters.
+ *   - Call this function before @ref XXH3_64bits_update().
+ *   - Digest will be equivalent to `XXH3_64bits()`.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ *
  */
-XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed);
-/*
- * XXH3_64bits_reset_withSecret():
- * `secret` is referenced, it _must outlive_ the hash streaming session.
- * Similar to one-shot API, `secretSize` must be >= `XXH3_SECRET_SIZE_MIN`,
+XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr);
+
+/*!
+ * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ * @param seed     The 64-bit seed to alter the hash result predictably.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   - This function resets `statePtr` and generate a secret from `seed`.
+ *   - Call this function before @ref XXH3_64bits_update().
+ *   - Digest will be equivalent to `XXH3_64bits_withSeed()`.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ *
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed);
+
+/*!
+ * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   `secret` is referenced, it _must outlive_ the hash streaming session.
+ *
+ * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN,
  * and the quality of produced hash values depends on secret's entropy
  * (secret's content should look like a bunch of random bytes).
  * When in doubt about the randomness of a candidate `secret`,
  * consider employing `XXH3_generateSecret()` instead (see below).
+ *
+ * @see @ref streaming_example "Streaming Example"
  */
-XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize);
+XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize);
 
-XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH3_state_t* statePtr, const void* input, size_t length);
-XXH_PUBLIC_API XXH64_hash_t  XXH3_64bits_digest (const XXH3_state_t* statePtr);
+/*!
+ * @brief Consumes a block of @p input to an @ref XXH3_state_t.
+ *
+ * @param statePtr The state struct to update.
+ * @param input The block of data to be hashed, at least @p length bytes in size.
+ * @param length The length of @p input, in bytes.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ * @pre
+ *   The memory between @p input and @p input + @p length must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p input may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note Call this to incrementally consume blocks of data.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length);
+
+/*!
+ * @brief Returns the calculated XXH3 64-bit hash value from an @ref XXH3_state_t.
+ *
+ * @param statePtr The state struct to calculate the hash from.
+ *
+ * @pre
+ *  @p statePtr must not be `NULL`.
+ *
+ * @return The calculated XXH3 64-bit hash value from that state.
+ *
+ * @note
+ *   Calling XXH3_64bits_digest() will not affect @p statePtr, so you can update,
+ *   digest, and update again.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t  XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr);
+#endif /* !XXH_NO_STREAM */
 
 /* note : canonical representation of XXH3 is the same as XXH64
  * since they both produce XXH64_hash_t values */
@@ -873,11 +1369,76 @@ typedef struct {
     XXH64_hash_t high64;  /*!< `value >> 64` */
 } XXH128_hash_t;
 
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* data, size_t len);
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed(const void* data, size_t len, XXH64_hash_t seed);
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(const void* data, size_t len, const void* secret, size_t secretSize);
+/*!
+ * @brief Calculates 128-bit unseeded variant of XXH3 of @p data.
+ *
+ * @param data The block of data to be hashed, at least @p length bytes in size.
+ * @param len  The length of @p data, in bytes.
+ *
+ * @return The calculated 128-bit variant of XXH3 value.
+ *
+ * The 128-bit variant of XXH3 has more strength, but it has a bit of overhead
+ * for shorter inputs.
+ *
+ * This is equivalent to @ref XXH3_128bits_withSeed() with a seed of `0`, however
+ * it may have slightly better performance due to constant propagation of the
+ * defaults.
+ *
+ * @see XXH3_128bits_withSeed(), XXH3_128bits_withSecret(): other seeding variants
+ * @see @ref single_shot_example "Single Shot Example" for an example.
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* data, size_t len);
+/*! @brief Calculates 128-bit seeded variant of XXH3 hash of @p data.
+ *
+ * @param data The block of data to be hashed, at least @p length bytes in size.
+ * @param len  The length of @p data, in bytes.
+ * @param seed The 64-bit seed to alter the hash result predictably.
+ *
+ * @return The calculated 128-bit variant of XXH3 value.
+ *
+ * @note
+ *    seed == 0 produces the same results as @ref XXH3_64bits().
+ *
+ * This variant generates a custom secret on the fly based on default secret
+ * altered using the @p seed value.
+ *
+ * While this operation is decently fast, note that it's not completely free.
+ *
+ * @see XXH3_128bits(), XXH3_128bits_withSecret(): other seeding variants
+ * @see @ref single_shot_example "Single Shot Example" for an example.
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSeed(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed);
+/*!
+ * @brief Calculates 128-bit variant of XXH3 with a custom "secret".
+ *
+ * @param data       The block of data to be hashed, at least @p len bytes in size.
+ * @param len        The length of @p data, in bytes.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ *
+ * @return The calculated 128-bit variant of XXH3 value.
+ *
+ * It's possible to provide any blob of bytes as a "secret" to generate the hash.
+ * This makes it more difficult for an external actor to prepare an intentional collision.
+ * The main condition is that @p secretSize *must* be large enough (>= @ref XXH3_SECRET_SIZE_MIN).
+ * However, the quality of the secret impacts the dispersion of the hash algorithm.
+ * Therefore, the secret _must_ look like a bunch of random bytes.
+ * Avoid "trivial" or structured data such as repeated sequences or a text document.
+ * Whenever in doubt about the "randomness" of the blob of bytes,
+ * consider employing @ref XXH3_generateSecret() instead (see below).
+ * It will generate a proper high entropy secret derived from the blob of bytes.
+ * Another advantage of using XXH3_generateSecret() is that
+ * it guarantees that all bits within the initial blob of bytes
+ * will impact every bit of the output.
+ * This is not necessarily the case when using the blob of bytes directly
+ * because, when hashing _small_ inputs, only a portion of the secret is employed.
+ *
+ * @see @ref single_shot_example "Single Shot Example" for an example.
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecret(XXH_NOESCAPE const void* data, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize);
 
 /*******   Streaming   *******/
+#ifndef XXH_NO_STREAM
 /*
  * Streaming requires state maintenance.
  * This operation costs memory and CPU.
@@ -890,39 +1451,169 @@ XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret(const void* data, size_t le
  * All reset and streaming functions have same meaning as their 64-bit counterpart.
  */
 
-XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH3_state_t* statePtr);
-XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed);
-XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize);
+/*!
+ * @brief Resets an @ref XXH3_state_t to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   - This function resets `statePtr` and generate a secret with default parameters.
+ *   - Call it before @ref XXH3_128bits_update().
+ *   - Digest will be equivalent to `XXH3_128bits()`.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr);
 
-XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update (XXH3_state_t* statePtr, const void* input, size_t length);
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (const XXH3_state_t* statePtr);
+/*!
+ * @brief Resets an @ref XXH3_state_t with 64-bit seed to begin a new hash.
+ *
+ * @param statePtr The state struct to reset.
+ * @param seed     The 64-bit seed to alter the hash result predictably.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   - This function resets `statePtr` and generate a secret from `seed`.
+ *   - Call it before @ref XXH3_128bits_update().
+ *   - Digest will be equivalent to `XXH3_128bits_withSeed()`.
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed);
+/*!
+ * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
+ *
+ * @param statePtr   The state struct to reset.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * `secret` is referenced, it _must outlive_ the hash streaming session.
+ * Similar to one-shot API, `secretSize` must be >= @ref XXH3_SECRET_SIZE_MIN,
+ * and the quality of produced hash values depends on secret's entropy
+ * (secret's content should look like a bunch of random bytes).
+ * When in doubt about the randomness of a candidate `secret`,
+ * consider employing `XXH3_generateSecret()` instead (see below).
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize);
+
+/*!
+ * @brief Consumes a block of @p input to an @ref XXH3_state_t.
+ *
+ * Call this to incrementally consume blocks of data.
+ *
+ * @param statePtr The state struct to update.
+ * @param input The block of data to be hashed, at least @p length bytes in size.
+ * @param length The length of @p input, in bytes.
+ *
+ * @pre
+ *   @p statePtr must not be `NULL`.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @note
+ *   The memory between @p input and @p input + @p length must be valid,
+ *   readable, contiguous memory. However, if @p length is `0`, @p input may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ */
+XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length);
+
+/*!
+ * @brief Returns the calculated XXH3 128-bit hash value from an @ref XXH3_state_t.
+ *
+ * @param statePtr The state struct to calculate the hash from.
+ *
+ * @pre
+ *  @p statePtr must not be `NULL`.
+ *
+ * @return The calculated XXH3 128-bit hash value from that state.
+ *
+ * @note
+ *   Calling XXH3_128bits_digest() will not affect @p statePtr, so you can update,
+ *   digest, and update again.
+ *
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr);
+#endif /* !XXH_NO_STREAM */
 
 /* Following helper functions make it possible to compare XXH128_hast_t values.
  * Since XXH128_hash_t is a structure, this capability is not offered by the language.
  * Note: For better performance, these functions can be inlined using XXH_INLINE_ALL */
 
 /*!
- * XXH128_isEqual():
- * Return: 1 if `h1` and `h2` are equal, 0 if they are not.
+ * @brief Check equality of two XXH128_hash_t values
+ *
+ * @param h1 The 128-bit hash value.
+ * @param h2 Another 128-bit hash value.
+ *
+ * @return `1` if `h1` and `h2` are equal.
+ * @return `0` if they are not.
  */
-XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2);
+XXH_PUBLIC_API XXH_PUREF int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2);
 
 /*!
- * XXH128_cmp():
+ * @brief Compares two @ref XXH128_hash_t
  *
  * This comparator is compatible with stdlib's `qsort()`/`bsearch()`.
  *
- * return: >0 if *h128_1  > *h128_2
- *         =0 if *h128_1 == *h128_2
- *         <0 if *h128_1  < *h128_2
+ * @param h128_1 Left-hand side value
+ * @param h128_2 Right-hand side value
+ *
+ * @return >0 if @p h128_1  > @p h128_2
+ * @return =0 if @p h128_1 == @p h128_2
+ * @return <0 if @p h128_1  < @p h128_2
  */
-XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2);
+XXH_PUBLIC_API XXH_PUREF int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2);
 
 
 /*******   Canonical representation   *******/
 typedef struct { unsigned char digest[sizeof(XXH128_hash_t)]; } XXH128_canonical_t;
-XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash);
-XXH_PUBLIC_API XXH128_hash_t XXH128_hashFromCanonical(const XXH128_canonical_t* src);
+
+
+/*!
+ * @brief Converts an @ref XXH128_hash_t to a big endian @ref XXH128_canonical_t.
+ *
+ * @param dst  The @ref XXH128_canonical_t pointer to be stored to.
+ * @param hash The @ref XXH128_hash_t to be converted.
+ *
+ * @pre
+ *   @p dst must not be `NULL`.
+ * @see @ref canonical_representation_example "Canonical Representation Example"
+ */
+XXH_PUBLIC_API void XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash);
+
+/*!
+ * @brief Converts an @ref XXH128_canonical_t to a native @ref XXH128_hash_t.
+ *
+ * @param src The @ref XXH128_canonical_t to convert.
+ *
+ * @pre
+ *   @p src must not be `NULL`.
+ *
+ * @return The converted hash.
+ * @see @ref canonical_representation_example "Canonical Representation Example"
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src);
 
 
 #endif  /* !XXH_NO_XXH3 */
@@ -996,7 +1687,6 @@ struct XXH64_state_s {
    XXH64_hash_t reserved64;   /*!< Reserved field. Do not read or write to it. */
 };   /* typedef'd to XXH64_state_t */
 
-
 #ifndef XXH_NO_XXH3
 
 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* >= C11 */
@@ -1032,6 +1722,7 @@ struct XXH64_state_s {
 #define XXH3_INTERNALBUFFER_SIZE 256
 
 /*!
+ * @internal
  * @brief Default size of the secret buffer (and @ref XXH3_kSecret).
  *
  * This is the size used in @ref XXH3_kSecret and the seeded functions.
@@ -1064,7 +1755,7 @@ struct XXH64_state_s {
  */
 struct XXH3_state_s {
    XXH_ALIGN_MEMBER(64, XXH64_hash_t acc[8]);
-       /*!< The 8 accumulators. Similar to `vN` in @ref XXH32_state_s::v1 and @ref XXH64_state_s */
+       /*!< The 8 accumulators. See @ref XXH32_state_s::v and @ref XXH64_state_s::v */
    XXH_ALIGN_MEMBER(64, unsigned char customSecret[XXH3_SECRET_DEFAULT_SIZE]);
        /*!< Used to store a custom secret generated from a seed. */
    XXH_ALIGN_MEMBER(64, unsigned char buffer[XXH3_INTERNALBUFFER_SIZE]);
@@ -1104,69 +1795,148 @@ struct XXH3_state_s {
  * Note that this doesn't prepare the state for a streaming operation,
  * it's still necessary to use XXH3_NNbits_reset*() afterwards.
  */
-#define XXH3_INITSTATE(XXH3_state_ptr)   { (XXH3_state_ptr)->seed = 0; }
+#define XXH3_INITSTATE(XXH3_state_ptr)                       \
+    do {                                                     \
+        XXH3_state_t* tmp_xxh3_state_ptr = (XXH3_state_ptr); \
+        tmp_xxh3_state_ptr->seed = 0;                        \
+        tmp_xxh3_state_ptr->extSecret = NULL;                \
+    } while(0)
 
 
-/* XXH128() :
- * simple alias to pre-selected XXH3_128bits variant
+/*!
+ * @brief Calculates the 128-bit hash of @p data using XXH3.
+ *
+ * @param data The block of data to be hashed, at least @p len bytes in size.
+ * @param len  The length of @p data, in bytes.
+ * @param seed The 64-bit seed to alter the hash's output predictably.
+ *
+ * @pre
+ *   The memory between @p data and @p data + @p len must be valid,
+ *   readable, contiguous memory. However, if @p len is `0`, @p data may be
+ *   `NULL`. In C++, this also must be *TriviallyCopyable*.
+ *
+ * @return The calculated 128-bit XXH3 value.
+ *
+ * @see @ref single_shot_example "Single Shot Example" for an example.
  */
-XXH_PUBLIC_API XXH128_hash_t XXH128(const void* data, size_t len, XXH64_hash_t seed);
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128(XXH_NOESCAPE const void* data, size_t len, XXH64_hash_t seed);
 
 
 /* ===   Experimental API   === */
 /* Symbols defined below must be considered tied to a specific library version. */
 
-/*
- * XXH3_generateSecret():
+/*!
+ * @brief Derive a high-entropy secret from any user-defined content, named customSeed.
+ *
+ * @param secretBuffer    A writable buffer for derived high-entropy secret data.
+ * @param secretSize      Size of secretBuffer, in bytes.  Must be >= XXH3_SECRET_DEFAULT_SIZE.
+ * @param customSeed      A user-defined content.
+ * @param customSeedSize  Size of customSeed, in bytes.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
  *
- * Derive a high-entropy secret from any user-defined content, named customSeed.
  * The generated secret can be used in combination with `*_withSecret()` functions.
- * The `_withSecret()` variants are useful to provide a higher level of protection than 64-bit seed,
- * as it becomes much more difficult for an external actor to guess how to impact the calculation logic.
+ * The `_withSecret()` variants are useful to provide a higher level of protection
+ * than 64-bit seed, as it becomes much more difficult for an external actor to
+ * guess how to impact the calculation logic.
  *
  * The function accepts as input a custom seed of any length and any content,
- * and derives from it a high-entropy secret of length @secretSize
- * into an already allocated buffer @secretBuffer.
- * @secretSize must be >= XXH3_SECRET_SIZE_MIN
+ * and derives from it a high-entropy secret of length @p secretSize into an
+ * already allocated buffer @p secretBuffer.
  *
  * The generated secret can then be used with any `*_withSecret()` variant.
- * Functions `XXH3_128bits_withSecret()`, `XXH3_64bits_withSecret()`,
- * `XXH3_128bits_reset_withSecret()` and `XXH3_64bits_reset_withSecret()`
+ * The functions @ref XXH3_128bits_withSecret(), @ref XXH3_64bits_withSecret(),
+ * @ref XXH3_128bits_reset_withSecret() and @ref XXH3_64bits_reset_withSecret()
  * are part of this list. They all accept a `secret` parameter
- * which must be large enough for implementation reasons (>= XXH3_SECRET_SIZE_MIN)
+ * which must be large enough for implementation reasons (>= @ref XXH3_SECRET_SIZE_MIN)
  * _and_ feature very high entropy (consist of random-looking bytes).
- * These conditions can be a high bar to meet, so
- * XXH3_generateSecret() can be employed to ensure proper quality.
+ * These conditions can be a high bar to meet, so @ref XXH3_generateSecret() can
+ * be employed to ensure proper quality.
  *
- * customSeed can be anything. It can have any size, even small ones,
- * and its content can be anything, even "poor entropy" sources such as a bunch of zeroes.
- * The resulting `secret` will nonetheless provide all required qualities.
+ * @p customSeed can be anything. It can have any size, even small ones,
+ * and its content can be anything, even "poor entropy" sources such as a bunch
+ * of zeroes. The resulting `secret` will nonetheless provide all required qualities.
  *
- * When customSeedSize > 0, supplying NULL as customSeed is undefined behavior.
+ * @pre
+ *   - @p secretSize must be >= @ref XXH3_SECRET_SIZE_MIN
+ *   - When @p customSeedSize > 0, supplying NULL as customSeed is undefined behavior.
+ *
+ * Example code:
+ * @code{.c}
+ *    #include 
+ *    #include 
+ *    #include 
+ *    #define XXH_STATIC_LINKING_ONLY // expose unstable API
+ *    #include "xxhash.h"
+ *    // Hashes argv[2] using the entropy from argv[1].
+ *    int main(int argc, char* argv[])
+ *    {
+ *        char secret[XXH3_SECRET_SIZE_MIN];
+ *        if (argv != 3) { return 1; }
+ *        XXH3_generateSecret(secret, sizeof(secret), argv[1], strlen(argv[1]));
+ *        XXH64_hash_t h = XXH3_64bits_withSecret(
+ *             argv[2], strlen(argv[2]),
+ *             secret, sizeof(secret)
+ *        );
+ *        printf("%016llx\n", (unsigned long long) h);
+ *    }
+ * @endcode
  */
-XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(void* secretBuffer, size_t secretSize, const void* customSeed, size_t customSeedSize);
+XXH_PUBLIC_API XXH_errorcode XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize);
 
-
-/*
- * XXH3_generateSecret_fromSeed():
+/*!
+ * @brief Generate the same secret as the _withSeed() variants.
  *
- * Generate the same secret as the _withSeed() variants.
- *
- * The resulting secret has a length of XXH3_SECRET_DEFAULT_SIZE (necessarily).
- * @secretBuffer must be already allocated, of size at least XXH3_SECRET_DEFAULT_SIZE bytes.
+ * @param secretBuffer A writable buffer of @ref XXH3_SECRET_SIZE_MIN bytes
+ * @param seed         The 64-bit seed to alter the hash result predictably.
  *
  * The generated secret can be used in combination with
  *`*_withSecret()` and `_withSecretandSeed()` variants.
- * This generator is notably useful in combination with `_withSecretandSeed()`,
- * as a way to emulate a faster `_withSeed()` variant.
+ *
+ * Example C++ `std::string` hash class:
+ * @code{.cpp}
+ *    #include 
+ *    #define XXH_STATIC_LINKING_ONLY // expose unstable API
+ *    #include "xxhash.h"
+ *    // Slow, seeds each time
+ *    class HashSlow {
+ *        XXH64_hash_t seed;
+ *    public:
+ *        HashSlow(XXH64_hash_t s) : seed{s} {}
+ *        size_t operator()(const std::string& x) const {
+ *            return size_t{XXH3_64bits_withSeed(x.c_str(), x.length(), seed)};
+ *        }
+ *    };
+ *    // Fast, caches the seeded secret for future uses.
+ *    class HashFast {
+ *        unsigned char secret[XXH3_SECRET_SIZE_MIN];
+ *    public:
+ *        HashFast(XXH64_hash_t s) {
+ *            XXH3_generateSecret_fromSeed(secret, seed);
+ *        }
+ *        size_t operator()(const std::string& x) const {
+ *            return size_t{
+ *                XXH3_64bits_withSecret(x.c_str(), x.length(), secret, sizeof(secret))
+ *            };
+ *        }
+ *    };
+ * @endcode
  */
-XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed);
+XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed);
 
-/*
- * *_withSecretandSeed() :
+/*!
+ * @brief Calculates 64/128-bit seeded variant of XXH3 hash of @p data.
+ *
+ * @param data       The block of data to be hashed, at least @p len bytes in size.
+ * @param len        The length of @p data, in bytes.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ * @param seed       The 64-bit seed to alter the hash result predictably.
+ *
  * These variants generate hash values using either
- * @seed for "short" keys (< XXH3_MIDSIZE_MAX = 240 bytes)
- * or @secret for "large" keys (>= XXH3_MIDSIZE_MAX).
+ * @p seed for "short" keys (< @ref XXH3_MIDSIZE_MAX = 240 bytes)
+ * or @p secret for "large" keys (>= @ref XXH3_MIDSIZE_MAX).
  *
  * This generally benefits speed, compared to `_withSeed()` or `_withSecret()`.
  * `_withSeed()` has to generate the secret on the fly for "large" keys.
@@ -1175,7 +1945,7 @@ XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_
  * which requires more instructions than _withSeed() variants.
  * Therefore, _withSecretandSeed variant combines the best of both worlds.
  *
- * When @secret has been generated by XXH3_generateSecret_fromSeed(),
+ * When @p secret has been generated by XXH3_generateSecret_fromSeed(),
  * this variant produces *exactly* the same results as `_withSeed()` variant,
  * hence offering only a pure speed benefit on "large" input,
  * by skipping the need to regenerate the secret for every large input.
@@ -1184,33 +1954,71 @@ XXH_PUBLIC_API void XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_
  * for example with XXH3_64bits(), which then becomes the seed,
  * and then employ both the seed and the secret in _withSecretandSeed().
  * On top of speed, an added benefit is that each bit in the secret
- * has a 50% chance to swap each bit in the output,
- * via its impact to the seed.
+ * has a 50% chance to swap each bit in the output, via its impact to the seed.
+ *
  * This is not guaranteed when using the secret directly in "small data" scenarios,
  * because only portions of the secret are employed for small data.
  */
-XXH_PUBLIC_API XXH64_hash_t
-XXH3_64bits_withSecretandSeed(const void* data, size_t len,
-                              const void* secret, size_t secretSize,
+XXH_PUBLIC_API XXH_PUREF XXH64_hash_t
+XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* data, size_t len,
+                              XXH_NOESCAPE const void* secret, size_t secretSize,
                               XXH64_hash_t seed);
-
-XXH_PUBLIC_API XXH128_hash_t
-XXH3_128bits_withSecretandSeed(const void* data, size_t len,
-                               const void* secret, size_t secretSize,
+/*!
+ * @brief Calculates 128-bit seeded variant of XXH3 hash of @p data.
+ *
+ * @param input      The block of data to be hashed, at least @p len bytes in size.
+ * @param length     The length of @p data, in bytes.
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ * @param seed64     The 64-bit seed to alter the hash result predictably.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @see XXH3_64bits_withSecretandSeed()
+ */
+XXH_PUBLIC_API XXH_PUREF XXH128_hash_t
+XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length,
+                               XXH_NOESCAPE const void* secret, size_t secretSize,
                                XXH64_hash_t seed64);
-
+#ifndef XXH_NO_STREAM
+/*!
+ * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
+ *
+ * @param statePtr   A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ * @param seed64     The 64-bit seed to alter the hash result predictably.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @see XXH3_64bits_withSecretandSeed()
+ */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
-                                    const void* secret, size_t secretSize,
+XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
+                                    XXH_NOESCAPE const void* secret, size_t secretSize,
                                     XXH64_hash_t seed64);
-
+/*!
+ * @brief Resets an @ref XXH3_state_t with secret data to begin a new hash.
+ *
+ * @param statePtr   A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
+ * @param secret     The secret data.
+ * @param secretSize The length of @p secret, in bytes.
+ * @param seed64     The 64-bit seed to alter the hash result predictably.
+ *
+ * @return @ref XXH_OK on success.
+ * @return @ref XXH_ERROR on failure.
+ *
+ * @see XXH3_64bits_withSecretandSeed()
+ */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
-                                     const void* secret, size_t secretSize,
+XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
+                                     XXH_NOESCAPE const void* secret, size_t secretSize,
                                      XXH64_hash_t seed64);
+#endif /* !XXH_NO_STREAM */
 
-
-#endif  /* XXH_NO_XXH3 */
+#endif  /* !XXH_NO_XXH3 */
 #endif  /* XXH_NO_LONG_LONG */
 #if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
 #  define XXH_IMPLEMENTATION
@@ -1264,7 +2072,7 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
 /*!
  * @brief Define this to disable 64-bit code.
  *
- * Useful if only using the @ref xxh32_family and you have a strict C90 compiler.
+ * Useful if only using the @ref XXH32_family and you have a strict C90 compiler.
  */
 #  define XXH_NO_LONG_LONG
 #  undef XXH_NO_LONG_LONG /* don't actually */
@@ -1287,7 +2095,7 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  *     Use `memcpy()`. Safe and portable. Note that most modern compilers will
  *     eliminate the function call and treat it as an unaligned access.
  *
- *  - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((packed))`
+ *  - `XXH_FORCE_MEMORY_ACCESS=1`: `__attribute__((aligned(1)))`
  *   @par
  *     Depends on compiler extensions and is therefore not portable.
  *     This method is safe _if_ your compiler supports it,
@@ -1307,7 +2115,7 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  *     inline small `memcpy()` calls, and it might also be faster on big-endian
  *     systems which lack a native byteswap instruction. However, some compilers
  *     will emit literal byteshifts even if the target supports unaligned access.
- *  .
+ *
  *
  * @warning
  *   Methods 1 and 2 rely on implementation-defined behavior. Use these with
@@ -1320,6 +2128,34 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  */
 #  define XXH_FORCE_MEMORY_ACCESS 0
 
+/*!
+ * @def XXH_SIZE_OPT
+ * @brief Controls how much xxHash optimizes for size.
+ *
+ * xxHash, when compiled, tends to result in a rather large binary size. This
+ * is mostly due to heavy usage to forced inlining and constant folding of the
+ * @ref XXH3_family to increase performance.
+ *
+ * However, some developers prefer size over speed. This option can
+ * significantly reduce the size of the generated code. When using the `-Os`
+ * or `-Oz` options on GCC or Clang, this is defined to 1 by default,
+ * otherwise it is defined to 0.
+ *
+ * Most of these size optimizations can be controlled manually.
+ *
+ * This is a number from 0-2.
+ *  - `XXH_SIZE_OPT` == 0: Default. xxHash makes no size optimizations. Speed
+ *    comes first.
+ *  - `XXH_SIZE_OPT` == 1: Default for `-Os` and `-Oz`. xxHash is more
+ *    conservative and disables hacks that increase code size. It implies the
+ *    options @ref XXH_NO_INLINE_HINTS == 1, @ref XXH_FORCE_ALIGN_CHECK == 0,
+ *    and @ref XXH3_NEON_LANES == 8 if they are not already defined.
+ *  - `XXH_SIZE_OPT` == 2: xxHash tries to make itself as small as possible.
+ *    Performance may cry. For example, the single shot functions just use the
+ *    streaming API.
+ */
+#  define XXH_SIZE_OPT 0
+
 /*!
  * @def XXH_FORCE_ALIGN_CHECK
  * @brief If defined to non-zero, adds a special path for aligned inputs (XXH32()
@@ -1341,9 +2177,11 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  *
  * In these cases, the alignment check can be removed by setting this macro to 0.
  * Then the code will always use unaligned memory access.
- * Align check is automatically disabled on x86, x64 & arm64,
+ * Align check is automatically disabled on x86, x64, ARM64, and some ARM chips
  * which are platforms known to offer good unaligned memory accesses performance.
  *
+ * It is also disabled by default when @ref XXH_SIZE_OPT >= 1.
+ *
  * This option does not affect XXH3 (only XXH32 and XXH64).
  */
 #  define XXH_FORCE_ALIGN_CHECK 0
@@ -1365,11 +2203,28 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  * XXH_NO_INLINE_HINTS marks all internal functions as static, giving the
  * compiler full control on whether to inline or not.
  *
- * When not optimizing (-O0), optimizing for size (-Os, -Oz), or using
- * -fno-inline with GCC or Clang, this will automatically be defined.
+ * When not optimizing (-O0), using `-fno-inline` with GCC or Clang, or if
+ * @ref XXH_SIZE_OPT >= 1, this will automatically be defined.
  */
 #  define XXH_NO_INLINE_HINTS 0
 
+/*!
+ * @def XXH3_INLINE_SECRET
+ * @brief Determines whether to inline the XXH3 withSecret code.
+ *
+ * When the secret size is known, the compiler can improve the performance
+ * of XXH3_64bits_withSecret() and XXH3_128bits_withSecret().
+ *
+ * However, if the secret size is not known, it doesn't have any benefit. This
+ * happens when xxHash is compiled into a global symbol. Therefore, if
+ * @ref XXH_INLINE_ALL is *not* defined, this will be defined to 0.
+ *
+ * Additionally, this defaults to 0 on GCC 12+, which has an issue with function pointers
+ * that are *sometimes* force inline on -Og, and it is impossible to automatically
+ * detect this optimization level.
+ */
+#  define XXH3_INLINE_SECRET 0
+
 /*!
  * @def XXH32_ENDJMP
  * @brief Whether to use a jump for `XXH32_finalize`.
@@ -1391,34 +2246,45 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
  */
 #  define XXH_OLD_NAMES
 #  undef XXH_OLD_NAMES /* don't actually use, it is ugly. */
+
+/*!
+ * @def XXH_NO_STREAM
+ * @brief Disables the streaming API.
+ *
+ * When xxHash is not inlined and the streaming functions are not used, disabling
+ * the streaming functions can improve code size significantly, especially with
+ * the @ref XXH3_family which tends to make constant folded copies of itself.
+ */
+#  define XXH_NO_STREAM
+#  undef XXH_NO_STREAM /* don't actually */
 #endif /* XXH_DOXYGEN */
 /*!
  * @}
  */
 
 #ifndef XXH_FORCE_MEMORY_ACCESS   /* can be defined externally, on command line for example */
-   /* prefer __packed__ structures (method 1) for gcc on armv7+ and mips */
-#  if !defined(__clang__) && \
-( \
-    (defined(__INTEL_COMPILER) && !defined(_WIN32)) || \
-    ( \
-        defined(__GNUC__) && ( \
-            (defined(__ARM_ARCH) && __ARM_ARCH >= 7) || \
-            ( \
-                defined(__mips__) && \
-                (__mips <= 5 || __mips_isa_rev < 6) && \
-                (!defined(__mips16) || defined(__mips_mips16e2)) \
-            ) \
-        ) \
-    ) \
-)
+   /* prefer __packed__ structures (method 1) for GCC
+    * < ARMv7 with unaligned access (e.g. Raspbian armhf) still uses byte shifting, so we use memcpy
+    * which for some reason does unaligned loads. */
+#  if defined(__GNUC__) && !(defined(__ARM_ARCH) && __ARM_ARCH < 7 && defined(__ARM_FEATURE_UNALIGNED))
 #    define XXH_FORCE_MEMORY_ACCESS 1
 #  endif
 #endif
 
+#ifndef XXH_SIZE_OPT
+   /* default to 1 for -Os or -Oz */
+#  if (defined(__GNUC__) || defined(__clang__)) && defined(__OPTIMIZE_SIZE__)
+#    define XXH_SIZE_OPT 1
+#  else
+#    define XXH_SIZE_OPT 0
+#  endif
+#endif
+
 #ifndef XXH_FORCE_ALIGN_CHECK  /* can be defined externally */
-#  if defined(__i386)  || defined(__x86_64__) || defined(__aarch64__) \
-   || defined(_M_IX86) || defined(_M_X64)     || defined(_M_ARM64) /* visual */
+   /* don't check on sizeopt, x86, aarch64, or arm when unaligned access is available */
+#  if XXH_SIZE_OPT >= 1 || \
+      defined(__i386)  || defined(__x86_64__) || defined(__aarch64__) || defined(__ARM_FEATURE_UNALIGNED) \
+   || defined(_M_IX86) || defined(_M_X64)     || defined(_M_ARM64)    || defined(_M_ARM) /* visual */
 #    define XXH_FORCE_ALIGN_CHECK 0
 #  else
 #    define XXH_FORCE_ALIGN_CHECK 1
@@ -1426,14 +2292,22 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
 #endif
 
 #ifndef XXH_NO_INLINE_HINTS
-#  if defined(__OPTIMIZE_SIZE__) /* -Os, -Oz */ \
-   || defined(__NO_INLINE__)     /* -O0, -fno-inline */
+#  if XXH_SIZE_OPT >= 1 || defined(__NO_INLINE__)  /* -O0, -fno-inline */
 #    define XXH_NO_INLINE_HINTS 1
 #  else
 #    define XXH_NO_INLINE_HINTS 0
 #  endif
 #endif
 
+#ifndef XXH3_INLINE_SECRET
+#  if (defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12) \
+     || !defined(XXH_INLINE_ALL)
+#    define XXH3_INLINE_SECRET 0
+#  else
+#    define XXH3_INLINE_SECRET 1
+#  endif
+#endif
+
 #ifndef XXH32_ENDJMP
 /* generally preferable for performance */
 #  define XXH32_ENDJMP 0
@@ -1448,13 +2322,56 @@ XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr,
 /* *************************************
 *  Includes & Memory related functions
 ***************************************/
-/* Modify the local functions below should you wish to use some other memory routines */
-/* for ZSTD_malloc(), ZSTD_free() */
-#define ZSTD_DEPS_NEED_MALLOC
-#include "zstd_deps.h"  /* size_t, ZSTD_malloc, ZSTD_free, ZSTD_memcpy */
-static void* XXH_malloc(size_t s) { return ZSTD_malloc(s); }
-static void  XXH_free  (void* p)  { ZSTD_free(p); }
-static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_memcpy(dest,src,size); }
+#if defined(XXH_NO_STREAM)
+/* nothing */
+#elif defined(XXH_NO_STDLIB)
+
+/* When requesting to disable any mention of stdlib,
+ * the library loses the ability to invoked malloc / free.
+ * In practice, it means that functions like `XXH*_createState()`
+ * will always fail, and return NULL.
+ * This flag is useful in situations where
+ * xxhash.h is integrated into some kernel, embedded or limited environment
+ * without access to dynamic allocation.
+ */
+
+static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; }
+static void XXH_free(void* p) { (void)p; }
+
+#else
+
+/*
+ * Modify the local functions below should you wish to use
+ * different memory routines for malloc() and free()
+ */
+#include 
+
+/*!
+ * @internal
+ * @brief Modify this function to use a different routine than malloc().
+ */
+static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); }
+
+/*!
+ * @internal
+ * @brief Modify this function to use a different routine than free().
+ */
+static void XXH_free(void* p) { free(p); }
+
+#endif  /* XXH_NO_STDLIB */
+
+#include 
+
+/*!
+ * @internal
+ * @brief Modify this function to use a different routine than memcpy().
+ */
+static void* XXH_memcpy(void* dest, const void* src, size_t size)
+{
+    return memcpy(dest,src,size);
+}
+
+#include    /* ULLONG_MAX */
 
 
 /* *************************************
@@ -1487,6 +2404,11 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_
 #  define XXH_NO_INLINE static
 #endif
 
+#if XXH3_INLINE_SECRET
+#  define XXH3_WITH_SECRET_INLINE XXH_FORCE_INLINE
+#else
+#  define XXH3_WITH_SECRET_INLINE XXH_NO_INLINE
+#endif
 
 
 /* *************************************
@@ -1512,14 +2434,17 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_
 #  include    /* note: can still be disabled with NDEBUG */
 #  define XXH_ASSERT(c)   assert(c)
 #else
-#  define XXH_ASSERT(c)   ((void)0)
+#  if defined(__INTEL_COMPILER)
+#    define XXH_ASSERT(c)   XXH_ASSUME((unsigned char) (c))
+#  else
+#    define XXH_ASSERT(c)   XXH_ASSUME(c)
+#  endif
 #endif
 
 /* note: use after variable declarations */
 #ifndef XXH_STATIC_ASSERT
 #  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)    /* C11 */
-#    include 
-#    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0)
+#    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { _Static_assert((c),m); } while(0)
 #  elif defined(__cplusplus) && (__cplusplus >= 201103L)            /* C++11 */
 #    define XXH_STATIC_ASSERT_WITH_MESSAGE(c,m) do { static_assert((c),m); } while(0)
 #  else
@@ -1534,7 +2459,7 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_
  * @brief Used to prevent unwanted optimizations for @p var.
  *
  * It uses an empty GCC inline assembly statement with a register constraint
- * which forces @p var into a general purpose register (e.g. eax, ebx, ecx
+ * which forces @p var into a general purpose register (eg eax, ebx, ecx
  * on x86) and marks it as modified.
  *
  * This is used in a few places to avoid unwanted autovectorization (e.g.
@@ -1545,11 +2470,19 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_
  * XXH3_initCustomSecret_scalar().
  */
 #if defined(__GNUC__) || defined(__clang__)
-#  define XXH_COMPILER_GUARD(var) __asm__ __volatile__("" : "+r" (var))
+#  define XXH_COMPILER_GUARD(var) __asm__("" : "+r" (var))
 #else
 #  define XXH_COMPILER_GUARD(var) ((void)0)
 #endif
 
+/* Specifically for NEON vectors which use the "w" constraint, on
+ * Clang. */
+#if defined(__clang__) && defined(__ARM_ARCH) && !defined(__wasm__)
+#  define XXH_COMPILER_GUARD_CLANG_NEON(var) __asm__("" : "+w" (var))
+#else
+#  define XXH_COMPILER_GUARD_CLANG_NEON(var) ((void)0)
+#endif
+
 /* *************************************
 *  Basic Types
 ***************************************/
@@ -1564,6 +2497,7 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return ZSTD_
 typedef XXH32_hash_t xxh_u32;
 
 #ifdef XXH_OLD_NAMES
+#  warning "XXH_OLD_NAMES is planned to be removed starting v0.9. If the program depends on it, consider moving away from it by employing newer type names directly"
 #  define BYTE xxh_u8
 #  define U8   xxh_u8
 #  define U32  xxh_u32
@@ -1637,18 +2571,19 @@ static xxh_u32 XXH_read32(const void* memPtr) { return *(const xxh_u32*) memPtr;
 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))
 
 /*
- * __pack instructions are safer but compiler specific, hence potentially
- * problematic for some compilers.
- *
- * Currently only defined for GCC and ICC.
+ * __attribute__((aligned(1))) is supported by gcc and clang. Originally the
+ * documentation claimed that it only increased the alignment, but actually it
+ * can decrease it on gcc, clang, and icc:
+ * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502,
+ * https://gcc.godbolt.org/z/xYez1j67Y.
  */
 #ifdef XXH_OLD_NAMES
 typedef union { xxh_u32 u32; } __attribute__((packed)) unalign;
 #endif
 static xxh_u32 XXH_read32(const void* ptr)
 {
-    typedef union { xxh_u32 u32; } __attribute__((packed)) xxh_unalign;
-    return ((const xxh_unalign*)ptr)->u32;
+    typedef __attribute__((aligned(1))) xxh_u32 xxh_unalign32;
+    return *((const xxh_unalign32*)ptr);
 }
 
 #else
@@ -1731,6 +2666,51 @@ static int XXH_isLittleEndian(void)
 #  define XXH_HAS_BUILTIN(x) 0
 #endif
 
+
+
+/*
+ * C23 and future versions have standard "unreachable()".
+ * Once it has been implemented reliably we can add it as an
+ * additional case:
+ *
+ * ```
+ * #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= XXH_C23_VN)
+ * #  include 
+ * #  ifdef unreachable
+ * #    define XXH_UNREACHABLE() unreachable()
+ * #  endif
+ * #endif
+ * ```
+ *
+ * Note C++23 also has std::unreachable() which can be detected
+ * as follows:
+ * ```
+ * #if defined(__cpp_lib_unreachable) && (__cpp_lib_unreachable >= 202202L)
+ * #  include 
+ * #  define XXH_UNREACHABLE() std::unreachable()
+ * #endif
+ * ```
+ * NB: `__cpp_lib_unreachable` is defined in the `` header.
+ * We don't use that as including `` in `extern "C"` blocks
+ * doesn't work on GCC12
+ */
+
+#if XXH_HAS_BUILTIN(__builtin_unreachable)
+#  define XXH_UNREACHABLE() __builtin_unreachable()
+
+#elif defined(_MSC_VER)
+#  define XXH_UNREACHABLE() __assume(0)
+
+#else
+#  define XXH_UNREACHABLE()
+#endif
+
+#if XXH_HAS_BUILTIN(__builtin_assume)
+#  define XXH_ASSUME(c) __builtin_assume(c)
+#else
+#  define XXH_ASSUME(c) if (!(c)) { XXH_UNREACHABLE(); }
+#endif
+
 /*!
  * @internal
  * @def XXH_rotl32(x,r)
@@ -1853,8 +2833,10 @@ XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; }
 *********************************************************************/
 /*!
  * @}
- * @defgroup xxh32_impl XXH32 implementation
+ * @defgroup XXH32_impl XXH32 implementation
  * @ingroup impl
+ *
+ * Details on the XXH32 implementation.
  * @{
  */
  /* #define instead of static const, to be used as initializers */
@@ -1888,7 +2870,7 @@ static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input)
     acc += input * XXH_PRIME32_2;
     acc  = XXH_rotl32(acc, 13);
     acc *= XXH_PRIME32_1;
-#if (defined(__SSE4_1__) || defined(__aarch64__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
+#if (defined(__SSE4_1__) || defined(__aarch64__) || defined(__wasm_simd128__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
     /*
      * UGLY HACK:
      * A compiler fence is the only thing that prevents GCC and Clang from
@@ -1918,9 +2900,12 @@ static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input)
      *   can load data, while v3 can multiply. SSE forces them to operate
      *   together.
      *
-     * This is also enabled on AArch64, as Clang autovectorizes it incorrectly
-     * and it is pointless writing a NEON implementation that is basically the
-     * same speed as scalar for XXH32.
+     * This is also enabled on AArch64, as Clang is *very aggressive* in vectorizing
+     * the loop. NEON is only faster on the A53, and with the newer cores, it is less
+     * than half the speed.
+     *
+     * Additionally, this is used on WASM SIMD128 because it JITs to the same
+     * SIMD instructions and has the same issue.
      */
     XXH_COMPILER_GUARD(acc);
 #endif
@@ -1934,17 +2919,17 @@ static xxh_u32 XXH32_round(xxh_u32 acc, xxh_u32 input)
  * The final mix ensures that all input bits have a chance to impact any bit in
  * the output digest, resulting in an unbiased distribution.
  *
- * @param h32 The hash to avalanche.
+ * @param hash The hash to avalanche.
  * @return The avalanched hash.
  */
-static xxh_u32 XXH32_avalanche(xxh_u32 h32)
+static xxh_u32 XXH32_avalanche(xxh_u32 hash)
 {
-    h32 ^= h32 >> 15;
-    h32 *= XXH_PRIME32_2;
-    h32 ^= h32 >> 13;
-    h32 *= XXH_PRIME32_3;
-    h32 ^= h32 >> 16;
-    return(h32);
+    hash ^= hash >> 15;
+    hash *= XXH_PRIME32_2;
+    hash ^= hash >> 13;
+    hash *= XXH_PRIME32_3;
+    hash ^= hash >> 16;
+    return hash;
 }
 
 #define XXH_get32bits(p) XXH_readLE32_align(p, align)
@@ -1957,24 +2942,25 @@ static xxh_u32 XXH32_avalanche(xxh_u32 h32)
  * This final stage will digest them to ensure that all input bytes are present
  * in the final mix.
  *
- * @param h32 The hash to finalize.
+ * @param hash The hash to finalize.
  * @param ptr The pointer to the remaining input.
  * @param len The remaining length, modulo 16.
  * @param align Whether @p ptr is aligned.
  * @return The finalized hash.
+ * @see XXH64_finalize().
  */
-static xxh_u32
-XXH32_finalize(xxh_u32 h32, const xxh_u8* ptr, size_t len, XXH_alignment align)
+static XXH_PUREF xxh_u32
+XXH32_finalize(xxh_u32 hash, const xxh_u8* ptr, size_t len, XXH_alignment align)
 {
-#define XXH_PROCESS1 do {                           \
-    h32 += (*ptr++) * XXH_PRIME32_5;                \
-    h32 = XXH_rotl32(h32, 11) * XXH_PRIME32_1;      \
+#define XXH_PROCESS1 do {                             \
+    hash += (*ptr++) * XXH_PRIME32_5;                 \
+    hash = XXH_rotl32(hash, 11) * XXH_PRIME32_1;      \
 } while (0)
 
-#define XXH_PROCESS4 do {                           \
-    h32 += XXH_get32bits(ptr) * XXH_PRIME32_3;      \
-    ptr += 4;                                   \
-    h32  = XXH_rotl32(h32, 17) * XXH_PRIME32_4;     \
+#define XXH_PROCESS4 do {                             \
+    hash += XXH_get32bits(ptr) * XXH_PRIME32_3;       \
+    ptr += 4;                                         \
+    hash  = XXH_rotl32(hash, 17) * XXH_PRIME32_4;     \
 } while (0)
 
     if (ptr==NULL) XXH_ASSERT(len == 0);
@@ -1990,49 +2976,49 @@ XXH32_finalize(xxh_u32 h32, const xxh_u8* ptr, size_t len, XXH_alignment align)
             XXH_PROCESS1;
             --len;
         }
-        return XXH32_avalanche(h32);
+        return XXH32_avalanche(hash);
     } else {
          switch(len&15) /* or switch(bEnd - p) */ {
            case 12:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 8:       XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 4:       XXH_PROCESS4;
-                         return XXH32_avalanche(h32);
+                         return XXH32_avalanche(hash);
 
            case 13:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 9:       XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 5:       XXH_PROCESS4;
                          XXH_PROCESS1;
-                         return XXH32_avalanche(h32);
+                         return XXH32_avalanche(hash);
 
            case 14:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 10:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 6:       XXH_PROCESS4;
                          XXH_PROCESS1;
                          XXH_PROCESS1;
-                         return XXH32_avalanche(h32);
+                         return XXH32_avalanche(hash);
 
            case 15:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 11:      XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 7:       XXH_PROCESS4;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 3:       XXH_PROCESS1;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 2:       XXH_PROCESS1;
-                         XXH_FALLTHROUGH;
+                         XXH_FALLTHROUGH;  /* fallthrough */
            case 1:       XXH_PROCESS1;
-                         XXH_FALLTHROUGH;
-           case 0:       return XXH32_avalanche(h32);
+                         XXH_FALLTHROUGH;  /* fallthrough */
+           case 0:       return XXH32_avalanche(hash);
         }
         XXH_ASSERT(0);
-        return h32;   /* reaching this point is deemed impossible */
+        return hash;   /* reaching this point is deemed impossible */
     }
 }
 
@@ -2052,7 +3038,7 @@ XXH32_finalize(xxh_u32 h32, const xxh_u8* ptr, size_t len, XXH_alignment align)
  * @param align Whether @p input is aligned.
  * @return The calculated hash.
  */
-XXH_FORCE_INLINE xxh_u32
+XXH_FORCE_INLINE XXH_PUREF xxh_u32
 XXH32_endian_align(const xxh_u8* input, size_t len, xxh_u32 seed, XXH_alignment align)
 {
     xxh_u32 h32;
@@ -2085,10 +3071,10 @@ XXH32_endian_align(const xxh_u8* input, size_t len, xxh_u32 seed, XXH_alignment
     return XXH32_finalize(h32, input, len&15, align);
 }
 
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t len, XXH32_hash_t seed)
 {
-#if 0
+#if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2
     /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
     XXH32_state_t state;
     XXH32_reset(&state, seed);
@@ -2107,27 +3093,26 @@ XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t len, XXH32_hash_t s
 
 
 /*******   Hash streaming   *******/
-/*!
- * @ingroup xxh32_family
- */
+#ifndef XXH_NO_STREAM
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void)
 {
     return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));
 }
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
 {
     XXH_free(statePtr);
     return XXH_OK;
 }
 
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState)
 {
     XXH_memcpy(dstState, srcState, sizeof(*dstState));
 }
 
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, XXH32_hash_t seed)
 {
     XXH_ASSERT(statePtr != NULL);
@@ -2140,7 +3125,7 @@ XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, XXH32_hash_t s
 }
 
 
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH_errorcode
 XXH32_update(XXH32_state_t* state, const void* input, size_t len)
 {
@@ -2195,7 +3180,7 @@ XXH32_update(XXH32_state_t* state, const void* input, size_t len)
 }
 
 
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t* state)
 {
     xxh_u32 h32;
@@ -2213,31 +3198,18 @@ XXH_PUBLIC_API XXH32_hash_t XXH32_digest(const XXH32_state_t* state)
 
     return XXH32_finalize(h32, (const xxh_u8*)state->mem32, state->memsize, XXH_aligned);
 }
-
+#endif /* !XXH_NO_STREAM */
 
 /*******   Canonical representation   *******/
 
-/*!
- * @ingroup xxh32_family
- * The default return values from XXH functions are unsigned 32 and 64 bit
- * integers.
- *
- * The canonical representation uses big endian convention, the same convention
- * as human-readable numbers (large digits first).
- *
- * This way, hash values can be written into a file or buffer, remaining
- * comparable across different systems.
- *
- * The following functions allow transformation of hash values to and from their
- * canonical format.
- */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash)
 {
-    /* XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); */
+    XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));
     if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash);
     XXH_memcpy(dst, &hash, sizeof(*dst));
 }
-/*! @ingroup xxh32_family */
+/*! @ingroup XXH32_family */
 XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src)
 {
     return XXH_readBE32(src);
@@ -2278,18 +3250,19 @@ static xxh_u64 XXH_read64(const void* memPtr)
 #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))
 
 /*
- * __pack instructions are safer, but compiler specific, hence potentially
- * problematic for some compilers.
- *
- * Currently only defined for GCC and ICC.
+ * __attribute__((aligned(1))) is supported by gcc and clang. Originally the
+ * documentation claimed that it only increased the alignment, but actually it
+ * can decrease it on gcc, clang, and icc:
+ * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69502,
+ * https://gcc.godbolt.org/z/xYez1j67Y.
  */
 #ifdef XXH_OLD_NAMES
 typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((packed)) unalign64;
 #endif
 static xxh_u64 XXH_read64(const void* ptr)
 {
-    typedef union { xxh_u32 u32; xxh_u64 u64; } __attribute__((packed)) xxh_unalign64;
-    return ((const xxh_unalign64*)ptr)->u64;
+    typedef __attribute__((aligned(1))) xxh_u64 xxh_unalign64;
+    return *((const xxh_unalign64*)ptr);
 }
 
 #else
@@ -2380,8 +3353,10 @@ XXH_readLE64_align(const void* ptr, XXH_alignment align)
 /*******   xxh64   *******/
 /*!
  * @}
- * @defgroup xxh64_impl XXH64 implementation
+ * @defgroup XXH64_impl XXH64 implementation
  * @ingroup impl
+ *
+ * Details on the XXH64 implementation.
  * @{
  */
 /* #define rather that static const, to be used as initializers */
@@ -2399,6 +3374,7 @@ XXH_readLE64_align(const void* ptr, XXH_alignment align)
 #  define PRIME64_5 XXH_PRIME64_5
 #endif
 
+/*! @copydoc XXH32_round */
 static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input)
 {
     acc += input * XXH_PRIME64_2;
@@ -2415,43 +3391,59 @@ static xxh_u64 XXH64_mergeRound(xxh_u64 acc, xxh_u64 val)
     return acc;
 }
 
-static xxh_u64 XXH64_avalanche(xxh_u64 h64)
+/*! @copydoc XXH32_avalanche */
+static xxh_u64 XXH64_avalanche(xxh_u64 hash)
 {
-    h64 ^= h64 >> 33;
-    h64 *= XXH_PRIME64_2;
-    h64 ^= h64 >> 29;
-    h64 *= XXH_PRIME64_3;
-    h64 ^= h64 >> 32;
-    return h64;
+    hash ^= hash >> 33;
+    hash *= XXH_PRIME64_2;
+    hash ^= hash >> 29;
+    hash *= XXH_PRIME64_3;
+    hash ^= hash >> 32;
+    return hash;
 }
 
 
 #define XXH_get64bits(p) XXH_readLE64_align(p, align)
 
-static xxh_u64
-XXH64_finalize(xxh_u64 h64, const xxh_u8* ptr, size_t len, XXH_alignment align)
+/*!
+ * @internal
+ * @brief Processes the last 0-31 bytes of @p ptr.
+ *
+ * There may be up to 31 bytes remaining to consume from the input.
+ * This final stage will digest them to ensure that all input bytes are present
+ * in the final mix.
+ *
+ * @param hash The hash to finalize.
+ * @param ptr The pointer to the remaining input.
+ * @param len The remaining length, modulo 32.
+ * @param align Whether @p ptr is aligned.
+ * @return The finalized hash
+ * @see XXH32_finalize().
+ */
+static XXH_PUREF xxh_u64
+XXH64_finalize(xxh_u64 hash, const xxh_u8* ptr, size_t len, XXH_alignment align)
 {
     if (ptr==NULL) XXH_ASSERT(len == 0);
     len &= 31;
     while (len >= 8) {
         xxh_u64 const k1 = XXH64_round(0, XXH_get64bits(ptr));
         ptr += 8;
-        h64 ^= k1;
-        h64  = XXH_rotl64(h64,27) * XXH_PRIME64_1 + XXH_PRIME64_4;
+        hash ^= k1;
+        hash  = XXH_rotl64(hash,27) * XXH_PRIME64_1 + XXH_PRIME64_4;
         len -= 8;
     }
     if (len >= 4) {
-        h64 ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1;
+        hash ^= (xxh_u64)(XXH_get32bits(ptr)) * XXH_PRIME64_1;
         ptr += 4;
-        h64 = XXH_rotl64(h64, 23) * XXH_PRIME64_2 + XXH_PRIME64_3;
+        hash = XXH_rotl64(hash, 23) * XXH_PRIME64_2 + XXH_PRIME64_3;
         len -= 4;
     }
     while (len > 0) {
-        h64 ^= (*ptr++) * XXH_PRIME64_5;
-        h64 = XXH_rotl64(h64, 11) * XXH_PRIME64_1;
+        hash ^= (*ptr++) * XXH_PRIME64_5;
+        hash = XXH_rotl64(hash, 11) * XXH_PRIME64_1;
         --len;
     }
-    return  XXH64_avalanche(h64);
+    return  XXH64_avalanche(hash);
 }
 
 #ifdef XXH_OLD_NAMES
@@ -2464,7 +3456,15 @@ XXH64_finalize(xxh_u64 h64, const xxh_u8* ptr, size_t len, XXH_alignment align)
 #  undef XXH_PROCESS8_64
 #endif
 
-XXH_FORCE_INLINE xxh_u64
+/*!
+ * @internal
+ * @brief The implementation for @ref XXH64().
+ *
+ * @param input , len , seed Directly passed from @ref XXH64().
+ * @param align Whether @p input is aligned.
+ * @return The calculated hash.
+ */
+XXH_FORCE_INLINE XXH_PUREF xxh_u64
 XXH64_endian_align(const xxh_u8* input, size_t len, xxh_u64 seed, XXH_alignment align)
 {
     xxh_u64 h64;
@@ -2501,10 +3501,10 @@ XXH64_endian_align(const xxh_u8* input, size_t len, xxh_u64 seed, XXH_alignment
 }
 
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t len, XXH64_hash_t seed)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API XXH64_hash_t XXH64 (XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed)
 {
-#if 0
+#if !defined(XXH_NO_STREAM) && XXH_SIZE_OPT >= 2
     /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
     XXH64_state_t state;
     XXH64_reset(&state, seed);
@@ -2522,27 +3522,27 @@ XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t len, XXH64_hash_t s
 }
 
 /*******   Hash Streaming   *******/
-
-/*! @ingroup xxh64_family*/
+#ifndef XXH_NO_STREAM
+/*! @ingroup XXH64_family*/
 XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void)
 {
     return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));
 }
-/*! @ingroup xxh64_family */
+/*! @ingroup XXH64_family */
 XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
 {
     XXH_free(statePtr);
     return XXH_OK;
 }
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dstState, const XXH64_state_t* srcState)
 {
     XXH_memcpy(dstState, srcState, sizeof(*dstState));
 }
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, XXH64_hash_t seed)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed)
 {
     XXH_ASSERT(statePtr != NULL);
     memset(statePtr, 0, sizeof(*statePtr));
@@ -2553,9 +3553,9 @@ XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, XXH64_hash_t s
     return XXH_OK;
 }
 
-/*! @ingroup xxh64_family */
+/*! @ingroup XXH64_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH64_update (XXH64_state_t* state, const void* input, size_t len)
+XXH64_update (XXH_NOESCAPE XXH64_state_t* state, XXH_NOESCAPE const void* input, size_t len)
 {
     if (input==NULL) {
         XXH_ASSERT(len == 0);
@@ -2605,8 +3605,8 @@ XXH64_update (XXH64_state_t* state, const void* input, size_t len)
 }
 
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API XXH64_hash_t XXH64_digest(const XXH64_state_t* state)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API XXH64_hash_t XXH64_digest(XXH_NOESCAPE const XXH64_state_t* state)
 {
     xxh_u64 h64;
 
@@ -2624,20 +3624,20 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_digest(const XXH64_state_t* state)
 
     return XXH64_finalize(h64, (const xxh_u8*)state->mem64, (size_t)state->total_len, XXH_aligned);
 }
-
+#endif /* !XXH_NO_STREAM */
 
 /******* Canonical representation   *******/
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH_NOESCAPE XXH64_canonical_t* dst, XXH64_hash_t hash)
 {
-    /* XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); */
+    XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));
     if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash);
     XXH_memcpy(dst, &hash, sizeof(*dst));
 }
 
-/*! @ingroup xxh64_family */
-XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src)
+/*! @ingroup XXH64_family */
+XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_canonical_t* src)
 {
     return XXH_readBE64(src);
 }
@@ -2650,7 +3650,7 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
 ************************************************************************ */
 /*!
  * @}
- * @defgroup xxh3_impl XXH3 implementation
+ * @defgroup XXH3_impl XXH3 implementation
  * @ingroup impl
  * @{
  */
@@ -2658,11 +3658,19 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
 /* ===   Compiler specifics   === */
 
 #if ((defined(sun) || defined(__sun)) && __cplusplus) /* Solaris includes __STDC_VERSION__ with C++. Tested with GCC 5.5 */
-#  define XXH_RESTRICT /* disable */
+#  define XXH_RESTRICT   /* disable */
 #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* >= C99 */
 #  define XXH_RESTRICT   restrict
+#elif (defined (__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))) \
+   || (defined (__clang__)) \
+   || (defined (_MSC_VER) && (_MSC_VER >= 1400)) \
+   || (defined (__INTEL_COMPILER) && (__INTEL_COMPILER >= 1300))
+/*
+ * There are a LOT more compilers that recognize __restrict but this
+ * covers the major ones.
+ */
+#  define XXH_RESTRICT   __restrict
 #else
-/* Note: it might be useful to define __restrict or __restrict__ for some C++ compilers */
 #  define XXH_RESTRICT   /* disable */
 #endif
 
@@ -2676,10 +3684,26 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
 #    define XXH_unlikely(x) (x)
 #endif
 
+#ifndef XXH_HAS_INCLUDE
+#  ifdef __has_include
+/*
+ * Not defined as XXH_HAS_INCLUDE(x) (function-like) because
+ * this causes segfaults in Apple Clang 4.2 (on Mac OS X 10.7 Lion)
+ */
+#    define XXH_HAS_INCLUDE __has_include
+#  else
+#    define XXH_HAS_INCLUDE(x) 0
+#  endif
+#endif
+
 #if defined(__GNUC__) || defined(__clang__)
+#  if defined(__ARM_FEATURE_SVE)
+#    include 
+#  endif
 #  if defined(__ARM_NEON__) || defined(__ARM_NEON) \
-   || defined(__aarch64__)  || defined(_M_ARM) \
-   || defined(_M_ARM64)     || defined(_M_ARM64EC)
+   || (defined(_M_ARM) && _M_ARM >= 7) \
+   || defined(_M_ARM64) || defined(_M_ARM64EC) \
+   || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* WASM SIMD128 via SIMDe */
 #    define inline __inline__  /* circumvent a clang bug */
 #    include 
 #    undef inline
@@ -2790,7 +3814,7 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src
  * Note that these are actually implemented as macros.
  *
  * If this is not defined, it is detected automatically.
- * @ref XXH_X86DISPATCH overrides this.
+ * internal macro XXH_X86DISPATCH overrides this.
  */
 enum XXH_VECTOR_TYPE /* fake enum */ {
     XXH_SCALAR = 0,  /*!< Portable scalar version */
@@ -2802,8 +3826,13 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
                       */
     XXH_AVX2   = 2,  /*!< AVX2 for Haswell and Bulldozer */
     XXH_AVX512 = 3,  /*!< AVX512 for Skylake and Icelake */
-    XXH_NEON   = 4,  /*!< NEON for most ARMv7-A and all AArch64 */
+    XXH_NEON   = 4,  /*!<
+                       * NEON for most ARMv7-A, all AArch64, and WASM SIMD128
+                       * via the SIMDeverywhere polyfill provided with the
+                       * Emscripten SDK.
+                       */
     XXH_VSX    = 5,  /*!< VSX and ZVector for POWER8/z13 (64-bit) */
+    XXH_SVE    = 6,  /*!< SVE for some ARMv8-A and ARMv9-A */
 };
 /*!
  * @ingroup tuning
@@ -2825,12 +3854,16 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #  define XXH_AVX512 3
 #  define XXH_NEON   4
 #  define XXH_VSX    5
+#  define XXH_SVE    6
 #endif
 
 #ifndef XXH_VECTOR    /* can be defined on command line */
-#  if ( \
+#  if defined(__ARM_FEATURE_SVE)
+#    define XXH_VECTOR XXH_SVE
+#  elif ( \
         defined(__ARM_NEON__) || defined(__ARM_NEON) /* gcc */ \
      || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) /* msvc */ \
+     || (defined(__wasm_simd128__) && XXH_HAS_INCLUDE()) /* wasm simd128 via SIMDe */ \
    ) && ( \
         defined(_WIN32) || defined(__LITTLE_ENDIAN__) /* little endian only */ \
     || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \
@@ -2851,6 +3884,17 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #  endif
 #endif
 
+/* __ARM_FEATURE_SVE is only supported by GCC & Clang. */
+#if (XXH_VECTOR == XXH_SVE) && !defined(__ARM_FEATURE_SVE)
+#  ifdef _MSC_VER
+#    pragma warning(once : 4606)
+#  else
+#    warning "__ARM_FEATURE_SVE isn't supported. Use SCALAR instead."
+#  endif
+#  undef XXH_VECTOR
+#  define XXH_VECTOR XXH_SCALAR
+#endif
+
 /*
  * Controls the alignment of the accumulator,
  * for compatibility with aligned vector loads, which are usually faster.
@@ -2870,16 +3914,26 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #     define XXH_ACC_ALIGN 16
 #  elif XXH_VECTOR == XXH_AVX512  /* avx512 */
 #     define XXH_ACC_ALIGN 64
+#  elif XXH_VECTOR == XXH_SVE   /* sve */
+#     define XXH_ACC_ALIGN 64
 #  endif
 #endif
 
 #if defined(XXH_X86DISPATCH) || XXH_VECTOR == XXH_SSE2 \
     || XXH_VECTOR == XXH_AVX2 || XXH_VECTOR == XXH_AVX512
 #  define XXH_SEC_ALIGN XXH_ACC_ALIGN
+#elif XXH_VECTOR == XXH_SVE
+#  define XXH_SEC_ALIGN XXH_ACC_ALIGN
 #else
 #  define XXH_SEC_ALIGN 8
 #endif
 
+#if defined(__GNUC__) || defined(__clang__)
+#  define XXH_ALIASING __attribute__((may_alias))
+#else
+#  define XXH_ALIASING /* nothing */
+#endif
+
 /*
  * UGLY HACK:
  * GCC usually generates the best code with -O3 for xxHash.
@@ -2903,153 +3957,126 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
  */
 #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
   && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
-  && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
+  && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */
 #  pragma GCC push_options
 #  pragma GCC optimize("-O2")
 #endif
 
-
 #if XXH_VECTOR == XXH_NEON
+
 /*
- * NEON's setup for vmlal_u32 is a little more complicated than it is on
- * SSE2, AVX2, and VSX.
+ * UGLY HACK: While AArch64 GCC on Linux does not seem to care, on macOS, GCC -O3
+ * optimizes out the entire hashLong loop because of the aliasing violation.
  *
- * While PMULUDQ and VMULEUW both perform a mask, VMLAL.U32 performs an upcast.
- *
- * To do the same operation, the 128-bit 'Q' register needs to be split into
- * two 64-bit 'D' registers, performing this operation::
- *
- *   [                a                 |                 b                ]
- *            |              '---------. .--------'                |
- *            |                         x                          |
- *            |              .---------' '--------.                |
- *   [ a & 0xFFFFFFFF | b & 0xFFFFFFFF ],[    a >> 32     |     b >> 32    ]
- *
- * Due to significant changes in aarch64, the fastest method for aarch64 is
- * completely different than the fastest method for ARMv7-A.
- *
- * ARMv7-A treats D registers as unions overlaying Q registers, so modifying
- * D11 will modify the high half of Q5. This is similar to how modifying AH
- * will only affect bits 8-15 of AX on x86.
- *
- * VZIP takes two registers, and puts even lanes in one register and odd lanes
- * in the other.
- *
- * On ARMv7-A, this strangely modifies both parameters in place instead of
- * taking the usual 3-operand form.
- *
- * Therefore, if we want to do this, we can simply use a D-form VZIP.32 on the
- * lower and upper halves of the Q register to end up with the high and low
- * halves where we want - all in one instruction.
- *
- *   vzip.32   d10, d11       @ d10 = { d10[0], d11[0] }; d11 = { d10[1], d11[1] }
- *
- * Unfortunately we need inline assembly for this: Instructions modifying two
- * registers at once is not possible in GCC or Clang's IR, and they have to
- * create a copy.
- *
- * aarch64 requires a different approach.
- *
- * In order to make it easier to write a decent compiler for aarch64, many
- * quirks were removed, such as conditional execution.
- *
- * NEON was also affected by this.
- *
- * aarch64 cannot access the high bits of a Q-form register, and writes to a
- * D-form register zero the high bits, similar to how writes to W-form scalar
- * registers (or DWORD registers on x86_64) work.
- *
- * The formerly free vget_high intrinsics now require a vext (with a few
- * exceptions)
- *
- * Additionally, VZIP was replaced by ZIP1 and ZIP2, which are the equivalent
- * of PUNPCKL* and PUNPCKH* in SSE, respectively, in order to only modify one
- * operand.
- *
- * The equivalent of the VZIP.32 on the lower and upper halves would be this
- * mess:
- *
- *   ext     v2.4s, v0.4s, v0.4s, #2 // v2 = { v0[2], v0[3], v0[0], v0[1] }
- *   zip1    v1.2s, v0.2s, v2.2s     // v1 = { v0[0], v2[0] }
- *   zip2    v0.2s, v0.2s, v1.2s     // v0 = { v0[1], v2[1] }
- *
- * Instead, we use a literal downcast, vmovn_u64 (XTN), and vshrn_n_u64 (SHRN):
- *
- *   shrn    v1.2s, v0.2d, #32  // v1 = (uint32x2_t)(v0 >> 32);
- *   xtn     v0.2s, v0.2d       // v0 = (uint32x2_t)(v0 & 0xFFFFFFFF);
- *
- * This is available on ARMv7-A, but is less efficient than a single VZIP.32.
+ * However, GCC is also inefficient at load-store optimization with vld1q/vst1q,
+ * so the only option is to mark it as aliasing.
  */
+typedef uint64x2_t xxh_aliasing_uint64x2_t XXH_ALIASING;
 
 /*!
- * Function-like macro:
- * void XXH_SPLIT_IN_PLACE(uint64x2_t &in, uint32x2_t &outLo, uint32x2_t &outHi)
- * {
- *     outLo = (uint32x2_t)(in & 0xFFFFFFFF);
- *     outHi = (uint32x2_t)(in >> 32);
- *     in = UNDEFINED;
- * }
+ * @internal
+ * @brief `vld1q_u64` but faster and alignment-safe.
+ *
+ * On AArch64, unaligned access is always safe, but on ARMv7-a, it is only
+ * *conditionally* safe (`vld1` has an alignment bit like `movdq[ua]` in x86).
+ *
+ * GCC for AArch64 sees `vld1q_u8` as an intrinsic instead of a load, so it
+ * prohibits load-store optimizations. Therefore, a direct dereference is used.
+ *
+ * Otherwise, `vld1q_u8` is used with `vreinterpretq_u8_u64` to do a safe
+ * unaligned load.
  */
-# if !defined(XXH_NO_VZIP_HACK) /* define to disable */ \
-   && (defined(__GNUC__) || defined(__clang__)) \
-   && (defined(__arm__) || defined(__thumb__) || defined(_M_ARM))
-#  define XXH_SPLIT_IN_PLACE(in, outLo, outHi)                                              \
-    do {                                                                                    \
-      /* Undocumented GCC/Clang operand modifier: %e0 = lower D half, %f0 = upper D half */ \
-      /* https://github.com/gcc-mirror/gcc/blob/38cf91e5/gcc/config/arm/arm.c#L22486 */     \
-      /* https://github.com/llvm-mirror/llvm/blob/2c4ca683/lib/Target/ARM/ARMAsmPrinter.cpp#L399 */ \
-      __asm__("vzip.32  %e0, %f0" : "+w" (in));                                             \
-      (outLo) = vget_low_u32 (vreinterpretq_u32_u64(in));                                   \
-      (outHi) = vget_high_u32(vreinterpretq_u32_u64(in));                                   \
-   } while (0)
-# else
-#  define XXH_SPLIT_IN_PLACE(in, outLo, outHi)                                            \
-    do {                                                                                  \
-      (outLo) = vmovn_u64    (in);                                                        \
-      (outHi) = vshrn_n_u64  ((in), 32);                                                  \
-    } while (0)
-# endif
+#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__)
+XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr) /* silence -Wcast-align */
+{
+    return *(xxh_aliasing_uint64x2_t const *)ptr;
+}
+#else
+XXH_FORCE_INLINE uint64x2_t XXH_vld1q_u64(void const* ptr)
+{
+    return vreinterpretq_u64_u8(vld1q_u8((uint8_t const*)ptr));
+}
+#endif
+
+/*!
+ * @internal
+ * @brief `vmlal_u32` on low and high halves of a vector.
+ *
+ * This is a workaround for AArch64 GCC < 11 which implemented arm_neon.h with
+ * inline assembly and were therefore incapable of merging the `vget_{low, high}_u32`
+ * with `vmlal_u32`.
+ */
+#if defined(__aarch64__) && defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 11
+XXH_FORCE_INLINE uint64x2_t
+XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
+{
+    /* Inline assembly is the only way */
+    __asm__("umlal   %0.2d, %1.2s, %2.2s" : "+w" (acc) : "w" (lhs), "w" (rhs));
+    return acc;
+}
+XXH_FORCE_INLINE uint64x2_t
+XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
+{
+    /* This intrinsic works as expected */
+    return vmlal_high_u32(acc, lhs, rhs);
+}
+#else
+/* Portable intrinsic versions */
+XXH_FORCE_INLINE uint64x2_t
+XXH_vmlal_low_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
+{
+    return vmlal_u32(acc, vget_low_u32(lhs), vget_low_u32(rhs));
+}
+/*! @copydoc XXH_vmlal_low_u32
+ * Assume the compiler converts this to vmlal_high_u32 on aarch64 */
+XXH_FORCE_INLINE uint64x2_t
+XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
+{
+    return vmlal_u32(acc, vget_high_u32(lhs), vget_high_u32(rhs));
+}
+#endif
 
 /*!
  * @ingroup tuning
  * @brief Controls the NEON to scalar ratio for XXH3
  *
- * On AArch64 when not optimizing for size, XXH3 will run 6 lanes using NEON and
- * 2 lanes on scalar by default.
+ * This can be set to 2, 4, 6, or 8.
  *
- * This can be set to 2, 4, 6, or 8. ARMv7 will default to all 8 NEON lanes, as the
- * emulated 64-bit arithmetic is too slow.
+ * ARM Cortex CPUs are _very_ sensitive to how their pipelines are used.
  *
- * Modern ARM CPUs are _very_ sensitive to how their pipelines are used.
+ * For example, the Cortex-A73 can dispatch 3 micro-ops per cycle, but only 2 of those
+ * can be NEON. If you are only using NEON instructions, you are only using 2/3 of the CPU
+ * bandwidth.
  *
- * For example, the Cortex-A73 can dispatch 3 micro-ops per cycle, but it can't
- * have more than 2 NEON (F0/F1) micro-ops. If you are only using NEON instructions,
- * you are only using 2/3 of the CPU bandwidth.
- *
- * This is even more noticeable on the more advanced cores like the A76 which
+ * This is even more noticeable on the more advanced cores like the Cortex-A76 which
  * can dispatch 8 micro-ops per cycle, but still only 2 NEON micro-ops at once.
  *
- * Therefore, @ref XXH3_NEON_LANES lanes will be processed using NEON, and the
- * remaining lanes will use scalar instructions. This improves the bandwidth
- * and also gives the integer pipelines something to do besides twiddling loop
- * counters and pointers.
+ * Therefore, to make the most out of the pipeline, it is beneficial to run 6 NEON lanes
+ * and 2 scalar lanes, which is chosen by default.
+ *
+ * This does not apply to Apple processors or 32-bit processors, which run better with
+ * full NEON. These will default to 8. Additionally, size-optimized builds run 8 lanes.
  *
  * This change benefits CPUs with large micro-op buffers without negatively affecting
- * other CPUs:
+ * most other CPUs:
  *
  *  | Chipset               | Dispatch type       | NEON only | 6:2 hybrid | Diff. |
  *  |:----------------------|:--------------------|----------:|-----------:|------:|
  *  | Snapdragon 730 (A76)  | 2 NEON/8 micro-ops  |  8.8 GB/s |  10.1 GB/s |  ~16% |
  *  | Snapdragon 835 (A73)  | 2 NEON/3 micro-ops  |  5.1 GB/s |   5.3 GB/s |   ~5% |
  *  | Marvell PXA1928 (A53) | In-order dual-issue |  1.9 GB/s |   1.9 GB/s |    0% |
+ *  | Apple M1              | 4 NEON/8 micro-ops  | 37.3 GB/s |  36.1 GB/s |  ~-3% |
  *
  * It also seems to fix some bad codegen on GCC, making it almost as fast as clang.
  *
+ * When using WASM SIMD128, if this is 2 or 6, SIMDe will scalarize 2 of the lanes meaning
+ * it effectively becomes worse 4.
+ *
  * @see XXH3_accumulate_512_neon()
  */
 # ifndef XXH3_NEON_LANES
 #  if (defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) \
-   && !defined(__OPTIMIZE_SIZE__)
+   && !defined(__APPLE__) && XXH_SIZE_OPT <= 0
 #   define XXH3_NEON_LANES 6
 #  else
 #   define XXH3_NEON_LANES XXH_ACC_NB
@@ -3066,27 +4093,42 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
  * inconsistent intrinsics, spotty coverage, and multiple endiannesses.
  */
 #if XXH_VECTOR == XXH_VSX
+/* Annoyingly, these headers _may_ define three macros: `bool`, `vector`,
+ * and `pixel`. This is a problem for obvious reasons.
+ *
+ * These keywords are unnecessary; the spec literally says they are
+ * equivalent to `__bool`, `__vector`, and `__pixel` and may be undef'd
+ * after including the header.
+ *
+ * We use pragma push_macro/pop_macro to keep the namespace clean. */
+#  pragma push_macro("bool")
+#  pragma push_macro("vector")
+#  pragma push_macro("pixel")
+/* silence potential macro redefined warnings */
+#  undef bool
+#  undef vector
+#  undef pixel
+
 #  if defined(__s390x__)
 #    include 
 #  else
-/* gcc's altivec.h can have the unwanted consequence to unconditionally
- * #define bool, vector, and pixel keywords,
- * with bad consequences for programs already using these keywords for other purposes.
- * The paragraph defining these macros is skipped when __APPLE_ALTIVEC__ is defined.
- * __APPLE_ALTIVEC__ is _generally_ defined automatically by the compiler,
- * but it seems that, in some cases, it isn't.
- * Force the build macro to be defined, so that keywords are not altered.
- */
-#    if defined(__GNUC__) && !defined(__APPLE_ALTIVEC__)
-#      define __APPLE_ALTIVEC__
-#    endif
 #    include 
 #  endif
 
+/* Restore the original macro values, if applicable. */
+#  pragma pop_macro("pixel")
+#  pragma pop_macro("vector")
+#  pragma pop_macro("bool")
+
 typedef __vector unsigned long long xxh_u64x2;
 typedef __vector unsigned char xxh_u8x16;
 typedef __vector unsigned xxh_u32x4;
 
+/*
+ * UGLY HACK: Similar to aarch64 macOS GCC, s390x GCC has the same aliasing issue.
+ */
+typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING;
+
 # ifndef XXH_VSX_BE
 #  if defined(__BIG_ENDIAN__) \
   || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
@@ -3138,8 +4180,9 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_loadu(const void *ptr)
  /* s390x is always big endian, no issue on this platform */
 #  define XXH_vec_mulo vec_mulo
 #  define XXH_vec_mule vec_mule
-# elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw)
+# elif defined(__clang__) && XXH_HAS_BUILTIN(__builtin_altivec_vmuleuw) && !defined(__ibmxl__)
 /* Clang has a better way to control this, we can just use the builtin which doesn't swap. */
+ /* The IBM XL Compiler (which defined __clang__) only implements the vec_* operations */
 #  define XXH_vec_mulo __builtin_altivec_vmulouw
 #  define XXH_vec_mule __builtin_altivec_vmuleuw
 # else
@@ -3160,13 +4203,28 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
 # endif /* XXH_vec_mulo, XXH_vec_mule */
 #endif /* XXH_VECTOR == XXH_VSX */
 
+#if XXH_VECTOR == XXH_SVE
+#define ACCRND(acc, offset) \
+do { \
+    svuint64_t input_vec = svld1_u64(mask, xinput + offset);         \
+    svuint64_t secret_vec = svld1_u64(mask, xsecret + offset);       \
+    svuint64_t mixed = sveor_u64_x(mask, secret_vec, input_vec);     \
+    svuint64_t swapped = svtbl_u64(input_vec, kSwap);                \
+    svuint64_t mixed_lo = svextw_u64_x(mask, mixed);                 \
+    svuint64_t mixed_hi = svlsr_n_u64_x(mask, mixed, 32);            \
+    svuint64_t mul = svmad_u64_x(mask, mixed_lo, mixed_hi, swapped); \
+    acc = svadd_u64_x(mask, acc, mul);                               \
+} while (0)
+#endif /* XXH_VECTOR == XXH_SVE */
 
 /* prefetch
  * can be disabled, by declaring XXH_NO_PREFETCH build macro */
 #if defined(XXH_NO_PREFETCH)
 #  define XXH_PREFETCH(ptr)  (void)(ptr)  /* disabled */
 #else
-#  if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) && !defined(_M_ARM64EC)  /* _mm_prefetch() not defined outside of x86/x64 */
+#  if XXH_SIZE_OPT >= 1
+#    define XXH_PREFETCH(ptr) (void)(ptr)
+#  elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))  /* _mm_prefetch() not defined outside of x86/x64 */
 #    include    /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
 #    define XXH_PREFETCH(ptr)  _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
 #  elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )
@@ -3203,6 +4261,8 @@ XXH_ALIGN(64) static const xxh_u8 XXH3_kSecret[XXH_SECRET_DEFAULT_SIZE] = {
     0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
 };
 
+static const xxh_u64 PRIME_MX1 = 0x165667919E3779F9ULL;  /*!< 0b0001011001010110011001111001000110011110001101110111100111111001 */
+static const xxh_u64 PRIME_MX2 = 0x9FB21C651E98DF25ULL;  /*!< 0b1001111110110010000111000110010100011110100110001101111100100101 */
 
 #ifdef XXH_OLD_NAMES
 #  define kSecret XXH3_kSecret
@@ -3394,7 +4454,7 @@ XXH3_mul128_fold64(xxh_u64 lhs, xxh_u64 rhs)
 }
 
 /*! Seems to produce slightly better code on GCC for some reason. */
-XXH_FORCE_INLINE xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift)
+XXH_FORCE_INLINE XXH_CONSTF xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift)
 {
     XXH_ASSERT(0 <= shift && shift < 64);
     return v64 ^ (v64 >> shift);
@@ -3407,7 +4467,7 @@ XXH_FORCE_INLINE xxh_u64 XXH_xorshift64(xxh_u64 v64, int shift)
 static XXH64_hash_t XXH3_avalanche(xxh_u64 h64)
 {
     h64 = XXH_xorshift64(h64, 37);
-    h64 *= 0x165667919E3779F9ULL;
+    h64 *= PRIME_MX1;
     h64 = XXH_xorshift64(h64, 32);
     return h64;
 }
@@ -3421,9 +4481,9 @@ static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len)
 {
     /* this mix is inspired by Pelle Evensen's rrmxmx */
     h64 ^= XXH_rotl64(h64, 49) ^ XXH_rotl64(h64, 24);
-    h64 *= 0x9FB21C651E98DF25ULL;
+    h64 *= PRIME_MX2;
     h64 ^= (h64 >> 35) + len ;
-    h64 *= 0x9FB21C651E98DF25ULL;
+    h64 *= PRIME_MX2;
     return XXH_xorshift64(h64, 28);
 }
 
@@ -3461,7 +4521,7 @@ static XXH64_hash_t XXH3_rrmxmx(xxh_u64 h64, xxh_u64 len)
  *
  * This adds an extra layer of strength for custom secrets.
  */
-XXH_FORCE_INLINE XXH64_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(input != NULL);
@@ -3483,7 +4543,7 @@ XXH3_len_1to3_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_h
     }
 }
 
-XXH_FORCE_INLINE XXH64_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(input != NULL);
@@ -3499,7 +4559,7 @@ XXH3_len_4to8_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_h
     }
 }
 
-XXH_FORCE_INLINE XXH64_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(input != NULL);
@@ -3516,7 +4576,7 @@ XXH3_len_9to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_
     }
 }
 
-XXH_FORCE_INLINE XXH64_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_0to16_64b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(len <= 16);
@@ -3586,7 +4646,7 @@ XXH_FORCE_INLINE xxh_u64 XXH3_mix16B(const xxh_u8* XXH_RESTRICT input,
 }
 
 /* For mid range keys, XXH3 uses a Mum-hash variant. */
-XXH_FORCE_INLINE XXH64_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
                      const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
                      XXH64_hash_t seed)
@@ -3595,6 +4655,14 @@ XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
     XXH_ASSERT(16 < len && len <= 128);
 
     {   xxh_u64 acc = len * XXH_PRIME64_1;
+#if XXH_SIZE_OPT >= 1
+        /* Smaller and cleaner, but slightly slower. */
+        unsigned int i = (unsigned int)(len - 1) / 32;
+        do {
+            acc += XXH3_mix16B(input+16 * i, secret+32*i, seed);
+            acc += XXH3_mix16B(input+len-16*(i+1), secret+32*i+16, seed);
+        } while (i-- != 0);
+#else
         if (len > 32) {
             if (len > 64) {
                 if (len > 96) {
@@ -3609,14 +4677,17 @@ XXH3_len_17to128_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
         }
         acc += XXH3_mix16B(input+0, secret+0, seed);
         acc += XXH3_mix16B(input+len-16, secret+16, seed);
-
+#endif
         return XXH3_avalanche(acc);
     }
 }
 
+/*!
+ * @brief Maximum size of "short" key in bytes.
+ */
 #define XXH3_MIDSIZE_MAX 240
 
-XXH_NO_INLINE XXH64_hash_t
+XXH_NO_INLINE XXH_PUREF XXH64_hash_t
 XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
                       XXH64_hash_t seed)
@@ -3628,13 +4699,17 @@ XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
     #define XXH3_MIDSIZE_LASTOFFSET  17
 
     {   xxh_u64 acc = len * XXH_PRIME64_1;
-        int const nbRounds = (int)len / 16;
-        int i;
+        xxh_u64 acc_end;
+        unsigned int const nbRounds = (unsigned int)len / 16;
+        unsigned int i;
+        XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
         for (i=0; i<8; i++) {
             acc += XXH3_mix16B(input+(16*i), secret+(16*i), seed);
         }
-        acc = XXH3_avalanche(acc);
+        /* last bytes */
+        acc_end = XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
         XXH_ASSERT(nbRounds >= 8);
+        acc = XXH3_avalanche(acc);
 #if defined(__clang__)                                /* Clang */ \
     && (defined(__ARM_NEON) || defined(__ARM_NEON__)) /* NEON */ \
     && !defined(XXH_ENABLE_AUTOVECTORIZE)             /* Define to disable */
@@ -3661,11 +4736,13 @@ XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
         #pragma clang loop vectorize(disable)
 #endif
         for (i=8 ; i < nbRounds; i++) {
-            acc += XXH3_mix16B(input+(16*i), secret+(16*(i-8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
+            /*
+             * Prevents clang for unrolling the acc loop and interleaving with this one.
+             */
+            XXH_COMPILER_GUARD(acc);
+            acc_end += XXH3_mix16B(input+(16*i), secret+(16*(i-8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
         }
-        /* last bytes */
-        acc += XXH3_mix16B(input + len - 16, secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
-        return XXH3_avalanche(acc);
+        return XXH3_avalanche(acc + acc_end);
     }
 }
 
@@ -3681,6 +4758,47 @@ XXH3_len_129to240_64b(const xxh_u8* XXH_RESTRICT input, size_t len,
 #  define ACC_NB XXH_ACC_NB
 #endif
 
+#ifndef XXH_PREFETCH_DIST
+#  ifdef __clang__
+#    define XXH_PREFETCH_DIST 320
+#  else
+#    if (XXH_VECTOR == XXH_AVX512)
+#      define XXH_PREFETCH_DIST 512
+#    else
+#      define XXH_PREFETCH_DIST 384
+#    endif
+#  endif  /* __clang__ */
+#endif  /* XXH_PREFETCH_DIST */
+
+/*
+ * These macros are to generate an XXH3_accumulate() function.
+ * The two arguments select the name suffix and target attribute.
+ *
+ * The name of this symbol is XXH3_accumulate_() and it calls
+ * XXH3_accumulate_512_().
+ *
+ * It may be useful to hand implement this function if the compiler fails to
+ * optimize the inline function.
+ */
+#define XXH3_ACCUMULATE_TEMPLATE(name)                      \
+void                                                        \
+XXH3_accumulate_##name(xxh_u64* XXH_RESTRICT acc,           \
+                       const xxh_u8* XXH_RESTRICT input,    \
+                       const xxh_u8* XXH_RESTRICT secret,   \
+                       size_t nbStripes)                    \
+{                                                           \
+    size_t n;                                               \
+    for (n = 0; n < nbStripes; n++ ) {                      \
+        const xxh_u8* const in = input + n*XXH_STRIPE_LEN;  \
+        XXH_PREFETCH(in + XXH_PREFETCH_DIST);               \
+        XXH3_accumulate_512_##name(                         \
+                 acc,                                       \
+                 in,                                        \
+                 secret + n*XXH_SECRET_CONSUME_RATE);       \
+    }                                                       \
+}
+
+
 XXH_FORCE_INLINE void XXH_writeLE64(void* dst, xxh_u64 v64)
 {
     if (!XXH_CPU_LITTLE_ENDIAN) v64 = XXH_swap64(v64);
@@ -3749,7 +4867,7 @@ XXH3_accumulate_512_avx512(void* XXH_RESTRICT acc,
         /* data_key    = data_vec ^ key_vec; */
         __m512i const data_key    = _mm512_xor_si512     (data_vec, key_vec);
         /* data_key_lo = data_key >> 32; */
-        __m512i const data_key_lo = _mm512_shuffle_epi32 (data_key, (_MM_PERM_ENUM)_MM_SHUFFLE(0, 3, 0, 1));
+        __m512i const data_key_lo = _mm512_srli_epi64 (data_key, 32);
         /* product     = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
         __m512i const product     = _mm512_mul_epu32     (data_key, data_key_lo);
         /* xacc[0] += swap(data_vec); */
@@ -3759,6 +4877,7 @@ XXH3_accumulate_512_avx512(void* XXH_RESTRICT acc,
         *xacc = _mm512_add_epi64(product, sum);
     }
 }
+XXH_FORCE_INLINE XXH_TARGET_AVX512 XXH3_ACCUMULATE_TEMPLATE(avx512)
 
 /*
  * XXH3_scrambleAcc: Scrambles the accumulators to improve mixing.
@@ -3792,13 +4911,12 @@ XXH3_scrambleAcc_avx512(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
         /* xacc[0] ^= (xacc[0] >> 47) */
         __m512i const acc_vec     = *xacc;
         __m512i const shifted     = _mm512_srli_epi64    (acc_vec, 47);
-        __m512i const data_vec    = _mm512_xor_si512     (acc_vec, shifted);
         /* xacc[0] ^= secret; */
         __m512i const key_vec     = _mm512_loadu_si512   (secret);
-        __m512i const data_key    = _mm512_xor_si512     (data_vec, key_vec);
+        __m512i const data_key    = _mm512_ternarylogic_epi32(key_vec, acc_vec, shifted, 0x96 /* key_vec ^ acc_vec ^ shifted */);
 
         /* xacc[0] *= XXH_PRIME32_1; */
-        __m512i const data_key_hi = _mm512_shuffle_epi32 (data_key, (_MM_PERM_ENUM)_MM_SHUFFLE(0, 3, 0, 1));
+        __m512i const data_key_hi = _mm512_srli_epi64 (data_key, 32);
         __m512i const prod_lo     = _mm512_mul_epu32     (data_key, prime32);
         __m512i const prod_hi     = _mm512_mul_epu32     (data_key_hi, prime32);
         *xacc = _mm512_add_epi64(prod_lo, _mm512_slli_epi64(prod_hi, 32));
@@ -3813,7 +4931,8 @@ XXH3_initCustomSecret_avx512(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
     XXH_ASSERT(((size_t)customSecret & 63) == 0);
     (void)(&XXH_writeLE64);
     {   int const nbRounds = XXH_SECRET_DEFAULT_SIZE / sizeof(__m512i);
-        __m512i const seed = _mm512_mask_set1_epi64(_mm512_set1_epi64((xxh_i64)seed64), 0xAA, (xxh_i64)(0U - seed64));
+        __m512i const seed_pos = _mm512_set1_epi64((xxh_i64)seed64);
+        __m512i const seed     = _mm512_mask_sub_epi64(seed_pos, 0xAA, _mm512_set1_epi8(0), seed_pos);
 
         const __m512i* const src  = (const __m512i*) ((const void*) XXH3_kSecret);
               __m512i* const dest = (      __m512i*) customSecret;
@@ -3821,14 +4940,7 @@ XXH3_initCustomSecret_avx512(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
         XXH_ASSERT(((size_t)src & 63) == 0); /* control alignment */
         XXH_ASSERT(((size_t)dest & 63) == 0);
         for (i=0; i < nbRounds; ++i) {
-            /* GCC has a bug, _mm512_stream_load_si512 accepts 'void*', not 'void const*',
-             * this will warn "discards 'const' qualifier". */
-            union {
-                const __m512i* cp;
-                void* p;
-            } remote_const_void;
-            remote_const_void.cp = src + i;
-            dest[i] = _mm512_add_epi64(_mm512_stream_load_si512(remote_const_void.p), seed);
+            dest[i] = _mm512_add_epi64(_mm512_load_si512(src + i), seed);
     }   }
 }
 
@@ -3864,7 +4976,7 @@ XXH3_accumulate_512_avx2( void* XXH_RESTRICT acc,
             /* data_key    = data_vec ^ key_vec; */
             __m256i const data_key    = _mm256_xor_si256     (data_vec, key_vec);
             /* data_key_lo = data_key >> 32; */
-            __m256i const data_key_lo = _mm256_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
+            __m256i const data_key_lo = _mm256_srli_epi64 (data_key, 32);
             /* product     = (data_key & 0xffffffff) * (data_key_lo & 0xffffffff); */
             __m256i const product     = _mm256_mul_epu32     (data_key, data_key_lo);
             /* xacc[i] += swap(data_vec); */
@@ -3874,6 +4986,7 @@ XXH3_accumulate_512_avx2( void* XXH_RESTRICT acc,
             xacc[i] = _mm256_add_epi64(product, sum);
     }   }
 }
+XXH_FORCE_INLINE XXH_TARGET_AVX2 XXH3_ACCUMULATE_TEMPLATE(avx2)
 
 XXH_FORCE_INLINE XXH_TARGET_AVX2 void
 XXH3_scrambleAcc_avx2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
@@ -3896,7 +5009,7 @@ XXH3_scrambleAcc_avx2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
             __m256i const data_key    = _mm256_xor_si256     (data_vec, key_vec);
 
             /* xacc[i] *= XXH_PRIME32_1; */
-            __m256i const data_key_hi = _mm256_shuffle_epi32 (data_key, _MM_SHUFFLE(0, 3, 0, 1));
+            __m256i const data_key_hi = _mm256_srli_epi64 (data_key, 32);
             __m256i const prod_lo     = _mm256_mul_epu32     (data_key, prime32);
             __m256i const prod_hi     = _mm256_mul_epu32     (data_key_hi, prime32);
             xacc[i] = _mm256_add_epi64(prod_lo, _mm256_slli_epi64(prod_hi, 32));
@@ -3928,12 +5041,12 @@ XXH_FORCE_INLINE XXH_TARGET_AVX2 void XXH3_initCustomSecret_avx2(void* XXH_RESTR
         XXH_ASSERT(((size_t)dest & 31) == 0);
 
         /* GCC -O2 need unroll loop manually */
-        dest[0] = _mm256_add_epi64(_mm256_stream_load_si256(src+0), seed);
-        dest[1] = _mm256_add_epi64(_mm256_stream_load_si256(src+1), seed);
-        dest[2] = _mm256_add_epi64(_mm256_stream_load_si256(src+2), seed);
-        dest[3] = _mm256_add_epi64(_mm256_stream_load_si256(src+3), seed);
-        dest[4] = _mm256_add_epi64(_mm256_stream_load_si256(src+4), seed);
-        dest[5] = _mm256_add_epi64(_mm256_stream_load_si256(src+5), seed);
+        dest[0] = _mm256_add_epi64(_mm256_load_si256(src+0), seed);
+        dest[1] = _mm256_add_epi64(_mm256_load_si256(src+1), seed);
+        dest[2] = _mm256_add_epi64(_mm256_load_si256(src+2), seed);
+        dest[3] = _mm256_add_epi64(_mm256_load_si256(src+3), seed);
+        dest[4] = _mm256_add_epi64(_mm256_load_si256(src+4), seed);
+        dest[5] = _mm256_add_epi64(_mm256_load_si256(src+5), seed);
     }
 }
 
@@ -3980,6 +5093,7 @@ XXH3_accumulate_512_sse2( void* XXH_RESTRICT acc,
             xacc[i] = _mm_add_epi64(product, sum);
     }   }
 }
+XXH_FORCE_INLINE XXH_TARGET_SSE2 XXH3_ACCUMULATE_TEMPLATE(sse2)
 
 XXH_FORCE_INLINE XXH_TARGET_SSE2 void
 XXH3_scrambleAcc_sse2(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
@@ -4058,14 +5172,28 @@ XXH3_scalarScrambleRound(void* XXH_RESTRICT acc,
 
 /*!
  * @internal
- * @brief The bulk processing loop for NEON.
+ * @brief The bulk processing loop for NEON and WASM SIMD128.
  *
  * The NEON code path is actually partially scalar when running on AArch64. This
  * is to optimize the pipelining and can have up to 15% speedup depending on the
  * CPU, and it also mitigates some GCC codegen issues.
  *
  * @see XXH3_NEON_LANES for configuring this and details about this optimization.
+ *
+ * NEON's 32-bit to 64-bit long multiply takes a half vector of 32-bit
+ * integers instead of the other platforms which mask full 64-bit vectors,
+ * so the setup is more complicated than just shifting right.
+ *
+ * Additionally, there is an optimization for 4 lanes at once noted below.
+ *
+ * Since, as stated, the most optimal amount of lanes for Cortexes is 6,
+ * there needs to be *three* versions of the accumulate operation used
+ * for the remaining 2 lanes.
+ *
+ * WASM's SIMD128 uses SIMDe's arm_neon.h polyfill because the intrinsics overlap
+ * nearly perfectly.
  */
+
 XXH_FORCE_INLINE void
 XXH3_accumulate_512_neon( void* XXH_RESTRICT acc,
                     const void* XXH_RESTRICT input,
@@ -4073,101 +5201,182 @@ XXH3_accumulate_512_neon( void* XXH_RESTRICT acc,
 {
     XXH_ASSERT((((size_t)acc) & 15) == 0);
     XXH_STATIC_ASSERT(XXH3_NEON_LANES > 0 && XXH3_NEON_LANES <= XXH_ACC_NB && XXH3_NEON_LANES % 2 == 0);
-    {
-        uint64x2_t* const xacc = (uint64x2_t *) acc;
+    {   /* GCC for darwin arm64 does not like aliasing here */
+        xxh_aliasing_uint64x2_t* const xacc = (xxh_aliasing_uint64x2_t*) acc;
         /* We don't use a uint32x4_t pointer because it causes bus errors on ARMv7. */
-        uint8_t const* const xinput = (const uint8_t *) input;
-        uint8_t const* const xsecret  = (const uint8_t *) secret;
+        uint8_t const* xinput = (const uint8_t *) input;
+        uint8_t const* xsecret  = (const uint8_t *) secret;
 
         size_t i;
-        /* NEON for the first few lanes (these loops are normally interleaved) */
-        for (i=0; i < XXH3_NEON_LANES / 2; i++) {
-            /* data_vec = xinput[i]; */
-            uint8x16_t data_vec    = vld1q_u8(xinput  + (i * 16));
-            /* key_vec  = xsecret[i];  */
-            uint8x16_t key_vec     = vld1q_u8(xsecret + (i * 16));
-            uint64x2_t data_key;
-            uint32x2_t data_key_lo, data_key_hi;
-            /* xacc[i] += swap(data_vec); */
-            uint64x2_t const data64  = vreinterpretq_u64_u8(data_vec);
-            uint64x2_t const swapped = vextq_u64(data64, data64, 1);
-            xacc[i] = vaddq_u64 (xacc[i], swapped);
-            /* data_key = data_vec ^ key_vec; */
-            data_key = vreinterpretq_u64_u8(veorq_u8(data_vec, key_vec));
-            /* data_key_lo = (uint32x2_t) (data_key & 0xFFFFFFFF);
-             * data_key_hi = (uint32x2_t) (data_key >> 32);
-             * data_key = UNDEFINED; */
-            XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
-            /* xacc[i] += (uint64x2_t) data_key_lo * (uint64x2_t) data_key_hi; */
-            xacc[i] = vmlal_u32 (xacc[i], data_key_lo, data_key_hi);
-
-        }
-        /* Scalar for the remainder. This may be a zero iteration loop. */
+#ifdef __wasm_simd128__
+        /*
+         * On WASM SIMD128, Clang emits direct address loads when XXH3_kSecret
+         * is constant propagated, which results in it converting it to this
+         * inside the loop:
+         *
+         *    a = v128.load(XXH3_kSecret +  0 + $secret_offset, offset = 0)
+         *    b = v128.load(XXH3_kSecret + 16 + $secret_offset, offset = 0)
+         *    ...
+         *
+         * This requires a full 32-bit address immediate (and therefore a 6 byte
+         * instruction) as well as an add for each offset.
+         *
+         * Putting an asm guard prevents it from folding (at the cost of losing
+         * the alignment hint), and uses the free offset in `v128.load` instead
+         * of adding secret_offset each time which overall reduces code size by
+         * about a kilobyte and improves performance.
+         */
+        XXH_COMPILER_GUARD(xsecret);
+#endif
+        /* Scalar lanes use the normal scalarRound routine */
         for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
             XXH3_scalarRound(acc, input, secret, i);
         }
+        i = 0;
+        /* 4 NEON lanes at a time. */
+        for (; i+1 < XXH3_NEON_LANES / 2; i+=2) {
+            /* data_vec = xinput[i]; */
+            uint64x2_t data_vec_1 = XXH_vld1q_u64(xinput  + (i * 16));
+            uint64x2_t data_vec_2 = XXH_vld1q_u64(xinput  + ((i+1) * 16));
+            /* key_vec  = xsecret[i];  */
+            uint64x2_t key_vec_1  = XXH_vld1q_u64(xsecret + (i * 16));
+            uint64x2_t key_vec_2  = XXH_vld1q_u64(xsecret + ((i+1) * 16));
+            /* data_swap = swap(data_vec) */
+            uint64x2_t data_swap_1 = vextq_u64(data_vec_1, data_vec_1, 1);
+            uint64x2_t data_swap_2 = vextq_u64(data_vec_2, data_vec_2, 1);
+            /* data_key = data_vec ^ key_vec; */
+            uint64x2_t data_key_1 = veorq_u64(data_vec_1, key_vec_1);
+            uint64x2_t data_key_2 = veorq_u64(data_vec_2, key_vec_2);
+
+            /*
+             * If we reinterpret the 64x2 vectors as 32x4 vectors, we can use a
+             * de-interleave operation for 4 lanes in 1 step with `vuzpq_u32` to
+             * get one vector with the low 32 bits of each lane, and one vector
+             * with the high 32 bits of each lane.
+             *
+             * The intrinsic returns a double vector because the original ARMv7-a
+             * instruction modified both arguments in place. AArch64 and SIMD128 emit
+             * two instructions from this intrinsic.
+             *
+             *  [ dk11L | dk11H | dk12L | dk12H ] -> [ dk11L | dk12L | dk21L | dk22L ]
+             *  [ dk21L | dk21H | dk22L | dk22H ] -> [ dk11H | dk12H | dk21H | dk22H ]
+             */
+            uint32x4x2_t unzipped = vuzpq_u32(
+                vreinterpretq_u32_u64(data_key_1),
+                vreinterpretq_u32_u64(data_key_2)
+            );
+            /* data_key_lo = data_key & 0xFFFFFFFF */
+            uint32x4_t data_key_lo = unzipped.val[0];
+            /* data_key_hi = data_key >> 32 */
+            uint32x4_t data_key_hi = unzipped.val[1];
+            /*
+             * Then, we can split the vectors horizontally and multiply which, as for most
+             * widening intrinsics, have a variant that works on both high half vectors
+             * for free on AArch64. A similar instruction is available on SIMD128.
+             *
+             * sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi
+             */
+            uint64x2_t sum_1 = XXH_vmlal_low_u32(data_swap_1, data_key_lo, data_key_hi);
+            uint64x2_t sum_2 = XXH_vmlal_high_u32(data_swap_2, data_key_lo, data_key_hi);
+            /*
+             * Clang reorders
+             *    a += b * c;     // umlal   swap.2d, dkl.2s, dkh.2s
+             *    c += a;         // add     acc.2d, acc.2d, swap.2d
+             * to
+             *    c += a;         // add     acc.2d, acc.2d, swap.2d
+             *    c += b * c;     // umlal   acc.2d, dkl.2s, dkh.2s
+             *
+             * While it would make sense in theory since the addition is faster,
+             * for reasons likely related to umlal being limited to certain NEON
+             * pipelines, this is worse. A compiler guard fixes this.
+             */
+            XXH_COMPILER_GUARD_CLANG_NEON(sum_1);
+            XXH_COMPILER_GUARD_CLANG_NEON(sum_2);
+            /* xacc[i] = acc_vec + sum; */
+            xacc[i]   = vaddq_u64(xacc[i], sum_1);
+            xacc[i+1] = vaddq_u64(xacc[i+1], sum_2);
+        }
+        /* Operate on the remaining NEON lanes 2 at a time. */
+        for (; i < XXH3_NEON_LANES / 2; i++) {
+            /* data_vec = xinput[i]; */
+            uint64x2_t data_vec = XXH_vld1q_u64(xinput  + (i * 16));
+            /* key_vec  = xsecret[i];  */
+            uint64x2_t key_vec  = XXH_vld1q_u64(xsecret + (i * 16));
+            /* acc_vec_2 = swap(data_vec) */
+            uint64x2_t data_swap = vextq_u64(data_vec, data_vec, 1);
+            /* data_key = data_vec ^ key_vec; */
+            uint64x2_t data_key = veorq_u64(data_vec, key_vec);
+            /* For two lanes, just use VMOVN and VSHRN. */
+            /* data_key_lo = data_key & 0xFFFFFFFF; */
+            uint32x2_t data_key_lo = vmovn_u64(data_key);
+            /* data_key_hi = data_key >> 32; */
+            uint32x2_t data_key_hi = vshrn_n_u64(data_key, 32);
+            /* sum = data_swap + (u64x2) data_key_lo * (u64x2) data_key_hi; */
+            uint64x2_t sum = vmlal_u32(data_swap, data_key_lo, data_key_hi);
+            /* Same Clang workaround as before */
+            XXH_COMPILER_GUARD_CLANG_NEON(sum);
+            /* xacc[i] = acc_vec + sum; */
+            xacc[i] = vaddq_u64 (xacc[i], sum);
+        }
     }
 }
+XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(neon)
 
 XXH_FORCE_INLINE void
 XXH3_scrambleAcc_neon(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
 {
     XXH_ASSERT((((size_t)acc) & 15) == 0);
 
-    {   uint64x2_t* xacc       = (uint64x2_t*) acc;
+    {   xxh_aliasing_uint64x2_t* xacc       = (xxh_aliasing_uint64x2_t*) acc;
         uint8_t const* xsecret = (uint8_t const*) secret;
-        uint32x2_t prime       = vdup_n_u32 (XXH_PRIME32_1);
 
         size_t i;
-        /* NEON for the first few lanes (these loops are normally interleaved) */
-        for (i=0; i < XXH3_NEON_LANES / 2; i++) {
-            /* xacc[i] ^= (xacc[i] >> 47); */
-            uint64x2_t acc_vec  = xacc[i];
-            uint64x2_t shifted  = vshrq_n_u64 (acc_vec, 47);
-            uint64x2_t data_vec = veorq_u64   (acc_vec, shifted);
+        /* WASM uses operator overloads and doesn't need these. */
+#ifndef __wasm_simd128__
+        /* { prime32_1, prime32_1 } */
+        uint32x2_t const kPrimeLo = vdup_n_u32(XXH_PRIME32_1);
+        /* { 0, prime32_1, 0, prime32_1 } */
+        uint32x4_t const kPrimeHi = vreinterpretq_u32_u64(vdupq_n_u64((xxh_u64)XXH_PRIME32_1 << 32));
+#endif
 
-            /* xacc[i] ^= xsecret[i]; */
-            uint8x16_t key_vec  = vld1q_u8    (xsecret + (i * 16));
-            uint64x2_t data_key = veorq_u64   (data_vec, vreinterpretq_u64_u8(key_vec));
-
-            /* xacc[i] *= XXH_PRIME32_1 */
-            uint32x2_t data_key_lo, data_key_hi;
-            /* data_key_lo = (uint32x2_t) (xacc[i] & 0xFFFFFFFF);
-             * data_key_hi = (uint32x2_t) (xacc[i] >> 32);
-             * xacc[i] = UNDEFINED; */
-            XXH_SPLIT_IN_PLACE(data_key, data_key_lo, data_key_hi);
-            {   /*
-                 * prod_hi = (data_key >> 32) * XXH_PRIME32_1;
-                 *
-                 * Avoid vmul_u32 + vshll_n_u32 since Clang 6 and 7 will
-                 * incorrectly "optimize" this:
-                 *   tmp     = vmul_u32(vmovn_u64(a), vmovn_u64(b));
-                 *   shifted = vshll_n_u32(tmp, 32);
-                 * to this:
-                 *   tmp     = "vmulq_u64"(a, b); // no such thing!
-                 *   shifted = vshlq_n_u64(tmp, 32);
-                 *
-                 * However, unlike SSE, Clang lacks a 64-bit multiply routine
-                 * for NEON, and it scalarizes two 64-bit multiplies instead.
-                 *
-                 * vmull_u32 has the same timing as vmul_u32, and it avoids
-                 * this bug completely.
-                 * See https://bugs.llvm.org/show_bug.cgi?id=39967
-                 */
-                uint64x2_t prod_hi = vmull_u32 (data_key_hi, prime);
-                /* xacc[i] = prod_hi << 32; */
-                xacc[i] = vshlq_n_u64(prod_hi, 32);
-                /* xacc[i] += (prod_hi & 0xFFFFFFFF) * XXH_PRIME32_1; */
-                xacc[i] = vmlal_u32(xacc[i], data_key_lo, prime);
-            }
-        }
-        /* Scalar for the remainder. This may be a zero iteration loop. */
+        /* AArch64 uses both scalar and neon at the same time */
         for (i = XXH3_NEON_LANES; i < XXH_ACC_NB; i++) {
             XXH3_scalarScrambleRound(acc, secret, i);
         }
+        for (i=0; i < XXH3_NEON_LANES / 2; i++) {
+            /* xacc[i] ^= (xacc[i] >> 47); */
+            uint64x2_t acc_vec  = xacc[i];
+            uint64x2_t shifted  = vshrq_n_u64(acc_vec, 47);
+            uint64x2_t data_vec = veorq_u64(acc_vec, shifted);
+
+            /* xacc[i] ^= xsecret[i]; */
+            uint64x2_t key_vec  = XXH_vld1q_u64(xsecret + (i * 16));
+            uint64x2_t data_key = veorq_u64(data_vec, key_vec);
+            /* xacc[i] *= XXH_PRIME32_1 */
+#ifdef __wasm_simd128__
+            /* SIMD128 has multiply by u64x2, use it instead of expanding and scalarizing */
+            xacc[i] = data_key * XXH_PRIME32_1;
+#else
+            /*
+             * Expanded version with portable NEON intrinsics
+             *
+             *    lo(x) * lo(y) + (hi(x) * lo(y) << 32)
+             *
+             * prod_hi = hi(data_key) * lo(prime) << 32
+             *
+             * Since we only need 32 bits of this multiply a trick can be used, reinterpreting the vector
+             * as a uint32x4_t and multiplying by { 0, prime, 0, prime } to cancel out the unwanted bits
+             * and avoid the shift.
+             */
+            uint32x4_t prod_hi = vmulq_u32 (vreinterpretq_u32_u64(data_key), kPrimeHi);
+            /* Extract low bits for vmlal_u32  */
+            uint32x2_t data_key_lo = vmovn_u64(data_key);
+            /* xacc[i] = prod_hi + lo(data_key) * XXH_PRIME32_1; */
+            xacc[i] = vmlal_u32(vreinterpretq_u64_u32(prod_hi), data_key_lo, kPrimeLo);
+#endif
+        }
     }
 }
-
 #endif
 
 #if (XXH_VECTOR == XXH_VSX)
@@ -4178,23 +5387,23 @@ XXH3_accumulate_512_vsx(  void* XXH_RESTRICT acc,
                     const void* XXH_RESTRICT secret)
 {
     /* presumed aligned */
-    unsigned int* const xacc = (unsigned int*) acc;
-    xxh_u64x2 const* const xinput   = (xxh_u64x2 const*) input;   /* no alignment restriction */
-    xxh_u64x2 const* const xsecret  = (xxh_u64x2 const*) secret;    /* no alignment restriction */
+    xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc;
+    xxh_u8 const* const xinput   = (xxh_u8 const*) input;   /* no alignment restriction */
+    xxh_u8 const* const xsecret  = (xxh_u8 const*) secret;    /* no alignment restriction */
     xxh_u64x2 const v32 = { 32, 32 };
     size_t i;
     for (i = 0; i < XXH_STRIPE_LEN / sizeof(xxh_u64x2); i++) {
         /* data_vec = xinput[i]; */
-        xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + i);
+        xxh_u64x2 const data_vec = XXH_vec_loadu(xinput + 16*i);
         /* key_vec = xsecret[i]; */
-        xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + i);
+        xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + 16*i);
         xxh_u64x2 const data_key = data_vec ^ key_vec;
         /* shuffled = (data_key << 32) | (data_key >> 32); */
         xxh_u32x4 const shuffled = (xxh_u32x4)vec_rl(data_key, v32);
         /* product = ((xxh_u64x2)data_key & 0xFFFFFFFF) * ((xxh_u64x2)shuffled & 0xFFFFFFFF); */
         xxh_u64x2 const product  = XXH_vec_mulo((xxh_u32x4)data_key, shuffled);
         /* acc_vec = xacc[i]; */
-        xxh_u64x2 acc_vec        = (xxh_u64x2)vec_xl(0, xacc + 4 * i);
+        xxh_u64x2 acc_vec        = xacc[i];
         acc_vec += product;
 
         /* swap high and low halves */
@@ -4203,18 +5412,18 @@ XXH3_accumulate_512_vsx(  void* XXH_RESTRICT acc,
 #else
         acc_vec += vec_xxpermdi(data_vec, data_vec, 2);
 #endif
-        /* xacc[i] = acc_vec; */
-        vec_xst((xxh_u32x4)acc_vec, 0, xacc + 4 * i);
+        xacc[i] = acc_vec;
     }
 }
+XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(vsx)
 
 XXH_FORCE_INLINE void
 XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
 {
     XXH_ASSERT((((size_t)acc) & 15) == 0);
 
-    {         xxh_u64x2* const xacc    =       (xxh_u64x2*) acc;
-        const xxh_u64x2* const xsecret = (const xxh_u64x2*) secret;
+    {   xxh_aliasing_u64x2* const xacc = (xxh_aliasing_u64x2*) acc;
+        const xxh_u8* const xsecret = (const xxh_u8*) secret;
         /* constants */
         xxh_u64x2 const v32  = { 32, 32 };
         xxh_u64x2 const v47 = { 47, 47 };
@@ -4226,7 +5435,7 @@ XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
             xxh_u64x2 const data_vec = acc_vec ^ (acc_vec >> v47);
 
             /* xacc[i] ^= xsecret[i]; */
-            xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + i);
+            xxh_u64x2 const key_vec  = XXH_vec_loadu(xsecret + 16*i);
             xxh_u64x2 const data_key = data_vec ^ key_vec;
 
             /* xacc[i] *= XXH_PRIME32_1 */
@@ -4240,8 +5449,148 @@ XXH3_scrambleAcc_vsx(void* XXH_RESTRICT acc, const void* XXH_RESTRICT secret)
 
 #endif
 
+#if (XXH_VECTOR == XXH_SVE)
+
+XXH_FORCE_INLINE void
+XXH3_accumulate_512_sve( void* XXH_RESTRICT acc,
+                   const void* XXH_RESTRICT input,
+                   const void* XXH_RESTRICT secret)
+{
+    uint64_t *xacc = (uint64_t *)acc;
+    const uint64_t *xinput = (const uint64_t *)(const void *)input;
+    const uint64_t *xsecret = (const uint64_t *)(const void *)secret;
+    svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1);
+    uint64_t element_count = svcntd();
+    if (element_count >= 8) {
+        svbool_t mask = svptrue_pat_b64(SV_VL8);
+        svuint64_t vacc = svld1_u64(mask, xacc);
+        ACCRND(vacc, 0);
+        svst1_u64(mask, xacc, vacc);
+    } else if (element_count == 2) {   /* sve128 */
+        svbool_t mask = svptrue_pat_b64(SV_VL2);
+        svuint64_t acc0 = svld1_u64(mask, xacc + 0);
+        svuint64_t acc1 = svld1_u64(mask, xacc + 2);
+        svuint64_t acc2 = svld1_u64(mask, xacc + 4);
+        svuint64_t acc3 = svld1_u64(mask, xacc + 6);
+        ACCRND(acc0, 0);
+        ACCRND(acc1, 2);
+        ACCRND(acc2, 4);
+        ACCRND(acc3, 6);
+        svst1_u64(mask, xacc + 0, acc0);
+        svst1_u64(mask, xacc + 2, acc1);
+        svst1_u64(mask, xacc + 4, acc2);
+        svst1_u64(mask, xacc + 6, acc3);
+    } else {
+        svbool_t mask = svptrue_pat_b64(SV_VL4);
+        svuint64_t acc0 = svld1_u64(mask, xacc + 0);
+        svuint64_t acc1 = svld1_u64(mask, xacc + 4);
+        ACCRND(acc0, 0);
+        ACCRND(acc1, 4);
+        svst1_u64(mask, xacc + 0, acc0);
+        svst1_u64(mask, xacc + 4, acc1);
+    }
+}
+
+XXH_FORCE_INLINE void
+XXH3_accumulate_sve(xxh_u64* XXH_RESTRICT acc,
+               const xxh_u8* XXH_RESTRICT input,
+               const xxh_u8* XXH_RESTRICT secret,
+               size_t nbStripes)
+{
+    if (nbStripes != 0) {
+        uint64_t *xacc = (uint64_t *)acc;
+        const uint64_t *xinput = (const uint64_t *)(const void *)input;
+        const uint64_t *xsecret = (const uint64_t *)(const void *)secret;
+        svuint64_t kSwap = sveor_n_u64_z(svptrue_b64(), svindex_u64(0, 1), 1);
+        uint64_t element_count = svcntd();
+        if (element_count >= 8) {
+            svbool_t mask = svptrue_pat_b64(SV_VL8);
+            svuint64_t vacc = svld1_u64(mask, xacc + 0);
+            do {
+                /* svprfd(svbool_t, void *, enum svfprop); */
+                svprfd(mask, xinput + 128, SV_PLDL1STRM);
+                ACCRND(vacc, 0);
+                xinput += 8;
+                xsecret += 1;
+                nbStripes--;
+           } while (nbStripes != 0);
+
+           svst1_u64(mask, xacc + 0, vacc);
+        } else if (element_count == 2) { /* sve128 */
+            svbool_t mask = svptrue_pat_b64(SV_VL2);
+            svuint64_t acc0 = svld1_u64(mask, xacc + 0);
+            svuint64_t acc1 = svld1_u64(mask, xacc + 2);
+            svuint64_t acc2 = svld1_u64(mask, xacc + 4);
+            svuint64_t acc3 = svld1_u64(mask, xacc + 6);
+            do {
+                svprfd(mask, xinput + 128, SV_PLDL1STRM);
+                ACCRND(acc0, 0);
+                ACCRND(acc1, 2);
+                ACCRND(acc2, 4);
+                ACCRND(acc3, 6);
+                xinput += 8;
+                xsecret += 1;
+                nbStripes--;
+           } while (nbStripes != 0);
+
+           svst1_u64(mask, xacc + 0, acc0);
+           svst1_u64(mask, xacc + 2, acc1);
+           svst1_u64(mask, xacc + 4, acc2);
+           svst1_u64(mask, xacc + 6, acc3);
+        } else {
+            svbool_t mask = svptrue_pat_b64(SV_VL4);
+            svuint64_t acc0 = svld1_u64(mask, xacc + 0);
+            svuint64_t acc1 = svld1_u64(mask, xacc + 4);
+            do {
+                svprfd(mask, xinput + 128, SV_PLDL1STRM);
+                ACCRND(acc0, 0);
+                ACCRND(acc1, 4);
+                xinput += 8;
+                xsecret += 1;
+                nbStripes--;
+           } while (nbStripes != 0);
+
+           svst1_u64(mask, xacc + 0, acc0);
+           svst1_u64(mask, xacc + 4, acc1);
+       }
+    }
+}
+
+#endif
+
 /* scalar variants - universal */
 
+#if defined(__aarch64__) && (defined(__GNUC__) || defined(__clang__))
+/*
+ * In XXH3_scalarRound(), GCC and Clang have a similar codegen issue, where they
+ * emit an excess mask and a full 64-bit multiply-add (MADD X-form).
+ *
+ * While this might not seem like much, as AArch64 is a 64-bit architecture, only
+ * big Cortex designs have a full 64-bit multiplier.
+ *
+ * On the little cores, the smaller 32-bit multiplier is used, and full 64-bit
+ * multiplies expand to 2-3 multiplies in microcode. This has a major penalty
+ * of up to 4 latency cycles and 2 stall cycles in the multiply pipeline.
+ *
+ * Thankfully, AArch64 still provides the 32-bit long multiply-add (UMADDL) which does
+ * not have this penalty and does the mask automatically.
+ */
+XXH_FORCE_INLINE xxh_u64
+XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc)
+{
+    xxh_u64 ret;
+    /* note: %x = 64-bit register, %w = 32-bit register */
+    __asm__("umaddl %x0, %w1, %w2, %x3" : "=r" (ret) : "r" (lhs), "r" (rhs), "r" (acc));
+    return ret;
+}
+#else
+XXH_FORCE_INLINE xxh_u64
+XXH_mult32to64_add64(xxh_u64 lhs, xxh_u64 rhs, xxh_u64 acc)
+{
+    return XXH_mult32to64((xxh_u32)lhs, (xxh_u32)rhs) + acc;
+}
+#endif
+
 /*!
  * @internal
  * @brief Scalar round for @ref XXH3_accumulate_512_scalar().
@@ -4264,7 +5613,7 @@ XXH3_scalarRound(void* XXH_RESTRICT acc,
         xxh_u64 const data_val = XXH_readLE64(xinput + lane * 8);
         xxh_u64 const data_key = data_val ^ XXH_readLE64(xsecret + lane * 8);
         xacc[lane ^ 1] += data_val; /* swap adjacent lanes */
-        xacc[lane] += XXH_mult32to64(data_key & 0xFFFFFFFF, data_key >> 32);
+        xacc[lane] = XXH_mult32to64_add64(data_key /* & 0xFFFFFFFF */, data_key >> 32, xacc[lane]);
     }
 }
 
@@ -4278,10 +5627,18 @@ XXH3_accumulate_512_scalar(void* XXH_RESTRICT acc,
                      const void* XXH_RESTRICT secret)
 {
     size_t i;
+    /* ARM GCC refuses to unroll this loop, resulting in a 24% slowdown on ARMv6. */
+#if defined(__GNUC__) && !defined(__clang__) \
+  && (defined(__arm__) || defined(__thumb2__)) \
+  && defined(__ARM_FEATURE_UNALIGNED) /* no unaligned access just wastes bytes */ \
+  && XXH_SIZE_OPT <= 0
+#  pragma GCC unroll 8
+#endif
     for (i=0; i < XXH_ACC_NB; i++) {
         XXH3_scalarRound(acc, input, secret, i);
     }
 }
+XXH_FORCE_INLINE XXH3_ACCUMULATE_TEMPLATE(scalar)
 
 /*!
  * @internal
@@ -4333,10 +5690,10 @@ XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
     const xxh_u8* kSecretPtr = XXH3_kSecret;
     XXH_STATIC_ASSERT((XXH_SECRET_DEFAULT_SIZE & 15) == 0);
 
-#if defined(__clang__) && defined(__aarch64__)
+#if defined(__GNUC__) && defined(__aarch64__)
     /*
      * UGLY HACK:
-     * Clang generates a bunch of MOV/MOVK pairs for aarch64, and they are
+     * GCC and Clang generate a bunch of MOV/MOVK pairs for aarch64, and they are
      * placed sequentially, in order, at the top of the unrolled loop.
      *
      * While MOVK is great for generating constants (2 cycles for a 64-bit
@@ -4351,7 +5708,7 @@ XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
      * ADD
      * SUB      STR
      *          STR
-     * By forcing loads from memory (as the asm line causes Clang to assume
+     * By forcing loads from memory (as the asm line causes the compiler to assume
      * that XXH3_kSecretPtr has been changed), the pipelines are used more
      * efficiently:
      *   I   L   S
@@ -4368,17 +5725,11 @@ XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
      */
     XXH_COMPILER_GUARD(kSecretPtr);
 #endif
-    /*
-     * Note: in debug mode, this overrides the asm optimization
-     * and Clang will emit MOVK chains again.
-     */
-    XXH_ASSERT(kSecretPtr == XXH3_kSecret);
-
     {   int const nbRounds = XXH_SECRET_DEFAULT_SIZE / 16;
         int i;
         for (i=0; i < nbRounds; i++) {
             /*
-             * The asm hack causes Clang to assume that kSecretPtr aliases with
+             * The asm hack causes the compiler to assume that kSecretPtr aliases with
              * customSecret, and on aarch64, this prevented LDP from merging two
              * loads together for free. Putting the loads together before the stores
              * properly generates LDP.
@@ -4391,7 +5742,7 @@ XXH3_initCustomSecret_scalar(void* XXH_RESTRICT customSecret, xxh_u64 seed64)
 }
 
 
-typedef void (*XXH3_f_accumulate_512)(void* XXH_RESTRICT, const void*, const void*);
+typedef void (*XXH3_f_accumulate)(xxh_u64* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, const xxh_u8* XXH_RESTRICT, size_t);
 typedef void (*XXH3_f_scrambleAcc)(void* XXH_RESTRICT, const void*);
 typedef void (*XXH3_f_initCustomSecret)(void* XXH_RESTRICT, xxh_u64);
 
@@ -4399,82 +5750,63 @@ typedef void (*XXH3_f_initCustomSecret)(void* XXH_RESTRICT, xxh_u64);
 #if (XXH_VECTOR == XXH_AVX512)
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_avx512
+#define XXH3_accumulate     XXH3_accumulate_avx512
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_avx512
 #define XXH3_initCustomSecret XXH3_initCustomSecret_avx512
 
 #elif (XXH_VECTOR == XXH_AVX2)
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_avx2
+#define XXH3_accumulate     XXH3_accumulate_avx2
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_avx2
 #define XXH3_initCustomSecret XXH3_initCustomSecret_avx2
 
 #elif (XXH_VECTOR == XXH_SSE2)
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_sse2
+#define XXH3_accumulate     XXH3_accumulate_sse2
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_sse2
 #define XXH3_initCustomSecret XXH3_initCustomSecret_sse2
 
 #elif (XXH_VECTOR == XXH_NEON)
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_neon
+#define XXH3_accumulate     XXH3_accumulate_neon
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_neon
 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
 
 #elif (XXH_VECTOR == XXH_VSX)
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_vsx
+#define XXH3_accumulate     XXH3_accumulate_vsx
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_vsx
 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
 
+#elif (XXH_VECTOR == XXH_SVE)
+#define XXH3_accumulate_512 XXH3_accumulate_512_sve
+#define XXH3_accumulate     XXH3_accumulate_sve
+#define XXH3_scrambleAcc    XXH3_scrambleAcc_scalar
+#define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
+
 #else /* scalar */
 
 #define XXH3_accumulate_512 XXH3_accumulate_512_scalar
+#define XXH3_accumulate     XXH3_accumulate_scalar
 #define XXH3_scrambleAcc    XXH3_scrambleAcc_scalar
 #define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
 
 #endif
 
-
-
-#ifndef XXH_PREFETCH_DIST
-#  ifdef __clang__
-#    define XXH_PREFETCH_DIST 320
-#  else
-#    if (XXH_VECTOR == XXH_AVX512)
-#      define XXH_PREFETCH_DIST 512
-#    else
-#      define XXH_PREFETCH_DIST 384
-#    endif
-#  endif  /* __clang__ */
-#endif  /* XXH_PREFETCH_DIST */
-
-/*
- * XXH3_accumulate()
- * Loops over XXH3_accumulate_512().
- * Assumption: nbStripes will not overflow the secret size
- */
-XXH_FORCE_INLINE void
-XXH3_accumulate(     xxh_u64* XXH_RESTRICT acc,
-                const xxh_u8* XXH_RESTRICT input,
-                const xxh_u8* XXH_RESTRICT secret,
-                      size_t nbStripes,
-                      XXH3_f_accumulate_512 f_acc512)
-{
-    size_t n;
-    for (n = 0; n < nbStripes; n++ ) {
-        const xxh_u8* const in = input + n*XXH_STRIPE_LEN;
-        XXH_PREFETCH(in + XXH_PREFETCH_DIST);
-        f_acc512(acc,
-                 in,
-                 secret + n*XXH_SECRET_CONSUME_RATE);
-    }
-}
+#if XXH_SIZE_OPT >= 1 /* don't do SIMD for initialization */
+#  undef XXH3_initCustomSecret
+#  define XXH3_initCustomSecret XXH3_initCustomSecret_scalar
+#endif
 
 XXH_FORCE_INLINE void
 XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc,
                       const xxh_u8* XXH_RESTRICT input, size_t len,
                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
-                            XXH3_f_accumulate_512 f_acc512,
+                            XXH3_f_accumulate f_acc,
                             XXH3_f_scrambleAcc f_scramble)
 {
     size_t const nbStripesPerBlock = (secretSize - XXH_STRIPE_LEN) / XXH_SECRET_CONSUME_RATE;
@@ -4486,7 +5818,7 @@ XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc,
     XXH_ASSERT(secretSize >= XXH3_SECRET_SIZE_MIN);
 
     for (n = 0; n < nb_blocks; n++) {
-        XXH3_accumulate(acc, input + n*block_len, secret, nbStripesPerBlock, f_acc512);
+        f_acc(acc, input + n*block_len, secret, nbStripesPerBlock);
         f_scramble(acc, secret + secretSize - XXH_STRIPE_LEN);
     }
 
@@ -4494,12 +5826,12 @@ XXH3_hashLong_internal_loop(xxh_u64* XXH_RESTRICT acc,
     XXH_ASSERT(len > XXH_STRIPE_LEN);
     {   size_t const nbStripes = ((len - 1) - (block_len * nb_blocks)) / XXH_STRIPE_LEN;
         XXH_ASSERT(nbStripes <= (secretSize / XXH_SECRET_CONSUME_RATE));
-        XXH3_accumulate(acc, input + nb_blocks*block_len, secret, nbStripes, f_acc512);
+        f_acc(acc, input + nb_blocks*block_len, secret, nbStripes);
 
         /* last stripe */
         {   const xxh_u8* const p = input + len - XXH_STRIPE_LEN;
 #define XXH_SECRET_LASTACC_START 7  /* not aligned on 8, last secret is different from acc & scrambler */
-            f_acc512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START);
+            XXH3_accumulate_512(acc, p, secret + secretSize - XXH_STRIPE_LEN - XXH_SECRET_LASTACC_START);
     }   }
 }
 
@@ -4544,12 +5876,12 @@ XXH3_mergeAccs(const xxh_u64* XXH_RESTRICT acc, const xxh_u8* XXH_RESTRICT secre
 XXH_FORCE_INLINE XXH64_hash_t
 XXH3_hashLong_64b_internal(const void* XXH_RESTRICT input, size_t len,
                            const void* XXH_RESTRICT secret, size_t secretSize,
-                           XXH3_f_accumulate_512 f_acc512,
+                           XXH3_f_accumulate f_acc,
                            XXH3_f_scrambleAcc f_scramble)
 {
     XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
 
-    XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, f_acc512, f_scramble);
+    XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, (const xxh_u8*)secret, secretSize, f_acc, f_scramble);
 
     /* converge into final hash */
     XXH_STATIC_ASSERT(sizeof(acc) == 64);
@@ -4563,13 +5895,15 @@ XXH3_hashLong_64b_internal(const void* XXH_RESTRICT input, size_t len,
  * It's important for performance to transmit secret's size (when it's static)
  * so that the compiler can properly optimize the vectorized loop.
  * This makes a big performance difference for "medium" keys (<1 KB) when using AVX instruction set.
+ * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE
+ * breaks -Og, this is XXH_NO_INLINE.
  */
-XXH_FORCE_INLINE XXH64_hash_t
+XXH3_WITH_SECRET_INLINE XXH64_hash_t
 XXH3_hashLong_64b_withSecret(const void* XXH_RESTRICT input, size_t len,
                              XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen)
 {
     (void)seed64;
-    return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate_512, XXH3_scrambleAcc);
+    return XXH3_hashLong_64b_internal(input, len, secret, secretLen, XXH3_accumulate, XXH3_scrambleAcc);
 }
 
 /*
@@ -4578,12 +5912,12 @@ XXH3_hashLong_64b_withSecret(const void* XXH_RESTRICT input, size_t len,
  * Note that inside this no_inline function, we do inline the internal loop,
  * and provide a statically defined secret size to allow optimization of vector loop.
  */
-XXH_NO_INLINE XXH64_hash_t
+XXH_NO_INLINE XXH_PUREF XXH64_hash_t
 XXH3_hashLong_64b_default(const void* XXH_RESTRICT input, size_t len,
                           XXH64_hash_t seed64, const xxh_u8* XXH_RESTRICT secret, size_t secretLen)
 {
     (void)seed64; (void)secret; (void)secretLen;
-    return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate_512, XXH3_scrambleAcc);
+    return XXH3_hashLong_64b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_accumulate, XXH3_scrambleAcc);
 }
 
 /*
@@ -4600,18 +5934,20 @@ XXH3_hashLong_64b_default(const void* XXH_RESTRICT input, size_t len,
 XXH_FORCE_INLINE XXH64_hash_t
 XXH3_hashLong_64b_withSeed_internal(const void* input, size_t len,
                                     XXH64_hash_t seed,
-                                    XXH3_f_accumulate_512 f_acc512,
+                                    XXH3_f_accumulate f_acc,
                                     XXH3_f_scrambleAcc f_scramble,
                                     XXH3_f_initCustomSecret f_initSec)
 {
+#if XXH_SIZE_OPT <= 0
     if (seed == 0)
         return XXH3_hashLong_64b_internal(input, len,
                                           XXH3_kSecret, sizeof(XXH3_kSecret),
-                                          f_acc512, f_scramble);
+                                          f_acc, f_scramble);
+#endif
     {   XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
         f_initSec(secret, seed);
         return XXH3_hashLong_64b_internal(input, len, secret, sizeof(secret),
-                                          f_acc512, f_scramble);
+                                          f_acc, f_scramble);
     }
 }
 
@@ -4619,12 +5955,12 @@ XXH3_hashLong_64b_withSeed_internal(const void* input, size_t len,
  * It's important for performance that XXH3_hashLong is not inlined.
  */
 XXH_NO_INLINE XXH64_hash_t
-XXH3_hashLong_64b_withSeed(const void* input, size_t len,
-                           XXH64_hash_t seed, const xxh_u8* secret, size_t secretLen)
+XXH3_hashLong_64b_withSeed(const void* XXH_RESTRICT input, size_t len,
+                           XXH64_hash_t seed, const xxh_u8* XXH_RESTRICT secret, size_t secretLen)
 {
     (void)secret; (void)secretLen;
     return XXH3_hashLong_64b_withSeed_internal(input, len, seed,
-                XXH3_accumulate_512, XXH3_scrambleAcc, XXH3_initCustomSecret);
+                XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret);
 }
 
 
@@ -4656,37 +5992,37 @@ XXH3_64bits_internal(const void* XXH_RESTRICT input, size_t len,
 
 /* ===   Public entry point   === */
 
-/*! @ingroup xxh3_family */
-XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(const void* input, size_t len)
+/*! @ingroup XXH3_family */
+XXH_PUBLIC_API XXH64_hash_t XXH3_64bits(XXH_NOESCAPE const void* input, size_t length)
 {
-    return XXH3_64bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default);
+    return XXH3_64bits_internal(input, length, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_default);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH64_hash_t
-XXH3_64bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
+XXH3_64bits_withSecret(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize)
 {
-    return XXH3_64bits_internal(input, len, 0, secret, secretSize, XXH3_hashLong_64b_withSecret);
+    return XXH3_64bits_internal(input, length, 0, secret, secretSize, XXH3_hashLong_64b_withSecret);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH64_hash_t
-XXH3_64bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
+XXH3_64bits_withSeed(XXH_NOESCAPE const void* input, size_t length, XXH64_hash_t seed)
 {
-    return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed);
+    return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed);
 }
 
 XXH_PUBLIC_API XXH64_hash_t
-XXH3_64bits_withSecretandSeed(const void* input, size_t len, const void* secret, size_t secretSize, XXH64_hash_t seed)
+XXH3_64bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t length, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed)
 {
-    if (len <= XXH3_MIDSIZE_MAX)
-        return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
-    return XXH3_hashLong_64b_withSecret(input, len, seed, (const xxh_u8*)secret, secretSize);
+    if (length <= XXH3_MIDSIZE_MAX)
+        return XXH3_64bits_internal(input, length, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
+    return XXH3_hashLong_64b_withSecret(input, length, seed, (const xxh_u8*)secret, secretSize);
 }
 
 
 /* ===   XXH3 streaming   === */
-
+#ifndef XXH_NO_STREAM
 /*
  * Malloc's a pointer that is always aligned to align.
  *
@@ -4710,7 +6046,7 @@ XXH3_64bits_withSecretandSeed(const void* input, size_t len, const void* secret,
  *
  * Align must be a power of 2 and 8 <= align <= 128.
  */
-static void* XXH_alignedMalloc(size_t s, size_t align)
+static XXH_MALLOCF void* XXH_alignedMalloc(size_t s, size_t align)
 {
     XXH_ASSERT(align <= 128 && align >= 8); /* range check */
     XXH_ASSERT((align & (align-1)) == 0);   /* power of 2 */
@@ -4752,7 +6088,17 @@ static void XXH_alignedFree(void* p)
         XXH_free(base);
     }
 }
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
+/*!
+ * @brief Allocate an @ref XXH3_state_t.
+ *
+ * @return An allocated pointer of @ref XXH3_state_t on success.
+ * @return `NULL` on failure.
+ *
+ * @note Must be freed with XXH3_freeState().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
 XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void)
 {
     XXH3_state_t* const state = (XXH3_state_t*)XXH_alignedMalloc(sizeof(XXH3_state_t), 64);
@@ -4761,16 +6107,27 @@ XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void)
     return state;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
+/*!
+ * @brief Frees an @ref XXH3_state_t.
+ *
+ * @param statePtr A pointer to an @ref XXH3_state_t allocated with @ref XXH3_createState().
+ *
+ * @return @ref XXH_OK.
+ *
+ * @note Must be allocated with XXH3_createState().
+ *
+ * @see @ref streaming_example "Streaming Example"
+ */
 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr)
 {
     XXH_alignedFree(statePtr);
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API void
-XXH3_copyState(XXH3_state_t* dst_state, const XXH3_state_t* src_state)
+XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOESCAPE const XXH3_state_t* src_state)
 {
     XXH_memcpy(dst_state, src_state, sizeof(*dst_state));
 }
@@ -4802,18 +6159,18 @@ XXH3_reset_internal(XXH3_state_t* statePtr,
     statePtr->nbStripesPerBlock = statePtr->secretLimit / XXH_SECRET_CONSUME_RATE;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_reset(XXH3_state_t* statePtr)
+XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr)
 {
     if (statePtr == NULL) return XXH_ERROR;
     XXH3_reset_internal(statePtr, 0, XXH3_kSecret, XXH_SECRET_DEFAULT_SIZE);
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
+XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize)
 {
     if (statePtr == NULL) return XXH_ERROR;
     XXH3_reset_internal(statePtr, 0, secret, secretSize);
@@ -4822,9 +6179,9 @@ XXH3_64bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
+XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed)
 {
     if (statePtr == NULL) return XXH_ERROR;
     if (seed==0) return XXH3_64bits_reset(statePtr);
@@ -4834,9 +6191,9 @@ XXH3_64bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_reset_withSecretandSeed(XXH3_state_t* statePtr, const void* secret, size_t secretSize, XXH64_hash_t seed64)
+XXH3_64bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed64)
 {
     if (statePtr == NULL) return XXH_ERROR;
     if (secret == NULL) return XXH_ERROR;
@@ -4846,35 +6203,61 @@ XXH3_64bits_reset_withSecretandSeed(XXH3_state_t* statePtr, const void* secret,
     return XXH_OK;
 }
 
-/* Note : when XXH3_consumeStripes() is invoked,
- * there must be a guarantee that at least one more byte must be consumed from input
- * so that the function can blindly consume all stripes using the "normal" secret segment */
-XXH_FORCE_INLINE void
+/*!
+ * @internal
+ * @brief Processes a large input for XXH3_update() and XXH3_digest_long().
+ *
+ * Unlike XXH3_hashLong_internal_loop(), this can process data that overlaps a block.
+ *
+ * @param acc                Pointer to the 8 accumulator lanes
+ * @param nbStripesSoFarPtr  In/out pointer to the number of leftover stripes in the block*
+ * @param nbStripesPerBlock  Number of stripes in a block
+ * @param input              Input pointer
+ * @param nbStripes          Number of stripes to process
+ * @param secret             Secret pointer
+ * @param secretLimit        Offset of the last block in @p secret
+ * @param f_acc              Pointer to an XXH3_accumulate implementation
+ * @param f_scramble         Pointer to an XXH3_scrambleAcc implementation
+ * @return                   Pointer past the end of @p input after processing
+ */
+XXH_FORCE_INLINE const xxh_u8 *
 XXH3_consumeStripes(xxh_u64* XXH_RESTRICT acc,
                     size_t* XXH_RESTRICT nbStripesSoFarPtr, size_t nbStripesPerBlock,
                     const xxh_u8* XXH_RESTRICT input, size_t nbStripes,
                     const xxh_u8* XXH_RESTRICT secret, size_t secretLimit,
-                    XXH3_f_accumulate_512 f_acc512,
+                    XXH3_f_accumulate f_acc,
                     XXH3_f_scrambleAcc f_scramble)
 {
-    XXH_ASSERT(nbStripes <= nbStripesPerBlock);  /* can handle max 1 scramble per invocation */
-    XXH_ASSERT(*nbStripesSoFarPtr < nbStripesPerBlock);
-    if (nbStripesPerBlock - *nbStripesSoFarPtr <= nbStripes) {
-        /* need a scrambling operation */
-        size_t const nbStripesToEndofBlock = nbStripesPerBlock - *nbStripesSoFarPtr;
-        size_t const nbStripesAfterBlock = nbStripes - nbStripesToEndofBlock;
-        XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripesToEndofBlock, f_acc512);
-        f_scramble(acc, secret + secretLimit);
-        XXH3_accumulate(acc, input + nbStripesToEndofBlock * XXH_STRIPE_LEN, secret, nbStripesAfterBlock, f_acc512);
-        *nbStripesSoFarPtr = nbStripesAfterBlock;
-    } else {
-        XXH3_accumulate(acc, input, secret + nbStripesSoFarPtr[0] * XXH_SECRET_CONSUME_RATE, nbStripes, f_acc512);
+    const xxh_u8* initialSecret = secret + *nbStripesSoFarPtr * XXH_SECRET_CONSUME_RATE;
+    /* Process full blocks */
+    if (nbStripes >= (nbStripesPerBlock - *nbStripesSoFarPtr)) {
+        /* Process the initial partial block... */
+        size_t nbStripesThisIter = nbStripesPerBlock - *nbStripesSoFarPtr;
+
+        do {
+            /* Accumulate and scramble */
+            f_acc(acc, input, initialSecret, nbStripesThisIter);
+            f_scramble(acc, secret + secretLimit);
+            input += nbStripesThisIter * XXH_STRIPE_LEN;
+            nbStripes -= nbStripesThisIter;
+            /* Then continue the loop with the full block size */
+            nbStripesThisIter = nbStripesPerBlock;
+            initialSecret = secret;
+        } while (nbStripes >= nbStripesPerBlock);
+        *nbStripesSoFarPtr = 0;
+    }
+    /* Process a partial block */
+    if (nbStripes > 0) {
+        f_acc(acc, input, initialSecret, nbStripes);
+        input += nbStripes * XXH_STRIPE_LEN;
         *nbStripesSoFarPtr += nbStripes;
     }
+    /* Return end pointer */
+    return input;
 }
 
 #ifndef XXH3_STREAM_USE_STACK
-# ifndef __clang__ /* clang doesn't need additional stack space */
+# if XXH_SIZE_OPT <= 0 && !defined(__clang__) /* clang doesn't need additional stack space */
 #   define XXH3_STREAM_USE_STACK 1
 # endif
 #endif
@@ -4884,7 +6267,7 @@ XXH3_consumeStripes(xxh_u64* XXH_RESTRICT acc,
 XXH_FORCE_INLINE XXH_errorcode
 XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
             const xxh_u8* XXH_RESTRICT input, size_t len,
-            XXH3_f_accumulate_512 f_acc512,
+            XXH3_f_accumulate f_acc,
             XXH3_f_scrambleAcc f_scramble)
 {
     if (input==NULL) {
@@ -4900,7 +6283,8 @@ XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
          * when operating accumulators directly into state.
          * Operating into stack space seems to enable proper optimization.
          * clang, on the other hand, doesn't seem to need this trick */
-        XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8]; memcpy(acc, state->acc, sizeof(acc));
+        XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[8];
+        XXH_memcpy(acc, state->acc, sizeof(acc));
 #else
         xxh_u64* XXH_RESTRICT const acc = state->acc;
 #endif
@@ -4908,7 +6292,7 @@ XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
         XXH_ASSERT(state->bufferedSize <= XXH3_INTERNALBUFFER_SIZE);
 
         /* small input : just fill in tmp buffer */
-        if (state->bufferedSize + len <= XXH3_INTERNALBUFFER_SIZE) {
+        if (len <= XXH3_INTERNALBUFFER_SIZE - state->bufferedSize) {
             XXH_memcpy(state->buffer + state->bufferedSize, input, len);
             state->bufferedSize += (XXH32_hash_t)len;
             return XXH_OK;
@@ -4930,57 +6314,20 @@ XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
                                &state->nbStripesSoFar, state->nbStripesPerBlock,
                                 state->buffer, XXH3_INTERNALBUFFER_STRIPES,
                                 secret, state->secretLimit,
-                                f_acc512, f_scramble);
+                                f_acc, f_scramble);
             state->bufferedSize = 0;
         }
         XXH_ASSERT(input < bEnd);
-
-        /* large input to consume : ingest per full block */
-        if ((size_t)(bEnd - input) > state->nbStripesPerBlock * XXH_STRIPE_LEN) {
+        if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) {
             size_t nbStripes = (size_t)(bEnd - 1 - input) / XXH_STRIPE_LEN;
-            XXH_ASSERT(state->nbStripesPerBlock >= state->nbStripesSoFar);
-            /* join to current block's end */
-            {   size_t const nbStripesToEnd = state->nbStripesPerBlock - state->nbStripesSoFar;
-                XXH_ASSERT(nbStripesToEnd <= nbStripes);
-                XXH3_accumulate(acc, input, secret + state->nbStripesSoFar * XXH_SECRET_CONSUME_RATE, nbStripesToEnd, f_acc512);
-                f_scramble(acc, secret + state->secretLimit);
-                state->nbStripesSoFar = 0;
-                input += nbStripesToEnd * XXH_STRIPE_LEN;
-                nbStripes -= nbStripesToEnd;
-            }
-            /* consume per entire blocks */
-            while(nbStripes >= state->nbStripesPerBlock) {
-                XXH3_accumulate(acc, input, secret, state->nbStripesPerBlock, f_acc512);
-                f_scramble(acc, secret + state->secretLimit);
-                input += state->nbStripesPerBlock * XXH_STRIPE_LEN;
-                nbStripes -= state->nbStripesPerBlock;
-            }
-            /* consume last partial block */
-            XXH3_accumulate(acc, input, secret, nbStripes, f_acc512);
-            input += nbStripes * XXH_STRIPE_LEN;
-            XXH_ASSERT(input < bEnd);  /* at least some bytes left */
-            state->nbStripesSoFar = nbStripes;
-            /* buffer predecessor of last partial stripe */
-            XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
-            XXH_ASSERT(bEnd - input <= XXH_STRIPE_LEN);
-        } else {
-            /* content to consume <= block size */
-            /* Consume input by a multiple of internal buffer size */
-            if (bEnd - input > XXH3_INTERNALBUFFER_SIZE) {
-                const xxh_u8* const limit = bEnd - XXH3_INTERNALBUFFER_SIZE;
-                do {
-                    XXH3_consumeStripes(acc,
+            input = XXH3_consumeStripes(acc,
                                        &state->nbStripesSoFar, state->nbStripesPerBlock,
-                                        input, XXH3_INTERNALBUFFER_STRIPES,
-                                        secret, state->secretLimit,
-                                        f_acc512, f_scramble);
-                    input += XXH3_INTERNALBUFFER_SIZE;
-                } while (inputbuffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
-            }
-        }
+                                       input, nbStripes,
+                                       secret, state->secretLimit,
+                                       f_acc, f_scramble);
+            XXH_memcpy(state->buffer + sizeof(state->buffer) - XXH_STRIPE_LEN, input - XXH_STRIPE_LEN, XXH_STRIPE_LEN);
 
+        }
         /* Some remaining input (always) : buffer it */
         XXH_ASSERT(input < bEnd);
         XXH_ASSERT(bEnd - input <= XXH3_INTERNALBUFFER_SIZE);
@@ -4989,19 +6336,19 @@ XXH3_update(XXH3_state_t* XXH_RESTRICT const state,
         state->bufferedSize = (XXH32_hash_t)(bEnd-input);
 #if defined(XXH3_STREAM_USE_STACK) && XXH3_STREAM_USE_STACK >= 1
         /* save stack accumulators into state */
-        memcpy(state->acc, acc, sizeof(acc));
+        XXH_memcpy(state->acc, acc, sizeof(acc));
 #endif
     }
 
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_64bits_update(XXH3_state_t* state, const void* input, size_t len)
+XXH3_64bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len)
 {
     return XXH3_update(state, (const xxh_u8*)input, len,
-                       XXH3_accumulate_512, XXH3_scrambleAcc);
+                       XXH3_accumulate, XXH3_scrambleAcc);
 }
 
 
@@ -5010,37 +6357,40 @@ XXH3_digest_long (XXH64_hash_t* acc,
                   const XXH3_state_t* state,
                   const unsigned char* secret)
 {
+    xxh_u8 lastStripe[XXH_STRIPE_LEN];
+    const xxh_u8* lastStripePtr;
+
     /*
      * Digest on a local copy. This way, the state remains unaltered, and it can
      * continue ingesting more input afterwards.
      */
     XXH_memcpy(acc, state->acc, sizeof(state->acc));
     if (state->bufferedSize >= XXH_STRIPE_LEN) {
+        /* Consume remaining stripes then point to remaining data in buffer */
         size_t const nbStripes = (state->bufferedSize - 1) / XXH_STRIPE_LEN;
         size_t nbStripesSoFar = state->nbStripesSoFar;
         XXH3_consumeStripes(acc,
                            &nbStripesSoFar, state->nbStripesPerBlock,
                             state->buffer, nbStripes,
                             secret, state->secretLimit,
-                            XXH3_accumulate_512, XXH3_scrambleAcc);
-        /* last stripe */
-        XXH3_accumulate_512(acc,
-                            state->buffer + state->bufferedSize - XXH_STRIPE_LEN,
-                            secret + state->secretLimit - XXH_SECRET_LASTACC_START);
+                            XXH3_accumulate, XXH3_scrambleAcc);
+        lastStripePtr = state->buffer + state->bufferedSize - XXH_STRIPE_LEN;
     } else {  /* bufferedSize < XXH_STRIPE_LEN */
-        xxh_u8 lastStripe[XXH_STRIPE_LEN];
+        /* Copy to temp buffer */
         size_t const catchupSize = XXH_STRIPE_LEN - state->bufferedSize;
         XXH_ASSERT(state->bufferedSize > 0);  /* there is always some input buffered */
         XXH_memcpy(lastStripe, state->buffer + sizeof(state->buffer) - catchupSize, catchupSize);
         XXH_memcpy(lastStripe + catchupSize, state->buffer, state->bufferedSize);
-        XXH3_accumulate_512(acc,
-                            lastStripe,
-                            secret + state->secretLimit - XXH_SECRET_LASTACC_START);
+        lastStripePtr = lastStripe;
     }
+    /* Last stripe */
+    XXH3_accumulate_512(acc,
+                        lastStripePtr,
+                        secret + state->secretLimit - XXH_SECRET_LASTACC_START);
 }
 
-/*! @ingroup xxh3_family */
-XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (const XXH3_state_t* state)
+/*! @ingroup XXH3_family */
+XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* state)
 {
     const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
     if (state->totalLen > XXH3_MIDSIZE_MAX) {
@@ -5056,7 +6406,7 @@ XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (const XXH3_state_t* state)
     return XXH3_64bits_withSecret(state->buffer, (size_t)(state->totalLen),
                                   secret, state->secretLimit + XXH_STRIPE_LEN);
 }
-
+#endif /* !XXH_NO_STREAM */
 
 
 /* ==========================================
@@ -5076,7 +6426,7 @@ XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_digest (const XXH3_state_t* state)
  * fast for a _128-bit_ hash on 32-bit (it usually clears XXH64).
  */
 
-XXH_FORCE_INLINE XXH128_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     /* A doubled version of 1to3_64b with different constants. */
@@ -5105,7 +6455,7 @@ XXH3_len_1to3_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_
     }
 }
 
-XXH_FORCE_INLINE XXH128_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(input != NULL);
@@ -5125,14 +6475,14 @@ XXH3_len_4to8_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_
         m128.low64  ^= (m128.high64 >> 3);
 
         m128.low64   = XXH_xorshift64(m128.low64, 35);
-        m128.low64  *= 0x9FB21C651E98DF25ULL;
+        m128.low64  *= PRIME_MX2;
         m128.low64   = XXH_xorshift64(m128.low64, 28);
         m128.high64  = XXH3_avalanche(m128.high64);
         return m128;
     }
 }
 
-XXH_FORCE_INLINE XXH128_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(input != NULL);
@@ -5207,7 +6557,7 @@ XXH3_len_9to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64
 /*
  * Assumption: `secret` size is >= XXH3_SECRET_SIZE_MIN
  */
-XXH_FORCE_INLINE XXH128_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_0to16_128b(const xxh_u8* input, size_t len, const xxh_u8* secret, XXH64_hash_t seed)
 {
     XXH_ASSERT(len <= 16);
@@ -5238,7 +6588,7 @@ XXH128_mix32B(XXH128_hash_t acc, const xxh_u8* input_1, const xxh_u8* input_2,
 }
 
 
-XXH_FORCE_INLINE XXH128_hash_t
+XXH_FORCE_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
                       const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
                       XXH64_hash_t seed)
@@ -5249,6 +6599,16 @@ XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
     {   XXH128_hash_t acc;
         acc.low64 = len * XXH_PRIME64_1;
         acc.high64 = 0;
+
+#if XXH_SIZE_OPT >= 1
+        {
+            /* Smaller, but slightly slower. */
+            unsigned int i = (unsigned int)(len - 1) / 32;
+            do {
+                acc = XXH128_mix32B(acc, input+16*i, input+len-16*(i+1), secret+32*i, seed);
+            } while (i-- != 0);
+        }
+#else
         if (len > 32) {
             if (len > 64) {
                 if (len > 96) {
@@ -5259,6 +6619,7 @@ XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
             acc = XXH128_mix32B(acc, input+16, input+len-32, secret+32, seed);
         }
         acc = XXH128_mix32B(acc, input, input+len-16, secret, seed);
+#endif
         {   XXH128_hash_t h128;
             h128.low64  = acc.low64 + acc.high64;
             h128.high64 = (acc.low64    * XXH_PRIME64_1)
@@ -5271,7 +6632,7 @@ XXH3_len_17to128_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
     }
 }
 
-XXH_NO_INLINE XXH128_hash_t
+XXH_NO_INLINE XXH_PUREF XXH128_hash_t
 XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
                        const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
                        XXH64_hash_t seed)
@@ -5280,25 +6641,34 @@ XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
     XXH_ASSERT(128 < len && len <= XXH3_MIDSIZE_MAX);
 
     {   XXH128_hash_t acc;
-        int const nbRounds = (int)len / 32;
-        int i;
+        unsigned i;
         acc.low64 = len * XXH_PRIME64_1;
         acc.high64 = 0;
-        for (i=0; i<4; i++) {
+        /*
+         *  We set as `i` as offset + 32. We do this so that unchanged
+         * `len` can be used as upper bound. This reaches a sweet spot
+         * where both x86 and aarch64 get simple agen and good codegen
+         * for the loop.
+         */
+        for (i = 32; i < 160; i += 32) {
             acc = XXH128_mix32B(acc,
-                                input  + (32 * i),
-                                input  + (32 * i) + 16,
-                                secret + (32 * i),
+                                input  + i - 32,
+                                input  + i - 16,
+                                secret + i - 32,
                                 seed);
         }
         acc.low64 = XXH3_avalanche(acc.low64);
         acc.high64 = XXH3_avalanche(acc.high64);
-        XXH_ASSERT(nbRounds >= 4);
-        for (i=4 ; i < nbRounds; i++) {
+        /*
+         * NB: `i <= len` will duplicate the last 32-bytes if
+         * len % 32 was zero. This is an unfortunate necessity to keep
+         * the hash result stable.
+         */
+        for (i=160; i <= len; i += 32) {
             acc = XXH128_mix32B(acc,
-                                input + (32 * i),
-                                input + (32 * i) + 16,
-                                secret + XXH3_MIDSIZE_STARTOFFSET + (32 * (i - 4)),
+                                input + i - 32,
+                                input + i - 16,
+                                secret + XXH3_MIDSIZE_STARTOFFSET + i - 160,
                                 seed);
         }
         /* last bytes */
@@ -5306,7 +6676,7 @@ XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
                             input + len - 16,
                             input + len - 32,
                             secret + XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET - 16,
-                            0ULL - seed);
+                            (XXH64_hash_t)0 - seed);
 
         {   XXH128_hash_t h128;
             h128.low64  = acc.low64 + acc.high64;
@@ -5323,12 +6693,12 @@ XXH3_len_129to240_128b(const xxh_u8* XXH_RESTRICT input, size_t len,
 XXH_FORCE_INLINE XXH128_hash_t
 XXH3_hashLong_128b_internal(const void* XXH_RESTRICT input, size_t len,
                             const xxh_u8* XXH_RESTRICT secret, size_t secretSize,
-                            XXH3_f_accumulate_512 f_acc512,
+                            XXH3_f_accumulate f_acc,
                             XXH3_f_scrambleAcc f_scramble)
 {
     XXH_ALIGN(XXH_ACC_ALIGN) xxh_u64 acc[XXH_ACC_NB] = XXH3_INIT_ACC;
 
-    XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, secret, secretSize, f_acc512, f_scramble);
+    XXH3_hashLong_internal_loop(acc, (const xxh_u8*)input, len, secret, secretSize, f_acc, f_scramble);
 
     /* converge into final hash */
     XXH_STATIC_ASSERT(sizeof(acc) == 64);
@@ -5346,47 +6716,50 @@ XXH3_hashLong_128b_internal(const void* XXH_RESTRICT input, size_t len,
 }
 
 /*
- * It's important for performance that XXH3_hashLong is not inlined.
+ * It's important for performance that XXH3_hashLong() is not inlined.
  */
-XXH_NO_INLINE XXH128_hash_t
+XXH_NO_INLINE XXH_PUREF XXH128_hash_t
 XXH3_hashLong_128b_default(const void* XXH_RESTRICT input, size_t len,
                            XXH64_hash_t seed64,
                            const void* XXH_RESTRICT secret, size_t secretLen)
 {
     (void)seed64; (void)secret; (void)secretLen;
     return XXH3_hashLong_128b_internal(input, len, XXH3_kSecret, sizeof(XXH3_kSecret),
-                                       XXH3_accumulate_512, XXH3_scrambleAcc);
+                                       XXH3_accumulate, XXH3_scrambleAcc);
 }
 
 /*
- * It's important for performance to pass @secretLen (when it's static)
+ * It's important for performance to pass @p secretLen (when it's static)
  * to the compiler, so that it can properly optimize the vectorized loop.
+ *
+ * When the secret size is unknown, or on GCC 12 where the mix of NO_INLINE and FORCE_INLINE
+ * breaks -Og, this is XXH_NO_INLINE.
  */
-XXH_FORCE_INLINE XXH128_hash_t
+XXH3_WITH_SECRET_INLINE XXH128_hash_t
 XXH3_hashLong_128b_withSecret(const void* XXH_RESTRICT input, size_t len,
                               XXH64_hash_t seed64,
                               const void* XXH_RESTRICT secret, size_t secretLen)
 {
     (void)seed64;
     return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, secretLen,
-                                       XXH3_accumulate_512, XXH3_scrambleAcc);
+                                       XXH3_accumulate, XXH3_scrambleAcc);
 }
 
 XXH_FORCE_INLINE XXH128_hash_t
 XXH3_hashLong_128b_withSeed_internal(const void* XXH_RESTRICT input, size_t len,
                                 XXH64_hash_t seed64,
-                                XXH3_f_accumulate_512 f_acc512,
+                                XXH3_f_accumulate f_acc,
                                 XXH3_f_scrambleAcc f_scramble,
                                 XXH3_f_initCustomSecret f_initSec)
 {
     if (seed64 == 0)
         return XXH3_hashLong_128b_internal(input, len,
                                            XXH3_kSecret, sizeof(XXH3_kSecret),
-                                           f_acc512, f_scramble);
+                                           f_acc, f_scramble);
     {   XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
         f_initSec(secret, seed64);
         return XXH3_hashLong_128b_internal(input, len, (const xxh_u8*)secret, sizeof(secret),
-                                           f_acc512, f_scramble);
+                                           f_acc, f_scramble);
     }
 }
 
@@ -5399,7 +6772,7 @@ XXH3_hashLong_128b_withSeed(const void* input, size_t len,
 {
     (void)secret; (void)secretLen;
     return XXH3_hashLong_128b_withSeed_internal(input, len, seed64,
-                XXH3_accumulate_512, XXH3_scrambleAcc, XXH3_initCustomSecret);
+                XXH3_accumulate, XXH3_scrambleAcc, XXH3_initCustomSecret);
 }
 
 typedef XXH128_hash_t (*XXH3_hashLong128_f)(const void* XXH_RESTRICT, size_t,
@@ -5429,94 +6802,93 @@ XXH3_128bits_internal(const void* input, size_t len,
 
 /* ===   Public XXH128 API   === */
 
-/*! @ingroup xxh3_family */
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(const void* input, size_t len)
+/*! @ingroup XXH3_family */
+XXH_PUBLIC_API XXH128_hash_t XXH3_128bits(XXH_NOESCAPE const void* input, size_t len)
 {
     return XXH3_128bits_internal(input, len, 0,
                                  XXH3_kSecret, sizeof(XXH3_kSecret),
                                  XXH3_hashLong_128b_default);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH128_hash_t
-XXH3_128bits_withSecret(const void* input, size_t len, const void* secret, size_t secretSize)
+XXH3_128bits_withSecret(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize)
 {
     return XXH3_128bits_internal(input, len, 0,
                                  (const xxh_u8*)secret, secretSize,
                                  XXH3_hashLong_128b_withSecret);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH128_hash_t
-XXH3_128bits_withSeed(const void* input, size_t len, XXH64_hash_t seed)
+XXH3_128bits_withSeed(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed)
 {
     return XXH3_128bits_internal(input, len, seed,
                                  XXH3_kSecret, sizeof(XXH3_kSecret),
                                  XXH3_hashLong_128b_withSeed);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH128_hash_t
-XXH3_128bits_withSecretandSeed(const void* input, size_t len, const void* secret, size_t secretSize, XXH64_hash_t seed)
+XXH3_128bits_withSecretandSeed(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed)
 {
     if (len <= XXH3_MIDSIZE_MAX)
         return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), NULL);
     return XXH3_hashLong_128b_withSecret(input, len, seed, secret, secretSize);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH128_hash_t
-XXH128(const void* input, size_t len, XXH64_hash_t seed)
+XXH128(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed)
 {
     return XXH3_128bits_withSeed(input, len, seed);
 }
 
 
 /* ===   XXH3 128-bit streaming   === */
-
+#ifndef XXH_NO_STREAM
 /*
  * All initialization and update functions are identical to 64-bit streaming variant.
  * The only difference is the finalization routine.
  */
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_reset(XXH3_state_t* statePtr)
+XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr)
 {
     return XXH3_64bits_reset(statePtr);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_reset_withSecret(XXH3_state_t* statePtr, const void* secret, size_t secretSize)
+XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize)
 {
     return XXH3_64bits_reset_withSecret(statePtr, secret, secretSize);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_reset_withSeed(XXH3_state_t* statePtr, XXH64_hash_t seed)
+XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed)
 {
     return XXH3_64bits_reset_withSeed(statePtr, seed);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_reset_withSecretandSeed(XXH3_state_t* statePtr, const void* secret, size_t secretSize, XXH64_hash_t seed)
+XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize, XXH64_hash_t seed)
 {
     return XXH3_64bits_reset_withSecretandSeed(statePtr, secret, secretSize, seed);
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_128bits_update(XXH3_state_t* state, const void* input, size_t len)
+XXH3_128bits_update(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len)
 {
-    return XXH3_update(state, (const xxh_u8*)input, len,
-                       XXH3_accumulate_512, XXH3_scrambleAcc);
+    return XXH3_64bits_update(state, input, len);
 }
 
-/*! @ingroup xxh3_family */
-XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (const XXH3_state_t* state)
+/*! @ingroup XXH3_family */
+XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_t* state)
 {
     const unsigned char* const secret = (state->extSecret == NULL) ? state->customSecret : state->extSecret;
     if (state->totalLen > XXH3_MIDSIZE_MAX) {
@@ -5540,13 +6912,13 @@ XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (const XXH3_state_t* state)
     return XXH3_128bits_withSecret(state->buffer, (size_t)(state->totalLen),
                                    secret, state->secretLimit + XXH_STRIPE_LEN);
 }
-
+#endif /* !XXH_NO_STREAM */
 /* 128-bit utility functions */
 
 #include    /* memcmp, memcpy */
 
 /* return : 1 is equal, 0 if different */
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2)
 {
     /* note : XXH128_hash_t is compact, it has no padding byte */
@@ -5554,11 +6926,11 @@ XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2)
 }
 
 /* This prototype is compatible with stdlib's qsort().
- * return : >0 if *h128_1  > *h128_2
- *          <0 if *h128_1  < *h128_2
- *          =0 if *h128_1 == *h128_2  */
-/*! @ingroup xxh3_family */
-XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2)
+ * @return : >0 if *h128_1  > *h128_2
+ *           <0 if *h128_1  < *h128_2
+ *           =0 if *h128_1 == *h128_2  */
+/*! @ingroup XXH3_family */
+XXH_PUBLIC_API int XXH128_cmp(XXH_NOESCAPE const void* h128_1, XXH_NOESCAPE const void* h128_2)
 {
     XXH128_hash_t const h1 = *(const XXH128_hash_t*)h128_1;
     XXH128_hash_t const h2 = *(const XXH128_hash_t*)h128_2;
@@ -5570,9 +6942,9 @@ XXH_PUBLIC_API int XXH128_cmp(const void* h128_1, const void* h128_2)
 
 
 /*======   Canonical representation   ======*/
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API void
-XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash)
+XXH128_canonicalFromHash(XXH_NOESCAPE XXH128_canonical_t* dst, XXH128_hash_t hash)
 {
     XXH_STATIC_ASSERT(sizeof(XXH128_canonical_t) == sizeof(XXH128_hash_t));
     if (XXH_CPU_LITTLE_ENDIAN) {
@@ -5583,9 +6955,9 @@ XXH128_canonicalFromHash(XXH128_canonical_t* dst, XXH128_hash_t hash)
     XXH_memcpy((char*)dst + sizeof(hash.high64), &hash.low64, sizeof(hash.low64));
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH128_hash_t
-XXH128_hashFromCanonical(const XXH128_canonical_t* src)
+XXH128_hashFromCanonical(XXH_NOESCAPE const XXH128_canonical_t* src)
 {
     XXH128_hash_t h;
     h.high64 = XXH_readBE64(src);
@@ -5607,9 +6979,9 @@ XXH_FORCE_INLINE void XXH3_combine16(void* dst, XXH128_hash_t h128)
     XXH_writeLE64( (char*)dst+8, XXH_readLE64((char*)dst+8) ^ h128.high64 );
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API XXH_errorcode
-XXH3_generateSecret(void* secretBuffer, size_t secretSize, const void* customSeed, size_t customSeedSize)
+XXH3_generateSecret(XXH_NOESCAPE void* secretBuffer, size_t secretSize, XXH_NOESCAPE const void* customSeed, size_t customSeedSize)
 {
 #if (XXH_DEBUGLEVEL >= 1)
     XXH_ASSERT(secretBuffer != NULL);
@@ -5652,9 +7024,9 @@ XXH3_generateSecret(void* secretBuffer, size_t secretSize, const void* customSee
     return XXH_OK;
 }
 
-/*! @ingroup xxh3_family */
+/*! @ingroup XXH3_family */
 XXH_PUBLIC_API void
-XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed)
+XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed)
 {
     XXH_ALIGN(XXH_SEC_ALIGN) xxh_u8 secret[XXH_SECRET_DEFAULT_SIZE];
     XXH3_initCustomSecret(secret, seed);
@@ -5667,7 +7039,7 @@ XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed)
 /* Pop our optimization override from above */
 #if XXH_VECTOR == XXH_AVX2 /* AVX2 */ \
   && defined(__GNUC__) && !defined(__clang__) /* GCC, not Clang */ \
-  && defined(__OPTIMIZE__) && !defined(__OPTIMIZE_SIZE__) /* respect -O0 and -Os */
+  && defined(__OPTIMIZE__) && XXH_SIZE_OPT <= 0 /* respect -O0 and -Os */
 #  pragma GCC pop_options
 #endif
 
@@ -5682,5 +7054,5 @@ XXH3_generateSecret_fromSeed(void* secretBuffer, XXH64_hash_t seed)
 
 
 #if defined (__cplusplus)
-}
+} /* extern "C" */
 #endif

From 3fd5f9f52dff5e4e8a9afcf9afb1abc946844535 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 13 Nov 2023 15:46:59 -0800
Subject: [PATCH 118/937] fix the copyright linter

---
 lib/common/xxhash.c | 2 +-
 lib/common/xxhash.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/common/xxhash.c b/lib/common/xxhash.c
index 1a8f735ba..50640c765 100644
--- a/lib/common/xxhash.c
+++ b/lib/common/xxhash.c
@@ -1,6 +1,6 @@
 /*
  * xxHash - Extremely Fast Hash algorithm
- * Copyright (C) 2012-2023 Yann Collet
+ * Copyright (c) Yann Collet - Meta Platforms, Inc
  *
  * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
  *
diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index fe3abc1b4..2abdc0734 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -1,7 +1,7 @@
 /*
  * xxHash - Extremely Fast Hash algorithm
  * Header File
- * Copyright (C) 2012-2023 Yann Collet
+ * Copyright (c) Yann Collet - Meta Platforms, Inc
  *
  * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
  *

From 136a16dd8b4c71526771528ffbbe8d19fde50f85 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 12:00:11 -0800
Subject: [PATCH 119/937] [linux] Backport intptr_t removal

Linux started providing intptr_t in  so we no longer need
to define it here.

https://lkml.kernel.org/r/ed66b9e4-1fb7-45be-9bb9-d4bc291c691f@p183
---
 contrib/linux-kernel/zstd_deps.h | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/contrib/linux-kernel/zstd_deps.h b/contrib/linux-kernel/zstd_deps.h
index 670c5fa2a..f931f7d0e 100644
--- a/contrib/linux-kernel/zstd_deps.h
+++ b/contrib/linux-kernel/zstd_deps.h
@@ -115,11 +115,7 @@ static uint64_t ZSTD_div64(uint64_t dividend, uint32_t divisor) {
 #ifndef ZSTD_DEPS_STDINT
 #define ZSTD_DEPS_STDINT
 
-/*
- * The Linux Kernel doesn't provide intptr_t, only uintptr_t, which
- * is an unsigned long.
- */
-typedef long intptr_t;
+/* intptr_t already provided by ZSTD_DEPS_COMMON */
 
 #endif /* ZSTD_DEPS_STDINT */
 #endif /* ZSTD_DEPS_NEED_STDINT */

From ca498343dd9932a9b6463eefda96c05b2c567391 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 12:02:07 -0800
Subject: [PATCH 120/937] [linux] Backport fix for arry-index-out-of-bounds
 UBSAN warning

Backport the fix already in the kernel, and is fixed in the dev branch
in a different way.

https://lkml.kernel.org/r/20231012213428.1390905-1-nickrterrell@gmail.com
---
 lib/common/fse_decompress.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/common/fse_decompress.c b/lib/common/fse_decompress.c
index 1e1c9f92d..d0781d5d7 100644
--- a/lib/common/fse_decompress.c
+++ b/lib/common/fse_decompress.c
@@ -237,7 +237,7 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
 
 typedef struct {
     short ncount[FSE_MAX_SYMBOL_VALUE + 1];
-    FSE_DTable dtable[1]; /* Dynamically sized */
+    FSE_DTable dtable[]; /* Dynamically sized */
 } FSE_DecompressWksp;
 
 

From 59dcc475798b3e522be8cd3ba41a170b34c10d63 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 16 Nov 2023 16:19:25 -0800
Subject: [PATCH 121/937] update license text

---
 lib/common/xxhash.c | 37 ++++++-------------------------------
 lib/common/xxhash.h | 32 ++++----------------------------
 2 files changed, 10 insertions(+), 59 deletions(-)

diff --git a/lib/common/xxhash.c b/lib/common/xxhash.c
index 50640c765..052cd5228 100644
--- a/lib/common/xxhash.c
+++ b/lib/common/xxhash.c
@@ -2,42 +2,17 @@
  * xxHash - Extremely Fast Hash algorithm
  * Copyright (c) Yann Collet - Meta Platforms, Inc
  *
- * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *    * Redistributions of source code must retain the above copyright
- *      notice, this list of conditions and the following disclaimer.
- *    * Redistributions in binary form must reproduce the above
- *      copyright notice, this list of conditions and the following disclaimer
- *      in the documentation and/or other materials provided with the
- *      distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * You can contact the author at:
- *   - xxHash homepage: https://www.xxhash.com
- *   - xxHash source repository: https://github.com/Cyan4973/xxHash
+ * 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.
  */
 
-
 /*
  * xxhash.c instantiates functions defined in xxhash.h
  */
 
-#define XXH_STATIC_LINKING_ONLY   /* access advanced declarations */
-#define XXH_IMPLEMENTATION   /* access definitions */
+#define XXH_STATIC_LINKING_ONLY /* access advanced declarations */
+#define XXH_IMPLEMENTATION      /* access definitions */
 
 #include "xxhash.h"
diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 2abdc0734..424ed19b8 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -3,34 +3,10 @@
  * Header File
  * Copyright (c) Yann Collet - Meta Platforms, Inc
  *
- * BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *    * Redistributions of source code must retain the above copyright
- *      notice, this list of conditions and the following disclaimer.
- *    * Redistributions in binary form must reproduce the above
- *      copyright notice, this list of conditions and the following disclaimer
- *      in the documentation and/or other materials provided with the
- *      distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * You can contact the author at:
- *   - xxHash homepage: https://www.xxhash.com
- *   - xxHash source repository: https://github.com/Cyan4973/xxHash
+ * 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.
  */
 
 /* Local adaptations for Zstandard */

From 58b3ef79eb9f1e6613684ea6e5b89720660ee8b6 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 16:53:44 -0800
Subject: [PATCH 122/937] [linux] Remove usage of deprecated function

ZSTD_resetDStream() is deprecated and replaced by ZSTD_DCtx_reset().
This removes deprecation warnings from the kernel build.

This change is a no-op, see the docs suggesting this replacement.

https://github.com/facebook/zstd/blob/fcbf2fde9ac7ce1562c7b3a394350e764bcb580f/lib/zstd.h#L2655-L2663
---
 contrib/linux-kernel/zstd_decompress_module.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/contrib/linux-kernel/zstd_decompress_module.c b/contrib/linux-kernel/zstd_decompress_module.c
index eb1c49e69..7d31518e9 100644
--- a/contrib/linux-kernel/zstd_decompress_module.c
+++ b/contrib/linux-kernel/zstd_decompress_module.c
@@ -77,7 +77,7 @@ EXPORT_SYMBOL(zstd_init_dstream);
 
 size_t zstd_reset_dstream(zstd_dstream *dstream)
 {
-	return ZSTD_resetDStream(dstream);
+	return ZSTD_DCtx_reset(dstream, ZSTD_reset_session_only);
 }
 EXPORT_SYMBOL(zstd_reset_dstream);
 

From a419265d30f4fa05caa8df0b12fac1ce2558ec6a Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 12:00:11 -0800
Subject: [PATCH 123/937] [linux] Backport intptr_t removal

Linux started providing intptr_t in  so we no longer need
to define it here.

https://lkml.kernel.org/r/ed66b9e4-1fb7-45be-9bb9-d4bc291c691f@p183
---
 contrib/linux-kernel/zstd_deps.h | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/contrib/linux-kernel/zstd_deps.h b/contrib/linux-kernel/zstd_deps.h
index 670c5fa2a..f931f7d0e 100644
--- a/contrib/linux-kernel/zstd_deps.h
+++ b/contrib/linux-kernel/zstd_deps.h
@@ -115,11 +115,7 @@ static uint64_t ZSTD_div64(uint64_t dividend, uint32_t divisor) {
 #ifndef ZSTD_DEPS_STDINT
 #define ZSTD_DEPS_STDINT
 
-/*
- * The Linux Kernel doesn't provide intptr_t, only uintptr_t, which
- * is an unsigned long.
- */
-typedef long intptr_t;
+/* intptr_t already provided by ZSTD_DEPS_COMMON */
 
 #endif /* ZSTD_DEPS_STDINT */
 #endif /* ZSTD_DEPS_NEED_STDINT */

From c2d470581eaee3dc9f747dbab16d1fc0816f94aa Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 16:53:44 -0800
Subject: [PATCH 124/937] [linux] Remove usage of deprecated function

ZSTD_resetDStream() is deprecated and replaced by ZSTD_DCtx_reset().
This removes deprecation warnings from the kernel build.

This change is a no-op, see the docs suggesting this replacement.

https://github.com/facebook/zstd/blob/fcbf2fde9ac7ce1562c7b3a394350e764bcb580f/lib/zstd.h#L2655-L2663
---
 contrib/linux-kernel/zstd_decompress_module.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/contrib/linux-kernel/zstd_decompress_module.c b/contrib/linux-kernel/zstd_decompress_module.c
index eb1c49e69..7d31518e9 100644
--- a/contrib/linux-kernel/zstd_decompress_module.c
+++ b/contrib/linux-kernel/zstd_decompress_module.c
@@ -77,7 +77,7 @@ EXPORT_SYMBOL(zstd_init_dstream);
 
 size_t zstd_reset_dstream(zstd_dstream *dstream)
 {
-	return ZSTD_resetDStream(dstream);
+	return ZSTD_DCtx_reset(dstream, ZSTD_reset_session_only);
 }
 EXPORT_SYMBOL(zstd_reset_dstream);
 

From e122fcbf58e142e837a2bba382ef7ca4f5eaa13b Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 16 Nov 2023 17:15:25 -0800
Subject: [PATCH 125/937] [debug] Don't define g_debuglevel in the kernel

We only use this constant when `DEBUGLEVEL>=2`, but we get
-Werror=pedantic errors for empty translation units, so still define it
except in kernel environments.

Backport from the kernel:

https://lore.kernel.org/lkml/20230616144400.172683-1-ben.dooks@codethink.co.uk/
---
 lib/common/debug.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/lib/common/debug.c b/lib/common/debug.c
index ebf7bfccf..9d0b7d229 100644
--- a/lib/common/debug.c
+++ b/lib/common/debug.c
@@ -21,4 +21,10 @@
 
 #include "debug.h"
 
+#if !defined(ZSTD_LINUX_KERNEL) || (DEBUGLEVEL>=2)
+/* We only use this when DEBUGLEVEL>=2, but we get -Werror=pedantic errors if a
+ * translation unit is empty. So remove this from Linux kernel builds, but
+ * otherwise just leave it in.
+ */
 int g_debuglevel = DEBUGLEVEL;
+#endif

From c7269add7eaf028ed828d9af41e732cf01993aad Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Fri, 17 Nov 2023 18:20:19 -0800
Subject: [PATCH 126/937] [huf] Improve fast huffman decoding speed in linux
 kernel

gcc in the linux kernel was not unrolling the inner loops of the Huffman
decoder, which was destroying decoding performance. The compiler was
generating crazy code with all sorts of branches. I suspect because of
Spectre mitigations, but I'm not certain. Once the loops were manually
unrolled, performance was restored.

Additionally, when gcc couldn't prove that the variable left shift in
the 4X2 decode loop wasn't greater than 63, it inserted checks to verify
it. To fix this, mask `entry.nbBits & 0x3F`, which allows gcc to eliete
this check. This is a no op, because `entry.nbBits` is guaranteed to be
less than 64.

Lastly, introduce the `HUF_DISABLE_FAST_DECODE` macro to disable the
fast C loops for Issue #3762. So if even after this change, there is a
performance regression, users can opt-out at compile time.
---
 lib/README.md                   |   4 +
 lib/decompress/huf_decompress.c | 171 ++++++++++++++++++++------------
 2 files changed, 109 insertions(+), 66 deletions(-)

diff --git a/lib/README.md b/lib/README.md
index 572b7df78..a560f06ca 100644
--- a/lib/README.md
+++ b/lib/README.md
@@ -178,6 +178,10 @@ The file structure is designed to make this selection manually achievable for an
   `ZSTDERRORLIB_VSIBILITY`, and `ZDICTLIB_VISIBILITY` if unset, for backwards compatibility
   with the old macro names.
 
+- The C compiler macro `HUF_DISABLE_FAST_DECODE` disables the newer Huffman fast C
+  and assembly decoding loops. You may want to use this macro if these loops are
+  slower on your platform.
+
 #### Windows : using MinGW+MSYS to create DLL
 
 DLL can be created using MinGW+MSYS with the `make libzstd` command.
diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index 15e420402..5bbdef49a 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -34,6 +34,12 @@
 *  Macros
 ****************************************************************/
 
+#ifdef HUF_DISABLE_FAST_DECODE
+# define HUF_ENABLE_FAST_DECODE 0
+#else
+# define HUF_ENABLE_FAST_DECODE 1
+#endif
+
 /* These two optional macros force the use one way or another of the two
  * Huffman decompression implementations. You can't force in both directions
  * at the same time.
@@ -292,6 +298,24 @@ static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArg
     return 0;
 }
 
+/* Calls X(N) for each stream 0, 1, 2, 3. */
+#define HUF_4X_FOR_EACH_STREAM(X) \
+    {                             \
+        X(0)                      \
+        X(1)                      \
+        X(2)                      \
+        X(3)                      \
+    }
+
+/* Calls X(N, var) for each stream 0, 1, 2, 3. */
+#define HUF_4X_FOR_EACH_STREAM_WITH_VAR(X, var) \
+    {                                           \
+        X(0, (var))                             \
+        X(1, (var))                             \
+        X(2, (var))                             \
+        X(3, (var))                             \
+    }
+
 
 #ifndef HUF_FORCE_DECOMPRESS_X2
 
@@ -706,7 +730,6 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     for (;;) {
         BYTE* olimit;
         int stream;
-        int symbol;
 
         /* Assert loop preconditions */
 #ifndef NDEBUG
@@ -753,27 +776,42 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         }
 #endif
 
+#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol)                 \
+    {                                                           \
+        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_RELOAD_STREAM(_stream)                              \
+    {                                                               \
+        int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
+        int const nbBits = ctz & 7;                                 \
+        int const nbBytes = ctz >> 3;                               \
+        op[(_stream)] += 5;                                         \
+        ip[(_stream)] -= nbBytes;                                   \
+        bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
+        bits[(_stream)] <<= nbBits;                                 \
+    }
+
+        /* Manually unroll the loop because compilers don't consistently
+         * unroll the inner loops, which destroys performance.
+         */
         do {
             /* Decode 5 symbols in each of the 4 streams */
-            for (symbol = 0; symbol < 5; ++symbol) {
-                for (stream = 0; stream < 4; ++stream) {
-                    int const index = (int)(bits[stream] >> 53);
-                    int const entry = (int)dtable[index];
-                    bits[stream] <<= (entry & 63);
-                    op[stream][symbol] = (BYTE)((entry >> 8) & 0xFF);
-                }
-            }
-            /* Reload the bitstreams */
-            for (stream = 0; stream < 4; ++stream) {
-                int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
-                int const nbBits = ctz & 7;
-                int const nbBytes = ctz >> 3;
-                op[stream] += 5;
-                ip[stream] -= nbBytes;
-                bits[stream] = MEM_read64(ip[stream]) | 1;
-                bits[stream] <<= nbBits;
-            }
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3)
+            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)
         } while (op[3] < olimit);
+
+#undef HUF_4X1_DECODE_SYMBOL
+#undef HUF_4X1_RELOAD_STREAM
     }
 
 _out:
@@ -869,7 +907,7 @@ static size_t HUF_decompress4X1_usingDTable_internal(void* dst, size_t dstSize,
     }
 #endif
 
-    if (!(flags & HUF_flags_disableFast)) {
+    if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) {
         size_t const ret = HUF_decompress4X1_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
         if (ret != 0)
             return ret;
@@ -1492,7 +1530,6 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     for (;;) {
         BYTE* olimit;
         int stream;
-        int symbol;
 
         /* Assert loop preconditions */
 #ifndef NDEBUG
@@ -1549,54 +1586,56 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         }
 #endif
 
+#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3)        \
+    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_RELOAD_STREAM(_stream)                                  \
+    {                                                                   \
+        HUF_4X2_DECODE_SYMBOL(3, 1)                                     \
+        {                                                               \
+            int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
+            int const nbBits = ctz & 7;                                 \
+            int const nbBytes = ctz >> 3;                               \
+            ip[(_stream)] -= nbBytes;                                   \
+            bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
+            bits[(_stream)] <<= nbBits;                                 \
+        }                                                               \
+    }
+
+        /* Manually unroll the loop because compilers don't consistently
+         * unroll the inner loops, which destroys performance.
+         */
         do {
-            /* Do 5 table lookups for each of the first 3 streams */
-            for (symbol = 0; symbol < 5; ++symbol) {
-                for (stream = 0; stream < 3; ++stream) {
-                    int const index = (int)(bits[stream] >> 53);
-                    HUF_DEltX2 const entry = dtable[index];
-                    MEM_write16(op[stream], entry.sequence);
-                    bits[stream] <<= (entry.nbBits);
-                    op[stream] += (entry.length);
-                }
-            }
-            /* Do 1 table lookup from the final stream */
-            {
-                int const index = (int)(bits[3] >> 53);
-                HUF_DEltX2 const entry = dtable[index];
-                MEM_write16(op[3], entry.sequence);
-                bits[3] <<= (entry.nbBits);
-                op[3] += (entry.length);
-            }
-            /* Do 4 table lookups from the final stream & reload bitstreams */
-            for (stream = 0; stream < 4; ++stream) {
-                /* Do a table lookup from the final stream.
-                 * This is interleaved with the reloading to reduce register
-                 * pressure. This shouldn't be necessary, but compilers can
-                 * struggle with codegen with high register pressure.
-                 */
-                {
-                    int const index = (int)(bits[3] >> 53);
-                    HUF_DEltX2 const entry = dtable[index];
-                    MEM_write16(op[3], entry.sequence);
-                    bits[3] <<= (entry.nbBits);
-                    op[3] += (entry.length);
-                }
-                /* Reload the bistreams. The final bitstream must be reloaded
-                 * after the 5th symbol was decoded.
-                 */
-                {
-                    int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
-                    int const nbBits = ctz & 7;
-                    int const nbBytes = ctz >> 3;
-                    ip[stream] -= nbBytes;
-                    bits[stream] = MEM_read64(ip[stream]) | 1;
-                    bits[stream] <<= nbBits;
-                }
-            }
+            /* Decode 5 symbols from each of the first 3 streams.
+             * 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(HUF_4X2_RELOAD_STREAM)
         } while (op[3] < olimit);
     }
 
+#undef HUF_4X2_DECODE_SYMBOL
+#undef HUF_4X2_RELOAD_STREAM
+
 _out:
 
     /* Save the final values of each of the state variables back to args. */
@@ -1681,7 +1720,7 @@ static size_t HUF_decompress4X2_usingDTable_internal(void* dst, size_t dstSize,
     }
 #endif
 
-    if (!(flags & HUF_flags_disableFast)) {
+    if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) {
         size_t const ret = HUF_decompress4X2_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
         if (ret != 0)
             return ret;

From 3ff79dbe942dcaaac464bcd57ffbd3123e585248 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Fri, 17 Nov 2023 18:20:19 -0800
Subject: [PATCH 127/937] [huf] Improve fast huffman decoding speed in linux
 kernel

gcc in the linux kernel was not unrolling the inner loops of the Huffman
decoder, which was destroying decoding performance. The compiler was
generating crazy code with all sorts of branches. I suspect because of
Spectre mitigations, but I'm not certain. Once the loops were manually
unrolled, performance was restored.

Additionally, when gcc couldn't prove that the variable left shift in
the 4X2 decode loop wasn't greater than 63, it inserted checks to verify
it. To fix this, mask `entry.nbBits & 0x3F`, which allows gcc to eliete
this check. This is a no op, because `entry.nbBits` is guaranteed to be
less than 64.

Lastly, introduce the `HUF_DISABLE_FAST_DECODE` macro to disable the
fast C loops for Issue #3762. So if even after this change, there is a
performance regression, users can opt-out at compile time.
---
 lib/README.md                   |   4 +
 lib/decompress/huf_decompress.c | 171 ++++++++++++++++++++------------
 2 files changed, 109 insertions(+), 66 deletions(-)

diff --git a/lib/README.md b/lib/README.md
index c3b5d1817..3fe9acdf4 100644
--- a/lib/README.md
+++ b/lib/README.md
@@ -169,6 +169,10 @@ The file structure is designed to make this selection manually achievable for an
   `ZSTDERRORLIB_VSIBILITY`, and `ZDICTLIB_VISIBILITY` if unset, for backwards compatibility
   with the old macro names.
 
+- The C compiler macro `HUF_DISABLE_FAST_DECODE` disables the newer Huffman fast C
+  and assembly decoding loops. You may want to use this macro if these loops are
+  slower on your platform.
+
 #### Windows : using MinGW+MSYS to create DLL
 
 DLL can be created using MinGW+MSYS with the `make libzstd` command.
diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index 5b217ac58..9a9196171 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -34,6 +34,12 @@
 *  Macros
 ****************************************************************/
 
+#ifdef HUF_DISABLE_FAST_DECODE
+# define HUF_ENABLE_FAST_DECODE 0
+#else
+# define HUF_ENABLE_FAST_DECODE 1
+#endif
+
 /* These two optional macros force the use one way or another of the two
  * Huffman decompression implementations. You can't force in both directions
  * at the same time.
@@ -292,6 +298,24 @@ static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArg
     return 0;
 }
 
+/* Calls X(N) for each stream 0, 1, 2, 3. */
+#define HUF_4X_FOR_EACH_STREAM(X) \
+    {                             \
+        X(0)                      \
+        X(1)                      \
+        X(2)                      \
+        X(3)                      \
+    }
+
+/* Calls X(N, var) for each stream 0, 1, 2, 3. */
+#define HUF_4X_FOR_EACH_STREAM_WITH_VAR(X, var) \
+    {                                           \
+        X(0, (var))                             \
+        X(1, (var))                             \
+        X(2, (var))                             \
+        X(3, (var))                             \
+    }
+
 
 #ifndef HUF_FORCE_DECOMPRESS_X2
 
@@ -705,7 +729,6 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     for (;;) {
         BYTE* olimit;
         int stream;
-        int symbol;
 
         /* Assert loop preconditions */
 #ifndef NDEBUG
@@ -752,27 +775,42 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         }
 #endif
 
+#define HUF_4X1_DECODE_SYMBOL(_stream, _symbol)                 \
+    {                                                           \
+        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_RELOAD_STREAM(_stream)                              \
+    {                                                               \
+        int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
+        int const nbBits = ctz & 7;                                 \
+        int const nbBytes = ctz >> 3;                               \
+        op[(_stream)] += 5;                                         \
+        ip[(_stream)] -= nbBytes;                                   \
+        bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
+        bits[(_stream)] <<= nbBits;                                 \
+    }
+
+        /* Manually unroll the loop because compilers don't consistently
+         * unroll the inner loops, which destroys performance.
+         */
         do {
             /* Decode 5 symbols in each of the 4 streams */
-            for (symbol = 0; symbol < 5; ++symbol) {
-                for (stream = 0; stream < 4; ++stream) {
-                    int const index = (int)(bits[stream] >> 53);
-                    int const entry = (int)dtable[index];
-                    bits[stream] <<= (entry & 63);
-                    op[stream][symbol] = (BYTE)((entry >> 8) & 0xFF);
-                }
-            }
-            /* Reload the bitstreams */
-            for (stream = 0; stream < 4; ++stream) {
-                int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
-                int const nbBits = ctz & 7;
-                int const nbBytes = ctz >> 3;
-                op[stream] += 5;
-                ip[stream] -= nbBytes;
-                bits[stream] = MEM_read64(ip[stream]) | 1;
-                bits[stream] <<= nbBits;
-            }
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3)
+            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)
         } while (op[3] < olimit);
+
+#undef HUF_4X1_DECODE_SYMBOL
+#undef HUF_4X1_RELOAD_STREAM
     }
 
 _out:
@@ -868,7 +906,7 @@ static size_t HUF_decompress4X1_usingDTable_internal(void* dst, size_t dstSize,
     }
 #endif
 
-    if (!(flags & HUF_flags_disableFast)) {
+    if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) {
         size_t const ret = HUF_decompress4X1_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
         if (ret != 0)
             return ret;
@@ -1490,7 +1528,6 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     for (;;) {
         BYTE* olimit;
         int stream;
-        int symbol;
 
         /* Assert loop preconditions */
 #ifndef NDEBUG
@@ -1547,54 +1584,56 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         }
 #endif
 
+#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3)        \
+    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_RELOAD_STREAM(_stream)                                  \
+    {                                                                   \
+        HUF_4X2_DECODE_SYMBOL(3, 1)                                     \
+        {                                                               \
+            int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
+            int const nbBits = ctz & 7;                                 \
+            int const nbBytes = ctz >> 3;                               \
+            ip[(_stream)] -= nbBytes;                                   \
+            bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
+            bits[(_stream)] <<= nbBits;                                 \
+        }                                                               \
+    }
+
+        /* Manually unroll the loop because compilers don't consistently
+         * unroll the inner loops, which destroys performance.
+         */
         do {
-            /* Do 5 table lookups for each of the first 3 streams */
-            for (symbol = 0; symbol < 5; ++symbol) {
-                for (stream = 0; stream < 3; ++stream) {
-                    int const index = (int)(bits[stream] >> 53);
-                    HUF_DEltX2 const entry = dtable[index];
-                    MEM_write16(op[stream], entry.sequence);
-                    bits[stream] <<= (entry.nbBits);
-                    op[stream] += (entry.length);
-                }
-            }
-            /* Do 1 table lookup from the final stream */
-            {
-                int const index = (int)(bits[3] >> 53);
-                HUF_DEltX2 const entry = dtable[index];
-                MEM_write16(op[3], entry.sequence);
-                bits[3] <<= (entry.nbBits);
-                op[3] += (entry.length);
-            }
-            /* Do 4 table lookups from the final stream & reload bitstreams */
-            for (stream = 0; stream < 4; ++stream) {
-                /* Do a table lookup from the final stream.
-                 * This is interleaved with the reloading to reduce register
-                 * pressure. This shouldn't be necessary, but compilers can
-                 * struggle with codegen with high register pressure.
-                 */
-                {
-                    int const index = (int)(bits[3] >> 53);
-                    HUF_DEltX2 const entry = dtable[index];
-                    MEM_write16(op[3], entry.sequence);
-                    bits[3] <<= (entry.nbBits);
-                    op[3] += (entry.length);
-                }
-                /* Reload the bistreams. The final bitstream must be reloaded
-                 * after the 5th symbol was decoded.
-                 */
-                {
-                    int const ctz = ZSTD_countTrailingZeros64(bits[stream]);
-                    int const nbBits = ctz & 7;
-                    int const nbBytes = ctz >> 3;
-                    ip[stream] -= nbBytes;
-                    bits[stream] = MEM_read64(ip[stream]) | 1;
-                    bits[stream] <<= nbBits;
-                }
-            }
+            /* Decode 5 symbols from each of the first 3 streams.
+             * 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(HUF_4X2_RELOAD_STREAM)
         } while (op[3] < olimit);
     }
 
+#undef HUF_4X2_DECODE_SYMBOL
+#undef HUF_4X2_RELOAD_STREAM
+
 _out:
 
     /* Save the final values of each of the state variables back to args. */
@@ -1679,7 +1718,7 @@ static size_t HUF_decompress4X2_usingDTable_internal(void* dst, size_t dstSize,
     }
 #endif
 
-    if (!(flags & HUF_flags_disableFast)) {
+    if (HUF_ENABLE_FAST_DECODE && !(flags & HUF_flags_disableFast)) {
         size_t const ret = HUF_decompress4X2_usingDTable_internal_fast(dst, dstSize, cSrc, cSrcSize, DTable, loopFn);
         if (ret != 0)
             return ret;

From 5ab78c0418dd2b77e76e8350a563b9771a424b27 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Mon, 20 Nov 2023 11:33:57 -0800
Subject: [PATCH 128/937] [huf] Improve fast C & ASM performance on small data
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

* Rename `ilimit` to `ilowest` and set it equal to `src` instead of
  `src + 6 + 8`. This is safe because the fast decoding loops guarantee
  to never read below `ilowest` already. This allows the fast decoder to
  run for at least two more iterations, because it consumes at most 7
  bytes per iteration.
* Continue the fast loop all the way until the number of safe iterations
 is 0. Initially, I thought that when it got towards the end, the
 computation of how many iterations of safe might become expensive. But
 it ends up being slower to have to decode each of the 4 streams
 individually, which makes sense.

This drastically speeds up the Huffman decoder on the `github` dataset
for the issue raised in #3762, measured with `zstd -b1e1r github/`.

| Decoder  | Speed before | Speed after |
|----------|--------------|-------------|
| Fallback | 477 MB/s     | 477 MB/s    |
| Fast C   | 384 MB/s     | 492 MB/s    |
| Assembly | 385 MB/s     | 501 MB/s    |

We can also look at the speed delta for different block sizes of silesia
using `zstd -b1e1r silesia.tar -B#`.

| Decoder  | -B1K ∆ | -B2K ∆ | -B4K ∆ | -B8K ∆ | -B16K ∆ | -B32K ∆ | -B64K ∆ | -B128K ∆ |
|----------|--------|--------|--------|--------|---------|---------|---------|----------|
| Fast C   | +11.2% | +8.2%  | +6.1%  | +4.4%  | +2.7%   | +1.5%   | +0.6%   | +0.2%    |
| Assembly | +12.5% | +9.0%  | +6.2%  | +3.6%  | +1.5%   | +0.7%   | +0.2%   | +0.03%   |
---
 lib/decompress/huf_decompress.c       | 84 ++++++++++++++-------------
 lib/decompress/huf_decompress_amd64.S | 34 +++++------
 2 files changed, 61 insertions(+), 57 deletions(-)

diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index 5bbdef49a..b8795efb5 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -164,17 +164,18 @@ static size_t HUF_initFastDStream(BYTE const* ip) {
  * op [in/out] - The output pointers, must be updated to reflect what is written.
  * bits [in/out] - The bitstream containers, must be updated to reflect the current state.
  * dt [in] - The decoding table.
- * ilimit [in] - The input limit, stop when any input pointer is below ilimit.
+ * ilowest [in] - The beginning of the valid range of the input. Decoders may read
+ *                down to this pointer. It may be below iend[0].
  * oend [in] - The end of the output stream. op[3] must not cross oend.
  * iend [in] - The end of each input stream. ip[i] may cross iend[i],
- *             as long as it is above ilimit, but that indicates corruption.
+ *             as long as it is above ilowest, but that indicates corruption.
  */
 typedef struct {
     BYTE const* ip[4];
     BYTE* op[4];
     U64 bits[4];
     void const* dt;
-    BYTE const* ilimit;
+    BYTE const* ilowest;
     BYTE* oend;
     BYTE const* iend[4];
 } HUF_DecompressFastArgs;
@@ -192,7 +193,7 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
     void const* dt = DTable + 1;
     U32 const dtLog = HUF_getDTableDesc(DTable).tableLog;
 
-    const BYTE* const ilimit = (const BYTE*)src + 6 + 8;
+    const BYTE* const istart = (const BYTE*)src;
 
     BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
 
@@ -215,7 +216,6 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
 
     /* Read the jump table. */
     {
-        const BYTE* const istart = (const BYTE*)src;
         size_t const length1 = MEM_readLE16(istart);
         size_t const length2 = MEM_readLE16(istart+2);
         size_t const length3 = MEM_readLE16(istart+4);
@@ -227,10 +227,8 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
 
         /* HUF_initFastDStream() requires this, and this small of an input
          * won't benefit from the ASM loop anyways.
-         * length1 must be >= 16 so that ip[0] >= ilimit before the loop
-         * starts.
          */
-        if (length1 < 16 || length2 < 8 || length3 < 8 || length4 < 8)
+        if (length1 < 8 || length2 < 8 || length3 < 8 || length4 < 8)
             return 0;
         if (length4 > srcSize) return ERROR(corruption_detected);   /* overflow */
     }
@@ -262,11 +260,12 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
     args->bits[2] = HUF_initFastDStream(args->ip[2]);
     args->bits[3] = HUF_initFastDStream(args->ip[3]);
 
-    /* If ip[] >= ilimit, it is guaranteed to be safe to
-        * reload bits[]. It may be beyond its section, but is
-        * guaranteed to be valid (>= istart).
-        */
-    args->ilimit = ilimit;
+    /* The decoders must be sure to never read beyond ilowest.
+     * This is lower than iend[0], but allowing decoders to read
+     * down to ilowest can allow an extra iteration or two in the
+     * fast loop.
+     */
+    args->ilowest = istart;
 
     args->oend = oend;
     args->dt = dt;
@@ -291,7 +290,7 @@ static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArg
     assert(sizeof(size_t) == 8);
     bit->bitContainer = MEM_readLEST(args->ip[stream]);
     bit->bitsConsumed = ZSTD_countTrailingZeros64(args->bits[stream]);
-    bit->start = (const char*)args->iend[0];
+    bit->start = (const char*)args->ilowest;
     bit->limitPtr = bit->start + sizeof(size_t);
     bit->ptr = (const char*)args->ip[stream];
 
@@ -717,7 +716,7 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     BYTE* op[4];
     U16 const* const dtable = (U16 const*)args->dt;
     BYTE* const oend = args->oend;
-    BYTE const* const ilimit = args->ilimit;
+    BYTE const* const ilowest = args->ilowest;
 
     /* Copy the arguments to local variables */
     ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
@@ -735,7 +734,7 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
 #ifndef NDEBUG
         for (stream = 0; stream < 4; ++stream) {
             assert(op[stream] <= (stream == 3 ? oend : op[stream + 1]));
-            assert(ip[stream] >= ilimit);
+            assert(ip[stream] >= ilowest);
         }
 #endif
         /* Compute olimit */
@@ -745,7 +744,7 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
             /* Each iteration consumes up to 11 bits * 5 = 55 bits < 7 bytes
              * per stream.
              */
-            size_t const iiters = (size_t)(ip[0] - ilimit) / 7;
+            size_t const iiters = (size_t)(ip[0] - ilowest) / 7;
             /* We can safely run iters iterations before running bounds checks */
             size_t const iters = MIN(oiters, iiters);
             size_t const symbols = iters * 5;
@@ -756,8 +755,8 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
              */
             olimit = op[3] + symbols;
 
-            /* Exit fast decoding loop once we get close to the end. */
-            if (op[3] + 20 > olimit)
+            /* Exit fast decoding loop once we reach the end. */
+            if (op[3] == olimit)
                 break;
 
             /* Exit the decoding loop if any input pointer has crossed the
@@ -836,7 +835,7 @@ HUF_decompress4X1_usingDTable_internal_fast(
     HUF_DecompressFastLoopFn loopFn)
 {
     void const* dt = DTable + 1;
-    const BYTE* const iend = (const BYTE*)cSrc + 6;
+    BYTE const* const ilowest = (BYTE const*)cSrc;
     BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
     HUF_DecompressFastArgs args;
     {   size_t const ret = HUF_DecompressFastArgs_init(&args, dst, dstSize, cSrc, cSrcSize, DTable);
@@ -845,18 +844,22 @@ HUF_decompress4X1_usingDTable_internal_fast(
             return 0;
     }
 
-    assert(args.ip[0] >= args.ilimit);
+    assert(args.ip[0] >= args.ilowest);
     loopFn(&args);
 
-    /* Our loop guarantees that ip[] >= ilimit and that we haven't
+    /* Our loop guarantees that ip[] >= ilowest and that we haven't
     * overwritten any op[].
     */
-    assert(args.ip[0] >= iend);
-    assert(args.ip[1] >= iend);
-    assert(args.ip[2] >= iend);
-    assert(args.ip[3] >= iend);
+    assert(args.ip[0] >= ilowest);
+    assert(args.ip[0] >= ilowest);
+    assert(args.ip[1] >= ilowest);
+    assert(args.ip[2] >= ilowest);
+    assert(args.ip[3] >= ilowest);
     assert(args.op[3] <= oend);
-    (void)iend;
+
+    assert(ilowest == args.ilowest);
+    assert(ilowest + 6 == args.iend[0]);
+    (void)ilowest;
 
     /* finish bit streams one by one. */
     {   size_t const segmentSize = (dstSize+3) / 4;
@@ -1512,7 +1515,7 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
     BYTE* op[4];
     BYTE* oend[4];
     HUF_DEltX2 const* const dtable = (HUF_DEltX2 const*)args->dt;
-    BYTE const* const ilimit = args->ilimit;
+    BYTE const* const ilowest = args->ilowest;
 
     /* Copy the arguments to local registers. */
     ZSTD_memcpy(&bits, &args->bits, sizeof(bits));
@@ -1535,7 +1538,7 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
 #ifndef NDEBUG
         for (stream = 0; stream < 4; ++stream) {
             assert(op[stream] <= oend[stream]);
-            assert(ip[stream] >= ilimit);
+            assert(ip[stream] >= ilowest);
         }
 #endif
         /* Compute olimit */
@@ -1548,7 +1551,7 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
              * We also know that each input pointer is >= ip[0]. So we can run
              * iters loops before running out of input.
              */
-            size_t iters = (size_t)(ip[0] - ilimit) / 7;
+            size_t iters = (size_t)(ip[0] - ilowest) / 7;
             /* Each iteration can produce up to 10 bytes of output per stream.
              * Each output stream my advance at different rates. So take the
              * minimum number of safe iterations among all the output streams.
@@ -1566,8 +1569,8 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
              */
             olimit = op[3] + (iters * 5);
 
-            /* Exit the fast decoding loop if we are too close to the end. */
-            if (op[3] + 10 > olimit)
+            /* Exit the fast decoding loop once we reach the end. */
+            if (op[3] == olimit)
                 break;
 
             /* Exit the decoding loop if any input pointer has crossed the
@@ -1652,7 +1655,7 @@ HUF_decompress4X2_usingDTable_internal_fast(
     const HUF_DTable* DTable,
     HUF_DecompressFastLoopFn loopFn) {
     void const* dt = DTable + 1;
-    const BYTE* const iend = (const BYTE*)cSrc + 6;
+    const BYTE* const ilowest = (const BYTE*)cSrc;
     BYTE* const oend = ZSTD_maybeNullPtrAdd((BYTE*)dst, dstSize);
     HUF_DecompressFastArgs args;
     {
@@ -1662,16 +1665,19 @@ HUF_decompress4X2_usingDTable_internal_fast(
             return 0;
     }
 
-    assert(args.ip[0] >= args.ilimit);
+    assert(args.ip[0] >= args.ilowest);
     loopFn(&args);
 
     /* note : op4 already verified within main loop */
-    assert(args.ip[0] >= iend);
-    assert(args.ip[1] >= iend);
-    assert(args.ip[2] >= iend);
-    assert(args.ip[3] >= iend);
+    assert(args.ip[0] >= ilowest);
+    assert(args.ip[1] >= ilowest);
+    assert(args.ip[2] >= ilowest);
+    assert(args.ip[3] >= ilowest);
     assert(args.op[3] <= oend);
-    (void)iend;
+
+    assert(ilowest == args.ilowest);
+    assert(ilowest + 6 == args.iend[0]);
+    (void)ilowest;
 
     /* finish bitStreams one by one */
     {
diff --git a/lib/decompress/huf_decompress_amd64.S b/lib/decompress/huf_decompress_amd64.S
index 671624fe3..3b96b4461 100644
--- a/lib/decompress/huf_decompress_amd64.S
+++ b/lib/decompress/huf_decompress_amd64.S
@@ -131,7 +131,7 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop:
     movq 88(%rax), %bits3
     movq 96(%rax), %dtable
     push %rax      /* argument */
-    push 104(%rax) /* ilimit */
+    push 104(%rax) /* ilowest */
     push 112(%rax) /* oend */
     push %olimit   /* olimit space */
 
@@ -156,11 +156,11 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop:
     shrq $2, %r15
 
     movq %ip0,     %rax /* rax = ip0 */
-    movq 40(%rsp), %rdx /* rdx = ilimit */
-    subq %rdx,     %rax /* rax = ip0 - ilimit */
-    movq %rax,     %rbx /* rbx = ip0 - ilimit */
+    movq 40(%rsp), %rdx /* rdx = ilowest */
+    subq %rdx,     %rax /* rax = ip0 - ilowest */
+    movq %rax,     %rbx /* rbx = ip0 - ilowest */
 
-    /* rdx = (ip0 - ilimit) / 7 */
+    /* rdx = (ip0 - ilowest) / 7 */
     movabsq $2635249153387078803, %rdx
     mulq %rdx
     subq %rdx, %rbx
@@ -183,9 +183,8 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop:
 
     /* If (op3 + 20 > olimit) */
     movq %op3, %rax    /* rax = op3 */
-    addq $20,  %rax    /* rax = op3 + 20 */
-    cmpq %rax, %olimit /* op3 + 20 > olimit */
-    jb .L_4X1_exit
+    cmpq %rax, %olimit /* op3 == olimit */
+    je .L_4X1_exit
 
     /* If (ip1 < ip0) go to exit */
     cmpq %ip0, %ip1
@@ -316,7 +315,7 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop:
     /* Restore stack (oend & olimit) */
     pop %rax /* olimit */
     pop %rax /* oend */
-    pop %rax /* ilimit */
+    pop %rax /* ilowest */
     pop %rax /* arg */
 
     /* Save ip / op / bits */
@@ -387,7 +386,7 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop:
     movq 96(%rax), %dtable
     push %rax      /* argument */
     push %rax      /* olimit */
-    push 104(%rax) /* ilimit */
+    push 104(%rax) /* ilowest */
 
     movq 112(%rax), %rax
     push %rax /* oend3 */
@@ -414,9 +413,9 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop:
 
     /* We can consume up to 7 input bytes each iteration. */
     movq %ip0,     %rax  /* rax = ip0 */
-    movq 40(%rsp), %rdx  /* rdx = ilimit */
-    subq %rdx,     %rax  /* rax = ip0 - ilimit */
-    movq %rax,    %r15   /* r15 = ip0 - ilimit */
+    movq 40(%rsp), %rdx  /* rdx = ilowest */
+    subq %rdx,     %rax  /* rax = ip0 - ilowest */
+    movq %rax,    %r15   /* r15 = ip0 - ilowest */
 
     /* rdx = rax / 7 */
     movabsq $2635249153387078803, %rdx
@@ -426,7 +425,7 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop:
     addq %r15, %rdx
     shrq $2, %rdx
 
-    /* r15 = (ip0 - ilimit) / 7 */
+    /* r15 = (ip0 - ilowest) / 7 */
     movq %rdx, %r15
 
     /* r15 = min(r15, min(oend0 - op0, oend1 - op1, oend2 - op2, oend3 - op3) / 10) */
@@ -467,9 +466,8 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop:
 
     /* If (op3 + 10 > olimit) */
     movq %op3, %rax    /* rax = op3 */
-    addq $10,  %rax    /* rax = op3 + 10 */
-    cmpq %rax, %olimit /* op3 + 10 > olimit */
-    jb .L_4X2_exit
+    cmpq %rax, %olimit /* op3 == olimit */
+    je .L_4X2_exit
 
     /* If (ip1 < ip0) go to exit */
     cmpq %ip0, %ip1
@@ -537,7 +535,7 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop:
     pop %rax /* oend1 */
     pop %rax /* oend2 */
     pop %rax /* oend3 */
-    pop %rax /* ilimit */
+    pop %rax /* ilowest */
     pop %rax /* olimit */
     pop %rax /* arg */
 

From dd4de1dd7a78ccff933025cf1de08a75d310802b Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Mon, 20 Nov 2023 12:04:30 -0800
Subject: [PATCH 129/937] [huf] Fix null pointer addition

`HUF_DecompressFastArgs_init()` was adding 0 to NULL. Fix it by exiting
early for empty outputs. This is no change in behavior, because the
function was already exiting 0 in this case, just slightly later.
---
 lib/decompress/huf_decompress.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index b8795efb5..0c43c656d 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -203,6 +203,11 @@ static size_t HUF_DecompressFastArgs_init(HUF_DecompressFastArgs* args, void* ds
     if (!MEM_isLittleEndian() || MEM_32bits())
         return 0;
 
+    /* Avoid nullptr addition */
+    if (dstSize == 0)
+        return 0;
+    assert(dst != NULL);
+
     /* strict minimum : jump table + 1 byte per stream */
     if (srcSize < 10)
         return ERROR(corruption_detected);

From 8193250615f56ace446a3bf963d195f9f33fa9a9 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Tue, 21 Nov 2023 13:26:25 -0800
Subject: [PATCH 130/937] Modernize macros to use `do { } while (0)`

This PR introduces no functional changes. It attempts to change all
macros currently using `{ }` or some variant of that to to
`do { } while (0)`, and introduces trailing `;` where necessary.
There were no bugs found during this migration.

The bug in Visual Studios warning on this has been fixed since VS2015.
Additionally, we have several instances of `do { } while (0)` which have
been present for several releases, so we don't have to worry about
breaking peoples builds.

Fixes Issue #3830.
---
 lib/common/compiler.h            |  33 ++++-----
 lib/common/debug.h               |  27 ++++---
 lib/common/error_private.h       |  81 +++++++++++----------
 lib/common/zstd_internal.h       |   6 +-
 lib/compress/zstd_compress.c     |  20 +++---
 lib/compress/zstd_double_fast.c  |   4 +-
 lib/compress/zstd_fast.c         |   2 +-
 lib/compress/zstd_opt.c          |   4 +-
 lib/compress/zstdmt_compress.c   |  61 ++++++++--------
 lib/decompress/huf_decompress.c  | 118 +++++++++++++++++--------------
 lib/decompress/zstd_decompress.c |   2 +-
 lib/dictBuilder/zdict.c          |  18 +++--
 12 files changed, 207 insertions(+), 169 deletions(-)

diff --git a/lib/common/compiler.h b/lib/common/compiler.h
index df39d91c6..31880ecbe 100644
--- a/lib/common/compiler.h
+++ b/lib/common/compiler.h
@@ -132,8 +132,8 @@
 /* prefetch
  * can be disabled, by declaring NO_PREFETCH build macro */
 #if defined(NO_PREFETCH)
-#  define PREFETCH_L1(ptr)  (void)(ptr)  /* disabled */
-#  define PREFETCH_L2(ptr)  (void)(ptr)  /* disabled */
+#  define PREFETCH_L1(ptr)  do { (void)(ptr); } while (0)  /* disabled */
+#  define PREFETCH_L2(ptr)  do { (void)(ptr); } while (0)  /* disabled */
 #else
 #  if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) && !defined(_M_ARM64EC)  /* _mm_prefetch() is not defined outside of x86/x64 */
 #    include    /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
@@ -143,24 +143,25 @@
 #    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)  __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr)))
-#    define PREFETCH_L2(ptr)  __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr)))
+#    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)
 #  else
-#    define PREFETCH_L1(ptr) (void)(ptr)  /* disabled */
-#    define PREFETCH_L2(ptr) (void)(ptr)  /* disabled */
+#    define PREFETCH_L1(ptr) do { (void)(ptr); } while (0)  /* disabled */
+#    define PREFETCH_L2(ptr) do { (void)(ptr); } while (0)  /* disabled */
 #  endif
 #endif  /* NO_PREFETCH */
 
 #define CACHELINE_SIZE 64
 
-#define PREFETCH_AREA(p, s)  {            \
-    const char* const _ptr = (const char*)(p);  \
-    size_t const _size = (size_t)(s);     \
-    size_t _pos;                          \
-    for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) {  \
-        PREFETCH_L2(_ptr + _pos);         \
-    }                                     \
-}
+#define PREFETCH_AREA(p, s)                              \
+    do {                                                 \
+        const char* const _ptr = (const char*)(p);       \
+        size_t const _size = (size_t)(s);                \
+        size_t _pos;                                     \
+        for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \
+            PREFETCH_L2(_ptr + _pos);                    \
+        }                                                \
+    } while (0)
 
 /* vectorization
  * older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax,
@@ -189,9 +190,9 @@
 #endif
 
 #if __has_builtin(__builtin_unreachable) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)))
-#  define ZSTD_UNREACHABLE { assert(0), __builtin_unreachable(); }
+#  define ZSTD_UNREACHABLE do { assert(0), __builtin_unreachable(); } while (0)
 #else
-#  define ZSTD_UNREACHABLE { assert(0); }
+#  define ZSTD_UNREACHABLE do { assert(0); } while (0)
 #endif
 
 /* disable warnings */
diff --git a/lib/common/debug.h b/lib/common/debug.h
index 0e9817ea6..8049e4b5d 100644
--- a/lib/common/debug.h
+++ b/lib/common/debug.h
@@ -85,18 +85,23 @@ extern int g_debuglevel; /* the variable is only declared,
                             It's useful when enabling very verbose levels
                             on selective conditions (such as position in src) */
 
-#  define RAWLOG(l, ...) {                                       \
-                if (l<=g_debuglevel) {                           \
-                    ZSTD_DEBUG_PRINT(__VA_ARGS__);               \
-            }   }
-#  define DEBUGLOG(l, ...) {                                     \
-                if (l<=g_debuglevel) {                           \
-                    ZSTD_DEBUG_PRINT(__FILE__ ": " __VA_ARGS__); \
-                    ZSTD_DEBUG_PRINT(" \n");                     \
-            }   }
+#  define RAWLOG(l, ...)                   \
+    do {                                   \
+        if (l<=g_debuglevel) {             \
+            ZSTD_DEBUG_PRINT(__VA_ARGS__); \
+        }                                  \
+    } while (0)
+
+#  define DEBUGLOG(l, ...)                               \
+    do {                                                 \
+        if (l<=g_debuglevel) {                           \
+            ZSTD_DEBUG_PRINT(__FILE__ ": " __VA_ARGS__); \
+            ZSTD_DEBUG_PRINT(" \n");                     \
+        }                                                \
+    } while (0)
 #else
-#  define RAWLOG(l, ...)      {}    /* disabled */
-#  define DEBUGLOG(l, ...)    {}    /* disabled */
+#  define RAWLOG(l, ...)   do { } while (0)    /* disabled */
+#  define DEBUGLOG(l, ...) do { } while (0)    /* disabled */
 #endif
 
 
diff --git a/lib/common/error_private.h b/lib/common/error_private.h
index 325daad40..0156010c7 100644
--- a/lib/common/error_private.h
+++ b/lib/common/error_private.h
@@ -60,8 +60,13 @@ ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }
 ERR_STATIC ERR_enum ERR_getErrorCode(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); }
 
 /* check and forward error code */
-#define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e
-#define CHECK_F(f)   { CHECK_V_F(_var_err__, f); }
+#define CHECK_V_F(e, f)     \
+    size_t const e = f;     \
+    do {                    \
+        if (ERR_isError(e)) \
+            return e;       \
+    } while (0)
+#define CHECK_F(f)   do { CHECK_V_F(_var_err__, f); } while (0)
 
 
 /*-****************************************
@@ -95,10 +100,12 @@ void _force_has_format_string(const char *format, ...) {
  * We want to force this function invocation to be syntactically correct, but
  * we don't want to force runtime evaluation of its arguments.
  */
-#define _FORCE_HAS_FORMAT_STRING(...) \
-  if (0) { \
-    _force_has_format_string(__VA_ARGS__); \
-  }
+#define _FORCE_HAS_FORMAT_STRING(...)              \
+    do {                                           \
+        if (0) {                                   \
+            _force_has_format_string(__VA_ARGS__); \
+        }                                          \
+    } while (0)
 
 #define ERR_QUOTE(str) #str
 
@@ -109,48 +116,50 @@ void _force_has_format_string(const char *format, ...) {
  * In order to do that (particularly, printing the conditional that failed),
  * this can't just wrap RETURN_ERROR().
  */
-#define RETURN_ERROR_IF(cond, err, ...) \
-  if (cond) { \
-    RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \
-           __FILE__, __LINE__, ERR_QUOTE(cond), ERR_QUOTE(ERROR(err))); \
-    _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
-    RAWLOG(3, ": " __VA_ARGS__); \
-    RAWLOG(3, "\n"); \
-    return ERROR(err); \
-  }
+#define RETURN_ERROR_IF(cond, err, ...)                                        \
+    do {                                                                       \
+        if (cond) {                                                            \
+            RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s",          \
+                  __FILE__, __LINE__, ERR_QUOTE(cond), ERR_QUOTE(ERROR(err))); \
+            _FORCE_HAS_FORMAT_STRING(__VA_ARGS__);                             \
+            RAWLOG(3, ": " __VA_ARGS__);                                       \
+            RAWLOG(3, "\n");                                                   \
+            return ERROR(err);                                                 \
+        }                                                                      \
+    } while (0)
 
 /**
  * Unconditionally return the specified error.
  *
  * In debug modes, prints additional information.
  */
-#define RETURN_ERROR(err, ...) \
-  do { \
-    RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \
-           __FILE__, __LINE__, ERR_QUOTE(ERROR(err))); \
-    _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
-    RAWLOG(3, ": " __VA_ARGS__); \
-    RAWLOG(3, "\n"); \
-    return ERROR(err); \
-  } while(0);
+#define RETURN_ERROR(err, ...)                                               \
+    do {                                                                     \
+        RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \
+              __FILE__, __LINE__, ERR_QUOTE(ERROR(err)));                    \
+        _FORCE_HAS_FORMAT_STRING(__VA_ARGS__);                               \
+        RAWLOG(3, ": " __VA_ARGS__);                                         \
+        RAWLOG(3, "\n");                                                     \
+        return ERROR(err);                                                   \
+    } while(0)
 
 /**
  * If the provided expression evaluates to an error code, returns that error code.
  *
  * In debug modes, prints additional information.
  */
-#define FORWARD_IF_ERROR(err, ...) \
-  do { \
-    size_t const err_code = (err); \
-    if (ERR_isError(err_code)) { \
-      RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \
-             __FILE__, __LINE__, ERR_QUOTE(err), ERR_getErrorName(err_code)); \
-      _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
-      RAWLOG(3, ": " __VA_ARGS__); \
-      RAWLOG(3, "\n"); \
-      return err_code; \
-    } \
-  } while(0);
+#define FORWARD_IF_ERROR(err, ...)                                                 \
+    do {                                                                           \
+        size_t const err_code = (err);                                             \
+        if (ERR_isError(err_code)) {                                               \
+            RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s",                 \
+                  __FILE__, __LINE__, ERR_QUOTE(err), ERR_getErrorName(err_code)); \
+            _FORCE_HAS_FORMAT_STRING(__VA_ARGS__);                                 \
+            RAWLOG(3, ": " __VA_ARGS__);                                           \
+            RAWLOG(3, "\n");                                                       \
+            return err_code;                                                       \
+        }                                                                          \
+    } while(0)
 
 #if defined (__cplusplus)
 }
diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h
index f7c57a028..ecb9cfba8 100644
--- a/lib/common/zstd_internal.h
+++ b/lib/common/zstd_internal.h
@@ -178,7 +178,7 @@ static void ZSTD_copy8(void* dst, const void* src) {
     ZSTD_memcpy(dst, src, 8);
 #endif
 }
-#define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
+#define COPY8(d,s) do { ZSTD_copy8(d,s); d+=8; s+=8; } while (0)
 
 /* Need to use memmove here since the literal buffer can now be located within
    the dst buffer. In circumstances where the op "catches up" to where the
@@ -198,7 +198,7 @@ static void ZSTD_copy16(void* dst, const void* src) {
     ZSTD_memcpy(dst, copy16_buf, 16);
 #endif
 }
-#define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }
+#define COPY16(d,s) do { ZSTD_copy16(d,s); d+=16; s+=16; } while (0)
 
 #define WILDCOPY_OVERLENGTH 32
 #define WILDCOPY_VECLEN 16
@@ -227,7 +227,7 @@ void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e
     if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {
         /* Handle short offset copies. */
         do {
-            COPY8(op, ip)
+            COPY8(op, ip);
         } while (op < oend);
     } else {
         assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index b79266fdb..4e441baf0 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -650,10 +650,11 @@ static size_t ZSTD_cParam_clampBounds(ZSTD_cParameter cParam, int* value)
     return 0;
 }
 
-#define BOUNDCHECK(cParam, val) { \
-    RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val), \
-                    parameter_outOfBound, "Param out of bounds"); \
-}
+#define BOUNDCHECK(cParam, val)                                       \
+    do {                                                              \
+        RETURN_ERROR_IF(!ZSTD_cParam_withinBounds(cParam,val),        \
+                        parameter_outOfBound, "Param out of bounds"); \
+    } while (0)
 
 
 static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
@@ -1392,11 +1393,12 @@ size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
 static ZSTD_compressionParameters
 ZSTD_clampCParams(ZSTD_compressionParameters cParams)
 {
-#   define CLAMP_TYPE(cParam, val, type) {                                \
-        ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
-        if ((int)valbounds.upperBound) val=(type)bounds.upperBound; \
-    }
+#   define CLAMP_TYPE(cParam, val, type)                                      \
+        do {                                                                  \
+            ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);         \
+            if ((int)valbounds.upperBound) val=(type)bounds.upperBound; \
+        } while (0)
 #   define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, unsigned)
     CLAMP(ZSTD_c_windowLog, cParams.windowLog);
     CLAMP(ZSTD_c_chainLog,  cParams.chainLog);
diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c
index aaa6f3d3d..a4e9c50d3 100644
--- a/lib/compress/zstd_double_fast.c
+++ b/lib/compress/zstd_double_fast.c
@@ -356,8 +356,8 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic(
     if (ms->prefetchCDictTables) {
         size_t const hashTableBytes = (((size_t)1) << dictCParams->hashLog) * sizeof(U32);
         size_t const chainTableBytes = (((size_t)1) << dictCParams->chainLog) * sizeof(U32);
-        PREFETCH_AREA(dictHashLong, hashTableBytes)
-        PREFETCH_AREA(dictHashSmall, chainTableBytes)
+        PREFETCH_AREA(dictHashLong, hashTableBytes);
+        PREFETCH_AREA(dictHashSmall, chainTableBytes);
     }
 
     /* init */
diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c
index fb1ef60c1..6c4554cfc 100644
--- a/lib/compress/zstd_fast.c
+++ b/lib/compress/zstd_fast.c
@@ -508,7 +508,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic(
 
     if (ms->prefetchCDictTables) {
         size_t const hashTableBytes = (((size_t)1) << dictCParams->hashLog) * sizeof(U32);
-        PREFETCH_AREA(dictHashTable, hashTableBytes)
+        PREFETCH_AREA(dictHashTable, hashTableBytes);
     }
 
     /* init */
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 11d460c60..68537e600 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1182,7 +1182,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
         for (cur = 1; cur <= last_pos; cur++) {
             const BYTE* const inr = ip + cur;
             assert(cur < ZSTD_OPT_NUM);
-            DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)
+            DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur);
 
             /* Fix current position with one literal if cheaper */
             {   U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
@@ -1331,7 +1331,7 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
             }
 
             /* save sequences */
-            DEBUGLOG(6, "sending selected sequences into seqStore")
+            DEBUGLOG(6, "sending selected sequences into seqStore");
             {   U32 storePos;
                 for (storePos=storeStart; storePos <= storeEnd; storePos++) {
                     U32 const llen = opt[storePos].litlen;
diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index 6b3391a0f..baa0f0069 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -40,12 +40,13 @@
 #  include 
 #  include 
 
-#  define DEBUG_PRINTHEX(l,p,n) {            \
-    unsigned debug_u;                        \
-    for (debug_u=0; debug_u<(n); debug_u++)  \
-        RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
-    RAWLOG(l, " \n");                        \
-}
+#  define DEBUG_PRINTHEX(l,p,n)                                       \
+    do {                                                              \
+        unsigned debug_u;                                             \
+        for (debug_u=0; debug_u<(n); debug_u++)                       \
+            RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
+        RAWLOG(l, " \n");                                             \
+    } while (0)
 
 static unsigned long long GetCurrentClockTimeMicroseconds(void)
 {
@@ -57,25 +58,28 @@ static unsigned long long GetCurrentClockTimeMicroseconds(void)
 }  }
 
 #define MUTEX_WAIT_TIME_DLEVEL 6
-#define ZSTD_PTHREAD_MUTEX_LOCK(mutex) {          \
-    if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) {   \
-        unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \
-        ZSTD_pthread_mutex_lock(mutex);           \
-        {   unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
-            unsigned long long const elapsedTime = (afterTime-beforeTime); \
-            if (elapsedTime > 1000) {  /* or whatever threshold you like; I'm using 1 millisecond here */ \
-                DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \
-                   elapsedTime, #mutex);          \
-        }   }                                     \
-    } else {                                      \
-        ZSTD_pthread_mutex_lock(mutex);           \
-    }                                             \
-}
+#define ZSTD_PTHREAD_MUTEX_LOCK(mutex)                                                  \
+    do {                                                                                \
+        if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) {                                     \
+            unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds();    \
+            ZSTD_pthread_mutex_lock(mutex);                                             \
+            {   unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
+                unsigned long long const elapsedTime = (afterTime-beforeTime);          \
+                if (elapsedTime > 1000) {                                               \
+                    /* or whatever threshold you like; I'm using 1 millisecond here */  \
+                    DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL,                                    \
+                        "Thread took %llu microseconds to acquire mutex %s \n",         \
+                        elapsedTime, #mutex);                                           \
+            }   }                                                                       \
+        } else {                                                                        \
+            ZSTD_pthread_mutex_lock(mutex);                                             \
+        }                                                                               \
+    } while (0)
 
 #else
 
 #  define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)
-#  define DEBUG_PRINTHEX(l,p,n) {}
+#  define DEBUG_PRINTHEX(l,p,n) do { } while (0)
 
 #endif
 
@@ -667,12 +671,13 @@ typedef struct {
     unsigned frameChecksumNeeded;        /* used only by mtctx */
 } ZSTDMT_jobDescription;
 
-#define JOB_ERROR(e) {                          \
-    ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);   \
-    job->cSize = e;                             \
-    ZSTD_pthread_mutex_unlock(&job->job_mutex); \
-    goto _endJob;                               \
-}
+#define JOB_ERROR(e)                                \
+    do {                                            \
+        ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);   \
+        job->cSize = e;                             \
+        ZSTD_pthread_mutex_unlock(&job->job_mutex); \
+        goto _endJob;                               \
+    } while (0)
 
 /* ZSTDMT_compressionJob() is a POOL_function type */
 static void ZSTDMT_compressionJob(void* jobDescription)
@@ -1101,7 +1106,7 @@ ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
     {   unsigned jobNb;
         unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
         DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
-                    mtctx->doneJobID, lastJobNb, mtctx->jobReady)
+                    mtctx->doneJobID, lastJobNb, mtctx->jobReady);
         for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
             unsigned const wJobID = jobNb & mtctx->jobIDMask;
             ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c
index 0c43c656d..f85dd0bee 100644
--- a/lib/decompress/huf_decompress.c
+++ b/lib/decompress/huf_decompress.c
@@ -304,21 +304,21 @@ static size_t HUF_initRemainingDStream(BIT_DStream_t* bit, HUF_DecompressFastArg
 
 /* Calls X(N) for each stream 0, 1, 2, 3. */
 #define HUF_4X_FOR_EACH_STREAM(X) \
-    {                             \
-        X(0)                      \
-        X(1)                      \
-        X(2)                      \
-        X(3)                      \
-    }
+    do {                          \
+        X(0);                     \
+        X(1);                     \
+        X(2);                     \
+        X(3);                     \
+    } while (0)
 
 /* Calls X(N, var) for each stream 0, 1, 2, 3. */
 #define HUF_4X_FOR_EACH_STREAM_WITH_VAR(X, var) \
-    {                                           \
-        X(0, (var))                             \
-        X(1, (var))                             \
-        X(2, (var))                             \
-        X(3, (var))                             \
-    }
+    do {                                        \
+        X(0, (var));                            \
+        X(1, (var));                            \
+        X(2, (var));                            \
+        X(3, (var));                            \
+    } while (0)
 
 
 #ifndef HUF_FORCE_DECOMPRESS_X2
@@ -528,15 +528,19 @@ HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog
 }
 
 #define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \
-    *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog)
+    do { *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog); } while (0)
 
-#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr)  \
-    if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
-        HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
+#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr)      \
+    do {                                            \
+        if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
+            HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr); \
+    } while (0)
 
-#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \
-    if (MEM_64bits()) \
-        HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
+#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr)      \
+    do {                                            \
+        if (MEM_64bits())                           \
+            HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr); \
+    } while (0)
 
 HINT_INLINE size_t
 HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog)
@@ -781,15 +785,15 @@ 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); \
-    }
+    } while (0)
 
 #define HUF_4X1_RELOAD_STREAM(_stream)                              \
-    {                                                               \
+    do {                                                            \
         int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
         int const nbBits = ctz & 7;                                 \
         int const nbBytes = ctz >> 3;                               \
@@ -797,21 +801,21 @@ void HUF_decompress4X1_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         ip[(_stream)] -= nbBytes;                                   \
         bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
         bits[(_stream)] <<= nbBits;                                 \
-    }
+    } while (0)
 
         /* Manually unroll the loop because compilers don't consistently
          * unroll the inner loops, which destroys performance.
          */
         do {
             /* Decode 5 symbols in each of the 4 streams */
-            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0)
-            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1)
-            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2)
-            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3)
-            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 4)
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 0);
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 1);
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 2);
+            HUF_4X_FOR_EACH_STREAM_WITH_VAR(HUF_4X1_DECODE_SYMBOL, 3);
+            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_4X1_RELOAD_STREAM);
         } while (op[3] < olimit);
 
 #undef HUF_4X1_DECODE_SYMBOL
@@ -1286,15 +1290,19 @@ HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, c
 }
 
 #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
-    ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+    do { ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); } while (0)
 
-#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
-    if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
-        ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr)                     \
+    do {                                                           \
+        if (MEM_64bits() || (HUF_TABLELOG_MAX<=12))                \
+            ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); \
+    } while (0)
 
-#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
-    if (MEM_64bits()) \
-        ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr)                     \
+    do {                                                           \
+        if (MEM_64bits())                                          \
+            ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog); \
+    } while (0)
 
 HINT_INLINE size_t
 HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd,
@@ -1594,18 +1602,20 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
         }
 #endif
 
-#define HUF_4X2_DECODE_SYMBOL(_stream, _decode3)        \
-    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) {                           \
+            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);                          \
+        }                                                             \
+    } while (0)
 
 #define HUF_4X2_RELOAD_STREAM(_stream)                                  \
-    {                                                                   \
-        HUF_4X2_DECODE_SYMBOL(3, 1)                                     \
+    do {                                                                \
+        HUF_4X2_DECODE_SYMBOL(3, 1);                                    \
         {                                                               \
             int const ctz = ZSTD_countTrailingZeros64(bits[(_stream)]); \
             int const nbBits = ctz & 7;                                 \
@@ -1614,7 +1624,7 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
             bits[(_stream)] = MEM_read64(ip[(_stream)]) | 1;            \
             bits[(_stream)] <<= nbBits;                                 \
         }                                                               \
-    }
+    } while (0)
 
         /* Manually unroll the loop because compilers don't consistently
          * unroll the inner loops, which destroys performance.
@@ -1624,20 +1634,20 @@ void HUF_decompress4X2_usingDTable_internal_fast_c_loop(HUF_DecompressFastArgs*
              * 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)
+            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)
+            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(HUF_4X2_RELOAD_STREAM)
+            HUF_4X_FOR_EACH_STREAM(HUF_4X2_RELOAD_STREAM);
         } while (op[3] < olimit);
     }
 
diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index 027a0f8cc..f57b31e70 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -2173,7 +2173,7 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB
                     /* shortcut : using single-pass mode */
                     size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, (size_t)(oend-op), istart, cSize, ZSTD_getDDict(zds));
                     if (ZSTD_isError(decompressedSize)) return decompressedSize;
-                    DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")
+                    DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()");
                     assert(istart != NULL);
                     ip = istart + cSize;
                     op = op ? op + decompressedSize : op; /* can occur if frameContentSize = 0 (empty frame) */
diff --git a/lib/dictBuilder/zdict.c b/lib/dictBuilder/zdict.c
index 58290f450..82e999e80 100644
--- a/lib/dictBuilder/zdict.c
+++ b/lib/dictBuilder/zdict.c
@@ -74,9 +74,9 @@ static const U32 g_selectivity_default = 9;
 *  Console display
 ***************************************/
 #undef  DISPLAY
-#define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
+#define DISPLAY(...)         do { fprintf(stderr, __VA_ARGS__); fflush( stderr ); } while (0)
 #undef  DISPLAYLEVEL
-#define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); }    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
+#define DISPLAYLEVEL(l, ...) do { if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } } while (0)    /* 0 : no display;   1: errors;   2: default;  3: details;  4: debug */
 
 static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
 
@@ -477,10 +477,16 @@ static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
     clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
 
 #   undef  DISPLAYUPDATE
-#   define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
-            if (ZDICT_clockSpan(displayClock) > refreshRate)  \
-            { displayClock = clock(); DISPLAY(__VA_ARGS__); \
-            if (notificationLevel>=4) fflush(stderr); } }
+#   define DISPLAYUPDATE(l, ...)                                   \
+        do {                                                       \
+            if (notificationLevel>=l) {                            \
+                if (ZDICT_clockSpan(displayClock) > refreshRate) { \
+                    displayClock = clock();                        \
+                    DISPLAY(__VA_ARGS__);                          \
+                }                                                  \
+                if (notificationLevel>=4) fflush(stderr);          \
+            }                                                      \
+        } while (0)
 
     /* init */
     DISPLAYLEVEL(2, "\r%70s\r", "");   /* clean display line */

From dc84e35138338e95016fe23feb7dae43a842ca4f Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Wed, 8 Nov 2023 23:25:00 -0500
Subject: [PATCH 131/937] Clarify that the presence of a value with weight 1 is
 required

---
 doc/zstd_compression_format.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index b64ddc3bf..dbf409eac 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1252,7 +1252,7 @@ Number_of_Bits = Weight ? (Max_Number_of_Bits + 1 - Weight) : 0
 ```
 When a literal value is not present, it receives a `Weight` of 0.
 The least frequent symbol receives a `Weight` of 1.
-Consequently, the `Weight` 1 is necessarily present.
+If no symbol has a `Weight` of 1, then the data is considered corrupted.
 The most frequent symbol receives a `Weight` anywhere between 1 and 11 (max).
 The last symbol's `Weight` is deduced from previously retrieved Weights,
 by completing to the nearest power of 2. It's necessarily non 0.

From 05059e5a48333e594e0204894cbbdffe51305487 Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Wed, 8 Nov 2023 23:46:37 -0500
Subject: [PATCH 132/937] Clarify that there must be at least 2 weights, i.e.
 encoding all weights as 0 is invalid

---
 doc/zstd_compression_format.md | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index dbf409eac..4a8d338b7 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1252,7 +1252,9 @@ Number_of_Bits = Weight ? (Max_Number_of_Bits + 1 - Weight) : 0
 ```
 When a literal value is not present, it receives a `Weight` of 0.
 The least frequent symbol receives a `Weight` of 1.
-If no symbol has a `Weight` of 1, then the data is considered corrupted.
+If no literal has a `Weight` of 1, then the data is considered corrupted.
+If there are not at least two literals with non-zero `Weight`, then the data
+is considered corrupted.
 The most frequent symbol receives a `Weight` anywhere between 1 and 11 (max).
 The last symbol's `Weight` is deduced from previously retrieved Weights,
 by completing to the nearest power of 2. It's necessarily non 0.

From 809c7eb6bff1934745b425437d2116d9c0dbe0df Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Mon, 27 Nov 2023 06:52:36 -0800
Subject: [PATCH 133/937] Refactor ZSTD_sequenceProducer_F typedef to
 ZSTD_sequenceProducer_F*

---
 lib/compress/zstd_compress.c          | 2 +-
 lib/compress/zstd_compress_internal.h | 2 +-
 lib/zstd.h                            | 4 ++--
 3 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 4e441baf0..1a414a5dc 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -7086,7 +7086,7 @@ ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeH
 
 void ZSTD_registerSequenceProducer(
     ZSTD_CCtx* zc, void* mState,
-    ZSTD_sequenceProducer_F* mFinder
+    ZSTD_sequenceProducer_F mFinder
 ) {
     if (mFinder != NULL) {
         ZSTD_externalMatchCtx emctx;
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index b5e1a08ca..819bd3956 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -404,7 +404,7 @@ typedef struct {
 /* Context for block-level external matchfinder API */
 typedef struct {
   void* mState;
-  ZSTD_sequenceProducer_F* mFinder;
+  ZSTD_sequenceProducer_F mFinder;
   ZSTD_Sequence* seqBuffer;
   size_t seqBufferCapacity;
 } ZSTD_externalMatchCtx;
diff --git a/lib/zstd.h b/lib/zstd.h
index c33dab3cd..61f81db0f 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -2789,7 +2789,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);
 
 #define ZSTD_SEQUENCE_PRODUCER_ERROR ((size_t)(-1))
 
-typedef size_t ZSTD_sequenceProducer_F (
+typedef size_t (*ZSTD_sequenceProducer_F) (
   void* sequenceProducerState,
   ZSTD_Sequence* outSeqs, size_t outSeqsCapacity,
   const void* src, size_t srcSize,
@@ -2821,7 +2821,7 @@ ZSTDLIB_STATIC_API void
 ZSTD_registerSequenceProducer(
   ZSTD_CCtx* cctx,
   void* sequenceProducerState,
-  ZSTD_sequenceProducer_F* sequenceProducer
+  ZSTD_sequenceProducer_F sequenceProducer
 );
 
 

From d151a4880bdcb15d10ed11136b8b7d8d3d66af2c Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Mon, 27 Nov 2023 06:52:52 -0800
Subject: [PATCH 134/937] Move offload API params into ZSTD_CCtx_params

---
 lib/compress/zstd_compress.c          | 66 ++++++++++++---------------
 lib/compress/zstd_compress_internal.h | 26 +++++------
 2 files changed, 42 insertions(+), 50 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 1a414a5dc..cdd763ff6 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -1365,7 +1365,6 @@ size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
         RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong,
                         "Reset parameters is only possible during init stage.");
         ZSTD_clearAllDicts(cctx);
-        ZSTD_memset(&cctx->externalMatchCtx, 0, sizeof(cctx->externalMatchCtx));
         return ZSTD_CCtxParams_reset(&cctx->requestedParams);
     }
     return 0;
@@ -1752,7 +1751,7 @@ size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
      * 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, params->useSequenceProducer, params->maxBlockSize);
+        &cParams, ¶ms->ldmParams, 1, useRowMatchFinder, 0, 0, ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
 }
 
 size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
@@ -1813,7 +1812,7 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
 
         return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
             &cParams, ¶ms->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
-            ZSTD_CONTENTSIZE_UNKNOWN, params->useSequenceProducer, params->maxBlockSize);
+            ZSTD_CONTENTSIZE_UNKNOWN, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
     }
 }
 
@@ -2119,7 +2118,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
 
     {   size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params->cParams.windowLog), pledgedSrcSize));
         size_t const blockSize = MIN(params->maxBlockSize, windowSize);
-        size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, params->useSequenceProducer);
+        size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, params->cParams.minMatch, ZSTD_hasExtSeqProd(params));
         size_t const buffOutSize = (zbuff == ZSTDb_buffered && params->outBufferMode == ZSTD_bm_buffered)
                 ? ZSTD_compressBound(blockSize) + 1
                 : 0;
@@ -2136,7 +2135,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
         size_t const neededSpace =
             ZSTD_estimateCCtxSize_usingCCtxParams_internal(
                 ¶ms->cParams, ¶ms->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
-                buffInSize, buffOutSize, pledgedSrcSize, params->useSequenceProducer, params->maxBlockSize);
+                buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
         int resizeWorkspace;
 
         FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
@@ -2221,10 +2220,10 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
         }
 
         /* reserve space for block-level external sequences */
-        if (params->useSequenceProducer) {
+        if (ZSTD_hasExtSeqProd(params)) {
             size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize);
-            zc->externalMatchCtx.seqBufferCapacity = maxNbExternalSeq;
-            zc->externalMatchCtx.seqBuffer =
+            zc->extSeqBufCapacity = maxNbExternalSeq;
+            zc->extSeqBuf =
                 (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence));
         }
 
@@ -3248,7 +3247,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
             /* External matchfinder + LDM is technically possible, just not implemented yet.
              * We need to revisit soon and implement it. */
             RETURN_ERROR_IF(
-                zc->appliedParams.useSequenceProducer,
+                ZSTD_hasExtSeqProd(&zc->appliedParams),
                 parameter_combination_unsupported,
                 "Long-distance matching with external sequence producer enabled is not currently supported."
             );
@@ -3267,7 +3266,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
             /* External matchfinder + LDM is technically possible, just not implemented yet.
              * We need to revisit soon and implement it. */
             RETURN_ERROR_IF(
-                zc->appliedParams.useSequenceProducer,
+                ZSTD_hasExtSeqProd(&zc->appliedParams),
                 parameter_combination_unsupported,
                 "Long-distance matching with external sequence producer enabled is not currently supported."
             );
@@ -3286,18 +3285,18 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
                                        zc->appliedParams.useRowMatchFinder,
                                        src, srcSize);
             assert(ldmSeqStore.pos == ldmSeqStore.size);
-        } else if (zc->appliedParams.useSequenceProducer) {
+        } else if (ZSTD_hasExtSeqProd(&zc->appliedParams)) {
             assert(
-                zc->externalMatchCtx.seqBufferCapacity >= ZSTD_sequenceBound(srcSize)
+                zc->extSeqBufCapacity >= ZSTD_sequenceBound(srcSize)
             );
-            assert(zc->externalMatchCtx.mFinder != NULL);
+            assert(zc->appliedParams.extSeqProdFunc != NULL);
 
             {   U32 const windowSize = (U32)1 << zc->appliedParams.cParams.windowLog;
 
-                size_t const nbExternalSeqs = (zc->externalMatchCtx.mFinder)(
-                    zc->externalMatchCtx.mState,
-                    zc->externalMatchCtx.seqBuffer,
-                    zc->externalMatchCtx.seqBufferCapacity,
+                size_t const nbExternalSeqs = (zc->appliedParams.extSeqProdFunc)(
+                    zc->appliedParams.extSeqProdState,
+                    zc->extSeqBuf,
+                    zc->extSeqBufCapacity,
                     src, srcSize,
                     NULL, 0,  /* dict and dictSize, currently not supported */
                     zc->appliedParams.compressionLevel,
@@ -3305,21 +3304,21 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize)
                 );
 
                 size_t const nbPostProcessedSeqs = ZSTD_postProcessSequenceProducerResult(
-                    zc->externalMatchCtx.seqBuffer,
+                    zc->extSeqBuf,
                     nbExternalSeqs,
-                    zc->externalMatchCtx.seqBufferCapacity,
+                    zc->extSeqBufCapacity,
                     srcSize
                 );
 
                 /* Return early if there is no error, since we don't need to worry about last literals */
                 if (!ZSTD_isError(nbPostProcessedSeqs)) {
                     ZSTD_sequencePosition seqPos = {0,0,0};
-                    size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->externalMatchCtx.seqBuffer, nbPostProcessedSeqs);
+                    size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs);
                     RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!");
                     FORWARD_IF_ERROR(
                         ZSTD_copySequencesToSeqStoreExplicitBlockDelim(
                             zc, &seqPos,
-                            zc->externalMatchCtx.seqBuffer, nbPostProcessedSeqs,
+                            zc->extSeqBuf, nbPostProcessedSeqs,
                             src, srcSize,
                             zc->appliedParams.searchForExternalRepcodes
                         ),
@@ -6209,7 +6208,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
 #ifdef ZSTD_MULTITHREAD
     /* If external matchfinder is enabled, make sure to fail before checking job size (for consistency) */
     RETURN_ERROR_IF(
-        params.useSequenceProducer == 1 && params.nbWorkers >= 1,
+        ZSTD_hasExtSeqProd(¶ms) && params.nbWorkers >= 1,
         parameter_combination_unsupported,
         "External sequence producer isn't supported with nbWorkers >= 1"
     );
@@ -6501,7 +6500,7 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
         if (cctx->appliedParams.validateSequences) {
             seqPos->posInSrc += litLength + matchLength;
             FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
-                                                cctx->appliedParams.cParams.windowLog, dictSize, cctx->appliedParams.useSequenceProducer),
+                                                cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
                                                 "Sequence validation failed");
         }
         RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid,
@@ -6639,7 +6638,7 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition*
         if (cctx->appliedParams.validateSequences) {
             seqPos->posInSrc += litLength + matchLength;
             FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc,
-                                                   cctx->appliedParams.cParams.windowLog, dictSize, cctx->appliedParams.useSequenceProducer),
+                                                   cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)),
                                                    "Sequence validation failed");
         }
         DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength);
@@ -7085,19 +7084,14 @@ ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeH
 }
 
 void ZSTD_registerSequenceProducer(
-    ZSTD_CCtx* zc, void* mState,
-    ZSTD_sequenceProducer_F mFinder
+    ZSTD_CCtx* zc, void* extSeqProdState,
+    ZSTD_sequenceProducer_F extSeqProdFunc
 ) {
-    if (mFinder != NULL) {
-        ZSTD_externalMatchCtx emctx;
-        emctx.mState = mState;
-        emctx.mFinder = mFinder;
-        emctx.seqBuffer = NULL;
-        emctx.seqBufferCapacity = 0;
-        zc->externalMatchCtx = emctx;
-        zc->requestedParams.useSequenceProducer = 1;
+    if (extSeqProdFunc != NULL) {
+        zc->requestedParams.extSeqProdFunc = extSeqProdFunc;
+        zc->requestedParams.extSeqProdState = extSeqProdState;
     } else {
-        ZSTD_memset(&zc->externalMatchCtx, 0, sizeof(zc->externalMatchCtx));
-        zc->requestedParams.useSequenceProducer = 0;
+        zc->requestedParams.extSeqProdFunc = NULL;
+        zc->requestedParams.extSeqProdState = NULL;
     }
 }
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 819bd3956..60f22239e 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -360,10 +360,11 @@ struct ZSTD_CCtx_params_s {
      * if the external matchfinder returns an error code. */
     int enableMatchFinderFallback;
 
-    /* Indicates whether an external matchfinder has been referenced.
-     * Users can't set this externally.
-     * It is set internally in ZSTD_registerSequenceProducer(). */
-    int useSequenceProducer;
+    /* Parameters for the external sequence producer API.
+     * Users set these parameters through ZSTD_registerSequenceProducer().
+     * It is not possible to set these parameters individually through the public API. */
+    void* extSeqProdState;
+    ZSTD_sequenceProducer_F extSeqProdFunc;
 
     /* Adjust the max block size*/
     size_t maxBlockSize;
@@ -401,14 +402,6 @@ typedef struct {
     ZSTD_entropyCTablesMetadata_t entropyMetadata;
 } ZSTD_blockSplitCtx;
 
-/* Context for block-level external matchfinder API */
-typedef struct {
-  void* mState;
-  ZSTD_sequenceProducer_F mFinder;
-  ZSTD_Sequence* seqBuffer;
-  size_t seqBufferCapacity;
-} ZSTD_externalMatchCtx;
-
 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. */
@@ -479,8 +472,9 @@ struct ZSTD_CCtx_s {
     /* Workspace for block splitter */
     ZSTD_blockSplitCtx blockSplitCtx;
 
-    /* Workspace for external matchfinder */
-    ZSTD_externalMatchCtx externalMatchCtx;
+    /* Buffer for output from external sequence producer */
+    ZSTD_Sequence* extSeqBuf;
+    size_t extSeqBufCapacity;
 };
 
 typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
@@ -1512,6 +1506,10 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition*
                                    const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
                                    const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
 
+/* Returns 1 if an external sequence producer is registered, otherwise returns 0. */
+MEM_STATIC int ZSTD_hasExtSeqProd(const ZSTD_CCtx_params* params) {
+    return params->extSeqProdFunc != NULL;
+}
 
 /* ===============================================================
  * Deprecated definitions that are still used internally to avoid

From 468bb173782115e7bd2704f3a9e82341912eebd4 Mon Sep 17 00:00:00 2001
From: aimuz 
Date: Tue, 28 Nov 2023 21:04:37 +0800
Subject: [PATCH 135/937] lib/decompress: check for reserved bit corruption in
 zstd

The patch adds a validation to ensure that the last field, which is
reserved, must be all-zeroes in ZSTD_decodeSeqHeaders. This prevents
potential corruption from going undetected.

Fixes an issue where corrupted input could lead to undefined behavior
due to improper validation of reserved bits.

Signed-off-by: aimuz 
---
 lib/decompress/zstd_decompress_block.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 19cbdc5c1..80c29db69 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -607,6 +607,7 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
 
     /* FSE table descriptors */
     RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
+    RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */
     {   symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
         symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
         symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);

From 20f8df64404b125fb76b851ccea944f47b820fd8 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 13 Dec 2023 10:53:13 -0500
Subject: [PATCH 136/937] Update FreeBSD CI: drop 12.4 as it is nearly EOL

12.4 is EOL as of the end of December 2023, and pkg installation will
start failing some time after that so remove those jobs now.
---
 .cirrus.yml | 1 -
 1 file changed, 1 deletion(-)

diff --git a/.cirrus.yml b/.cirrus.yml
index 047e77f69..2e5e18c01 100644
--- a/.cirrus.yml
+++ b/.cirrus.yml
@@ -3,7 +3,6 @@ task:
   freebsd_instance:
     matrix:
       image_family: freebsd-13-2
-      image_family: freebsd-12-4
   install_script: pkg install -y gmake coreutils
   script: |
     MOREFLAGS="-Werror" gmake -j all

From 2ce0290e4d745846f03956be238596929de88768 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 13 Dec 2023 19:54:29 -0500
Subject: [PATCH 137/937] zlibWrapper: convert to C89 / ANSI C

Clang 16 (which is the system compiler in FreeBSD 14.0) no longer allows
K&R function definitions.  Formatting of the changes matches current
zlib.
---
 zlibWrapper/examples/example.c          | 67 +++++-------------
 zlibWrapper/examples/example_original.c | 49 ++++---------
 zlibWrapper/examples/minigzip.c         | 63 ++++-------------
 zlibWrapper/gzclose.c                   |  4 +-
 zlibWrapper/gzlib.c                     | 93 ++++++-------------------
 zlibWrapper/gzread.c                    | 75 +++++---------------
 zlibWrapper/gzwrite.c                   | 76 +++++---------------
 7 files changed, 103 insertions(+), 324 deletions(-)

diff --git a/zlibWrapper/examples/example.c b/zlibWrapper/examples/example.c
index d7590e312..99fbf5b19 100644
--- a/zlibWrapper/examples/example.c
+++ b/zlibWrapper/examples/example.c
@@ -77,9 +77,7 @@ int  main               _Z_OF((int argc, char *argv[]));
 void *myalloc _Z_OF((void *, unsigned, unsigned));
 void myfree _Z_OF((void *, void *));
 
-void *myalloc(q, n, m)
-    void *q;
-    unsigned n, m;
+void *myalloc(void *q, unsigned n, unsigned m)
 {
     void *buf = calloc(n, m);
     q = Z_NULL;
@@ -110,10 +108,8 @@ void test_gzio          _Z_OF((const char *fname,
 /* ===========================================================================
  * Test compress() and uncompress()
  */
-void test_compress(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+void test_compress(Byte *compr, uLong comprLen, Byte *uncompr,
+                   uLong uncomprLen) {
     int err;
     uLong len = (uLong)strlen(hello)+1;
 
@@ -136,11 +132,7 @@ void test_compress(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test read/write of .gz files
  */
-void test_gzio(fname, uncompr, uncomprLen)
-    const char *fname; /* compressed file name */
-    Byte *uncompr;
-    uLong uncomprLen;
-{
+void test_gzio(const char *fname, Byte *uncompr, uLong uncomprLen) {
 #ifdef NO_GZCOMPRESS
     fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
 #else
@@ -222,10 +214,7 @@ void test_gzio(fname, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with small buffers
  */
-void test_deflate(compr, comprLen)
-    Byte *compr;
-    uLong comprLen;
-{
+void test_deflate(Byte *compr, uLong comprLen) {
     z_stream c_stream; /* compression stream */
     int err;
     uLong len = (uLong)strlen(hello)+1;
@@ -260,10 +249,8 @@ void test_deflate(compr, comprLen)
 /* ===========================================================================
  * Test inflate() with small buffers
  */
-void test_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+void test_inflate(Byte *compr, uLong comprLen, Byte *uncompr,
+                  uLong uncomprLen) {
     int err;
     z_stream d_stream; /* decompression stream */
 
@@ -301,10 +288,8 @@ void test_inflate(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with large buffers and dynamic change of compression level
  */
-void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+void test_large_deflate(Byte *compr, uLong comprLen, Byte *uncompr,
+                        uLong uncomprLen) {
     z_stream c_stream; /* compression stream */
     int err;
 
@@ -355,11 +340,9 @@ void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
 
 /* ===========================================================================
  * Test inflate() with large buffers
- */
-void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+ */ 
+void test_large_inflate(Byte *compr, uLong comprLen, Byte *uncompr,
+                        uLong uncomprLen) {
     int err;
     z_stream d_stream; /* decompression stream */
 
@@ -397,10 +380,7 @@ void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with full flush
  */
-void test_flush(compr, comprLen)
-    Byte *compr;
-    uLong *comprLen;
-{
+void test_flush(Byte *compr, uLong *comprLen) {
     z_stream c_stream; /* compression stream */
     int err;
     uInt len = (uInt)strlen(hello)+1;
@@ -435,10 +415,7 @@ void test_flush(compr, comprLen)
 /* ===========================================================================
  * Test inflateSync()
  */
-void test_sync(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+void test_sync(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) {
     int err;
     z_stream d_stream; /* decompression stream */
 
@@ -479,10 +456,7 @@ void test_sync(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with preset dictionary
  */
-void test_dict_deflate(compr, comprLen)
-    Byte *compr;
-    uLong comprLen;
-{
+void test_dict_deflate(Byte *compr, uLong comprLen) {
     z_stream c_stream; /* compression stream */
     int err;
 
@@ -516,10 +490,8 @@ void test_dict_deflate(compr, comprLen)
 /* ===========================================================================
  * Test inflate() with a preset dictionary
  */
-void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
-{
+void test_dict_inflate(Byte *compr, uLong comprLen, Byte *uncompr,
+                       uLong uncomprLen) {
     int err;
     z_stream d_stream; /* decompression stream */
 
@@ -567,10 +539,7 @@ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
  * Usage:  example [output.gz  [input.gz]]
  */
 
-int main(argc, argv)
-    int argc;
-    char *argv[];
-{
+int main(int argc, char *argv[]) {
     Byte *compr, *uncompr;
     uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
     uLong uncomprLen = comprLen;
diff --git a/zlibWrapper/examples/example_original.c b/zlibWrapper/examples/example_original.c
index 5b4e4d1d8..828b06c88 100644
--- a/zlibWrapper/examples/example_original.c
+++ b/zlibWrapper/examples/example_original.c
@@ -102,9 +102,7 @@ void test_gzio          _Z_OF((const char *fname,
 /* ===========================================================================
  * Test compress() and uncompress()
  */
-void test_compress(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_compress(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)
 {
     int err;
     uLong len = (uLong)strlen(hello)+1;
@@ -128,10 +126,8 @@ void test_compress(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test read/write of .gz files
  */
-void test_gzio(fname, uncompr, uncomprLen)
-    const char *fname; /* compressed file name */
-    Byte *uncompr;
-    uLong uncomprLen;
+void test_gzio(const char *fname /* compressed file name */, Byte *uncompr,
+    uLong uncomprLen)
 {
 #ifdef NO_GZCOMPRESS
     fprintf(stderr, "NO_GZCOMPRESS -- gz* functions cannot compress\n");
@@ -214,9 +210,7 @@ void test_gzio(fname, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with small buffers
  */
-void test_deflate(compr, comprLen)
-    Byte *compr;
-    uLong comprLen;
+void test_deflate(Byte *compr, uLong comprLen)
 {
     z_stream c_stream; /* compression stream */
     int err;
@@ -252,9 +246,7 @@ void test_deflate(compr, comprLen)
 /* ===========================================================================
  * Test inflate() with small buffers
  */
-void test_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_inflate(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)
 {
     int err;
     z_stream d_stream; /* decompression stream */
@@ -293,9 +285,8 @@ void test_inflate(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with large buffers and dynamic change of compression level
  */
-void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_large_deflate(Byte *compr, uLong comprLen, Byte *uncompr,
+    uLong uncomprLen)
 {
     z_stream c_stream; /* compression stream */
     int err;
@@ -348,9 +339,8 @@ void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test inflate() with large buffers
  */
-void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_large_inflate(Byte *compr, uLong comprLen, Byte *uncompr,
+    uLong uncomprLen)
 {
     int err;
     z_stream d_stream; /* decompression stream */
@@ -389,9 +379,7 @@ void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with full flush
  */
-void test_flush(compr, comprLen)
-    Byte *compr;
-    uLong *comprLen;
+void test_flush(Byte *compr, uLong comprLen)
 {
     z_stream c_stream; /* compression stream */
     int err;
@@ -427,9 +415,7 @@ void test_flush(compr, comprLen)
 /* ===========================================================================
  * Test inflateSync()
  */
-void test_sync(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_sync(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen)
 {
     int err;
     z_stream d_stream; /* decompression stream */
@@ -471,9 +457,7 @@ void test_sync(compr, comprLen, uncompr, uncomprLen)
 /* ===========================================================================
  * Test deflate() with preset dictionary
  */
-void test_dict_deflate(compr, comprLen)
-    Byte *compr;
-    uLong comprLen;
+void test_dict_deflate(Byte *compr, uLong comprLen)
 {
     z_stream c_stream; /* compression stream */
     int err;
@@ -508,9 +492,8 @@ void test_dict_deflate(compr, comprLen)
 /* ===========================================================================
  * Test inflate() with a preset dictionary
  */
-void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
-    Byte *compr, *uncompr;
-    uLong comprLen, uncomprLen;
+void test_dict_inflate(Byte *compr, uLong comprLen, Byte *uncompr,
+    uLong uncomprLen)
 {
     int err;
     z_stream d_stream; /* decompression stream */
@@ -559,9 +542,7 @@ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
  * Usage:  example [output.gz  [input.gz]]
  */
 
-int main(argc, argv)
-    int argc;
-    char *argv[];
+int main(int argc, char *argv[])
 {
     Byte *compr, *uncompr;
     uLong comprLen = 10000*sizeof(int); /* don't overflow on MSDOS */
diff --git a/zlibWrapper/examples/minigzip.c b/zlibWrapper/examples/minigzip.c
index 67a17907b..1af815207 100644
--- a/zlibWrapper/examples/minigzip.c
+++ b/zlibWrapper/examples/minigzip.c
@@ -82,8 +82,7 @@
    The strwinerror function does not change the current setting
    of GetLastError.  */
 
-static char *strwinerror (error)
-     DWORD error;
+static char *strwinerror(DWORD error)
 {
     static char buf[1024];
 
@@ -121,8 +120,7 @@ static char *strwinerror (error)
     return buf;
 }
 
-static void pwinerror (s)
-    const char *s;
+static void pwinerror (const char *s)
 {
     if (s && *s)
         fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
@@ -198,11 +196,7 @@ const char *mode;
     return gz_open(NULL, fd, mode);
 }
 
-gzFile gz_open(path, fd, mode)
-    const char *path;
-    int fd;
-    const char *mode;
-{
+gzFile gz_open(const char *path, int fd, const char *mode) {
     gzFile gz;
     int ret;
 
@@ -238,11 +232,7 @@ gzFile gz_open(path, fd, mode)
 
 int gzwrite _Z_OF((gzFile, const void *, unsigned));
 
-int gzwrite(gz, buf, len)
-    gzFile gz;
-    const void *buf;
-    unsigned len;
-{
+int gzwrite(gzFile gz, const void *buf, unsigned len) {
     z_stream *strm;
     unsigned char out[BUFLEN];
 
@@ -262,11 +252,7 @@ int gzwrite(gz, buf, len)
 
 int gzread _Z_OF((gzFile, void *, unsigned));
 
-int gzread(gz, buf, len)
-    gzFile gz;
-    void *buf;
-    unsigned len;
-{
+int gzread(gzFile gz, void *buf, unsigned len) {
     int ret;
     unsigned got;
     unsigned char in[1];
@@ -299,9 +285,7 @@ int gzread(gz, buf, len)
 
 int gzclose _Z_OF((gzFile));
 
-int gzclose(gz)
-    gzFile gz;
-{
+int gzclose(gzFile gz) {
     z_stream *strm;
     unsigned char out[BUFLEN];
 
@@ -328,9 +312,7 @@ int gzclose(gz)
 
 const char *gzerror _Z_OF((gzFile, int *));
 
-const char *gzerror(gz, err)
-    gzFile gz;
-    int *err;
+const char *gzerror(gzFile gz, int *err)
 {
     *err = gz->err;
     return gz->msg;
@@ -353,8 +335,7 @@ int  main             _Z_OF((int argc, char *argv[]));
 /* ===========================================================================
  * Display error message and exit
  */
-void error(msg)
-    const char *msg;
+void error(const char *msg)
 {
     fprintf(stderr, "%s: %s\n", prog, msg);
     exit(1);
@@ -364,9 +345,7 @@ void error(msg)
  * Compress input to output then close both files.
  */
 
-void gz_compress(in, out)
-    FILE   *in;
-    gzFile out;
+void gz_compress(FILE *in, gzFile out)
 {
     local char buf[BUFLEN];
     int len;
@@ -397,10 +376,7 @@ void gz_compress(in, out)
 /* Try compressing the input file at once using mmap. Return Z_OK if
  * if success, Z_ERRNO otherwise.
  */
-int gz_compress_mmap(in, out)
-    FILE   *in;
-    gzFile out;
-{
+int gz_compress_mmap(FILE *in, gzFile out) {
     int len;
     int err;
     int ifd = fileno(in);
@@ -432,10 +408,7 @@ int gz_compress_mmap(in, out)
 /* ===========================================================================
  * Uncompress input to output then close both files.
  */
-void gz_uncompress(in, out)
-    gzFile in;
-    FILE   *out;
-{
+void gz_uncompress(gzFile in, FILE *out) {
     local char buf[BUFLEN];
     int len;
     int err;
@@ -459,10 +432,7 @@ void gz_uncompress(in, out)
  * Compress the given file: create a corresponding .gz file and remove the
  * original.
  */
-void file_compress(file, mode)
-    char  *file;
-    char  *mode;
-{
+void file_compress(char *file, char *mode) {
     local char outfile[MAX_NAME_LEN];
     FILE  *in;
     gzFile out;
@@ -494,9 +464,7 @@ void file_compress(file, mode)
 /* ===========================================================================
  * Uncompress the given file and remove the original.
  */
-void file_uncompress(file)
-    char  *file;
-{
+void file_uncompress(char *file) {
     local char buf[MAX_NAME_LEN];
     char *infile, *outfile;
     FILE  *out;
@@ -546,10 +514,7 @@ void file_uncompress(file)
  *   -1 to -9 : compression level
  */
 
-int main(argc, argv)
-    int argc;
-    char *argv[];
-{
+int main(int argc, char *argv[]) {
     int copyout = 0;
     int uncompr = 0;
     gzFile file;
diff --git a/zlibWrapper/gzclose.c b/zlibWrapper/gzclose.c
index ba43b8c5e..12a2dfc58 100644
--- a/zlibWrapper/gzclose.c
+++ b/zlibWrapper/gzclose.c
@@ -11,9 +11,7 @@
 /* gzclose() is in a separate file so that it is linked in only if it is used.
    That way the other gzclose functions can be used instead to avoid linking in
    unneeded compression or decompression routines. */
-int ZEXPORT gzclose(file)
-    gzFile file;
-{
+int ZEXPORT gzclose(gzFile file) {
 #ifndef NO_GZCOMPRESS
     gz_statep state;
 
diff --git a/zlibWrapper/gzlib.c b/zlibWrapper/gzlib.c
index eea480a74..c72651511 100644
--- a/zlibWrapper/gzlib.c
+++ b/zlibWrapper/gzlib.c
@@ -33,9 +33,7 @@ local gzFile gz_open _Z_OF((const void *, int, const char *));
 
    The gz_strwinerror function does not change the current setting of
    GetLastError. */
-char ZLIB_INTERNAL *gz_strwinerror (error)
-     DWORD error;
-{
+char ZLIB_INTERNAL *gz_strwinerror(DWORD error) {
     static char buf[1024];
 
     wchar_t *msgbuf;
@@ -75,9 +73,7 @@ char ZLIB_INTERNAL *gz_strwinerror (error)
 #endif /* UNDER_CE */
 
 /* Reset gzip file state */
-local void gz_reset(state)
-    gz_statep state;
-{
+local void gz_reset(gz_statep state) {
     state.state->x.have = 0;              /* no output data available */
     if (state.state->mode == GZ_READ) {   /* for reading ... */
         state.state->eof = 0;             /* not at end of file */
@@ -91,11 +87,7 @@ local void gz_reset(state)
 }
 
 /* Open a gzip file either by name or file descriptor. */
-local gzFile gz_open(path, fd, mode)
-    const void *path;
-    int fd;
-    const char *mode;
-{
+local gzFile gz_open(const void *path, int fd, const char *mode) {
     gz_statep state;
     z_size_t len;
     int oflag;
@@ -270,26 +262,17 @@ local gzFile gz_open(path, fd, mode)
 }
 
 /* -- see zlib.h -- */
-gzFile ZEXPORT gzopen(path, mode)
-    const char *path;
-    const char *mode;
-{
+gzFile ZEXPORT gzopen(const char *path, const char *mode) {
     return gz_open(path, -1, mode);
 }
 
 /* -- see zlib.h -- */
-gzFile ZEXPORT gzopen64(path, mode)
-    const char *path;
-    const char *mode;
-{
+gzFile ZEXPORT gzopen64(const char *path, const char *mode) {
     return gz_open(path, -1, mode);
 }
 
 /* -- see zlib.h -- */
-gzFile ZEXPORT gzdopen(fd, mode)
-    int fd;
-    const char *mode;
-{
+gzFile ZEXPORT gzdopen(int fd, const char *mode) {
     char *path;         /* identifier for error messages */
     gzFile gz;
 
@@ -307,19 +290,13 @@ gzFile ZEXPORT gzdopen(fd, mode)
 
 /* -- see zlib.h -- */
 #ifdef WIDECHAR
-gzFile ZEXPORT gzopen_w(path, mode)
-    const wchar_t *path;
-    const char *mode;
-{
+gzFile ZEXPORT gzopen_w(const wchar_t *path, const char *mode) {
     return gz_open(path, -2, mode);
 }
 #endif
 
 /* -- see zlib.h -- */
-int ZEXPORT gzbuffer(file, size)
-    gzFile file;
-    unsigned size;
-{
+int ZEXPORT gzbuffer(gzFile file, unsigned size) {
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -343,9 +320,7 @@ int ZEXPORT gzbuffer(file, size)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzrewind(file)
-    gzFile file;
-{
+int ZEXPORT gzrewind(gzFile file) {
     gz_statep state;
 
     /* get internal structure */
@@ -366,11 +341,7 @@ int ZEXPORT gzrewind(file)
 }
 
 /* -- see zlib.h -- */
-z_off64_t ZEXPORT gzseek64(file, offset, whence)
-    gzFile file;
-    z_off64_t offset;
-    int whence;
-{
+z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) {
     unsigned n;
     z_off64_t ret;
     gz_statep state;
@@ -443,11 +414,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence)
 }
 
 /* -- see zlib.h -- */
-z_off_t ZEXPORT gzseek(file, offset, whence)
-    gzFile file;
-    z_off_t offset;
-    int whence;
-{
+z_off_t ZEXPORT gzseek(gzFile file, z_off_t offset, int whence) {
     z_off64_t ret;
 
     ret = gzseek64(file, (z_off64_t)offset, whence);
@@ -455,9 +422,7 @@ z_off_t ZEXPORT gzseek(file, offset, whence)
 }
 
 /* -- see zlib.h -- */
-z_off64_t ZEXPORT gztell64(file)
-    gzFile file;
-{
+z_off64_t ZEXPORT gztell64(gzFile file) {
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -472,9 +437,7 @@ z_off64_t ZEXPORT gztell64(file)
 }
 
 /* -- see zlib.h -- */
-z_off_t ZEXPORT gztell(file)
-    gzFile file;
-{
+z_off_t ZEXPORT gztell(gzFile file) {
     z_off64_t ret;
 
     ret = gztell64(file);
@@ -482,9 +445,7 @@ z_off_t ZEXPORT gztell(file)
 }
 
 /* -- see zlib.h -- */
-z_off64_t ZEXPORT gzoffset64(file)
-    gzFile file;
-{
+z_off64_t ZEXPORT gzoffset64(gzFile file) {
     z_off64_t offset;
     gz_statep state;
 
@@ -505,9 +466,7 @@ z_off64_t ZEXPORT gzoffset64(file)
 }
 
 /* -- see zlib.h -- */
-z_off_t ZEXPORT gzoffset(file)
-    gzFile file;
-{
+z_off_t ZEXPORT gzoffset(gzFile file) {
     z_off64_t ret;
 
     ret = gzoffset64(file);
@@ -515,9 +474,7 @@ z_off_t ZEXPORT gzoffset(file)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzeof(file)
-    gzFile file;
-{
+int ZEXPORT gzeof(gzFile file) {
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -532,10 +489,7 @@ int ZEXPORT gzeof(file)
 }
 
 /* -- see zlib.h -- */
-const char * ZEXPORT gzerror(file, errnum)
-    gzFile file;
-    int *errnum;
-{
+const char * ZEXPORT gzerror(gzFile file, int *errnum) {
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -553,9 +507,7 @@ const char * ZEXPORT gzerror(file, errnum)
 }
 
 /* -- see zlib.h -- */
-void ZEXPORT gzclearerr(file)
-    gzFile file;
-{
+void ZEXPORT gzclearerr(gzFile file) {
     gz_statep state;
 
     /* get internal structure and check integrity */
@@ -579,11 +531,7 @@ void ZEXPORT gzclearerr(file)
    memory).  Simply save the error message as a static string.  If there is an
    allocation failure constructing the error message, then convert the error to
    out of memory. */
-void ZLIB_INTERNAL gz_error(state, err, msg)
-    gz_statep state;
-    int err;
-    const char *msg;
-{
+void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) {
     /* free previously allocated message and clear */
     if (state.state->msg != NULL) {
         if (state.state->err != Z_MEM_ERROR)
@@ -625,8 +573,7 @@ void ZLIB_INTERNAL gz_error(state, err, msg)
    available) -- we need to do this to cover cases where 2's complement not
    used, since C standard permits 1's complement and sign-bit representations,
    otherwise we could just use ((unsigned)-1) >> 1 */
-unsigned ZLIB_INTERNAL gz_intmax()
-{
+unsigned ZLIB_INTERNAL gz_intmax() {
     unsigned p, q;
 
     p = 1;
diff --git a/zlibWrapper/gzread.c b/zlibWrapper/gzread.c
index 584fad1ea..ed3c17826 100644
--- a/zlibWrapper/gzread.c
+++ b/zlibWrapper/gzread.c
@@ -29,12 +29,8 @@ local z_size_t gz_read _Z_OF((gz_statep, voidp, z_size_t));
    state.state->fd, and update state.state->eof, state.state->err, and state.state->msg as appropriate.
    This function needs to loop on read(), since read() is not guaranteed to
    read the number of bytes requested, depending on the type of descriptor. */
-local int gz_load(state, buf, len, have)
-    gz_statep state;
-    unsigned char *buf;
-    unsigned len;
-    unsigned *have;
-{
+local int gz_load(gz_statep state, unsigned char *buf, unsigned len,
+                  unsigned *have) {
     ssize_t ret;
     unsigned get, max = ((unsigned)-1 >> 2) + 1;
 
@@ -64,8 +60,7 @@ local int gz_load(state, buf, len, have)
    If strm->avail_in != 0, then the current data is moved to the beginning of
    the input buffer, and then the remainder of the buffer is loaded with the
    available data from the input file. */
-local int gz_avail(state)
-    gz_statep state;
+local int gz_avail(gz_statep state)
 {
     unsigned got;
     z_streamp strm = &(state.state->strm);
@@ -99,9 +94,7 @@ local int gz_avail(state)
    case, all further file reads will be directly to either the output buffer or
    a user buffer.  If decompressing, the inflate state will be initialized.
    gz_look() will return 0 on success or -1 on failure. */
-local int gz_look(state)
-    gz_statep state;
-{
+local int gz_look(gz_statep state) {
     z_streamp strm = &(state.state->strm);
 
     /* allocate read buffers and inflate memory */
@@ -184,9 +177,7 @@ local int gz_look(state)
    data.  If the gzip stream completes, state.state->how is reset to LOOK to look for
    the next gzip stream or raw data, once state.state->x.have is depleted.  Returns 0
    on success, -1 on failure. */
-local int gz_decomp(state)
-    gz_statep state;
-{
+local int gz_decomp(gz_statep state) {
     int ret = Z_OK;
     unsigned had;
     z_streamp strm = &(state.state->strm);
@@ -238,9 +229,7 @@ local int gz_decomp(state)
    looked for to determine whether to copy or decompress.  Returns -1 on error,
    otherwise 0.  gz_fetch() will leave state.state->how as COPY or GZIP unless the
    end of the input file has been reached and all data has been processed.  */
-local int gz_fetch(state)
-    gz_statep state;
-{
+local int gz_fetch(gz_statep state) {
     z_streamp strm = &(state.state->strm);
 
     do {
@@ -268,10 +257,7 @@ local int gz_fetch(state)
 }
 
 /* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
-local int gz_skip(state, len)
-    gz_statep state;
-    z_off64_t len;
-{
+local int gz_skip(gz_statep state, z_off64_t len) {
     unsigned n;
 
     /* skip over len bytes or reach end-of-file, whichever comes first */
@@ -303,11 +289,7 @@ local int gz_skip(state, len)
    input.  Return the number of bytes read.  If zero is returned, either the
    end of file was reached, or there was an error.  state.state->err must be
    consulted in that case to determine which. */
-local z_size_t gz_read(state, buf, len)
-    gz_statep state;
-    voidp buf;
-    z_size_t len;
-{
+local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) {
     z_size_t got;
     unsigned n;
 
@@ -384,11 +366,7 @@ local z_size_t gz_read(state, buf, len)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzread(file, buf, len)
-    gzFile file;
-    voidp buf;
-    unsigned len;
-{
+int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) {
     gz_statep state;
 
     /* get internal structure */
@@ -420,12 +398,8 @@ int ZEXPORT gzread(file, buf, len)
 }
 
 /* -- see zlib.h -- */
-z_size_t ZEXPORT gzfread(buf, size, nitems, file)
-    voidp buf;
-    z_size_t size;
-    z_size_t nitems;
-    gzFile file;
-{
+z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
+                         gzFile file) {
     z_size_t len;
     gz_statep state;
 
@@ -468,9 +442,7 @@ ZEXTERN int ZEXPORT gzgetc _Z_OF((gzFile file));
 ZEXTERN int ZEXPORT gzgetc_ _Z_OF((gzFile file));
 #endif
 
-int ZEXPORT gzgetc(file)
-    gzFile file;
-{
+int ZEXPORT gzgetc(gzFile file) {
     int ret;
     unsigned char buf[1];
     gz_statep state;
@@ -497,17 +469,12 @@ int ZEXPORT gzgetc(file)
     return ret < 1 ? -1 : buf[0];
 }
 
-int ZEXPORT gzgetc_(file)
-gzFile file;
-{
+int ZEXPORT gzgetc_(gzFile file) {
     return gzgetc(file);
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzungetc(c, file)
-    int c;
-    gzFile file;
-{
+int ZEXPORT gzungetc(int c, gzFile file) {
     gz_statep state;
 
     /* get internal structure */
@@ -564,11 +531,7 @@ int ZEXPORT gzungetc(c, file)
 }
 
 /* -- see zlib.h -- */
-char * ZEXPORT gzgets(file, buf, len)
-    gzFile file;
-    char *buf;
-    int len;
-{
+char * ZEXPORT gzgets(gzFile file, char *buf, int len) {
     unsigned left, n;
     char *str;
     unsigned char *eol;
@@ -628,9 +591,7 @@ char * ZEXPORT gzgets(file, buf, len)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzdirect(file)
-    gzFile file;
-{
+int ZEXPORT gzdirect(gzFile file) {
     gz_statep state;
 
     /* get internal structure */
@@ -648,9 +609,7 @@ int ZEXPORT gzdirect(file)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzclose_r(file)
-    gzFile file;
-{
+int ZEXPORT gzclose_r(gzFile file) {
     int ret, err;
     gz_statep state;
 
diff --git a/zlibWrapper/gzwrite.c b/zlibWrapper/gzwrite.c
index ccd4f71f1..81da15314 100644
--- a/zlibWrapper/gzwrite.c
+++ b/zlibWrapper/gzwrite.c
@@ -19,9 +19,7 @@ local z_size_t gz_write _Z_OF((gz_statep, voidpc, z_size_t));
 /* Initialize state for writing a gzip file.  Mark initialization by setting
    state.state->size to non-zero.  Return -1 on a memory allocation failure, or 0 on
    success. */
-local int gz_init(state)
-    gz_statep state;
-{
+local int gz_init(gz_statep state) {
     int ret;
     z_streamp strm = &(state.state->strm);
 
@@ -75,10 +73,7 @@ local int gz_init(state)
    deflate() flush value.  If flush is Z_FINISH, then the deflate() state is
    reset to start a new gzip stream.  If gz->direct is true, then simply write
    to the output file without compressing, and ignore flush. */
-local int gz_comp(state, flush)
-    gz_statep state;
-    int flush;
-{
+local int gz_comp(gz_statep state, int flush) {
     int ret, writ;
     unsigned have, put, max = ((unsigned)-1 >> 2) + 1;
     z_streamp strm = &(state.state->strm);
@@ -147,10 +142,7 @@ local int gz_comp(state, flush)
 
 /* Compress len zeros to output.  Return -1 on a write error or memory
    allocation failure by gz_comp(), or 0 on success. */
-local int gz_zero(state, len)
-    gz_statep state;
-    z_off64_t len;
-{
+local int gz_zero(gz_statep state, z_off64_t len) {
     int first;
     unsigned n;
     z_streamp strm = &(state.state->strm);
@@ -180,11 +172,7 @@ local int gz_zero(state, len)
 
 /* Write len bytes from buf to file.  Return the number of bytes written.  If
    the returned value is less than len, then there was an error. */
-local z_size_t gz_write(state, buf, len)
-    gz_statep state;
-    voidpc buf;
-    z_size_t len;
-{
+local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) {
     z_size_t put = len;
 
     /* if len is zero, avoid unnecessary operations */
@@ -248,11 +236,7 @@ local z_size_t gz_write(state, buf, len)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzwrite(file, buf, len)
-    gzFile file;
-    voidpc buf;
-    unsigned len;
-{
+int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len) {
     gz_statep state;
 
     /* get internal structure */
@@ -276,12 +260,8 @@ int ZEXPORT gzwrite(file, buf, len)
 }
 
 /* -- see zlib.h -- */
-z_size_t ZEXPORT gzfwrite(buf, size, nitems, file)
-    voidpc buf;
-    z_size_t size;
-    z_size_t nitems;
-    gzFile file;
-{
+z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size, z_size_t nitems,
+                          gzFile file) {
     z_size_t len;
     gz_statep state;
 
@@ -307,10 +287,7 @@ z_size_t ZEXPORT gzfwrite(buf, size, nitems, file)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzputc(file, c)
-    gzFile file;
-    int c;
-{
+int ZEXPORT gzputc(gzFile file, int c) {
     unsigned have;
     unsigned char buf[1];
     gz_statep state;
@@ -355,10 +332,7 @@ int ZEXPORT gzputc(file, c)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzputs(file, str)
-    gzFile file;
-    const char *str;
-{
+int ZEXPORT gzputs(gzFile file, const char *str) {
     int ret;
     z_size_t len;
     gz_statep state;
@@ -382,8 +356,7 @@ int ZEXPORT gzputs(file, str)
 #include 
 
 /* -- see zlib.h -- */
-int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)
-{
+int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) {
     int len;
     unsigned left;
     char *next;
@@ -454,8 +427,7 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)
     return len;
 }
 
-int ZEXPORTVA gzprintf(gzFile file, const char *format, ...)
-{
+int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) {
     va_list va;
     int ret;
 
@@ -468,13 +440,10 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, ...)
 #else /* !STDC && !Z_HAVE_STDARG_H */
 
 /* -- see zlib.h -- */
-int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
-                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
-    gzFile file;
-    const char *format;
-    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
-        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
-{
+int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3,
+                       int a4, int a5, int a6, int a7, int a8, int a9, int a10,
+                       int a11, int a12, int a13, int a14, int a15, int a16,
+                       int a17, int a18, int a19, int a20) {
     unsigned len, left;
     char *next;
     gz_statep state;
@@ -556,10 +525,7 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
 #endif
 
 /* -- see zlib.h -- */
-int ZEXPORT gzflush(file, flush)
-    gzFile file;
-    int flush;
-{
+int ZEXPORT gzflush(gzFile file, int flush) {
     gz_statep state;
 
     /* get internal structure */
@@ -588,11 +554,7 @@ int ZEXPORT gzflush(file, flush)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzsetparams(file, level, strategy)
-    gzFile file;
-    int level;
-    int strategy;
-{
+int ZEXPORT gzsetparams(gzFile file, int level, int strategy) {
     gz_statep state;
     z_streamp strm;
 
@@ -630,9 +592,7 @@ int ZEXPORT gzsetparams(file, level, strategy)
 }
 
 /* -- see zlib.h -- */
-int ZEXPORT gzclose_w(file)
-    gzFile file;
-{
+int ZEXPORT gzclose_w(gzFile file) {
     int ret = Z_OK;
     gz_statep state;
 

From 9a3b17c4d61f00e22997d946f422533564812fe3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C5=82=20Chojnowski?= 
Date: Sat, 16 Dec 2023 12:32:52 +0100
Subject: [PATCH 138/937] Fix a nullptr dereference in
 ZSTD_createCDict_advanced2()

If the relevant allocation returns NULL, ZSTD_createCDict_advanced_internal()
will return NULL. But ZSTD_createCDict_advanced2() doesn't check for
this and attempts to use the returned pointer anyway, which leads to
a segfault.
---
 lib/compress/zstd_compress.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index cdd763ff6..dc892dae7 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -5525,7 +5525,7 @@ ZSTD_CDict* ZSTD_createCDict_advanced2(
                         cctxParams.useRowMatchFinder, cctxParams.enableDedicatedDictSearch,
                         customMem);
 
-    if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
+    if (!cdict || ZSTD_isError( ZSTD_initCDict_internal(cdict,
                                     dict, dictSize,
                                     dictLoadMethod, dictContentType,
                                     cctxParams) )) {

From e515327764889938692dac3257a300df56a15e8f Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 18 Dec 2023 05:26:39 +0000
Subject: [PATCH 139/937] Bump actions/upload-artifact from 3.1.3 to 4.0.0

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3.1.3 to 4.0.0.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/a8a3f3ad30e3422c9c7b888a15615d19a852ae32...c7d193f32edcb7bfad88892161225aeda64e9392)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/scorecards.yml        | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index dbef98982..4a47c9c89 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -290,7 +290,7 @@ jobs:
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3.1.3
+      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 7518519dc..2d698967d 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -51,7 +51,7 @@ jobs:
       # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
       # format to the repository Actions tab.
       - name: "Upload artifact"
-        uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3.1.3
+        uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
         with:
           name: SARIF file
           path: results.sarif
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index 70c2d163b..2300d09bf 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # tag=v3
+      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v3
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From 8052cd0131a4f483ef14be3e564530c07ea382f5 Mon Sep 17 00:00:00 2001
From: Ruslan Sayfutdinov 
Date: Sat, 16 Dec 2023 15:28:19 +0000
Subject: [PATCH 140/937] cli: better errors on arguent parsing

---
 programs/zstdcli.c                        | 48 +++++++++++++----------
 tests/cli-tests/basic/args.sh             | 10 +++++
 tests/cli-tests/basic/args.sh.exit        |  1 +
 tests/cli-tests/basic/args.sh.stderr.glob | 28 +++++++++++++
 4 files changed, 66 insertions(+), 21 deletions(-)
 create mode 100755 tests/cli-tests/basic/args.sh
 create mode 100644 tests/cli-tests/basic/args.sh.exit
 create mode 100644 tests/cli-tests/basic/args.sh.stderr.glob

diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 66952aa82..3f0ae8bdd 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -138,8 +138,8 @@ static int exeNameMatch(const char* exeName, const char* test)
 *  Command Line
 **************************************/
 /* print help either in `stderr` or `stdout` depending on originating request
- * error (badusage) => stderr
- * help (usage_advanced) => stdout
+ * error (badUsage) => stderr
+ * help (usageAdvanced) => stdout
  */
 static void usage(FILE* f, const char* programName)
 {
@@ -175,7 +175,7 @@ static void usage(FILE* f, const char* programName)
     DISPLAY_F(f, "\n");
 }
 
-static void usage_advanced(const char* programName)
+static void usageAdvanced(const char* programName)
 {
     DISPLAYOUT(WELCOME_MESSAGE);
     DISPLAYOUT("\n");
@@ -316,9 +316,9 @@ static void usage_advanced(const char* programName)
 
 }
 
-static void badusage(const char* programName)
+static void badUsage(const char* programName, const char* parameter)
 {
-    DISPLAYLEVEL(1, "Incorrect parameters \n");
+    DISPLAYLEVEL(1, "Incorrect parameter: %s\n", parameter);
     if (g_displayLevel >= 2) usage(stderr, programName);
 }
 
@@ -589,7 +589,7 @@ static ZDICT_fastCover_params_t defaultFastCoverParams(void)
 
 
 /** parseAdaptParameters() :
- *  reads adapt parameters from *stringPtr (e.g. "--zstd=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
+ *  reads adapt parameters from *stringPtr (e.g. "--adapt=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
  *  Both adaptMinPtr and adaptMaxPtr must be already allocated and correctly initialized.
  *  There is no guarantee that any of these values will be updated.
  *  @return 1 means that parsing was successful,
@@ -933,6 +933,7 @@ int main(int argCount, const char* argv[])
     /* command switches */
     for (argNb=1; argNb&2
+zstd --blah
+println "+ zstd -xz" >&2
+zstd -xz
+println "+ zstd --adapt=min=1,maxx=2 file.txt" >&2
+zstd --adapt=min=1,maxx=2 file.txt
+println "+ zstd --train-cover=k=48,d=8,steps32 file.txt" >&2
+zstd --train-cover=k=48,d=8,steps32 file.txt
diff --git a/tests/cli-tests/basic/args.sh.exit b/tests/cli-tests/basic/args.sh.exit
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/tests/cli-tests/basic/args.sh.exit
@@ -0,0 +1 @@
+1
diff --git a/tests/cli-tests/basic/args.sh.stderr.glob b/tests/cli-tests/basic/args.sh.stderr.glob
new file mode 100644
index 000000000..df275471c
--- /dev/null
+++ b/tests/cli-tests/basic/args.sh.stderr.glob
@@ -0,0 +1,28 @@
++ zstd --blah
+Incorrect parameter: --blah
+...
+Usage: zstd *
+
+Options:
+...
++ zstd -xz
+Incorrect parameter: -x
+...
+Usage: zstd *
+
+Options:
+...
++ zstd --adapt=min=1,maxx=2 file.txt
+Incorrect parameter: --adapt=min=1,maxx=2
+...
+Usage: zstd *
+
+Options:
+...
++ zstd --train-cover=k=48,d=8,steps32 file.txt
+Incorrect parameter: --train-cover=k=48,d=8,steps32
+...
+Usage: zstd *
+
+Options:
+...

From 377ecefce93d3a8705cb54c553681ff234bd9f34 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 18 Dec 2023 09:39:42 -0800
Subject: [PATCH 141/937] Update windows-artifacts.yml

and fixed version number in comment
---
 .github/workflows/windows-artifacts.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index 2300d09bf..3a2bac7a4 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v3
+      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From 475da4fb2e2aef102edecba04278b38fce44fb81 Mon Sep 17 00:00:00 2001
From: Theodore Tsirpanis 
Date: Tue, 19 Dec 2023 15:06:03 +0200
Subject: [PATCH 142/937] Make `zstd::libzstd` an imported interface target. It
 cannot be an alias, because it would lock the package to use either static or
 shared libraries at its build time. We want to decide this at the time
 `find_package` is called.

---
 build/cmake/zstdConfig.cmake.in | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/build/cmake/zstdConfig.cmake.in b/build/cmake/zstdConfig.cmake.in
index 752f3ab11..0a7f773d7 100644
--- a/build/cmake/zstdConfig.cmake.in
+++ b/build/cmake/zstdConfig.cmake.in
@@ -7,10 +7,18 @@ endif()
 
 include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets.cmake")
 
-if(@ZSTD_BUILD_SHARED@ AND NOT @ZSTD_BUILD_STATIC@)
-  add_library(zstd::libzstd ALIAS zstd::libzstd_shared)
-elseif(NOT @ZSTD_BUILD_SHARED@ AND @ZSTD_BUILD_STATIC@)
-  add_library(zstd::libzstd ALIAS zstd::libzstd_static)
+if(NOT TARGET zstd::libzstd)
+  if(@ZSTD_BUILD_SHARED@ AND NOT @ZSTD_BUILD_STATIC@)
+    add_library(zstd::libzstd INTERFACE IMPORTED)
+    set_target_properties(zstd::libzstd PROPERTIES
+      INTERFACE_LINK_LIBRARIES "zstd::libzstd_shared"
+    )
+  elseif(NOT @ZSTD_BUILD_SHARED@ AND @ZSTD_BUILD_STATIC@)
+    add_library(zstd::libzstd INTERFACE IMPORTED)
+    set_target_properties(zstd::libzstd PROPERTIES
+      INTERFACE_LINK_LIBRARIES "zstd::libzstd_static"
+    )
+  endif()
 endif()
 
 check_required_components("zstd")

From c6cabf94417d84ebb5da62e05d8b8a9623763585 Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Thu, 28 Dec 2023 14:48:46 -0500
Subject: [PATCH 143/937] Make offload API compatible with static CCtx (#3854)

* Add ZSTD_CCtxParams_registerSequenceProducer() to public API

* add unit test

* add docs to zstd.h

* nits

* Add ZSTDLIB_STATIC_API prefix

* Add asserts
---
 lib/compress/zstd_compress.c | 23 +++++++++++----
 lib/zstd.h                   | 19 +++++++++++--
 tests/zstreamtest.c          | 54 +++++++++++++++++++++++++++++++++++-
 3 files changed, 87 insertions(+), 9 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index cdd763ff6..55415c7e3 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -7084,14 +7084,27 @@ ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeH
 }
 
 void ZSTD_registerSequenceProducer(
-    ZSTD_CCtx* zc, void* extSeqProdState,
+    ZSTD_CCtx* zc,
+    void* extSeqProdState,
     ZSTD_sequenceProducer_F extSeqProdFunc
 ) {
+    assert(zc != NULL);
+    ZSTD_CCtxParams_registerSequenceProducer(
+        &zc->requestedParams, extSeqProdState, extSeqProdFunc
+    );
+}
+
+void ZSTD_CCtxParams_registerSequenceProducer(
+  ZSTD_CCtx_params* params,
+  void* extSeqProdState,
+  ZSTD_sequenceProducer_F extSeqProdFunc
+) {
+    assert(params != NULL);
     if (extSeqProdFunc != NULL) {
-        zc->requestedParams.extSeqProdFunc = extSeqProdFunc;
-        zc->requestedParams.extSeqProdState = extSeqProdState;
+        params->extSeqProdFunc = extSeqProdFunc;
+        params->extSeqProdState = extSeqProdState;
     } else {
-        zc->requestedParams.extSeqProdFunc = NULL;
-        zc->requestedParams.extSeqProdState = NULL;
+        params->extSeqProdFunc = NULL;
+        params->extSeqProdState = NULL;
     }
 }
diff --git a/lib/zstd.h b/lib/zstd.h
index 61f81db0f..841269305 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -1665,9 +1665,6 @@ ZSTDLIB_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size);
  *
  *  Note : only single-threaded compression is supported.
  *  ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.
- *
- *  Note 2 : ZSTD_estimateCCtxSize* functions are not compatible with the Block-Level Sequence Producer API at this time.
- *  Size estimates assume that no external sequence producer is registered.
  */
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);
@@ -2824,6 +2821,22 @@ ZSTD_registerSequenceProducer(
   ZSTD_sequenceProducer_F sequenceProducer
 );
 
+/*! ZSTD_CCtxParams_registerSequenceProducer() :
+ * Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params.
+ * This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(),
+ * which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx().
+ *
+ * If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx()
+ * is required, then this function is for you. Otherwise, you probably don't need it.
+ *
+ * See tests/zstreamtest.c for example usage. */
+ZSTDLIB_STATIC_API void
+ZSTD_CCtxParams_registerSequenceProducer(
+  ZSTD_CCtx_params* params,
+  void* sequenceProducerState,
+  ZSTD_sequenceProducer_F sequenceProducer
+);
+
 
 /*********************************************************************
 *  Buffer-less and synchronous inner streaming functions (DEPRECATED)
diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c
index 04f1f8b0e..82aaf3db5 100644
--- a/tests/zstreamtest.c
+++ b/tests/zstreamtest.c
@@ -1920,7 +1920,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests)
     DISPLAYLEVEL(3, "test%3i : Block-Level External Sequence Producer API: ", testNb++);
     {
         size_t const dstBufSize = ZSTD_compressBound(CNBufferSize);
-        BYTE* const dstBuf = (BYTE*)malloc(ZSTD_compressBound(dstBufSize));
+        BYTE* const dstBuf = (BYTE*)malloc(dstBufSize);
         size_t const checkBufSize = CNBufferSize;
         BYTE* const checkBuf = (BYTE*)malloc(checkBufSize);
         int enableFallback;
@@ -2356,6 +2356,58 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests)
     }
     DISPLAYLEVEL(3, "OK \n");
 
+    DISPLAYLEVEL(3, "test%3i : Testing external sequence producer with static CCtx: ", testNb++);
+    {
+        size_t const dstBufSize = ZSTD_compressBound(CNBufferSize);
+        BYTE* const dstBuf = (BYTE*)malloc(dstBufSize);
+        size_t const checkBufSize = CNBufferSize;
+        BYTE* const checkBuf = (BYTE*)malloc(checkBufSize);
+        ZSTD_CCtx_params* params = ZSTD_createCCtxParams();
+        ZSTD_CCtx* staticCCtx;
+        void* cctxBuf;
+        EMF_testCase seqProdState;
+
+        CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_validateSequences, 1));
+        CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_enableSeqProducerFallback, 0));
+        ZSTD_CCtxParams_registerSequenceProducer(params, &seqProdState, zstreamSequenceProducer);
+
+        {
+            size_t const cctxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params);
+            cctxBuf = malloc(cctxSize);
+            staticCCtx = ZSTD_initStaticCCtx(cctxBuf, cctxSize);
+            ZSTD_CCtx_setParametersUsingCCtxParams(staticCCtx, params);
+        }
+
+        // Check that compression with external sequence producer succeeds when expected
+        seqProdState = EMF_LOTS_OF_SEQS;
+        {
+            size_t dResult;
+            size_t const cResult = ZSTD_compress2(staticCCtx, dstBuf, dstBufSize, CNBuffer, CNBufferSize);
+            CHECK(ZSTD_isError(cResult), "EMF: Compression error: %s", ZSTD_getErrorName(cResult));
+            dResult = ZSTD_decompress(checkBuf, checkBufSize, dstBuf, cResult);
+            CHECK(ZSTD_isError(dResult), "EMF: Decompression error: %s", ZSTD_getErrorName(dResult));
+            CHECK(dResult != CNBufferSize, "EMF: Corruption!");
+            CHECK(memcmp(CNBuffer, checkBuf, CNBufferSize) != 0, "EMF: Corruption!");
+        }
+
+        // Check that compression with external sequence producer fails when expected
+        seqProdState = EMF_BIG_ERROR;
+        {
+            size_t const cResult = ZSTD_compress2(staticCCtx, dstBuf, dstBufSize, CNBuffer, CNBufferSize);
+            CHECK(!ZSTD_isError(cResult), "EMF: Should have raised an error!");
+            CHECK(
+                ZSTD_getErrorCode(cResult) != ZSTD_error_sequenceProducer_failed,
+                "EMF: Wrong error code: %s", ZSTD_getErrorName(cResult)
+            );
+        }
+
+        free(dstBuf);
+        free(checkBuf);
+        free(cctxBuf);
+        ZSTD_freeCCtxParams(params);
+    }
+    DISPLAYLEVEL(3, "OK \n");
+
 _end:
     FUZ_freeDictionary(dictionary);
     ZSTD_freeCStream(zc);

From f06b18b3ff009ef7dc90294fca674658ddf139bf Mon Sep 17 00:00:00 2001
From: elasota <1137273+elasota@users.noreply.github.com>
Date: Sun, 19 Nov 2023 15:33:37 -0500
Subject: [PATCH 144/937] Specify offset 0 as invalid

---
 doc/decompressor_accepted_invalid_data.md | 14 ++++++++++++++
 doc/zstd_compression_format.md            |  5 ++++-
 2 files changed, 18 insertions(+), 1 deletion(-)
 create mode 100644 doc/decompressor_accepted_invalid_data.md

diff --git a/doc/decompressor_accepted_invalid_data.md b/doc/decompressor_accepted_invalid_data.md
new file mode 100644
index 000000000..f08f963d9
--- /dev/null
+++ b/doc/decompressor_accepted_invalid_data.md
@@ -0,0 +1,14 @@
+Decompressor Accepted Invalid Data
+==================================
+
+This document describes the behavior of the reference decompressor in cases
+where it accepts an invalid frame instead of reporting an error.
+
+Zero offsets converted to 1
+---------------------------
+If a sequence is decoded with `literals_length = 0` and `offset_value = 3`
+while `Repeated_Offset_1 = 1`, the computed offset will be `0`, which is
+invalid.
+
+The reference decompressor will process this case as if the computed
+offset was `1`, including inserting `1` into the repeated offset list.
\ No newline at end of file
diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 4a8d338b7..a8d4a0f35 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -929,7 +929,10 @@ There is an exception though, when current sequence's `literals_length = 0`.
 In this case, repeated offsets are shifted by one,
 so an `offset_value` of 1 means `Repeated_Offset2`,
 an `offset_value` of 2 means `Repeated_Offset3`,
-and an `offset_value` of 3 means `Repeated_Offset1 - 1_byte`.
+and an `offset_value` of 3 means `Repeated_Offset1 - 1`.
+
+In the final case, if `Repeated_Offset1 - 1` evaluates to 0, then the
+data is considered corrupted.
 
 For the first block, the starting offset history is populated with following values :
 `Repeated_Offset1`=1, `Repeated_Offset2`=4, `Repeated_Offset3`=8,

From a52d897d6044029a904ab0d6893f6e73eec87d18 Mon Sep 17 00:00:00 2001
From: Ed Maste 
Date: Wed, 13 Dec 2023 19:56:14 -0500
Subject: [PATCH 145/937] Cirrus-CI: Add FreeBSD 14

---
 .cirrus.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.cirrus.yml b/.cirrus.yml
index 2e5e18c01..bf3f0c415 100644
--- a/.cirrus.yml
+++ b/.cirrus.yml
@@ -2,6 +2,7 @@ task:
   name: FreeBSD (shortest)
   freebsd_instance:
     matrix:
+      image_family: freebsd-14-0
       image_family: freebsd-13-2
   install_script: pkg install -y gmake coreutils
   script: |

From 923cf3dc9289d00b668cd0a330d5c28f22d4837f Mon Sep 17 00:00:00 2001
From: Eli Schwartz 
Date: Tue, 2 Jan 2024 01:36:45 -0500
Subject: [PATCH 146/937] CI: meson: use builtin handling for MSVC

This avoids downloading -- and periodically bumping the checksum for --
a third-party action that isn't strictly required, and thus helps keep
down dependencies and reduce update churn.
---
 .github/workflows/dev-short-tests.yml | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 87de8394a..65e9ae655 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -63,7 +63,7 @@ jobs:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: build zstd bin against a dynamic lib (debuglevel for more dependencies)
       run: |
-        make -C lib lib-mt-release 
+        make -C lib lib-mt-release
         DEBUGLEVEL=2 make -C programs zstd-dll
 
   gcc-7-libzstd:
@@ -246,14 +246,12 @@ jobs:
       - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
       - name: Install packages
         run: pip install --pre meson
-      - name: Initialize the MSVC dev command prompt
-        uses: ilammy/msvc-dev-cmd@cec98b9d092141f74527d0afa6feb2af698cfe89
       - name: Configure with Meson
         run: |
-          meson setup build/meson/ builddir -Dbin_tests=true -Dbin_programs=true -Dbin_contrib=true
+          meson setup --vsenv build/meson/ builddir -Dbin_tests=true -Dbin_programs=true -Dbin_contrib=true
       - name: Build with Meson
         run: |
-          ninja -C builddir/
+          meson compile -C builddir/
       - name: Test with Meson
         run: |
           meson test -C builddir/ --print-errorlogs

From 66269e74a00e531a5f27fcb4fd65eb061d02dc5c Mon Sep 17 00:00:00 2001
From: Like Ma 
Date: Sat, 13 Jan 2024 15:36:20 +0800
Subject: [PATCH 147/937] Fix building xxhash on AIX 5.1

---
 lib/common/xxhash.h | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 424ed19b8..449bd5f08 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -575,7 +575,11 @@ typedef uint32_t XXH32_hash_t;
 #elif !defined (__VMS) \
   && (defined (__cplusplus) \
   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
-#   include 
+#   ifdef _AIX
+#     include 
+#   else
+#     include 
+#   endif
     typedef uint32_t XXH32_hash_t;
 
 #else
@@ -849,7 +853,11 @@ typedef uint64_t XXH64_hash_t;
 #elif !defined (__VMS) \
   && (defined (__cplusplus) \
   || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
-#  include 
+#   ifdef _AIX
+#     include 
+#   else
+#     include 
+#   endif
    typedef uint64_t XXH64_hash_t;
 #else
 #  include 
@@ -2465,7 +2473,11 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size)
 #if !defined (__VMS) \
  && (defined (__cplusplus) \
  || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
-# include 
+# ifdef _AIX
+#   include 
+# else
+#   include 
+# endif
   typedef uint8_t xxh_u8;
 #else
   typedef unsigned char xxh_u8;

From e49d1ab6aabcd662b76a46ef48391a5462357167 Mon Sep 17 00:00:00 2001
From: Like Ma 
Date: Sat, 13 Jan 2024 15:21:50 +0800
Subject: [PATCH 148/937] Fix building on HP-UX 11.11 PA-RISC

By CMake 3.8.2 and GCC 4.7.1
---
 build/cmake/CMakeLists.txt | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 023b998f5..32f5fd6ef 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -115,9 +115,20 @@ endif ()
 # External dependencies
 #-----------------------------------------------------------------------------
 if (ZSTD_MULTITHREAD_SUPPORT AND UNIX)
-    set(THREADS_PREFER_PTHREAD_FLAG ON)
-    find_package(Threads REQUIRED)
-    if(CMAKE_USE_PTHREADS_INIT)
+    if (CMAKE_SYSTEM_NAME MATCHES "HP-UX")
+        find_package(Threads)
+        if (NOT Threads_FOUND)
+            set(CMAKE_USE_PTHREADS_INIT 1)
+            set(CMAKE_THREAD_LIBS_INIT -lpthread)
+            set(CMAKE_HAVE_THREADS_LIBRARY 1)
+            set(Threads_FOUND TRUE)
+        endif ()
+    else ()
+        set(THREADS_PREFER_PTHREAD_FLAG ON)
+        find_package(Threads REQUIRED)
+    endif ()
+
+    if (CMAKE_USE_PTHREADS_INIT)
         set(THREADS_LIBS "${CMAKE_THREAD_LIBS_INIT}")
     else()
         message(SEND_ERROR "ZSTD currently does not support thread libraries other than pthreads")

From 3a2e302b2ca25eadca7d1952119837be70b2b8b2 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 15 Jan 2024 05:24:41 +0000
Subject: [PATCH 149/937] Bump github/codeql-action from 2.21.4 to 3.23.0

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2.21.4 to 3.23.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/a09933a12a80f87b87005513f0abb1494c27a716...e5f05b81d5b6ff8cfa111c80c22c5fd02a384118)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/scorecards.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 2d698967d..c61273902 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -59,6 +59,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@a09933a12a80f87b87005513f0abb1494c27a716 # tag=v2.21.4
+        uses: github/codeql-action/upload-sarif@e5f05b81d5b6ff8cfa111c80c22c5fd02a384118 # tag=v3.23.0
         with:
           sarif_file: results.sarif

From e2fe26627907274f04b9ad7dabf41a3243547a1d Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 15 Jan 2024 05:24:46 +0000
Subject: [PATCH 150/937] Bump actions/upload-artifact from 4.0.0 to 4.1.0

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/c7d193f32edcb7bfad88892161225aeda64e9392...1eb3cb2b3e0f29609092a73eb033bb759a334595)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/scorecards.yml        | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 4a47c9c89..2f3dd6a27 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -290,7 +290,7 @@ jobs:
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
+      uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 2d698967d..f2254ede0 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -51,7 +51,7 @@ jobs:
       # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
       # format to the repository Actions tab.
       - name: "Upload artifact"
-        uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
+        uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
         with:
           name: SARIF file
           path: results.sarif
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index 3a2bac7a4..10bef46db 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # tag=v4.0.0
+      uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From e6f4b464938008c4f800a26027248a00db5c81c8 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 15 Jan 2024 11:16:46 -0800
Subject: [PATCH 151/937] playTests.sh does no longer needs grep -E

it makes the test script more portable across posix systems
because `grep -E` is not guaranteed
while `grep` is fairly common.
---
 lib/common/pool.c         |  2 +-
 programs/fileio_asyncio.c |  4 +--
 tests/playTests.sh        | 66 +++++++++++++++++++--------------------
 3 files changed, 36 insertions(+), 36 deletions(-)

diff --git a/lib/common/pool.c b/lib/common/pool.c
index d5ca5a780..3adcefc9a 100644
--- a/lib/common/pool.c
+++ b/lib/common/pool.c
@@ -223,7 +223,7 @@ static int POOL_resize_internal(POOL_ctx* ctx, size_t 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 */
-        ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(*threadPool));
+        ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t));
         ZSTD_customFree(ctx->threads, ctx->customMem);
         ctx->threads = threadPool;
         /* Initialize additional threads */
diff --git a/programs/fileio_asyncio.c b/programs/fileio_asyncio.c
index dbf0c7564..5f7bd4a4c 100644
--- a/programs/fileio_asyncio.c
+++ b/programs/fileio_asyncio.c
@@ -453,8 +453,8 @@ static IOJob_t* AIO_ReadPool_findNextWaitingOffsetCompletedJob_locked(ReadPoolCt
 /* AIO_ReadPool_numReadsInFlight:
  * Returns the number of IO read jobs currently in flight. */
 static size_t AIO_ReadPool_numReadsInFlight(ReadPoolCtx_t* ctx) {
-    const size_t jobsHeld = (ctx->currentJobHeld==NULL ? 0 : 1);
-    return ctx->base.totalIoJobs - (ctx->base.availableJobsCount + ctx->completedJobsCount + jobsHeld);
+    const int jobsHeld = (ctx->currentJobHeld==NULL ? 0 : 1);
+    return (size_t)(ctx->base.totalIoJobs - (ctx->base.availableJobsCount + ctx->completedJobsCount + jobsHeld));
 }
 
 /* AIO_ReadPool_getNextCompletedJob:
diff --git a/tests/playTests.sh b/tests/playTests.sh
index bdbd00142..0e07ebb19 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -91,7 +91,13 @@ fi
 SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
 PRGDIR="$SCRIPT_DIR/../programs"
 TESTDIR="$SCRIPT_DIR/../tests"
-UNAME=$(uname)
+UNAME=${UNAME:-$(uname)}
+GREP=${GREP:-grep}
+
+case "$UNAME" in
+  SunOS) DIFF=${DIFF:-gdiff} ;;
+  *) DIFF=${DIFF:-diff} ;;
+esac
 
 detectedTerminal=false
 if [ -t 0 ] && [ -t 1 ]
@@ -151,11 +157,6 @@ assertSamePermissions() {
     [ "$STAT1" = "$STAT2" ] || die "permissions on $1 don't match those on $2 ($STAT1 != $STAT2)"
 }
 
-DIFF="diff"
-case "$UNAME" in
-  SunOS) DIFF="gdiff" ;;
-esac
-
 
 # check if ZSTD_BIN is defined. if not, use the default value
 if [ -z "${ZSTD_BIN}" ]; then
@@ -177,7 +178,7 @@ fi
 [ -n "$DATAGEN_BIN" ] || die "datagen not found at $DATAGEN_BIN! \n Please define DATAGEN_BIN pointing to the datagen binary. You might also consider rebuilding zstd tests following the instructions in README.md. "
 println "\nStarting playTests.sh isWindows=$isWindows EXE_PREFIX='$EXE_PREFIX' ZSTD_BIN='$ZSTD_BIN' DATAGEN_BIN='$DATAGEN_BIN'"
 
-if echo hello | zstd -v -T2 2>&1 > $INTOVOID | grep -q 'multi-threading is disabled'
+if echo hello | zstd -v -T2 2>&1 > $INTOVOID | $GREP -q 'multi-threading is disabled'
 then
     hasMT=""
 else
@@ -253,8 +254,8 @@ println "test : null-length file roundtrip"
 println -n '' | zstd - --stdout | zstd -d --stdout
 println "test : ensure small file doesn't add 3-bytes null block"
 datagen -g1 > tmp1
-zstd tmp1 -c | wc -c | grep "14"
-zstd < tmp1  | wc -c | grep "14"
+zstd tmp1 -c | wc -c | $GREP "14"
+zstd < tmp1  | wc -c | $GREP "14"
 println "test : decompress file with wrong suffix (must fail)"
 zstd -d tmpCompressed && die "wrong suffix error not detected!"
 zstd -df tmp && die "should have refused : wrong extension"
@@ -291,9 +292,9 @@ println "test: --no-progress flag"
 zstd tmpro -c --no-progress | zstd -d -f -o "$INTOVOID" --no-progress
 zstd tmpro -cv --no-progress | zstd -dv -f -o "$INTOVOID" --no-progress
 println "test: --progress flag"
-zstd tmpro -c | zstd -d -f -o "$INTOVOID" --progress 2>&1 | grep -E "[A-Za-z0-9._ ]+: [0-9]+ bytes"
-zstd tmpro -c | zstd -d -f -q -o "$INTOVOID" --progress 2>&1 | grep -E "[A-Za-z0-9._ ]+: [0-9]+ bytes"
-zstd tmpro -c | zstd -d -f -v -o "$INTOVOID" 2>&1 | grep -E "[A-Za-z0-9._ ]+: [0-9]+ bytes"
+zstd tmpro -c | zstd -d -f -o "$INTOVOID" --progress 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
+zstd tmpro -c | zstd -d -f -q -o "$INTOVOID" --progress 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
+zstd tmpro -c | zstd -d -f -v -o "$INTOVOID" 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
 rm -f tmpro tmpro.zst
 println "test: overwrite input file (must fail)"
 zstd tmp -fo tmp && die "zstd compression overwrote the input file"
@@ -320,7 +321,7 @@ zstd -d -f tmp.zst --no-check
 if [ "$isWindows" = false ] && [ "$UNAME" != "AIX" ]; then
   if [ -n "$(which readelf)" ]; then
     println "test: check if binary has executable stack (#2963)"
-    readelf -lW "$ZSTD_BIN" | grep 'GNU_STACK .* RW ' || die "zstd binary has executable stack!"
+    readelf -lW "$ZSTD_BIN" | $GREP 'GNU_STACK .* RW ' || die "zstd binary has executable stack!"
   fi
 fi
 
@@ -413,9 +414,9 @@ zstd -q tmp tmp2 -o tmp3.zst --rm && die "should refuse to concatenate"
 println "test : should quietly not remove non-regular file"
 println hello > tmp
 zstd tmp -f -o "$DEVDEVICE" 2>tmplog > "$INTOVOID"
-grep "Refusing to remove non-regular file" tmplog && die
+$GREP "Refusing to remove non-regular file" tmplog && die
 rm -f tmplog
-zstd tmp -f -o "$INTOVOID" 2>&1 | grep "Refusing to remove non-regular file" && die
+zstd tmp -f -o "$INTOVOID" 2>&1 | $GREP "Refusing to remove non-regular file" && die
 println "test : --rm on stdin"
 println a | zstd --rm > $INTOVOID   # --rm should remain silent
 rm -f tmp
@@ -615,7 +616,7 @@ if [ -n "$DEVNULLRIGHTS" ] ; then
     zstd tmp -f -o tmp.zst
     sudoZstd -d tmp.zst -c > $INTOVOID
     sudoZstd -d tmp.zst -o $INTOVOID
-    ls -las $INTOVOID | grep "rw-rw-rw-"
+    ls -las $INTOVOID | $GREP "rw-rw-rw-"
 fi
 
 if [ -n "$READFROMBLOCKDEVICE" ] ; then
@@ -625,7 +626,7 @@ if [ -n "$READFROMBLOCKDEVICE" ] ; then
     println "\n===> checking that zstd can read from a block device"
     datagen -g65536 > tmp.img
     sudo losetup -fP tmp.img
-    LOOP_DEV=$(losetup -a | grep 'tmp\.img' | cut -f1 -d:)
+    LOOP_DEV=$(losetup -a | $GREP 'tmp\.img' | cut -f1 -d:)
     [ -z "$LOOP_DEV" ] && die "failed to get loopback device"
     sudoZstd $LOOP_DEV -c > tmp.img.zst && die "should fail without -f"
     sudoZstd -f $LOOP_DEV -c > tmp.img.zst
@@ -774,13 +775,13 @@ println "\n===> --[no-]content-size tests"
 
 datagen > tmp_contentsize
 zstd -f tmp_contentsize
-zstd -lv tmp_contentsize.zst | grep "Decompressed Size:"
+zstd -lv tmp_contentsize.zst | $GREP "Decompressed Size:"
 zstd -f --no-content-size tmp_contentsize
-zstd -lv tmp_contentsize.zst | grep "Decompressed Size:" && die
+zstd -lv tmp_contentsize.zst | $GREP "Decompressed Size:" && die
 zstd -f --content-size tmp_contentsize
-zstd -lv tmp_contentsize.zst | grep "Decompressed Size:"
+zstd -lv tmp_contentsize.zst | $GREP "Decompressed Size:"
 zstd -f --content-size --no-content-size tmp_contentsize
-zstd -lv tmp_contentsize.zst | grep "Decompressed Size:" && die
+zstd -lv tmp_contentsize.zst | $GREP "Decompressed Size:" && die
 rm -rf tmp*
 
 println "test : show-default-cparams regular"
@@ -800,8 +801,7 @@ rm -rf tmp*
 println "test : show compression parameters in verbose mode"
 datagen > tmp
 zstd -vv tmp 2>&1 | \
-grep -q -E -- "--zstd=wlog=[[:digit:]]+,clog=[[:digit:]]+,hlog=[[:digit:]]+,\
-slog=[[:digit:]]+,mml=[[:digit:]]+,tlen=[[:digit:]]+,strat=[[:digit:]]+"
+$GREP -q -- "--zstd=wlog=[0-9]\+,clog=[0-9]\+,hlog=[0-9]\+,slog=[0-9]\+,mml=[0-9]\+,tlen=[0-9]\+,strat=[0-9]\+"
 rm -rf tmp*
 
 println "\n===>  Advanced compression parameters "
@@ -1098,8 +1098,8 @@ println "- Test --memory for dictionary compression"
 datagen -g12M -P90 > tmpCorpusHighCompress
 zstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=10K && die "Dictionary training should fail : --memory too low (10K)"
 zstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=5MB 2> zstTrainWithMemLimitStdErr
-cat zstTrainWithMemLimitStdErr | grep "setting manual memory limit for dictionary training data at 5 MB"
-cat zstTrainWithMemLimitStdErr | grep "Training samples set too large (12 MB); training on 5 MB only..."
+cat zstTrainWithMemLimitStdErr | $GREP "setting manual memory limit for dictionary training data at 5 MB"
+cat zstTrainWithMemLimitStdErr | $GREP "Training samples set too large (12 MB); training on 5 MB only..."
 rm zstTrainWithMemLimitStdErr
 
 println "\n===>  fastCover dictionary builder : advanced options "
@@ -1385,16 +1385,16 @@ println "\n===> suffix list test"
 ! zstd -d tmp.abc 2> tmplg
 
 if [ $GZIPMODE -ne 1 ]; then
-    grep ".gz" tmplg > $INTOVOID && die "Unsupported suffix listed"
+    $GREP ".gz" tmplg > $INTOVOID && die "Unsupported suffix listed"
 fi
 
 if [ $LZMAMODE -ne 1 ]; then
-    grep ".lzma" tmplg > $INTOVOID && die "Unsupported suffix listed"
-    grep ".xz" tmplg > $INTOVOID && die "Unsupported suffix listed"
+    $GREP ".lzma" tmplg > $INTOVOID && die "Unsupported suffix listed"
+    $GREP ".xz" tmplg > $INTOVOID && die "Unsupported suffix listed"
 fi
 
 if [ $LZ4MODE -ne 1 ]; then
-    grep ".lz4" tmplg > $INTOVOID && die "Unsupported suffix listed"
+    $GREP ".lz4" tmplg > $INTOVOID && die "Unsupported suffix listed"
 fi
 
 touch tmp1
@@ -1523,7 +1523,7 @@ datagen > tmp2
 datagen > tmp3
 zstd tmp*
 zstd -l ./*.zst
-zstd -lv ./*.zst | grep "Decompressed Size:"  # check that decompressed size is present in header
+zstd -lv ./*.zst | $GREP "Decompressed Size:"  # check that decompressed size is present in header
 zstd --list ./*.zst
 zstd --list -v ./*.zst
 
@@ -1566,13 +1566,13 @@ datagen -g0 > tmp5
 zstd tmp5
 zstd -l tmp5.zst
 zstd -l tmp5* && die "-l must fail on non-zstd file"
-zstd -lv tmp5.zst | grep "Decompressed Size: 0 B (0 B)"  # check that 0 size is present in header
+zstd -lv tmp5.zst | $GREP "Decompressed Size: 0 B (0 B)"  # check that 0 size is present in header
 zstd -lv tmp5* && die "-l must fail on non-zstd file"
 
 println "\n===>  zstd --list/-l test with no content size field "
 datagen -g513K | zstd > tmp6.zst
 zstd -l tmp6.zst
-zstd -lv tmp6.zst | grep "Decompressed Size:"  && die "Field :Decompressed Size: should not be available in this compressed file"
+zstd -lv tmp6.zst | $GREP "Decompressed Size:"  && die "Field :Decompressed Size: should not be available in this compressed file"
 
 println "\n===>   zstd --list/-l test with no checksum "
 zstd -f --no-check tmp1
@@ -1723,7 +1723,7 @@ else
     datagen -g5000000 > tmp_dict
     datagen -g5000000 > tmp_patch
 fi
-zstd -15 --patch-from=tmp_dict tmp_patch 2>&1 | grep "long mode automatically triggered"
+zstd -15 --patch-from=tmp_dict tmp_patch 2>&1 | $GREP "long mode automatically triggered"
 rm -rf tmp*
 
 println "\n===> patch-from very large dictionary and file test"

From 81f444f4f92b561278552c00d1d764caea1cff05 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 16 Jan 2024 12:14:35 -0800
Subject: [PATCH 152/937] made playTests.sh more compatible with older versions
 of grep

replaced `\+` by `*`.
`\+` means `[1-N]`,
while `*` means `[0-N]`,
so it's not strictly equivalent
but `\+` happens to be badly supported on some flavors of grep,
and for the purpose of these tests, `*` is good enough.
---
 tests/playTests.sh | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/tests/playTests.sh b/tests/playTests.sh
index 0e07ebb19..bf5fba89b 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -1,6 +1,7 @@
 #!/bin/sh
 
-set -e
+set -e # exit immediately on error
+# set -x # print commands before execution (debug)
 
 unset ZSTD_CLEVEL
 unset ZSTD_NBTHREADS
@@ -292,9 +293,9 @@ println "test: --no-progress flag"
 zstd tmpro -c --no-progress | zstd -d -f -o "$INTOVOID" --no-progress
 zstd tmpro -cv --no-progress | zstd -dv -f -o "$INTOVOID" --no-progress
 println "test: --progress flag"
-zstd tmpro -c | zstd -d -f -o "$INTOVOID" --progress 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
-zstd tmpro -c | zstd -d -f -q -o "$INTOVOID" --progress 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
-zstd tmpro -c | zstd -d -f -v -o "$INTOVOID" 2>&1 | $GREP "[A-Za-z0-9._ ]\+: [0-9]\+ bytes"
+zstd tmpro -c | zstd -d -f -o "$INTOVOID" --progress 2>&1 | $GREP '[A-Za-z0-9._ ]*: [0-9]* bytes'
+zstd tmpro -c | zstd -d -f -q -o "$INTOVOID" --progress 2>&1 | $GREP '[A-Za-z0-9._ ]*: [0-9]* bytes'
+zstd tmpro -c | zstd -d -f -v -o "$INTOVOID" 2>&1 | $GREP '[A-Za-z0-9._ ]*: [0-9]* bytes'
 rm -f tmpro tmpro.zst
 println "test: overwrite input file (must fail)"
 zstd tmp -fo tmp && die "zstd compression overwrote the input file"
@@ -801,7 +802,7 @@ rm -rf tmp*
 println "test : show compression parameters in verbose mode"
 datagen > tmp
 zstd -vv tmp 2>&1 | \
-$GREP -q -- "--zstd=wlog=[0-9]\+,clog=[0-9]\+,hlog=[0-9]\+,slog=[0-9]\+,mml=[0-9]\+,tlen=[0-9]\+,strat=[0-9]\+"
+$GREP -q -- "--zstd=wlog=[0-9]*,clog=[0-9]*,hlog=[0-9]*,slog=[0-9]*,mml=[0-9]*,tlen=[0-9]*,strat=[0-9]*"
 rm -rf tmp*
 
 println "\n===>  Advanced compression parameters "

From ee2efb634eab104a2ec18ab6b2ce277bc159cbd0 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 22 Jan 2024 05:21:32 +0000
Subject: [PATCH 153/937] Bump actions/upload-artifact from 4.1.0 to 4.2.0

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.1.0 to 4.2.0.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/1eb3cb2b3e0f29609092a73eb033bb759a334595...694cdabd8bdb0f10b2cea11669e1bf5453eed0a6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/scorecards.yml        | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 2f3dd6a27..3fe5eb2f6 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -290,7 +290,7 @@ jobs:
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
+      uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 5b5175489..8d7d71b5f 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -51,7 +51,7 @@ jobs:
       # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
       # format to the repository Actions tab.
       - name: "Upload artifact"
-        uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
+        uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
         with:
           name: SARIF file
           path: results.sarif
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index 10bef46db..e0f3b7134 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@1eb3cb2b3e0f29609092a73eb033bb759a334595 # tag=v4.1.0
+      uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From c7611d6964d7012c24850c3a2cd3092f50f9d6ba Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 27 Jan 2024 15:37:29 -0800
Subject: [PATCH 154/937] disable Intel CET Compatibility tests

The binary blob that must be downloaded from intel.com is no longer available
---
 .github/workflows/dev-short-tests.yml | 45 ++++++++++++++-------------
 1 file changed, 24 insertions(+), 21 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 65e9ae655..911ba60cc 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -524,25 +524,6 @@ jobs:
         make -C tests fuzzer &&
         ./tests/fuzzer.exe -v -T1m
 
-  intel-cet-compatibility:
-    runs-on: ubuntu-latest
-    steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - name: Build Zstd
-      run: |
-        make -j zstd V=1
-        readelf -n zstd
-    - name: Get Intel SDE
-      run: |
-        curl -LO https://downloadmirror.intel.com/684899/sde-external-9.0.0-2021-11-07-lin.tar.xz
-        tar xJvf sde-external-9.0.0-2021-11-07-lin.tar.xz
-    - name: Configure Permissions
-      run: |
-        echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
-    - name: Run Under SDE
-      run: |
-        sde-external-9.0.0-2021-11-07-lin/sde -cet -cet-raise 0 -cet-endbr-exe -cet-stderr -cet-abort -- ./zstd -b3
-
   pkg-config:
     runs-on: ubuntu-latest
     container:
@@ -600,9 +581,9 @@ jobs:
         ./programs/zstd -b
 
 
-# For reference : icc tests
+# Failing tests, for reference
+
 # icc tests are currently failing on Github Actions, likely to issues during installation stage
-# To be fixed later
 #
 #  icc:
 #    name: icc-check
@@ -622,3 +603,25 @@ jobs:
 #    - name: make check
 #      run: |
 #        make CC=/opt/intel/oneapi/compiler/latest/linux/bin/intel64/icc check
+
+
+# intel-cet-compatibility tests are currently failing, during download stage
+#
+#  intel-cet-compatibility:
+#    runs-on: ubuntu-latest
+#    steps:
+#    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+#    - name: Build Zstd
+#      run: |
+#        make -j zstd V=1
+#        readelf -n zstd
+#    - name: Get Intel SDE
+#      run: |
+#        curl -LO https://downloadmirror.intel.com/684899/sde-external-9.0.0-2021-11-07-lin.tar.xz
+#        tar xJvf sde-external-9.0.0-2021-11-07-lin.tar.xz
+#    - name: Configure Permissions
+#      run: |
+#        echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
+#    - name: Run Under SDE
+#      run: |
+#        sde-external-9.0.0-2021-11-07-lin/sde -cet -cet-raise 0 -cet-endbr-exe -cet-stderr -cet-abort -- ./zstd -b3

From 2fc7248412db6c92086369fc3243f93f397cff4c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 27 Jan 2024 15:09:21 -0800
Subject: [PATCH 155/937] fix cmakebuild test

write it in a way which is more compatible with older versions of cmake (<3.13)

Also:
fix pzstd compilation (notably on macos)
---
 .github/workflows/dev-short-tests.yml    |  9 +++----
 .gitignore                               |  2 ++
 Makefile                                 | 32 +++++++++++++-----------
 build/cmake/contrib/pzstd/CMakeLists.txt |  1 +
 4 files changed, 24 insertions(+), 20 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 911ba60cc..593f37879 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -80,19 +80,16 @@ jobs:
         make clean
         LDFLAGS=-Wl,--no-undefined make -C lib libzstd-mt
 
-    # candidate test (to check) : underlink test
+    # candidate test (for discussion) : underlink test
     # LDFLAGS=-Wl,--no-undefined : will make the linker fail if dll is underlinked
 
   cmake-build-and-test-check:
     runs-on: ubuntu-latest
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - name: cmake build and test check
+    - name: cmake build and test
       run: |
-        FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild
-        cp -r ./ "../zstd source"
-        cd "../zstd source"
-        FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild
+        FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1
 
   cpp-gnu90-c99-compatibility:
     runs-on: ubuntu-latest
diff --git a/.gitignore b/.gitignore
index e95a8d07c..048a4c4e4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,8 @@ tmp*
 dictionary.
 dictionary
 NUL
+cmakebuild/
+install/
 
 # Build artefacts
 contrib/linux-kernel/linux/
diff --git a/Makefile b/Makefile
index 7bc7ec5bf..87d80d16d 100644
--- a/Makefile
+++ b/Makefile
@@ -145,7 +145,7 @@ clean:
 	$(Q)$(MAKE) -C contrib/largeNbDicts $@ > $(VOID)
 	$(Q)$(MAKE) -C contrib/externalSequenceProducer $@ > $(VOID)
 	$(Q)$(RM) zstd$(EXT) zstdmt$(EXT) tmp*
-	$(Q)$(RM) -r lz4
+	$(Q)$(RM) -r lz4 cmakebuild install
 	@echo Cleaning completed
 
 #------------------------------------------------------------------------------
@@ -389,28 +389,32 @@ lz4install:
 endif
 
 
-CMAKE_PARAMS = -DZSTD_BUILD_CONTRIB:BOOL=ON -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZLIB_SUPPORT:BOOL=ON -DZSTD_LZMA_SUPPORT:BOOL=ON -DCMAKE_BUILD_TYPE=Release
-
 ifneq (,$(filter MSYS%,$(shell uname)))
 HOST_OS = MSYS
-CMAKE_PARAMS = -G"MSYS Makefiles" -DCMAKE_BUILD_TYPE=Debug -DZSTD_MULTITHREAD_SUPPORT:BOOL=OFF -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON
 endif
 
 #------------------------------------------------------------------------
 # target specific tests
 #------------------------------------------------------------------------
 ifneq (,$(filter $(HOST_OS),MSYS POSIX))
-.PHONY: cmakebuild c89build gnu90build c99build gnu99build c11build bmix64build bmix32build bmi32build staticAnalyze
-cmakebuild:
-	cmake --version
-	$(RM) -r $(BUILDIR)/cmake/build
-	$(MKDIR) $(BUILDIR)/cmake/build
-	cd $(BUILDIR)/cmake/build; cmake -DCMAKE_INSTALL_PREFIX:PATH=~/install_test_dir $(CMAKE_PARAMS) ..
-	$(MAKE) -C $(BUILDIR)/cmake/build -j4;
-	$(MAKE) -C $(BUILDIR)/cmake/build install;
-	$(MAKE) -C $(BUILDIR)/cmake/build uninstall;
-	cd $(BUILDIR)/cmake/build; ctest -V -L Medium
 
+CMAKE ?= cmake
+CMAKE_PARAMS = -DZSTD_BUILD_CONTRIB:BOOL=ON -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZLIB_SUPPORT:BOOL=ON -DZSTD_LZMA_SUPPORT:BOOL=ON
+
+ifneq (,$(filter MSYS%,$(shell uname)))
+CMAKE_PARAMS = -G"MSYS Makefiles" -DZSTD_MULTITHREAD_SUPPORT:BOOL=OFF -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON
+endif
+
+.PHONY: cmakebuild
+cmakebuild:
+	$(CMAKE) --version
+	$(RM) -r cmakebuild install
+	$(MKDIR) cmakebuild install
+	cd cmakebuild; $(CMAKE) -Wdev -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="-Werror -O0" -DCMAKE_INSTALL_PREFIX=install $(CMAKE_PARAMS) ../build/cmake
+	$(CMAKE) --build cmakebuild --target install -- -j V=1
+	cd cmakebuild; ctest -V -L Medium
+
+.PHONY: c89build gnu90build c99build gnu99build c11build bmix64build bmix32build bmi32build staticAnalyze
 c89build: clean
 	$(CC) -v
 	CFLAGS="-std=c89 -Werror -Wno-attributes -Wpedantic -Wno-long-long -Wno-variadic-macros -O0" $(MAKE) lib zstd
diff --git a/build/cmake/contrib/pzstd/CMakeLists.txt b/build/cmake/contrib/pzstd/CMakeLists.txt
index f7098fa0f..e1c8e0672 100644
--- a/build/cmake/contrib/pzstd/CMakeLists.txt
+++ b/build/cmake/contrib/pzstd/CMakeLists.txt
@@ -18,6 +18,7 @@ set(PZSTD_DIR ${ZSTD_SOURCE_DIR}/contrib/pzstd)
 include_directories(${PROGRAMS_DIR} ${LIBRARY_DIR} ${LIBRARY_DIR}/common ${PZSTD_DIR})
 
 add_executable(pzstd ${PROGRAMS_DIR}/util.c ${PZSTD_DIR}/main.cpp ${PZSTD_DIR}/Options.cpp ${PZSTD_DIR}/Pzstd.cpp ${PZSTD_DIR}/SkippableFrame.cpp)
+target_compile_features(pzstd PRIVATE cxx_std_11)
 set_property(TARGET pzstd APPEND PROPERTY COMPILE_DEFINITIONS "NDEBUG")
 set_property(TARGET pzstd APPEND PROPERTY COMPILE_OPTIONS "-Wno-shadow")
 

From e1ef81a3ae94dad4aa846615fc6e2293b28f50e8 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 28 Jan 2024 20:25:04 -0800
Subject: [PATCH 156/937] add sparc64 compilation test

---
 .github/workflows/dev-short-tests.yml | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 593f37879..ace63b380 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -381,6 +381,7 @@ jobs:
           { name: S390X,    xcc_pkg: gcc-s390x-linux-gnu,       xcc: s390x-linux-gnu-gcc,       xemu_pkg: qemu-system-s390x,  xemu: qemu-s390x-static   },
           { name: MIPS,     xcc_pkg: gcc-mips-linux-gnu,        xcc: mips-linux-gnu-gcc,        xemu_pkg: qemu-system-mips,   xemu: qemu-mips-static    },
           { name: M68K,     xcc_pkg: gcc-m68k-linux-gnu,        xcc: m68k-linux-gnu-gcc,        xemu_pkg: qemu-system-m68k,   xemu: qemu-m68k-static    },
+          { name: SPARC,    xcc_pkg: gcc-sparc64-linux-gnu,     xcc: sparc64-linux-gnu-gcc,     xemu_pkg: qemu-system-sparc,  xemu: qemu-sparc64-static },
         ]
     env:                        # Set environment variables
       XCC: ${{ matrix.xcc }}
@@ -427,6 +428,10 @@ jobs:
       if: ${{ matrix.name == 'M68K' }}
       run: |
         LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check
+    - name: SPARC
+      if: ${{ matrix.name == 'SPARC' }}
+      run: |
+        LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check
 
   mingw-short-test:
     runs-on: windows-latest

From 163e9b66377126e1b498c40628660d59aababf9f Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 29 Jan 2024 05:53:39 +0000
Subject: [PATCH 157/937] Bump actions/upload-artifact from 4.2.0 to 4.3.0

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.2.0 to 4.3.0.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/694cdabd8bdb0f10b2cea11669e1bf5453eed0a6...26f96dfa697d77e81fd5907df203aa23a56210a8)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/scorecards.yml        | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 3fe5eb2f6..29db7316e 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -290,7 +290,7 @@ jobs:
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
+      uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 8d7d71b5f..770f9d4a3 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -51,7 +51,7 @@ jobs:
       # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
       # format to the repository Actions tab.
       - name: "Upload artifact"
-        uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
+        uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
         with:
           name: SARIF file
           path: results.sarif
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index e0f3b7134..b689bf560 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@694cdabd8bdb0f10b2cea11669e1bf5453eed0a6 # tag=v4.2.0
+      uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From c485b57bc73abfda9085650b4caaf013248e42dc Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 29 Jan 2024 05:53:45 +0000
Subject: [PATCH 158/937] Bump microsoft/setup-msbuild from 1.3.1 to 1.3.2

Bumps [microsoft/setup-msbuild](https://github.com/microsoft/setup-msbuild) from 1.3.1 to 1.3.2.
- [Release notes](https://github.com/microsoft/setup-msbuild/releases)
- [Changelog](https://github.com/microsoft/setup-msbuild/blob/main/building-release.md)
- [Commits](https://github.com/microsoft/setup-msbuild/compare/1ff57057b5cfdc39105cd07a01d78e9b0ea0c14c...031090342aeefe171e49f3820f3b52110c66e402)

---
updated-dependencies:
- dependency-name: microsoft/setup-msbuild
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-short-tests.yml | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 593f37879..b834ce2d7 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -271,7 +271,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@1ff57057b5cfdc39105cd07a01d78e9b0ea0c14c # tag=v1.3
+      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
     - name: Build
       working-directory: ${{env.GITHUB_WORKSPACE}}
       run: |
@@ -298,7 +298,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@1ff57057b5cfdc39105cd07a01d78e9b0ea0c14c # tag=v1.3
+      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
     - name: Build ${{matrix.name}}
       working-directory: ${{env.GITHUB_WORKSPACE}}
       # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference
@@ -480,7 +480,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@1ff57057b5cfdc39105cd07a01d78e9b0ea0c14c # tag=v1.3
+      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
     - name: Build and run tests
       working-directory: ${{env.GITHUB_WORKSPACE}}
       env:

From d0b7da30e26406c7ece2bf538a70410e80b9de9f Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 15:00:32 -0800
Subject: [PATCH 159/937] add a lorem ipsum generator

this generator replaces the statistical generator
for the general case when no statistic is requested.

Generated data features a compression level speed / ratio curve
which is more in line with expectation.
---
 programs/benchzstd.c |  17 ++--
 programs/benchzstd.h |  11 +--
 programs/lorem.c     | 207 +++++++++++++++++++++++++++++++++++++++++++
 programs/lorem.h     |  32 +++++++
 programs/zstdcli.c   |   4 +-
 5 files changed, 259 insertions(+), 12 deletions(-)
 create mode 100644 programs/lorem.c
 create mode 100644 programs/lorem.h

diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index 9bc3628ee..b3af4c332 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -32,12 +32,13 @@
 #include "benchfn.h"
 #include "../lib/common/mem.h"
 #ifndef ZSTD_STATIC_LINKING_ONLY
-#define ZSTD_STATIC_LINKING_ONLY
+# define ZSTD_STATIC_LINKING_ONLY
 #endif
 #include "../lib/zstd.h"
 #include "datagen.h"     /* RDG_genBuffer */
+#include "lorem.h"       /* LOREM_genBuffer */
 #ifndef XXH_INLINE_ALL
-#define XXH_INLINE_ALL
+# define XXH_INLINE_ALL
 #endif
 #include "../lib/common/xxhash.h"
 #include "benchzstd.h"
@@ -701,7 +702,8 @@ int BMK_syntheticTest(int cLevel, double compressibility,
                       const ZSTD_compressionParameters* compressionParams,
                       int displayLevel, const BMK_advancedParams_t* adv)
 {
-    char name[20] = {0};
+    char nameBuff[20] = {0};
+    const char* name = nameBuff;
     size_t const benchedSize = 10000000;
     void* srcBuffer;
     BMK_benchOutcome_t res;
@@ -719,10 +721,15 @@ int BMK_syntheticTest(int cLevel, double compressibility,
     }
 
     /* Fill input buffer */
-    RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
+    if (compressibility < 0.0) {
+        LOREM_genBuffer(srcBuffer, benchedSize, 0);
+        name = "Lorem ipsum";
+    } else {
+        RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
+        snprintf (nameBuff, sizeof(nameBuff), "Synthetic %2u%%", (unsigned)(compressibility*100));
+    }
 
     /* Bench */
-    snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));
     res = BMK_benchCLevel(srcBuffer, benchedSize,
                     &benchedSize /* ? */, 1 /* ? */,
                     cLevel, compressionParams,
diff --git a/programs/benchzstd.h b/programs/benchzstd.h
index f14a68192..cdb6101c2 100644
--- a/programs/benchzstd.h
+++ b/programs/benchzstd.h
@@ -126,11 +126,12 @@ int BMK_benchFilesAdvanced(
 
 /*! BMK_syntheticTest() -- called from zstdcli */
 /*  Generates a sample with datagen, using compressibility argument */
-/*  cLevel - compression level to benchmark, errors if invalid
- *  compressibility - determines compressibility of sample
- *  compressionParams - basic compression Parameters
- *  displayLevel - see benchFiles
- *  adv - see advanced_Params_t
+/* @cLevel - compression level to benchmark, errors if invalid
+ * @compressibility - determines compressibility of sample, range [0.0 - 1.0]
+ *        if @compressibility < 0.0, uses the lorem ipsum generator
+ * @compressionParams - basic compression Parameters
+ * @displayLevel - see benchFiles
+ * @adv - see advanced_Params_t
  * @return: 0 on success, !0 on error
  */
 int BMK_syntheticTest(int cLevel, double compressibility,
diff --git a/programs/lorem.c b/programs/lorem.c
new file mode 100644
index 000000000..59dd6da62
--- /dev/null
+++ b/programs/lorem.c
@@ -0,0 +1,207 @@
+/*
+ * 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.
+ */
+
+
+/* Implementation notes:
+ *
+ * This is a very simple lorem ipsum generator
+ * which features a static list of words
+ * and print them one after another randomly
+ * with a fake sentence / paragraph structure.
+ *
+ * The goal is to generate a printable text
+ * that can be used to fake a text compression scenario.
+ * The resulting compression / ratio curve of the lorem ipsum generator
+ * is more satisfying than the previous statistical generator,
+ * which was initially designed for entropy compression,
+ * and lacks a regularity more representative of text.
+ *
+ * The compression ratio achievable on the generated lorem ipsum
+ * is still a bit too good, presumably because the dictionary is too small.
+ * It would be possible to create some more complex scheme,
+ * notably by enlarging the dictionary with a word generator,
+ * and adding grammatical rules (composition) and syntax rules.
+ * But that's probably overkill for the intended goal.
+ */
+
+#include "lorem.h"
+#include   /* memcpy */
+#include   /* INT_MAX */
+#include 
+
+#define WORD_MAX_SIZE 20
+
+/* Define the word pool */
+static const char *words[] = {
+    "lorem",       "ipsum",      "dolor",      "sit",          "amet",
+    "consectetur", "adipiscing", "elit",       "sed",          "do",
+    "eiusmod",     "tempor",     "incididunt", "ut",           "labore",
+    "et",          "dolore",     "magna",      "aliqua",       "dis",
+    "lectus",      "vestibulum", "mattis",     "ullamcorper",  "velit",
+    "commodo",     "a",          "lacus",      "arcu",         "magnis",
+    "parturient",  "montes",     "nascetur",   "ridiculus",    "mus",
+    "mauris",      "nulla",      "malesuada",  "pellentesque", "eget",
+    "gravida",     "in",         "dictum",     "non",          "erat",
+    "nam",         "voluptat",   "maecenas",   "blandit",      "aliquam",
+    "etiam",       "enim",       "lobortis",   "scelerisque",  "fermentum",
+    "dui",         "faucibus",   "ornare",     "at",           "elementum",
+    "eu",          "facilisis",  "odio",       "morbi",        "quis",
+    "eros",        "donec",      "ac",         "orci",         "purus",
+    "turpis",      "cursus",     "leo",        "vel",          "porta"};
+
+/* simple distribution that favors small words :
+ * 1 letter : weight 3
+ * 2-3 letters : weight 2
+ * 4+ letters : weight 1
+ * This is expected to be a bit more difficult to compress */
+static const int distrib[] = {
+    0, 1, 2, 3, 3, 4, 5, 6, 7, 8,
+    8,9, 9, 10, 11, 12, 13, 13, 14, 15,
+    15, 16, 17, 18, 19, 19, 20, 21, 22, 23,
+    24, 25, 26, 26, 26, 27, 28, 29, 30, 31,
+    32, 33, 34, 34, 35, 36, 37, 38, 39, 40,
+    41, 41, 42, 43, 43, 44, 45, 45, 46, 47,
+    48, 49, 50, 51, 52, 53, 54, 55, 55, 56,
+    57, 58, 58, 59, 60, 60, 61, 62, 63, 64,
+    65, 66, 67, 67, 68, 69, 70, 71, 72, 72,
+    73, 73, 74 };
+static const unsigned distribCount = sizeof(distrib) / sizeof(distrib[0]);
+
+/* Note: this unit only works when invoked sequentially.
+ * No concurrent access is allowed */
+static char *g_ptr = NULL;
+static size_t g_nbChars = 0;
+static size_t g_maxChars = 10000000;
+static unsigned g_randRoot = 0;
+
+#define RDG_rotl32(x, r) ((x << r) | (x >> (32 - r)))
+static unsigned LOREM_rand(unsigned range) {
+  static const unsigned prime1 = 2654435761U;
+  static const unsigned prime2 = 2246822519U;
+  unsigned rand32 = g_randRoot;
+  rand32 *= prime1;
+  rand32 ^= prime2;
+  rand32 = RDG_rotl32(rand32, 13);
+  g_randRoot = rand32;
+  return (unsigned)(((unsigned long long)rand32 * range) >> 32);
+}
+
+static void writeLastCharacters(void) {
+  size_t lastChars = g_maxChars - g_nbChars;
+  assert(g_maxChars >= g_nbChars);
+  if (lastChars == 0)
+    return;
+  g_ptr[g_nbChars++] = '.';
+  if (lastChars > 2) {
+    memset(g_ptr + g_nbChars, ' ', lastChars - 2);
+  }
+  if (lastChars > 1) {
+    g_ptr[g_maxChars-1] = '\n';
+  }
+  g_nbChars = g_maxChars;
+}
+
+static void generateWord(const char *word, const char *separator, int upCase)
+{
+    size_t const len = strlen(word) + strlen(separator);
+    if (g_nbChars + len > g_maxChars) {
+        writeLastCharacters();
+        return;
+    }
+    memcpy(g_ptr + g_nbChars, word, strlen(word));
+    if (upCase) {
+        static const char toUp = 'A' - 'a';
+        g_ptr[g_nbChars] = (char)(g_ptr[g_nbChars] + toUp);
+    }
+    g_nbChars += strlen(word);
+    memcpy(g_ptr + g_nbChars, separator, strlen(separator));
+    g_nbChars += strlen(separator);
+}
+
+static int about(unsigned target) {
+  return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
+}
+
+/* Function to generate a random sentence */
+static void generateSentence(int nbWords) {
+  int commaPos = about(9);
+  int comma2 = commaPos + about(7);
+  int i;
+  for (i = 0; i < nbWords; i++) {
+    int const wordID = distrib[LOREM_rand(distribCount)];
+    const char *const word = words[wordID];
+    const char* sep = " ";
+    if (i == commaPos)
+      sep = ", ";
+    if (i == comma2)
+      sep = ", ";
+    if (i == nbWords - 1)
+      sep = ". ";
+    generateWord(word, sep, i==0);
+  }
+}
+
+static void generateParagraph(int nbSentences) {
+  int i;
+  for (i = 0; i < nbSentences; i++) {
+    int wordsPerSentence = about(8);
+    generateSentence(wordsPerSentence);
+  }
+  if (g_nbChars < g_maxChars) {
+    g_ptr[g_nbChars++] = '\n';
+  }
+  if (g_nbChars < g_maxChars) {
+    g_ptr[g_nbChars++] = '\n';
+  }
+}
+
+/* It's "common" for lorem ipsum generators to start with the same first
+ * pre-defined sentence */
+static void generateFirstSentence(void) {
+  int i;
+  for (i = 0; i < 18; i++) {
+    const char *word = words[i];
+    const char *separator = " ";
+    if (i == 4)
+      separator = ", ";
+    if (i == 7)
+      separator = ", ";
+    generateWord(word, separator, i==0);
+  }
+  generateWord(words[18], ". ", 0);
+}
+
+size_t LOREM_genBlock(void* buffer, size_t size,
+                      unsigned seed,
+                      int first, int fill)
+{
+  g_ptr = (char*)buffer;
+  assert(size < INT_MAX);
+  g_maxChars = size;
+  g_nbChars = 0;
+  g_randRoot = seed;
+  if (first) {
+    generateFirstSentence();
+  }
+  while (g_nbChars < g_maxChars) {
+    int sentencePerParagraph = about(7);
+    generateParagraph(sentencePerParagraph);
+    if (!fill)
+      break; /* only generate one paragraph in not-fill mode */
+  }
+  g_ptr = NULL;
+  return g_nbChars;
+}
+
+void LOREM_genBuffer(void* buffer, size_t size, unsigned seed)
+{
+  LOREM_genBlock(buffer, size, seed, 1, 1);
+}
+
diff --git a/programs/lorem.h b/programs/lorem.h
new file mode 100644
index 000000000..4a87f8748
--- /dev/null
+++ b/programs/lorem.h
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+/* lorem ipsum generator */
+
+#include    /* size_t */
+
+/*
+ * LOREM_genBuffer():
+ * Generate @size bytes of compressible data using lorem ipsum generator
+ * into provided @buffer.
+ */
+void LOREM_genBuffer(void* buffer, size_t size, unsigned seed);
+
+/*
+ * LOREM_genBlock():
+ * Similar to LOREM_genBuffer, with additional controls :
+ * - @first : generate the first sentence
+ * - @fill : fill the entire @buffer,
+ *           if ==0: generate one paragraph at most.
+ * @return : nb of bytes generated into @buffer.
+ */
+size_t LOREM_genBlock(void* buffer, size_t size,
+                      unsigned seed,
+                      int first, int fill);
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 3f0ae8bdd..dd21021b0 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -856,7 +856,7 @@ int main(int argCount, const char* argv[])
     ZSTD_paramSwitch_e useRowMatchFinder = ZSTD_ps_auto;
     FIO_compressionType_t cType = FIO_zstdCompression;
     unsigned nbWorkers = 0;
-    double compressibility = 0.5;
+    double compressibility = -1.0;  /* lorem ipsum generator */
     unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
     size_t blockSize = 0;
 
@@ -1280,7 +1280,7 @@ int main(int argCount, const char* argv[])
                     break;
 
                     /* unknown command */
-                default : 
+                default :
                     sprintf(shortArgument, "-%c", argument[0]);
                     badUsage(programName, shortArgument);
                     CLEAN_RETURN(1);

From a261375996c2301267ef6b00643e6efe92043d8a Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 15:18:27 -0800
Subject: [PATCH 160/937] fix paramgrill Makefile recipe

---
 tests/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tests/Makefile b/tests/Makefile
index c31e75005..6bf8b4a08 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -203,7 +203,7 @@ zstreamtest-dll : $(ZSTREAM_LOCAL_FILES)
 CLEAN += paramgrill
 paramgrill : DEBUGFLAGS =   # turn off debug for speed measurements
 paramgrill : LDLIBS += -lm
-paramgrill : $(ZSTD_FILES) $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(PRGDIR)/benchzstd.c $(PRGDIR)/datagen.c paramgrill.c
+paramgrill : $(ZSTD_FILES) $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(PRGDIR)/benchzstd.c $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c paramgrill.c
 
 CLEAN += datagen
 datagen : $(PRGDIR)/datagen.c datagencli.c

From 3ce4c6e046ed29ba4c0cb05fb48581edc52c1d3c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 15:24:42 -0800
Subject: [PATCH 161/937] fix Visual Studio solutions

note: we probably don't want to maintain VS2008 solution anymore.
Its successor VS2010 is > 10 years old,
which is more or less the limit after which we can stop supporting old compilers.
---
 build/VS2008/zstd/zstd.vcproj  | 4 ++++
 build/VS2010/zstd/zstd.vcxproj | 1 +
 2 files changed, 5 insertions(+)

diff --git a/build/VS2008/zstd/zstd.vcproj b/build/VS2008/zstd/zstd.vcproj
index 91f2bda53..de1501d20 100644
--- a/build/VS2008/zstd/zstd.vcproj
+++ b/build/VS2008/zstd/zstd.vcproj
@@ -356,6 +356,10 @@
 				RelativePath="..\..\..\programs\dibio.c"
 				>
 			
+			
+			
 			
diff --git a/build/VS2010/zstd/zstd.vcxproj b/build/VS2010/zstd/zstd.vcxproj
index 5e1bced6f..5a5237f0e 100644
--- a/build/VS2010/zstd/zstd.vcxproj
+++ b/build/VS2010/zstd/zstd.vcxproj
@@ -63,6 +63,7 @@
     
     
     
+    
     
     
   

From befcec17886479a22028b1d0b632fa15e31d5abc Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 15:45:16 -0800
Subject: [PATCH 162/937] fix cmake recipe

---
 build/cmake/programs/CMakeLists.txt | 7 +------
 build/cmake/tests/CMakeLists.txt    | 4 ++--
 2 files changed, 3 insertions(+), 8 deletions(-)

diff --git a/build/cmake/programs/CMakeLists.txt b/build/cmake/programs/CMakeLists.txt
index 6a8165866..5e239e32a 100644
--- a/build/cmake/programs/CMakeLists.txt
+++ b/build/cmake/programs/CMakeLists.txt
@@ -32,12 +32,7 @@ if (MSVC)
     set(PlatformDependResources ${MSVC_RESOURCE_DIR}/zstd.rc)
 endif ()
 
-set(ZSTD_PROGRAM_SRCS ${PROGRAMS_DIR}/zstdcli.c ${PROGRAMS_DIR}/util.c
-    ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/fileio.c
-    ${PROGRAMS_DIR}/fileio_asyncio.c ${PROGRAMS_DIR}/benchfn.c
-    ${PROGRAMS_DIR}/benchzstd.c ${PROGRAMS_DIR}/datagen.c
-    ${PROGRAMS_DIR}/dibio.c ${PROGRAMS_DIR}/zstdcli_trace.c
-    ${PlatformDependResources})
+file(GLOB ZSTD_PROGRAM_SRCS "${PROGRAMS_DIR}/*.c")
 if (MSVC AND ZSTD_PROGRAMS_LINK_SHARED)
     list(APPEND ZSTD_PROGRAM_SRCS ${LIBRARY_DIR}/common/pool.c ${LIBRARY_DIR}/common/threading.c)
 endif ()
diff --git a/build/cmake/tests/CMakeLists.txt b/build/cmake/tests/CMakeLists.txt
index 250f0508f..3226374a5 100644
--- a/build/cmake/tests/CMakeLists.txt
+++ b/build/cmake/tests/CMakeLists.txt
@@ -56,7 +56,7 @@ target_link_libraries(datagen libzstd_static)
 #
 # fullbench
 #
-add_executable(fullbench ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/benchfn.c ${PROGRAMS_DIR}/benchzstd.c ${TESTS_DIR}/fullbench.c)
+add_executable(fullbench ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/lorem.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${PROGRAMS_DIR}/benchfn.c ${PROGRAMS_DIR}/benchzstd.c ${TESTS_DIR}/fullbench.c)
 if (NOT MSVC)
     target_compile_options(fullbench PRIVATE "-Wno-deprecated-declarations")
 endif()
@@ -110,7 +110,7 @@ endif()
 # Label the "Medium" set of tests (see TESTING.md)
 set_property(TEST fuzzer zstreamtest playTests APPEND PROPERTY LABELS Medium)
 
-add_executable(paramgrill ${PROGRAMS_DIR}/benchfn.c ${PROGRAMS_DIR}/benchzstd.c ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${TESTS_DIR}/paramgrill.c)
+add_executable(paramgrill ${PROGRAMS_DIR}/benchfn.c ${PROGRAMS_DIR}/benchzstd.c ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/lorem.c ${PROGRAMS_DIR}/util.c ${PROGRAMS_DIR}/timefn.c ${TESTS_DIR}/paramgrill.c)
 if (UNIX)
     target_link_libraries(paramgrill libzstd_static m) #m is math library
 else()

From fd03971252d043bb9d3e065dc2361db6d40c87b6 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 15:50:21 -0800
Subject: [PATCH 163/937] blindfix meson recipe

note: absence of GLOB capability within meson makes its maintenance more painful.
---
 build/meson/programs/meson.build | 1 +
 build/meson/tests/meson.build    | 1 +
 2 files changed, 2 insertions(+)

diff --git a/build/meson/programs/meson.build b/build/meson/programs/meson.build
index 0b5a93056..e103a6295 100644
--- a/build/meson/programs/meson.build
+++ b/build/meson/programs/meson.build
@@ -18,6 +18,7 @@ zstd_programs_sources = [join_paths(zstd_rootdir, 'programs/zstdcli.c'),
   join_paths(zstd_rootdir, 'programs/benchfn.c'),
   join_paths(zstd_rootdir, 'programs/benchzstd.c'),
   join_paths(zstd_rootdir, 'programs/datagen.c'),
+  join_paths(zstd_rootdir, 'programs/lorem.c'),
   join_paths(zstd_rootdir, 'programs/dibio.c'),
   join_paths(zstd_rootdir, 'programs/zstdcli_trace.c')]
 
diff --git a/build/meson/tests/meson.build b/build/meson/tests/meson.build
index 2dd8d1067..03480d205 100644
--- a/build/meson/tests/meson.build
+++ b/build/meson/tests/meson.build
@@ -29,6 +29,7 @@ DECODECORPUS_TESTTIME = '-T30'
 test_includes = [ include_directories(join_paths(zstd_rootdir, 'programs')) ]
 
 testcommon_sources = [join_paths(zstd_rootdir, 'programs/datagen.c'),
+  join_paths(zstd_rootdir, 'programs/lorem.c'),
   join_paths(zstd_rootdir, 'programs/util.c'),
   join_paths(zstd_rootdir, 'programs/timefn.c'),
   join_paths(zstd_rootdir, 'programs/benchfn.c'),

From de10f56be2765e8375939b97bb27ad3e378f217f Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 29 Jan 2024 23:25:24 -0800
Subject: [PATCH 164/937] improve high compression ratio for file like #3793

this works great for 32-bit arrays,
notably the synthetic ones, with extreme regularity,
unfortunately, it's not universal,
and in some cases, it's a loss.
Crucially, on average, it's a loss on silesia.
The most negatively impacted file is x-ray.
It deserves an investigation before suggesting it as an evolution.
---
 lib/compress/zstd_opt.c | 54 +++++++++++++++++++++++++++++++----------
 1 file changed, 41 insertions(+), 13 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 68537e600..e16e5e4fb 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -566,7 +566,7 @@ void ZSTD_updateTree_internal(
     const BYTE* const base = ms->window.base;
     U32 const target = (U32)(ip - base);
     U32 idx = ms->nextToUpdate;
-    DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u  (dictMode:%u)",
+    DEBUGLOG(7, "ZSTD_updateTree_internal, from %u to %u  (dictMode:%u)",
                 idx, target, dictMode);
 
     while(idx < target) {
@@ -1069,6 +1069,10 @@ listStats(const U32* table, int lastEltID)
 
 #endif
 
+#define LIT_PRICE(_p) (int)ZSTD_rawLiteralsCost(_p, 1, optStatePtr, optLevel)
+#define LL_PRICE(_l) (int)ZSTD_litLengthPrice(_l, optStatePtr, optLevel)
+#define LL_INCPRICE(_l) (LL_PRICE(_l) - LL_PRICE(_l-1))
+
 FORCE_INLINE_TEMPLATE
 ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
 size_t
@@ -1122,7 +1126,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             U32 const ll0 = !litlen;
             U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);
             ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
-                                              (U32)(ip-istart), (U32)(iend - ip));
+                                              (U32)(ip-istart), (U32)(iend-ip));
             if (!nbMatches) { ip++; continue; }
 
             /* initialize opt[0] */
@@ -1134,7 +1138,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
              * in every price. We include the literal length to avoid negative
              * prices when we subtract the previous literal length.
              */
-            opt[0].price = (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel);
+            opt[0].price = LL_PRICE(litlen);
 
             /* large match -> immediate encoding */
             {   U32 const maxML = matches[nbMatches-1].len;
@@ -1155,11 +1159,12 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
 
             /* set prices for first matches starting position == 0 */
             assert(opt[0].price >= 0);
-            {   U32 const literalsPrice = (U32)opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
+            {   U32 const literalsPrice = (U32)opt[0].price + (U32)LL_PRICE(0);
                 U32 pos;
                 U32 matchNb;
                 for (pos = 1; pos < minMatch; pos++) {
                     opt[pos].price = ZSTD_MAX_PRICE;   /* mlen, litlen and price will be fixed during forward scanning */
+                    opt[pos].mlen = 0;
                 }
                 for (matchNb = 0; matchNb < nbMatches; matchNb++) {
                     U32 const offBase = matches[matchNb].off;
@@ -1173,7 +1178,9 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         opt[pos].off = offBase;
                         opt[pos].litlen = litlen;
                         opt[pos].price = (int)sequencePrice;
-                }   }
+                    }
+                    opt[pos].price = ZSTD_MAX_PRICE;
+                }
                 last_pos = pos-1;
             }
         }
@@ -1187,18 +1194,38 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             /* Fix current position with one literal if cheaper */
             {   U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
                 int const price = opt[cur-1].price
-                                + (int)ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)
-                                + (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)
-                                - (int)ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);
+                                + LIT_PRICE(ip+cur-1)
+                                + LL_INCPRICE(litlen);
                 assert(price < 1000000000); /* overflow check */
                 if (price <= opt[cur].price) {
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
                                 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
-                    opt[cur].mlen = 0;
-                    opt[cur].off = 0;
-                    opt[cur].litlen = litlen;
-                    opt[cur].price = price;
+                    if ( (optLevel == 2) /* additional check only for high modes */
+                      && (opt[cur].mlen > 0) /* interrupt a match */
+                      && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
+                    {
+                        /* check next position, in case it would be cheaper */
+                        int with1literal = opt[cur].price + LL_INCPRICE(1);
+                        int withMoreLiterals = price + LL_INCPRICE(litlen+1);
+                        DEBUGLOG(7, "But at next rPos %u : match+1lit %.2f vs %ulits %.2f",
+                                cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
+                        if (with1literal < withMoreLiterals) {
+                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) !!!", ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals));
+                            /* do not take this literal */
+                        } else {
+                            opt[cur].mlen = 0;
+                            opt[cur].off = 0;
+                            opt[cur].litlen = litlen;
+                            opt[cur].price = price;
+                        }
+                    } else {
+                        /* normal case: take the literal, it's expected to be cheaper */
+                        opt[cur].mlen = 0;
+                        opt[cur].off = 0;
+                        opt[cur].litlen = litlen;
+                        opt[cur].price = price;
+                    }
                 } else {
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),
@@ -1236,7 +1263,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             {   U32 const ll0 = (opt[cur].mlen != 0);
                 U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;
                 U32 const previousPrice = (U32)opt[cur].price;
-                U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
+                U32 const basePrice = previousPrice + (U32)LL_PRICE(0);
                 U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);
                 U32 matchNb;
 
@@ -1291,6 +1318,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                             if (optLevel==0) break;  /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
                         }
             }   }   }
+            opt[last_pos+1].price = ZSTD_MAX_PRICE;
         }  /* for (cur = 1; cur <= last_pos; cur++) */
 
         lastSequence = opt[last_pos];

From 4683667785c6248a20eba83dd192dc9baea70d84 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 31 Jan 2024 02:51:46 -0800
Subject: [PATCH 165/937] refactor optimal parser

store stretches as intermediate solution instead of sequences.
makes it possible to link a solution to a predecessor.
---
 lib/compress/zstd_compress.c           |   8 +-
 lib/compress/zstd_compress_internal.h  |  14 +-
 lib/compress/zstd_opt.c                | 194 +++++++++++++++----------
 lib/decompress/zstd_decompress_block.c |  17 ++-
 4 files changed, 137 insertions(+), 96 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index b4beff7a9..23c517d2b 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -1661,8 +1661,8 @@ ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
       + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32))
       + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32))
       + ZSTD_cwksp_aligned_alloc_size((1<strategy, useRowMatchFinder)
                                             ? ZSTD_cwksp_aligned_alloc_size(hSize)
                                             : 0;
@@ -2045,8 +2045,8 @@ ZSTD_reset_matchState(ZSTD_matchState_t* ms,
         ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
         ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
         ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
-        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_match_t));
-        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+1) * sizeof(ZSTD_optimal_t));
+        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+2) * sizeof(ZSTD_match_t));
+        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+2) * sizeof(ZSTD_optimal_t));
     }
 
     ms->cParams = *cParams;
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 60f22239e..ec34f2a77 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -159,11 +159,11 @@ typedef struct {
 UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0};
 
 typedef struct {
-    int price;
-    U32 off;
-    U32 mlen;
-    U32 litlen;
-    U32 rep[ZSTD_REP_NUM];
+    int price;  /* price from beginning of segment to this position */
+    U32 off;    /* offset of previous match */
+    U32 mlen;   /* length of previous match */
+    U32 litlen; /* nb of literals after previous match */
+    U32 rep[ZSTD_REP_NUM];  /* offset history after previous match */
 } ZSTD_optimal_t;
 
 typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
@@ -174,8 +174,8 @@ typedef struct {
     unsigned* litLengthFreq;     /* table of litLength statistics, of size (MaxLL+1) */
     unsigned* matchLengthFreq;   /* table of matchLength statistics, of size (MaxML+1) */
     unsigned* offCodeFreq;       /* table of offCode statistics, of size (MaxOff+1) */
-    ZSTD_match_t* matchTable;    /* list of found matches, of size ZSTD_OPT_NUM+1 */
-    ZSTD_optimal_t* priceTable;  /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */
+    ZSTD_match_t* matchTable;    /* list of found matches, of size ZSTD_OPT_NUM+2 */
+    ZSTD_optimal_t* priceTable;  /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+2 */
 
     U32  litSum;                 /* nb of literals */
     U32  litLengthSum;           /* nb of litLength codes */
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index e16e5e4fb..76f3ef054 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1047,11 +1047,6 @@ ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm,
 *  Optimal parser
 *********************************/
 
-static U32 ZSTD_totalLen(ZSTD_optimal_t sol)
-{
-    return sol.litlen + sol.mlen;
-}
-
 #if 0 /* debug */
 
 static void
@@ -1101,10 +1096,10 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
 
     ZSTD_optimal_t* const opt = optStatePtr->priceTable;
     ZSTD_match_t* const matches = optStatePtr->matchTable;
-    ZSTD_optimal_t lastSequence;
+    ZSTD_optimal_t lastStretch;
     ZSTD_optLdm_t optLdm;
 
-    ZSTD_memset(&lastSequence, 0, sizeof(ZSTD_optimal_t));
+    ZSTD_memset(&lastStretch, 0, sizeof(ZSTD_optimal_t));
 
     optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;
     optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;
@@ -1127,18 +1122,23 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);
             ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,
                                               (U32)(ip-istart), (U32)(iend-ip));
-            if (!nbMatches) { ip++; continue; }
+            if (!nbMatches) {
+                DEBUGLOG(8, "no match found at cPos %u", (unsigned)(ip-istart));
+                ip++;
+                continue;
+            }
 
             /* initialize opt[0] */
-            { U32 i ; for (i=0; i immediate encoding */
             {   U32 const maxML = matches[nbMatches-1].len;
@@ -1147,37 +1147,36 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                             nbMatches, maxML, maxOffBase, (U32)(ip-prefixStart));
 
                 if (maxML > sufficient_len) {
-                    lastSequence.litlen = litlen;
-                    lastSequence.mlen = maxML;
-                    lastSequence.off = maxOffBase;
-                    DEBUGLOG(6, "large match (%u>%u), immediate encoding",
+                    lastStretch.litlen = 0;
+                    lastStretch.mlen = maxML;
+                    lastStretch.off = maxOffBase;
+                    DEBUGLOG(6, "large match (%u>%u) => immediate encoding",
                                 maxML, sufficient_len);
                     cur = 0;
-                    last_pos = ZSTD_totalLen(lastSequence);
+                    last_pos = maxML;
                     goto _shortestPath;
             }   }
 
             /* set prices for first matches starting position == 0 */
             assert(opt[0].price >= 0);
-            {   U32 const literalsPrice = (U32)opt[0].price + (U32)LL_PRICE(0);
-                U32 pos;
+            {   U32 pos;
                 U32 matchNb;
                 for (pos = 1; pos < minMatch; pos++) {
-                    opt[pos].price = ZSTD_MAX_PRICE;   /* mlen, litlen and price will be fixed during forward scanning */
-                    opt[pos].mlen = 0;
+                    opt[pos].price = ZSTD_MAX_PRICE;
+                    /* will be updated later on at match check */
                 }
                 for (matchNb = 0; matchNb < nbMatches; matchNb++) {
                     U32 const offBase = matches[matchNb].off;
                     U32 const end = matches[matchNb].len;
                     for ( ; pos <= end ; pos++ ) {
-                        U32 const matchPrice = ZSTD_getMatchPrice(offBase, pos, optStatePtr, optLevel);
-                        U32 const sequencePrice = literalsPrice + matchPrice;
+                        int const matchPrice = (int)ZSTD_getMatchPrice(offBase, pos, optStatePtr, optLevel);
+                        int const sequencePrice = opt[0].price + matchPrice;
                         DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
-                                    pos, ZSTD_fCost((int)sequencePrice));
+                                    pos, ZSTD_fCost(sequencePrice));
                         opt[pos].mlen = pos;
                         opt[pos].off = offBase;
-                        opt[pos].litlen = litlen;
-                        opt[pos].price = (int)sequencePrice;
+                        opt[pos].litlen = 0; /* end of match */
+                        opt[pos].price = sequencePrice + LL_PRICE(0);
                     }
                     opt[pos].price = ZSTD_MAX_PRICE;
                 }
@@ -1192,7 +1191,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur);
 
             /* Fix current position with one literal if cheaper */
-            {   U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
+            {   U32 const litlen = opt[cur-1].litlen + 1;
                 int const price = opt[cur-1].price
                                 + LIT_PRICE(ip+cur-1)
                                 + LL_INCPRICE(litlen);
@@ -1201,7 +1200,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
                                 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
-                    if ( (optLevel == 2) /* additional check only for high modes */
+                    if ( 0 && (optLevel == 2) /* additional check only for high modes */
                       && (opt[cur].mlen > 0) /* interrupt a match */
                       && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
                     {
@@ -1214,15 +1213,15 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                             DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) !!!", ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals));
                             /* do not take this literal */
                         } else {
-                            opt[cur].mlen = 0;
-                            opt[cur].off = 0;
+                            opt[cur].mlen = opt[cur-1].mlen;
+                            opt[cur].off = opt[cur-1].off;
                             opt[cur].litlen = litlen;
                             opt[cur].price = price;
                         }
                     } else {
-                        /* normal case: take the literal, it's expected to be cheaper */
-                        opt[cur].mlen = 0;
-                        opt[cur].off = 0;
+                        /* normal case: take the literal, it's expected to be cheaper at position @cur */
+                        opt[cur].mlen = opt[cur-1].mlen;
+                        opt[cur].off = opt[cur-1].off;
                         opt[cur].litlen = litlen;
                         opt[cur].price = price;
                     }
@@ -1240,9 +1239,10 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
              */
             ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));
             assert(cur >= opt[cur].mlen);
-            if (opt[cur].mlen != 0) {
+            if (opt[cur].litlen == 0) {
+                /* just finished a match => alter offset history */
                 U32 const prev = cur - opt[cur].mlen;
-                repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0);
+                repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
                 ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));
             } else {
                 ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
@@ -1255,15 +1255,14 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
 
             if ( (optLevel==0) /*static_test*/
               && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
-                DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);
+                DEBUGLOG(7, "skip current position : next rPos(%u) price is cheaper", cur+1);
                 continue;  /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
             }
 
             assert(opt[cur].price >= 0);
-            {   U32 const ll0 = (opt[cur].mlen != 0);
-                U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;
-                U32 const previousPrice = (U32)opt[cur].price;
-                U32 const basePrice = previousPrice + (U32)LL_PRICE(0);
+            {   U32 const ll0 = (opt[cur].litlen == 0);
+                int const previousPrice = opt[cur].price;
+                int const basePrice = previousPrice + LL_PRICE(0);
                 U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);
                 U32 matchNb;
 
@@ -1275,18 +1274,16 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     continue;
                 }
 
-                {   U32 const maxML = matches[nbMatches-1].len;
-                    DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",
-                                inr-istart, cur, nbMatches, maxML);
+                {   U32 const longestML = matches[nbMatches-1].len;
+                    DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of longest ML=%u",
+                                inr-istart, cur, nbMatches, longestML);
 
-                    if ( (maxML > sufficient_len)
-                      || (cur + maxML >= ZSTD_OPT_NUM) ) {
-                        lastSequence.mlen = maxML;
-                        lastSequence.off = matches[nbMatches-1].off;
-                        lastSequence.litlen = litlen;
-                        cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0;  /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */
-                        last_pos = cur + ZSTD_totalLen(lastSequence);
-                        if (cur > ZSTD_OPT_NUM) cur = 0;   /* underflow => first match */
+                    if ( (longestML > sufficient_len)
+                      || (cur + longestML >= ZSTD_OPT_NUM) ) {
+                        lastStretch.mlen = longestML;
+                        lastStretch.off = matches[nbMatches-1].off;
+                        lastStretch.litlen = 0;
+                        last_pos = cur + longestML;
                         goto _shortestPath;
                 }   }
 
@@ -1298,11 +1295,11 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     U32 mlen;
 
                     DEBUGLOG(7, "testing match %u => offBase=%4u, mlen=%2u, llen=%2u",
-                                matchNb, matches[matchNb].off, lastML, litlen);
+                                matchNb, matches[matchNb].off, lastML, opt[cur].litlen);
 
                     for (mlen = lastML; mlen >= startML; mlen--) {  /* scan downward */
                         U32 const pos = cur + mlen;
-                        int const price = (int)basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
+                        int const price = basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
 
                         if ((pos > last_pos) || (price < opt[pos].price)) {
                             DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
@@ -1310,7 +1307,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                             while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; }   /* fill empty positions */
                             opt[pos].mlen = mlen;
                             opt[pos].off = offset;
-                            opt[pos].litlen = litlen;
+                            opt[pos].litlen = 0;
                             opt[pos].price = price;
                         } else {
                             DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
@@ -1321,41 +1318,77 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
             opt[last_pos+1].price = ZSTD_MAX_PRICE;
         }  /* for (cur = 1; cur <= last_pos; cur++) */
 
-        lastSequence = opt[last_pos];
-        cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0;  /* single sequence, and it starts before `ip` */
-        assert(cur < ZSTD_OPT_NUM);  /* control overflow*/
+        lastStretch = opt[last_pos];
+        assert(cur >= lastStretch.mlen);
+        cur = last_pos - lastStretch.mlen;
 
 _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
         assert(opt[0].mlen == 0);
+        assert(last_pos >= lastStretch.mlen);
+        assert(cur == last_pos - lastStretch.mlen);
+        assert(lastStretch.rep[0] != 0);
 
-        /* Set the next chunk's repcodes based on the repcodes of the beginning
-         * of the last match, and the last sequence. This avoids us having to
-         * update them while traversing the sequences.
-         */
-        if (lastSequence.mlen != 0) {
-            repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0);
-            ZSTD_memcpy(rep, &reps, sizeof(reps));
+        if (lastStretch.mlen==0) {
+            /* no solution : all matches have been converted into literals */
+            assert(lastStretch.litlen == (ip - anchor) + last_pos);
+            ip += last_pos;
+            continue;
+        }
+        assert(lastStretch.off > 0);
+
+        /* Update offset history */
+        if (lastStretch.litlen == 0) {
+            /* finishing on a match : update offset history */
+            repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastStretch.off, opt[cur].litlen==0);
+            ZSTD_memcpy(rep, &reps, sizeof(repcodes_t));
         } else {
-            ZSTD_memcpy(rep, opt[cur].rep, sizeof(repcodes_t));
+            ZSTD_memcpy(rep, lastStretch.rep, sizeof(repcodes_t));
+            assert(cur >= lastStretch.litlen);
+            cur -= lastStretch.litlen;
         }
 
-        {   U32 const storeEnd = cur + 1;
+        /* let's write the shortest path solution
+         * solution is stored in @opt,
+         * in reverse order,
+         * starting from @storeEnd (==cur+1)
+         * (effectively partially overwriting @opt).
+         * Content is changed too:
+         * - So far, @opt stored stretches, aka a match followed by literals
+         * - Now, it will store sequences, aka literals followed by a match
+         */
+        {   U32 const storeEnd = cur + 2;
             U32 storeStart = storeEnd;
-            U32 seqPos = cur;
+            U32 stretchPos = cur;
+            ZSTD_optimal_t nextStretch;
 
             DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
                         last_pos, cur); (void)last_pos;
             assert(storeEnd < ZSTD_OPT_NUM);
-            DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
-                        storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);
-            opt[storeEnd] = lastSequence;
-            while (seqPos > 0) {
-                U32 const backDist = ZSTD_totalLen(opt[seqPos]);
+            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;
+            }
+            while (1) {
+                nextStretch = opt[stretchPos];
+                opt[storeStart].litlen = nextStretch.litlen;
+                DEBUGLOG(6, "selected sequence (llen=%u,mlen=%u,ofc=%u)",
+                            opt[storeStart].litlen, opt[storeStart].mlen, opt[storeStart].off);
+                if (nextStretch.mlen == 0) {
+                    /* reaching beginning of segment */
+                    break;
+                }
                 storeStart--;
-                DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
-                            seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);
-                opt[storeStart] = opt[seqPos];
-                seqPos = (seqPos > backDist) ? seqPos - backDist : 0;
+                opt[storeStart] = nextStretch; /* note: litlen will be fixed */
+                assert(nextStretch.litlen + nextStretch.mlen <= stretchPos);
+                stretchPos -= nextStretch.litlen + nextStretch.mlen;
             }
 
             /* save sequences */
@@ -1381,6 +1414,9 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
                     anchor += advance;
                     ip = anchor;
             }   }
+            DEBUGLOG(7, "new offset history : %u, %u, %u", rep[0], rep[1], rep[2]);
+
+            /* update all costs */
             ZSTD_setBasePrices(optStatePtr, optLevel);
         }
     }   /* while (ip < ilimit) */
@@ -1476,7 +1512,7 @@ size_t ZSTD_compressBlock_btultra2(
      * Consequently, this can only work if no data has been previously loaded in tables,
      * aka, no dictionary, no prefix, no ldm preprocessing.
      * The compression ratio gain is generally small (~0.5% on first block),
-    ** the cost is 2x cpu time on first block. */
+     * the cost is 2x cpu time on first block. */
     assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
     if ( (ms->opt.litLengthSum==0)   /* first block */
       && (seqStore->sequences == seqStore->sequencesStart)  /* no ldm */
diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 11bf201bc..4be145732 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -1585,7 +1585,8 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
     /* last literal segment */
     if (dctx->litBufferLocation == ZSTD_split) {
         /* split hasn't been reached yet, first get dst then copy litExtraBuffer */
-        size_t const lastLLSize = litBufferEnd - litPtr;
+        size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
+        DEBUGLOG(6, "copy last literals from segment : %u", (U32)lastLLSize);
         RETURN_ERROR_IF(lastLLSize > (size_t)(oend - op), dstSize_tooSmall, "");
         if (op != NULL) {
             ZSTD_memmove(op, litPtr, lastLLSize);
@@ -1596,14 +1597,16 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx,
         dctx->litBufferLocation = ZSTD_not_in_dst;
     }
     /* copy last literals from internal buffer */
-    {   size_t const lastLLSize = litBufferEnd - litPtr;
+    {   size_t const lastLLSize = (size_t)(litBufferEnd - litPtr);
+        DEBUGLOG(6, "copy last literals from internal buffer : %u", (U32)lastLLSize);
         RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
         if (op != NULL) {
             ZSTD_memcpy(op, litPtr, lastLLSize);
             op += lastLLSize;
     }   }
 
-    return op-ostart;
+    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
+    return (size_t)(op - ostart);
 }
 
 FORCE_INLINE_TEMPLATE size_t
@@ -1673,14 +1676,16 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx,
     }
 
     /* last literal segment */
-    {   size_t const lastLLSize = litEnd - litPtr;
+    {   size_t const lastLLSize = (size_t)(litEnd - litPtr);
+        DEBUGLOG(6, "copy last literals : %u", (U32)lastLLSize);
         RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
         if (op != NULL) {
             ZSTD_memcpy(op, litPtr, lastLLSize);
             op += lastLLSize;
     }   }
 
-    return op-ostart;
+    DEBUGLOG(6, "decoded block of size %u bytes", (U32)(op - ostart));
+    return (size_t)(op - ostart);
 }
 
 static size_t
@@ -1878,7 +1883,7 @@ ZSTD_decompressSequencesLong_body(
         }
     }
 
-    return op-ostart;
+    return (size_t)(op - ostart);
 }
 
 static size_t

From 0166b2ba8083481df3ae68e3431a43f541d3c9bd Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 31 Jan 2024 11:12:57 -0800
Subject: [PATCH 166/937] modification: differentiate literal update at pos+1

helps when litlen==1 is cheaper than litlen==0

works great on pathological arr[u32] examples
but doesn't generalize well on other files.

silesia/x-ray is amoung the most negatively affected ones.
---
 lib/compress/zstd_opt.c | 52 +++++++++++++++++++++--------------------
 1 file changed, 27 insertions(+), 25 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 76f3ef054..d7fb191cc 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1200,8 +1200,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
                                 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
-                    if ( 0 && (optLevel == 2) /* additional check only for high modes */
-                      && (opt[cur].mlen > 0) /* interrupt a match */
+                    if ((optLevel == 2) /* additional check only for high modes */
+                      && (opt[cur].litlen == 0) /* interrupt a match */
                       && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
                     {
                         /* check next position, in case it would be cheaper */
@@ -1209,33 +1209,35 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         int withMoreLiterals = price + LL_INCPRICE(litlen+1);
                         DEBUGLOG(7, "But at next rPos %u : match+1lit %.2f vs %ulits %.2f",
                                 cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
-                        if (with1literal < withMoreLiterals) {
-                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) !!!", ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals));
-                            /* do not take this literal */
-                        } else {
-                            opt[cur].mlen = opt[cur-1].mlen;
-                            opt[cur].off = opt[cur-1].off;
-                            opt[cur].litlen = litlen;
-                            opt[cur].price = price;
+                        if ( (with1literal < withMoreLiterals)
+                          && (with1literal < opt[cur+1].price) ) {
+                            /* update offset history - before it disappears */
+                            U32 const prev = cur - opt[cur].mlen;
+                            repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
+                            assert(cur >= opt[cur].mlen);
+                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !",
+                                        ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals),
+                                        newReps.rep[0], newReps.rep[1], newReps.rep[2] );
+                            opt[cur+1] = opt[cur];  /* mlen & offbase */
+                            ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(repcodes_t));
+                            opt[cur+1].litlen = 1;
+                            opt[cur+1].price = with1literal;
+                            if (last_pos < cur+1) last_pos = cur+1;
                         }
-                    } else {
-                        /* normal case: take the literal, it's expected to be cheaper at position @cur */
-                        opt[cur].mlen = opt[cur-1].mlen;
-                        opt[cur].off = opt[cur-1].off;
-                        opt[cur].litlen = litlen;
-                        opt[cur].price = price;
                     }
+                    opt[cur].mlen = opt[cur-1].mlen;
+                    opt[cur].off = opt[cur-1].off;
+                    opt[cur].litlen = litlen;
+                    opt[cur].price = price;
+                    ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
                 } else {
-                    DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",
-                                inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),
-                                opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);
+                    DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f)",
+                                inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price));
                 }
             }
 
-            /* Set the repcodes of the current position. We must do it here
-             * because we rely on the repcodes of the 2nd to last sequence being
-             * correct to set the next chunks repcodes during the backward
-             * traversal.
+            /* Offset history is not updated during match comparison.
+             * Do it here, now that the match is selected and confirmed.
              */
             ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));
             assert(cur >= opt[cur].mlen);
@@ -1244,8 +1246,6 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                 U32 const prev = cur - opt[cur].mlen;
                 repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
                 ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));
-            } else {
-                ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
             }
 
             /* last match must start at a minimum distance of 8 from oend */
@@ -1514,6 +1514,7 @@ size_t ZSTD_compressBlock_btultra2(
      * The compression ratio gain is generally small (~0.5% on first block),
      * the cost is 2x cpu time on first block. */
     assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
+    //g_debuglevel = -g_debuglevel;
     if ( (ms->opt.litLengthSum==0)   /* first block */
       && (seqStore->sequences == seqStore->sequencesStart)  /* no ldm */
       && (ms->window.dictLimit == ms->window.lowLimit)   /* no dictionary */
@@ -1523,6 +1524,7 @@ size_t ZSTD_compressBlock_btultra2(
         ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
     }
 
+    //g_debuglevel = -g_debuglevel;
     return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
 }
 #endif

From 04a6c8cbe240495f2dcf7ab108bec327ef245813 Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Wed, 31 Jan 2024 11:07:15 -0500
Subject: [PATCH 167/937] Update Dependency in Intel CET Test; Re-Enable Test

Motivated by #3884.
---
 .github/workflows/dev-short-tests.yml | 41 +++++++++++++--------------
 1 file changed, 19 insertions(+), 22 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index b834ce2d7..020f8419e 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -577,6 +577,25 @@ jobs:
         make -C programs zstd-pgo
         ./programs/zstd -b
 
+  intel-cet-compatibility:
+    runs-on: ubuntu-latest
+    steps:
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - name: Build Zstd
+      run: |
+        make -j zstd V=1
+        readelf -n zstd
+    - name: Get Intel SDE
+      run: |
+        curl -LO https://downloadmirror.intel.com/813591/sde-external-9.33.0-2024-01-07-lin.tar.xz
+        tar xJvf sde-external-9.33.0-2024-01-07-lin.tar.xz
+    - name: Configure Permissions
+      run: |
+        echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
+    - name: Run Under SDE
+      run: |
+        sde-external-9.33.0-2024-01-07-lin/sde -cet -cet-raise 0 -cet-endbr-exe -cet-stderr -cet-abort -- ./zstd -b3
+
 
 # Failing tests, for reference
 
@@ -600,25 +619,3 @@ jobs:
 #    - name: make check
 #      run: |
 #        make CC=/opt/intel/oneapi/compiler/latest/linux/bin/intel64/icc check
-
-
-# intel-cet-compatibility tests are currently failing, during download stage
-#
-#  intel-cet-compatibility:
-#    runs-on: ubuntu-latest
-#    steps:
-#    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-#    - name: Build Zstd
-#      run: |
-#        make -j zstd V=1
-#        readelf -n zstd
-#    - name: Get Intel SDE
-#      run: |
-#        curl -LO https://downloadmirror.intel.com/684899/sde-external-9.0.0-2021-11-07-lin.tar.xz
-#        tar xJvf sde-external-9.0.0-2021-11-07-lin.tar.xz
-#    - name: Configure Permissions
-#      run: |
-#        echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
-#    - name: Run Under SDE
-#      run: |
-#        sde-external-9.0.0-2021-11-07-lin/sde -cet -cet-raise 0 -cet-endbr-exe -cet-stderr -cet-abort -- ./zstd -b3

From d31018e223691256aac9c426fcfbeec735a2d6ab Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 14:26:18 -0800
Subject: [PATCH 168/937] finally, a version that generalizes well

While it's not always strictly a win,
it's a win for files that see a noticeably compression ratio increase,
while it's a very small noise for other files.

Downside is, this patch is less efficient for 32-bit arrays of integer
than the previous patch which was introducing losses for other files,
but it's still a net improvement on this scenario.
---
 lib/compress/zstd_opt.c | 62 ++++++++++++++++++++++++-----------------
 1 file changed, 36 insertions(+), 26 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index d7fb191cc..2c4af2f06 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1178,9 +1178,10 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         opt[pos].litlen = 0; /* end of match */
                         opt[pos].price = sequencePrice + LL_PRICE(0);
                     }
-                    opt[pos].price = ZSTD_MAX_PRICE;
                 }
                 last_pos = pos-1;
+                opt[pos].price = ZSTD_MAX_PRICE;
+                opt[pos+1].price = ZSTD_MAX_PRICE;
             }
         }
 
@@ -1197,39 +1198,47 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                                 + LL_INCPRICE(litlen);
                 assert(price < 1000000000); /* overflow check */
                 if (price <= opt[cur].price) {
+                    ZSTD_optimal_t const prevMatch = opt[cur];
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
                                 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
-                    if ((optLevel == 2) /* additional check only for high modes */
-                      && (opt[cur].litlen == 0) /* interrupt a match */
-                      && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
-                    {
-                        /* check next position, in case it would be cheaper */
-                        int with1literal = opt[cur].price + LL_INCPRICE(1);
-                        int withMoreLiterals = price + LL_INCPRICE(litlen+1);
-                        DEBUGLOG(7, "But at next rPos %u : match+1lit %.2f vs %ulits %.2f",
-                                cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
-                        if ( (with1literal < withMoreLiterals)
-                          && (with1literal < opt[cur+1].price) ) {
-                            /* update offset history - before it disappears */
-                            U32 const prev = cur - opt[cur].mlen;
-                            repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0);
-                            assert(cur >= opt[cur].mlen);
-                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !",
-                                        ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals),
-                                        newReps.rep[0], newReps.rep[1], newReps.rep[2] );
-                            opt[cur+1] = opt[cur];  /* mlen & offbase */
-                            ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(repcodes_t));
-                            opt[cur+1].litlen = 1;
-                            opt[cur+1].price = with1literal;
-                            if (last_pos < cur+1) last_pos = cur+1;
-                        }
-                    }
                     opt[cur].mlen = opt[cur-1].mlen;
                     opt[cur].off = opt[cur-1].off;
                     opt[cur].litlen = litlen;
                     opt[cur].price = price;
                     ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
+                    if ((optLevel == 2) /* additional check only for high modes */
+                      && (prevMatch.litlen == 0) /* interrupt a match */
+                      && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
+                    {
+                        /* check next position, in case it would be cheaper */
+                        int with1literal = prevMatch.price + LIT_PRICE(ip+cur) + LL_INCPRICE(1);
+                        int withMoreLiterals = price + LIT_PRICE(ip+cur) + LL_INCPRICE(litlen+1);
+                        DEBUGLOG(7, "But at next rPos %u : match+1lit %.2f vs %ulits %.2f",
+                                cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
+                        if ( (with1literal < withMoreLiterals)
+                          && (with1literal < opt[cur+1].price) ) {
+                            /* update offset history - before it disappears */
+                            U32 const prev = cur - prevMatch.mlen;
+                            repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, prevMatch.off, opt[prev].litlen==0);
+                            assert(cur >= prevMatch.mlen);
+                            DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !",
+                                        ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals),
+                                        newReps.rep[0], newReps.rep[1], newReps.rep[2] );
+                            opt[cur+1] = prevMatch;  /* mlen & offbase */
+                            ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(repcodes_t));
+                            opt[cur+1].litlen = 1;
+                            opt[cur+1].price = with1literal;
+                            if (last_pos < cur+1) last_pos = cur+1;
+#if 0
+                            /* but, for following byte, get back to literal run */
+                            opt[cur+2] = opt[cur];
+                            opt[cur+2].litlen += 2;
+                            opt[cur+2].price += LIT_PRICE(ip+cur) + LIT_PRICE(ip+cur+1) + LL_INCPRICE(litlen+1) + LL_INCPRICE(litlen+2);
+                            if (last_pos < cur+2) last_pos = cur+2;
+#endif
+                        }
+                    }
                 } else {
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price));
@@ -1316,6 +1325,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         }
             }   }   }
             opt[last_pos+1].price = ZSTD_MAX_PRICE;
+            opt[last_pos+2].price = ZSTD_MAX_PRICE;
         }  /* for (cur = 1; cur <= last_pos; cur++) */
 
         lastStretch = opt[last_pos];

From 8168a451e58261baf9a53b0c1bcfdaff2ba0480d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 17:26:47 -0800
Subject: [PATCH 169/937] minor optimization, mostly for clarity

---
 lib/compress/zstd_opt.c | 19 ++++---------------
 1 file changed, 4 insertions(+), 15 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 2c4af2f06..bbf367b24 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1181,7 +1181,6 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                 }
                 last_pos = pos-1;
                 opt[pos].price = ZSTD_MAX_PRICE;
-                opt[pos+1].price = ZSTD_MAX_PRICE;
             }
         }
 
@@ -1202,19 +1201,17 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
                                 inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
                                 opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
-                    opt[cur].mlen = opt[cur-1].mlen;
-                    opt[cur].off = opt[cur-1].off;
+                    opt[cur] = opt[cur-1];
                     opt[cur].litlen = litlen;
                     opt[cur].price = price;
-                    ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));
                     if ((optLevel == 2) /* additional check only for high modes */
                       && (prevMatch.litlen == 0) /* interrupt a match */
-                      && (LL_INCPRICE(1) < 0) ) /* ll1 is cheaper than ll0 */
-                    {
+                      && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
+                    ) {
                         /* check next position, in case it would be cheaper */
                         int with1literal = prevMatch.price + LIT_PRICE(ip+cur) + LL_INCPRICE(1);
                         int withMoreLiterals = price + LIT_PRICE(ip+cur) + LL_INCPRICE(litlen+1);
-                        DEBUGLOG(7, "But at next rPos %u : match+1lit %.2f vs %ulits %.2f",
+                        DEBUGLOG(7, "then at next rPos %u : match+1lit %.2f vs %ulits %.2f",
                                 cur+1, ZSTD_fCost(with1literal), litlen+1, ZSTD_fCost(withMoreLiterals));
                         if ( (with1literal < withMoreLiterals)
                           && (with1literal < opt[cur+1].price) ) {
@@ -1230,13 +1227,6 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                             opt[cur+1].litlen = 1;
                             opt[cur+1].price = with1literal;
                             if (last_pos < cur+1) last_pos = cur+1;
-#if 0
-                            /* but, for following byte, get back to literal run */
-                            opt[cur+2] = opt[cur];
-                            opt[cur+2].litlen += 2;
-                            opt[cur+2].price += LIT_PRICE(ip+cur) + LIT_PRICE(ip+cur+1) + LL_INCPRICE(litlen+1) + LL_INCPRICE(litlen+2);
-                            if (last_pos < cur+2) last_pos = cur+2;
-#endif
                         }
                     }
                 } else {
@@ -1325,7 +1315,6 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         }
             }   }   }
             opt[last_pos+1].price = ZSTD_MAX_PRICE;
-            opt[last_pos+2].price = ZSTD_MAX_PRICE;
         }  /* for (cur = 1; cur <= last_pos; cur++) */
 
         lastStretch = opt[last_pos];

From e5af24c5fa82186d61ee1ed4dfe161d65a1c1a7d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 17:48:29 -0800
Subject: [PATCH 170/937] fixed wrong assert

---
 lib/compress/zstd_opt.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index bbf367b24..bcebfaa35 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1325,7 +1325,6 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
         assert(opt[0].mlen == 0);
         assert(last_pos >= lastStretch.mlen);
         assert(cur == last_pos - lastStretch.mlen);
-        assert(lastStretch.rep[0] != 0);
 
         if (lastStretch.mlen==0) {
             /* no solution : all matches have been converted into literals */

From 9ae3bf5ee2ea676594b84afc6a3a4edcc22a19bf Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 17:52:50 -0800
Subject: [PATCH 171/937] update compression results

good news: there are only improvements
---
 tests/regression/results.csv | 84 ++++++++++++++++++------------------
 1 file changed, 42 insertions(+), 42 deletions(-)

diff --git a/tests/regression/results.csv b/tests/regression/results.csv
index d072c0d85..6d398c0e7 100644
--- a/tests/regression/results.csv
+++ b/tests/regression/results.csv
@@ -11,10 +11,10 @@ silesia.tar,                        level 6,                            compress
 silesia.tar,                        level 7,                            compress simple,                    4579828
 silesia.tar,                        level 9,                            compress simple,                    4555448
 silesia.tar,                        level 13,                           compress simple,                    4502956
-silesia.tar,                        level 16,                           compress simple,                    4360546
-silesia.tar,                        level 19,                           compress simple,                    4265911
+silesia.tar,                        level 16,                           compress simple,                    4360529
+silesia.tar,                        level 19,                           compress simple,                    4261475
 silesia.tar,                        uncompressed literals,              compress simple,                    4854086
-silesia.tar,                        uncompressed literals optimal,      compress simple,                    4265911
+silesia.tar,                        uncompressed literals optimal,      compress simple,                    4261475
 silesia.tar,                        huffman literals,                   compress simple,                    6179047
 github.tar,                         level -5,                           compress simple,                    52115
 github.tar,                         level -3,                           compress simple,                    45678
@@ -45,8 +45,8 @@ silesia,                            level 6,                            compress
 silesia,                            level 7,                            compress cctx,                      4570271
 silesia,                            level 9,                            compress cctx,                      4545850
 silesia,                            level 13,                           compress cctx,                      4493990
-silesia,                            level 16,                           compress cctx,                      4360041
-silesia,                            level 19,                           compress cctx,                      4296055
+silesia,                            level 16,                           compress cctx,                      4359969
+silesia,                            level 19,                           compress cctx,                      4267082
 silesia,                            long distance mode,                 compress cctx,                      4842075
 silesia,                            multithreaded,                      compress cctx,                      4842075
 silesia,                            multithreaded long distance mode,   compress cctx,                      4842075
@@ -55,7 +55,7 @@ silesia,                            small hash log,                     compress
 silesia,                            small chain log,                    compress cctx,                      4912197
 silesia,                            explicit params,                    compress cctx,                      4794318
 silesia,                            uncompressed literals,              compress cctx,                      4842075
-silesia,                            uncompressed literals optimal,      compress cctx,                      4296055
+silesia,                            uncompressed literals optimal,      compress cctx,                      4267082
 silesia,                            huffman literals,                   compress cctx,                      6172202
 silesia,                            multithreaded with advanced params, compress cctx,                      4842075
 github,                             level -5,                           compress cctx,                      204407
@@ -109,8 +109,8 @@ silesia,                            level 6,                            zstdcli,
 silesia,                            level 7,                            zstdcli,                            4570319
 silesia,                            level 9,                            zstdcli,                            4545898
 silesia,                            level 13,                           zstdcli,                            4494038
-silesia,                            level 16,                           zstdcli,                            4360089
-silesia,                            level 19,                           zstdcli,                            4296103
+silesia,                            level 16,                           zstdcli,                            4360017
+silesia,                            level 19,                           zstdcli,                            4267130
 silesia,                            long distance mode,                 zstdcli,                            4833785
 silesia,                            multithreaded,                      zstdcli,                            4842123
 silesia,                            multithreaded long distance mode,   zstdcli,                            4833785
@@ -119,7 +119,7 @@ silesia,                            small hash log,                     zstdcli,
 silesia,                            small chain log,                    zstdcli,                            4912245
 silesia,                            explicit params,                    zstdcli,                            4795840
 silesia,                            uncompressed literals,              zstdcli,                            5120614
-silesia,                            uncompressed literals optimal,      zstdcli,                            4319566
+silesia,                            uncompressed literals optimal,      zstdcli,                            4317385
 silesia,                            huffman literals,                   zstdcli,                            5321417
 silesia,                            multithreaded with advanced params, zstdcli,                            5120614
 silesia.tar,                        level -5,                           zstdcli,                            6862049
@@ -134,8 +134,8 @@ silesia.tar,                        level 6,                            zstdcli,
 silesia.tar,                        level 7,                            zstdcli,                            4581791
 silesia.tar,                        level 9,                            zstdcli,                            4555452
 silesia.tar,                        level 13,                           zstdcli,                            4502960
-silesia.tar,                        level 16,                           zstdcli,                            4360550
-silesia.tar,                        level 19,                           zstdcli,                            4265915
+silesia.tar,                        level 16,                           zstdcli,                            4360533
+silesia.tar,                        level 19,                           zstdcli,                            4261479
 silesia.tar,                        no source size,                     zstdcli,                            4854160
 silesia.tar,                        long distance mode,                 zstdcli,                            4845745
 silesia.tar,                        multithreaded,                      zstdcli,                            4854164
@@ -145,7 +145,7 @@ silesia.tar,                        small hash log,                     zstdcli,
 silesia.tar,                        small chain log,                    zstdcli,                            4917022
 silesia.tar,                        explicit params,                    zstdcli,                            4821112
 silesia.tar,                        uncompressed literals,              zstdcli,                            5122571
-silesia.tar,                        uncompressed literals optimal,      zstdcli,                            4310145
+silesia.tar,                        uncompressed literals optimal,      zstdcli,                            4308929
 silesia.tar,                        huffman literals,                   zstdcli,                            5342074
 silesia.tar,                        multithreaded with advanced params, zstdcli,                            5122571
 github,                             level -5,                           zstdcli,                            206407
@@ -248,8 +248,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced one pass,                  4505658
 silesia,                            level 12 row 2,                     advanced one pass,                  4503429
 silesia,                            level 13,                           advanced one pass,                  4493990
-silesia,                            level 16,                           advanced one pass,                  4360041
-silesia,                            level 19,                           advanced one pass,                  4296055
+silesia,                            level 16,                           advanced one pass,                  4359969
+silesia,                            level 19,                           advanced one pass,                  4267082
 silesia,                            no source size,                     advanced one pass,                  4842075
 silesia,                            long distance mode,                 advanced one pass,                  4833710
 silesia,                            multithreaded,                      advanced one pass,                  4842075
@@ -259,7 +259,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced one pass,                  4912197
 silesia,                            explicit params,                    advanced one pass,                  4795840
 silesia,                            uncompressed literals,              advanced one pass,                  5120566
-silesia,                            uncompressed literals optimal,      advanced one pass,                  4319518
+silesia,                            uncompressed literals optimal,      advanced one pass,                  4317337
 silesia,                            huffman literals,                   advanced one pass,                  5321369
 silesia,                            multithreaded with advanced params, advanced one pass,                  5120566
 silesia.tar,                        level -5,                           advanced one pass,                  6861055
@@ -282,8 +282,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced one pass,                  4514517
 silesia.tar,                        level 12 row 2,                     advanced one pass,                  4514007
 silesia.tar,                        level 13,                           advanced one pass,                  4502956
-silesia.tar,                        level 16,                           advanced one pass,                  4360546
-silesia.tar,                        level 19,                           advanced one pass,                  4265911
+silesia.tar,                        level 16,                           advanced one pass,                  4360529
+silesia.tar,                        level 19,                           advanced one pass,                  4261475
 silesia.tar,                        no source size,                     advanced one pass,                  4854086
 silesia.tar,                        long distance mode,                 advanced one pass,                  4840452
 silesia.tar,                        multithreaded,                      advanced one pass,                  4854160
@@ -293,7 +293,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced one pass,                  4917041
 silesia.tar,                        explicit params,                    advanced one pass,                  4807274
 silesia.tar,                        uncompressed literals,              advanced one pass,                  5122473
-silesia.tar,                        uncompressed literals optimal,      advanced one pass,                  4310141
+silesia.tar,                        uncompressed literals optimal,      advanced one pass,                  4308925
 silesia.tar,                        huffman literals,                   advanced one pass,                  5341705
 silesia.tar,                        multithreaded with advanced params, advanced one pass,                  5122567
 github,                             level -5,                           advanced one pass,                  204407
@@ -566,8 +566,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced one pass small out,        4505658
 silesia,                            level 12 row 2,                     advanced one pass small out,        4503429
 silesia,                            level 13,                           advanced one pass small out,        4493990
-silesia,                            level 16,                           advanced one pass small out,        4360041
-silesia,                            level 19,                           advanced one pass small out,        4296055
+silesia,                            level 16,                           advanced one pass small out,        4359969
+silesia,                            level 19,                           advanced one pass small out,        4267082
 silesia,                            no source size,                     advanced one pass small out,        4842075
 silesia,                            long distance mode,                 advanced one pass small out,        4833710
 silesia,                            multithreaded,                      advanced one pass small out,        4842075
@@ -577,7 +577,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced one pass small out,        4912197
 silesia,                            explicit params,                    advanced one pass small out,        4795840
 silesia,                            uncompressed literals,              advanced one pass small out,        5120566
-silesia,                            uncompressed literals optimal,      advanced one pass small out,        4319518
+silesia,                            uncompressed literals optimal,      advanced one pass small out,        4317337
 silesia,                            huffman literals,                   advanced one pass small out,        5321369
 silesia,                            multithreaded with advanced params, advanced one pass small out,        5120566
 silesia.tar,                        level -5,                           advanced one pass small out,        6861055
@@ -600,8 +600,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced one pass small out,        4514517
 silesia.tar,                        level 12 row 2,                     advanced one pass small out,        4514007
 silesia.tar,                        level 13,                           advanced one pass small out,        4502956
-silesia.tar,                        level 16,                           advanced one pass small out,        4360546
-silesia.tar,                        level 19,                           advanced one pass small out,        4265911
+silesia.tar,                        level 16,                           advanced one pass small out,        4360529
+silesia.tar,                        level 19,                           advanced one pass small out,        4261475
 silesia.tar,                        no source size,                     advanced one pass small out,        4854086
 silesia.tar,                        long distance mode,                 advanced one pass small out,        4840452
 silesia.tar,                        multithreaded,                      advanced one pass small out,        4854160
@@ -611,7 +611,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced one pass small out,        4917041
 silesia.tar,                        explicit params,                    advanced one pass small out,        4807274
 silesia.tar,                        uncompressed literals,              advanced one pass small out,        5122473
-silesia.tar,                        uncompressed literals optimal,      advanced one pass small out,        4310141
+silesia.tar,                        uncompressed literals optimal,      advanced one pass small out,        4308925
 silesia.tar,                        huffman literals,                   advanced one pass small out,        5341705
 silesia.tar,                        multithreaded with advanced params, advanced one pass small out,        5122567
 github,                             level -5,                           advanced one pass small out,        204407
@@ -884,8 +884,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced streaming,                 4505658
 silesia,                            level 12 row 2,                     advanced streaming,                 4503429
 silesia,                            level 13,                           advanced streaming,                 4493990
-silesia,                            level 16,                           advanced streaming,                 4360041
-silesia,                            level 19,                           advanced streaming,                 4296055
+silesia,                            level 16,                           advanced streaming,                 4359969
+silesia,                            level 19,                           advanced streaming,                 4267082
 silesia,                            no source size,                     advanced streaming,                 4842039
 silesia,                            long distance mode,                 advanced streaming,                 4833710
 silesia,                            multithreaded,                      advanced streaming,                 4842075
@@ -895,7 +895,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced streaming,                 4912197
 silesia,                            explicit params,                    advanced streaming,                 4795857
 silesia,                            uncompressed literals,              advanced streaming,                 5120566
-silesia,                            uncompressed literals optimal,      advanced streaming,                 4319518
+silesia,                            uncompressed literals optimal,      advanced streaming,                 4317337
 silesia,                            huffman literals,                   advanced streaming,                 5321370
 silesia,                            multithreaded with advanced params, advanced streaming,                 5120566
 silesia.tar,                        level -5,                           advanced streaming,                 6856523
@@ -918,8 +918,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced streaming,                 4514514
 silesia.tar,                        level 12 row 2,                     advanced streaming,                 4514003
 silesia.tar,                        level 13,                           advanced streaming,                 4502956
-silesia.tar,                        level 16,                           advanced streaming,                 4360546
-silesia.tar,                        level 19,                           advanced streaming,                 4265911
+silesia.tar,                        level 16,                           advanced streaming,                 4360529
+silesia.tar,                        level 19,                           advanced streaming,                 4261475
 silesia.tar,                        no source size,                     advanced streaming,                 4859267
 silesia.tar,                        long distance mode,                 advanced streaming,                 4840452
 silesia.tar,                        multithreaded,                      advanced streaming,                 4854160
@@ -929,7 +929,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced streaming,                 4917021
 silesia.tar,                        explicit params,                    advanced streaming,                 4807288
 silesia.tar,                        uncompressed literals,              advanced streaming,                 5127423
-silesia.tar,                        uncompressed literals optimal,      advanced streaming,                 4310141
+silesia.tar,                        uncompressed literals optimal,      advanced streaming,                 4308925
 silesia.tar,                        huffman literals,                   advanced streaming,                 5341712
 silesia.tar,                        multithreaded with advanced params, advanced streaming,                 5122567
 github,                             level -5,                           advanced streaming,                 204407
@@ -1194,11 +1194,11 @@ silesia,                            level 6,                            old stre
 silesia,                            level 7,                            old streaming,                      4570271
 silesia,                            level 9,                            old streaming,                      4545850
 silesia,                            level 13,                           old streaming,                      4493990
-silesia,                            level 16,                           old streaming,                      4360041
-silesia,                            level 19,                           old streaming,                      4296055
+silesia,                            level 16,                           old streaming,                      4359969
+silesia,                            level 19,                           old streaming,                      4267082
 silesia,                            no source size,                     old streaming,                      4842039
 silesia,                            uncompressed literals,              old streaming,                      4842075
-silesia,                            uncompressed literals optimal,      old streaming,                      4296055
+silesia,                            uncompressed literals optimal,      old streaming,                      4267082
 silesia,                            huffman literals,                   old streaming,                      6172207
 silesia.tar,                        level -5,                           old streaming,                      6856523
 silesia.tar,                        level -3,                           old streaming,                      6505954
@@ -1212,11 +1212,11 @@ silesia.tar,                        level 6,                            old stre
 silesia.tar,                        level 7,                            old streaming,                      4579823
 silesia.tar,                        level 9,                            old streaming,                      4555445
 silesia.tar,                        level 13,                           old streaming,                      4502956
-silesia.tar,                        level 16,                           old streaming,                      4360546
-silesia.tar,                        level 19,                           old streaming,                      4265911
+silesia.tar,                        level 16,                           old streaming,                      4360529
+silesia.tar,                        level 19,                           old streaming,                      4261475
 silesia.tar,                        no source size,                     old streaming,                      4859267
 silesia.tar,                        uncompressed literals,              old streaming,                      4859271
-silesia.tar,                        uncompressed literals optimal,      old streaming,                      4265911
+silesia.tar,                        uncompressed literals optimal,      old streaming,                      4261475
 silesia.tar,                        huffman literals,                   old streaming,                      6179056
 github,                             level -5,                           old streaming,                      204407
 github,                             level -5 with dict,                 old streaming,                      45832
@@ -1296,8 +1296,8 @@ silesia,                            level 6,                            old stre
 silesia,                            level 7,                            old streaming advanced,             4570271
 silesia,                            level 9,                            old streaming advanced,             4545850
 silesia,                            level 13,                           old streaming advanced,             4493990
-silesia,                            level 16,                           old streaming advanced,             4360041
-silesia,                            level 19,                           old streaming advanced,             4296055
+silesia,                            level 16,                           old streaming advanced,             4359969
+silesia,                            level 19,                           old streaming advanced,             4267082
 silesia,                            no source size,                     old streaming advanced,             4842039
 silesia,                            long distance mode,                 old streaming advanced,             4842075
 silesia,                            multithreaded,                      old streaming advanced,             4842075
@@ -1307,7 +1307,7 @@ silesia,                            small hash log,                     old stre
 silesia,                            small chain log,                    old streaming advanced,             4912197
 silesia,                            explicit params,                    old streaming advanced,             4795857
 silesia,                            uncompressed literals,              old streaming advanced,             4842075
-silesia,                            uncompressed literals optimal,      old streaming advanced,             4296055
+silesia,                            uncompressed literals optimal,      old streaming advanced,             4267082
 silesia,                            huffman literals,                   old streaming advanced,             6172207
 silesia,                            multithreaded with advanced params, old streaming advanced,             4842075
 silesia.tar,                        level -5,                           old streaming advanced,             6856523
@@ -1322,8 +1322,8 @@ silesia.tar,                        level 6,                            old stre
 silesia.tar,                        level 7,                            old streaming advanced,             4579823
 silesia.tar,                        level 9,                            old streaming advanced,             4555445
 silesia.tar,                        level 13,                           old streaming advanced,             4502956
-silesia.tar,                        level 16,                           old streaming advanced,             4360546
-silesia.tar,                        level 19,                           old streaming advanced,             4265911
+silesia.tar,                        level 16,                           old streaming advanced,             4360529
+silesia.tar,                        level 19,                           old streaming advanced,             4261475
 silesia.tar,                        no source size,                     old streaming advanced,             4859267
 silesia.tar,                        long distance mode,                 old streaming advanced,             4859271
 silesia.tar,                        multithreaded,                      old streaming advanced,             4859271
@@ -1333,7 +1333,7 @@ silesia.tar,                        small hash log,                     old stre
 silesia.tar,                        small chain log,                    old streaming advanced,             4917021
 silesia.tar,                        explicit params,                    old streaming advanced,             4807288
 silesia.tar,                        uncompressed literals,              old streaming advanced,             4859271
-silesia.tar,                        uncompressed literals optimal,      old streaming advanced,             4265911
+silesia.tar,                        uncompressed literals optimal,      old streaming advanced,             4261475
 silesia.tar,                        huffman literals,                   old streaming advanced,             6179056
 silesia.tar,                        multithreaded with advanced params, old streaming advanced,             4859271
 github,                             level -5,                           old streaming advanced,             213265

From 5474edbe6016175453d09eca139566baefe0b97b Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 19:31:53 -0800
Subject: [PATCH 172/937] fixed wrong assert

by introducing ZSTD_OPT_SIZE
---
 lib/compress/zstd_compress.c          | 8 ++++----
 lib/compress/zstd_compress_internal.h | 5 +++--
 lib/compress/zstd_opt.c               | 2 +-
 3 files changed, 8 insertions(+), 7 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 23c517d2b..f8abbbbd9 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -1661,8 +1661,8 @@ ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
       + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32))
       + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32))
       + ZSTD_cwksp_aligned_alloc_size((1<strategy, useRowMatchFinder)
                                             ? ZSTD_cwksp_aligned_alloc_size(hSize)
                                             : 0;
@@ -2045,8 +2045,8 @@ ZSTD_reset_matchState(ZSTD_matchState_t* ms,
         ms->opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned));
         ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned));
         ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned));
-        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+2) * sizeof(ZSTD_match_t));
-        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, (ZSTD_OPT_NUM+2) * sizeof(ZSTD_optimal_t));
+        ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t));
+        ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t));
     }
 
     ms->cParams = *cParams;
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index ec34f2a77..dae8526d4 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -168,14 +168,15 @@ typedef struct {
 
 typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
 
+#define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+2)
 typedef struct {
     /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
     unsigned* litFreq;           /* table of literals statistics, of size 256 */
     unsigned* litLengthFreq;     /* table of litLength statistics, of size (MaxLL+1) */
     unsigned* matchLengthFreq;   /* table of matchLength statistics, of size (MaxML+1) */
     unsigned* offCodeFreq;       /* table of offCode statistics, of size (MaxOff+1) */
-    ZSTD_match_t* matchTable;    /* list of found matches, of size ZSTD_OPT_NUM+2 */
-    ZSTD_optimal_t* priceTable;  /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+2 */
+    ZSTD_match_t* matchTable;    /* list of found matches, of size ZSTD_OPT_SIZE */
+    ZSTD_optimal_t* priceTable;  /* All positions tracked by optimal parser, of size ZSTD_OPT_SIZE */
 
     U32  litSum;                 /* nb of literals */
     U32  litLengthSum;           /* nb of litLength codes */
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index bcebfaa35..eb8647062 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1361,7 +1361,7 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
 
             DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
                         last_pos, cur); (void)last_pos;
-            assert(storeEnd < ZSTD_OPT_NUM);
+            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) {

From 0ae21d8c3170741e4005c877d3c300a6034601ec Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 19:32:59 -0800
Subject: [PATCH 173/937] removed trace control

---
 lib/compress/zstd_opt.c | 2 --
 1 file changed, 2 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index eb8647062..04587e855 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1512,7 +1512,6 @@ size_t ZSTD_compressBlock_btultra2(
      * The compression ratio gain is generally small (~0.5% on first block),
      * the cost is 2x cpu time on first block. */
     assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
-    //g_debuglevel = -g_debuglevel;
     if ( (ms->opt.litLengthSum==0)   /* first block */
       && (seqStore->sequences == seqStore->sequencesStart)  /* no ldm */
       && (ms->window.dictLimit == ms->window.lowLimit)   /* no dictionary */
@@ -1522,7 +1521,6 @@ size_t ZSTD_compressBlock_btultra2(
         ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
     }
 
-    //g_debuglevel = -g_debuglevel;
     return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);
 }
 #endif

From fe2e2ad36d434d0989ca669d3a4f4d60f1cb907b Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 3 Feb 2024 19:57:38 -0800
Subject: [PATCH 174/937] use ZSTD_memcpy()

which can be redirected in Linux kernel mode
---
 lib/compress/zstd_opt.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 04587e855..20a30406a 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1138,7 +1138,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
              */
             opt[0].price = LL_PRICE(litlen);
             ZSTD_STATIC_ASSERT(sizeof(opt[0].rep[0]) == sizeof(rep[0]));
-            memcpy(&opt[0].rep, rep, sizeof(opt[0].rep));
+            ZSTD_memcpy(&opt[0].rep, rep, sizeof(opt[0].rep));
 
             /* large match -> immediate encoding */
             {   U32 const maxML = matches[nbMatches-1].len;

From 9fed5ef108d63ff25964574c2ec980e578b1adbc Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 5 Feb 2024 05:43:28 +0000
Subject: [PATCH 175/937] Bump microsoft/setup-msbuild from 1.3.2 to 2.0.0

Bumps [microsoft/setup-msbuild](https://github.com/microsoft/setup-msbuild) from 1.3.2 to 2.0.0.
- [Release notes](https://github.com/microsoft/setup-msbuild/releases)
- [Changelog](https://github.com/microsoft/setup-msbuild/blob/main/building-release.md)
- [Commits](https://github.com/microsoft/setup-msbuild/compare/031090342aeefe171e49f3820f3b52110c66e402...6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce)

---
updated-dependencies:
- dependency-name: microsoft/setup-msbuild
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-short-tests.yml | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 28bb70980..52e88dfee 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -271,7 +271,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
     - name: Build
       working-directory: ${{env.GITHUB_WORKSPACE}}
       run: |
@@ -298,7 +298,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
     - name: Build ${{matrix.name}}
       working-directory: ${{env.GITHUB_WORKSPACE}}
       # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference
@@ -485,7 +485,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@031090342aeefe171e49f3820f3b52110c66e402 # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
     - name: Build and run tests
       working-directory: ${{env.GITHUB_WORKSPACE}}
       env:

From 0d9fb5dc3394161097dc54642bd793e6de3f7593 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 4 Feb 2024 22:45:18 -0800
Subject: [PATCH 176/937] fix msbuild action version number

---
 .github/workflows/dev-short-tests.yml | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 52e88dfee..3123e129b 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -271,7 +271,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0
     - name: Build
       working-directory: ${{env.GITHUB_WORKSPACE}}
       run: |
@@ -298,7 +298,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0
     - name: Build ${{matrix.name}}
       working-directory: ${{env.GITHUB_WORKSPACE}}
       # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference
@@ -485,7 +485,7 @@ jobs:
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
     - name: Add MSBuild to PATH
-      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v1.3
+      uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0
     - name: Build and run tests
       working-directory: ${{env.GITHUB_WORKSPACE}}
       env:

From 641749fc0935b6905b2fcfaa362cedfc631f5960 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 5 Feb 2024 00:36:10 -0800
Subject: [PATCH 177/937] fix uasan dictionary_stream_round_trip fuzz test

---
 lib/compress/zstd_opt.c | 6 ++++--
 tests/Makefile          | 5 +++--
 2 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 20a30406a..eed331929 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -267,6 +267,7 @@ static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,
                                 const optState_t* const optPtr,
                                 int optLevel)
 {
+    DEBUGLOG(8, "ZSTD_rawLiteralsCost (%u literals)", litLength);
     if (litLength == 0) return 0;
 
     if (!ZSTD_compressedLiterals(optPtr))
@@ -1204,7 +1205,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     opt[cur] = opt[cur-1];
                     opt[cur].litlen = litlen;
                     opt[cur].price = price;
-                    if ((optLevel == 2) /* additional check only for high modes */
+                    if ( (optLevel == 2) /* additional check only for high modes */
                       && (prevMatch.litlen == 0) /* interrupt a match */
                       && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
                     ) {
@@ -1278,7 +1279,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                                 inr-istart, cur, nbMatches, longestML);
 
                     if ( (longestML > sufficient_len)
-                      || (cur + longestML >= ZSTD_OPT_NUM) ) {
+                      || (cur + longestML >= ZSTD_OPT_NUM)
+                      || (ip + cur + longestML >= iend) ) {
                         lastStretch.mlen = longestML;
                         lastStretch.off = matches[nbMatches-1].off;
                         lastStretch.litlen = 0;
diff --git a/tests/Makefile b/tests/Makefile
index c31e75005..2f33e1d0f 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -251,8 +251,9 @@ checkTag.o : $(ZSTDDIR)/zstd.h
 clean:
 	$(MAKE) -C $(ZSTDDIR) clean
 	$(MAKE) -C $(PRGDIR) clean
-	$(RM) -fR $(TESTARTEFACT)
-	$(RM) -rf tmp*  # some test directories are named tmp*
+	$(MAKE) -C fuzz clean
+	$(RM) -R $(TESTARTEFACT)
+	$(RM) -r tmp*  # some test directories are named tmp*
 	$(RM) $(CLEAN) core *.o *.tmp result* *.gcda dictionary *.zst \
         $(PRGDIR)/zstd$(EXT) $(PRGDIR)/zstd32$(EXT) \
         fullbench-dll$(EXT) fuzzer-dll$(EXT) zstreamtest-dll$(EXT)

From 6c35fb2e8cb826b70226856cd7442861037cca8a Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 5 Feb 2024 01:21:06 -0800
Subject: [PATCH 178/937] fix msan warnings

---
 Makefile                |  5 +++--
 lib/compress/zstd_opt.c | 14 ++++++++++----
 2 files changed, 13 insertions(+), 6 deletions(-)

diff --git a/Makefile b/Makefile
index 87d80d16d..11eca19ce 100644
--- a/Makefile
+++ b/Makefile
@@ -328,8 +328,9 @@ asan-%: clean
 msan: clean
 	$(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=memory -fno-omit-frame-pointer -Werror $(MOREFLAGS)" HAVE_LZMA=0   # datagen.c fails this test for no obvious reason
 
-msan-%: clean
-	LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=memory -fno-omit-frame-pointer -Werror $(MOREFLAGS)" FUZZER_FLAGS="--no-big-tests $(FUZZER_FLAGS)" $(MAKE) -C $(TESTDIR) HAVE_LZMA=0 $*
+msan-%:
+	$(MAKE) clean
+	LDFLAGS=-fuse-ld=gold MOREFLAGS="-g -fno-sanitize-recover=all -fsanitize=memory -fno-omit-frame-pointer -Werror $(MOREFLAGS)" FUZZER_FLAGS="--no-big-tests $(FUZZER_FLAGS)" $(MAKE) -j -C $(TESTDIR) HAVE_LZMA=0 $*
 
 asan32: clean
 	$(MAKE) -C $(TESTDIR) test32 CC=clang MOREFLAGS="-g -fsanitize=address $(MOREFLAGS)"
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index eed331929..25715eabb 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1164,7 +1164,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                 U32 matchNb;
                 for (pos = 1; pos < minMatch; pos++) {
                     opt[pos].price = ZSTD_MAX_PRICE;
-                    /* will be updated later on at match check */
+                    opt[pos].mlen = 0;
+                    opt[pos].litlen = litlen + pos;
                 }
                 for (matchNb = 0; matchNb < nbMatches; matchNb++) {
                     U32 const offBase = matches[matchNb].off;
@@ -1205,8 +1206,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     opt[cur] = opt[cur-1];
                     opt[cur].litlen = litlen;
                     opt[cur].price = price;
-                    if ( (optLevel == 2) /* additional check only for high modes */
-                      && (prevMatch.litlen == 0) /* interrupt a match */
+                    if ( (optLevel >= 1) /* additional check only for higher modes */
+                      && (prevMatch.litlen == 0) /* replace a match */
                       && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
                     ) {
                         /* check next position, in case it would be cheaper */
@@ -1305,7 +1306,12 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                         if ((pos > last_pos) || (price < opt[pos].price)) {
                             DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
                                         pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
-                            while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; }   /* fill empty positions */
+                            while (last_pos < pos) {
+                                /* fill empty positions, for future comparisons */
+                                last_pos++;
+                                opt[last_pos].price = ZSTD_MAX_PRICE;
+                                opt[last_pos].litlen = !0;  /* just needs to be != 0, to mean "not an end of match" */
+                            }
                             opt[pos].mlen = mlen;
                             opt[pos].off = offset;
                             opt[pos].litlen = 0;

From 887f5b62aea77ec26a1a693ff9d8e2b1eba3a2cd Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 5 Feb 2024 01:27:22 -0800
Subject: [PATCH 179/937] update compression results for regression tests

---
 tests/regression/results.csv | 264 +++++++++++++++++------------------
 1 file changed, 132 insertions(+), 132 deletions(-)

diff --git a/tests/regression/results.csv b/tests/regression/results.csv
index 6d398c0e7..fc3fbe7c7 100644
--- a/tests/regression/results.csv
+++ b/tests/regression/results.csv
@@ -11,10 +11,10 @@ silesia.tar,                        level 6,                            compress
 silesia.tar,                        level 7,                            compress simple,                    4579828
 silesia.tar,                        level 9,                            compress simple,                    4555448
 silesia.tar,                        level 13,                           compress simple,                    4502956
-silesia.tar,                        level 16,                           compress simple,                    4360529
-silesia.tar,                        level 19,                           compress simple,                    4261475
+silesia.tar,                        level 16,                           compress simple,                    4360385
+silesia.tar,                        level 19,                           compress simple,                    4260939
 silesia.tar,                        uncompressed literals,              compress simple,                    4854086
-silesia.tar,                        uncompressed literals optimal,      compress simple,                    4261475
+silesia.tar,                        uncompressed literals optimal,      compress simple,                    4260939
 silesia.tar,                        huffman literals,                   compress simple,                    6179047
 github.tar,                         level -5,                           compress simple,                    52115
 github.tar,                         level -3,                           compress simple,                    45678
@@ -29,9 +29,9 @@ github.tar,                         level 7,                            compress
 github.tar,                         level 9,                            compress simple,                    36723
 github.tar,                         level 13,                           compress simple,                    35501
 github.tar,                         level 16,                           compress simple,                    40466
-github.tar,                         level 19,                           compress simple,                    32276
+github.tar,                         level 19,                           compress simple,                    32262
 github.tar,                         uncompressed literals,              compress simple,                    38831
-github.tar,                         uncompressed literals optimal,      compress simple,                    32276
+github.tar,                         uncompressed literals optimal,      compress simple,                    32262
 github.tar,                         huffman literals,                   compress simple,                    42560
 silesia,                            level -5,                           compress cctx,                      6857372
 silesia,                            level -3,                           compress cctx,                      6503412
@@ -45,8 +45,8 @@ silesia,                            level 6,                            compress
 silesia,                            level 7,                            compress cctx,                      4570271
 silesia,                            level 9,                            compress cctx,                      4545850
 silesia,                            level 13,                           compress cctx,                      4493990
-silesia,                            level 16,                           compress cctx,                      4359969
-silesia,                            level 19,                           compress cctx,                      4267082
+silesia,                            level 16,                           compress cctx,                      4359652
+silesia,                            level 19,                           compress cctx,                      4266582
 silesia,                            long distance mode,                 compress cctx,                      4842075
 silesia,                            multithreaded,                      compress cctx,                      4842075
 silesia,                            multithreaded long distance mode,   compress cctx,                      4842075
@@ -55,7 +55,7 @@ silesia,                            small hash log,                     compress
 silesia,                            small chain log,                    compress cctx,                      4912197
 silesia,                            explicit params,                    compress cctx,                      4794318
 silesia,                            uncompressed literals,              compress cctx,                      4842075
-silesia,                            uncompressed literals optimal,      compress cctx,                      4267082
+silesia,                            uncompressed literals optimal,      compress cctx,                      4266582
 silesia,                            huffman literals,                   compress cctx,                      6172202
 silesia,                            multithreaded with advanced params, compress cctx,                      4842075
 github,                             level -5,                           compress cctx,                      204407
@@ -83,9 +83,9 @@ github,                             level 9 with dict,                  compress
 github,                             level 13,                           compress cctx,                      132878
 github,                             level 13 with dict,                 compress cctx,                      39948
 github,                             level 16,                           compress cctx,                      133209
-github,                             level 16 with dict,                 compress cctx,                      37568
+github,                             level 16 with dict,                 compress cctx,                      37892
 github,                             level 19,                           compress cctx,                      132879
-github,                             level 19 with dict,                 compress cctx,                      37567
+github,                             level 19 with dict,                 compress cctx,                      37906
 github,                             long distance mode,                 compress cctx,                      141069
 github,                             multithreaded,                      compress cctx,                      141069
 github,                             multithreaded long distance mode,   compress cctx,                      141069
@@ -109,8 +109,8 @@ silesia,                            level 6,                            zstdcli,
 silesia,                            level 7,                            zstdcli,                            4570319
 silesia,                            level 9,                            zstdcli,                            4545898
 silesia,                            level 13,                           zstdcli,                            4494038
-silesia,                            level 16,                           zstdcli,                            4360017
-silesia,                            level 19,                           zstdcli,                            4267130
+silesia,                            level 16,                           zstdcli,                            4359700
+silesia,                            level 19,                           zstdcli,                            4266630
 silesia,                            long distance mode,                 zstdcli,                            4833785
 silesia,                            multithreaded,                      zstdcli,                            4842123
 silesia,                            multithreaded long distance mode,   zstdcli,                            4833785
@@ -119,7 +119,7 @@ silesia,                            small hash log,                     zstdcli,
 silesia,                            small chain log,                    zstdcli,                            4912245
 silesia,                            explicit params,                    zstdcli,                            4795840
 silesia,                            uncompressed literals,              zstdcli,                            5120614
-silesia,                            uncompressed literals optimal,      zstdcli,                            4317385
+silesia,                            uncompressed literals optimal,      zstdcli,                            4316928
 silesia,                            huffman literals,                   zstdcli,                            5321417
 silesia,                            multithreaded with advanced params, zstdcli,                            5120614
 silesia.tar,                        level -5,                           zstdcli,                            6862049
@@ -134,8 +134,8 @@ silesia.tar,                        level 6,                            zstdcli,
 silesia.tar,                        level 7,                            zstdcli,                            4581791
 silesia.tar,                        level 9,                            zstdcli,                            4555452
 silesia.tar,                        level 13,                           zstdcli,                            4502960
-silesia.tar,                        level 16,                           zstdcli,                            4360533
-silesia.tar,                        level 19,                           zstdcli,                            4261479
+silesia.tar,                        level 16,                           zstdcli,                            4360389
+silesia.tar,                        level 19,                           zstdcli,                            4260943
 silesia.tar,                        no source size,                     zstdcli,                            4854160
 silesia.tar,                        long distance mode,                 zstdcli,                            4845745
 silesia.tar,                        multithreaded,                      zstdcli,                            4854164
@@ -145,7 +145,7 @@ silesia.tar,                        small hash log,                     zstdcli,
 silesia.tar,                        small chain log,                    zstdcli,                            4917022
 silesia.tar,                        explicit params,                    zstdcli,                            4821112
 silesia.tar,                        uncompressed literals,              zstdcli,                            5122571
-silesia.tar,                        uncompressed literals optimal,      zstdcli,                            4308929
+silesia.tar,                        uncompressed literals optimal,      zstdcli,                            4308455
 silesia.tar,                        huffman literals,                   zstdcli,                            5342074
 silesia.tar,                        multithreaded with advanced params, zstdcli,                            5122571
 github,                             level -5,                           zstdcli,                            206407
@@ -173,9 +173,9 @@ github,                             level 9 with dict,                  zstdcli,
 github,                             level 13,                           zstdcli,                            134878
 github,                             level 13 with dict,                 zstdcli,                            41900
 github,                             level 16,                           zstdcli,                            135209
-github,                             level 16 with dict,                 zstdcli,                            39577
+github,                             level 16 with dict,                 zstdcli,                            39902
 github,                             level 19,                           zstdcli,                            134879
-github,                             level 19 with dict,                 zstdcli,                            39576
+github,                             level 19 with dict,                 zstdcli,                            39916
 github,                             long distance mode,                 zstdcli,                            138332
 github,                             multithreaded,                      zstdcli,                            138332
 github,                             multithreaded long distance mode,   zstdcli,                            138332
@@ -212,9 +212,9 @@ github.tar,                         level 9 with dict,                  zstdcli,
 github.tar,                         level 13,                           zstdcli,                            35505
 github.tar,                         level 13 with dict,                 zstdcli,                            37134
 github.tar,                         level 16,                           zstdcli,                            40470
-github.tar,                         level 16 with dict,                 zstdcli,                            33378
-github.tar,                         level 19,                           zstdcli,                            32280
-github.tar,                         level 19 with dict,                 zstdcli,                            32716
+github.tar,                         level 16 with dict,                 zstdcli,                            33379
+github.tar,                         level 19,                           zstdcli,                            32266
+github.tar,                         level 19 with dict,                 zstdcli,                            32705
 github.tar,                         no source size,                     zstdcli,                            38832
 github.tar,                         no source size with dict,           zstdcli,                            38004
 github.tar,                         long distance mode,                 zstdcli,                            40236
@@ -225,7 +225,7 @@ github.tar,                         small hash log,                     zstdcli,
 github.tar,                         small chain log,                    zstdcli,                            41673
 github.tar,                         explicit params,                    zstdcli,                            41385
 github.tar,                         uncompressed literals,              zstdcli,                            41529
-github.tar,                         uncompressed literals optimal,      zstdcli,                            35401
+github.tar,                         uncompressed literals optimal,      zstdcli,                            35360
 github.tar,                         huffman literals,                   zstdcli,                            38857
 github.tar,                         multithreaded with advanced params, zstdcli,                            41529
 silesia,                            level -5,                           advanced one pass,                  6857372
@@ -248,8 +248,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced one pass,                  4505658
 silesia,                            level 12 row 2,                     advanced one pass,                  4503429
 silesia,                            level 13,                           advanced one pass,                  4493990
-silesia,                            level 16,                           advanced one pass,                  4359969
-silesia,                            level 19,                           advanced one pass,                  4267082
+silesia,                            level 16,                           advanced one pass,                  4359652
+silesia,                            level 19,                           advanced one pass,                  4266582
 silesia,                            no source size,                     advanced one pass,                  4842075
 silesia,                            long distance mode,                 advanced one pass,                  4833710
 silesia,                            multithreaded,                      advanced one pass,                  4842075
@@ -259,7 +259,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced one pass,                  4912197
 silesia,                            explicit params,                    advanced one pass,                  4795840
 silesia,                            uncompressed literals,              advanced one pass,                  5120566
-silesia,                            uncompressed literals optimal,      advanced one pass,                  4317337
+silesia,                            uncompressed literals optimal,      advanced one pass,                  4316880
 silesia,                            huffman literals,                   advanced one pass,                  5321369
 silesia,                            multithreaded with advanced params, advanced one pass,                  5120566
 silesia.tar,                        level -5,                           advanced one pass,                  6861055
@@ -282,8 +282,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced one pass,                  4514517
 silesia.tar,                        level 12 row 2,                     advanced one pass,                  4514007
 silesia.tar,                        level 13,                           advanced one pass,                  4502956
-silesia.tar,                        level 16,                           advanced one pass,                  4360529
-silesia.tar,                        level 19,                           advanced one pass,                  4261475
+silesia.tar,                        level 16,                           advanced one pass,                  4360385
+silesia.tar,                        level 19,                           advanced one pass,                  4260939
 silesia.tar,                        no source size,                     advanced one pass,                  4854086
 silesia.tar,                        long distance mode,                 advanced one pass,                  4840452
 silesia.tar,                        multithreaded,                      advanced one pass,                  4854160
@@ -293,7 +293,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced one pass,                  4917041
 silesia.tar,                        explicit params,                    advanced one pass,                  4807274
 silesia.tar,                        uncompressed literals,              advanced one pass,                  5122473
-silesia.tar,                        uncompressed literals optimal,      advanced one pass,                  4308925
+silesia.tar,                        uncompressed literals optimal,      advanced one pass,                  4308451
 silesia.tar,                        huffman literals,                   advanced one pass,                  5341705
 silesia.tar,                        multithreaded with advanced params, advanced one pass,                  5122567
 github,                             level -5,                           advanced one pass,                  204407
@@ -397,17 +397,17 @@ github,                             level 13 with dict dds,             advanced
 github,                             level 13 with dict copy,            advanced one pass,                  39948
 github,                             level 13 with dict load,            advanced one pass,                  42624
 github,                             level 16,                           advanced one pass,                  133209
-github,                             level 16 with dict,                 advanced one pass,                  37577
-github,                             level 16 with dict dms,             advanced one pass,                  37577
-github,                             level 16 with dict dds,             advanced one pass,                  37577
-github,                             level 16 with dict copy,            advanced one pass,                  37568
-github,                             level 16 with dict load,            advanced one pass,                  42338
+github,                             level 16 with dict,                 advanced one pass,                  37902
+github,                             level 16 with dict dms,             advanced one pass,                  37902
+github,                             level 16 with dict dds,             advanced one pass,                  37902
+github,                             level 16 with dict copy,            advanced one pass,                  37892
+github,                             level 16 with dict load,            advanced one pass,                  42402
 github,                             level 19,                           advanced one pass,                  132879
-github,                             level 19 with dict,                 advanced one pass,                  37576
-github,                             level 19 with dict dms,             advanced one pass,                  37576
-github,                             level 19 with dict dds,             advanced one pass,                  37576
-github,                             level 19 with dict copy,            advanced one pass,                  37567
-github,                             level 19 with dict load,            advanced one pass,                  39613
+github,                             level 19 with dict,                 advanced one pass,                  37916
+github,                             level 19 with dict dms,             advanced one pass,                  37916
+github,                             level 19 with dict dds,             advanced one pass,                  37916
+github,                             level 19 with dict copy,            advanced one pass,                  37906
+github,                             level 19 with dict load,            advanced one pass,                  39770
 github,                             no source size,                     advanced one pass,                  136332
 github,                             no source size with dict,           advanced one pass,                  41148
 github,                             long distance mode,                 advanced one pass,                  136332
@@ -522,17 +522,17 @@ github.tar,                         level 13 with dict dds,             advanced
 github.tar,                         level 13 with dict copy,            advanced one pass,                  37130
 github.tar,                         level 13 with dict load,            advanced one pass,                  36010
 github.tar,                         level 16,                           advanced one pass,                  40466
-github.tar,                         level 16 with dict,                 advanced one pass,                  33374
-github.tar,                         level 16 with dict dms,             advanced one pass,                  33206
-github.tar,                         level 16 with dict dds,             advanced one pass,                  33206
-github.tar,                         level 16 with dict copy,            advanced one pass,                  33374
+github.tar,                         level 16 with dict,                 advanced one pass,                  33375
+github.tar,                         level 16 with dict dms,             advanced one pass,                  33207
+github.tar,                         level 16 with dict dds,             advanced one pass,                  33207
+github.tar,                         level 16 with dict copy,            advanced one pass,                  33375
 github.tar,                         level 16 with dict load,            advanced one pass,                  39081
-github.tar,                         level 19,                           advanced one pass,                  32276
-github.tar,                         level 19 with dict,                 advanced one pass,                  32712
-github.tar,                         level 19 with dict dms,             advanced one pass,                  32555
-github.tar,                         level 19 with dict dds,             advanced one pass,                  32555
-github.tar,                         level 19 with dict copy,            advanced one pass,                  32712
-github.tar,                         level 19 with dict load,            advanced one pass,                  32479
+github.tar,                         level 19,                           advanced one pass,                  32262
+github.tar,                         level 19 with dict,                 advanced one pass,                  32701
+github.tar,                         level 19 with dict dms,             advanced one pass,                  32565
+github.tar,                         level 19 with dict dds,             advanced one pass,                  32565
+github.tar,                         level 19 with dict copy,            advanced one pass,                  32701
+github.tar,                         level 19 with dict load,            advanced one pass,                  32428
 github.tar,                         no source size,                     advanced one pass,                  38831
 github.tar,                         no source size with dict,           advanced one pass,                  37995
 github.tar,                         long distance mode,                 advanced one pass,                  40252
@@ -543,7 +543,7 @@ github.tar,                         small hash log,                     advanced
 github.tar,                         small chain log,                    advanced one pass,                  41669
 github.tar,                         explicit params,                    advanced one pass,                  41385
 github.tar,                         uncompressed literals,              advanced one pass,                  41525
-github.tar,                         uncompressed literals optimal,      advanced one pass,                  35397
+github.tar,                         uncompressed literals optimal,      advanced one pass,                  35356
 github.tar,                         huffman literals,                   advanced one pass,                  38853
 github.tar,                         multithreaded with advanced params, advanced one pass,                  41525
 silesia,                            level -5,                           advanced one pass small out,        6857372
@@ -566,8 +566,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced one pass small out,        4505658
 silesia,                            level 12 row 2,                     advanced one pass small out,        4503429
 silesia,                            level 13,                           advanced one pass small out,        4493990
-silesia,                            level 16,                           advanced one pass small out,        4359969
-silesia,                            level 19,                           advanced one pass small out,        4267082
+silesia,                            level 16,                           advanced one pass small out,        4359652
+silesia,                            level 19,                           advanced one pass small out,        4266582
 silesia,                            no source size,                     advanced one pass small out,        4842075
 silesia,                            long distance mode,                 advanced one pass small out,        4833710
 silesia,                            multithreaded,                      advanced one pass small out,        4842075
@@ -577,7 +577,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced one pass small out,        4912197
 silesia,                            explicit params,                    advanced one pass small out,        4795840
 silesia,                            uncompressed literals,              advanced one pass small out,        5120566
-silesia,                            uncompressed literals optimal,      advanced one pass small out,        4317337
+silesia,                            uncompressed literals optimal,      advanced one pass small out,        4316880
 silesia,                            huffman literals,                   advanced one pass small out,        5321369
 silesia,                            multithreaded with advanced params, advanced one pass small out,        5120566
 silesia.tar,                        level -5,                           advanced one pass small out,        6861055
@@ -600,8 +600,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced one pass small out,        4514517
 silesia.tar,                        level 12 row 2,                     advanced one pass small out,        4514007
 silesia.tar,                        level 13,                           advanced one pass small out,        4502956
-silesia.tar,                        level 16,                           advanced one pass small out,        4360529
-silesia.tar,                        level 19,                           advanced one pass small out,        4261475
+silesia.tar,                        level 16,                           advanced one pass small out,        4360385
+silesia.tar,                        level 19,                           advanced one pass small out,        4260939
 silesia.tar,                        no source size,                     advanced one pass small out,        4854086
 silesia.tar,                        long distance mode,                 advanced one pass small out,        4840452
 silesia.tar,                        multithreaded,                      advanced one pass small out,        4854160
@@ -611,7 +611,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced one pass small out,        4917041
 silesia.tar,                        explicit params,                    advanced one pass small out,        4807274
 silesia.tar,                        uncompressed literals,              advanced one pass small out,        5122473
-silesia.tar,                        uncompressed literals optimal,      advanced one pass small out,        4308925
+silesia.tar,                        uncompressed literals optimal,      advanced one pass small out,        4308451
 silesia.tar,                        huffman literals,                   advanced one pass small out,        5341705
 silesia.tar,                        multithreaded with advanced params, advanced one pass small out,        5122567
 github,                             level -5,                           advanced one pass small out,        204407
@@ -715,17 +715,17 @@ github,                             level 13 with dict dds,             advanced
 github,                             level 13 with dict copy,            advanced one pass small out,        39948
 github,                             level 13 with dict load,            advanced one pass small out,        42624
 github,                             level 16,                           advanced one pass small out,        133209
-github,                             level 16 with dict,                 advanced one pass small out,        37577
-github,                             level 16 with dict dms,             advanced one pass small out,        37577
-github,                             level 16 with dict dds,             advanced one pass small out,        37577
-github,                             level 16 with dict copy,            advanced one pass small out,        37568
-github,                             level 16 with dict load,            advanced one pass small out,        42338
+github,                             level 16 with dict,                 advanced one pass small out,        37902
+github,                             level 16 with dict dms,             advanced one pass small out,        37902
+github,                             level 16 with dict dds,             advanced one pass small out,        37902
+github,                             level 16 with dict copy,            advanced one pass small out,        37892
+github,                             level 16 with dict load,            advanced one pass small out,        42402
 github,                             level 19,                           advanced one pass small out,        132879
-github,                             level 19 with dict,                 advanced one pass small out,        37576
-github,                             level 19 with dict dms,             advanced one pass small out,        37576
-github,                             level 19 with dict dds,             advanced one pass small out,        37576
-github,                             level 19 with dict copy,            advanced one pass small out,        37567
-github,                             level 19 with dict load,            advanced one pass small out,        39613
+github,                             level 19 with dict,                 advanced one pass small out,        37916
+github,                             level 19 with dict dms,             advanced one pass small out,        37916
+github,                             level 19 with dict dds,             advanced one pass small out,        37916
+github,                             level 19 with dict copy,            advanced one pass small out,        37906
+github,                             level 19 with dict load,            advanced one pass small out,        39770
 github,                             no source size,                     advanced one pass small out,        136332
 github,                             no source size with dict,           advanced one pass small out,        41148
 github,                             long distance mode,                 advanced one pass small out,        136332
@@ -840,17 +840,17 @@ github.tar,                         level 13 with dict dds,             advanced
 github.tar,                         level 13 with dict copy,            advanced one pass small out,        37130
 github.tar,                         level 13 with dict load,            advanced one pass small out,        36010
 github.tar,                         level 16,                           advanced one pass small out,        40466
-github.tar,                         level 16 with dict,                 advanced one pass small out,        33374
-github.tar,                         level 16 with dict dms,             advanced one pass small out,        33206
-github.tar,                         level 16 with dict dds,             advanced one pass small out,        33206
-github.tar,                         level 16 with dict copy,            advanced one pass small out,        33374
+github.tar,                         level 16 with dict,                 advanced one pass small out,        33375
+github.tar,                         level 16 with dict dms,             advanced one pass small out,        33207
+github.tar,                         level 16 with dict dds,             advanced one pass small out,        33207
+github.tar,                         level 16 with dict copy,            advanced one pass small out,        33375
 github.tar,                         level 16 with dict load,            advanced one pass small out,        39081
-github.tar,                         level 19,                           advanced one pass small out,        32276
-github.tar,                         level 19 with dict,                 advanced one pass small out,        32712
-github.tar,                         level 19 with dict dms,             advanced one pass small out,        32555
-github.tar,                         level 19 with dict dds,             advanced one pass small out,        32555
-github.tar,                         level 19 with dict copy,            advanced one pass small out,        32712
-github.tar,                         level 19 with dict load,            advanced one pass small out,        32479
+github.tar,                         level 19,                           advanced one pass small out,        32262
+github.tar,                         level 19 with dict,                 advanced one pass small out,        32701
+github.tar,                         level 19 with dict dms,             advanced one pass small out,        32565
+github.tar,                         level 19 with dict dds,             advanced one pass small out,        32565
+github.tar,                         level 19 with dict copy,            advanced one pass small out,        32701
+github.tar,                         level 19 with dict load,            advanced one pass small out,        32428
 github.tar,                         no source size,                     advanced one pass small out,        38831
 github.tar,                         no source size with dict,           advanced one pass small out,        37995
 github.tar,                         long distance mode,                 advanced one pass small out,        40252
@@ -861,7 +861,7 @@ github.tar,                         small hash log,                     advanced
 github.tar,                         small chain log,                    advanced one pass small out,        41669
 github.tar,                         explicit params,                    advanced one pass small out,        41385
 github.tar,                         uncompressed literals,              advanced one pass small out,        41525
-github.tar,                         uncompressed literals optimal,      advanced one pass small out,        35397
+github.tar,                         uncompressed literals optimal,      advanced one pass small out,        35356
 github.tar,                         huffman literals,                   advanced one pass small out,        38853
 github.tar,                         multithreaded with advanced params, advanced one pass small out,        41525
 silesia,                            level -5,                           advanced streaming,                 6854744
@@ -884,8 +884,8 @@ silesia,                            level 11 row 2,                     advanced
 silesia,                            level 12 row 1,                     advanced streaming,                 4505658
 silesia,                            level 12 row 2,                     advanced streaming,                 4503429
 silesia,                            level 13,                           advanced streaming,                 4493990
-silesia,                            level 16,                           advanced streaming,                 4359969
-silesia,                            level 19,                           advanced streaming,                 4267082
+silesia,                            level 16,                           advanced streaming,                 4359652
+silesia,                            level 19,                           advanced streaming,                 4266582
 silesia,                            no source size,                     advanced streaming,                 4842039
 silesia,                            long distance mode,                 advanced streaming,                 4833710
 silesia,                            multithreaded,                      advanced streaming,                 4842075
@@ -895,7 +895,7 @@ silesia,                            small hash log,                     advanced
 silesia,                            small chain log,                    advanced streaming,                 4912197
 silesia,                            explicit params,                    advanced streaming,                 4795857
 silesia,                            uncompressed literals,              advanced streaming,                 5120566
-silesia,                            uncompressed literals optimal,      advanced streaming,                 4317337
+silesia,                            uncompressed literals optimal,      advanced streaming,                 4316880
 silesia,                            huffman literals,                   advanced streaming,                 5321370
 silesia,                            multithreaded with advanced params, advanced streaming,                 5120566
 silesia.tar,                        level -5,                           advanced streaming,                 6856523
@@ -918,8 +918,8 @@ silesia.tar,                        level 11 row 2,                     advanced
 silesia.tar,                        level 12 row 1,                     advanced streaming,                 4514514
 silesia.tar,                        level 12 row 2,                     advanced streaming,                 4514003
 silesia.tar,                        level 13,                           advanced streaming,                 4502956
-silesia.tar,                        level 16,                           advanced streaming,                 4360529
-silesia.tar,                        level 19,                           advanced streaming,                 4261475
+silesia.tar,                        level 16,                           advanced streaming,                 4360385
+silesia.tar,                        level 19,                           advanced streaming,                 4260939
 silesia.tar,                        no source size,                     advanced streaming,                 4859267
 silesia.tar,                        long distance mode,                 advanced streaming,                 4840452
 silesia.tar,                        multithreaded,                      advanced streaming,                 4854160
@@ -929,7 +929,7 @@ silesia.tar,                        small hash log,                     advanced
 silesia.tar,                        small chain log,                    advanced streaming,                 4917021
 silesia.tar,                        explicit params,                    advanced streaming,                 4807288
 silesia.tar,                        uncompressed literals,              advanced streaming,                 5127423
-silesia.tar,                        uncompressed literals optimal,      advanced streaming,                 4308925
+silesia.tar,                        uncompressed literals optimal,      advanced streaming,                 4308451
 silesia.tar,                        huffman literals,                   advanced streaming,                 5341712
 silesia.tar,                        multithreaded with advanced params, advanced streaming,                 5122567
 github,                             level -5,                           advanced streaming,                 204407
@@ -1033,17 +1033,17 @@ github,                             level 13 with dict dds,             advanced
 github,                             level 13 with dict copy,            advanced streaming,                 39948
 github,                             level 13 with dict load,            advanced streaming,                 42624
 github,                             level 16,                           advanced streaming,                 133209
-github,                             level 16 with dict,                 advanced streaming,                 37577
-github,                             level 16 with dict dms,             advanced streaming,                 37577
-github,                             level 16 with dict dds,             advanced streaming,                 37577
-github,                             level 16 with dict copy,            advanced streaming,                 37568
-github,                             level 16 with dict load,            advanced streaming,                 42338
+github,                             level 16 with dict,                 advanced streaming,                 37902
+github,                             level 16 with dict dms,             advanced streaming,                 37902
+github,                             level 16 with dict dds,             advanced streaming,                 37902
+github,                             level 16 with dict copy,            advanced streaming,                 37892
+github,                             level 16 with dict load,            advanced streaming,                 42402
 github,                             level 19,                           advanced streaming,                 132879
-github,                             level 19 with dict,                 advanced streaming,                 37576
-github,                             level 19 with dict dms,             advanced streaming,                 37576
-github,                             level 19 with dict dds,             advanced streaming,                 37576
-github,                             level 19 with dict copy,            advanced streaming,                 37567
-github,                             level 19 with dict load,            advanced streaming,                 39613
+github,                             level 19 with dict,                 advanced streaming,                 37916
+github,                             level 19 with dict dms,             advanced streaming,                 37916
+github,                             level 19 with dict dds,             advanced streaming,                 37916
+github,                             level 19 with dict copy,            advanced streaming,                 37906
+github,                             level 19 with dict load,            advanced streaming,                 39770
 github,                             no source size,                     advanced streaming,                 136332
 github,                             no source size with dict,           advanced streaming,                 41148
 github,                             long distance mode,                 advanced streaming,                 136332
@@ -1158,17 +1158,17 @@ github.tar,                         level 13 with dict dds,             advanced
 github.tar,                         level 13 with dict copy,            advanced streaming,                 37130
 github.tar,                         level 13 with dict load,            advanced streaming,                 36010
 github.tar,                         level 16,                           advanced streaming,                 40466
-github.tar,                         level 16 with dict,                 advanced streaming,                 33374
-github.tar,                         level 16 with dict dms,             advanced streaming,                 33206
-github.tar,                         level 16 with dict dds,             advanced streaming,                 33206
-github.tar,                         level 16 with dict copy,            advanced streaming,                 33374
+github.tar,                         level 16 with dict,                 advanced streaming,                 33375
+github.tar,                         level 16 with dict dms,             advanced streaming,                 33207
+github.tar,                         level 16 with dict dds,             advanced streaming,                 33207
+github.tar,                         level 16 with dict copy,            advanced streaming,                 33375
 github.tar,                         level 16 with dict load,            advanced streaming,                 39081
-github.tar,                         level 19,                           advanced streaming,                 32276
-github.tar,                         level 19 with dict,                 advanced streaming,                 32712
-github.tar,                         level 19 with dict dms,             advanced streaming,                 32555
-github.tar,                         level 19 with dict dds,             advanced streaming,                 32555
-github.tar,                         level 19 with dict copy,            advanced streaming,                 32712
-github.tar,                         level 19 with dict load,            advanced streaming,                 32479
+github.tar,                         level 19,                           advanced streaming,                 32262
+github.tar,                         level 19 with dict,                 advanced streaming,                 32701
+github.tar,                         level 19 with dict dms,             advanced streaming,                 32565
+github.tar,                         level 19 with dict dds,             advanced streaming,                 32565
+github.tar,                         level 19 with dict copy,            advanced streaming,                 32701
+github.tar,                         level 19 with dict load,            advanced streaming,                 32428
 github.tar,                         no source size,                     advanced streaming,                 38828
 github.tar,                         no source size with dict,           advanced streaming,                 38000
 github.tar,                         long distance mode,                 advanced streaming,                 40252
@@ -1179,7 +1179,7 @@ github.tar,                         small hash log,                     advanced
 github.tar,                         small chain log,                    advanced streaming,                 41669
 github.tar,                         explicit params,                    advanced streaming,                 41385
 github.tar,                         uncompressed literals,              advanced streaming,                 41525
-github.tar,                         uncompressed literals optimal,      advanced streaming,                 35397
+github.tar,                         uncompressed literals optimal,      advanced streaming,                 35356
 github.tar,                         huffman literals,                   advanced streaming,                 38853
 github.tar,                         multithreaded with advanced params, advanced streaming,                 41525
 silesia,                            level -5,                           old streaming,                      6854744
@@ -1194,11 +1194,11 @@ silesia,                            level 6,                            old stre
 silesia,                            level 7,                            old streaming,                      4570271
 silesia,                            level 9,                            old streaming,                      4545850
 silesia,                            level 13,                           old streaming,                      4493990
-silesia,                            level 16,                           old streaming,                      4359969
-silesia,                            level 19,                           old streaming,                      4267082
+silesia,                            level 16,                           old streaming,                      4359652
+silesia,                            level 19,                           old streaming,                      4266582
 silesia,                            no source size,                     old streaming,                      4842039
 silesia,                            uncompressed literals,              old streaming,                      4842075
-silesia,                            uncompressed literals optimal,      old streaming,                      4267082
+silesia,                            uncompressed literals optimal,      old streaming,                      4266582
 silesia,                            huffman literals,                   old streaming,                      6172207
 silesia.tar,                        level -5,                           old streaming,                      6856523
 silesia.tar,                        level -3,                           old streaming,                      6505954
@@ -1212,11 +1212,11 @@ silesia.tar,                        level 6,                            old stre
 silesia.tar,                        level 7,                            old streaming,                      4579823
 silesia.tar,                        level 9,                            old streaming,                      4555445
 silesia.tar,                        level 13,                           old streaming,                      4502956
-silesia.tar,                        level 16,                           old streaming,                      4360529
-silesia.tar,                        level 19,                           old streaming,                      4261475
+silesia.tar,                        level 16,                           old streaming,                      4360385
+silesia.tar,                        level 19,                           old streaming,                      4260939
 silesia.tar,                        no source size,                     old streaming,                      4859267
 silesia.tar,                        uncompressed literals,              old streaming,                      4859271
-silesia.tar,                        uncompressed literals optimal,      old streaming,                      4261475
+silesia.tar,                        uncompressed literals optimal,      old streaming,                      4260939
 silesia.tar,                        huffman literals,                   old streaming,                      6179056
 github,                             level -5,                           old streaming,                      204407
 github,                             level -5 with dict,                 old streaming,                      45832
@@ -1243,9 +1243,9 @@ github,                             level 9 with dict,                  old stre
 github,                             level 13,                           old streaming,                      132878
 github,                             level 13 with dict,                 old streaming,                      39900
 github,                             level 16,                           old streaming,                      133209
-github,                             level 16 with dict,                 old streaming,                      37577
+github,                             level 16 with dict,                 old streaming,                      37902
 github,                             level 19,                           old streaming,                      132879
-github,                             level 19 with dict,                 old streaming,                      37576
+github,                             level 19 with dict,                 old streaming,                      37916
 github,                             no source size,                     old streaming,                      140599
 github,                             no source size with dict,           old streaming,                      40654
 github,                             uncompressed literals,              old streaming,                      136332
@@ -1276,13 +1276,13 @@ github.tar,                         level 9 with dict,                  old stre
 github.tar,                         level 13,                           old streaming,                      35501
 github.tar,                         level 13 with dict,                 old streaming,                      37130
 github.tar,                         level 16,                           old streaming,                      40466
-github.tar,                         level 16 with dict,                 old streaming,                      33374
-github.tar,                         level 19,                           old streaming,                      32276
-github.tar,                         level 19 with dict,                 old streaming,                      32712
+github.tar,                         level 16 with dict,                 old streaming,                      33375
+github.tar,                         level 19,                           old streaming,                      32262
+github.tar,                         level 19 with dict,                 old streaming,                      32701
 github.tar,                         no source size,                     old streaming,                      38828
 github.tar,                         no source size with dict,           old streaming,                      38000
 github.tar,                         uncompressed literals,              old streaming,                      38831
-github.tar,                         uncompressed literals optimal,      old streaming,                      32276
+github.tar,                         uncompressed literals optimal,      old streaming,                      32262
 github.tar,                         huffman literals,                   old streaming,                      42560
 silesia,                            level -5,                           old streaming advanced,             6854744
 silesia,                            level -3,                           old streaming advanced,             6503319
@@ -1296,8 +1296,8 @@ silesia,                            level 6,                            old stre
 silesia,                            level 7,                            old streaming advanced,             4570271
 silesia,                            level 9,                            old streaming advanced,             4545850
 silesia,                            level 13,                           old streaming advanced,             4493990
-silesia,                            level 16,                           old streaming advanced,             4359969
-silesia,                            level 19,                           old streaming advanced,             4267082
+silesia,                            level 16,                           old streaming advanced,             4359652
+silesia,                            level 19,                           old streaming advanced,             4266582
 silesia,                            no source size,                     old streaming advanced,             4842039
 silesia,                            long distance mode,                 old streaming advanced,             4842075
 silesia,                            multithreaded,                      old streaming advanced,             4842075
@@ -1307,7 +1307,7 @@ silesia,                            small hash log,                     old stre
 silesia,                            small chain log,                    old streaming advanced,             4912197
 silesia,                            explicit params,                    old streaming advanced,             4795857
 silesia,                            uncompressed literals,              old streaming advanced,             4842075
-silesia,                            uncompressed literals optimal,      old streaming advanced,             4267082
+silesia,                            uncompressed literals optimal,      old streaming advanced,             4266582
 silesia,                            huffman literals,                   old streaming advanced,             6172207
 silesia,                            multithreaded with advanced params, old streaming advanced,             4842075
 silesia.tar,                        level -5,                           old streaming advanced,             6856523
@@ -1322,8 +1322,8 @@ silesia.tar,                        level 6,                            old stre
 silesia.tar,                        level 7,                            old streaming advanced,             4579823
 silesia.tar,                        level 9,                            old streaming advanced,             4555445
 silesia.tar,                        level 13,                           old streaming advanced,             4502956
-silesia.tar,                        level 16,                           old streaming advanced,             4360529
-silesia.tar,                        level 19,                           old streaming advanced,             4261475
+silesia.tar,                        level 16,                           old streaming advanced,             4360385
+silesia.tar,                        level 19,                           old streaming advanced,             4260939
 silesia.tar,                        no source size,                     old streaming advanced,             4859267
 silesia.tar,                        long distance mode,                 old streaming advanced,             4859271
 silesia.tar,                        multithreaded,                      old streaming advanced,             4859271
@@ -1333,7 +1333,7 @@ silesia.tar,                        small hash log,                     old stre
 silesia.tar,                        small chain log,                    old streaming advanced,             4917021
 silesia.tar,                        explicit params,                    old streaming advanced,             4807288
 silesia.tar,                        uncompressed literals,              old streaming advanced,             4859271
-silesia.tar,                        uncompressed literals optimal,      old streaming advanced,             4261475
+silesia.tar,                        uncompressed literals optimal,      old streaming advanced,             4260939
 silesia.tar,                        huffman literals,                   old streaming advanced,             6179056
 silesia.tar,                        multithreaded with advanced params, old streaming advanced,             4859271
 github,                             level -5,                           old streaming advanced,             213265
@@ -1361,9 +1361,9 @@ github,                             level 9 with dict,                  old stre
 github,                             level 13,                           old streaming advanced,             138676
 github,                             level 13 with dict,                 old streaming advanced,             39725
 github,                             level 16,                           old streaming advanced,             138575
-github,                             level 16 with dict,                 old streaming advanced,             40789
+github,                             level 16 with dict,                 old streaming advanced,             40804
 github,                             level 19,                           old streaming advanced,             132879
-github,                             level 19 with dict,                 old streaming advanced,             37576
+github,                             level 19 with dict,                 old streaming advanced,             37916
 github,                             no source size,                     old streaming advanced,             140599
 github,                             no source size with dict,           old streaming advanced,             40608
 github,                             long distance mode,                 old streaming advanced,             141104
@@ -1403,8 +1403,8 @@ github.tar,                         level 13,                           old stre
 github.tar,                         level 13 with dict,                 old streaming advanced,             35807
 github.tar,                         level 16,                           old streaming advanced,             40466
 github.tar,                         level 16 with dict,                 old streaming advanced,             38578
-github.tar,                         level 19,                           old streaming advanced,             32276
-github.tar,                         level 19 with dict,                 old streaming advanced,             32704
+github.tar,                         level 19,                           old streaming advanced,             32262
+github.tar,                         level 19 with dict,                 old streaming advanced,             32678
 github.tar,                         no source size,                     old streaming advanced,             38828
 github.tar,                         no source size with dict,           old streaming advanced,             38015
 github.tar,                         long distance mode,                 old streaming advanced,             38831
@@ -1415,7 +1415,7 @@ github.tar,                         small hash log,                     old stre
 github.tar,                         small chain log,                    old streaming advanced,             41669
 github.tar,                         explicit params,                    old streaming advanced,             41385
 github.tar,                         uncompressed literals,              old streaming advanced,             38831
-github.tar,                         uncompressed literals optimal,      old streaming advanced,             32276
+github.tar,                         uncompressed literals optimal,      old streaming advanced,             32262
 github.tar,                         huffman literals,                   old streaming advanced,             42560
 github.tar,                         multithreaded with advanced params, old streaming advanced,             38831
 github,                             level -5 with dict,                 old streaming cdict,                45832
@@ -1430,8 +1430,8 @@ github,                             level 6 with dict,                  old stre
 github,                             level 7 with dict,                  old streaming cdict,                38765
 github,                             level 9 with dict,                  old streaming cdict,                39439
 github,                             level 13 with dict,                 old streaming cdict,                39900
-github,                             level 16 with dict,                 old streaming cdict,                37577
-github,                             level 19 with dict,                 old streaming cdict,                37576
+github,                             level 16 with dict,                 old streaming cdict,                37902
+github,                             level 19 with dict,                 old streaming cdict,                37916
 github,                             no source size with dict,           old streaming cdict,                40654
 github.tar,                         level -5 with dict,                 old streaming cdict,                51286
 github.tar,                         level -3 with dict,                 old streaming cdict,                45147
@@ -1446,7 +1446,7 @@ github.tar,                         level 7 with dict,                  old stre
 github.tar,                         level 9 with dict,                  old streaming cdict,                36322
 github.tar,                         level 13 with dict,                 old streaming cdict,                36010
 github.tar,                         level 16 with dict,                 old streaming cdict,                39081
-github.tar,                         level 19 with dict,                 old streaming cdict,                32479
+github.tar,                         level 19 with dict,                 old streaming cdict,                32428
 github.tar,                         no source size with dict,           old streaming cdict,                38000
 github,                             level -5 with dict,                 old streaming advanced cdict,       46708
 github,                             level -3 with dict,                 old streaming advanced cdict,       45476
@@ -1460,8 +1460,8 @@ github,                             level 6 with dict,                  old stre
 github,                             level 7 with dict,                  old streaming advanced cdict,       38875
 github,                             level 9 with dict,                  old streaming advanced cdict,       38941
 github,                             level 13 with dict,                 old streaming advanced cdict,       39725
-github,                             level 16 with dict,                 old streaming advanced cdict,       40789
-github,                             level 19 with dict,                 old streaming advanced cdict,       37576
+github,                             level 16 with dict,                 old streaming advanced cdict,       40804
+github,                             level 19 with dict,                 old streaming advanced cdict,       37916
 github,                             no source size with dict,           old streaming advanced cdict,       40608
 github.tar,                         level -5 with dict,                 old streaming advanced cdict,       50791
 github.tar,                         level -3 with dict,                 old streaming advanced cdict,       44926
@@ -1476,5 +1476,5 @@ github.tar,                         level 7 with dict,                  old stre
 github.tar,                         level 9 with dict,                  old streaming advanced cdict,       36241
 github.tar,                         level 13 with dict,                 old streaming advanced cdict,       35807
 github.tar,                         level 16 with dict,                 old streaming advanced cdict,       38578
-github.tar,                         level 19 with dict,                 old streaming advanced cdict,       32704
+github.tar,                         level 19 with dict,                 old streaming advanced cdict,       32678
 github.tar,                         no source size with dict,           old streaming advanced cdict,       38015

From b88c593d8ff79b96390308380604f232802e0f04 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 5 Feb 2024 18:32:25 -0800
Subject: [PATCH 180/937] added or updated code comments

as suggested by @terrelln,
to make the code of the optimal parser a bit more understandable.
---
 lib/compress/zstd_compress_internal.h |  2 +-
 lib/compress/zstd_opt.c               | 22 ++++++++++++++--------
 2 files changed, 15 insertions(+), 9 deletions(-)

diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index dae8526d4..087ea49dc 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -162,7 +162,7 @@ typedef struct {
     int price;  /* price from beginning of segment to this position */
     U32 off;    /* offset of previous match */
     U32 mlen;   /* length of previous match */
-    U32 litlen; /* nb of literals after previous match */
+    U32 litlen; /* nb of literals since previous match */
     U32 rep[ZSTD_REP_NUM];  /* offset history after previous match */
 } ZSTD_optimal_t;
 
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 25715eabb..8e1be1cec 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1129,13 +1129,20 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                 continue;
             }
 
+            /* Match found: let's store this solution, and eventually find more candidates.
+             * During this forward pass, @opt is used to store stretches,
+             * defined as "a match followed by N literals".
+             * Note how this is different from a Sequence, which is "N literals followed by a match".
+             * Storing stretches allows us to store different match predecessors
+             * for each literal position part of a literals run. */
+
             /* initialize opt[0] */
             opt[0].mlen = 0;  /* there are only literals so far */
             opt[0].litlen = litlen;
-            /* No need to include the actual price of the literals before the segment
+            /* No need to include the actual price of the literals before the first match
              * because it is static for the duration of the forward pass, and is included
-             * in every subsequent price. We include the literal length as the cost variation
-             * of litlen depends on the value of litlen.
+             * in every subsequent price. But, we include the literal length because
+             * the cost variation of litlen depends on the value of litlen.
              */
             opt[0].price = LL_PRICE(litlen);
             ZSTD_STATIC_ASSERT(sizeof(opt[0].rep[0]) == sizeof(rep[0]));
@@ -1353,11 +1360,10 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
             cur -= lastStretch.litlen;
         }
 
-        /* let's write the shortest path solution
-         * solution is stored in @opt,
-         * in reverse order,
-         * starting from @storeEnd (==cur+1)
-         * (effectively partially overwriting @opt).
+        /* Let's write the shortest path solution.
+         * It is stored in @opt in reverse order,
+         * starting from @storeEnd (==cur+2),
+         * effectively partially @opt overwriting.
          * Content is changed too:
          * - So far, @opt stored stretches, aka a match followed by literals
          * - Now, it will store sequences, aka literals followed by a match

From 1f87c88ecf3814ef59fa514dd7fe3522d2d400b1 Mon Sep 17 00:00:00 2001
From: sergeyandreenko 
Date: Tue, 6 Feb 2024 12:07:11 -0800
Subject: [PATCH 181/937] [Zstd] Less verbose log for patch mode.

---
 programs/fileio.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/programs/fileio.c b/programs/fileio.c
index 81d343023..b0d95f63a 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -1096,15 +1096,15 @@ static void FIO_adjustParamsForPatchFromMode(FIO_prefs_t* const prefs,
     comprParams->windowLog = MAX(ZSTD_WINDOWLOG_MIN, MIN(ZSTD_WINDOWLOG_MAX, fileWindowLog));
     if (fileWindowLog > ZSTD_cycleLog(cParams.chainLog, cParams.strategy)) {
         if (!prefs->ldmFlag)
-            DISPLAYLEVEL(1, "long mode automatically triggered\n");
+            DISPLAYLEVEL(2, "long mode automatically triggered\n");
         FIO_setLdmFlag(prefs, 1);
     }
     if (cParams.strategy >= ZSTD_btopt) {
-        DISPLAYLEVEL(1, "[Optimal parser notes] Consider the following to improve patch size at the cost of speed:\n");
-        DISPLAYLEVEL(1, "- Use --single-thread mode in the zstd cli\n");
-        DISPLAYLEVEL(1, "- Set a larger targetLength (e.g. --zstd=targetLength=4096)\n");
-        DISPLAYLEVEL(1, "- Set a larger chainLog (e.g. --zstd=chainLog=%u)\n", ZSTD_CHAINLOG_MAX);
-        DISPLAYLEVEL(1, "Also consider playing around with searchLog and hashLog\n");
+        DISPLAYLEVEL(3, "[Optimal parser notes] Consider the following to improve patch size at the cost of speed:\n");
+        DISPLAYLEVEL(3, "- Use --single-thread mode in the zstd cli\n");
+        DISPLAYLEVEL(3, "- Set a larger targetLength (e.g. --zstd=targetLength=4096)\n");
+        DISPLAYLEVEL(3, "- Set a larger chainLog (e.g. --zstd=chainLog=%u)\n", ZSTD_CHAINLOG_MAX);
+        DISPLAYLEVEL(3, "Also consider playing around with searchLog and hashLog\n");
     }
 }
 

From 22574d848df09616d07fe26b363700525cb9cce9 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 6 Feb 2024 12:15:54 -0800
Subject: [PATCH 182/937] fix issue 5921623844651008

ossfuzz managed to create a scenario which triggers an `assert`.
This fixes it, by giving +1 more space for the backward search pass.
---
 lib/compress/zstd_compress_internal.h | 2 +-
 lib/compress/zstd_opt.c               | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 087ea49dc..e41d7b78e 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -168,7 +168,7 @@ typedef struct {
 
 typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
 
-#define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+2)
+#define ZSTD_OPT_SIZE (ZSTD_OPT_NUM+3)
 typedef struct {
     /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
     unsigned* litFreq;           /* table of literals statistics, of size 256 */
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 8e1be1cec..0449204dd 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1196,7 +1196,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
         /* check further positions */
         for (cur = 1; cur <= last_pos; cur++) {
             const BYTE* const inr = ip + cur;
-            assert(cur < ZSTD_OPT_NUM);
+            assert(cur <= ZSTD_OPT_NUM);
             DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur);
 
             /* Fix current position with one literal if cheaper */

From 3a64c69eba2592ec1cbcbed294a84019ab47dd19 Mon Sep 17 00:00:00 2001
From: Josh Kearney 
Date: Thu, 1 Feb 2024 11:21:16 -0600
Subject: [PATCH 183/937] Convert the CircleCI workflow to a GitHub Actions
 workflow

---
 .github/workflows/commit.yml  | 88 +++++++++++++++++++++++++++++++++++
 .github/workflows/nightly.yml | 64 +++++++++++++++++++++++++
 2 files changed, 152 insertions(+)
 create mode 100644 .github/workflows/commit.yml
 create mode 100644 .github/workflows/nightly.yml

diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml
new file mode 100644
index 000000000..83a6412b9
--- /dev/null
+++ b/.github/workflows/commit.yml
@@ -0,0 +1,88 @@
+name: facebook/zstd/commit
+on:
+  push:
+    branches:
+    - dev
+jobs:
+  short-tests-0:
+    runs-on: ubuntu-latest
+    services:
+      docker:
+        image: fbopensource/zstd-circleci-primary:0.0.1
+        options: --entrypoint /bin/bash
+    steps:
+    - uses: actions/checkout@v4
+    - name: Install Dependencies
+      run: |
+        sudo apt-get update
+        sudo apt-get install libcurl4-gnutls-dev
+    - name: Test
+      run: |
+        ./tests/test-license.py
+        cc -v
+        CFLAGS="-O0 -Werror -pedantic" make allmost; make clean
+        make c99build; make clean
+        make c11build; make clean
+        make -j regressiontest; make clean
+        make shortest; make clean
+        make cxxtest; make clean
+  short-tests-1:
+    runs-on: ubuntu-latest
+    services:
+      docker:
+        image: fbopensource/zstd-circleci-primary:0.0.1
+        options: --entrypoint /bin/bash
+    steps:
+    - uses: actions/checkout@v4
+    - name: Install Dependencies
+      run: |
+        sudo apt-get update
+        sudo apt-get install gcc-powerpc-linux-gnu gcc-arm-linux-gnueabi gcc-aarch64-linux-gnu libc6-dev-ppc64-powerpc-cross libcurl4-gnutls-dev lib64gcc-11-dev-powerpc-cross
+    - name: Test
+      run: |-
+        make gnu90build; make clean
+        make gnu99build; make clean
+        make ppc64build V=1; make clean
+        make ppcbuild   V=1; make clean
+        make armbuild   V=1; make clean
+        make aarch64build V=1; make clean
+        make -C tests test-legacy test-longmatch; make clean
+        make -C lib libzstd-nomt; make clean
+  regression-test:
+    runs-on: ubuntu-latest
+    services:
+      docker:
+        image: fbopensource/zstd-circleci-primary:0.0.1
+        options: --entrypoint /bin/bash
+    env:
+      CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts"
+    steps:
+    - uses: actions/checkout@v4
+    - name: restore_cache
+      uses: actions/cache@v3
+      with:
+        key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0
+        path: tests/regression/cache
+        restore-keys: regression-cache-{{ checksum "tests/regression/data.c" }}-v0
+    - name: Install Dependencies
+      run: |
+        sudo apt-get update
+        sudo apt-get install libcurl4-gnutls-dev
+    - name: Regression Test
+      run: |
+        make -C programs zstd
+        make -C tests/regression test
+        mkdir -p $CIRCLE_ARTIFACTS
+        ./tests/regression/test                     \
+            --cache  tests/regression/cache         \
+            --output $CIRCLE_ARTIFACTS/results.csv  \
+            --zstd   programs/zstd
+        echo "NOTE: The new results.csv is uploaded as an artifact to this job"
+        echo "      If this fails, go to the Artifacts pane in CircleCI, "
+        echo "      download /tmp/circleci-artifacts/results.csv, and if they "
+        echo "      are still good, copy it into the repo and commit it."
+        echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv"
+        diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv
+    - uses: actions/upload-artifact@v4
+      with:
+        path: "/tmp/circleci-artifacts"
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
new file mode 100644
index 000000000..0eb9ecbde
--- /dev/null
+++ b/.github/workflows/nightly.yml
@@ -0,0 +1,64 @@
+name: facebook/zstd/nightly
+on:
+  schedule:
+  - cron: 0 0 * * *
+  push:
+    branches:
+    - release
+    - dev
+    - master
+jobs:
+  regression-test:
+    runs-on: ubuntu-latest
+    services:
+      docker:
+        image: fbopensource/zstd-circleci-primary:0.0.1
+        options: --entrypoint /bin/bash
+    env:
+      CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts"
+    steps:
+    - uses: actions/checkout@v4
+    - uses: actions/cache@v3
+      with:
+        key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0
+        path: tests/regression/cache
+        restore-keys: regression-cache-{{ checksum "tests/regression/data.c" }}-v0
+    - uses: actions/upload-artifact@v4
+      with:
+        path: "/tmp/circleci-artifacts"
+    - name: Install Dependencies
+      run: |
+        sudo apt-get update
+        sudo apt-get install libcurl4-gnutls-dev
+    - name: Regression Test
+      run: |
+        make -C programs zstd
+        make -C tests/regression test
+        mkdir -p $CIRCLE_ARTIFACTS
+        ./tests/regression/test                     \
+            --cache  tests/regression/cache         \
+            --output $CIRCLE_ARTIFACTS/results.csv  \
+            --zstd   programs/zstd
+        echo "NOTE: The new results.csv is uploaded as an artifact to this job"
+        echo "      If this fails, go to the Artifacts pane in CircleCI, "
+        echo "      download /tmp/circleci-artifacts/results.csv, and if they "
+        echo "      are still good, copy it into the repo and commit it."
+        echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv"
+        diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv
+
+# Longer tests
+  #- make -C tests test-zstd-nolegacy && make clean
+  #- pyenv global 3.4.4; make -C tests versionsTest && make clean
+  #- make zlibwrapper         && make clean
+  #- gcc -v; make -C tests test32 MOREFLAGS="-I/usr/include/x86_64-linux-gnu" && make clean
+  #- make uasan               && make clean
+  #- make asan32              && make clean
+  #- make -C tests test32 CC=clang MOREFLAGS="-g -fsanitize=address -I/usr/include/x86_64-linux-gnu"
+# Valgrind tests
+  #- CFLAGS="-O1 -g" make -C zlibWrapper valgrindTest && make clean
+  #- make -C tests valgrindTest && make clean
+# ARM, AArch64, PowerPC, PowerPC64 tests
+  #- make ppctest             && make clean
+  #- make ppc64test           && make clean
+  #- make armtest             && make clean
+  #- make aarch64test         && make clean

From 695d154cac251c4ae2e2a438af21f0455a4c4149 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 8 Feb 2024 16:14:14 -0800
Subject: [PATCH 184/937] fuzz: control debuglevel from Makefile

and make the compilation faster
---
 tests/fuzz/Makefile | 2 +-
 tests/fuzz/fuzz.py  | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile
index 525e396bc..554bd10d5 100644
--- a/tests/fuzz/Makefile
+++ b/tests/fuzz/Makefile
@@ -257,7 +257,7 @@ corpora: $(patsubst %,corpora/%,$(FUZZ_TARGETS))
 seedcorpora: $(patsubst %,corpora/%_seed_corpus.zip,$(FUZZ_TARGETS))
 
 regressiontest: corpora
-	CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" $(PYTHON) ./fuzz.py build all
+	CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" $(PYTHON) ./fuzz.py build all --debug=$(DEBUGLEVEL)
 	$(PYTHON) ./fuzz.py regression all
 
 clean:
diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py
index 058fca813..c489b8fa6 100755
--- a/tests/fuzz/fuzz.py
+++ b/tests/fuzz/fuzz.py
@@ -492,6 +492,7 @@ def build(args):
     subprocess.check_call(clean_cmd)
     build_cmd = [
         'make',
+        '-j',
         cc_str,
         cxx_str,
         cppflags_str,

From b0e8580dc7f71881361f3a6fe46841af9d70bedf Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 8 Feb 2024 16:38:20 -0800
Subject: [PATCH 185/937] fix fuzz issue 5131069967892480

---
 lib/compress/zstd_opt.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index 0449204dd..c2ec2a9ed 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1216,6 +1216,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
                     if ( (optLevel >= 1) /* additional check only for higher modes */
                       && (prevMatch.litlen == 0) /* replace a match */
                       && (LL_INCPRICE(1) < 0) /* ll1 is cheaper than ll0 */
+                      && LIKELY(ip + cur < iend)
                     ) {
                         /* check next position, in case it would be cheaper */
                         int with1literal = prevMatch.price + LIT_PRICE(ip+cur) + LL_INCPRICE(1);

From b921f1aad67cfc347ea7f8ef1c0afb6688bad4b6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Christoph=20Gr=C3=BCninger?= 
Date: Sun, 11 Feb 2024 11:22:05 +0100
Subject: [PATCH 186/937] Reduce scope of variables

This improves readability, keeps variables local, and
prevents the unintended use (e.g. typo) later on.
Found by Cppcheck (variableScope)
---
 lib/compress/huf_compress.c    | 16 +++++++++-------
 lib/compress/zstd_compress.c   |  6 ++----
 lib/compress/zstd_ldm.c        |  2 +-
 lib/compress/zstd_opt.c        |  3 +--
 lib/compress/zstdmt_compress.c |  4 ++--
 programs/benchfn.c             |  4 ++--
 programs/fileio.c              | 10 +++++-----
 programs/util.c                | 10 +++++-----
 8 files changed, 27 insertions(+), 28 deletions(-)

diff --git a/lib/compress/huf_compress.c b/lib/compress/huf_compress.c
index 1097d13d8..ea0007232 100644
--- a/lib/compress/huf_compress.c
+++ b/lib/compress/huf_compress.c
@@ -1062,12 +1062,12 @@ HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,
     const BYTE* ip = (const BYTE*) src;
     BYTE* const ostart = (BYTE*)dst;
     BYTE* const oend = ostart + dstSize;
-    BYTE* op = ostart;
     HUF_CStream_t bitC;
 
     /* init */
     if (dstSize < 8) return 0;   /* not enough space to compress */
-    { size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));
+    { BYTE* op = ostart;
+      size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));
       if (HUF_isError(initErr)) return 0; }
 
     if (dstSize < HUF_tightCompressBound(srcSize, (size_t)tableLog) || tableLog > 11)
@@ -1288,7 +1288,7 @@ unsigned HUF_optimalTableLog(
 
     {   BYTE* dst = (BYTE*)workSpace + sizeof(HUF_WriteCTableWksp);
         size_t dstSize = wkspSize - sizeof(HUF_WriteCTableWksp);
-        size_t maxBits, hSize, newSize;
+        size_t hSize, newSize;
         const unsigned symbolCardinality = HUF_cardinality(count, maxSymbolValue);
         const unsigned minTableLog = HUF_minTableLog(symbolCardinality);
         size_t optSize = ((size_t) ~0) - 1;
@@ -1299,12 +1299,14 @@ unsigned HUF_optimalTableLog(
         /* Search until size increases */
         for (optLogGuess = minTableLog; optLogGuess <= maxTableLog; optLogGuess++) {
             DEBUGLOG(7, "checking for huffLog=%u", optLogGuess);
-            maxBits = HUF_buildCTable_wksp(table, count, maxSymbolValue, optLogGuess, workSpace, wkspSize);
-            if (ERR_isError(maxBits)) continue;
 
-            if (maxBits < optLogGuess && optLogGuess > minTableLog) break;
+            {   size_t maxBits = HUF_buildCTable_wksp(table, count, maxSymbolValue, optLogGuess, workSpace, wkspSize);
+                if (ERR_isError(maxBits)) continue;
 
-            hSize = HUF_writeCTable_wksp(dst, dstSize, table, maxSymbolValue, (U32)maxBits, workSpace, wkspSize);
+                if (maxBits < optLogGuess && optLogGuess > minTableLog) break;
+
+                hSize = HUF_writeCTable_wksp(dst, dstSize, table, maxSymbolValue, (U32)maxBits, workSpace, wkspSize);
+            }
 
             if (ERR_isError(hSize)) continue;
 
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index f8abbbbd9..451f2f91e 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -2136,7 +2136,6 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
             ZSTD_estimateCCtxSize_usingCCtxParams_internal(
                 ¶ms->cParams, ¶ms->ldmParams, zc->staticSize != 0, params->useRowMatchFinder,
                 buffInSize, buffOutSize, pledgedSrcSize, ZSTD_hasExtSeqProd(params), params->maxBlockSize);
-        int resizeWorkspace;
 
         FORWARD_IF_ERROR(neededSpace, "cctx size estimate failed!");
 
@@ -2145,7 +2144,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
         {   /* Check if workspace is large enough, alloc a new one if needed */
             int const workspaceTooSmall = ZSTD_cwksp_sizeof(ws) < neededSpace;
             int const workspaceWasteful = ZSTD_cwksp_check_wasteful(ws, neededSpace);
-            resizeWorkspace = workspaceTooSmall || workspaceWasteful;
+            int resizeWorkspace = workspaceTooSmall || workspaceWasteful;
             DEBUGLOG(4, "Need %zu B workspace", neededSpace);
             DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
 
@@ -5176,14 +5175,13 @@ static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
 {
     BYTE* const ostart = (BYTE*)dst;
     BYTE* op = ostart;
-    size_t fhSize = 0;
 
     DEBUGLOG(4, "ZSTD_writeEpilogue");
     RETURN_ERROR_IF(cctx->stage == ZSTDcs_created, stage_wrong, "init missing");
 
     /* special case : empty frame */
     if (cctx->stage == ZSTDcs_init) {
-        fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
+        size_t fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, &cctx->appliedParams, 0, 0);
         FORWARD_IF_ERROR(fhSize, "ZSTD_writeFrameHeader failed");
         dstCapacity -= fhSize;
         op += fhSize;
diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c
index 7a0792ee4..17c069fe1 100644
--- a/lib/compress/zstd_ldm.c
+++ b/lib/compress/zstd_ldm.c
@@ -695,7 +695,6 @@ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
         /* maybeSplitSequence updates rawSeqStore->pos */
         rawSeq const sequence = maybeSplitSequence(rawSeqStore,
                                                    (U32)(iend - ip), minMatch);
-        int i;
         /* End signal */
         if (sequence.offset == 0)
             break;
@@ -708,6 +707,7 @@ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
         /* Run the block compressor */
         DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
         {
+            int i;
             size_t const newLitLength =
                 blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
             ip += sequence.litLength;
diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c
index c2ec2a9ed..e63073e5a 100644
--- a/lib/compress/zstd_opt.c
+++ b/lib/compress/zstd_opt.c
@@ -1372,7 +1372,6 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
         {   U32 const storeEnd = cur + 2;
             U32 storeStart = storeEnd;
             U32 stretchPos = cur;
-            ZSTD_optimal_t nextStretch;
 
             DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
                         last_pos, cur); (void)last_pos;
@@ -1390,7 +1389,7 @@ _shortestPath:   /* cur, last_pos, best_mlen, best_off have to be set */
                 storeStart = storeEnd;
             }
             while (1) {
-                nextStretch = opt[stretchPos];
+                ZSTD_optimal_t nextStretch = opt[stretchPos];
                 opt[storeStart].litlen = nextStretch.litlen;
                 DEBUGLOG(6, "selected sequence (llen=%u,mlen=%u,ofc=%u)",
                             opt[storeStart].litlen, opt[storeStart].mlen, opt[storeStart].off);
diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c
index baa0f0069..e86fdb2ba 100644
--- a/lib/compress/zstdmt_compress.c
+++ b/lib/compress/zstdmt_compress.c
@@ -105,10 +105,10 @@ typedef struct ZSTDMT_bufferPool_s {
 
 static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
 {
-    unsigned u;
     DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
     if (!bufPool) return;   /* compatibility with free on NULL */
     if (bufPool->buffers) {
+        unsigned u;
         for (u=0; utotalBuffers; u++) {
             DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->buffers[u].start);
             ZSTD_customFree(bufPool->buffers[u].start, bufPool->cMem);
@@ -364,10 +364,10 @@ typedef struct {
 /* note : all CCtx borrowed from the pool must be reverted back to the pool _before_ freeing the pool */
 static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
 {
-    int cid;
     if (!pool) return;
     ZSTD_pthread_mutex_destroy(&pool->poolMutex);
     if (pool->cctxs) {
+        int cid;
         for (cid=0; cidtotalCCtx; cid++)
             ZSTD_freeCCtx(pool->cctxs[cid]);  /* free compatible with NULL */
         ZSTD_customFree(pool->cctxs, pool->cMem);
diff --git a/programs/benchfn.c b/programs/benchfn.c
index 8e6726f8d..3e042cf38 100644
--- a/programs/benchfn.c
+++ b/programs/benchfn.c
@@ -108,7 +108,6 @@ static BMK_runOutcome_t BMK_setValid_runTime(BMK_runTime_t runTime)
 BMK_runOutcome_t BMK_benchFunction(BMK_benchParams_t p,
                                    unsigned nbLoops)
 {
-    size_t dstSize = 0;
     nbLoops += !nbLoops;   /* minimum nbLoops is 1 */
 
     /* init */
@@ -118,7 +117,8 @@ BMK_runOutcome_t BMK_benchFunction(BMK_benchParams_t p,
     }   }
 
     /* benchmark */
-    {   UTIL_time_t const clockStart = UTIL_getTime();
+    {   size_t dstSize = 0;
+        UTIL_time_t const clockStart = UTIL_getTime();
         unsigned loopNb, blockNb;
         if (p.initFn != NULL) p.initFn(p.initPayload);
         for (loopNb = 0; loopNb < nbLoops; loopNb++) {
diff --git a/programs/fileio.c b/programs/fileio.c
index b0d95f63a..a7597d893 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -1839,7 +1839,6 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx,
     int closeDstFile = 0;
     int result;
     int transferStat = 0;
-    FILE *dstFile;
     int dstFd = -1;
 
     assert(AIO_ReadPool_getFile(ress.readCtx) != NULL);
@@ -1854,10 +1853,11 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx,
 
         closeDstFile = 1;
         DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: opening dst: %s \n", dstFileName);
-        dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName, dstFileInitialPermissions);
-        if (dstFile==NULL) return 1;  /* could not open dstFileName */
-        dstFd = fileno(dstFile);
-        AIO_WritePool_setFile(ress.writeCtx, dstFile);
+        {   FILE *dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName, dstFileInitialPermissions);
+            if (dstFile==NULL) return 1;  /* could not open dstFileName */
+            dstFd = fileno(dstFile);
+            AIO_WritePool_setFile(ress.writeCtx, dstFile);
+        }
         /* Must only be added after FIO_openDstFile() succeeds.
          * Otherwise we may delete the destination file if it already exists,
          * and the user presses Ctrl-C when asked if they wish to overwrite.
diff --git a/programs/util.c b/programs/util.c
index c9031e91d..862fc8008 100644
--- a/programs/util.c
+++ b/programs/util.c
@@ -660,7 +660,6 @@ UTIL_createFileNamesTable_fromFileName(const char* inputFileName)
     size_t nbFiles = 0;
     char* buf;
     size_t bufSize;
-    size_t pos = 0;
     stat_t statbuf;
 
     if (!UTIL_stat(inputFileName, &statbuf) || !UTIL_isRegularFileStat(&statbuf))
@@ -687,12 +686,13 @@ UTIL_createFileNamesTable_fromFileName(const char* inputFileName)
     {   const char** filenamesTable = (const char**) malloc(nbFiles * sizeof(*filenamesTable));
         CONTROL(filenamesTable != NULL);
 
-        {   size_t fnb;
-            for (fnb = 0, pos = 0; fnb < nbFiles; fnb++) {
+        {   size_t fnb, pos = 0;
+            for (fnb = 0; fnb < nbFiles; fnb++) {
                 filenamesTable[fnb] = buf+pos;
                 pos += strlen(buf+pos)+1;  /* +1 for the finishing `\0` */
-        }   }
+            }
         assert(pos <= bufSize);
+        }
 
         return UTIL_assembleFileNamesTable(filenamesTable, nbFiles, buf);
     }
@@ -753,7 +753,7 @@ void UTIL_refFilename(FileNamesTable* fnt, const char* filename)
 
 static size_t getTotalTableSize(FileNamesTable* table)
 {
-    size_t fnb = 0, totalSize = 0;
+    size_t fnb, totalSize = 0;
     for(fnb = 0 ; fnb < table->tableSize && table->fileNames[fnb] ; ++fnb) {
         totalSize += strlen(table->fileNames[fnb]) + 1; /* +1 to add '\0' at the end of each fileName */
     }

From 927d0799442c42ece088dcf339ca25968274f5a0 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 12 Feb 2024 05:17:13 +0000
Subject: [PATCH 187/937] Bump actions/upload-artifact from 4.3.0 to 4.3.1

Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.3.0 to 4.3.1.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/26f96dfa697d77e81fd5907df203aa23a56210a8...5d5d22a31266ced268874388b861e4b58bb5c2f3)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/scorecards.yml        | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 29db7316e..aed68bb93 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -290,7 +290,7 @@ jobs:
         dry-run: false
         sanitizer: ${{ matrix.sanitizer }}
     - name: Upload Crash
-      uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
+      uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1
       if: failure() && steps.build.outcome == 'success'
       with:
         name: ${{ matrix.sanitizer }}-artifacts
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 770f9d4a3..0ccd87625 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -51,7 +51,7 @@ jobs:
       # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
       # format to the repository Actions tab.
       - name: "Upload artifact"
-        uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
+        uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1
         with:
           name: SARIF file
           path: results.sarif
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index b689bf560..52bc90a49 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -52,7 +52,7 @@ jobs:
         cd ..
 
     - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip
-      uses: actions/upload-artifact@26f96dfa697d77e81fd5907df203aa23a56210a8 # tag=v4.3.0
+      uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1
       with:
         path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip
         name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip

From b6805c54d67f902d32afecc5ca153cd81a77764f Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Tue, 13 Feb 2024 11:50:55 -0500
Subject: [PATCH 188/937] Add SECURITY.md File

This just adds a copy of the Meta default SECURITY.md that we can then modify.
---
 SECURITY.md | 7 +++++++
 1 file changed, 7 insertions(+)
 create mode 100644 SECURITY.md

diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 000000000..4e5f09cbe
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,7 @@
+# Reporting and Fixing Security Issues
+
+Please do not open GitHub issues or pull requests - this makes the problem immediately visible to everyone, including malicious actors. Security issues in this open source project can be safely reported via the Meta Bug Bounty program:
+
+https://www.facebook.com/whitehat
+
+Meta's security team will triage your report and determine whether or not is it eligible for a bounty under our program.

From e13d099bf881d69d6cf8bcd5cd4f677e1ce86bea Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Tue, 13 Feb 2024 11:51:37 -0500
Subject: [PATCH 189/937] Advertise Availability of Security Vulnerability
 Notifications

---
 SECURITY.md | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/SECURITY.md b/SECURITY.md
index 4e5f09cbe..a5f9a7e1f 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -5,3 +5,11 @@ Please do not open GitHub issues or pull requests - this makes the problem immed
 https://www.facebook.com/whitehat
 
 Meta's security team will triage your report and determine whether or not is it eligible for a bounty under our program.
+
+# Receiving Vulnerability Notifications
+
+In the case that a significant security vulnerability is reported to us or discovered by us---without being publicly known---we will, at our discretion, notify high-profile, high-exposure users of Zstandard ahead of our public disclosure of the issue and associated fix.
+
+If you believe your project would benefit from inclusion in this list, please reach out to one of the maintainers.
+
+

From 1e046ce7fa6ebabb48a182009df6e4fe90fa2740 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 00:12:32 -0800
Subject: [PATCH 190/937] increase vocabulary size

makes compression a bit less good,
hence a bit more comparable with real text (though still too easy to compress).
level 6 is now stronger than level 4, by a hair.
However, there is still a ratio dip at level 5.
---
 .gitignore       |   7 +-
 programs/lorem.c | 257 +++++++++++++++++++++++++----------------------
 2 files changed, 141 insertions(+), 123 deletions(-)

diff --git a/.gitignore b/.gitignore
index 048a4c4e4..34e18b443 100644
--- a/.gitignore
+++ b/.gitignore
@@ -39,12 +39,15 @@ buck-out/
 build-*
 *.gcda
 
+# IDE
+.clang_complete
+compile_flags.txt
+.clang-format
+
 # Other files
 .directory
 _codelite/
 _zstdbench/
-.clang_complete
-compile_flags.txt
 *.idea
 *.swp
 .DS_Store
diff --git a/programs/lorem.c b/programs/lorem.c
index 59dd6da62..cf452ca8b 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -8,7 +8,6 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
-
 /* Implementation notes:
  *
  * This is a very simple lorem ipsum generator
@@ -32,83 +31,97 @@
  */
 
 #include "lorem.h"
-#include   /* memcpy */
-#include   /* INT_MAX */
 #include 
+#include  /* INT_MAX */
+#include  /* memcpy */
 
 #define WORD_MAX_SIZE 20
 
 /* Define the word pool */
-static const char *words[] = {
-    "lorem",       "ipsum",      "dolor",      "sit",          "amet",
-    "consectetur", "adipiscing", "elit",       "sed",          "do",
-    "eiusmod",     "tempor",     "incididunt", "ut",           "labore",
-    "et",          "dolore",     "magna",      "aliqua",       "dis",
-    "lectus",      "vestibulum", "mattis",     "ullamcorper",  "velit",
-    "commodo",     "a",          "lacus",      "arcu",         "magnis",
-    "parturient",  "montes",     "nascetur",   "ridiculus",    "mus",
-    "mauris",      "nulla",      "malesuada",  "pellentesque", "eget",
-    "gravida",     "in",         "dictum",     "non",          "erat",
-    "nam",         "voluptat",   "maecenas",   "blandit",      "aliquam",
-    "etiam",       "enim",       "lobortis",   "scelerisque",  "fermentum",
-    "dui",         "faucibus",   "ornare",     "at",           "elementum",
-    "eu",          "facilisis",  "odio",       "morbi",        "quis",
-    "eros",        "donec",      "ac",         "orci",         "purus",
-    "turpis",      "cursus",     "leo",        "vel",          "porta"};
+static const char* words[] = {
+    "lorem",        "ipsum",      "dolor",       "sit",          "amet",
+    "consectetur",  "adipiscing", "elit",        "sed",          "do",
+    "eiusmod",      "tempor",     "incididunt",  "ut",           "labore",
+    "et",           "dolore",     "magna",       "aliqua",       "dis",
+    "lectus",       "vestibulum", "mattis",      "ullamcorper",  "velit",
+    "commodo",      "a",          "lacus",       "arcu",         "magnis",
+    "parturient",   "montes",     "nascetur",    "ridiculus",    "mus",
+    "mauris",       "nulla",      "malesuada",   "pellentesque", "eget",
+    "gravida",      "in",         "dictum",      "non",          "erat",
+    "nam",          "voluptat",   "maecenas",    "blandit",      "aliquam",
+    "etiam",        "enim",       "lobortis",    "scelerisque",  "fermentum",
+    "dui",          "faucibus",   "ornare",      "at",           "elementum",
+    "eu",           "facilisis",  "odio",        "morbi",        "quis",
+    "eros",         "donec",      "ac",          "orci",         "purus",
+    "turpis",       "cursus",     "leo",         "vel",          "porta",
+    "consequat",    "interdum",   "varius",      "vulputate",    "aliquet",
+    "pharetra",     "nunc",       "auctor",      "urna",         "id",
+    "metus",        "viverra",    "nibh",        "cras",         "mi",
+    "unde",         "omnis",      "iste",        "natus",        "error",
+    "perspiciatis", "voluptatem", "accusantium", "doloremque",   "laudantium",
+    "totam",        "rem",        "aperiam",     "eaque",        "ipsa",
+    "quae",         "ab",         "illo",        "inventore",    "veritatis",
+    "quasi",        "architecto", "beatae",      "vitae",        "dicta",
+    "sunt",         "explicabo",  "nemo",        "ipsam",        "quia",
+    "voluptas",     "aspernatur", "aut",         "odit",         "fugit"
+};
 
-/* simple distribution that favors small words :
+/* simple 1-dimension distribution that favors small words :
  * 1 letter : weight 3
  * 2-3 letters : weight 2
  * 4+ letters : weight 1
- * This is expected to be a bit more difficult to compress */
+ */
 static const int distrib[] = {
-    0, 1, 2, 3, 3, 4, 5, 6, 7, 8,
-    8,9, 9, 10, 11, 12, 13, 13, 14, 15,
-    15, 16, 17, 18, 19, 19, 20, 21, 22, 23,
-    24, 25, 26, 26, 26, 27, 28, 29, 30, 31,
-    32, 33, 34, 34, 35, 36, 37, 38, 39, 40,
-    41, 41, 42, 43, 43, 44, 45, 45, 46, 47,
-    48, 49, 50, 51, 52, 53, 54, 55, 55, 56,
-    57, 58, 58, 59, 60, 60, 61, 62, 63, 64,
-    65, 66, 67, 67, 68, 69, 70, 71, 72, 72,
-    73, 73, 74 };
+    0,   1,   2,   3,   3,   4,   5,   6,   7,   8,   8,   9,   9,   10,  11,
+    12,  13,  13,  14,  15,  15,  16,  17,  18,  19,  19,  20,  21,  22,  23,
+    24,  25,  26,  26,  26,  27,  28,  29,  30,  31,  32,  33,  34,  34,  35,
+    36,  37,  38,  39,  40,  41,  41,  42,  43,  43,  44,  45,  45,  46,  47,
+    48,  49,  50,  51,  52,  53,  54,  55,  55,  56,  57,  58,  58,  59,  60,
+    60,  61,  62,  63,  64,  65,  66,  67,  67,  68,  69,  70,  71,  72,  72,
+    73,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  84,  85,
+    86,  87,  88,  89,  89,  90,  91,  92,  93,  94,  95,  96,  97,  98,  99,
+    100, 101, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112,
+    113, 114, 115, 116, 117, 118, 119, 129, 121, 122, 123, 124,
+};
 static const unsigned distribCount = sizeof(distrib) / sizeof(distrib[0]);
 
 /* Note: this unit only works when invoked sequentially.
  * No concurrent access is allowed */
-static char *g_ptr = NULL;
-static size_t g_nbChars = 0;
-static size_t g_maxChars = 10000000;
+static char* g_ptr         = NULL;
+static size_t g_nbChars    = 0;
+static size_t g_maxChars   = 10000000;
 static unsigned g_randRoot = 0;
 
 #define RDG_rotl32(x, r) ((x << r) | (x >> (32 - r)))
-static unsigned LOREM_rand(unsigned range) {
-  static const unsigned prime1 = 2654435761U;
-  static const unsigned prime2 = 2246822519U;
-  unsigned rand32 = g_randRoot;
-  rand32 *= prime1;
-  rand32 ^= prime2;
-  rand32 = RDG_rotl32(rand32, 13);
-  g_randRoot = rand32;
-  return (unsigned)(((unsigned long long)rand32 * range) >> 32);
+static unsigned LOREM_rand(unsigned range)
+{
+    static const unsigned prime1 = 2654435761U;
+    static const unsigned prime2 = 2246822519U;
+    unsigned rand32              = g_randRoot;
+    rand32 *= prime1;
+    rand32 ^= prime2;
+    rand32     = RDG_rotl32(rand32, 13);
+    g_randRoot = rand32;
+    return (unsigned)(((unsigned long long)rand32 * range) >> 32);
 }
 
-static void writeLastCharacters(void) {
-  size_t lastChars = g_maxChars - g_nbChars;
-  assert(g_maxChars >= g_nbChars);
-  if (lastChars == 0)
-    return;
-  g_ptr[g_nbChars++] = '.';
-  if (lastChars > 2) {
-    memset(g_ptr + g_nbChars, ' ', lastChars - 2);
-  }
-  if (lastChars > 1) {
-    g_ptr[g_maxChars-1] = '\n';
-  }
-  g_nbChars = g_maxChars;
+static void writeLastCharacters(void)
+{
+    size_t lastChars = g_maxChars - g_nbChars;
+    assert(g_maxChars >= g_nbChars);
+    if (lastChars == 0)
+        return;
+    g_ptr[g_nbChars++] = '.';
+    if (lastChars > 2) {
+        memset(g_ptr + g_nbChars, ' ', lastChars - 2);
+    }
+    if (lastChars > 1) {
+        g_ptr[g_maxChars - 1] = '\n';
+    }
+    g_nbChars = g_maxChars;
 }
 
-static void generateWord(const char *word, const char *separator, int upCase)
+static void generateWord(const char* word, const char* separator, int upCase)
 {
     size_t const len = strlen(word) + strlen(separator);
     if (g_nbChars + len > g_maxChars) {
@@ -118,90 +131,92 @@ static void generateWord(const char *word, const char *separator, int upCase)
     memcpy(g_ptr + g_nbChars, word, strlen(word));
     if (upCase) {
         static const char toUp = 'A' - 'a';
-        g_ptr[g_nbChars] = (char)(g_ptr[g_nbChars] + toUp);
+        g_ptr[g_nbChars]       = (char)(g_ptr[g_nbChars] + toUp);
     }
     g_nbChars += strlen(word);
     memcpy(g_ptr + g_nbChars, separator, strlen(separator));
     g_nbChars += strlen(separator);
 }
 
-static int about(unsigned target) {
-  return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
+static int about(unsigned target)
+{
+    return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
 }
 
 /* Function to generate a random sentence */
-static void generateSentence(int nbWords) {
-  int commaPos = about(9);
-  int comma2 = commaPos + about(7);
-  int i;
-  for (i = 0; i < nbWords; i++) {
-    int const wordID = distrib[LOREM_rand(distribCount)];
-    const char *const word = words[wordID];
-    const char* sep = " ";
-    if (i == commaPos)
-      sep = ", ";
-    if (i == comma2)
-      sep = ", ";
-    if (i == nbWords - 1)
-      sep = ". ";
-    generateWord(word, sep, i==0);
-  }
+static void generateSentence(int nbWords)
+{
+    int commaPos = about(9);
+    int comma2   = commaPos + about(7);
+    int i;
+    for (i = 0; i < nbWords; i++) {
+        int const wordID       = distrib[LOREM_rand(distribCount)];
+        const char* const word = words[wordID];
+        const char* sep        = " ";
+        if (i == commaPos)
+            sep = ", ";
+        if (i == comma2)
+            sep = ", ";
+        if (i == nbWords - 1)
+            sep = ". ";
+        generateWord(word, sep, i == 0);
+    }
 }
 
-static void generateParagraph(int nbSentences) {
-  int i;
-  for (i = 0; i < nbSentences; i++) {
-    int wordsPerSentence = about(8);
-    generateSentence(wordsPerSentence);
-  }
-  if (g_nbChars < g_maxChars) {
-    g_ptr[g_nbChars++] = '\n';
-  }
-  if (g_nbChars < g_maxChars) {
-    g_ptr[g_nbChars++] = '\n';
-  }
+static void generateParagraph(int nbSentences)
+{
+    int i;
+    for (i = 0; i < nbSentences; i++) {
+        int wordsPerSentence = about(8);
+        generateSentence(wordsPerSentence);
+    }
+    if (g_nbChars < g_maxChars) {
+        g_ptr[g_nbChars++] = '\n';
+    }
+    if (g_nbChars < g_maxChars) {
+        g_ptr[g_nbChars++] = '\n';
+    }
 }
 
 /* It's "common" for lorem ipsum generators to start with the same first
  * pre-defined sentence */
-static void generateFirstSentence(void) {
-  int i;
-  for (i = 0; i < 18; i++) {
-    const char *word = words[i];
-    const char *separator = " ";
-    if (i == 4)
-      separator = ", ";
-    if (i == 7)
-      separator = ", ";
-    generateWord(word, separator, i==0);
-  }
-  generateWord(words[18], ". ", 0);
+static void generateFirstSentence(void)
+{
+    int i;
+    for (i = 0; i < 18; i++) {
+        const char* word      = words[i];
+        const char* separator = " ";
+        if (i == 4)
+            separator = ", ";
+        if (i == 7)
+            separator = ", ";
+        generateWord(word, separator, i == 0);
+    }
+    generateWord(words[18], ". ", 0);
 }
 
-size_t LOREM_genBlock(void* buffer, size_t size,
-                      unsigned seed,
-                      int first, int fill)
+size_t
+LOREM_genBlock(void* buffer, size_t size, unsigned seed, int first, int fill)
 {
-  g_ptr = (char*)buffer;
-  assert(size < INT_MAX);
-  g_maxChars = size;
-  g_nbChars = 0;
-  g_randRoot = seed;
-  if (first) {
-    generateFirstSentence();
-  }
-  while (g_nbChars < g_maxChars) {
-    int sentencePerParagraph = about(7);
-    generateParagraph(sentencePerParagraph);
-    if (!fill)
-      break; /* only generate one paragraph in not-fill mode */
-  }
-  g_ptr = NULL;
-  return g_nbChars;
+    g_ptr = (char*)buffer;
+    assert(size < INT_MAX);
+    g_maxChars = size;
+    g_nbChars  = 0;
+    g_randRoot = seed;
+    if (first) {
+        generateFirstSentence();
+    }
+    while (g_nbChars < g_maxChars) {
+        int sentencePerParagraph = about(7);
+        generateParagraph(sentencePerParagraph);
+        if (!fill)
+            break; /* only generate one paragraph in not-fill mode */
+    }
+    g_ptr = NULL;
+    return g_nbChars;
 }
 
 void LOREM_genBuffer(void* buffer, size_t size, unsigned seed)
 {
-  LOREM_genBlock(buffer, size, seed, 1, 1);
+    LOREM_genBlock(buffer, size, seed, 1, 1);
 }
-

From 40874d4aea44bc9e1efd2ce14b98ea19d1d2e42d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 00:30:29 -0800
Subject: [PATCH 191/937] enriched vocabulary again

using real latin sentences from Cicero.

Compression ratio lower again, closer to "real" text,

now level 6 is way better than level 4.

level 5 is still lower than level 4,
but at least it's now higher than level 3.
---
 programs/lorem.c | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/programs/lorem.c b/programs/lorem.c
index cf452ca8b..5f0aba41a 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -63,7 +63,17 @@ static const char* words[] = {
     "quae",         "ab",         "illo",        "inventore",    "veritatis",
     "quasi",        "architecto", "beatae",      "vitae",        "dicta",
     "sunt",         "explicabo",  "nemo",        "ipsam",        "quia",
-    "voluptas",     "aspernatur", "aut",         "odit",         "fugit"
+    "voluptas",     "aspernatur", "aut",         "odit",         "fugit",
+    "consequuntur", "magni",      "dolores",     "eos",          "qui",
+    "ratione",      "sequi",      "nesciunt",    "neque",        "porro",
+    "quisquam",     "est",        "dolorem",     "adipisci",     "numquam",
+    "eius",         "modi",       "tempora",     "incidunt",     "magnam",
+    "quaerat",      "ad",         "minima",      "veniam",       "nostrum",
+    "ullam",        "corporis",   "suscipit",    "laboriosam",   "nisi",
+    "aliquid",      "ex",         "ea",          "commodi",      "consequatur",
+    "autem",        "eum",        "iure",        "voluptate",    "esse",
+    "quam",         "nihil",      "molestiae",   "illum",        "fugiat",
+    "quo",          "pariatur"
 };
 
 /* simple 1-dimension distribution that favors small words :
@@ -81,7 +91,11 @@ static const int distrib[] = {
     73,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  84,  85,
     86,  87,  88,  89,  89,  90,  91,  92,  93,  94,  95,  96,  97,  98,  99,
     100, 101, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112,
-    113, 114, 115, 116, 117, 118, 119, 129, 121, 122, 123, 124,
+    113, 114, 115, 116, 117, 118, 119, 129, 121, 122, 123, 124, 125, 126, 127,
+    128, 128, 129, 129, 130, 131, 132, 133, 134, 135, 136, 136, 137, 138, 139,
+    140, 141, 142, 143, 144, 145, 146, 146, 147, 148, 149, 150, 151, 152, 153,
+    154, 155, 156, 156, 157, 157, 158, 159, 160, 161, 161, 162, 163, 164, 165,
+    166, 167, 168, 169, 170, 170, 171,
 };
 static const unsigned distribCount = sizeof(distrib) / sizeof(distrib[0]);
 

From 5a1bb4a4e0aaba722e57cdca46486bc3c6d7e457 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 00:37:21 -0800
Subject: [PATCH 192/937] add question marks

and (slightly) longer sentences.
---
 programs/lorem.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/programs/lorem.c b/programs/lorem.c
index 5f0aba41a..8f2596e79 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -160,8 +160,10 @@ static int about(unsigned target)
 /* Function to generate a random sentence */
 static void generateSentence(int nbWords)
 {
-    int commaPos = about(9);
-    int comma2   = commaPos + about(7);
+    int commaPos       = about(9);
+    int comma2         = commaPos + about(7);
+    int qmark          = (LOREM_rand(11) == 7);
+    const char* endSep = qmark ? "? " : ". ";
     int i;
     for (i = 0; i < nbWords; i++) {
         int const wordID       = distrib[LOREM_rand(distribCount)];
@@ -172,7 +174,7 @@ static void generateSentence(int nbWords)
         if (i == comma2)
             sep = ", ";
         if (i == nbWords - 1)
-            sep = ". ";
+            sep = endSep;
         generateWord(word, sep, i == 0);
     }
 }
@@ -181,7 +183,7 @@ static void generateParagraph(int nbSentences)
 {
     int i;
     for (i = 0; i < nbSentences; i++) {
-        int wordsPerSentence = about(8);
+        int wordsPerSentence = about(10);
         generateSentence(wordsPerSentence);
     }
     if (g_nbChars < g_maxChars) {

From 3dbd861b7dc05bc4291f9de222e397e50fb4c32b Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 12:26:37 -0800
Subject: [PATCH 193/937] runtime weight distribution table

and made small words a bit more common.
---
 programs/lorem.c | 83 +++++++++++++++++++++++++++++++++---------------
 1 file changed, 57 insertions(+), 26 deletions(-)

diff --git a/programs/lorem.c b/programs/lorem.c
index 8f2596e79..49408b5a1 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -38,7 +38,7 @@
 #define WORD_MAX_SIZE 20
 
 /* Define the word pool */
-static const char* words[] = {
+static const char* kWords[] = {
     "lorem",        "ipsum",      "dolor",       "sit",          "amet",
     "consectetur",  "adipiscing", "elit",        "sed",          "do",
     "eiusmod",      "tempor",     "incididunt",  "ut",           "labore",
@@ -75,29 +75,56 @@ static const char* words[] = {
     "quam",         "nihil",      "molestiae",   "illum",        "fugiat",
     "quo",          "pariatur"
 };
+static const unsigned kNbWords = sizeof(kWords) / sizeof(kWords[0]);
 
-/* simple 1-dimension distribution that favors small words :
- * 1 letter : weight 3
- * 2-3 letters : weight 2
- * 4+ letters : weight 1
+/* simple 1-dimension distribution, based on word's length, favors small words
  */
-static const int distrib[] = {
-    0,   1,   2,   3,   3,   4,   5,   6,   7,   8,   8,   9,   9,   10,  11,
-    12,  13,  13,  14,  15,  15,  16,  17,  18,  19,  19,  20,  21,  22,  23,
-    24,  25,  26,  26,  26,  27,  28,  29,  30,  31,  32,  33,  34,  34,  35,
-    36,  37,  38,  39,  40,  41,  41,  42,  43,  43,  44,  45,  45,  46,  47,
-    48,  49,  50,  51,  52,  53,  54,  55,  55,  56,  57,  58,  58,  59,  60,
-    60,  61,  62,  63,  64,  65,  66,  67,  67,  68,  69,  70,  71,  72,  72,
-    73,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  84,  85,
-    86,  87,  88,  89,  89,  90,  91,  92,  93,  94,  95,  96,  97,  98,  99,
-    100, 101, 101, 102, 103, 104, 105, 106, 106, 107, 108, 109, 110, 111, 112,
-    113, 114, 115, 116, 117, 118, 119, 129, 121, 122, 123, 124, 125, 126, 127,
-    128, 128, 129, 129, 130, 131, 132, 133, 134, 135, 136, 136, 137, 138, 139,
-    140, 141, 142, 143, 144, 145, 146, 146, 147, 148, 149, 150, 151, 152, 153,
-    154, 155, 156, 156, 157, 157, 158, 159, 160, 161, 161, 162, 163, 164, 165,
-    166, 167, 168, 169, 170, 170, 171,
-};
-static const unsigned distribCount = sizeof(distrib) / sizeof(distrib[0]);
+static const int kWeights[]      = { 0, 8, 6, 4, 3, 2 };
+static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
+
+#define DISTRIB_SIZE_MAX 500
+static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
+static unsigned g_distribCount         = 0;
+
+static void countFreqs(
+        const char* words[],
+        size_t nbWords,
+        const int* weights,
+        unsigned long nbWeights)
+{
+    unsigned total = 0;
+    size_t w;
+    for (w = 0; w < nbWords; w++) {
+        unsigned long len = strlen(words[w]);
+        int lmax;
+        if (len >= nbWeights)
+            len = nbWeights - 1;
+        lmax = weights[len];
+        total += (unsigned)lmax;
+    }
+    g_distribCount = total;
+    assert(g_distribCount <= DISTRIB_SIZE_MAX);
+}
+
+static void init_word_distrib(
+        const char* words[],
+        size_t nbWords,
+        const int* weights,
+        unsigned long nbWeights)
+{
+    size_t w, d = 0;
+    countFreqs(words, nbWords, weights, nbWeights);
+    for (w = 0; w < nbWords; w++) {
+        unsigned long len = strlen(words[w]);
+        int l, lmax;
+        if (len >= nbWeights)
+            len = nbWeights - 1;
+        lmax = weights[len];
+        for (l = 0; l < lmax; l++) {
+            g_distrib[d++] = (int)w;
+        }
+    }
+}
 
 /* Note: this unit only works when invoked sequentially.
  * No concurrent access is allowed */
@@ -166,8 +193,8 @@ static void generateSentence(int nbWords)
     const char* endSep = qmark ? "? " : ". ";
     int i;
     for (i = 0; i < nbWords; i++) {
-        int const wordID       = distrib[LOREM_rand(distribCount)];
-        const char* const word = words[wordID];
+        int const wordID       = g_distrib[LOREM_rand(g_distribCount)];
+        const char* const word = kWords[wordID];
         const char* sep        = " ";
         if (i == commaPos)
             sep = ", ";
@@ -200,7 +227,7 @@ static void generateFirstSentence(void)
 {
     int i;
     for (i = 0; i < 18; i++) {
-        const char* word      = words[i];
+        const char* word      = kWords[i];
         const char* separator = " ";
         if (i == 4)
             separator = ", ";
@@ -208,7 +235,7 @@ static void generateFirstSentence(void)
             separator = ", ";
         generateWord(word, separator, i == 0);
     }
-    generateWord(words[18], ". ", 0);
+    generateWord(kWords[18], ". ", 0);
 }
 
 size_t
@@ -219,6 +246,10 @@ LOREM_genBlock(void* buffer, size_t size, unsigned seed, int first, int fill)
     g_maxChars = size;
     g_nbChars  = 0;
     g_randRoot = seed;
+    if (g_distribCount == 0) {
+        init_word_distrib(kWords, kNbWords, kWeights, kNbWeights);
+    }
+
     if (first) {
         generateFirstSentence();
     }

From 7003c9905e0c80aafe00ef485e586f859707c04c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 13:27:36 -0800
Subject: [PATCH 194/937] increase word dictionary

for higher variety of messages.
Now, level 5 compresses better than level 4 (by a hair).
---
 programs/lorem.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)

diff --git a/programs/lorem.c b/programs/lorem.c
index 49408b5a1..2fb977b07 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -73,7 +73,23 @@ static const char* kWords[] = {
     "aliquid",      "ex",         "ea",          "commodi",      "consequatur",
     "autem",        "eum",        "iure",        "voluptate",    "esse",
     "quam",         "nihil",      "molestiae",   "illum",        "fugiat",
-    "quo",          "pariatur"
+    "quo",          "pariatur",   "vero",        "accusamus",    "iusto",
+    "dignissimos",  "ducimus",    "blanditiis",  "praesentium",  "voluptatum",
+    "deleniti",     "atque",      "corrupti",    "quos",         "quas",
+    "molestias",    "excepturi",  "sint",        "occaecati",    "cupiditate",
+    "provident",    "similique",  "culpa",       "officia",      "deserunt",
+    "mollitia",     "animi",      "laborum",     "dolorum",      "fuga",
+    "harum",        "quidem",     "rerum",       "facilis",      "expedita",
+    "distinctio",   "libero",     "tempore",     "cum",          "soluta",
+    "nobis",        "eligendi",   "optio",       "cumque",       "impedit",
+    "minus",        "quod",       "maxime",      "placeat",      "facere",
+    "possimus",     "assumenda",  "repellendus", "temporibus",   "quibusdam",
+    "officiis",     "debitis",    "saepe",       "eveniet",      "voluptates",
+    "repudiandae",  "recusandae", "itaque",      "earum",        "hic",
+    "tenetur",      "sapiente",   "delectus",    "reiciendis",   "cillum",
+    "maiores",      "alias",      "perferendis", "doloribus",    "asperiores",
+    "repellat",     "minim",      "nostrud",     "exercitation", "ullamco",
+    "laboris",      "aliquip",    "duis",        "aute",         "irure",
 };
 static const unsigned kNbWords = sizeof(kWords) / sizeof(kWords[0]);
 
@@ -82,7 +98,7 @@ static const unsigned kNbWords = sizeof(kWords) / sizeof(kWords[0]);
 static const int kWeights[]      = { 0, 8, 6, 4, 3, 2 };
 static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
 
-#define DISTRIB_SIZE_MAX 500
+#define DISTRIB_SIZE_MAX 650
 static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
 static unsigned g_distribCount         = 0;
 
@@ -210,7 +226,7 @@ static void generateParagraph(int nbSentences)
 {
     int i;
     for (i = 0; i < nbSentences; i++) {
-        int wordsPerSentence = about(10);
+        int wordsPerSentence = about(11);
         generateSentence(wordsPerSentence);
     }
     if (g_nbChars < g_maxChars) {

From 83598aa106ba0edaa8b449b2fe5d63773eeebc4e Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 15:24:25 -0800
Subject: [PATCH 195/937] datagen generates lorem ipsum by default

---
 programs/lorem.c   |  10 +--
 tests/Makefile     |   2 +-
 tests/datagencli.c | 192 +++++++++++++++++++++++++--------------------
 tests/loremOut.c   |  50 ++++++++++++
 tests/loremOut.h   |  15 ++++
 5 files changed, 177 insertions(+), 92 deletions(-)
 create mode 100644 tests/loremOut.c
 create mode 100644 tests/loremOut.h

diff --git a/programs/lorem.c b/programs/lorem.c
index 2fb977b07..56e229058 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -23,11 +23,11 @@
  * and lacks a regularity more representative of text.
  *
  * The compression ratio achievable on the generated lorem ipsum
- * is still a bit too good, presumably because the dictionary is too small.
- * It would be possible to create some more complex scheme,
- * notably by enlarging the dictionary with a word generator,
- * and adding grammatical rules (composition) and syntax rules.
- * But that's probably overkill for the intended goal.
+ * is still a bit too good, presumably because the dictionary is a bit too
+ * small. It would be possible to create some more complex scheme, notably by
+ * enlarging the dictionary with a word generator, and adding grammatical rules
+ * (composition) and syntax rules. But that's probably overkill for the intended
+ * goal.
  */
 
 #include "lorem.h"
diff --git a/tests/Makefile b/tests/Makefile
index 35be1039b..ed7638b74 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -206,7 +206,7 @@ paramgrill : LDLIBS += -lm
 paramgrill : $(ZSTD_FILES) $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(PRGDIR)/benchzstd.c $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c paramgrill.c
 
 CLEAN += datagen
-datagen : $(PRGDIR)/datagen.c datagencli.c
+datagen : $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c loremOut.c datagencli.c
 	$(LINK.c) $^ -o $@$(EXT)
 
 CLEAN += roundTripCrash
diff --git a/tests/datagencli.c b/tests/datagencli.c
index 09ec5e9ae..b30209953 100644
--- a/tests/datagencli.c
+++ b/tests/datagencli.c
@@ -8,122 +8,142 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
+/*-************************************
+ *  Dependencies
+ **************************************/
+#include     /* fprintf, stderr */
+#include "datagen.h"  /* RDG_generate */
+#include "loremOut.h" /* LOREM_genOut */
+#include "util.h"     /* Compiler options */
 
 /*-************************************
-*  Dependencies
-**************************************/
-#include "util.h"      /* Compiler options */
-#include      /* fprintf, stderr */
-#include "datagen.h"   /* RDG_generate */
-
-
-/*-************************************
-*  Constants
-**************************************/
-#define KB *(1 <<10)
-#define MB *(1 <<20)
-#define GB *(1U<<30)
+ *  Constants
+ **************************************/
+#define KB *(1 << 10)
+#define MB *(1 << 20)
+#define GB *(1U << 30)
 
 #define SIZE_DEFAULT ((64 KB) + 1)
 #define SEED_DEFAULT 0
-#define COMPRESSIBILITY_DEFAULT 50
-
+#define COMPRESSIBILITY_DEFAULT 9999
 
 /*-************************************
-*  Macros
-**************************************/
-#define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
-#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+ *  Macros
+ **************************************/
+#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
+#define DISPLAYLEVEL(l, ...)  \
+    if (displayLevel >= l) {  \
+        DISPLAY(__VA_ARGS__); \
+    }
 static unsigned displayLevel = 2;
 
-
 /*-*******************************************************
-*  Command line
-*********************************************************/
+ *  Command line
+ *********************************************************/
 static int usage(const char* programName)
 {
-    DISPLAY( "Compressible data generator\n");
-    DISPLAY( "Usage :\n");
-    DISPLAY( "      %s [args]\n", programName);
-    DISPLAY( "\n");
-    DISPLAY( "Arguments :\n");
-    DISPLAY( " -g#    : generate # data (default:%i)\n", SIZE_DEFAULT);
-    DISPLAY( " -s#    : Select seed (default:%i)\n", SEED_DEFAULT);
-    DISPLAY( " -P#    : Select compressibility in %% (default:%i%%)\n",
-                        COMPRESSIBILITY_DEFAULT);
-    DISPLAY( " -h     : display help and exit\n");
+    DISPLAY("Compressible data generator\n");
+    DISPLAY("Usage :\n");
+    DISPLAY("      %s [args]\n", programName);
+    DISPLAY("\n");
+    DISPLAY("Arguments :\n");
+    DISPLAY(" -g#    : generate # data (default:%i)\n", SIZE_DEFAULT);
+    DISPLAY(" -s#    : Select seed (default:%i)\n", SEED_DEFAULT);
+    DISPLAY(" -P#    : Select compressibility in %% (range [0-100])\n");
+    DISPLAY(" -h     : display help and exit\n");
     return 0;
 }
 
-
 int main(int argc, const char** argv)
 {
-    unsigned probaU32 = COMPRESSIBILITY_DEFAULT;
-    double litProba = 0.0;
-    U64 size = SIZE_DEFAULT;
-    U32 seed = SEED_DEFAULT;
+    unsigned probaU32             = COMPRESSIBILITY_DEFAULT;
+    double litProba               = 0.0;
+    U64 size                      = SIZE_DEFAULT;
+    U32 seed                      = SEED_DEFAULT;
     const char* const programName = argv[0];
 
     int argNb;
-    for(argNb=1; argNb='0') && (*argument<='9'))
-                        size *= 10, size += *argument++ - '0';
-                    if (*argument=='K') { size <<= 10; argument++; }
-                    if (*argument=='M') { size <<= 20; argument++; }
-                    if (*argument=='G') { size <<= 30; argument++; }
-                    if (*argument=='B') { argument++; }
-                    break;
-                case 's':
-                    argument++;
-                    seed=0;
-                    while ((*argument>='0') && (*argument<='9'))
-                        seed *= 10, seed += *argument++ - '0';
-                    break;
-                case 'P':
-                    argument++;
-                    probaU32 = 0;
-                    while ((*argument>='0') && (*argument<='9'))
-                        probaU32 *= 10, probaU32 += *argument++ - '0';
-                    if (probaU32>100) probaU32 = 100;
-                    break;
-                case 'L':   /* hidden argument : Literal distribution probability */
-                    argument++;
-                    litProba=0.;
-                    while ((*argument>='0') && (*argument<='9'))
-                        litProba *= 10, litProba += *argument++ - '0';
-                    if (litProba>100.) litProba=100.;
-                    litProba /= 100.;
-                    break;
-                case 'v':
-                    displayLevel = 4;
-                    argument++;
-                    break;
-                default:
-                    return usage(programName);
+            while (*argument != 0) {
+                switch (*argument) {
+                    case 'h':
+                        return usage(programName);
+                    case 'g':
+                        argument++;
+                        size = 0;
+                        while ((*argument >= '0') && (*argument <= '9'))
+                            size *= 10, size += (U64)(*argument++ - '0');
+                        if (*argument == 'K') {
+                            size <<= 10;
+                            argument++;
+                        }
+                        if (*argument == 'M') {
+                            size <<= 20;
+                            argument++;
+                        }
+                        if (*argument == 'G') {
+                            size <<= 30;
+                            argument++;
+                        }
+                        if (*argument == 'B') {
+                            argument++;
+                        }
+                        break;
+                    case 's':
+                        argument++;
+                        seed = 0;
+                        while ((*argument >= '0') && (*argument <= '9'))
+                            seed *= 10, seed += (U32)(*argument++ - '0');
+                        break;
+                    case 'P':
+                        argument++;
+                        probaU32 = 0;
+                        while ((*argument >= '0') && (*argument <= '9'))
+                            probaU32 *= 10,
+                                    probaU32 += (U32)(*argument++ - '0');
+                        if (probaU32 > 100)
+                            probaU32 = 100;
+                        break;
+                    case 'L': /* hidden argument : Literal distribution
+                                 probability */
+                        argument++;
+                        litProba = 0.;
+                        while ((*argument >= '0') && (*argument <= '9'))
+                            litProba *= 10, litProba += *argument++ - '0';
+                        if (litProba > 100.)
+                            litProba = 100.;
+                        litProba /= 100.;
+                        break;
+                    case 'v':
+                        displayLevel = 4;
+                        argument++;
+                        break;
+                    default:
+                        return usage(programName);
                 }
-    }   }   }   /* for(argNb=1; argNb 4 GB).
+ * Note that, beyond 1 paragraph, this generator produces
+ * a different content than LOREM_genBuffer (even when using same seed).
+ */
+
+#include "loremOut.h"
+#include 
+#include 
+#include "lorem.h"    /* LOREM_genBlock */
+#include "platform.h" /* Compiler options, SET_BINARY_MODE */
+
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#define LOREM_BLOCKSIZE (1 << 10)
+void LOREM_genOut(unsigned long long size, unsigned seed)
+{
+    char buff[LOREM_BLOCKSIZE] = { 0 };
+    unsigned long long total   = 0;
+    size_t genBlockSize        = (size_t)MIN(size, LOREM_BLOCKSIZE);
+
+    /* init */
+    SET_BINARY_MODE(stdout);
+
+    /* Generate Ipsum text, one paragraph at a time */
+    while (total < size) {
+        size_t generated =
+                LOREM_genBlock(buff, genBlockSize, seed++, total == 0, 0);
+        assert(generated <= genBlockSize);
+        total += generated;
+        assert(total <= size);
+        fwrite(buff,
+               1,
+               generated,
+               stdout); /* note: should check potential write error */
+        if (size - total < genBlockSize)
+            genBlockSize = (size_t)(size - total);
+    }
+    assert(total == size);
+}
diff --git a/tests/loremOut.h b/tests/loremOut.h
new file mode 100644
index 000000000..3a32e1161
--- /dev/null
+++ b/tests/loremOut.h
@@ -0,0 +1,15 @@
+/*
+ * 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.
+ */
+
+/* LOREM_genOut():
+ * Generate @size bytes of compressible data using lorem ipsum generator into
+ * stdout.
+ */
+void LOREM_genOut(unsigned long long size, unsigned seed);

From 7a225c0c465149f1a72811dab669985b6ea5e5f4 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 15:47:09 -0800
Subject: [PATCH 196/937] internal benchmark: can select size of generated
 synthetic sample

---
 programs/benchzstd.c | 1121 ++++++++++++++++++++++++++----------------
 programs/lorem.c     |   12 +-
 2 files changed, 710 insertions(+), 423 deletions(-)

diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index b3af4c332..56af23d33 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -8,198 +8,230 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
-
 /* **************************************
-*  Tuning parameters
-****************************************/
-#ifndef BMK_TIMETEST_DEFAULT_S   /* default minimum time per test */
-# define BMK_TIMETEST_DEFAULT_S 3
+ *  Tuning parameters
+ ****************************************/
+#ifndef BMK_TIMETEST_DEFAULT_S /* default minimum time per test */
+#    define BMK_TIMETEST_DEFAULT_S 3
 #endif
 
-
 /* *************************************
-*  Includes
-***************************************/
-#include "platform.h"    /* Large Files support */
-#include "util.h"        /* UTIL_getFileSize, UTIL_sleep */
-#include       /* malloc, free */
-#include       /* memset, strerror */
-#include        /* fprintf, fopen */
+ *  Includes
+ ***************************************/
+#include  /* assert */
 #include 
-#include       /* assert */
+#include     /* fprintf, fopen */
+#include    /* malloc, free */
+#include    /* memset, strerror */
+#include "platform.h" /* Large Files support */
+#include "util.h"     /* UTIL_getFileSize, UTIL_sleep */
 
-#include "timefn.h"      /* UTIL_time_t */
-#include "benchfn.h"
 #include "../lib/common/mem.h"
+#include "benchfn.h"
+#include "timefn.h" /* UTIL_time_t */
 #ifndef ZSTD_STATIC_LINKING_ONLY
-# define ZSTD_STATIC_LINKING_ONLY
+#    define ZSTD_STATIC_LINKING_ONLY
 #endif
 #include "../lib/zstd.h"
-#include "datagen.h"     /* RDG_genBuffer */
-#include "lorem.h"       /* LOREM_genBuffer */
+#include "datagen.h" /* RDG_genBuffer */
+#include "lorem.h"   /* LOREM_genBuffer */
 #ifndef XXH_INLINE_ALL
-# define XXH_INLINE_ALL
+#    define XXH_INLINE_ALL
 #endif
 #include "../lib/common/xxhash.h"
-#include "benchzstd.h"
 #include "../lib/zstd_errors.h"
-
+#include "benchzstd.h"
 
 /* *************************************
-*  Constants
-***************************************/
+ *  Constants
+ ***************************************/
 #ifndef ZSTD_GIT_COMMIT
-#  define ZSTD_GIT_COMMIT_STRING ""
+#    define ZSTD_GIT_COMMIT_STRING ""
 #else
-#  define ZSTD_GIT_COMMIT_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_GIT_COMMIT)
+#    define ZSTD_GIT_COMMIT_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_GIT_COMMIT)
 #endif
 
-#define TIMELOOP_MICROSEC     (1*1000000ULL) /* 1 second */
-#define TIMELOOP_NANOSEC      (1*1000000000ULL) /* 1 second */
-#define ACTIVEPERIOD_MICROSEC (70*TIMELOOP_MICROSEC) /* 70 seconds */
-#define COOLPERIOD_SEC        10
+#define TIMELOOP_MICROSEC (1 * 1000000ULL)             /* 1 second */
+#define TIMELOOP_NANOSEC (1 * 1000000000ULL)           /* 1 second */
+#define ACTIVEPERIOD_MICROSEC (70 * TIMELOOP_MICROSEC) /* 70 seconds */
+#define COOLPERIOD_SEC 10
 
-#define KB *(1 <<10)
-#define MB *(1 <<20)
-#define GB *(1U<<30)
+#define KB *(1 << 10)
+#define MB *(1 << 20)
+#define GB *(1U << 30)
 
 #define BMK_RUNTEST_DEFAULT_MS 1000
 
-static const size_t maxMemory = (sizeof(size_t)==4)  ?
-                    /* 32-bit */ (2 GB - 64 MB) :
-                    /* 64-bit */ (size_t)(1ULL << ((sizeof(size_t)*8)-31));
-
+static const size_t maxMemory = (sizeof(size_t) == 4)
+        ?
+        /* 32-bit */ (2 GB - 64 MB)
+        :
+        /* 64-bit */ (size_t)(1ULL << ((sizeof(size_t) * 8) - 31));
 
 /* *************************************
-*  console display
-***************************************/
-#define DISPLAY(...)         { fprintf(stderr, __VA_ARGS__); fflush(NULL); }
-#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
-/* 0 : no display;   1: errors;   2 : + result + interaction + warnings;   3 : + progression;   4 : + information */
-#define OUTPUT(...)          { fprintf(stdout, __VA_ARGS__); fflush(NULL); }
-#define OUTPUTLEVEL(l, ...)  if (displayLevel>=l) { OUTPUT(__VA_ARGS__); }
-
+ *  console display
+ ***************************************/
+#define DISPLAY(...)                  \
+    {                                 \
+        fprintf(stderr, __VA_ARGS__); \
+        fflush(NULL);                 \
+    }
+#define DISPLAYLEVEL(l, ...)  \
+    if (displayLevel >= l) {  \
+        DISPLAY(__VA_ARGS__); \
+    }
+/* 0 : no display;   1: errors;   2 : + result + interaction + warnings;   3 : +
+ * progression;   4 : + information */
+#define OUTPUT(...)                   \
+    {                                 \
+        fprintf(stdout, __VA_ARGS__); \
+        fflush(NULL);                 \
+    }
+#define OUTPUTLEVEL(l, ...)  \
+    if (displayLevel >= l) { \
+        OUTPUT(__VA_ARGS__); \
+    }
 
 /* *************************************
-*  Exceptions
-***************************************/
+ *  Exceptions
+ ***************************************/
 #ifndef DEBUG
-#  define DEBUG 0
+#    define DEBUG 0
 #endif
-#define DEBUGOUTPUT(...) { if (DEBUG) DISPLAY(__VA_ARGS__); }
+#define DEBUGOUTPUT(...)          \
+    {                             \
+        if (DEBUG)                \
+            DISPLAY(__VA_ARGS__); \
+    }
 
-#define RETURN_ERROR_INT(errorNum, ...)  {               \
-    DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__);    \
-    DISPLAYLEVEL(1, "Error %i : ", errorNum);         \
-    DISPLAYLEVEL(1, __VA_ARGS__);                     \
-    DISPLAYLEVEL(1, " \n");                           \
-    return errorNum;                                  \
-}
+#define RETURN_ERROR_INT(errorNum, ...)                \
+    {                                                  \
+        DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
+        DISPLAYLEVEL(1, "Error %i : ", errorNum);      \
+        DISPLAYLEVEL(1, __VA_ARGS__);                  \
+        DISPLAYLEVEL(1, " \n");                        \
+        return errorNum;                               \
+    }
 
-#define CHECK_Z(zf) {              \
-    size_t const zerr = zf;        \
-    if (ZSTD_isError(zerr)) {      \
-        DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__);  \
-        DISPLAY("Error : ");       \
-        DISPLAY("%s failed : %s",  \
-                #zf, ZSTD_getErrorName(zerr));   \
-        DISPLAY(" \n");            \
-        exit(1);                   \
-    }                              \
-}
-
-#define RETURN_ERROR(errorNum, retType, ...)  {       \
-    retType r;                                        \
-    memset(&r, 0, sizeof(retType));                   \
-    DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__);    \
-    DISPLAYLEVEL(1, "Error %i : ", errorNum);         \
-    DISPLAYLEVEL(1, __VA_ARGS__);                     \
-    DISPLAYLEVEL(1, " \n");                           \
-    r.tag = errorNum;                                 \
-    return r;                                         \
-}
+#define CHECK_Z(zf)                                                  \
+    {                                                                \
+        size_t const zerr = zf;                                      \
+        if (ZSTD_isError(zerr)) {                                    \
+            DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__);           \
+            DISPLAY("Error : ");                                     \
+            DISPLAY("%s failed : %s", #zf, ZSTD_getErrorName(zerr)); \
+            DISPLAY(" \n");                                          \
+            exit(1);                                                 \
+        }                                                            \
+    }
 
+#define RETURN_ERROR(errorNum, retType, ...)           \
+    {                                                  \
+        retType r;                                     \
+        memset(&r, 0, sizeof(retType));                \
+        DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
+        DISPLAYLEVEL(1, "Error %i : ", errorNum);      \
+        DISPLAYLEVEL(1, __VA_ARGS__);                  \
+        DISPLAYLEVEL(1, " \n");                        \
+        r.tag = errorNum;                              \
+        return r;                                      \
+    }
 
 /* *************************************
-*  Benchmark Parameters
-***************************************/
+ *  Benchmark Parameters
+ ***************************************/
 
-BMK_advancedParams_t BMK_initAdvancedParams(void) {
+BMK_advancedParams_t BMK_initAdvancedParams(void)
+{
     BMK_advancedParams_t const res = {
-        BMK_both, /* mode */
+        BMK_both,               /* mode */
         BMK_TIMETEST_DEFAULT_S, /* nbSeconds */
-        0, /* blockSize */
-        0, /* nbWorkers */
-        0, /* realTime */
-        0, /* additionalParam */
-        0, /* ldmFlag */
-        0, /* ldmMinMatch */
-        0, /* ldmHashLog */
-        0, /* ldmBuckSizeLog */
-        0,  /* ldmHashRateLog */
-        ZSTD_ps_auto, /* literalCompressionMode */
-        0 /* useRowMatchFinder */
+        0,                      /* blockSize */
+        0,                      /* nbWorkers */
+        0,                      /* realTime */
+        0,                      /* additionalParam */
+        0,                      /* ldmFlag */
+        0,                      /* ldmMinMatch */
+        0,                      /* ldmHashLog */
+        0,                      /* ldmBuckSizeLog */
+        0,                      /* ldmHashRateLog */
+        ZSTD_ps_auto,           /* literalCompressionMode */
+        0                       /* useRowMatchFinder */
     };
     return res;
 }
 
-
 /* ********************************************************
-*  Bench functions
-**********************************************************/
+ *  Bench functions
+ **********************************************************/
 typedef struct {
     const void* srcPtr;
     size_t srcSize;
-    void*  cPtr;
+    void* cPtr;
     size_t cRoom;
     size_t cSize;
-    void*  resPtr;
+    void* resPtr;
     size_t resSize;
 } blockParam_t;
 
 #undef MIN
 #undef MAX
-#define MIN(a,b)    ((a) < (b) ? (a) : (b))
-#define MAX(a,b)    ((a) > (b) ? (a) : (b))
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#define MAX(a, b) ((a) > (b) ? (a) : (b))
 
-static void
-BMK_initCCtx(ZSTD_CCtx* ctx,
-            const void* dictBuffer, size_t dictBufferSize,
-            int cLevel,
-            const ZSTD_compressionParameters* comprParams,
-            const BMK_advancedParams_t* adv)
+static void BMK_initCCtx(
+        ZSTD_CCtx* ctx,
+        const void* dictBuffer,
+        size_t dictBufferSize,
+        int cLevel,
+        const ZSTD_compressionParameters* comprParams,
+        const BMK_advancedParams_t* adv)
 {
     ZSTD_CCtx_reset(ctx, ZSTD_reset_session_and_parameters);
-    if (adv->nbWorkers==1) {
+    if (adv->nbWorkers == 1) {
         CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, 0));
     } else {
         CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, adv->nbWorkers));
     }
     CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_compressionLevel, cLevel));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_useRowMatchFinder, adv->useRowMatchFinder));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_enableLongDistanceMatching, adv->ldmFlag));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_useRowMatchFinder, adv->useRowMatchFinder));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_enableLongDistanceMatching, adv->ldmFlag));
     CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmMinMatch, adv->ldmMinMatch));
     CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashLog, adv->ldmHashLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmBucketSizeLog, adv->ldmBucketSizeLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_ldmHashRateLog, adv->ldmHashRateLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_windowLog, (int)comprParams->windowLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_hashLog, (int)comprParams->hashLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_chainLog, (int)comprParams->chainLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_searchLog, (int)comprParams->searchLog));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_minMatch, (int)comprParams->minMatch));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_targetLength, (int)comprParams->targetLength));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_literalCompressionMode, (int)adv->literalCompressionMode));
-    CHECK_Z(ZSTD_CCtx_setParameter(ctx, ZSTD_c_strategy, (int)comprParams->strategy));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_ldmBucketSizeLog, adv->ldmBucketSizeLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_ldmHashRateLog, adv->ldmHashRateLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_windowLog, (int)comprParams->windowLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_hashLog, (int)comprParams->hashLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_chainLog, (int)comprParams->chainLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_searchLog, (int)comprParams->searchLog));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_minMatch, (int)comprParams->minMatch));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_targetLength, (int)comprParams->targetLength));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx,
+            ZSTD_c_literalCompressionMode,
+            (int)adv->literalCompressionMode));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_strategy, (int)comprParams->strategy));
     CHECK_Z(ZSTD_CCtx_loadDictionary(ctx, dictBuffer, dictBufferSize));
 }
 
-static void BMK_initDCtx(ZSTD_DCtx* dctx,
-    const void* dictBuffer, size_t dictBufferSize) {
+static void
+BMK_initDCtx(ZSTD_DCtx* dctx, const void* dictBuffer, size_t dictBufferSize)
+{
     CHECK_Z(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters));
     CHECK_Z(ZSTD_DCtx_loadDictionary(dctx, dictBuffer, dictBufferSize));
 }
 
-
 typedef struct {
     ZSTD_CCtx* cctx;
     const void* dictBuffer;
@@ -209,9 +241,16 @@ typedef struct {
     const BMK_advancedParams_t* adv;
 } BMK_initCCtxArgs;
 
-static size_t local_initCCtx(void* payload) {
+static size_t local_initCCtx(void* payload)
+{
     BMK_initCCtxArgs* ag = (BMK_initCCtxArgs*)payload;
-    BMK_initCCtx(ag->cctx, ag->dictBuffer, ag->dictBufferSize, ag->cLevel, ag->comprParams, ag->adv);
+    BMK_initCCtx(
+            ag->cctx,
+            ag->dictBuffer,
+            ag->dictBufferSize,
+            ag->cLevel,
+            ag->comprParams,
+            ag->adv);
     return 0;
 }
 
@@ -221,18 +260,20 @@ typedef struct {
     size_t dictBufferSize;
 } BMK_initDCtxArgs;
 
-static size_t local_initDCtx(void* payload) {
+static size_t local_initDCtx(void* payload)
+{
     BMK_initDCtxArgs* ag = (BMK_initDCtxArgs*)payload;
     BMK_initDCtx(ag->dctx, ag->dictBuffer, ag->dictBufferSize);
     return 0;
 }
 
-
 /* `addArgs` is the context */
 static size_t local_defaultCompress(
-                    const void* srcBuffer, size_t srcSize,
-                    void* dstBuffer, size_t dstSize,
-                    void* addArgs)
+        const void* srcBuffer,
+        size_t srcSize,
+        void* dstBuffer,
+        size_t dstSize,
+        void* addArgs)
 {
     ZSTD_CCtx* const cctx = (ZSTD_CCtx*)addArgs;
     return ZSTD_compress2(cctx, dstBuffer, dstSize, srcBuffer, srcSize);
@@ -240,18 +281,24 @@ static size_t local_defaultCompress(
 
 /* `addArgs` is the context */
 static size_t local_defaultDecompress(
-                    const void* srcBuffer, size_t srcSize,
-                    void* dstBuffer, size_t dstCapacity,
-                    void* addArgs)
+        const void* srcBuffer,
+        size_t srcSize,
+        void* dstBuffer,
+        size_t dstCapacity,
+        void* addArgs)
 {
-    size_t moreToFlush = 1;
+    size_t moreToFlush    = 1;
     ZSTD_DCtx* const dctx = (ZSTD_DCtx*)addArgs;
     ZSTD_inBuffer in;
     ZSTD_outBuffer out;
-    in.src = srcBuffer; in.size = srcSize; in.pos = 0;
-    out.dst = dstBuffer; out.size = dstCapacity; out.pos = 0;
+    in.src   = srcBuffer;
+    in.size  = srcSize;
+    in.pos   = 0;
+    out.dst  = dstBuffer;
+    out.size = dstCapacity;
+    out.pos  = 0;
     while (moreToFlush) {
-        if(out.pos == out.size) {
+        if (out.pos == out.size) {
             return (size_t)-ZSTD_error_dstSize_tooSmall;
         }
         moreToFlush = ZSTD_decompressStream(dctx, &out, &in);
@@ -260,10 +307,8 @@ static size_t local_defaultDecompress(
         }
     }
     return out.pos;
-
 }
 
-
 /* ================================================================= */
 /*      Benchmark Zstandard, mem-to-mem scenarios                    */
 /* ================================================================= */
@@ -287,104 +332,145 @@ static BMK_benchOutcome_t BMK_benchOutcome_error(void)
     return b;
 }
 
-static BMK_benchOutcome_t BMK_benchOutcome_setValidResult(BMK_benchResult_t result)
+static BMK_benchOutcome_t BMK_benchOutcome_setValidResult(
+        BMK_benchResult_t result)
 {
     BMK_benchOutcome_t b;
-    b.tag = 0;
+    b.tag                         = 0;
     b.internal_never_use_directly = result;
     return b;
 }
 
-
 /* benchMem with no allocation */
-static BMK_benchOutcome_t
-BMK_benchMemAdvancedNoAlloc(
-                    const void** srcPtrs, size_t* srcSizes,
-                    void** cPtrs, size_t* cCapacities, size_t* cSizes,
-                    void** resPtrs, size_t* resSizes,
-                    void** resultBufferPtr, void* compressedBuffer,
-                    size_t maxCompressedSize,
-                    BMK_timedFnState_t* timeStateCompress,
-                    BMK_timedFnState_t* timeStateDecompress,
+static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc(
+        const void** srcPtrs,
+        size_t* srcSizes,
+        void** cPtrs,
+        size_t* cCapacities,
+        size_t* cSizes,
+        void** resPtrs,
+        size_t* resSizes,
+        void** resultBufferPtr,
+        void* compressedBuffer,
+        size_t maxCompressedSize,
+        BMK_timedFnState_t* timeStateCompress,
+        BMK_timedFnState_t* timeStateDecompress,
 
-                    const void* srcBuffer, size_t srcSize,
-                    const size_t* fileSizes, unsigned nbFiles,
-                    const int cLevel,
-                    const ZSTD_compressionParameters* comprParams,
-                    const void* dictBuffer, size_t dictBufferSize,
-                    ZSTD_CCtx* cctx, ZSTD_DCtx* dctx,
-                    int displayLevel, const char* displayName,
-                    const BMK_advancedParams_t* adv)
+        const void* srcBuffer,
+        size_t srcSize,
+        const size_t* fileSizes,
+        unsigned nbFiles,
+        const int cLevel,
+        const ZSTD_compressionParameters* comprParams,
+        const void* dictBuffer,
+        size_t dictBufferSize,
+        ZSTD_CCtx* cctx,
+        ZSTD_DCtx* dctx,
+        int displayLevel,
+        const char* displayName,
+        const BMK_advancedParams_t* adv)
 {
-    size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize);  /* avoid div by 0 */
+    size_t const blockSize =
+            ((adv->blockSize >= 32 && (adv->mode != BMK_decodeOnly))
+                     ? adv->blockSize
+                     : srcSize)
+            + (!srcSize); /* avoid div by 0 */
     BMK_benchResult_t benchResult;
     size_t const loadedCompressedSize = srcSize;
-    size_t cSize = 0;
-    double ratio = 0.;
+    size_t cSize                      = 0;
+    double ratio                      = 0.;
     U32 nbBlocks;
 
-    assert(cctx != NULL); assert(dctx != NULL);
+    assert(cctx != NULL);
+    assert(dctx != NULL);
 
     /* init */
     memset(&benchResult, 0, sizeof(benchResult));
-    if (strlen(displayName)>17) displayName += strlen(displayName) - 17;   /* display last 17 characters */
+    if (strlen(displayName) > 17)
+        displayName +=
+                strlen(displayName) - 17; /* display last 17 characters */
     if (adv->mode == BMK_decodeOnly) {
         /* benchmark only decompression : source must be already compressed */
         const char* srcPtr = (const char*)srcBuffer;
-        U64 totalDSize64 = 0;
+        U64 totalDSize64   = 0;
         U32 fileNb;
-        for (fileNb=0; fileNb decodedSize) {  /* size_t overflow */
-                RETURN_ERROR(32, BMK_benchOutcome_t, "decompressed size is too large for local system");
+            if (totalDSize64 > decodedSize) { /* size_t overflow */
+                RETURN_ERROR(
+                        32,
+                        BMK_benchOutcome_t,
+                        "decompressed size is too large for local system");
             }
             *resultBufferPtr = malloc(decodedSize);
             if (!(*resultBufferPtr)) {
-                RETURN_ERROR(33, BMK_benchOutcome_t, "allocation error: not enough memory");
+                RETURN_ERROR(
+                        33,
+                        BMK_benchOutcome_t,
+                        "allocation error: not enough memory");
             }
-            cSize = srcSize;
+            cSize   = srcSize;
             srcSize = decodedSize;
-            ratio = (double)srcSize / (double)cSize;
+            ratio   = (double)srcSize / (double)cSize;
         }
     }
 
     /* Init data blocks  */
-    {   const char* srcPtr = (const char*)srcBuffer;
-        char* cPtr = (char*)compressedBuffer;
-        char* resPtr = (char*)(*resultBufferPtr);
+    {
+        const char* srcPtr = (const char*)srcBuffer;
+        char* cPtr         = (char*)compressedBuffer;
+        char* resPtr       = (char*)(*resultBufferPtr);
         U32 fileNb;
-        for (nbBlocks=0, fileNb=0; fileNbmode == BMK_decodeOnly) ? 1 : (U32)((remaining + (blockSize-1)) / blockSize);
-            U32 const blockEnd = nbBlocks + nbBlocksforThisFile;
-            for ( ; nbBlocksmode == BMK_decodeOnly)
+                    ? 1
+                    : (U32)((remaining + (blockSize - 1)) / blockSize);
+            U32 const blockEnd            = nbBlocks + nbBlocksforThisFile;
+            for (; nbBlocks < blockEnd; nbBlocks++) {
                 size_t const thisBlockSize = MIN(remaining, blockSize);
-                srcPtrs[nbBlocks] = srcPtr;
-                srcSizes[nbBlocks] = thisBlockSize;
-                cPtrs[nbBlocks] = cPtr;
-                cCapacities[nbBlocks] = (adv->mode == BMK_decodeOnly) ? thisBlockSize : ZSTD_compressBound(thisBlockSize);
-                resPtrs[nbBlocks] = resPtr;
-                resSizes[nbBlocks] = (adv->mode == BMK_decodeOnly) ? (size_t) ZSTD_findDecompressedSize(srcPtr, thisBlockSize) : thisBlockSize;
+                srcPtrs[nbBlocks]          = srcPtr;
+                srcSizes[nbBlocks]         = thisBlockSize;
+                cPtrs[nbBlocks]            = cPtr;
+                cCapacities[nbBlocks]      = (adv->mode == BMK_decodeOnly)
+                             ? thisBlockSize
+                             : ZSTD_compressBound(thisBlockSize);
+                resPtrs[nbBlocks]          = resPtr;
+                resSizes[nbBlocks]         = (adv->mode == BMK_decodeOnly)
+                                ? (size_t)ZSTD_findDecompressedSize(
+                                srcPtr, thisBlockSize)
+                                : thisBlockSize;
                 srcPtr += thisBlockSize;
                 cPtr += cCapacities[nbBlocks];
                 resPtr += thisBlockSize;
                 remaining -= thisBlockSize;
                 if (adv->mode == BMK_decodeOnly) {
-                    cSizes[nbBlocks] = thisBlockSize;
+                    cSizes[nbBlocks]  = thisBlockSize;
                     benchResult.cSize = thisBlockSize;
-    }   }   }   }
+                }
+            }
+        }
+    }
 
     /* warming up `compressedBuffer` */
     if (adv->mode == BMK_decodeOnly) {
@@ -394,236 +480,329 @@ BMK_benchMemAdvancedNoAlloc(
     }
 
     if (!UTIL_support_MT_measurements() && adv->nbWorkers > 1) {
-        OUTPUTLEVEL(2, "Warning : time measurements may be incorrect in multithreading mode... \n")
+        OUTPUTLEVEL(
+                2,
+                "Warning : time measurements may be incorrect in multithreading mode... \n")
     }
 
     /* Bench */
-    {   U64 const crcOrig = (adv->mode == BMK_decodeOnly) ? 0 : XXH64(srcBuffer, srcSize, 0);
-#       define NB_MARKS 4
+    {
+        U64 const crcOrig = (adv->mode == BMK_decodeOnly)
+                ? 0
+                : XXH64(srcBuffer, srcSize, 0);
+#define NB_MARKS 4
         const char* marks[NB_MARKS] = { " |", " /", " =", " \\" };
-        U32 markNb = 0;
-        int compressionCompleted = (adv->mode == BMK_decodeOnly);
-        int decompressionCompleted = (adv->mode == BMK_compressOnly);
+        U32 markNb                  = 0;
+        int compressionCompleted    = (adv->mode == BMK_decodeOnly);
+        int decompressionCompleted  = (adv->mode == BMK_compressOnly);
         BMK_benchParams_t cbp, dbp;
         BMK_initCCtxArgs cctxprep;
         BMK_initDCtxArgs dctxprep;
 
-        cbp.benchFn = local_defaultCompress;   /* ZSTD_compress2 */
-        cbp.benchPayload = cctx;
-        cbp.initFn = local_initCCtx;   /* BMK_initCCtx */
-        cbp.initPayload = &cctxprep;
-        cbp.errorFn = ZSTD_isError;
-        cbp.blockCount = nbBlocks;
-        cbp.srcBuffers = srcPtrs;
-        cbp.srcSizes = srcSizes;
-        cbp.dstBuffers = cPtrs;
+        cbp.benchFn       = local_defaultCompress; /* ZSTD_compress2 */
+        cbp.benchPayload  = cctx;
+        cbp.initFn        = local_initCCtx; /* BMK_initCCtx */
+        cbp.initPayload   = &cctxprep;
+        cbp.errorFn       = ZSTD_isError;
+        cbp.blockCount    = nbBlocks;
+        cbp.srcBuffers    = srcPtrs;
+        cbp.srcSizes      = srcSizes;
+        cbp.dstBuffers    = cPtrs;
         cbp.dstCapacities = cCapacities;
-        cbp.blockResults = cSizes;
+        cbp.blockResults  = cSizes;
 
-        cctxprep.cctx = cctx;
-        cctxprep.dictBuffer = dictBuffer;
+        cctxprep.cctx           = cctx;
+        cctxprep.dictBuffer     = dictBuffer;
         cctxprep.dictBufferSize = dictBufferSize;
-        cctxprep.cLevel = cLevel;
-        cctxprep.comprParams = comprParams;
-        cctxprep.adv = adv;
+        cctxprep.cLevel         = cLevel;
+        cctxprep.comprParams    = comprParams;
+        cctxprep.adv            = adv;
 
-        dbp.benchFn = local_defaultDecompress;
-        dbp.benchPayload = dctx;
-        dbp.initFn = local_initDCtx;
-        dbp.initPayload = &dctxprep;
-        dbp.errorFn = ZSTD_isError;
-        dbp.blockCount = nbBlocks;
-        dbp.srcBuffers = (const void* const *) cPtrs;
-        dbp.srcSizes = cSizes;
-        dbp.dstBuffers = resPtrs;
+        dbp.benchFn       = local_defaultDecompress;
+        dbp.benchPayload  = dctx;
+        dbp.initFn        = local_initDCtx;
+        dbp.initPayload   = &dctxprep;
+        dbp.errorFn       = ZSTD_isError;
+        dbp.blockCount    = nbBlocks;
+        dbp.srcBuffers    = (const void* const*)cPtrs;
+        dbp.srcSizes      = cSizes;
+        dbp.dstBuffers    = resPtrs;
         dbp.dstCapacities = resSizes;
-        dbp.blockResults = NULL;
+        dbp.blockResults  = NULL;
 
-        dctxprep.dctx = dctx;
-        dctxprep.dictBuffer = dictBuffer;
+        dctxprep.dctx           = dctx;
+        dctxprep.dictBuffer     = dictBuffer;
         dctxprep.dictBufferSize = dictBufferSize;
 
-        OUTPUTLEVEL(2, "\r%70s\r", "");   /* blank line */
+        OUTPUTLEVEL(2, "\r%70s\r", ""); /* blank line */
         assert(srcSize < UINT_MAX);
-        OUTPUTLEVEL(2, "%2s-%-17.17s :%10u -> \r", marks[markNb], displayName, (unsigned)srcSize);
+        OUTPUTLEVEL(
+                2,
+                "%2s-%-17.17s :%10u -> \r",
+                marks[markNb],
+                displayName,
+                (unsigned)srcSize);
 
         while (!(compressionCompleted && decompressionCompleted)) {
             if (!compressionCompleted) {
-                BMK_runOutcome_t const cOutcome = BMK_benchTimedFn( timeStateCompress, cbp);
+                BMK_runOutcome_t const cOutcome =
+                        BMK_benchTimedFn(timeStateCompress, cbp);
 
                 if (!BMK_isSuccessful_runOutcome(cOutcome)) {
                     RETURN_ERROR(30, BMK_benchOutcome_t, "compression error");
                 }
 
-                {   BMK_runTime_t const cResult = BMK_extract_runTime(cOutcome);
-                    cSize = cResult.sumOfReturn;
+                {
+                    BMK_runTime_t const cResult = BMK_extract_runTime(cOutcome);
+                    cSize                       = cResult.sumOfReturn;
                     ratio = (double)srcSize / (double)cSize;
-                    {   BMK_benchResult_t newResult;
-                        newResult.cSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / cResult.nanoSecPerRun);
+                    {
+                        BMK_benchResult_t newResult;
+                        newResult.cSpeed =
+                                (U64)((double)srcSize * TIMELOOP_NANOSEC
+                                      / cResult.nanoSecPerRun);
                         benchResult.cSize = cSize;
                         if (newResult.cSpeed > benchResult.cSpeed)
                             benchResult.cSpeed = newResult.cSpeed;
-                }   }
-
-                {   int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
-                    assert(cSize < UINT_MAX);
-                    OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s \r",
-                            marks[markNb], displayName,
-                            (unsigned)srcSize, (unsigned)cSize,
-                            ratioAccuracy, ratio,
-                            benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT);
+                    }
                 }
-                compressionCompleted = BMK_isCompleted_TimedFn(timeStateCompress);
+
+                {
+                    int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
+                    assert(cSize < UINT_MAX);
+                    OUTPUTLEVEL(
+                            2,
+                            "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s \r",
+                            marks[markNb],
+                            displayName,
+                            (unsigned)srcSize,
+                            (unsigned)cSize,
+                            ratioAccuracy,
+                            ratio,
+                            benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1,
+                            (double)benchResult.cSpeed / MB_UNIT);
+                }
+                compressionCompleted =
+                        BMK_isCompleted_TimedFn(timeStateCompress);
             }
 
-            if(!decompressionCompleted) {
-                BMK_runOutcome_t const dOutcome = BMK_benchTimedFn(timeStateDecompress, dbp);
+            if (!decompressionCompleted) {
+                BMK_runOutcome_t const dOutcome =
+                        BMK_benchTimedFn(timeStateDecompress, dbp);
 
-                if(!BMK_isSuccessful_runOutcome(dOutcome)) {
+                if (!BMK_isSuccessful_runOutcome(dOutcome)) {
                     RETURN_ERROR(30, BMK_benchOutcome_t, "decompression error");
                 }
 
-                {   BMK_runTime_t const dResult = BMK_extract_runTime(dOutcome);
-                    U64 const newDSpeed = (U64)((double)srcSize * TIMELOOP_NANOSEC / dResult.nanoSecPerRun);
+                {
+                    BMK_runTime_t const dResult = BMK_extract_runTime(dOutcome);
+                    U64 const newDSpeed =
+                            (U64)((double)srcSize * TIMELOOP_NANOSEC
+                                  / dResult.nanoSecPerRun);
                     if (newDSpeed > benchResult.dSpeed)
                         benchResult.dSpeed = newDSpeed;
                 }
 
-                {   int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
-                    OUTPUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s\r",
-                            marks[markNb], displayName,
-                            (unsigned)srcSize, (unsigned)cSize,
-                            ratioAccuracy, ratio,
-                            benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT,
+                {
+                    int const ratioAccuracy = (ratio < 10.) ? 3 : 2;
+                    OUTPUTLEVEL(
+                            2,
+                            "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s\r",
+                            marks[markNb],
+                            displayName,
+                            (unsigned)srcSize,
+                            (unsigned)cSize,
+                            ratioAccuracy,
+                            ratio,
+                            benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1,
+                            (double)benchResult.cSpeed / MB_UNIT,
                             (double)benchResult.dSpeed / MB_UNIT);
                 }
-                decompressionCompleted = BMK_isCompleted_TimedFn(timeStateDecompress);
+                decompressionCompleted =
+                        BMK_isCompleted_TimedFn(timeStateDecompress);
             }
-            markNb = (markNb+1) % NB_MARKS;
-        }   /* while (!(compressionCompleted && decompressionCompleted)) */
+            markNb = (markNb + 1) % NB_MARKS;
+        } /* while (!(compressionCompleted && decompressionCompleted)) */
 
         /* CRC Checking */
-        {   const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr);
-            U64 const crcCheck = XXH64(resultBuffer, srcSize, 0);
-            if ((adv->mode == BMK_both) && (crcOrig!=crcCheck)) {
+        {
+            const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr);
+            U64 const crcCheck       = XXH64(resultBuffer, srcSize, 0);
+            if ((adv->mode == BMK_both) && (crcOrig != crcCheck)) {
                 size_t u;
                 DISPLAY("!!! WARNING !!! %14s : Invalid Checksum : %x != %x   \n",
-                        displayName, (unsigned)crcOrig, (unsigned)crcCheck);
-                for (u=0; u u) break;
+                            if (bacc + srcSizes[segNb] > u)
+                                break;
                             bacc += srcSizes[segNb];
                         }
                         pos = (U32)(u - bacc);
                         bNb = pos / (128 KB);
-                        DISPLAY("(sample %u, block %u, pos %u) \n", segNb, bNb, pos);
-                        {   size_t const lowest = (u>5) ? 5 : u;
+                        DISPLAY("(sample %u, block %u, pos %u) \n",
+                                segNb,
+                                bNb,
+                                pos);
+                        {
+                            size_t const lowest = (u > 5) ? 5 : u;
                             size_t n;
                             DISPLAY("origin: ");
-                            for (n=lowest; n>0; n--)
-                                DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u-n]);
+                            for (n = lowest; n > 0; n--)
+                                DISPLAY("%02X ",
+                                        ((const BYTE*)srcBuffer)[u - n]);
                             DISPLAY(" :%02X:  ", ((const BYTE*)srcBuffer)[u]);
-                            for (n=1; n<3; n++)
-                                DISPLAY("%02X ", ((const BYTE*)srcBuffer)[u+n]);
+                            for (n = 1; n < 3; n++)
+                                DISPLAY("%02X ",
+                                        ((const BYTE*)srcBuffer)[u + n]);
                             DISPLAY(" \n");
                             DISPLAY("decode: ");
-                            for (n=lowest; n>0; n--)
-                                DISPLAY("%02X ", resultBuffer[u-n]);
+                            for (n = lowest; n > 0; n--)
+                                DISPLAY("%02X ", resultBuffer[u - n]);
                             DISPLAY(" :%02X:  ", resultBuffer[u]);
-                            for (n=1; n<3; n++)
-                                DISPLAY("%02X ", resultBuffer[u+n]);
+                            for (n = 1; n < 3; n++)
+                                DISPLAY("%02X ", resultBuffer[u + n]);
                             DISPLAY(" \n");
                         }
                         break;
                     }
-                    if (u==srcSize-1) {  /* should never happen */
+                    if (u == srcSize - 1) { /* should never happen */
                         DISPLAY("no difference detected\n");
                     }
-                }   /* for (u=0; umode == BMK_both) && (crcOrig!=crcCheck)) */
-        }   /* CRC Checking */
+                } /* for (u=0; umode == BMK_both) && (crcOrig!=crcCheck)) */
+        }         /* CRC Checking */
 
-        if (displayLevel == 1) {   /* hidden display mode -q, used by python speed benchmark */
+        if (displayLevel
+            == 1) { /* hidden display mode -q, used by python speed benchmark */
             double const cSpeed = (double)benchResult.cSpeed / MB_UNIT;
             double const dSpeed = (double)benchResult.dSpeed / MB_UNIT;
             if (adv->additionalParam) {
-                OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, adv->additionalParam);
+                OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s (param=%d)\n",
+                       cLevel,
+                       (int)cSize,
+                       ratio,
+                       cSpeed,
+                       dSpeed,
+                       displayName,
+                       adv->additionalParam);
             } else {
-                OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName);
+                OUTPUT("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s  %s\n",
+                       cLevel,
+                       (int)cSize,
+                       ratio,
+                       cSpeed,
+                       dSpeed,
+                       displayName);
             }
         }
 
         OUTPUTLEVEL(2, "%2i#\n", cLevel);
-    }   /* Bench */
+    } /* Bench */
 
-    benchResult.cMem = (1ULL << (comprParams->windowLog)) + ZSTD_sizeof_CCtx(cctx);
+    benchResult.cMem =
+            (1ULL << (comprParams->windowLog)) + ZSTD_sizeof_CCtx(cctx);
     return BMK_benchOutcome_setValidResult(benchResult);
 }
 
-BMK_benchOutcome_t BMK_benchMemAdvanced(const void* srcBuffer, size_t srcSize,
-                        void* dstBuffer, size_t dstCapacity,
-                        const size_t* fileSizes, unsigned nbFiles,
-                        int cLevel, const ZSTD_compressionParameters* comprParams,
-                        const void* dictBuffer, size_t dictBufferSize,
-                        int displayLevel, const char* displayName, const BMK_advancedParams_t* adv)
+BMK_benchOutcome_t BMK_benchMemAdvanced(
+        const void* srcBuffer,
+        size_t srcSize,
+        void* dstBuffer,
+        size_t dstCapacity,
+        const size_t* fileSizes,
+        unsigned nbFiles,
+        int cLevel,
+        const ZSTD_compressionParameters* comprParams,
+        const void* dictBuffer,
+        size_t dictBufferSize,
+        int displayLevel,
+        const char* displayName,
+        const BMK_advancedParams_t* adv)
 
 {
-    int const dstParamsError = !dstBuffer ^ !dstCapacity;  /* must be both NULL or none */
+    int const dstParamsError =
+            !dstBuffer ^ !dstCapacity; /* must be both NULL or none */
 
-    size_t const blockSize = ((adv->blockSize>=32 && (adv->mode != BMK_decodeOnly)) ? adv->blockSize : srcSize) + (!srcSize) /* avoid div by 0 */ ;
-    U32 const maxNbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize) + nbFiles;
+    size_t const blockSize =
+            ((adv->blockSize >= 32 && (adv->mode != BMK_decodeOnly))
+                     ? adv->blockSize
+                     : srcSize)
+            + (!srcSize) /* avoid div by 0 */;
+    U32 const maxNbBlocks =
+            (U32)((srcSize + (blockSize - 1)) / blockSize) + nbFiles;
 
     /* these are the blockTable parameters, just split up */
-    const void ** const srcPtrs = (const void**)malloc(maxNbBlocks * sizeof(void*));
+    const void** const srcPtrs =
+            (const void**)malloc(maxNbBlocks * sizeof(void*));
     size_t* const srcSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
 
-
-    void ** const cPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));
-    size_t* const cSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
+    void** const cPtrs        = (void**)malloc(maxNbBlocks * sizeof(void*));
+    size_t* const cSizes      = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
     size_t* const cCapacities = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
 
-    void ** const resPtrs = (void**)malloc(maxNbBlocks * sizeof(void*));
+    void** const resPtrs   = (void**)malloc(maxNbBlocks * sizeof(void*));
     size_t* const resSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t));
 
-    BMK_timedFnState_t* timeStateCompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
-    BMK_timedFnState_t* timeStateDecompress = BMK_createTimedFnState(adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
+    BMK_timedFnState_t* timeStateCompress = BMK_createTimedFnState(
+            adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
+    BMK_timedFnState_t* timeStateDecompress = BMK_createTimedFnState(
+            adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS);
 
     ZSTD_CCtx* const cctx = ZSTD_createCCtx();
     ZSTD_DCtx* const dctx = ZSTD_createDCtx();
 
-    const size_t maxCompressedSize = dstCapacity ? dstCapacity : ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024);
+    const size_t maxCompressedSize = dstCapacity
+            ? dstCapacity
+            : ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024);
 
-    void* const internalDstBuffer = dstBuffer ? NULL : malloc(maxCompressedSize);
+    void* const internalDstBuffer =
+            dstBuffer ? NULL : malloc(maxCompressedSize);
     void* const compressedBuffer = dstBuffer ? dstBuffer : internalDstBuffer;
 
-    BMK_benchOutcome_t outcome = BMK_benchOutcome_error();  /* error by default */
+    BMK_benchOutcome_t outcome =
+            BMK_benchOutcome_error(); /* error by default */
 
     void* resultBuffer = srcSize ? malloc(srcSize) : NULL;
 
-    int const allocationincomplete = !srcPtrs || !srcSizes || !cPtrs ||
-        !cSizes || !cCapacities || !resPtrs || !resSizes ||
-        !timeStateCompress || !timeStateDecompress ||
-        !cctx || !dctx ||
-        !compressedBuffer || !resultBuffer;
-
+    int const allocationincomplete = !srcPtrs || !srcSizes || !cPtrs || !cSizes
+            || !cCapacities || !resPtrs || !resSizes || !timeStateCompress
+            || !timeStateDecompress || !cctx || !dctx || !compressedBuffer
+            || !resultBuffer;
 
     if (!allocationincomplete && !dstParamsError) {
-        outcome = BMK_benchMemAdvancedNoAlloc(srcPtrs, srcSizes,
-                                            cPtrs, cCapacities, cSizes,
-                                            resPtrs, resSizes,
-                                            &resultBuffer,
-                                            compressedBuffer, maxCompressedSize,
-                                            timeStateCompress, timeStateDecompress,
-                                            srcBuffer, srcSize,
-                                            fileSizes, nbFiles,
-                                            cLevel, comprParams,
-                                            dictBuffer, dictBufferSize,
-                                            cctx, dctx,
-                                            displayLevel, displayName, adv);
+        outcome = BMK_benchMemAdvancedNoAlloc(
+                srcPtrs,
+                srcSizes,
+                cPtrs,
+                cCapacities,
+                cSizes,
+                resPtrs,
+                resSizes,
+                &resultBuffer,
+                compressedBuffer,
+                maxCompressedSize,
+                timeStateCompress,
+                timeStateDecompress,
+                srcBuffer,
+                srcSize,
+                fileSizes,
+                nbFiles,
+                cLevel,
+                comprParams,
+                dictBuffer,
+                dictBufferSize,
+                cctx,
+                dctx,
+                displayLevel,
+                displayName,
+                adv);
     }
 
     /* clean up */
@@ -644,67 +823,104 @@ BMK_benchOutcome_t BMK_benchMemAdvanced(const void* srcBuffer, size_t srcSize,
     free(resPtrs);
     free(resSizes);
 
-    if(allocationincomplete) {
-        RETURN_ERROR(31, BMK_benchOutcome_t, "allocation error : not enough memory");
+    if (allocationincomplete) {
+        RETURN_ERROR(
+                31, BMK_benchOutcome_t, "allocation error : not enough memory");
     }
 
-    if(dstParamsError) {
+    if (dstParamsError) {
         RETURN_ERROR(32, BMK_benchOutcome_t, "Dst parameters not coherent");
     }
     return outcome;
 }
 
-BMK_benchOutcome_t BMK_benchMem(const void* srcBuffer, size_t srcSize,
-                        const size_t* fileSizes, unsigned nbFiles,
-                        int cLevel, const ZSTD_compressionParameters* comprParams,
-                        const void* dictBuffer, size_t dictBufferSize,
-                        int displayLevel, const char* displayName) {
-
+BMK_benchOutcome_t BMK_benchMem(
+        const void* srcBuffer,
+        size_t srcSize,
+        const size_t* fileSizes,
+        unsigned nbFiles,
+        int cLevel,
+        const ZSTD_compressionParameters* comprParams,
+        const void* dictBuffer,
+        size_t dictBufferSize,
+        int displayLevel,
+        const char* displayName)
+{
     BMK_advancedParams_t const adv = BMK_initAdvancedParams();
-    return BMK_benchMemAdvanced(srcBuffer, srcSize,
-                                NULL, 0,
-                                fileSizes, nbFiles,
-                                cLevel, comprParams,
-                                dictBuffer, dictBufferSize,
-                                displayLevel, displayName, &adv);
+    return BMK_benchMemAdvanced(
+            srcBuffer,
+            srcSize,
+            NULL,
+            0,
+            fileSizes,
+            nbFiles,
+            cLevel,
+            comprParams,
+            dictBuffer,
+            dictBufferSize,
+            displayLevel,
+            displayName,
+            &adv);
 }
 
-static BMK_benchOutcome_t BMK_benchCLevel(const void* srcBuffer, size_t benchedSize,
-                            const size_t* fileSizes, unsigned nbFiles,
-                            int cLevel, const ZSTD_compressionParameters* comprParams,
-                            const void* dictBuffer, size_t dictBufferSize,
-                            int displayLevel, const char* displayName,
-                            BMK_advancedParams_t const * const adv)
+static BMK_benchOutcome_t BMK_benchCLevel(
+        const void* srcBuffer,
+        size_t benchedSize,
+        const size_t* fileSizes,
+        unsigned nbFiles,
+        int cLevel,
+        const ZSTD_compressionParameters* comprParams,
+        const void* dictBuffer,
+        size_t dictBufferSize,
+        int displayLevel,
+        const char* displayName,
+        BMK_advancedParams_t const* const adv)
 {
     const char* pch = strrchr(displayName, '\\'); /* Windows */
-    if (!pch) pch = strrchr(displayName, '/');    /* Linux */
-    if (pch) displayName = pch+1;
+    if (!pch)
+        pch = strrchr(displayName, '/'); /* Linux */
+    if (pch)
+        displayName = pch + 1;
 
     if (adv->realTime) {
         DISPLAYLEVEL(2, "Note : switching to real-time priority \n");
         SET_REALTIME_PRIORITY;
     }
 
-    if (displayLevel == 1 && !adv->additionalParam)   /* --quiet mode */
+    if (displayLevel == 1 && !adv->additionalParam) /* --quiet mode */
         OUTPUT("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n",
-                ZSTD_VERSION_STRING, ZSTD_GIT_COMMIT_STRING,
-                (unsigned)benchedSize, adv->nbSeconds, (unsigned)(adv->blockSize>>10));
+               ZSTD_VERSION_STRING,
+               ZSTD_GIT_COMMIT_STRING,
+               (unsigned)benchedSize,
+               adv->nbSeconds,
+               (unsigned)(adv->blockSize >> 10));
 
-    return BMK_benchMemAdvanced(srcBuffer, benchedSize,
-                                NULL, 0,
-                                fileSizes, nbFiles,
-                                cLevel, comprParams,
-                                dictBuffer, dictBufferSize,
-                                displayLevel, displayName, adv);
+    return BMK_benchMemAdvanced(
+            srcBuffer,
+            benchedSize,
+            NULL,
+            0,
+            fileSizes,
+            nbFiles,
+            cLevel,
+            comprParams,
+            dictBuffer,
+            dictBufferSize,
+            displayLevel,
+            displayName,
+            adv);
 }
 
-int BMK_syntheticTest(int cLevel, double compressibility,
-                      const ZSTD_compressionParameters* compressionParams,
-                      int displayLevel, const BMK_advancedParams_t* adv)
+int BMK_syntheticTest(
+        int cLevel,
+        double compressibility,
+        const ZSTD_compressionParameters* compressionParams,
+        int displayLevel,
+        const BMK_advancedParams_t* adv)
 {
-    char nameBuff[20] = {0};
-    const char* name = nameBuff;
-    size_t const benchedSize = 10000000;
+    char nameBuff[20]        = { 0 };
+    const char* name         = nameBuff;
+    size_t const benchedSize = adv->blockSize ? adv->blockSize : 10000000;
     void* srcBuffer;
     BMK_benchOutcome_t res;
 
@@ -726,15 +942,26 @@ int BMK_syntheticTest(int cLevel, double compressibility,
         name = "Lorem ipsum";
     } else {
         RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
-        snprintf (nameBuff, sizeof(nameBuff), "Synthetic %2u%%", (unsigned)(compressibility*100));
+        snprintf(
+                nameBuff,
+                sizeof(nameBuff),
+                "Synthetic %2u%%",
+                (unsigned)(compressibility * 100));
     }
 
     /* Bench */
-    res = BMK_benchCLevel(srcBuffer, benchedSize,
-                    &benchedSize /* ? */, 1 /* ? */,
-                    cLevel, compressionParams,
-                    NULL, 0,  /* dictionary */
-                    displayLevel, name, adv);
+    res = BMK_benchCLevel(
+            srcBuffer,
+            benchedSize,
+            &benchedSize /* ? */,
+            1 /* ? */,
+            cLevel,
+            compressionParams,
+            NULL,
+            0, /* dictionary */
+            displayLevel,
+            name,
+            adv);
 
     /* clean up */
     free(srcBuffer);
@@ -742,16 +969,15 @@ int BMK_syntheticTest(int cLevel, double compressibility,
     return !BMK_isSuccessful_benchOutcome(res);
 }
 
-
-
 static size_t BMK_findMaxMem(U64 requiredMem)
 {
     size_t const step = 64 MB;
-    BYTE* testmem = NULL;
+    BYTE* testmem     = NULL;
 
     requiredMem = (((requiredMem >> 26) + 1) << 26);
     requiredMem += step;
-    if (requiredMem > maxMemory) requiredMem = maxMemory;
+    if (requiredMem > maxMemory)
+        requiredMem = maxMemory;
 
     do {
         testmem = (BYTE*)malloc((size_t)requiredMem);
@@ -765,53 +991,75 @@ static size_t BMK_findMaxMem(U64 requiredMem)
 /*! BMK_loadFiles() :
  *  Loads `buffer` with content of files listed within `fileNamesTable`.
  *  At most, fills `buffer` entirely. */
-static int BMK_loadFiles(void* buffer, size_t bufferSize,
-                         size_t* fileSizes,
-                         const char* const * fileNamesTable, unsigned nbFiles,
-                         int displayLevel)
+static int BMK_loadFiles(
+        void* buffer,
+        size_t bufferSize,
+        size_t* fileSizes,
+        const char* const* fileNamesTable,
+        unsigned nbFiles,
+        int displayLevel)
 {
     size_t pos = 0, totalSize = 0;
     unsigned n;
-    for (n=0; n bufferSize-pos) fileSize = bufferSize-pos, nbFiles=n;   /* buffer too small - stop after this file */
-            {   size_t const readSize = fread(((char*)buffer)+pos, 1, (size_t)fileSize, f);
-                if (readSize != (size_t)fileSize) RETURN_ERROR_INT(11, "could not read %s", fileNamesTable[n]);
+            if (fileSize > bufferSize - pos)
+                fileSize = bufferSize - pos,
+                nbFiles  = n; /* buffer too small - stop after this file */
+            {
+                size_t const readSize =
+                        fread(((char*)buffer) + pos, 1, (size_t)fileSize, f);
+                if (readSize != (size_t)fileSize)
+                    RETURN_ERROR_INT(
+                            11, "could not read %s", fileNamesTable[n]);
                 pos += readSize;
             }
             fileSizes[n] = (size_t)fileSize;
             totalSize += (size_t)fileSize;
             fclose(f);
-    }   }
+        }
+    }
 
-    if (totalSize == 0) RETURN_ERROR_INT(12, "no data to bench");
+    if (totalSize == 0)
+        RETURN_ERROR_INT(12, "no data to bench");
     return 0;
 }
 
 int BMK_benchFilesAdvanced(
-                        const char* const * fileNamesTable, unsigned nbFiles,
-                        const char* dictFileName, int cLevel,
-                        const ZSTD_compressionParameters* compressionParams,
-                        int displayLevel, const BMK_advancedParams_t* adv)
+        const char* const* fileNamesTable,
+        unsigned nbFiles,
+        const char* dictFileName,
+        int cLevel,
+        const ZSTD_compressionParameters* compressionParams,
+        int displayLevel,
+        const BMK_advancedParams_t* adv)
 {
     void* srcBuffer = NULL;
     size_t benchedSize;
-    void* dictBuffer = NULL;
+    void* dictBuffer      = NULL;
     size_t dictBufferSize = 0;
-    size_t* fileSizes = NULL;
+    size_t* fileSizes     = NULL;
     BMK_benchOutcome_t res;
     U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles);
 
@@ -840,7 +1088,11 @@ int BMK_benchFilesAdvanced(
     if (dictFileName != NULL) {
         U64 const dictFileSize = UTIL_getFileSize(dictFileName);
         if (dictFileSize == UTIL_FILESIZE_UNKNOWN) {
-            DISPLAYLEVEL(1, "error loading %s : %s \n", dictFileName, strerror(errno));
+            DISPLAYLEVEL(
+                    1,
+                    "error loading %s : %s \n",
+                    dictFileName,
+                    strerror(errno));
             free(fileSizes);
             DISPLAYLEVEL(1, "benchmark aborted");
             return 17;
@@ -851,28 +1103,38 @@ int BMK_benchFilesAdvanced(
             return 18;
         }
         dictBufferSize = (size_t)dictFileSize;
-        dictBuffer = malloc(dictBufferSize);
-        if (dictBuffer==NULL) {
+        dictBuffer     = malloc(dictBufferSize);
+        if (dictBuffer == NULL) {
             free(fileSizes);
-            DISPLAYLEVEL(1, "not enough memory for dictionary (%u bytes)",
-                            (unsigned)dictBufferSize);
+            DISPLAYLEVEL(
+                    1,
+                    "not enough memory for dictionary (%u bytes)",
+                    (unsigned)dictBufferSize);
             return 19;
         }
 
-        {   int const errorCode = BMK_loadFiles(dictBuffer, dictBufferSize,
-                                                fileSizes, &dictFileName /*?*/,
-                                                1 /*?*/, displayLevel);
+        {
+            int const errorCode = BMK_loadFiles(
+                    dictBuffer,
+                    dictBufferSize,
+                    fileSizes,
+                    &dictFileName /*?*/,
+                    1 /*?*/,
+                    displayLevel);
             if (errorCode) {
                 res = BMK_benchOutcome_error();
                 goto _cleanUp;
-        }   }
+            }
+        }
     }
 
     /* Memory allocation & restrictions */
     benchedSize = BMK_findMaxMem(totalSizeToLoad * 3) / 3;
-    if ((U64)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad;
+    if ((U64)benchedSize > totalSizeToLoad)
+        benchedSize = (size_t)totalSizeToLoad;
     if (benchedSize < totalSizeToLoad)
-        DISPLAY("Not enough memory; testing %u MB only...\n", (unsigned)(benchedSize >> 20));
+        DISPLAY("Not enough memory; testing %u MB only...\n",
+                (unsigned)(benchedSize >> 20));
 
     srcBuffer = benchedSize ? malloc(benchedSize) : NULL;
     if (!srcBuffer) {
@@ -883,25 +1145,41 @@ int BMK_benchFilesAdvanced(
     }
 
     /* Load input buffer */
-    {   int const errorCode = BMK_loadFiles(srcBuffer, benchedSize,
-                                        fileSizes, fileNamesTable, nbFiles,
-                                        displayLevel);
+    {
+        int const errorCode = BMK_loadFiles(
+                srcBuffer,
+                benchedSize,
+                fileSizes,
+                fileNamesTable,
+                nbFiles,
+                displayLevel);
         if (errorCode) {
             res = BMK_benchOutcome_error();
             goto _cleanUp;
-    }   }
+        }
+    }
 
     /* Bench */
-    {   char mfName[20] = {0};
-        snprintf (mfName, sizeof(mfName), " %u files", nbFiles);
-        {   const char* const displayName = (nbFiles > 1) ? mfName : fileNamesTable[0];
-            res = BMK_benchCLevel(srcBuffer, benchedSize,
-                                fileSizes, nbFiles,
-                                cLevel, compressionParams,
-                                dictBuffer, dictBufferSize,
-                                displayLevel, displayName,
-                                adv);
-    }   }
+    {
+        char mfName[20] = { 0 };
+        snprintf(mfName, sizeof(mfName), " %u files", nbFiles);
+        {
+            const char* const displayName =
+                    (nbFiles > 1) ? mfName : fileNamesTable[0];
+            res = BMK_benchCLevel(
+                    srcBuffer,
+                    benchedSize,
+                    fileSizes,
+                    nbFiles,
+                    cLevel,
+                    compressionParams,
+                    dictBuffer,
+                    dictBufferSize,
+                    displayLevel,
+                    displayName,
+                    adv);
+        }
+    }
 
 _cleanUp:
     free(srcBuffer);
@@ -910,12 +1188,21 @@ _cleanUp:
     return !BMK_isSuccessful_benchOutcome(res);
 }
 
-
-int BMK_benchFiles(const char* const * fileNamesTable, unsigned nbFiles,
-                    const char* dictFileName,
-                    int cLevel, const ZSTD_compressionParameters* compressionParams,
-                    int displayLevel)
+int BMK_benchFiles(
+        const char* const* fileNamesTable,
+        unsigned nbFiles,
+        const char* dictFileName,
+        int cLevel,
+        const ZSTD_compressionParameters* compressionParams,
+        int displayLevel)
 {
     BMK_advancedParams_t const adv = BMK_initAdvancedParams();
-    return BMK_benchFilesAdvanced(fileNamesTable, nbFiles, dictFileName, cLevel, compressionParams, displayLevel, &adv);
+    return BMK_benchFilesAdvanced(
+            fileNamesTable,
+            nbFiles,
+            dictFileName,
+            cLevel,
+            compressionParams,
+            displayLevel,
+            &adv);
 }
diff --git a/programs/lorem.c b/programs/lorem.c
index 56e229058..79030c92f 100644
--- a/programs/lorem.c
+++ b/programs/lorem.c
@@ -95,8 +95,8 @@ static const unsigned kNbWords = sizeof(kWords) / sizeof(kWords[0]);
 
 /* simple 1-dimension distribution, based on word's length, favors small words
  */
-static const int kWeights[]      = { 0, 8, 6, 4, 3, 2 };
-static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
+static const int kWeights[]    = { 0, 8, 6, 4, 3, 2 };
+static const size_t kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
 
 #define DISTRIB_SIZE_MAX 650
 static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
@@ -106,12 +106,12 @@ static void countFreqs(
         const char* words[],
         size_t nbWords,
         const int* weights,
-        unsigned long nbWeights)
+        size_t nbWeights)
 {
     unsigned total = 0;
     size_t w;
     for (w = 0; w < nbWords; w++) {
-        unsigned long len = strlen(words[w]);
+        size_t len = strlen(words[w]);
         int lmax;
         if (len >= nbWeights)
             len = nbWeights - 1;
@@ -126,12 +126,12 @@ static void init_word_distrib(
         const char* words[],
         size_t nbWords,
         const int* weights,
-        unsigned long nbWeights)
+        size_t nbWeights)
 {
     size_t w, d = 0;
     countFreqs(words, nbWords, weights, nbWeights);
     for (w = 0; w < nbWords; w++) {
-        unsigned long len = strlen(words[w]);
+        size_t len = strlen(words[w]);
         int l, lmax;
         if (len >= nbWeights)
             len = nbWeights - 1;

From 1e240af30a1d11ae45745c6c3e96307bad3771fd Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 18:06:56 -0800
Subject: [PATCH 197/937] fix datagen size control

---
 tests/datagencli.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/tests/datagencli.c b/tests/datagencli.c
index b30209953..56616bef4 100644
--- a/tests/datagencli.c
+++ b/tests/datagencli.c
@@ -143,7 +143,6 @@ int main(int argc, const char** argv)
         LOREM_genOut(size, seed);
     }
 
-    RDG_genStdout(size, (double)probaU32 / 100, litProba, seed);
     DISPLAYLEVEL(3, "\n");
 
     return 0;

From c2d357033838c01c827fc10f0b2b850df339776a Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 18:17:28 -0800
Subject: [PATCH 198/937] fix meson datagen build

---
 build/meson/tests/meson.build | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/build/meson/tests/meson.build b/build/meson/tests/meson.build
index 03480d205..9847ab037 100644
--- a/build/meson/tests/meson.build
+++ b/build/meson/tests/meson.build
@@ -44,7 +44,8 @@ testcommon_dep = declare_dependency(link_with: testcommon,
   dependencies: libzstd_deps,
   include_directories: libzstd_includes)
 
-datagen_sources = [join_paths(zstd_rootdir, 'tests/datagencli.c')]
+datagen_sources = [join_paths(zstd_rootdir, 'tests/datagencli.c'),
+  join_paths(zstd_rootdir, 'tests/loremOut.c')]
 datagen = executable('datagen',
   datagen_sources,
   c_args: [ '-DNDEBUG' ],

From 588dfbcc97657f1d70e711f3e22d8f992e14ae28 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 19:21:01 -0800
Subject: [PATCH 199/937] fix c89 compatibility by removing snprintf()

note that this function has been in the code for a long while,
so why does it only start failing CI tests now ?
---
 programs/benchzstd.c | 57 +++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 54 insertions(+), 3 deletions(-)

diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index 56af23d33..d310af924 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -137,6 +137,57 @@ static const size_t maxMemory = (sizeof(size_t) == 4)
         return r;                                      \
     }
 
+/* replacement for snprintf(), which is not supported by C89
+ * sprintf() would be the supported one, but it's labelled unsafe,
+ * so some modern static analyzer will flag it as such, making it unusable.
+ * formatString_u() replaces snprintf() for the specific case where there are only %u arguments */
+static int formatString_u(char *buffer, size_t buffer_size, const char *formatString, unsigned int value)
+{
+    size_t written = 0;
+    int i;
+    assert(value <= 100);
+
+    for (i = 0; formatString[i] != '\0' && written < buffer_size - 1; ++i) {
+        if (formatString[i] != '%') {
+            buffer[written++] = formatString[i];
+            continue;
+        }
+
+        if (formatString[++i] == 'u') {
+            /* Handle single digit */
+            if (value < 10) {
+                buffer[written++] = '0' + value;
+            } else if (value < 100) {
+                /* Handle two digits */
+                if (written >= buffer_size - 2) {
+                    return -1; /* buffer overflow */
+                }
+                buffer[written++] = '0' + value / 10;
+                buffer[written++] = '0' + value % 10;
+            } else { /* 100 */
+                if (written >= buffer_size - 3) {
+                    return -1; /* buffer overflow */
+                }
+                buffer[written++] = '1';
+                buffer[written++] = '0';
+                buffer[written++] = '0';
+            }
+        } else if (formatString[i] == '%') { /* Check for escaped percent sign */
+            buffer[written++] = '%';
+        } else {
+            return -1; /* unsupported format */
+        }
+    }
+
+    if (written < buffer_size) {
+        buffer[written] = '\0';
+    } else {
+        buffer[0] = '\0'; /* Handle truncation */
+    }
+
+    return written;
+}
+
 /* *************************************
  *  Benchmark Parameters
  ***************************************/
@@ -942,10 +993,10 @@ int BMK_syntheticTest(
         name = "Lorem ipsum";
     } else {
         RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
-        snprintf(
+        formatString_u(
                 nameBuff,
                 sizeof(nameBuff),
-                "Synthetic %2u%%",
+                "Synthetic %u%%",
                 (unsigned)(compressibility * 100));
     }
 
@@ -1162,7 +1213,7 @@ int BMK_benchFilesAdvanced(
     /* Bench */
     {
         char mfName[20] = { 0 };
-        snprintf(mfName, sizeof(mfName), " %u files", nbFiles);
+        formatString_u(mfName, sizeof(mfName), " %u files", nbFiles);
         {
             const char* const displayName =
                     (nbFiles > 1) ? mfName : fileNamesTable[0];

From b34517a4402603e8210c24ceb7b976a360ef978b Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 20:20:40 -0800
Subject: [PATCH 200/937] fix cmake build

---
 build/cmake/tests/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/build/cmake/tests/CMakeLists.txt b/build/cmake/tests/CMakeLists.txt
index 3226374a5..3ead07010 100644
--- a/build/cmake/tests/CMakeLists.txt
+++ b/build/cmake/tests/CMakeLists.txt
@@ -50,7 +50,7 @@ set(PROGRAMS_DIR ${ZSTD_SOURCE_DIR}/programs)
 set(TESTS_DIR ${ZSTD_SOURCE_DIR}/tests)
 include_directories(${TESTS_DIR} ${PROGRAMS_DIR} ${LIBRARY_DIR} ${LIBRARY_DIR}/common ${LIBRARY_DIR}/compress ${LIBRARY_DIR}/dictBuilder)
 
-add_executable(datagen ${PROGRAMS_DIR}/datagen.c ${TESTS_DIR}/datagencli.c)
+add_executable(datagen ${PROGRAMS_DIR}/datagen.c ${PROGRAMS_DIR}/lorem.c ${TESTS_DIR}/loremOut.c ${TESTS_DIR}/datagencli.c)
 target_link_libraries(datagen libzstd_static)
 
 #

From e62e15df190ebb41b0b9f1453b2a4e9bd6e05f51 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 22:43:22 -0800
Subject: [PATCH 201/937] fix clangbuild

notably -Wconversion and -Wdocumentation
---
 lib/common/xxhash.h  | 43 -------------------------------------------
 programs/benchzstd.c | 10 +++++-----
 2 files changed, 5 insertions(+), 48 deletions(-)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 424ed19b8..e5ed3dc04 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -630,7 +630,6 @@ XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32 (const void* input, size_t length, X
  * @brief The opaque state struct for the XXH32 streaming API.
  *
  * @see XXH32_state_s for details.
- * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH32_state_s XXH32_state_t;
 
@@ -641,8 +640,6 @@ typedef struct XXH32_state_s XXH32_state_t;
  * @return `NULL` on failure.
  *
  * @note Must be freed with XXH32_freeState().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t* XXH32_createState(void);
 /*!
@@ -654,8 +651,6 @@ XXH_PUBLIC_API XXH_MALLOCF XXH32_state_t* XXH32_createState(void);
  *
  * @note @p statePtr must be allocated with XXH32_createState().
  *
- * @see @ref streaming_example "Streaming Example"
- *
  */
 XXH_PUBLIC_API XXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);
 /*!
@@ -681,8 +676,6 @@ XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_
  * @return @ref XXH_ERROR on failure.
  *
  * @note This function resets and seeds a state. Call it before @ref XXH32_update().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, XXH32_hash_t seed);
 
@@ -704,8 +697,6 @@ XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, XXH32_hash_t
  * @return @ref XXH_ERROR on failure.
  *
  * @note Call this to incrementally consume blocks of data.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
 
@@ -722,8 +713,6 @@ XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void*
  * @note
  *   Calling XXH32_digest() will not affect @p statePtr, so you can update,
  *   digest, and update again.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr);
 #endif /* !XXH_NO_STREAM */
@@ -900,7 +889,6 @@ XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64(XXH_NOESCAPE const void* input, size
  * @brief The opaque state struct for the XXH64 streaming API.
  *
  * @see XXH64_state_s for details.
- * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */
 
@@ -911,8 +899,6 @@ typedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */
  * @return `NULL` on failure.
  *
  * @note Must be freed with XXH64_freeState().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t* XXH64_createState(void);
 
@@ -924,8 +910,6 @@ XXH_PUBLIC_API XXH_MALLOCF XXH64_state_t* XXH64_createState(void);
  * @return @ref XXH_OK.
  *
  * @note @p statePtr must be allocated with XXH64_createState().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);
 
@@ -952,8 +936,6 @@ XXH_PUBLIC_API void XXH64_copyState(XXH_NOESCAPE XXH64_state_t* dst_state, const
  * @return @ref XXH_ERROR on failure.
  *
  * @note This function resets and seeds a state. Call it before @ref XXH64_update().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH_NOESCAPE XXH64_state_t* statePtr, XXH64_hash_t seed);
 
@@ -975,8 +957,6 @@ XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH_NOESCAPE XXH64_state_t* statePtr,
  * @return @ref XXH_ERROR on failure.
  *
  * @note Call this to incrementally consume blocks of data.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH_NOESCAPE XXH64_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length);
 
@@ -993,8 +973,6 @@ XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH_NOESCAPE XXH64_state_t* statePtr,
  * @note
  *   Calling XXH64_digest() will not affect @p statePtr, so you can update,
  *   digest, and update again.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH64_digest (XXH_NOESCAPE const XXH64_state_t* statePtr);
 #endif /* !XXH_NO_STREAM */
@@ -1199,7 +1177,6 @@ XXH_PUBLIC_API XXH_PUREF XXH64_hash_t XXH3_64bits_withSecret(XXH_NOESCAPE const
  * @brief The opaque state struct for the XXH3 streaming API.
  *
  * @see XXH3_state_s for details.
- * @see @ref streaming_example "Streaming Example"
  */
 typedef struct XXH3_state_s XXH3_state_t;
 XXH_PUBLIC_API XXH_MALLOCF XXH3_state_t* XXH3_createState(void);
@@ -1231,8 +1208,6 @@ XXH_PUBLIC_API void XXH3_copyState(XXH_NOESCAPE XXH3_state_t* dst_state, XXH_NOE
  *   - Call this function before @ref XXH3_64bits_update().
  *   - Digest will be equivalent to `XXH3_64bits()`.
  *
- * @see @ref streaming_example "Streaming Example"
- *
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr);
 
@@ -1253,8 +1228,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset(XXH_NOESCAPE XXH3_state_t* stateP
  *   - Call this function before @ref XXH3_64bits_update().
  *   - Digest will be equivalent to `XXH3_64bits_withSeed()`.
  *
- * @see @ref streaming_example "Streaming Example"
- *
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed);
 
@@ -1279,8 +1252,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSeed(XXH_NOESCAPE XXH3_state_
  * (secret's content should look like a bunch of random bytes).
  * When in doubt about the randomness of a candidate `secret`,
  * consider employing `XXH3_generateSecret()` instead (see below).
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize);
 
@@ -1302,8 +1273,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_64bits_reset_withSecret(XXH_NOESCAPE XXH3_stat
  * @return @ref XXH_ERROR on failure.
  *
  * @note Call this to incrementally consume blocks of data.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* input, size_t length);
 
@@ -1320,8 +1289,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update (XXH_NOESCAPE XXH3_state_t* stat
  * @note
  *   Calling XXH3_64bits_digest() will not affect @p statePtr, so you can update,
  *   digest, and update again.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_PUREF XXH64_hash_t  XXH3_64bits_digest (XXH_NOESCAPE const XXH3_state_t* statePtr);
 #endif /* !XXH_NO_STREAM */
@@ -1442,8 +1409,6 @@ XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH3_128bits_withSecret(XXH_NOESCAPE cons
  *   - This function resets `statePtr` and generate a secret with default parameters.
  *   - Call it before @ref XXH3_128bits_update().
  *   - Digest will be equivalent to `XXH3_128bits()`.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* statePtr);
 
@@ -1463,8 +1428,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset(XXH_NOESCAPE XXH3_state_t* state
  *   - This function resets `statePtr` and generate a secret from `seed`.
  *   - Call it before @ref XXH3_128bits_update().
  *   - Digest will be equivalent to `XXH3_128bits_withSeed()`.
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state_t* statePtr, XXH64_hash_t seed);
 /*!
@@ -1486,8 +1449,6 @@ XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSeed(XXH_NOESCAPE XXH3_state
  * (secret's content should look like a bunch of random bytes).
  * When in doubt about the randomness of a candidate `secret`,
  * consider employing `XXH3_generateSecret()` instead (see below).
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_128bits_reset_withSecret(XXH_NOESCAPE XXH3_state_t* statePtr, XXH_NOESCAPE const void* secret, size_t secretSize);
 
@@ -6072,8 +6033,6 @@ static void XXH_alignedFree(void* p)
  * @return `NULL` on failure.
  *
  * @note Must be freed with XXH3_freeState().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void)
 {
@@ -6092,8 +6051,6 @@ XXH_PUBLIC_API XXH3_state_t* XXH3_createState(void)
  * @return @ref XXH_OK.
  *
  * @note Must be allocated with XXH3_createState().
- *
- * @see @ref streaming_example "Streaming Example"
  */
 XXH_PUBLIC_API XXH_errorcode XXH3_freeState(XXH3_state_t* statePtr)
 {
diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index d310af924..8ab9c0c2d 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -141,7 +141,7 @@ static const size_t maxMemory = (sizeof(size_t) == 4)
  * sprintf() would be the supported one, but it's labelled unsafe,
  * so some modern static analyzer will flag it as such, making it unusable.
  * formatString_u() replaces snprintf() for the specific case where there are only %u arguments */
-static int formatString_u(char *buffer, size_t buffer_size, const char *formatString, unsigned int value)
+static int formatString_u(char* buffer, size_t buffer_size, const char* formatString, unsigned int value)
 {
     size_t written = 0;
     int i;
@@ -156,14 +156,14 @@ static int formatString_u(char *buffer, size_t buffer_size, const char *formatSt
         if (formatString[++i] == 'u') {
             /* Handle single digit */
             if (value < 10) {
-                buffer[written++] = '0' + value;
+                buffer[written++] = '0' + (char)value;
             } else if (value < 100) {
                 /* Handle two digits */
                 if (written >= buffer_size - 2) {
                     return -1; /* buffer overflow */
                 }
-                buffer[written++] = '0' + value / 10;
-                buffer[written++] = '0' + value % 10;
+                buffer[written++] = '0' + (char)(value / 10);
+                buffer[written++] = '0' + (char)(value % 10);
             } else { /* 100 */
                 if (written >= buffer_size - 3) {
                     return -1; /* buffer overflow */
@@ -185,7 +185,7 @@ static int formatString_u(char *buffer, size_t buffer_size, const char *formatSt
         buffer[0] = '\0'; /* Handle truncation */
     }
 
-    return written;
+    return (int)written;
 }
 
 /* *************************************

From 9e711c9360d8ebf17132e750b3fe24f79fc63a6d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 22:59:58 -0800
Subject: [PATCH 202/937] fix Visual Studio datagen recipe

---
 build/VS2010/datagen/datagen.vcxproj | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/build/VS2010/datagen/datagen.vcxproj b/build/VS2010/datagen/datagen.vcxproj
index a66358a0d..aaba4788b 100644
--- a/build/VS2010/datagen/datagen.vcxproj
+++ b/build/VS2010/datagen/datagen.vcxproj
@@ -157,6 +157,8 @@
   
     
     
+    
+    
     
   
   

From 7170f51dd277d4aa4a675ffdd5593af362abe83c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 20 Feb 2024 23:36:04 -0800
Subject: [PATCH 203/937] fix include order

---
 programs/benchzstd.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index 8ab9c0c2d..32227669f 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -18,14 +18,16 @@
 /* *************************************
  *  Includes
  ***************************************/
+/* this must be included first */
+#include "platform.h" /* Large Files support, compiler specifics */
+
+/* then following system includes */
 #include  /* assert */
 #include 
 #include     /* fprintf, fopen */
 #include    /* malloc, free */
 #include    /* memset, strerror */
-#include "platform.h" /* Large Files support */
 #include "util.h"     /* UTIL_getFileSize, UTIL_sleep */
-
 #include "../lib/common/mem.h"
 #include "benchfn.h"
 #include "timefn.h" /* UTIL_time_t */

From 0a68be83e7cb84c8212f666b4b4aa6e0dc8477cc Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 21 Feb 2024 00:22:04 -0800
Subject: [PATCH 204/937] updated setup-msys2 to v2.22.0

following a warning in recent test reports

```
Node.js 16 actions are deprecated. Please update the following actions to use Node.js 20: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36. For more information see: https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20/.
```
---
 .github/workflows/dev-long-tests.yml  | 2 +-
 .github/workflows/dev-short-tests.yml | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 29db7316e..1e411a86d 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -247,7 +247,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2
+    - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0
       with:
         msystem: MINGW64
         install: make
diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 3123e129b..5f49bacae 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -448,7 +448,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2
+    - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0
       with:
         msystem: ${{ matrix.msystem }}
         install: make diffutils

From 68a232c5917ff387031c76acea80f77e8115419f Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 13:13:03 -0800
Subject: [PATCH 205/937] benchmark more can test targetCBlockSize

---
 programs/benchzstd.c | 3 +++
 programs/benchzstd.h | 1 +
 programs/zstd.1.md   | 4 ++++
 programs/zstdcli.c   | 1 +
 4 files changed, 9 insertions(+)

diff --git a/programs/benchzstd.c b/programs/benchzstd.c
index 32227669f..29ee595c1 100644
--- a/programs/benchzstd.c
+++ b/programs/benchzstd.c
@@ -200,6 +200,7 @@ BMK_advancedParams_t BMK_initAdvancedParams(void)
         BMK_both,               /* mode */
         BMK_TIMETEST_DEFAULT_S, /* nbSeconds */
         0,                      /* blockSize */
+        0,               /* targetCBlockSize */
         0,                      /* nbWorkers */
         0,                      /* realTime */
         0,                      /* additionalParam */
@@ -275,6 +276,8 @@ static void BMK_initCCtx(
             (int)adv->literalCompressionMode));
     CHECK_Z(ZSTD_CCtx_setParameter(
             ctx, ZSTD_c_strategy, (int)comprParams->strategy));
+    CHECK_Z(ZSTD_CCtx_setParameter(
+            ctx, ZSTD_c_targetCBlockSize, (int)adv->targetCBlockSize));
     CHECK_Z(ZSTD_CCtx_loadDictionary(ctx, dictBuffer, dictBufferSize));
 }
 
diff --git a/programs/benchzstd.h b/programs/benchzstd.h
index cdb6101c2..ad3088cd4 100644
--- a/programs/benchzstd.h
+++ b/programs/benchzstd.h
@@ -100,6 +100,7 @@ typedef struct {
     BMK_mode_t mode;        /* 0: all, 1: compress only 2: decode only */
     unsigned nbSeconds;     /* default timing is in nbSeconds */
     size_t blockSize;       /* Maximum size of each block*/
+    size_t targetCBlockSize;/* Approximative size of compressed blocks */
     int nbWorkers;          /* multithreading */
     unsigned realTime;      /* real time priority */
     int additionalParam;    /* used by python speed benchmark */
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index 231341b2a..9a4a5df2c 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -218,6 +218,10 @@ the last one takes effect.
     expected. This feature allows for controlling the guess when needed.
     Exact guesses result in better compression ratios. Overestimates result in slightly
     degraded compression ratios, while underestimates may result in significant degradation.
+* `--target-compressed-block-size=#`:
+    Attempt to produce compressed blocks of approximately this size.
+    This will split larger blocks in order to approach this target.
+    Notably useful to improve latency when the receiver can make use of early data sooner.
 * `-o FILE`:
     save result into `FILE`.
 * `-f`, `--force`:
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index dd21021b0..85d0e12d7 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -1374,6 +1374,7 @@ int main(int argCount, const char* argv[])
             CLEAN_RETURN(1);
         }
         benchParams.blockSize = blockSize;
+        benchParams.targetCBlockSize = targetCBlockSize;
         benchParams.nbWorkers = (int)nbWorkers;
         benchParams.realTime = (unsigned)setRealTimePrio;
         benchParams.nbSeconds = bench_nbSeconds;

From cc4530924b42c5d138f871c33726d374e2778ad3 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 14:03:26 -0800
Subject: [PATCH 206/937] speed optimized version of targetCBlockSize

note that the size of individual compressed blocks will vary more wildly with this modification.
But it seems good enough for a first test, and fix the speed regression issue.
Further refinements can be attempted later.
---
 lib/compress/zstd_compress_superblock.c | 112 ++++++++++++------------
 programs/zstd.1.md                      |   5 +-
 2 files changed, 58 insertions(+), 59 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index dacaf85db..5b22da026 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -122,7 +122,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
     }
     *entropyWritten = 1;
     DEBUGLOG(5, "Compressed literals: %u -> %u", (U32)litSize, (U32)(op-ostart));
-    return op-ostart;
+    return (size_t)(op-ostart);
 }
 
 static size_t
@@ -187,7 +187,7 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
     else
         op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
     if (nbSeq==0) {
-        return op - ostart;
+        return (size_t)(op - ostart);
     }
 
     /* seqHead : flags for FSE encoding type */
@@ -209,7 +209,7 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
     }
 
     {   size_t const bitstreamSize = ZSTD_encodeSequences(
-                                        op, oend - op,
+                                        op, (size_t)(oend - op),
                                         fseTables->matchlengthCTable, mlCode,
                                         fseTables->offcodeCTable, ofCode,
                                         fseTables->litlengthCTable, llCode,
@@ -253,7 +253,7 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables,
 #endif
 
     *entropyWritten = 1;
-    return op - ostart;
+    return (size_t)(op - ostart);
 }
 
 /** ZSTD_compressSubBlock() :
@@ -296,11 +296,11 @@ static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
         op += cSeqSize;
     }
     /* Write block header */
-    {   size_t cSize = (op-ostart)-ZSTD_blockHeaderSize;
+    {   size_t cSize = (size_t)(op-ostart) - ZSTD_blockHeaderSize;
         U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
         MEM_writeLE24(ostart, cBlockHeader24);
     }
-    return op-ostart;
+    return (size_t)(op-ostart);
 }
 
 static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t litSize,
@@ -419,6 +419,16 @@ static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMe
     return 0;
 }
 
+static size_t countLiterals(const seqDef* sp, size_t seqCount)
+{
+    size_t n, total = 0;
+    assert(sp != NULL);
+    for (n=0; nsequencesStart;
     const seqDef* const send = seqStorePtr->sequences;
-    const seqDef* sp = sstart;
+    size_t const nbSeqs = (size_t)(send - sstart);
+    size_t nbSeqsPerBlock = nbSeqs;
     const BYTE* const lstart = seqStorePtr->litStart;
     const BYTE* const lend = seqStorePtr->lit;
     const BYTE* lp = lstart;
+    size_t const nbLiterals = (size_t)(lend - lstart);
     BYTE const* ip = (BYTE const*)src;
     BYTE const* const iend = ip + srcSize;
     BYTE* const ostart = (BYTE*)dst;
@@ -451,52 +463,50 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const BYTE* mlCodePtr = seqStorePtr->mlCode;
     const BYTE* ofCodePtr = seqStorePtr->ofCode;
     size_t targetCBlockSize = cctxParams->targetCBlockSize;
-    size_t litSize, seqCount;
     int writeLitEntropy = entropyMetadata->hufMetadata.hType == set_compressed;
     int writeSeqEntropy = 1;
-    int lastSequence = 0;
+    size_t nbSubBlocks = 1;
 
     DEBUGLOG(5, "ZSTD_compressSubBlock_multi (litSize=%u, nbSeq=%u)",
                 (unsigned)(lend-lp), (unsigned)(send-sstart));
 
-    litSize = 0;
-    seqCount = 0;
-    do {
-        size_t cBlockSizeEstimate = 0;
-        if (sstart == send) {
-            lastSequence = 1;
-        } else {
-            const seqDef* const sequence = sp + seqCount;
-            lastSequence = sequence == send - 1;
-            litSize += ZSTD_getSequenceLength(seqStorePtr, sequence).litLength;
-            seqCount++;
-        }
-        if (lastSequence) {
-            assert(lp <= lend);
-            assert(litSize <= (size_t)(lend - lp));
-            litSize = (size_t)(lend - lp);
-        }
-        /* I think there is an optimization opportunity here.
-         * Calling ZSTD_estimateSubBlockSize for every sequence can be wasteful
-         * since it recalculates estimate from scratch.
-         * For example, it would recount literal distribution and symbol codes every time.
-         */
-        cBlockSizeEstimate = ZSTD_estimateSubBlockSize(lp, litSize, ofCodePtr, llCodePtr, mlCodePtr, seqCount,
-                                                       &nextCBlock->entropy, entropyMetadata,
-                                                       workspace, wkspSize, writeLitEntropy, writeSeqEntropy);
-        if (cBlockSizeEstimate > targetCBlockSize || lastSequence) {
+    /* let's start by a general estimation for the full block */
+    {   size_t const cBlockSizeEstimate =
+                ZSTD_estimateSubBlockSize(lp, nbLiterals,
+                                        ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
+                                        &nextCBlock->entropy, entropyMetadata,
+                                        workspace, wkspSize,
+                                        writeLitEntropy, writeSeqEntropy);
+        /* quick estimation */
+        nbSubBlocks = (cBlockSizeEstimate + (targetCBlockSize-1)) / targetCBlockSize;
+        assert(nbSubBlocks > 0);
+        nbSeqsPerBlock = nbSeqs / nbSubBlocks;
+        /* Note: this is very approximative. Obviously, some sub-blocks will be larger and others faster.
+         * But the contract of this feature has always been approximative, so for now we'll leverage it for speed.
+         * It can be refined later, for closer-to-target compressed block size, if it ever matters. */
+    }
+
+    /* write sub-blocks */
+    {   size_t n;
+        for (n=0; n < nbSubBlocks; n++) {
+            const seqDef* sp = sstart + n*nbSeqsPerBlock;
+            int lastSubBlock = (n==nbSubBlocks-1);
+            size_t const nbSeqsLastSubBlock = nbSeqs - (nbSubBlocks-1) * nbSeqsPerBlock;
+            size_t seqCount = lastSubBlock ? nbSeqsLastSubBlock : nbSeqsPerBlock;
+            size_t litSize = lastSubBlock ? (size_t)(lend-lp) : countLiterals(sp, seqCount);
             int litEntropyWritten = 0;
             int seqEntropyWritten = 0;
-            const size_t decompressedSize = ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSequence);
+            const size_t decompressedSize =
+                    ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSubBlock);
             const size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
                                                        sp, seqCount,
                                                        lp, litSize,
                                                        llCodePtr, mlCodePtr, ofCodePtr,
                                                        cctxParams,
-                                                       op, oend-op,
+                                                       op, (size_t)(oend-op),
                                                        bmi2, writeLitEntropy, writeSeqEntropy,
                                                        &litEntropyWritten, &seqEntropyWritten,
-                                                       lastBlock && lastSequence);
+                                                       lastBlock && lastSubBlock);
             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
             if (cSize > 0 && cSize < decompressedSize) {
                 DEBUGLOG(5, "Committed the sub-block");
@@ -519,7 +529,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                 }
             }
         }
-    } while (!lastSequence);
+    }
+
     if (writeLitEntropy) {
         DEBUGLOG(5, "ZSTD_compressSubBlock_multi has literal entropy tables unwritten");
         ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
@@ -531,25 +542,10 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         DEBUGLOG(5, "ZSTD_compressSubBlock_multi has sequence entropy tables unwritten");
         return 0;
     }
-    if (ip < iend) {
-        size_t const cSize = ZSTD_noCompressBlock(op, oend - op, ip, iend - ip, lastBlock);
-        DEBUGLOG(5, "ZSTD_compressSubBlock_multi last sub-block uncompressed, %zu bytes", (size_t)(iend - ip));
-        FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
-        assert(cSize != 0);
-        op += cSize;
-        /* We have to regenerate the repcodes because we've skipped some sequences */
-        if (sp < send) {
-            seqDef const* seq;
-            repcodes_t rep;
-            ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
-            for (seq = sstart; seq < sp; ++seq) {
-                ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
-            }
-            ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
-        }
-    }
-    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed");
-    return op-ostart;
+    assert(ip == iend); (void)iend;
+    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed: %u subBlocks, total compressed size = %u",
+                (unsigned)nbSubBlocks, (unsigned)(op-ostart));
+    return (size_t)(op-ostart);
 }
 
 size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index 9a4a5df2c..078455f3e 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -221,7 +221,10 @@ the last one takes effect.
 * `--target-compressed-block-size=#`:
     Attempt to produce compressed blocks of approximately this size.
     This will split larger blocks in order to approach this target.
-    Notably useful to improve latency when the receiver can make use of early data sooner.
+    This feature is notably useful for improved latency, when the receiver can leverage receiving early incomplete data.
+    This parameter defines a loose target: compressed blocks will target this size "on average", but individual blocks can still be larger or smaller.
+    Enabling this feature can decrease compression speed by up to ~10% at level 1.
+    Higher levels will see smaller relative speed regression, becoming invisible at higher settings.
 * `-o FILE`:
     save result into `FILE`.
 * `-f`, `--force`:

From 6b11fc436c3001cb9beb07627e7b434aab97b4b1 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 14:53:56 -0800
Subject: [PATCH 207/937] fix issue with incompressible sections

---
 lib/compress/zstd_compress_superblock.c | 91 ++++++++++++++++---------
 tests/fuzzer.c                          |  4 +-
 2 files changed, 60 insertions(+), 35 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 5b22da026..2bb2e2208 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -136,7 +136,7 @@ ZSTD_seqDecompressedSize(seqStore_t const* seqStore,
     size_t matchLengthSum = 0;
     size_t litLengthSum = 0;
     (void)(litLengthSum); /* suppress unused variable warning on some environments */
-    while (send-sp > 0) {
+    while (sp < send) {
         ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
         litLengthSum += seqLen.litLength;
         matchLengthSum += seqLen.matchLength;
@@ -462,7 +462,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const BYTE* llCodePtr = seqStorePtr->llCode;
     const BYTE* mlCodePtr = seqStorePtr->mlCode;
     const BYTE* ofCodePtr = seqStorePtr->ofCode;
-    size_t targetCBlockSize = cctxParams->targetCBlockSize;
+    size_t const minTarget = 2 KB; /* enforce minimum size to avoid undesirable side effects */
+    size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
     int writeLitEntropy = entropyMetadata->hufMetadata.hType == set_compressed;
     int writeSeqEntropy = 1;
     size_t nbSubBlocks = 1;
@@ -470,8 +471,13 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     DEBUGLOG(5, "ZSTD_compressSubBlock_multi (litSize=%u, nbSeq=%u)",
                 (unsigned)(lend-lp), (unsigned)(send-sstart));
 
-    /* let's start by a general estimation for the full block */
-    {   size_t const cBlockSizeEstimate =
+    if (nbSeqs == 0) {
+        /* special case : no sequence */
+        nbSeqsPerBlock = 0;
+        nbSubBlocks = 1;
+    } else {
+        /* let's start by a general estimation for the full block */
+        size_t const cBlockSizeEstimate =
                 ZSTD_estimateSubBlockSize(lp, nbLiterals,
                                         ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
                                         &nextCBlock->entropy, entropyMetadata,
@@ -480,8 +486,13 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         /* quick estimation */
         nbSubBlocks = (cBlockSizeEstimate + (targetCBlockSize-1)) / targetCBlockSize;
         assert(nbSubBlocks > 0);
-        nbSeqsPerBlock = nbSeqs / nbSubBlocks;
-        /* Note: this is very approximative. Obviously, some sub-blocks will be larger and others faster.
+        if (nbSeqs > nbSubBlocks) {
+            nbSeqsPerBlock = nbSeqs / nbSubBlocks;
+        } else {
+            nbSeqsPerBlock = 1;
+            nbSubBlocks = nbSeqs;
+        }
+        /* Note: this is very approximative. Obviously, some sub-blocks will be larger and others smaller.
          * But the contract of this feature has always been approximative, so for now we'll leverage it for speed.
          * It can be refined later, for closer-to-target compressed block size, if it ever matters. */
     }
@@ -498,36 +509,50 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
             int seqEntropyWritten = 0;
             const size_t decompressedSize =
                     ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSubBlock);
-            const size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
-                                                       sp, seqCount,
-                                                       lp, litSize,
-                                                       llCodePtr, mlCodePtr, ofCodePtr,
-                                                       cctxParams,
-                                                       op, (size_t)(oend-op),
-                                                       bmi2, writeLitEntropy, writeSeqEntropy,
-                                                       &litEntropyWritten, &seqEntropyWritten,
-                                                       lastBlock && lastSubBlock);
+            size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
+                                               sp, seqCount,
+                                               lp, litSize,
+                                               llCodePtr, mlCodePtr, ofCodePtr,
+                                               cctxParams,
+                                               op, (size_t)(oend-op),
+                                               bmi2, writeLitEntropy, writeSeqEntropy,
+                                               &litEntropyWritten, &seqEntropyWritten,
+                                               lastBlock && lastSubBlock);
             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
-            if (cSize > 0 && cSize < decompressedSize) {
-                DEBUGLOG(5, "Committed the sub-block");
-                assert(ip + decompressedSize <= iend);
-                ip += decompressedSize;
-                sp += seqCount;
-                lp += litSize;
-                op += cSize;
-                llCodePtr += seqCount;
-                mlCodePtr += seqCount;
-                ofCodePtr += seqCount;
-                litSize = 0;
-                seqCount = 0;
-                /* Entropy only needs to be written once */
-                if (litEntropyWritten) {
-                    writeLitEntropy = 0;
-                }
-                if (seqEntropyWritten) {
-                    writeSeqEntropy = 0;
+
+            if (cSize == 0 || cSize >= decompressedSize) {
+                cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, decompressedSize, lastBlock);
+                DEBUGLOG(5, "send an uncompressed sub-block of %u bytes", (unsigned)(decompressedSize));
+                FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
+                assert(cSize != 0);
+                /* We have to regenerate the repcodes because we've skipped some sequences */
+                if (sp < send) {
+                    seqDef const* seq;
+                    repcodes_t rep;
+                    ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
+                    for (seq = sstart; seq < sp; ++seq) {
+                        ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
+                    }
+                    ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
                 }
             }
+
+            DEBUGLOG(5, "Committed the sub-block");
+            assert(ip + decompressedSize <= iend);
+            ip += decompressedSize;
+            sp += seqCount;
+            lp += litSize;
+            op += cSize;
+            llCodePtr += seqCount;
+            mlCodePtr += seqCount;
+            ofCodePtr += seqCount;
+            /* Entropy only needs to be written once */
+            if (litEntropyWritten) {
+                writeLitEntropy = 0;
+            }
+            if (seqEntropyWritten) {
+                writeSeqEntropy = 0;
+            }
         }
     }
 
diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index d70a66904..6c1f58df7 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -952,7 +952,7 @@ static int basicUnitTests(U32 const seed, double compressibility)
         ZSTD_freeCDict(cdict);
         ZSTD_freeCCtx(cctx);
     }
-    
+
     DISPLAYLEVEL(3, "test%3i : maxBlockSize = 2K", testNb++);
     {
         ZSTD_CCtx* cctx = ZSTD_createCCtx();
@@ -1374,7 +1374,7 @@ static int basicUnitTests(U32 const seed, double compressibility)
     }
     DISPLAYLEVEL(3, "OK \n");
 
-    DISPLAYLEVEL(3, "test%3d: superblock uncompressible data, too many nocompress superblocks : ", testNb++);
+    DISPLAYLEVEL(3, "test%3d : superblock uncompressible data: too many nocompress superblocks : ", testNb++);
     {
         ZSTD_CCtx* const cctx = ZSTD_createCCtx();
         const BYTE* src = (BYTE*)CNBuffer; BYTE* dst = (BYTE*)compressedBuffer;

From 3b401000580a3e605694055834dcd254fa36202e Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 15:35:12 -0800
Subject: [PATCH 208/937] fix long sequences (> 64 KB)

---
 lib/compress/zstd_compress_superblock.c | 13 ++++++++-----
 tests/Makefile                          |  2 +-
 2 files changed, 9 insertions(+), 6 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 2bb2e2208..239072623 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -136,6 +136,7 @@ ZSTD_seqDecompressedSize(seqStore_t const* seqStore,
     size_t matchLengthSum = 0;
     size_t litLengthSum = 0;
     (void)(litLengthSum); /* suppress unused variable warning on some environments */
+    DEBUGLOG(6, "ZSTD_seqDecompressedSize (%u sequences from %p) (last==%i)", (unsigned)nbSeq, sp, lastSequence);
     while (sp < send) {
         ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
         litLengthSum += seqLen.litLength;
@@ -279,7 +280,8 @@ static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
                 litSize, nbSeq, writeLitEntropy, writeSeqEntropy, lastBlock);
     {   size_t cLitSize = ZSTD_compressSubBlock_literal((const HUF_CElt*)entropy->huf.CTable,
                                                         &entropyMetadata->hufMetadata, literals, litSize,
-                                                        op, oend-op, bmi2, writeLitEntropy, litEntropyWritten);
+                                                        op, (size_t)(oend-op),
+                                                        bmi2, writeLitEntropy, litEntropyWritten);
         FORWARD_IF_ERROR(cLitSize, "ZSTD_compressSubBlock_literal failed");
         if (cLitSize == 0) return 0;
         op += cLitSize;
@@ -289,7 +291,7 @@ static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy,
                                                   sequences, nbSeq,
                                                   llCode, mlCode, ofCode,
                                                   cctxParams,
-                                                  op, oend-op,
+                                                  op, (size_t)(oend-op),
                                                   bmi2, writeSeqEntropy, seqEntropyWritten);
         FORWARD_IF_ERROR(cSeqSize, "ZSTD_compressSubBlock_sequences failed");
         if (cSeqSize == 0) return 0;
@@ -419,13 +421,14 @@ static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMe
     return 0;
 }
 
-static size_t countLiterals(const seqDef* sp, size_t seqCount)
+static size_t countLiterals(seqStore_t const* seqStore, const seqDef* sp, size_t seqCount)
 {
     size_t n, total = 0;
     assert(sp != NULL);
     for (n=0; n %zu bytes", seqCount, sp, total);
     return total;
 }
 
@@ -504,7 +507,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
             int lastSubBlock = (n==nbSubBlocks-1);
             size_t const nbSeqsLastSubBlock = nbSeqs - (nbSubBlocks-1) * nbSeqsPerBlock;
             size_t seqCount = lastSubBlock ? nbSeqsLastSubBlock : nbSeqsPerBlock;
-            size_t litSize = lastSubBlock ? (size_t)(lend-lp) : countLiterals(sp, seqCount);
+            size_t litSize = lastSubBlock ? (size_t)(lend-lp) : countLiterals(seqStorePtr, sp, seqCount);
             int litEntropyWritten = 0;
             int seqEntropyWritten = 0;
             const size_t decompressedSize =
diff --git a/tests/Makefile b/tests/Makefile
index ed7638b74..700c64b1d 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -314,7 +314,7 @@ check: shortest
 fuzztest: test-fuzzer test-zstream test-decodecorpus
 
 .PHONY: test
-test: test-zstd test-fullbench test-fuzzer test-zstream test-invalidDictionaries test-legacy test-decodecorpus test-cli-tests
+test: test-zstd test-cli-tests test-fullbench test-fuzzer test-zstream test-invalidDictionaries test-legacy test-decodecorpus
 ifeq ($(QEMU_SYS),)
 test: test-pool
 endif

From 0591e7eea118eccb6b8ceef00296bedaad3d7e9e Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 16:05:09 -0800
Subject: [PATCH 209/937] minor: fix overly cautious conversion warning

---
 lib/compress/zstd_compress_superblock.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 239072623..d31bed32e 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -136,7 +136,7 @@ ZSTD_seqDecompressedSize(seqStore_t const* seqStore,
     size_t matchLengthSum = 0;
     size_t litLengthSum = 0;
     (void)(litLengthSum); /* suppress unused variable warning on some environments */
-    DEBUGLOG(6, "ZSTD_seqDecompressedSize (%u sequences from %p) (last==%i)", (unsigned)nbSeq, sp, lastSequence);
+    DEBUGLOG(6, "ZSTD_seqDecompressedSize (%u sequences from %p) (last==%i)", (unsigned)nbSeq, (const void*)sp, lastSequence);
     while (sp < send) {
         ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
         litLengthSum += seqLen.litLength;
@@ -428,7 +428,7 @@ static size_t countLiterals(seqStore_t const* seqStore, const seqDef* sp, size_t
     for (n=0; n %zu bytes", seqCount, sp, total);
+    DEBUGLOG(6, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);
     return total;
 }
 

From 6719794379ada9cc33cae486a6fea4930eda481c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 23 Feb 2024 18:48:29 -0800
Subject: [PATCH 210/937] fixed some regressionTests

but not all
---
 lib/compress/zstd_compress_superblock.c | 13 ++++++++-----
 tests/fuzz/dictionary_round_trip.c      | 12 ++++++------
 2 files changed, 14 insertions(+), 11 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index d31bed32e..09219d007 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -467,7 +467,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const BYTE* ofCodePtr = seqStorePtr->ofCode;
     size_t const minTarget = 2 KB; /* enforce minimum size to avoid undesirable side effects */
     size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
-    int writeLitEntropy = entropyMetadata->hufMetadata.hType == set_compressed;
+    int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
     int writeSeqEntropy = 1;
     size_t nbSubBlocks = 1;
 
@@ -523,9 +523,11 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                                                lastBlock && lastSubBlock);
             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
 
-            if (cSize == 0 || cSize >= decompressedSize) {
+            if (cSize == 0 || (cSize >= decompressedSize && n>0)) {
+                litEntropyWritten = 0;
+                seqEntropyWritten = 0;
                 cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, decompressedSize, lastBlock);
-                DEBUGLOG(5, "send an uncompressed sub-block of %u bytes", (unsigned)(decompressedSize));
+                DEBUGLOG(5, "Generate uncompressed sub-block of %u bytes", (unsigned)(decompressedSize));
                 FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
                 assert(cSize != 0);
                 /* We have to regenerate the repcodes because we've skipped some sequences */
@@ -578,8 +580,9 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
 
 size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc,
                                void* dst, size_t dstCapacity,
-                               void const* src, size_t srcSize,
-                               unsigned lastBlock) {
+                               const void* src, size_t srcSize,
+                               unsigned lastBlock)
+{
     ZSTD_entropyCTablesMetadata_t entropyMetadata;
 
     FORWARD_IF_ERROR(ZSTD_buildBlockEntropyStats(&zc->seqStore,
diff --git a/tests/fuzz/dictionary_round_trip.c b/tests/fuzz/dictionary_round_trip.c
index 06fdf24e9..0470fbf53 100644
--- a/tests/fuzz/dictionary_round_trip.c
+++ b/tests/fuzz/dictionary_round_trip.c
@@ -23,13 +23,13 @@
 #include "fuzz_data_producer.h"
 #include "fuzz_third_party_seq_prod.h"
 
-static ZSTD_CCtx *cctx = NULL;
-static ZSTD_DCtx *dctx = NULL;
+static ZSTD_CCtx* cctx = NULL;
+static ZSTD_DCtx* dctx = NULL;
 
-static size_t roundTripTest(void *result, size_t resultCapacity,
-                            void *compressed, size_t compressedCapacity,
-                            const void *src, size_t srcSize,
-                            FUZZ_dataProducer_t *producer)
+static size_t roundTripTest(void* result, size_t resultCapacity,
+                            void* compressed, size_t compressedCapacity,
+                            const void* src, size_t srcSize,
+                            FUZZ_dataProducer_t* producer)
 {
     ZSTD_dictContentType_e dictContentType = ZSTD_dct_auto;
     FUZZ_dict_t dict = FUZZ_train(src, srcSize, producer);

From 4b5152641239c571ae6cd67ae74cc87776e21362 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 24 Feb 2024 01:24:58 -0800
Subject: [PATCH 211/937] fix partial block uncompressed

---
 lib/compress/zstd_compress_superblock.c | 122 +++++++++++++-----------
 lib/decompress/zstd_decompress.c        |  11 ++-
 lib/decompress/zstd_decompress_block.c  |   2 +-
 3 files changed, 73 insertions(+), 62 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 09219d007..b35d9ad07 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -127,26 +127,25 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
 
 static size_t
 ZSTD_seqDecompressedSize(seqStore_t const* seqStore,
-                   const seqDef* sequences, size_t nbSeq,
-                         size_t litSize, int lastSequence)
+                   const seqDef* sequences, size_t nbSeqs,
+                         size_t litSize, int lastSubBlock)
 {
-    const seqDef* const sstart = sequences;
-    const seqDef* const send = sequences + nbSeq;
-    const seqDef* sp = sstart;
     size_t matchLengthSum = 0;
     size_t litLengthSum = 0;
-    (void)(litLengthSum); /* suppress unused variable warning on some environments */
-    DEBUGLOG(6, "ZSTD_seqDecompressedSize (%u sequences from %p) (last==%i)", (unsigned)nbSeq, (const void*)sp, lastSequence);
-    while (sp < send) {
-        ZSTD_sequenceLength const seqLen = ZSTD_getSequenceLength(seqStore, sp);
+    size_t n;
+    for (n=0; n %zu bytes", seqCount, (const void*)sp, total);
+    DEBUGLOG(5, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);
     return total;
 }
 
@@ -451,6 +450,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
 {
     const seqDef* const sstart = seqStorePtr->sequencesStart;
     const seqDef* const send = seqStorePtr->sequences;
+    const seqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */
     size_t const nbSeqs = (size_t)(send - sstart);
     size_t nbSeqsPerBlock = nbSeqs;
     const BYTE* const lstart = seqStorePtr->litStart;
@@ -471,8 +471,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     int writeSeqEntropy = 1;
     size_t nbSubBlocks = 1;
 
-    DEBUGLOG(5, "ZSTD_compressSubBlock_multi (litSize=%u, nbSeq=%u)",
-                (unsigned)(lend-lp), (unsigned)(send-sstart));
+    DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
+               (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
 
     if (nbSeqs == 0) {
         /* special case : no sequence */
@@ -502,17 +502,18 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
 
     /* write sub-blocks */
     {   size_t n;
+        size_t nbSeqsToProcess = 0;
         for (n=0; n < nbSubBlocks; n++) {
-            const seqDef* sp = sstart + n*nbSeqsPerBlock;
-            int lastSubBlock = (n==nbSubBlocks-1);
+            int const lastSubBlock = (n==nbSubBlocks-1);
             size_t const nbSeqsLastSubBlock = nbSeqs - (nbSubBlocks-1) * nbSeqsPerBlock;
-            size_t seqCount = lastSubBlock ? nbSeqsLastSubBlock : nbSeqsPerBlock;
+            size_t nbSeqsSubBlock = lastSubBlock ? nbSeqsLastSubBlock : nbSeqsPerBlock;
+            size_t seqCount = nbSeqsToProcess+nbSeqsSubBlock;
             size_t litSize = lastSubBlock ? (size_t)(lend-lp) : countLiterals(seqStorePtr, sp, seqCount);
             int litEntropyWritten = 0;
             int seqEntropyWritten = 0;
             const size_t decompressedSize =
                     ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSubBlock);
-            size_t cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
+            size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
                                                sp, seqCount,
                                                lp, litSize,
                                                llCodePtr, mlCodePtr, ofCodePtr,
@@ -521,59 +522,66 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                                                bmi2, writeLitEntropy, writeSeqEntropy,
                                                &litEntropyWritten, &seqEntropyWritten,
                                                lastBlock && lastSubBlock);
+            nbSeqsToProcess = seqCount;
             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
 
-            if (cSize == 0 || (cSize >= decompressedSize && n>0)) {
-                litEntropyWritten = 0;
-                seqEntropyWritten = 0;
-                cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, decompressedSize, lastBlock);
-                DEBUGLOG(5, "Generate uncompressed sub-block of %u bytes", (unsigned)(decompressedSize));
-                FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
-                assert(cSize != 0);
-                /* We have to regenerate the repcodes because we've skipped some sequences */
-                if (sp < send) {
-                    seqDef const* seq;
-                    repcodes_t rep;
-                    ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
-                    for (seq = sstart; seq < sp; ++seq) {
-                        ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
-                    }
-                    ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
+            if (cSize > 0 && cSize < decompressedSize) {
+                DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
+                            (unsigned)decompressedSize, (unsigned)cSize);
+                assert(ip + decompressedSize <= iend);
+                ip += decompressedSize;
+                lp += litSize;
+                op += cSize;
+                llCodePtr += seqCount;
+                mlCodePtr += seqCount;
+                ofCodePtr += seqCount;
+                /* Entropy only needs to be written once */
+                if (litEntropyWritten) {
+                    writeLitEntropy = 0;
                 }
+                if (seqEntropyWritten) {
+                    writeSeqEntropy = 0;
+                }
+                sp += seqCount;
+                nbSeqsToProcess = 0;
             }
-
-            DEBUGLOG(5, "Committed the sub-block");
-            assert(ip + decompressedSize <= iend);
-            ip += decompressedSize;
-            sp += seqCount;
-            lp += litSize;
-            op += cSize;
-            llCodePtr += seqCount;
-            mlCodePtr += seqCount;
-            ofCodePtr += seqCount;
-            /* Entropy only needs to be written once */
-            if (litEntropyWritten) {
-                writeLitEntropy = 0;
-            }
-            if (seqEntropyWritten) {
-                writeSeqEntropy = 0;
-            }
+            /* otherwise : coalesce current block with next one */
         }
     }
 
     if (writeLitEntropy) {
-        DEBUGLOG(5, "ZSTD_compressSubBlock_multi has literal entropy tables unwritten");
+        DEBUGLOG(5, "Literal entropy tables were never written");
         ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
     }
     if (writeSeqEntropy && ZSTD_needSequenceEntropyTables(&entropyMetadata->fseMetadata)) {
         /* If we haven't written our entropy tables, then we've violated our contract and
          * must emit an uncompressed block.
          */
-        DEBUGLOG(5, "ZSTD_compressSubBlock_multi has sequence entropy tables unwritten");
+        DEBUGLOG(5, "Sequence entropy tables were never written => cancel, emit an uncompressed block");
         return 0;
     }
-    assert(ip == iend); (void)iend;
-    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed: %u subBlocks, total compressed size = %u",
+
+    if (ip < iend) {
+        /* some data left : last part of the block sent uncompressed */
+        size_t const rSize = (size_t)((iend - ip));
+        size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
+        DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
+        FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
+        assert(cSize != 0);
+        op += cSize;
+        /* We have to regenerate the repcodes because we've skipped some sequences */
+        if (sp < send) {
+            const seqDef* seq;
+            repcodes_t rep;
+            ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep));
+            for (seq = sstart; seq < sp; ++seq) {
+                ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0);
+            }
+            ZSTD_memcpy(nextCBlock->rep, &rep, sizeof(rep));
+        }
+    }
+
+    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed %u subBlocks: total compressed size = %u",
                 (unsigned)nbSubBlocks, (unsigned)(op-ostart));
     return (size_t)(op-ostart);
 }
diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index f57b31e70..0d17b5e07 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -18,6 +18,7 @@
  * on stack (0), or into heap (1, default; requires malloc()).
  * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
  */
+#include "error_private.h"
 #ifndef ZSTD_HEAPMODE
 #  define ZSTD_HEAPMODE 1
 #endif
@@ -1023,12 +1024,14 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
         default:
             RETURN_ERROR(corruption_detected, "invalid block type");
         }
-
-        if (ZSTD_isError(decodedSize)) return decodedSize;
-        if (dctx->validateChecksum)
+        FORWARD_IF_ERROR(decodedSize, "Block decompression failure");
+        DEBUGLOG(5, "Decompressed block of dSize = %u", (unsigned)decodedSize);
+        if (dctx->validateChecksum) {
             XXH64_update(&dctx->xxhState, op, decodedSize);
-        if (decodedSize != 0)
+        }
+        if (decodedSize) /* support dst = NULL,0 */ {
             op += decodedSize;
+        }
         assert(ip != NULL);
         ip += cBlockSize;
         remainingSrcSize -= cBlockSize;
diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 4be145732..1943d7f57 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -2073,7 +2073,7 @@ ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
                         const void* src, size_t srcSize, const streaming_operation streaming)
 {   /* blockType == blockCompressed */
     const BYTE* ip = (const BYTE*)src;
-    DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
+    DEBUGLOG(5, "ZSTD_decompressBlock_internal (cSize : %u)", (unsigned)srcSize);
 
     /* Note : the wording of the specification
      * allows compressed block to be sized exactly ZSTD_blockSizeMax(dctx).

From f77f634d41149c3e5754ebfe4d5cf3a5f138c843 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 24 Feb 2024 01:28:17 -0800
Subject: [PATCH 212/937] update API documentation

---
 doc/zstd_manual.html             | 67 +++++++++++++++++++++-----------
 lib/decompress/zstd_decompress.c |  8 ++--
 2 files changed, 48 insertions(+), 27 deletions(-)

diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index d72eacc34..c81627d87 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -156,7 +156,7 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
  * for example to size a static array on stack.
  * Will produce constant value 0 if srcSize too large.
  */
-#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00LLU : 0xFF00FF00U)
+#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
 #define ZSTD_COMPRESSBOUND(srcSize)   (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
 size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
 /* ZSTD_isError() :
@@ -513,6 +513,7 @@ size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);  /* accept NULL pointer */
      * ZSTD_d_forceIgnoreChecksum
      * ZSTD_d_refMultipleDDicts
      * ZSTD_d_disableHuffmanAssembly
+     * ZSTD_d_maxBlockSize
      * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
      * note : never ever use experimentalParam? names directly
      */
@@ -520,7 +521,8 @@ size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);  /* accept NULL pointer */
      ZSTD_d_experimentalParam2=1001,
      ZSTD_d_experimentalParam3=1002,
      ZSTD_d_experimentalParam4=1003,
-     ZSTD_d_experimentalParam5=1004
+     ZSTD_d_experimentalParam5=1004,
+     ZSTD_d_experimentalParam6=1005
 
 } ZSTD_dParameter;
 

@@ -1386,58 +1388,61 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize,

Memory management


 
-
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int compressionLevel);
+
ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize(int maxCompressionLevel);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateDCtxSize(void);
 

These functions make it possible to estimate memory usage of a future {D,C}Ctx, before its creation. + This is useful in combination with ZSTD_initStatic(), + which makes it possible to employ a static buffer for ZSTD_CCtx* state. ZSTD_estimateCCtxSize() will provide a memory budget large enough - for any compression level up to selected one. - Note : Unlike ZSTD_estimateCStreamSize*(), this estimate - does not include space for a window buffer. - Therefore, the estimation is only guaranteed for single-shot compressions, not streaming. + to compress data of any size using one-shot compression ZSTD_compressCCtx() or ZSTD_compress2() + associated with any compression level up to max specified one. The estimate will assume the input may be arbitrarily large, which is the worst case. + Note that the size estimation is specific for one-shot compression, + it is not valid for streaming (see ZSTD_estimateCStreamSize*()) + nor other potential ways of using a ZSTD_CCtx* state. + When srcSize can be bound by a known and rather "small" value, - this fact can be used to provide a tighter estimation - because the CCtx compression context will need less memory. - This tighter estimation can be provided by more advanced functions + this knowledge can be used to provide a tighter budget estimation + because the ZSTD_CCtx* state will need less memory for small inputs. + This tighter estimation can be provided by employing more advanced functions ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(), and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter(). Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits. Note : only single-threaded compression is supported. ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. - - Note 2 : ZSTD_estimateCCtxSize* functions are not compatible with the Block-Level Sequence Producer API at this time. - Size estimates assume that no external sequence producer is registered.


-
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int compressionLevel);
+
ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize(int maxCompressionLevel);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params);
-ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t windowSize);
+ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize(size_t maxWindowSize);
 ZSTDLIB_STATIC_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);
-

ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one. - It will also consider src size to be arbitrarily "large", which is worst case. +

ZSTD_estimateCStreamSize() will provide a memory budget large enough for streaming compression + using any compression level up to the max specified one. + It will also consider src size to be arbitrarily "large", which is a worst case scenario. If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation. ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel. ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1. Note : CStream size estimation is only correct for single-threaded compression. - ZSTD_DStream memory budget depends on window Size. + ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. + Note 2 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. + Size estimates assume that no external sequence producer is registered. + + ZSTD_DStream memory budget depends on frame's window Size. This information can be passed manually, using ZSTD_estimateDStreamSize, or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame(); + Any frame requesting a window size larger than max specified one will be rejected. Note : if streaming is init with function ZSTD_init?Stream_usingDict(), an internal ?Dict will be created, which additional size is not estimated here. In this case, get total size by adding ZSTD_estimate?DictSize - Note 2 : only single-threaded compression is supported. - ZSTD_estimateCStreamSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1. - Note 3 : ZSTD_estimateCStreamSize* functions are not compatible with the Block-Level Sequence Producer API at this time. - Size estimates assume that no external sequence producer is registered.


@@ -1926,7 +1931,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); ZSTD_registerSequenceProducer( ZSTD_CCtx* cctx, void* sequenceProducerState, - ZSTD_sequenceProducer_F* sequenceProducer + ZSTD_sequenceProducer_F sequenceProducer );

Instruct zstd to use a block-level external sequence producer function. @@ -1948,6 +1953,22 @@ ZSTD_registerSequenceProducer( calling this function.


+
ZSTDLIB_STATIC_API void
+ZSTD_CCtxParams_registerSequenceProducer(
+  ZSTD_CCtx_params* params,
+  void* sequenceProducerState,
+  ZSTD_sequenceProducer_F sequenceProducer
+);
+

Same as ZSTD_registerSequenceProducer(), but operates on ZSTD_CCtx_params. + This is used for accurate size estimation with ZSTD_estimateCCtxSize_usingCCtxParams(), + which is needed when creating a ZSTD_CCtx with ZSTD_initStaticCCtx(). + + If you are using the external sequence producer API in a scenario where ZSTD_initStaticCCtx() + is required, then this function is for you. Otherwise, you probably don't need it. + + See tests/zstreamtest.c for example usage. +


+

Buffer-less and synchronous inner streaming functions (DEPRECATED)

   This API is deprecated, and will be removed in a future version.
   It allows streaming (de)compression with user allocated buffers.
diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index 0d17b5e07..173059085 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -18,7 +18,6 @@
  * on stack (0), or into heap (1, default; requires malloc()).
  * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
  */
-#include "error_private.h"
 #ifndef ZSTD_HEAPMODE
 #  define ZSTD_HEAPMODE 1
 #endif
@@ -56,18 +55,19 @@
 /*-*******************************************************
 *  Dependencies
 *********************************************************/
-#include "../common/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
 #include "../common/zstd_deps.h"   /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */
+#include "../common/allocations.h"  /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */
+#include "../common/error_private.h"
+#include "../common/zstd_internal.h"  /* blockProperties_t */
 #include "../common/mem.h"         /* low level memory routines */
+#include "../common/bits.h"  /* ZSTD_highbit32 */
 #define FSE_STATIC_LINKING_ONLY
 #include "../common/fse.h"
 #include "../common/huf.h"
 #include "../common/xxhash.h" /* XXH64_reset, XXH64_update, XXH64_digest, XXH64 */
-#include "../common/zstd_internal.h"  /* blockProperties_t */
 #include "zstd_decompress_internal.h"   /* ZSTD_DCtx */
 #include "zstd_ddict.h"  /* ZSTD_DDictDictContent */
 #include "zstd_decompress_block.h"   /* ZSTD_decompressBlock_internal */
-#include "../common/bits.h"  /* ZSTD_highbit32 */
 
 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
 #  include "../legacy/zstd_legacy.h"

From f8372191f595f112ba13445205cf46997da67350 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 24 Feb 2024 01:59:16 -0800
Subject: [PATCH 213/937] reduced minimum compressed block size

with the intention to match the transport layer size,
such as Ethernet and 4G mobile networks.
---
 lib/compress/zstd_compress_superblock.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index b35d9ad07..824a2be6d 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -76,8 +76,8 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
     }
 
     {   int const flags = bmi2 ? HUF_flags_bmi2 : 0;
-        const size_t cSize = singleStream ? HUF_compress1X_usingCTable(op, oend-op, literals, litSize, hufTable, flags)
-                                          : HUF_compress4X_usingCTable(op, oend-op, literals, litSize, hufTable, flags);
+        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)) {
@@ -102,7 +102,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable,
     switch(lhSize)
     {
     case 3: /* 2 - 2 - 10 - 10 */
-        {   U32 const lhc = hType + ((!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
+        {   U32 const lhc = hType + ((U32)(!singleStream) << 2) + ((U32)litSize<<4) + ((U32)cLitSize<<14);
             MEM_writeLE24(ostart, lhc);
             break;
         }
@@ -465,7 +465,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const BYTE* llCodePtr = seqStorePtr->llCode;
     const BYTE* mlCodePtr = seqStorePtr->mlCode;
     const BYTE* ofCodePtr = seqStorePtr->ofCode;
-    size_t const minTarget = 2 KB; /* enforce minimum size to avoid undesirable side effects */
+    size_t const minTarget = 1300; /* enforce minimum size, to reduce undesirable side effects */
     size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
     int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
     int writeSeqEntropy = 1;

From 4d2bf7f0f2feb2c6928204db218ff9384ac605ac Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 24 Feb 2024 23:03:40 -0800
Subject: [PATCH 214/937] removed sprintf usage from zstdcli.c

some static analyzers flag this standard C90 function as unsafe.
---
 programs/zstdcli.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 85d0e12d7..1cb16ef50 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -318,7 +318,7 @@ static void usageAdvanced(const char* programName)
 
 static void badUsage(const char* programName, const char* parameter)
 {
-    DISPLAYLEVEL(1, "Incorrect parameter: %s\n", parameter);
+    DISPLAYLEVEL(1, "Incorrect parameter: %s \n", parameter);
     if (g_displayLevel >= 2) usage(stderr, programName);
 }
 
@@ -1148,7 +1148,6 @@ int main(int argCount, const char* argv[])
 
             argument++;
             while (argument[0]!=0) {
-                char shortArgument[3];
 
 #ifndef ZSTD_NOCOMPRESS
                 /* compression Level */
@@ -1281,9 +1280,11 @@ int main(int argCount, const char* argv[])
 
                     /* unknown command */
                 default :
-                    sprintf(shortArgument, "-%c", argument[0]);
-                    badUsage(programName, shortArgument);
-                    CLEAN_RETURN(1);
+                    {   char shortArgument[3] = {'-', 0, 0};
+                        shortArgument[1] = argument[0];
+                        badUsage(programName, shortArgument);
+                        CLEAN_RETURN(1);
+                    }
                 }
             }
             continue;

From 038a8a906b8bbf60491b2643febaf8f9d5a4139c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 25 Feb 2024 17:33:41 -0800
Subject: [PATCH 215/937] targetCBlockSize: modified splitting strategy to
 generate blocks of more regular size

notably avoiding to feature a larger first block
---
 lib/compress/zstd_compress_superblock.c | 166 +++++++++++++++++-------
 1 file changed, 119 insertions(+), 47 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 824a2be6d..a32616409 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -390,7 +390,11 @@ static size_t ZSTD_estimateSubBlockSize_sequences(const BYTE* ofCodeTable,
     return cSeqSizeEstimate + sequencesSectionHeaderSize;
 }
 
-static size_t ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
+typedef struct {
+    size_t estLitSize;
+    size_t estBlockSize;
+} EstimatedBlockSize;
+static EstimatedBlockSize ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
                                         const BYTE* ofCodeTable,
                                         const BYTE* llCodeTable,
                                         const BYTE* mlCodeTable,
@@ -398,15 +402,17 @@ static size_t ZSTD_estimateSubBlockSize(const BYTE* literals, size_t litSize,
                                         const ZSTD_entropyCTables_t* entropy,
                                         const ZSTD_entropyCTablesMetadata_t* entropyMetadata,
                                         void* workspace, size_t wkspSize,
-                                        int writeLitEntropy, int writeSeqEntropy) {
-    size_t cSizeEstimate = 0;
-    cSizeEstimate += ZSTD_estimateSubBlockSize_literal(literals, litSize,
-                                                         &entropy->huf, &entropyMetadata->hufMetadata,
-                                                         workspace, wkspSize, writeLitEntropy);
-    cSizeEstimate += ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
+                                        int writeLitEntropy, int writeSeqEntropy)
+{
+    EstimatedBlockSize ebs;
+    ebs.estLitSize = ZSTD_estimateSubBlockSize_literal(literals, litSize,
+                                                        &entropy->huf, &entropyMetadata->hufMetadata,
+                                                        workspace, wkspSize, writeLitEntropy);
+    ebs.estBlockSize = ZSTD_estimateSubBlockSize_sequences(ofCodeTable, llCodeTable, mlCodeTable,
                                                          nbSeq, &entropy->fse, &entropyMetadata->fseMetadata,
                                                          workspace, wkspSize, writeSeqEntropy);
-    return cSizeEstimate + ZSTD_blockHeaderSize;
+    ebs.estBlockSize += ebs.estLitSize + ZSTD_blockHeaderSize;
+    return ebs;
 }
 
 static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMetadata)
@@ -427,17 +433,43 @@ static size_t countLiterals(seqStore_t const* seqStore, const seqDef* sp, size_t
     for (n=0; n %zu bytes", seqCount, (const void*)sp, total);
+    DEBUGLOG(6, "countLiterals for %zu sequences from %p => %zu bytes", seqCount, (const void*)sp, total);
     return total;
 }
 
+#define BYTESCALE 256
+
+static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs,
+                size_t targetBudget, size_t avgLitCost, size_t avgSeqCost,
+                int firstSubBlock)
+{
+    size_t n, budget = 0;
+    /* entropy headers */
+    if (firstSubBlock) {
+        budget += 120 * BYTESCALE; /* generous estimate */
+    }
+    /* first sequence => at least one sequence*/
+    budget += sp[0].litLength * avgLitCost + avgSeqCost;;
+    if (budget > targetBudget) return 1;
+
+    /* loop over sequences */
+    for (n=1; n targetBudget) break;
+        budget += currentCost;
+    }
+    return n;
+}
+
+#define CBLOCK_TARGET_SIZE_MIN 1300 /* suitable to fit an ethernet / wifi / 4G transport frame */
+
 /** ZSTD_compressSubBlock_multi() :
  *  Breaks super-block into multiple sub-blocks and compresses them.
- *  Entropy will be written to the first block.
- *  The following blocks will use repeat mode to compress.
- *  All sub-blocks are compressed blocks (no raw or rle blocks).
- *  @return : compressed size of the super block (which is multiple ZSTD blocks)
- *            Or 0 if it failed to compress. */
+ *  Entropy will be written into the first block.
+ *  The following blocks use repeat_mode to compress.
+ *  Sub-blocks are all compressed, except the last one when beneficial.
+ *  @return : compressed size of the super block (which features multiple ZSTD blocks)
+ *            or 0 if it failed to compress. */
 static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                             const ZSTD_compressedBlockState_t* prevCBlock,
                             ZSTD_compressedBlockState_t* nextCBlock,
@@ -452,7 +484,6 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const seqDef* const send = seqStorePtr->sequences;
     const seqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */
     size_t const nbSeqs = (size_t)(send - sstart);
-    size_t nbSeqsPerBlock = nbSeqs;
     const BYTE* const lstart = seqStorePtr->litStart;
     const BYTE* const lend = seqStorePtr->lit;
     const BYTE* lp = lstart;
@@ -465,54 +496,96 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     const BYTE* llCodePtr = seqStorePtr->llCode;
     const BYTE* mlCodePtr = seqStorePtr->mlCode;
     const BYTE* ofCodePtr = seqStorePtr->ofCode;
-    size_t const minTarget = 1300; /* enforce minimum size, to reduce undesirable side effects */
+    size_t const minTarget = CBLOCK_TARGET_SIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */
     size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
     int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
     int writeSeqEntropy = 1;
     size_t nbSubBlocks = 1;
+    size_t avgLitCost, avgSeqCost, avgBlockBudget;
 
     DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
                (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
 
+        /* let's start by a general estimation for the full block */
     if (nbSeqs == 0) {
-        /* special case : no sequence */
-        nbSeqsPerBlock = 0;
         nbSubBlocks = 1;
     } else {
-        /* let's start by a general estimation for the full block */
-        size_t const cBlockSizeEstimate =
+        EstimatedBlockSize const ebs =
                 ZSTD_estimateSubBlockSize(lp, nbLiterals,
                                         ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
                                         &nextCBlock->entropy, entropyMetadata,
                                         workspace, wkspSize,
                                         writeLitEntropy, writeSeqEntropy);
         /* quick estimation */
-        nbSubBlocks = (cBlockSizeEstimate + (targetCBlockSize-1)) / targetCBlockSize;
-        assert(nbSubBlocks > 0);
-        if (nbSeqs > nbSubBlocks) {
-            nbSeqsPerBlock = nbSeqs / nbSubBlocks;
-        } else {
-            nbSeqsPerBlock = 1;
-            nbSubBlocks = nbSeqs;
-        }
-        /* Note: this is very approximative. Obviously, some sub-blocks will be larger and others smaller.
-         * But the contract of this feature has always been approximative, so for now we'll leverage it for speed.
-         * It can be refined later, for closer-to-target compressed block size, if it ever matters. */
+        avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
+        avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
+        nbSubBlocks = (ebs.estBlockSize + (targetCBlockSize-1)) / targetCBlockSize;
+        if (nbSubBlocks<1) nbSubBlocks=1;
+        avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
+        DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
+                    (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
+                    (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
     }
 
-    /* write sub-blocks */
+    /* compress and write sub-blocks */
     {   size_t n;
-        size_t nbSeqsToProcess = 0;
-        for (n=0; n < nbSubBlocks; n++) {
-            int const lastSubBlock = (n==nbSubBlocks-1);
-            size_t const nbSeqsLastSubBlock = nbSeqs - (nbSubBlocks-1) * nbSeqsPerBlock;
-            size_t nbSeqsSubBlock = lastSubBlock ? nbSeqsLastSubBlock : nbSeqsPerBlock;
-            size_t seqCount = nbSeqsToProcess+nbSeqsSubBlock;
-            size_t litSize = lastSubBlock ? (size_t)(lend-lp) : countLiterals(seqStorePtr, sp, seqCount);
-            int litEntropyWritten = 0;
+        size_t blockBudgetSupp = 0;
+        for (n=0; n+1 < nbSubBlocks; n++) {
+            /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
+            size_t seqCount = sizeBlockSequences(sp, (size_t)(send-sp), avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
+            /* if reached last sequence : break to last sub-block (simplification) */
+            assert(seqCount <= (size_t)(send-sp));
+            if (sp + seqCount == send) break;
+            assert(seqCount > 0);
+            /* compress sub-block */
+            {   int litEntropyWritten = 0;
+                int seqEntropyWritten = 0;
+                size_t litSize = countLiterals(seqStorePtr, sp, seqCount);
+                const size_t decompressedSize =
+                        ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 0);
+                size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
+                                                sp, seqCount,
+                                                lp, litSize,
+                                                llCodePtr, mlCodePtr, ofCodePtr,
+                                                cctxParams,
+                                                op, (size_t)(oend-op),
+                                                bmi2, writeLitEntropy, writeSeqEntropy,
+                                                &litEntropyWritten, &seqEntropyWritten,
+                                                0);
+                FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
+
+                /* check compressibility, update state components */
+                if (cSize > 0 && cSize < decompressedSize) {
+                    DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
+                                (unsigned)decompressedSize, (unsigned)cSize);
+                    assert(ip + decompressedSize <= iend);
+                    ip += decompressedSize;
+                    lp += litSize;
+                    op += cSize;
+                    llCodePtr += seqCount;
+                    mlCodePtr += seqCount;
+                    ofCodePtr += seqCount;
+                    /* Entropy only needs to be written once */
+                    if (litEntropyWritten) {
+                        writeLitEntropy = 0;
+                    }
+                    if (seqEntropyWritten) {
+                        writeSeqEntropy = 0;
+                    }
+                    sp += seqCount;
+                    blockBudgetSupp = 0;
+            }   }
+            /* otherwise : do not compress yet, coalesce current block with next one */
+        }
+
+        /* write last block */
+        DEBUGLOG(2, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
+        {   int litEntropyWritten = 0;
             int seqEntropyWritten = 0;
+            size_t litSize = (size_t)(lend - lp);
+            size_t seqCount = (size_t)(send - sp);
             const size_t decompressedSize =
-                    ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, lastSubBlock);
+                    ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
             size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
                                                sp, seqCount,
                                                lp, litSize,
@@ -521,12 +594,12 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                                                op, (size_t)(oend-op),
                                                bmi2, writeLitEntropy, writeSeqEntropy,
                                                &litEntropyWritten, &seqEntropyWritten,
-                                               lastBlock && lastSubBlock);
-            nbSeqsToProcess = seqCount;
+                                               lastBlock);
             FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
 
+            /* update pointers, the nb of literals borrowed from next sequence must be preserved */
             if (cSize > 0 && cSize < decompressedSize) {
-                DEBUGLOG(5, "Committed sub-block compressing %u bytes => %u bytes",
+                DEBUGLOG(2, "Last sub-block compressed %u bytes => %u bytes",
                             (unsigned)decompressedSize, (unsigned)cSize);
                 assert(ip + decompressedSize <= iend);
                 ip += decompressedSize;
@@ -543,9 +616,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                     writeSeqEntropy = 0;
                 }
                 sp += seqCount;
-                nbSeqsToProcess = 0;
+                blockBudgetSupp = 0;
             }
-            /* otherwise : coalesce current block with next one */
         }
     }
 
@@ -565,7 +637,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         /* some data left : last part of the block sent uncompressed */
         size_t const rSize = (size_t)((iend - ip));
         size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
-        DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
+        DEBUGLOG(2, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
         FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
         assert(cSize != 0);
         op += cSize;

From 1fafd0c4ae56a524a92369c065d616a447a21a0f Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 25 Feb 2024 19:45:32 -0800
Subject: [PATCH 216/937] fix minor visual static analyzer warning

it's a false positive,
but change the code nonetheless to make it more obvious to the static analyzer.
---
 lib/compress/zstd_compress_superblock.c | 96 ++++++++++++-------------
 1 file changed, 45 insertions(+), 51 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index a32616409..5d0d23353 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -500,16 +500,12 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize);
     int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed);
     int writeSeqEntropy = 1;
-    size_t nbSubBlocks = 1;
-    size_t avgLitCost, avgSeqCost, avgBlockBudget;
 
     DEBUGLOG(5, "ZSTD_compressSubBlock_multi (srcSize=%u, litSize=%u, nbSeq=%u)",
                (unsigned)srcSize, (unsigned)(lend-lstart), (unsigned)(send-sstart));
 
         /* let's start by a general estimation for the full block */
-    if (nbSeqs == 0) {
-        nbSubBlocks = 1;
-    } else {
+    if (nbSeqs > 0) {
         EstimatedBlockSize const ebs =
                 ZSTD_estimateSubBlockSize(lp, nbLiterals,
                                         ofCodePtr, llCodePtr, mlCodePtr, nbSeqs,
@@ -517,19 +513,17 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                                         workspace, wkspSize,
                                         writeLitEntropy, writeSeqEntropy);
         /* quick estimation */
-        avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
-        avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
-        nbSubBlocks = (ebs.estBlockSize + (targetCBlockSize-1)) / targetCBlockSize;
+        size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
+        size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
+        size_t nbSubBlocks = (ebs.estBlockSize + (targetCBlockSize-1)) / targetCBlockSize;
+        size_t n, avgBlockBudget, blockBudgetSupp=0;
         if (nbSubBlocks<1) nbSubBlocks=1;
         avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
         DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
                     (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
                     (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
-    }
 
     /* compress and write sub-blocks */
-    {   size_t n;
-        size_t blockBudgetSupp = 0;
         for (n=0; n+1 < nbSubBlocks; n++) {
             /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
             size_t seqCount = sizeBlockSequences(sp, (size_t)(send-sp), avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
@@ -577,50 +571,50 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
             }   }
             /* otherwise : do not compress yet, coalesce current block with next one */
         }
+    } /* if (nbSeqs > 0) */
 
-        /* write last block */
-        DEBUGLOG(2, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
-        {   int litEntropyWritten = 0;
-            int seqEntropyWritten = 0;
-            size_t litSize = (size_t)(lend - lp);
-            size_t seqCount = (size_t)(send - sp);
-            const size_t decompressedSize =
-                    ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
-            size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
-                                               sp, seqCount,
-                                               lp, litSize,
-                                               llCodePtr, mlCodePtr, ofCodePtr,
-                                               cctxParams,
-                                               op, (size_t)(oend-op),
-                                               bmi2, writeLitEntropy, writeSeqEntropy,
-                                               &litEntropyWritten, &seqEntropyWritten,
-                                               lastBlock);
-            FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
+    /* write last block */
+    DEBUGLOG(2, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
+    {   int litEntropyWritten = 0;
+        int seqEntropyWritten = 0;
+        size_t litSize = (size_t)(lend - lp);
+        size_t seqCount = (size_t)(send - sp);
+        const size_t decompressedSize =
+                ZSTD_seqDecompressedSize(seqStorePtr, sp, seqCount, litSize, 1);
+        size_t const cSize = ZSTD_compressSubBlock(&nextCBlock->entropy, entropyMetadata,
+                                            sp, seqCount,
+                                            lp, litSize,
+                                            llCodePtr, mlCodePtr, ofCodePtr,
+                                            cctxParams,
+                                            op, (size_t)(oend-op),
+                                            bmi2, writeLitEntropy, writeSeqEntropy,
+                                            &litEntropyWritten, &seqEntropyWritten,
+                                            lastBlock);
+        FORWARD_IF_ERROR(cSize, "ZSTD_compressSubBlock failed");
 
-            /* update pointers, the nb of literals borrowed from next sequence must be preserved */
-            if (cSize > 0 && cSize < decompressedSize) {
-                DEBUGLOG(2, "Last sub-block compressed %u bytes => %u bytes",
-                            (unsigned)decompressedSize, (unsigned)cSize);
-                assert(ip + decompressedSize <= iend);
-                ip += decompressedSize;
-                lp += litSize;
-                op += cSize;
-                llCodePtr += seqCount;
-                mlCodePtr += seqCount;
-                ofCodePtr += seqCount;
-                /* Entropy only needs to be written once */
-                if (litEntropyWritten) {
-                    writeLitEntropy = 0;
-                }
-                if (seqEntropyWritten) {
-                    writeSeqEntropy = 0;
-                }
-                sp += seqCount;
-                blockBudgetSupp = 0;
+        /* update pointers, the nb of literals borrowed from next sequence must be preserved */
+        if (cSize > 0 && cSize < decompressedSize) {
+            DEBUGLOG(2, "Last sub-block compressed %u bytes => %u bytes",
+                        (unsigned)decompressedSize, (unsigned)cSize);
+            assert(ip + decompressedSize <= iend);
+            ip += decompressedSize;
+            lp += litSize;
+            op += cSize;
+            llCodePtr += seqCount;
+            mlCodePtr += seqCount;
+            ofCodePtr += seqCount;
+            /* Entropy only needs to be written once */
+            if (litEntropyWritten) {
+                writeLitEntropy = 0;
             }
+            if (seqEntropyWritten) {
+                writeSeqEntropy = 0;
+            }
+            sp += seqCount;
         }
     }
 
+
     if (writeLitEntropy) {
         DEBUGLOG(5, "Literal entropy tables were never written");
         ZSTD_memcpy(&nextCBlock->entropy.huf, &prevCBlock->entropy.huf, sizeof(prevCBlock->entropy.huf));
@@ -653,8 +647,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         }
     }
 
-    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed %u subBlocks: total compressed size = %u",
-                (unsigned)nbSubBlocks, (unsigned)(op-ostart));
+    DEBUGLOG(5, "ZSTD_compressSubBlock_multi compressed all subBlocks: total compressed size = %u",
+                (unsigned)(op-ostart));
     return (size_t)(op-ostart);
 }
 

From a412bedb3f63a5bbb88601c0ab085a8eb0c39e48 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 26 Feb 2024 05:59:24 +0000
Subject: [PATCH 217/937] Bump github/codeql-action from 3.23.0 to 3.24.5

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.23.0 to 3.24.5.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/e5f05b81d5b6ff8cfa111c80c22c5fd02a384118...47b3d888fe66b639e431abf22ebca059152f1eea)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/scorecards.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 0ccd87625..fce0784e3 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -59,6 +59,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@e5f05b81d5b6ff8cfa111c80c22c5fd02a384118 # tag=v3.23.0
+        uses: github/codeql-action/upload-sarif@47b3d888fe66b639e431abf22ebca059152f1eea # tag=v3.24.5
         with:
           sarif_file: results.sarif

From e0412c20625c7358d506c969a9c9861b70eb10ee Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 12:26:54 -0800
Subject: [PATCH 218/937] fix extraneous semicolon ';'

as reported by @terrelln
---
 lib/compress/zstd_compress_superblock.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 5d0d23353..32bea370f 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -449,7 +449,7 @@ static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs,
         budget += 120 * BYTESCALE; /* generous estimate */
     }
     /* first sequence => at least one sequence*/
-    budget += sp[0].litLength * avgLitCost + avgSeqCost;;
+    budget += sp[0].litLength * avgLitCost + avgSeqCost;
     if (budget > targetBudget) return 1;
 
     /* loop over sequences */

From aa8592c532e1a2b30b08763140b9bd66bdce4f83 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 13:21:14 -0800
Subject: [PATCH 219/937] minor: reformulate nbSubBlocks assignment

---
 lib/compress/zstd_compress_superblock.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 32bea370f..cf3cb4362 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -461,7 +461,7 @@ static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs,
     return n;
 }
 
-#define CBLOCK_TARGET_SIZE_MIN 1300 /* suitable to fit an ethernet / wifi / 4G transport frame */
+#define CBLOCK_TARGET_SIZE_MIN 1340 /* suitable to fit into an ethernet / wifi / 4G transport frame */
 
 /** ZSTD_compressSubBlock_multi() :
  *  Breaks super-block into multiple sub-blocks and compresses them.
@@ -515,9 +515,8 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         /* quick estimation */
         size_t const avgLitCost = nbLiterals ? (ebs.estLitSize * BYTESCALE) / nbLiterals : BYTESCALE;
         size_t const avgSeqCost = ((ebs.estBlockSize - ebs.estLitSize) * BYTESCALE) / nbSeqs;
-        size_t nbSubBlocks = (ebs.estBlockSize + (targetCBlockSize-1)) / targetCBlockSize;
+        const size_t nbSubBlocks = MAX((ebs.estBlockSize + (targetCBlockSize/2)) / targetCBlockSize, 1);
         size_t n, avgBlockBudget, blockBudgetSupp=0;
-        if (nbSubBlocks<1) nbSubBlocks=1;
         avgBlockBudget = (ebs.estBlockSize * BYTESCALE) / nbSubBlocks;
         DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
                     (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,

From ef82b214ad1023f6123c3d9c9a7dbce24130d9bd Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 13:23:59 -0800
Subject: [PATCH 220/937] nit: comment indentation

as reported by @terrelln
---
 lib/compress/zstd_compress_superblock.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index cf3cb4362..e9038c472 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -522,7 +522,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                     (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
                     (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
 
-    /* compress and write sub-blocks */
+        /* compress and write sub-blocks */
         for (n=0; n+1 < nbSubBlocks; n++) {
             /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
             size_t seqCount = sizeBlockSequences(sp, (size_t)(send-sp), avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);

From 86db60752d1f813642054d12d704663c7757d434 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 13:27:59 -0800
Subject: [PATCH 221/937] optimization: bail out faster in presence of
 incompressible data

---
 lib/compress/zstd_compress_superblock.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index e9038c472..a9e9493be 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -521,6 +521,9 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         DEBUGLOG(5, "estimated fullblock size=%u bytes ; avgLitCost=%.2f ; avgSeqCost=%.2f ; targetCBlockSize=%u, nbSubBlocks=%u ; avgBlockBudget=%.0f bytes",
                     (unsigned)ebs.estBlockSize, (double)avgLitCost/BYTESCALE, (double)avgSeqCost/BYTESCALE,
                     (unsigned)targetCBlockSize, (unsigned)nbSubBlocks, (double)avgBlockBudget/BYTESCALE);
+        /* simplification: if estimates states that the full superblock doesn't compress, just bail out immediately
+         * this will result in the production of a single uncompressed block covering @srcSize.*/
+        if (ebs.estBlockSize > srcSize) return 0;
 
         /* compress and write sub-blocks */
         for (n=0; n+1 < nbSubBlocks; n++) {
@@ -568,7 +571,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
                     sp += seqCount;
                     blockBudgetSupp = 0;
             }   }
-            /* otherwise : do not compress yet, coalesce current block with next one */
+            /* otherwise : do not compress yet, coalesce current sub-block with following one */
         }
     } /* if (nbSeqs > 0) */
 

From d23b95d21d5cb9c5378b3537271dbbff7cdb49b7 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 14:06:34 -0800
Subject: [PATCH 222/937] minor refactor for clarity

since we can ensure that nbSubBlocks>0
---
 lib/compress/zstd_compress_superblock.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index a9e9493be..295ccf304 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -526,9 +526,11 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         if (ebs.estBlockSize > srcSize) return 0;
 
         /* compress and write sub-blocks */
-        for (n=0; n+1 < nbSubBlocks; n++) {
+        assert(nbSubBlocks>0);
+        for (n=0; n < nbSubBlocks-1; n++) {
             /* determine nb of sequences for current sub-block + nbLiterals from next sequence */
-            size_t seqCount = sizeBlockSequences(sp, (size_t)(send-sp), avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
+            size_t const seqCount = sizeBlockSequences(sp, (size_t)(send-sp),
+                                        avgBlockBudget + blockBudgetSupp, avgLitCost, avgSeqCost, n==0);
             /* if reached last sequence : break to last sub-block (simplification) */
             assert(seqCount <= (size_t)(send-sp));
             if (sp + seqCount == send) break;

From 8d31e8ec42a736bf7cc70f9f21e9c1afc920c148 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 26 Feb 2024 14:31:12 -0800
Subject: [PATCH 223/937] sizeBlockSequences() also tracks uncompressed size

and only defines a sub-block boundary when
it believes that it is compressible.

It's effectively an optimization,
avoiding a compression cycle to reach the same conclusion.
---
 lib/compress/zstd_compress_superblock.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index 295ccf304..f5430eccb 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -443,21 +443,29 @@ static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs,
                 size_t targetBudget, size_t avgLitCost, size_t avgSeqCost,
                 int firstSubBlock)
 {
-    size_t n, budget = 0;
+    size_t n, budget = 0, inSize=0;
     /* entropy headers */
-    if (firstSubBlock) {
-        budget += 120 * BYTESCALE; /* generous estimate */
-    }
+    size_t const headerSize = (size_t)firstSubBlock * 120 * BYTESCALE; /* generous estimate */
+    assert(firstSubBlock==0 || firstSubBlock==1);
+    budget += headerSize;
+
     /* first sequence => at least one sequence*/
     budget += sp[0].litLength * avgLitCost + avgSeqCost;
     if (budget > targetBudget) return 1;
+    inSize = sp[0].litLength + (sp[0].mlBase+MINMATCH);
 
     /* loop over sequences */
     for (n=1; n targetBudget) break;
         budget += currentCost;
+        inSize += sp[n].litLength + (sp[n].mlBase+MINMATCH);
+        /* stop when sub-block budget is reached */
+        if ( (budget > targetBudget)
+            /* though continue to expand until the sub-block is deemed compressible */
+          && (budget < inSize * BYTESCALE) )
+            break;
     }
+
     return n;
 }
 

From dcd713ce06fd9729e2e1eefa079be866f5e2f519 Mon Sep 17 00:00:00 2001
From: Theodore Tsirpanis 
Date: Tue, 27 Feb 2024 23:39:59 +0200
Subject: [PATCH 224/937] Define the unified target inside the CMake project,
 and export it.

This is less error-prone.
---
 build/cmake/lib/CMakeLists.txt  | 10 ++++++++++
 build/cmake/zstdConfig.cmake.in | 14 --------------
 2 files changed, 10 insertions(+), 14 deletions(-)

diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt
index 2b64a07e2..7e16470fd 100644
--- a/build/cmake/lib/CMakeLists.txt
+++ b/build/cmake/lib/CMakeLists.txt
@@ -145,6 +145,16 @@ if (ZSTD_BUILD_STATIC)
     add_definition(libzstd_static ZSTDLIB_STATIC_API)
     add_definition(libzstd_static ZDICTLIB_STATIC_API)
 endif ()
+if (ZSTD_BUILD_SHARED AND NOT ZSTD_BUILD_STATIC)
+    add_library(libzstd INTERFACE)
+    target_link_libraries(libzstd INTERFACE libzstd_shared)
+    list(APPEND library_targets libzstd)
+endif ()
+if (ZSTD_BUILD_STATIC AND NOT ZSTD_BUILD_SHARED)
+    add_library(libzstd INTERFACE)
+    target_link_libraries(libzstd INTERFACE libzstd_static)
+    list(APPEND library_targets libzstd)
+endif ()
 
 # Add specific compile definitions for MSVC project
 if (MSVC)
diff --git a/build/cmake/zstdConfig.cmake.in b/build/cmake/zstdConfig.cmake.in
index 0a7f773d7..f4190f989 100644
--- a/build/cmake/zstdConfig.cmake.in
+++ b/build/cmake/zstdConfig.cmake.in
@@ -7,18 +7,4 @@ endif()
 
 include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets.cmake")
 
-if(NOT TARGET zstd::libzstd)
-  if(@ZSTD_BUILD_SHARED@ AND NOT @ZSTD_BUILD_STATIC@)
-    add_library(zstd::libzstd INTERFACE IMPORTED)
-    set_target_properties(zstd::libzstd PROPERTIES
-      INTERFACE_LINK_LIBRARIES "zstd::libzstd_shared"
-    )
-  elseif(NOT @ZSTD_BUILD_SHARED@ AND @ZSTD_BUILD_STATIC@)
-    add_library(zstd::libzstd INTERFACE IMPORTED)
-    set_target_properties(zstd::libzstd PROPERTIES
-      INTERFACE_LINK_LIBRARIES "zstd::libzstd_static"
-    )
-  endif()
-endif()
-
 check_required_components("zstd")

From bb4f85db42925a1dd129e733d3413316ebd5c9bb Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 3 Mar 2024 18:47:08 -0800
Subject: [PATCH 225/937] fix version of actions/checkout

---
 .github/workflows/dev-long-tests.yml  | 50 +++++++++---------
 .github/workflows/dev-short-tests.yml | 74 +++++++++++++--------------
 2 files changed, 62 insertions(+), 62 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 399100531..21882f024 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -15,7 +15,7 @@ jobs:
   make-all:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: make all
       run: make all
 
@@ -26,7 +26,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: make test
       run: make test
 
@@ -34,7 +34,7 @@ jobs:
   make-test-osx:
     runs-on: macos-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: OS-X test
       run: make test # make -c lib all doesn't work because of the fact that it's not a tty
 
@@ -45,7 +45,7 @@ jobs:
       DEVNULLRIGHTS: 1
       READFROMBLOCKDEVICE: 1
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: make test
       run: |
         sudo apt-get -qqq update
@@ -55,21 +55,21 @@ jobs:
   no-intrinsics-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: no intrinsics fuzztest
       run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest
 
   tsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer zstreamtest
       run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream
 
   ubsan-zstreamtest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: undefined behavior sanitizer zstreamtest
       run: CC=clang make uasan-test-zstream
 
@@ -77,7 +77,7 @@ jobs:
   tsan-fuzztest:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer fuzztest
       run: CC=clang make tsan-fuzztest
 
@@ -85,7 +85,7 @@ jobs:
   big-tests-zstreamtest32:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: zstream tests in 32bit mode, with big tests
       run: |
         sudo apt-get -qqq update
@@ -96,7 +96,7 @@ jobs:
   gcc-8-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: gcc-8 + ASan + UBSan + Test Zstd
       # See https://askubuntu.com/a/1428822
       run: |
@@ -108,14 +108,14 @@ jobs:
   clang-asan-ubsan-testzstd:
     runs-on: ubuntu-latest
     steps:
-    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
+    - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: clang + ASan + UBSan + Test Zstd
       run: CC=clang make -j uasan-test-zstd 
Date: Mon, 4 Mar 2024 05:34:30 +0000
Subject: [PATCH 226/937] Bump github/codeql-action from 3.24.5 to 3.24.6

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.5 to 3.24.6.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/47b3d888fe66b639e431abf22ebca059152f1eea...8a470fddafa5cbb6266ee11b37ef4d8aae19c571)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/scorecards.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 18b0db45d..513320271 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -59,6 +59,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@47b3d888fe66b639e431abf22ebca059152f1eea # tag=v3.24.5
+        uses: github/codeql-action/upload-sarif@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # tag=v3.24.6
         with:
           sarif_file: results.sarif

From 4fb0a77314cabc65eb90895fae35a7f38ace560d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sun, 3 Mar 2024 23:24:40 -0800
Subject: [PATCH 227/937] update -V documentation

to answer #3727 comment
---
 programs/zstd.1.md | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index 078455f3e..c5d0ef70a 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -290,10 +290,11 @@ the last one takes effect.
 * `-h`/`-H`, `--help`:
     display help/long help and exit
 * `-V`, `--version`:
-    display version number and exit.
+    display version number and immediately exit.
+    note that, since it exits, flags specified after `-V` are effectively ignored.
     Advanced: `-vV` also displays supported formats.
     `-vvV` also displays POSIX support.
-    `-q` will only display the version number, suitable for machine reading.
+    `-qV` will only display the version number, suitable for machine reading.
 * `-v`, `--verbose`:
     verbose mode, display more information
 * `-q`, `--quiet`:

From 2abe8d63e06f0e7c9adacd50855a05023e51f1e0 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 4 Mar 2024 00:16:01 -0800
Subject: [PATCH 228/937] fix LLU->ULL

LLU is a correct prefix according to C99 & C11 standards (but not C90).
However, older versions of Visual Studio do not work with it.
Replace by ULL, which doesn't have this issue.

Fixes https://github.com/facebook/zstd/issues/3647
---
 tests/fuzzer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tests/fuzzer.c b/tests/fuzzer.c
index 6c1f58df7..093492181 100644
--- a/tests/fuzzer.c
+++ b/tests/fuzzer.c
@@ -531,7 +531,7 @@ static void test_decompressBound(unsigned tnb)
             CHECK_EQ( ZSTD_flushStream(cctx, &out), 0 );
         }
         CHECK_EQ( ZSTD_endStream(cctx, &out), 0 );
-        CHECK( ZSTD_decompressBound(outBuffer, out.pos) > 0x100000000LLU /* 4 GB */ );
+        CHECK( ZSTD_decompressBound(outBuffer, out.pos) > 0x100000000ULL /* 4 GB */ );
         ZSTD_freeCCtx(cctx);
         free(outBuffer);
     }

From 007cda88ca1c7819eec966ce030934756d33c8c1 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 7 Mar 2024 16:43:13 -0800
Subject: [PATCH 229/937] prevent XXH64 from being autovectorized by XXH512 by
 default

backport fix https://github.com/Cyan4973/xxHash/pull/924 from libxxhash
---
 lib/common/xxhash.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index e5ed3dc04..d95bad191 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -3317,6 +3317,23 @@ static xxh_u64 XXH64_round(xxh_u64 acc, xxh_u64 input)
     acc += input * XXH_PRIME64_2;
     acc  = XXH_rotl64(acc, 31);
     acc *= XXH_PRIME64_1;
+#if (defined(__AVX512F__)) && !defined(XXH_ENABLE_AUTOVECTORIZE)
+    /*
+     * DISABLE AUTOVECTORIZATION:
+     * A compiler fence is used to prevent GCC and Clang from
+     * autovectorizing the XXH64 loop (pragmas and attributes don't work for some
+     * reason) without globally disabling AVX512.
+     *
+     * Autovectorization of XXH64 tends to be detrimental,
+     * though the exact outcome may change depending on exact cpu and compiler version.
+     * For information, it has been reported as detrimental for Skylake-X,
+     * but possibly beneficial for Zen4.
+     *
+     * The default is to disable auto-vectorization,
+     * but you can select to enable it instead using `XXH_ENABLE_AUTOVECTORIZE` build variable.
+     */
+    XXH_COMPILER_GUARD(acc);
+#endif
     return acc;
 }
 

From ad590275b482d4c561bdc58418ef6b6a1db80c25 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 7 Mar 2024 16:54:44 -0800
Subject: [PATCH 230/937] added RISC-V emulation tests on Github CI

---
 .github/workflows/dev-short-tests.yml | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index a781c25d0..9c36386a1 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -380,6 +380,7 @@ jobs:
           { name: PPC64LE,  xcc_pkg: gcc-powerpc64le-linux-gnu, xcc: powerpc64le-linux-gnu-gcc, xemu_pkg: qemu-system-ppc,    xemu: qemu-ppc64le-static },
           { name: S390X,    xcc_pkg: gcc-s390x-linux-gnu,       xcc: s390x-linux-gnu-gcc,       xemu_pkg: qemu-system-s390x,  xemu: qemu-s390x-static   },
           { name: MIPS,     xcc_pkg: gcc-mips-linux-gnu,        xcc: mips-linux-gnu-gcc,        xemu_pkg: qemu-system-mips,   xemu: qemu-mips-static    },
+          { name: RISC-V,   xcc_pkg: gcc-riscv64-linux-gnu,     xcc: riscv64-linux-gnu-gcc,     xemu_pkg: qemu-system-riscv64,xemu: qemu-riscv64-static },
           { name: M68K,     xcc_pkg: gcc-m68k-linux-gnu,        xcc: m68k-linux-gnu-gcc,        xemu_pkg: qemu-system-m68k,   xemu: qemu-m68k-static    },
           { name: SPARC,    xcc_pkg: gcc-sparc64-linux-gnu,     xcc: sparc64-linux-gnu-gcc,     xemu_pkg: qemu-system-sparc,  xemu: qemu-sparc64-static },
         ]
@@ -424,6 +425,10 @@ jobs:
       if: ${{ matrix.name == 'MIPS' }}
       run: |
         LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check
+    - name: RISC-V
+      if: ${{ matrix.name == 'RISC-V' }}
+      run: |
+        LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check
     - name: M68K
       if: ${{ matrix.name == 'M68K' }}
       run: |

From aed172a8fe84caccc86e5f27999a309d1df47c00 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 8 Mar 2024 14:29:44 -0800
Subject: [PATCH 231/937] minor: fix incorrect debug level

---
 lib/compress/zstd_compress_superblock.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c
index f5430eccb..8c466c479 100644
--- a/lib/compress/zstd_compress_superblock.c
+++ b/lib/compress/zstd_compress_superblock.c
@@ -586,7 +586,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
     } /* if (nbSeqs > 0) */
 
     /* write last block */
-    DEBUGLOG(2, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
+    DEBUGLOG(5, "Generate last sub-block: %u sequences remaining", (unsigned)(send - sp));
     {   int litEntropyWritten = 0;
         int seqEntropyWritten = 0;
         size_t litSize = (size_t)(lend - lp);
@@ -606,7 +606,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
 
         /* update pointers, the nb of literals borrowed from next sequence must be preserved */
         if (cSize > 0 && cSize < decompressedSize) {
-            DEBUGLOG(2, "Last sub-block compressed %u bytes => %u bytes",
+            DEBUGLOG(5, "Last sub-block compressed %u bytes => %u bytes",
                         (unsigned)decompressedSize, (unsigned)cSize);
             assert(ip + decompressedSize <= iend);
             ip += decompressedSize;
@@ -643,7 +643,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr,
         /* some data left : last part of the block sent uncompressed */
         size_t const rSize = (size_t)((iend - ip));
         size_t const cSize = ZSTD_noCompressBlock(op, (size_t)(oend - op), ip, rSize, lastBlock);
-        DEBUGLOG(2, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
+        DEBUGLOG(5, "Generate last uncompressed sub-block of %u bytes", (unsigned)(rSize));
         FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed");
         assert(cSize != 0);
         op += cSize;

From a9fb8d4c41bf3cc829adf20aea3768863d03cd0d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 8 Mar 2024 14:55:38 -0800
Subject: [PATCH 232/937] new method to deal with offset==0

in this new method, when an `offset==0` is detected,
it's converted into (size_t)(-1), instead of 1.

The logic is that (size_t)(-1) is effectively an extremely large positive number,
which will not pass the offset distance test at next stage (`execSequence()`).
Checked the source code, and offset is always checked (as it should),
using a formula which is not vulnerable to arithmetic overflow:
```
RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart),
```

The benefit is that such a case (offset==0) is always detected as corrupted data
as opposed to relying on the checksum to detect the error.
---
 lib/decompress/zstd_decompress_block.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c
index 8d9fea5fd..76d7332e8 100644
--- a/lib/decompress/zstd_decompress_block.c
+++ b/lib/decompress/zstd_decompress_block.c
@@ -1305,7 +1305,7 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c
                 } else {
                     offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
                     {   size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
-                        temp += !temp;   /* 0 is not valid; input is corrupted; force offset to 1 */
+                        temp -= !temp; /* 0 is not valid: input corrupted => force offset to -1 => corruption detected at execSequence */
                         if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
                         seqState->prevOffset[1] = seqState->prevOffset[0];
                         seqState->prevOffset[0] = offset = temp;

From d2f56ba44208f56b5370a9ef6ce0d2c32f283131 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Fri, 8 Mar 2024 15:55:30 -0800
Subject: [PATCH 233/937] update documentation

---
 doc/decompressor_accepted_invalid_data.md | 14 -----
 doc/decompressor_permissive.md            | 62 +++++++++++++++++++++++
 2 files changed, 62 insertions(+), 14 deletions(-)
 delete mode 100644 doc/decompressor_accepted_invalid_data.md
 create mode 100644 doc/decompressor_permissive.md

diff --git a/doc/decompressor_accepted_invalid_data.md b/doc/decompressor_accepted_invalid_data.md
deleted file mode 100644
index f08f963d9..000000000
--- a/doc/decompressor_accepted_invalid_data.md
+++ /dev/null
@@ -1,14 +0,0 @@
-Decompressor Accepted Invalid Data
-==================================
-
-This document describes the behavior of the reference decompressor in cases
-where it accepts an invalid frame instead of reporting an error.
-
-Zero offsets converted to 1
----------------------------
-If a sequence is decoded with `literals_length = 0` and `offset_value = 3`
-while `Repeated_Offset_1 = 1`, the computed offset will be `0`, which is
-invalid.
-
-The reference decompressor will process this case as if the computed
-offset was `1`, including inserting `1` into the repeated offset list.
\ No newline at end of file
diff --git a/doc/decompressor_permissive.md b/doc/decompressor_permissive.md
new file mode 100644
index 000000000..29846c31a
--- /dev/null
+++ b/doc/decompressor_permissive.md
@@ -0,0 +1,62 @@
+Decompressor Permissiveness to Invalid Data
+===========================================
+
+This document describes the behavior of the reference decompressor in cases
+where it accepts formally invalid data instead of reporting an error.
+
+While the reference decompressor *must* decode any compliant frame following
+the specification, its ability to detect erroneous data is on a best effort
+basis: the decoder may accept input data that would be formally invalid,
+when it causes no risk to the decoder, and which detection would cost too much
+complexity or speed regression.
+
+In practice, the vast majority of invalid data are detected, if only because
+many corruption events are dangerous for the decoder process (such as
+requesting an out-of-bound memory access) and many more are easy to check.
+
+This document lists a few known cases where invalid data was formerly accepted
+by the decoder, and what has changed since.
+
+
+Offset == 0
+-----------
+
+**Last affected version**: v1.5.5
+
+**Produced by the reference compressor**: No
+
+**Example Frame**: `28b5 2ffd 2000 1500 0000 00`
+
+If a sequence is decoded with `literals_length = 0` and `offset_value = 3`
+while `Repeated_Offset_1 = 1`, the computed offset will be `0`, which is
+invalid.
+
+The reference decompressor up to v1.5.5 processes this case as if the computed
+offset was `1`, including inserting `1` into the repeated offset list.
+This prevents the output buffer from remaining uninitialized, thus denying a
+potential attack vector from an untrusted source.
+However, in the rare case where this scenario would be the outcome of a
+transmission or storage error, the decoder relies on the checksum to detect
+the error.
+
+In newer versions, this case is always detected and reported as a corruption error.
+
+
+Non-zeroes reserved bits
+------------------------
+
+**Last affected version**: v1.5.5
+
+**Produced by the reference compressor**: No
+
+**Example Frame**: `28b5 2ffd 2000 1500 0000 00`
+
+The Sequences section of each block has a header, and one of its elements is a
+byte, which describes the compression mode of each symbol.
+This byte contains 2 reserved bits which must be set to zero.
+
+The reference decompressor up to v1.5.5 just ignores these 2 bits.
+This behavior has no consequence for the rest of the frame decoding process.
+
+In newer versions, the 2 reserved bits are actively checked for value zero,
+and the decoder reports a corruption error if they are not.

From eb5f7a7fa278ab76c3390555f36162c638f63b53 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Sat, 9 Mar 2024 00:33:44 -0800
Subject: [PATCH 234/937] produced golden sample for the offset==0 decoder test

is correctly detected as corrupted by new version,
and is accepted (changed into offset==1) by older version.

updated documentation accordingly, with an hexadecimal representation.
---
 doc/decompressor_permissive.md                 |   4 +---
 tests/golden-decompression-errors/off0.bin.zst | Bin 0 -> 17 bytes
 2 files changed, 1 insertion(+), 3 deletions(-)
 create mode 100644 tests/golden-decompression-errors/off0.bin.zst

diff --git a/doc/decompressor_permissive.md b/doc/decompressor_permissive.md
index 29846c31a..bd77165f0 100644
--- a/doc/decompressor_permissive.md
+++ b/doc/decompressor_permissive.md
@@ -25,7 +25,7 @@ Offset == 0
 
 **Produced by the reference compressor**: No
 
-**Example Frame**: `28b5 2ffd 2000 1500 0000 00`
+**Example Frame**: `28b5 2ffd 0000 4500 0008 0002 002f 430b ae`
 
 If a sequence is decoded with `literals_length = 0` and `offset_value = 3`
 while `Repeated_Offset_1 = 1`, the computed offset will be `0`, which is
@@ -49,8 +49,6 @@ Non-zeroes reserved bits
 
 **Produced by the reference compressor**: No
 
-**Example Frame**: `28b5 2ffd 2000 1500 0000 00`
-
 The Sequences section of each block has a header, and one of its elements is a
 byte, which describes the compression mode of each symbol.
 This byte contains 2 reserved bits which must be set to zero.
diff --git a/tests/golden-decompression-errors/off0.bin.zst b/tests/golden-decompression-errors/off0.bin.zst
new file mode 100644
index 0000000000000000000000000000000000000000..13493fb336c6e3e339c1c224a1a2ada1a8b57a0b
GIT binary patch
literal 17
YcmdPcs{faP!Igo5gMo=b-
Date: Mon, 11 Mar 2024 11:38:55 -0700
Subject: [PATCH 235/937] fix #3719

only disable `--rm` at end of command line parsing,
so that `-c` only disables `--rm` if it's effectively selected,
and not if it's overriden by a later `-o FILE` command.
---
 programs/zstd.1.md |  8 +++++---
 programs/zstdcli.c | 16 ++++++++++++----
 2 files changed, 17 insertions(+), 7 deletions(-)

diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index c5d0ef70a..b11ad900d 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -225,15 +225,17 @@ the last one takes effect.
     This parameter defines a loose target: compressed blocks will target this size "on average", but individual blocks can still be larger or smaller.
     Enabling this feature can decrease compression speed by up to ~10% at level 1.
     Higher levels will see smaller relative speed regression, becoming invisible at higher settings.
-* `-o FILE`:
-    save result into `FILE`.
 * `-f`, `--force`:
     disable input and output checks. Allows overwriting existing files, input
     from console, output to stdout, operating on links, block devices, etc.
     During decompression and when the output destination is stdout, pass-through
     unrecognized formats as-is.
 * `-c`, `--stdout`:
-    write to standard output (even if it is the console); keep original files unchanged.
+    write to standard output (even if it is the console); keep original files (disable `--rm`).
+* `-o FILE`:
+    save result into `FILE`.
+    This command is in conflict with `-c`.
+    If both are present on the command line, the last expressed one wins.
 * `--[no-]sparse`:
     enable / disable sparse FS support,
     to make files with many zeroes smaller on disk.
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 1cb16ef50..4ea9034a1 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -1176,7 +1176,10 @@ int main(int argCount, const char* argv[])
                         operation=zom_decompress; argument++; break;
 
                     /* Force stdout, even if stdout==console */
-                case 'c': forceStdout=1; outFileName=stdoutmark; removeSrcFile=0; argument++; break;
+                case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
+
+                    /* destination file name */
+                case 'o': argument++; NEXT_FIELD(outFileName); break;
 
                     /* do not store filename - gzip compatibility - nothing to do */
                 case 'n': argument++; break;
@@ -1202,9 +1205,6 @@ int main(int argCount, const char* argv[])
                     /* test compressed file */
                 case 't': operation=zom_test; argument++; break;
 
-                    /* destination file name */
-                case 'o': argument++; NEXT_FIELD(outFileName); break;
-
                     /* limit memory */
                 case 'M':
                     argument++;
@@ -1367,6 +1367,14 @@ int main(int argCount, const char* argv[])
 #endif
     }
 
+    /* disable --rm when writing to stdout */
+    if (!strcmp(outFileName, stdoutmark)) {
+        if (removeSrcFile) {
+            DISPLAYLEVEL(2, "warning: source not removed when writing to stdout \n");
+            removeSrcFile = 0;
+        }
+    }
+
     /* Check if benchmark is selected */
     if (operation==zom_bench) {
 #ifndef ZSTD_NOBENCH

From fbd9e628ae124d4bbf4db0b8afd54b6b6e653b29 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 11 Mar 2024 12:17:34 -0700
Subject: [PATCH 236/937] added tests

---
 programs/zstdcli.c | 10 +---------
 tests/playTests.sh | 32 ++++++++++++++++++++++++++++++--
 2 files changed, 31 insertions(+), 11 deletions(-)

diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 4ea9034a1..9dd6b051a 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -962,7 +962,7 @@ int main(int argCount, const char* argv[])
                 if (!strcmp(argument, "--help")) { usageAdvanced(programName); CLEAN_RETURN(0); }
                 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
                 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
-                if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; removeSrcFile=0; continue; }
+                if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; }
                 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
                 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
                 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
@@ -1367,14 +1367,6 @@ int main(int argCount, const char* argv[])
 #endif
     }
 
-    /* disable --rm when writing to stdout */
-    if (!strcmp(outFileName, stdoutmark)) {
-        if (removeSrcFile) {
-            DISPLAYLEVEL(2, "warning: source not removed when writing to stdout \n");
-            removeSrcFile = 0;
-        }
-    }
-
     /* Check if benchmark is selected */
     if (operation==zom_bench) {
 #ifndef ZSTD_NOBENCH
diff --git a/tests/playTests.sh b/tests/playTests.sh
index bf5fba89b..dc7794654 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -234,12 +234,23 @@ unset ZSTD_CLEVEL
 println "test : compress to stdout"
 zstd tmp -c > tmpCompressed
 zstd tmp --stdout > tmpCompressed       # long command format
-println "test : compress to named file"
+
+println "test : compress to named file (-o)"
 rm -f tmpCompressed
 zstd tmp -o tmpCompressed
 test -f tmpCompressed   # file must be created
+
 println "test : force write, correct order"
 zstd tmp -fo tmpCompressed
+
+println "test : -c + -o : last one wins"
+rm -f tmpOut
+zstd tmp -c > tmpCompressed -o tmpOut
+test -f tmpOut   # file must be created
+rm -f tmpCompressed
+zstd tmp -o tmpOut -c > tmpCompressed
+test -f tmpCompressed   # file must be created
+
 println "test : forgotten argument"
 cp tmp tmp2
 zstd tmp2 -fo && die "-o must be followed by filename "
@@ -394,6 +405,8 @@ println "test: --rm is disabled when output is stdout"
 test -f tmp
 zstd --rm tmp -c > $INTOVOID
 test -f tmp # tmp shall still be there
+zstd --rm tmp --stdout > $INTOVOID
+test -f tmp # tmp shall still be there
 zstd -f --rm tmp -c > $INTOVOID
 test -f tmp # tmp shall still be there
 zstd -f tmp -c > $INTOVOID --rm
@@ -411,7 +424,22 @@ zstd -f tmp tmp2 -o tmp3.zst --rm # just warns, no prompt
 test -f tmp
 test -f tmp2
 zstd -q tmp tmp2 -o tmp3.zst --rm && die "should refuse to concatenate"
-
+println "test: --rm is active with -o when single input"
+rm -f tmp2.zst
+zstd --rm tmp2 -o tmp2.zst
+test -f tmp2.zst
+test ! -f tmp2
+println "test: -c followed by -o => -o wins, so --rm remains active" # (#3719)
+rm tmp2.zst
+cp tmp tmp2
+zstd --rm tmp2 -c > $INTOVOID -o tmp2.zst
+test ! -f tmp2
+println "test: -o followed by -c => -c wins, so --rm is disabled" # (#3719)
+rm tmp3.zst
+cp tmp tmp2
+zstd -v --rm tmp2 -o tmp2.zst -c > tmp3.zst
+test -f tmp2
+test -f tmp3.zst
 println "test : should quietly not remove non-regular file"
 println hello > tmp
 zstd tmp -f -o "$DEVDEVICE" 2>tmplog > "$INTOVOID"

From 1362699e875994689390bbee3cba87d2c11a11fb Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 11 Mar 2024 12:23:37 -0700
Subject: [PATCH 237/937] minor man page clarification

---
 programs/zstd.1.md | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index b11ad900d..646e3cf28 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -234,8 +234,8 @@ the last one takes effect.
     write to standard output (even if it is the console); keep original files (disable `--rm`).
 * `-o FILE`:
     save result into `FILE`.
-    This command is in conflict with `-c`.
-    If both are present on the command line, the last expressed one wins.
+    Note that this operation is in conflict with `-c`.
+    If both operations are present on the command line, the last expressed one wins.
 * `--[no-]sparse`:
     enable / disable sparse FS support,
     to make files with many zeroes smaller on disk.

From f99a450ca4d5fdb25d0d9bc5ae4c5d4787fbcb87 Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Mon, 11 Mar 2024 15:20:06 -0400
Subject: [PATCH 238/937] Stop Hardcoding the POSIX Version on BSDs

BSDs should all have a `unistd.h` header.
---
 programs/platform.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/programs/platform.h b/programs/platform.h
index bbe0965ae..4d2b9490e 100644
--- a/programs/platform.h
+++ b/programs/platform.h
@@ -74,8 +74,7 @@ extern "C" {
 ***************************************************************/
 #ifndef PLATFORM_POSIX_VERSION
 
-#  if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1-2001 (SUSv3) conformant */ \
-     || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)  /* BSD distros */
+#  if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1-2001 (SUSv3) conformant */
      /* exception rule : force posix version to 200112L,
       * note: it's better to use unistd.h's _POSIX_VERSION whenever possible */
 #    define PLATFORM_POSIX_VERSION 200112L

From f6039f3d5fa607555fc193042671a05bf5029bad Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 11 Mar 2024 16:11:15 -0700
Subject: [PATCH 239/937] cmake refactor: move HP-UX specific logic into its
 own function

reduce visual clutter of corner case configuration.
---
 build/cmake/CMakeLists.txt | 25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 50b1bb95c..399b818fc 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -114,20 +114,25 @@ endif ()
 #-----------------------------------------------------------------------------
 # External dependencies
 #-----------------------------------------------------------------------------
+# Define a function to handle special thread settings for HP-UX
+# See https://github.com/facebook/zstd/pull/3862 for details.
+function(setup_hpux_threads)
+    find_package(Threads)
+    if (NOT Threads_FOUND)
+        set(CMAKE_USE_PTHREADS_INIT 1 PARENT_SCOPE)
+        set(CMAKE_THREAD_LIBS_INIT -lpthread PARENT_SCOPE)
+        set(CMAKE_HAVE_THREADS_LIBRARY 1 PARENT_SCOPE)
+        set(Threads_FOUND TRUE PARENT_SCOPE)
+    endif()
+endfunction()
+
 if (ZSTD_MULTITHREAD_SUPPORT AND UNIX)
     if (CMAKE_SYSTEM_NAME MATCHES "HP-UX")
-        find_package(Threads)
-        if (NOT Threads_FOUND)
-            set(CMAKE_USE_PTHREADS_INIT 1)
-            set(CMAKE_THREAD_LIBS_INIT -lpthread)
-            set(CMAKE_HAVE_THREADS_LIBRARY 1)
-            set(Threads_FOUND TRUE)
-        endif ()
-    else ()
+        setup_hpux_threads()
+    else()
         set(THREADS_PREFER_PTHREAD_FLAG ON)
         find_package(Threads REQUIRED)
-    endif ()
-
+    endif()
     if (CMAKE_USE_PTHREADS_INIT)
         set(THREADS_LIBS "${CMAKE_THREAD_LIBS_INIT}")
     else()

From edab9eed66f02c7c3c8be849f22f20ffbd04976b Mon Sep 17 00:00:00 2001
From: Yonatan Komornik <11005061+yoniko@users.noreply.github.com>
Date: Mon, 11 Mar 2024 16:28:32 -0700
Subject: [PATCH 240/937] Fix AsyncIO reading seed queueing (#3940)

Fixes a bug in AsyncIO where we queue reads after opening a file so our queue will always be saturated (or as saturated as possible).
Previous code was looping up to `availableJobsCount` not realizing `availableJobsCount` was also decreasing in each iteration, so instead of queueing 10 jobs we'd queue 5 (and instead of 2 we'd queue 1).
This PR fixes the loop to queue as long as `availableJobsCount` is not 0.
---
 programs/fileio_asyncio.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/programs/fileio_asyncio.c b/programs/fileio_asyncio.c
index 5f7bd4a4c..ae6db69e0 100644
--- a/programs/fileio_asyncio.c
+++ b/programs/fileio_asyncio.c
@@ -514,8 +514,7 @@ static void AIO_ReadPool_enqueueRead(ReadPoolCtx_t* ctx) {
 }
 
 static void AIO_ReadPool_startReading(ReadPoolCtx_t* ctx) {
-    int i;
-    for (i = 0; i < ctx->base.availableJobsCount; i++) {
+    while(ctx->base.availableJobsCount) {
         AIO_ReadPool_enqueueRead(ctx);
     }
 }

From 74e856a195005c2358b5fb4d6c90c540c5b29812 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 11 Mar 2024 17:57:57 -0700
Subject: [PATCH 241/937] add tests inspired from #2927

centered around -T# and --fast=# arguments
---
 tests/playTests.sh | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)

diff --git a/tests/playTests.sh b/tests/playTests.sh
index bf5fba89b..2c9f791f9 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -326,6 +326,51 @@ if [ "$isWindows" = false ] && [ "$UNAME" != "AIX" ]; then
   fi
 fi
 
+println "\n===>  multiple_thread test "
+
+datagen > tmp
+println "test : single-thread "
+zstd --fast --single-thread tmp -o tmpMT0
+println "test : one worker thread (default)"
+zstd --fast -T1 tmp -o tmpMT1
+println "test : two worker threads "
+zstd --fast -T2 tmp -o tmpMT2
+println "test : 16-thread "
+zstd --fast -T16 tmp -o tmpMT3
+println "test : 127-thread "
+zstd --fast -T127 tmp -o tmpMT4
+println "test : 128-thread "
+zstd --fast -T128 tmp -o tmpMT5
+println "test : max allowed numeric value is 4294967295 "
+zstd --fast -4294967295 tmp -o tmpMT6
+println "test : numeric value overflows 32-bit unsigned int "
+zstd --fast -4294967296 tmp -o tmptest9 && die "max allowed numeric value is 4294967295"
+
+datagen > tmp
+println "test : basic compression "
+zstd -f tmp  # trivial compression case, creates tmp.zst
+println "test : basic decompression"
+zstd -d -f -T1 tmp.zst
+println "note : decompression does not support -T mode, but execution support"
+rm -rf tmpMT*
+
+println "\n===>  --fast_argument test "
+datagen > tmp
+println "test : basic compression "
+zstd -f tmp  # trivial compression case, creates tmp.zst
+println "test: --fast=1"
+zstd --fast=1 -f tmp
+println "test: --fast=99"
+zstd --fast=99 -f tmp
+println "test: Invalid value -- negative number"
+zstd --fast=-1 -f tmp && die "error: Invalid value -- negative number"
+println "test: Invalid value -- zero"
+zstd --fast=0 -f tmp && die "error: Invalid value -- 0 number"
+println "test: max allowed numeric argument of --fast is 4294967295"
+zstd --fast=4294967295 -f tmp
+println "test: numeric value overflows 32-bit unsigned int "
+zstd --fast=4294967296 -f tmp && die "max allowed argument of --fast is 4294967295"
+
 println "\n===>  --exclude-compressed flag"
 rm -rf precompressedFilterTestDir
 mkdir -p precompressedFilterTestDir

From e0872806df5c255d23c9c9ec95fb7db50127a9e6 Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Tue, 12 Mar 2024 10:08:26 -0400
Subject: [PATCH 242/937] Use ZSTD_LEGACY_SUPPORT=5 in make test (#3943)

---
 lib/legacy/zstd_v02.c |  4 ++--
 lib/legacy/zstd_v03.c |  4 ++--
 tests/Makefile        | 27 ++++++++++++++++++---------
 3 files changed, 22 insertions(+), 13 deletions(-)

diff --git a/lib/legacy/zstd_v02.c b/lib/legacy/zstd_v02.c
index 80615e556..6d39b6e5b 100644
--- a/lib/legacy/zstd_v02.c
+++ b/lib/legacy/zstd_v02.c
@@ -862,7 +862,7 @@ extern "C" {
 *  Streaming functions
 ***************************************/
 
-typedef struct ZSTD_DCtx_s ZSTD_DCtx;
+typedef struct ZSTDv02_Dctx_s ZSTD_DCtx;
 
 /*
   Use above functions alternatively.
@@ -2737,7 +2737,7 @@ static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
 /* *************************************************************
 *   Decompression section
 ***************************************************************/
-struct ZSTD_DCtx_s
+struct ZSTDv02_Dctx_s
 {
     U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
     U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
diff --git a/lib/legacy/zstd_v03.c b/lib/legacy/zstd_v03.c
index 082fe8705..47195f337 100644
--- a/lib/legacy/zstd_v03.c
+++ b/lib/legacy/zstd_v03.c
@@ -862,7 +862,7 @@ extern "C" {
 *  Streaming functions
 ***************************************/
 
-typedef struct ZSTD_DCtx_s ZSTD_DCtx;
+typedef struct ZSTDv03_Dctx_s ZSTD_DCtx;
 
 /*
   Use above functions alternatively.
@@ -2377,7 +2377,7 @@ static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
 /* *************************************************************
 *   Decompression section
 ***************************************************************/
-struct ZSTD_DCtx_s
+struct ZSTDv03_Dctx_s
 {
     U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
     U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
diff --git a/tests/Makefile b/tests/Makefile
index 4eb77fdec..3550b7a9c 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -20,7 +20,7 @@
 # zstreamtest32: Same as zstreamtest, but forced to compile in 32-bits mode
 # ##########################################################################
 
-ZSTD_LEGACY_SUPPORT ?= 0
+ZSTD_LEGACY_SUPPORT ?= 5
 
 DEBUGLEVEL ?= 2
 export DEBUGLEVEL  # transmit value to sub-makefiles
@@ -33,28 +33,31 @@ PYTHON ?= python3
 TESTARTEFACT := versionsTest
 
 DEBUGFLAGS += -g -Wno-c++-compat
-CPPFLAGS   += -I$(LIB_SRCDIR) -I$(LIB_SRCDIR)/common -I$(LIB_SRCDIR)/compress \
+CPPFLAGS   += -I$(LIB_SRCDIR) -I$(LIB_SRCDIR)/common -I$(LIB_SRCDIR)/compress -I$(LIB_SRCDIR)/legacy \
               -I$(LIB_SRCDIR)/dictBuilder -I$(LIB_SRCDIR)/deprecated -I$(PRGDIR) \
               -DZSTD_WINDOW_OVERFLOW_CORRECT_FREQUENTLY=1
 
 ZSTDCOMMON_FILES := $(sort $(ZSTD_COMMON_FILES))
 ZSTDCOMP_FILES   := $(sort $(ZSTD_COMPRESS_FILES))
 ZSTDDECOMP_FILES := $(sort $(ZSTD_DECOMPRESS_FILES))
-ZSTD_FILES  := $(ZSTDDECOMP_FILES) $(ZSTDCOMMON_FILES) $(ZSTDCOMP_FILES)
+ZSTDLEGACY_FILES := $(sort $(wildcard $(LIB_SRCDIR)/legacy/*.c))
+ZSTD_FILES  := $(ZSTDDECOMP_FILES) $(ZSTDCOMMON_FILES) $(ZSTDCOMP_FILES) $(ZSTDLEGACY_FILES)
 ZDICT_FILES := $(sort $(ZSTD_DICTBUILDER_FILES))
 
 ZSTD_F1 := $(sort $(wildcard $(ZSTD_FILES)))
 ZSTD_OBJ1 := $(subst $(LIB_SRCDIR)/common/,zstdm_,$(ZSTD_F1))
 ZSTD_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,zstdc_,$(ZSTD_OBJ1))
 ZSTD_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,zstdd_,$(ZSTD_OBJ2))
-ZSTD_OBJ4 := $(ZSTD_OBJ3:.c=.o)
-ZSTD_OBJECTS := $(ZSTD_OBJ4:.S=.o)
+ZSTD_OBJ4 := $(subst $(LIB_SRCDIR)/legacy/,zstdl_,$(ZSTD_OBJ3))
+ZSTD_OBJ5 := $(ZSTD_OBJ4:.c=.o)
+ZSTD_OBJECTS := $(ZSTD_OBJ5:.S=.o)
 
 ZSTDMT_OBJ1 := $(subst $(LIB_SRCDIR)/common/,zstdmt_m_,$(ZSTD_F1))
 ZSTDMT_OBJ2 := $(subst $(LIB_SRCDIR)/compress/,zstdmt_c_,$(ZSTDMT_OBJ1))
 ZSTDMT_OBJ3 := $(subst $(LIB_SRCDIR)/decompress/,zstdmt_d_,$(ZSTDMT_OBJ2))
-ZSTDMT_OBJ4 := $(ZSTDMT_OBJ3:.c=.o)
-ZSTDMT_OBJECTS := $(ZSTDMT_OBJ4:.S=.o)
+ZSTDMT_OBJ4 := $(subst $(LIB_SRCDIR)/legacy/,zstdmt_l_,$(ZSTDMT_OBJ3))
+ZSTDMT_OBJ5 := $(ZSTDMT_OBJ4:.c=.o)
+ZSTDMT_OBJECTS := $(ZSTDMT_OBJ5:.S=.o)
 
 # Define *.exe as extension for Windows systems
 ifneq (,$(filter Windows%,$(OS)))
@@ -118,6 +121,9 @@ zstdd_%.o : $(LIB_SRCDIR)/decompress/%.c
 zstdd_%.o : $(LIB_SRCDIR)/decompress/%.S
 	$(CC) -c $(CPPFLAGS) $(ASFLAGS) $< -o $@
 
+zstdl_%.o : $(LIB_SRCDIR)/legacy/%.c
+	$(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@
+
 zstdmt%.o : CPPFLAGS += $(MULTITHREAD_CPP)
 
 zstdmt_m_%.o : $(LIB_SRCDIR)/common/%.c
@@ -132,6 +138,9 @@ zstdmt_d_%.o : $(LIB_SRCDIR)/decompress/%.c
 zstdmt_d_%.o : $(LIB_SRCDIR)/decompress/%.S
 	$(CC) -c $(CPPFLAGS) $(ASFLAGS) $< -o $@
 
+zstdmt_l_%.o : $(LIB_SRCDIR)/legacy/%.c
+	$(CC) -c $(CPPFLAGS) $(CFLAGS) $< -o $@
+
 FULLBENCHS := fullbench fullbench32
 CLEAN += $(FULLBENCHS)
 fullbench32: CPPFLAGS += -m32
@@ -222,8 +231,8 @@ CLEAN += invalidDictionaries
 invalidDictionaries : $(ZSTD_OBJECTS) invalidDictionaries.c
 
 CLEAN += legacy
-legacy : CPPFLAGS += -I$(LIB_SRCDIR)/legacy -UZSTD_LEGACY_SUPPORT -DZSTD_LEGACY_SUPPORT=4
-legacy : $(ZSTD_FILES) $(sort $(wildcard $(LIB_SRCDIR)/legacy/*.c)) legacy.c
+legacy : CPPFLAGS += -UZSTD_LEGACY_SUPPORT -DZSTD_LEGACY_SUPPORT=4
+legacy : $(ZSTD_FILES) legacy.c
 
 CLEAN += decodecorpus
 decodecorpus : LDLIBS += -lm

From ee6acaf26bbf842837513087c91776b83d4d9560 Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Tue, 12 Mar 2024 11:25:00 -0400
Subject: [PATCH 243/937] Pin tsan and msan CI jobs to ubuntu-20.04 (#3945)

---
 .github/workflows/dev-long-tests.yml | 34 ++++++++++++++--------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 21882f024..eb8f40a9a 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -60,14 +60,14 @@ jobs:
       run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest
 
   tsan-zstreamtest:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-20.04
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer zstreamtest
       run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream
 
   ubsan-zstreamtest:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-20.04
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: undefined behavior sanitizer zstreamtest
@@ -75,7 +75,7 @@ jobs:
 
   # lasts ~15mn
   tsan-fuzztest:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-20.04
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer fuzztest
@@ -94,7 +94,7 @@ jobs:
 
   # lasts ~23mn
   gcc-8-asan-ubsan-testzstd:
-    runs-on: ubuntu-latest
+    runs-on: ubuntu-20.04
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: gcc-8 + ASan + UBSan + Test Zstd
@@ -106,14 +106,14 @@ jobs:
         CC=gcc-8 make -j uasan-test-zstd 
Date: Tue, 12 Mar 2024 23:44:42 +0800
Subject: [PATCH 244/937] chore: fix some typos (#3949)

Signed-off-by: acceptacross 
---
 lib/Makefile      | 2 +-
 programs/Makefile | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/lib/Makefile b/lib/Makefile
index 754c90960..8bfdade9f 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -8,7 +8,7 @@
 # You may select, at your option, one of the above-listed licenses.
 # ################################################################
 
-# default target (when runing `make` with no argument)
+# default target (when running `make` with no argument)
 lib-release:
 
 # Modules
diff --git a/programs/Makefile b/programs/Makefile
index 6cd5c1eee..4dcd84105 100644
--- a/programs/Makefile
+++ b/programs/Makefile
@@ -15,7 +15,7 @@
 # zstd-decompress : decompressor-only version of zstd
 # ##########################################################################
 
-# default target (when runing `make` with no argument)
+# default target (when running `make` with no argument)
 zstd-release:
 
 LIBZSTD_MK_DIR = ../lib

From b39c76765b761c9c3c3c23db3ed55f3f825f7e4d Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 12 Mar 2024 09:28:25 -0700
Subject: [PATCH 245/937] Add the zeroSeq sample

that should have been part of #3674
---
 tests/golden-decompression-errors/.gitignore       |   1 +
 .../zeroSeq_extraneous.zst                         | Bin 0 -> 27 bytes
 2 files changed, 1 insertion(+)
 create mode 100644 tests/golden-decompression-errors/.gitignore
 create mode 100644 tests/golden-decompression-errors/zeroSeq_extraneous.zst

diff --git a/tests/golden-decompression-errors/.gitignore b/tests/golden-decompression-errors/.gitignore
new file mode 100644
index 000000000..574b37506
--- /dev/null
+++ b/tests/golden-decompression-errors/.gitignore
@@ -0,0 +1 @@
+!*.zst
diff --git a/tests/golden-decompression-errors/zeroSeq_extraneous.zst b/tests/golden-decompression-errors/zeroSeq_extraneous.zst
new file mode 100644
index 0000000000000000000000000000000000000000..0953be343f3cf3b334bd4281d63d9863cda309c0
GIT binary patch
literal 27
icmdPcs{faPVJZVdhDT~nPQF5Teo;<}B3A
Date: Tue, 12 Mar 2024 09:47:54 -0700
Subject: [PATCH 246/937] add same .gitignore rule in golden-decompression/

as requested by @embg
---
 tests/golden-decompression/.gitignore | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 tests/golden-decompression/.gitignore

diff --git a/tests/golden-decompression/.gitignore b/tests/golden-decompression/.gitignore
new file mode 100644
index 000000000..574b37506
--- /dev/null
+++ b/tests/golden-decompression/.gitignore
@@ -0,0 +1 @@
+!*.zst

From 37ff4f91eba72a936771b177c83d27151d33e2f1 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 12 Mar 2024 10:47:27 -0700
Subject: [PATCH 247/937] removed golden-decompression/.gitignore

replaced by an exclusion rule in tests/.gitignore
---
 tests/.gitignore                      | 3 +++
 tests/golden-decompression/.gitignore | 1 -
 2 files changed, 3 insertions(+), 1 deletion(-)
 delete mode 100644 tests/golden-decompression/.gitignore

diff --git a/tests/.gitignore b/tests/.gitignore
index fcb865d61..311a8b5eb 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -67,3 +67,6 @@ speedTest.pid
 *.exe
 *.out
 *.app
+
+# Specific exclusions
+!golden-decompression/*.zst
diff --git a/tests/golden-decompression/.gitignore b/tests/golden-decompression/.gitignore
deleted file mode 100644
index 574b37506..000000000
--- a/tests/golden-decompression/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-!*.zst

From 5a66afa0514d0853b0f2a6b5ff3df1ae706f4862 Mon Sep 17 00:00:00 2001
From: daniellerozenblit <48103643+daniellerozenblit@users.noreply.github.com>
Date: Tue, 12 Mar 2024 13:49:06 -0400
Subject: [PATCH 248/937] Add common file extensions to --exclude-compressed
 (#3951)

---
 programs/fileio.c  | 104 +++++++++++++++++++++++++++++++++++++++++++++
 programs/zstd.1.md |   2 +
 tests/playTests.sh |  13 ++++++
 3 files changed, 119 insertions(+)

diff --git a/programs/fileio.c b/programs/fileio.c
index a7597d893..6fd55d9a8 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -1907,6 +1907,110 @@ static const char *compressedFileExtensions[] = {
     TXZ_EXTENSION,
     LZ4_EXTENSION,
     TLZ4_EXTENSION,
+    ".7z",
+    ".aa3",
+    ".aac",
+    ".aar",
+    ".ace",
+    ".alac",
+    ".ape",
+    ".apk",
+    ".apng",
+    ".arc",
+    ".archive",
+    ".arj",
+    ".ark",
+    ".asf",
+    ".avi",
+    ".avif",
+    ".ba",
+    ".br",
+    ".bz2",
+    ".cab",
+    ".cdx",
+    ".chm",
+    ".cr2",
+    ".divx",
+    ".dmg",
+    ".dng",
+    ".docm",
+    ".docx",
+    ".dotm",
+    ".dotx",
+    ".dsft",
+    ".ear",
+    ".eftx",
+    ".emz",
+    ".eot",
+    ".epub",
+    ".f4v",
+    ".flac",
+    ".flv",
+    ".gho",
+    ".gif",
+    ".gifv",
+    ".gnp",
+    ".iso",
+    ".jar",
+    ".jpeg",
+    ".jpg",
+    ".jxl",
+    ".lz",
+    ".lzh",
+    ".m4a",
+    ".m4v",
+    ".mkv",
+    ".mov",
+    ".mp2",
+    ".mp3",
+    ".mp4",
+    ".mpa",
+    ".mpc",
+    ".mpe",
+    ".mpeg",
+    ".mpg",
+    ".mpl",
+    ".mpv",
+    ".msi",
+    ".odp",
+    ".ods",
+    ".odt",
+    ".ogg",
+    ".ogv",
+    ".otp",
+    ".ots",
+    ".ott",
+    ".pea",
+    ".png",
+    ".pptx",
+    ".qt",
+    ".rar",
+    ".s7z",
+    ".sfx",
+    ".sit",
+    ".sitx",
+    ".sqx",
+    ".svgz",
+    ".swf",
+    ".tbz2",
+    ".tib",
+    ".tlz",
+    ".vob",
+    ".war",
+    ".webm",
+    ".webp",
+    ".wma",
+    ".wmv",
+    ".woff",
+    ".woff2",
+    ".wvl",
+    ".xlsx",
+    ".xpi",
+    ".xps",
+    ".zip",
+    ".zipx",
+    ".zoo",
+    ".zpaq",
     NULL
 };
 
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index 646e3cf28..a5046932e 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -307,6 +307,8 @@ the last one takes effect.
 * `--show-default-cparams`:
     shows the default compression parameters that will be used for a particular input file, based on the provided compression level and the input size.
     If the provided file is not a regular file (e.g. a pipe), this flag will output the parameters used for inputs of unknown size.
+* `--exclude-compressed`:
+    only compress files that are not already compressed.
 * `--`:
     All arguments after `--` are treated as files
 
diff --git a/tests/playTests.sh b/tests/playTests.sh
index a79c06c99..e2a0694f5 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -410,6 +410,19 @@ zstd --long --rm -r precompressedFilterTestDir
 # Files should get compressed again without the --exclude-compressed flag.
 test -f precompressedFilterTestDir/input.5.zst.zst
 test -f precompressedFilterTestDir/input.6.zst.zst
+
+# Test some other compressed file extensions
+datagen $size > precompressedFilterTestDir/input.flac
+datagen $size > precompressedFilterTestDir/input.mov
+datagen $size > precompressedFilterTestDir/input.mp3
+zstd --exclude-compressed --long --rm -r precompressedFilterTestDir
+test ! -f precompressedFilterTestDir/input.flac.zst
+test ! -f precompressedFilterTestDir/input.mov.zst
+test ! -f precompressedFilterTestDir/input.mp3.zst
+zstd --long --rm -r precompressedFilterTestDir
+test -f precompressedFilterTestDir/input.flac.zst
+test -f precompressedFilterTestDir/input.mov.zst
+test -f precompressedFilterTestDir/input.mp3.zst
 rm -rf precompressedFilterTestDir
 println "Test completed"
 

From 83ec3d0164887904a7ae7f3382051ed20d5792b2 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 12 Mar 2024 11:27:42 -0700
Subject: [PATCH 249/937] no longer truncate file name in verbose mode

fix #3702
---
 programs/fileio.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/programs/fileio.c b/programs/fileio.c
index 6fd55d9a8..e3012a716 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -2441,9 +2441,10 @@ FIO_decompressZstdFrame(FIO_ctx_t* const fCtx, dRess_t* ress,
     U64 frameSize = 0;
     IOJob_t *writeJob = AIO_WritePool_acquireJob(ress->writeCtx);
 
-    /* display last 20 characters only */
+    /* display last 20 characters only when not --verbose */
     {   size_t const srcFileLength = strlen(srcFileName);
-        if (srcFileLength>20) srcFileName += srcFileLength-20;
+        if ((srcFileLength>20) && (g_display_prefs.displayLevel<3))
+            srcFileName += srcFileLength-20;
     }
 
     ZSTD_DCtx_reset(ress->dctx, ZSTD_reset_session_only);

From 92fbd42894e4dd9d58d3184923b17dda94ca6b44 Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Tue, 12 Mar 2024 14:36:54 -0400
Subject: [PATCH 250/937] Export ZSTD_LEGACY_SUPPORT in tests/Makefile (#3955)

This doesn't affect most of the targets, but will help me sleep better at night knowing that future refactors won't break the legacy support.

Should have been included in https://github.com/facebook/zstd/pull/3943 but I noticed after that merged, so putting up a separate PR.
---
 tests/Makefile | 1 +
 1 file changed, 1 insertion(+)

diff --git a/tests/Makefile b/tests/Makefile
index 3550b7a9c..ed3692a24 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -21,6 +21,7 @@
 # ##########################################################################
 
 ZSTD_LEGACY_SUPPORT ?= 5
+export ZSTD_LEGACY_SUPPORT
 
 DEBUGLEVEL ?= 2
 export DEBUGLEVEL  # transmit value to sub-makefiles

From 5473b72a05ad03555fed8774f7e5af5e99e27e47 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 12 Mar 2024 12:27:33 -0700
Subject: [PATCH 251/937] updated documentation

following recommendations by @zougloub at #3698
---
 programs/zstd.1    | 487 +++++++++++++++++++++++++++++++--------------
 programs/zstd.1.md | 341 ++++++++++++++++---------------
 2 files changed, 514 insertions(+), 314 deletions(-)

diff --git a/programs/zstd.1 b/programs/zstd.1
index 383d99470..1eb9b9738 100644
--- a/programs/zstd.1
+++ b/programs/zstd.1
@@ -1,381 +1,566 @@
-.TH "ZSTD" "1" "March 2023" "zstd 1.5.5" "User Commands"
+.
+.TH "ZSTD" "1" "March 2024" "zstd 1.5.5" "User Commands"
+.
 .SH "NAME"
 \fBzstd\fR \- zstd, zstdmt, unzstd, zstdcat \- Compress or decompress \.zst files
+.
 .SH "SYNOPSIS"
-.TS
-allbox;
-\fBzstd\fR [\fIOPTIONS\fR] [\-	\fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR]
-.TE
+\fBzstd\fR [\fIOPTIONS\fR] [\-|\fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR]
+.
 .P
 \fBzstdmt\fR is equivalent to \fBzstd \-T0\fR
+.
 .P
 \fBunzstd\fR is equivalent to \fBzstd \-d\fR
+.
 .P
 \fBzstdcat\fR is equivalent to \fBzstd \-dcf\fR
+.
 .SH "DESCRIPTION"
-\fBzstd\fR is a fast lossless compression algorithm and data compression tool, with command line syntax similar to \fBgzip\fR(1) and \fBxz\fR(1)\. It is based on the \fBLZ77\fR family, with further FSE & huff0 entropy stages\. \fBzstd\fR offers highly configurable compression speed, from fast modes at > 200 MB/s per core, to strong modes with excellent compression ratios\. It also features a very fast decoder, with speeds > 500 MB/s per core\.
+\fBzstd\fR is a fast lossless compression algorithm and data compression tool, with command line syntax similar to \fBgzip\fR(1) and \fBxz\fR(1)\. It is based on the \fBLZ77\fR family, with further FSE & huff0 entropy stages\. \fBzstd\fR offers highly configurable compression speed, from fast modes at > 200 MB/s per core, to strong modes with excellent compression ratios\. It also features a very fast decoder, with speeds > 500 MB/s per core, which remains roughly stable at all compression settings\.
+.
 .P
-\fBzstd\fR command line syntax is generally similar to gzip, but features the following differences:
-.IP "\[ci]" 4
+\fBzstd\fR command line syntax is generally similar to gzip, but features the following few differences:
+.
+.IP "\(bu" 4
 Source files are preserved by default\. It\'s possible to remove them automatically by using the \fB\-\-rm\fR command\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 When compressing a single file, \fBzstd\fR displays progress notifications and result summary by default\. Use \fB\-q\fR to turn them off\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fBzstd\fR displays a short help page when command line is an error\. Use \fB\-q\fR to turn it off\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fBzstd\fR does not accept input from console, though it does accept \fBstdin\fR when it\'s not the console\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fBzstd\fR does not store the input\'s filename or attributes, only its contents\.
+.
 .IP "" 0
+.
 .P
 \fBzstd\fR processes each \fIfile\fR according to the selected operation mode\. If no \fIfiles\fR are given or \fIfile\fR is \fB\-\fR, \fBzstd\fR reads from standard input and writes the processed data to standard output\. \fBzstd\fR will refuse to write compressed data to standard output if it is a terminal: it will display an error message and skip the file\. Similarly, \fBzstd\fR will refuse to read compressed data from standard input if it is a terminal\.
+.
 .P
 Unless \fB\-\-stdout\fR or \fB\-o\fR is specified, \fIfiles\fR are written to a new file whose name is derived from the source \fIfile\fR name:
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 When compressing, the suffix \fB\.zst\fR is appended to the source filename to get the target filename\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 When decompressing, the \fB\.zst\fR suffix is removed from the source filename to get the target filename
+.
 .IP "" 0
+.
 .SS "Concatenation with \.zst Files"
 It is possible to concatenate multiple \fB\.zst\fR files\. \fBzstd\fR will decompress such agglomerated file as if it was a single \fB\.zst\fR file\.
+.
 .SH "OPTIONS"
+.
 .SS "Integer Suffixes and Special Values"
 In most places where an integer argument is expected, an optional suffix is supported to easily indicate large integers\. There must be no space between the integer and the suffix\.
+.
 .TP
 \fBKiB\fR
-Multiply the integer by 1,024 (2\e^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\.
+Multiply the integer by 1,024 (2^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\.
+.
 .TP
 \fBMiB\fR
-Multiply the integer by 1,048,576 (2\e^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\.
+Multiply the integer by 1,048,576 (2^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\.
+.
 .SS "Operation Mode"
 If multiple operation mode options are given, the last one takes effect\.
+.
 .TP
 \fB\-z\fR, \fB\-\-compress\fR
 Compress\. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, \fBunzstd\fR implies \fB\-\-decompress\fR)\.
+.
 .TP
 \fB\-d\fR, \fB\-\-decompress\fR, \fB\-\-uncompress\fR
 Decompress\.
+.
 .TP
 \fB\-t\fR, \fB\-\-test\fR
 Test the integrity of compressed \fIfiles\fR\. This option is equivalent to \fB\-\-decompress \-\-stdout > /dev/null\fR, decompressed data is discarded and checksummed for errors\. No files are created or removed\.
+.
 .TP
 \fB\-b#\fR
 Benchmark file(s) using compression level \fI#\fR\. See \fIBENCHMARK\fR below for a description of this operation\.
+.
 .TP
 \fB\-\-train FILES\fR
 Use \fIFILES\fR as a training set to create a dictionary\. The training set should contain a lot of small files (> 100)\. See \fIDICTIONARY BUILDER\fR below for a description of this operation\.
+.
 .TP
 \fB\-l\fR, \fB\-\-list\fR
 Display information related to a zstd compressed file, such as size, ratio, and checksum\. Some of these fields may not be available\. This command\'s output can be augmented with the \fB\-v\fR modifier\.
+.
 .SS "Operation Modifiers"
-.IP "\[ci]" 4
-\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
+\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)\. Higher compression levels \fIgenerally\fR produce higher compression ratio at the expense of speed and memory\. A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels\. Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below)\. Because the compressor\'s behavior highly depends on the content to compress, there\'s no guarantee of a smooth progression from one level to another\.
+.
+.IP "\(bu" 4
 \fB\-\-ultra\fR: unlocks high compression levels 20+ (maximum 22), using a lot more memory\. Note that decompression will also require more memory when using these levels\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-fast[=#]\fR: switch to ultra\-fast compression levels\. If \fB=#\fR is not present, it defaults to \fB1\fR\. The higher the value, the faster the compression speed, at the cost of some compression ratio\. This setting overwrites compression level if one was set previously\. Similarly, if a compression level is set after \fB\-\-fast\fR, it overrides it\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-T#\fR, \fB\-\-threads=#\fR: Compress using \fB#\fR working threads (default: 1)\. If \fB#\fR is 0, attempt to detect and use the number of physical CPU cores\. In all cases, the nb of threads is capped to \fBZSTDMT_NBWORKERS_MAX\fR, which is either 64 in 32\-bit mode, or 256 for 64\-bit environments\. This modifier does nothing if \fBzstd\fR is compiled without multithread support\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-single\-thread\fR: Use a single thread for both I/O and compression\. As compression is serialized with I/O, this can be slightly slower\. Single\-thread mode features significantly lower memory usage, which can be useful for systems with limited amount of memory, such as 32\-bit systems\.
+.
 .IP
 Note 1: this mode is the only available one when multithread support is disabled\.
+.
 .IP
 Note 2: this mode is different from \fB\-T1\fR, which spawns 1 compression thread in parallel with I/O\. Final compressed result is also slightly different from \fB\-T1\fR\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-auto\-threads={physical,logical} (default: physical)\fR: When using a default amount of threads via \fB\-T0\fR, choose the default based on the number of detected physical or logical cores\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-adapt[=min=#,max=#]\fR: \fBzstd\fR will dynamically adapt compression level to perceived I/O conditions\. Compression level adaptation can be observed live by using command \fB\-v\fR\. Adaptation can be constrained between supplied \fBmin\fR and \fBmax\fR levels\. The feature works when combined with multi\-threading and \fB\-\-long\fR mode\. It does not work with \fB\-\-single\-thread\fR\. It sets window size to 8 MiB by default (can be changed manually, see \fBwlog\fR)\. Due to the chaotic nature of dynamic adaptation, compressed result is not reproducible\.
+.
 .IP
 \fINote\fR: at the time of this writing, \fB\-\-adapt\fR can remain stuck at low speed when combined with multiple worker threads (>=2)\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-long[=#]\fR: enables long distance matching with \fB#\fR \fBwindowLog\fR, if \fB#\fR is not present it defaults to \fB27\fR\. This increases the window size (\fBwindowLog\fR) and memory usage for both the compressor and decompressor\. This setting is designed to improve the compression ratio for files with long matches at a large distance\.
+.
 .IP
 Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-D DICT\fR: use \fBDICT\fR as Dictionary to compress or decompress FILE(s)
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-patch\-from FILE\fR: Specify the file to be used as a reference point for zstd\'s diff engine\. This is effectively dictionary compression with some convenient parameter selection, namely that \fIwindowSize\fR > \fIsrcSize\fR\.
+.
 .IP
 Note: cannot use both this and \fB\-D\fR together\.
+.
 .IP
 Note: \fB\-\-long\fR mode will be automatically activated if \fIchainLog\fR < \fIfileLog\fR (\fIfileLog\fR being the \fIwindowLog\fR required to cover the whole file)\. You can also manually force it\.
+.
 .IP
 Note: for all levels, you can use \fB\-\-patch\-from\fR in \fB\-\-single\-thread\fR mode to improve compression ratio at the cost of speed\.
+.
 .IP
 Note: for level 19, you can get increased compression ratio at the cost of speed by specifying \fB\-\-zstd=targetLength=\fR to be something large (i\.e\. 4096), and by setting a large \fB\-\-zstd=chainLog=\fR\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-rsyncable\fR: \fBzstd\fR will periodically synchronize the compression state to make the compressed file more rsync\-friendly\. There is a negligible impact to compression ratio, and a potential impact to compression speed, perceptible at higher speeds, for example when combining \fB\-\-rsyncable\fR with many parallel worker threads\. This feature does not work with \fB\-\-single\-thread\fR\. You probably don\'t want to use it with long range mode, since it will decrease the effectiveness of the synchronization points, but your mileage may vary\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-C\fR, \fB\-\-[no\-]check\fR: add integrity check computed from uncompressed data (default: enabled)
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-[no\-]content\-size\fR: enable / disable whether or not the original size of the file is placed in the header of the compressed file\. The default option is \fB\-\-content\-size\fR (meaning that the original size will be placed in the header)\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-no\-dictID\fR: do not store dictionary ID within frame header (dictionary compression)\. The decoder will have to rely on implicit knowledge about which dictionary to use, it won\'t be able to check if it\'s correct\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-M#\fR, \fB\-\-memory=#\fR: Set a memory usage limit\. By default, \fBzstd\fR uses 128 MiB for decompression as the maximum amount of memory the decompressor is allowed to use, but you can override this manually if need be in either direction (i\.e\. you can increase or decrease it)\.
+.
 .IP
 This is also used during compression when using with \fB\-\-patch\-from=\fR\. In this case, this parameter overrides that maximum size allowed for a dictionary\. (128 MiB)\.
+.
 .IP
 Additionally, this can be used to limit memory for dictionary training\. This parameter overrides the default limit of 2 GiB\. zstd will load training samples up to the memory limit and ignore the rest\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-stream\-size=#\fR: Sets the pledged source size of input coming from a stream\. This value must be exact, as it will be included in the produced frame header\. Incorrect stream sizes will cause an error\. This information will be used to better optimize compression parameters, resulting in better and potentially faster compression, especially for smaller source sizes\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-size\-hint=#\fR: When handling input from a stream, \fBzstd\fR must guess how large the source size will be when optimizing compression parameters\. If the stream size is relatively small, this guess may be a poor one, resulting in a higher compression ratio than expected\. This feature allows for controlling the guess when needed\. Exact guesses result in better compression ratios\. Overestimates result in slightly degraded compression ratios, while underestimates may result in significant degradation\.
-.IP "\[ci]" 4
-\fB\-o FILE\fR: save result into \fBFILE\fR\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
+\fB\-\-target\-compressed\-block\-size=#\fR: Attempt to produce compressed blocks of approximately this size\. This will split larger blocks in order to approach this target\. This feature is notably useful for improved latency, when the receiver can leverage receiving early incomplete data\. This parameter defines a loose target: compressed blocks will target this size "on average", but individual blocks can still be larger or smaller\. Enabling this feature can decrease compression speed by up to ~10% at level 1\. Higher levels will see smaller relative speed regression, becoming invisible at higher settings\.
+.
+.IP "\(bu" 4
 \fB\-f\fR, \fB\-\-force\fR: disable input and output checks\. Allows overwriting existing files, input from console, output to stdout, operating on links, block devices, etc\. During decompression and when the output destination is stdout, pass\-through unrecognized formats as\-is\.
-.IP "\[ci]" 4
-\fB\-c\fR, \fB\-\-stdout\fR: write to standard output (even if it is the console); keep original files unchanged\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
+\fB\-c\fR, \fB\-\-stdout\fR: write to standard output (even if it is the console); keep original files (disable \fB\-\-rm\fR)\.
+.
+.IP "\(bu" 4
+\fB\-o FILE\fR: save result into \fBFILE\fR\. Note that this operation is in conflict with \fB\-c\fR\. If both operations are present on the command line, the last expressed one wins\.
+.
+.IP "\(bu" 4
 \fB\-\-[no\-]sparse\fR: enable / disable sparse FS support, to make files with many zeroes smaller on disk\. Creating sparse files may save disk space and speed up decompression by reducing the amount of disk I/O\. default: enabled when output is into a file, and disabled when output is stdout\. This setting overrides default and can force sparse mode over stdout\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-[no\-]pass\-through\fR enable / disable passing through uncompressed files as\-is\. During decompression when pass\-through is enabled, unrecognized formats will be copied as\-is from the input to the output\. By default, pass\-through will occur when the output destination is stdout and the force (\fB\-f\fR) option is set\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-rm\fR: remove source file(s) after successful compression or decompression\. This command is silently ignored if output is \fBstdout\fR\. If used in combination with \fB\-o\fR, triggers a confirmation prompt (which can be silenced with \fB\-f\fR), as this is a destructive operation\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-k\fR, \fB\-\-keep\fR: keep source file(s) after successful compression or decompression\. This is the default behavior\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-r\fR: operate recursively on directories\. It selects all files in the named directory and all its subdirectories\. This can be useful both to reduce command line typing, and to circumvent shell expansion limitations, when there are a lot of files and naming breaks the maximum size of a command line\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-filelist FILE\fR read a list of files to process as content from \fBFILE\fR\. Format is compatible with \fBls\fR output, with one file per line\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-output\-dir\-flat DIR\fR: resulting files are stored into target \fBDIR\fR directory, instead of same directory as origin file\. Be aware that this command can introduce name collision issues, if multiple files, from different directories, end up having the same name\. Collision resolution ensures first file with a given name will be present in \fBDIR\fR, while in combination with \fB\-f\fR, the last file will be present instead\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-output\-dir\-mirror DIR\fR: similar to \fB\-\-output\-dir\-flat\fR, the output files are stored underneath target \fBDIR\fR directory, but this option will replicate input directory hierarchy into output \fBDIR\fR\.
+.
 .IP
 If input directory contains "\.\.", the files in this directory will be ignored\. If input directory is an absolute directory (i\.e\. "/var/tmp/abc"), it will be stored into the "output\-dir/var/tmp/abc"\. If there are multiple input files or directories, name collision resolution will follow the same rules as \fB\-\-output\-dir\-flat\fR\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-format=FORMAT\fR: compress and decompress in other formats\. If compiled with support, zstd can compress to or decompress from other compression algorithm formats\. Possibly available options are \fBzstd\fR, \fBgzip\fR, \fBxz\fR, \fBlzma\fR, and \fBlz4\fR\. If no such format is provided, \fBzstd\fR is the default\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-h\fR/\fB\-H\fR, \fB\-\-help\fR: display help/long help and exit
-.IP "\[ci]" 4
-\fB\-V\fR, \fB\-\-version\fR: display version number and exit\. Advanced: \fB\-vV\fR also displays supported formats\. \fB\-vvV\fR also displays POSIX support\. \fB\-q\fR will only display the version number, suitable for machine reading\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
+\fB\-V\fR, \fB\-\-version\fR: display version number and immediately exit\. note that, since it exits, flags specified after \fB\-V\fR are effectively ignored\. Advanced: \fB\-vV\fR also displays supported formats\. \fB\-vvV\fR also displays POSIX support\. \fB\-qV\fR will only display the version number, suitable for machine reading\.
+.
+.IP "\(bu" 4
 \fB\-v\fR, \fB\-\-verbose\fR: verbose mode, display more information
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-q\fR, \fB\-\-quiet\fR: suppress warnings, interactivity, and notifications\. specify twice to suppress errors too\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-no\-progress\fR: do not display the progress bar, but keep all other messages\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
 \fB\-\-show\-default\-cparams\fR: shows the default compression parameters that will be used for a particular input file, based on the provided compression level and the input size\. If the provided file is not a regular file (e\.g\. a pipe), this flag will output the parameters used for inputs of unknown size\.
-.IP "\[ci]" 4
+.
+.IP "\(bu" 4
+\fB\-\-exclude\-compressed\fR: only compress files that are not already compressed\.
+.
+.IP "\(bu" 4
 \fB\-\-\fR: All arguments after \fB\-\-\fR are treated as files
+.
 .IP "" 0
+.
 .SS "gzip Operation Modifiers"
 When invoked via a \fBgzip\fR symlink, \fBzstd\fR will support further options that intend to mimic the \fBgzip\fR behavior:
+.
 .TP
 \fB\-n\fR, \fB\-\-no\-name\fR
 do not store the original filename and timestamps when compressing a file\. This is the default behavior and hence a no\-op\.
+.
 .TP
 \fB\-\-best\fR
 alias to the option \fB\-9\fR\.
+.
 .SS "Environment Variables"
-Employing environment variables to set parameters has security implications\. Therefore, this avenue is intentionally limited\. Only \fBZSTD_CLEVEL\fR and \fBZSTD_NBTHREADS\fR are currently supported\. They set the compression level and number of threads to use during compression, respectively\.
+Employing environment variables to set parameters has security implications\. Therefore, this avenue is intentionally limited\. Only \fBZSTD_CLEVEL\fR and \fBZSTD_NBTHREADS\fR are currently supported\. They set the default compression level and number of threads to use during compression, respectively\.
+.
 .P
 \fBZSTD_CLEVEL\fR can be used to set the level between 1 and 19 (the "normal" range)\. If the value of \fBZSTD_CLEVEL\fR is not a valid integer, it will be ignored with a warning message\. \fBZSTD_CLEVEL\fR just replaces the default compression level (\fB3\fR)\.
+.
 .P
-\fBZSTD_NBTHREADS\fR can be used to set the number of threads \fBzstd\fR will attempt to use during compression\. If the value of \fBZSTD_NBTHREADS\fR is not a valid unsigned integer, it will be ignored with a warning message\. \fBZSTD_NBTHREADS\fR has a default value of (\fB1\fR), and is capped at ZSTDMT_NBWORKERS_MAX==200\. \fBzstd\fR must be compiled with multithread support for this to have any effect\.
+\fBZSTD_NBTHREADS\fR can be used to set the number of threads \fBzstd\fR will attempt to use during compression\. If the value of \fBZSTD_NBTHREADS\fR is not a valid unsigned integer, it will be ignored with a warning message\. \fBZSTD_NBTHREADS\fR has a default value of (\fB1\fR), and is capped at ZSTDMT_NBWORKERS_MAX==200\. \fBzstd\fR must be compiled with multithread support for this variable to have any effect\.
+.
 .P
 They can both be overridden by corresponding command line arguments: \fB\-#\fR for compression level and \fB\-T#\fR for number of compression threads\.
-.SH "DICTIONARY BUILDER"
-\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It\'s possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\.
-.TP
-\fB\-\-train FILEs\fR
-Use FILEs as training set to create a dictionary\. The training set should ideally contain a lot of samples (> 100), and weight typically 100x the target dictionary size (for example, ~10 MB for a 100 KB dictionary)\. \fB\-\-train\fR can be combined with \fB\-r\fR to indicate a directory rather than listing all the files, which can be useful to circumvent shell expansion limits\.
-.IP
-Since dictionary compression is mostly effective for small files, the expectation is that the training set will only contain small files\. In the case where some samples happen to be large, only the first 128 KiB of these samples will be used for training\.
-.IP
-\fB\-\-train\fR supports multithreading if \fBzstd\fR is compiled with threading support (default)\. Additional advanced parameters can be specified with \fB\-\-train\-fastcover\fR\. The legacy dictionary builder can be accessed with \fB\-\-train\-legacy\fR\. The slower cover dictionary builder can be accessed with \fB\-\-train\-cover\fR\. Default \fB\-\-train\fR is equivalent to \fB\-\-train\-fastcover=d=8,steps=4\fR\.
-.TP
-\fB\-o FILE\fR
-Dictionary saved into \fBFILE\fR (default name: dictionary)\.
-.TP
-\fB\-\-maxdict=#\fR
-Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it\'s possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\.
-.TP
-\fB\-#\fR
-Use \fB#\fR compression level during training (optional)\. Will generate statistics more tuned for selected compression level, resulting in a \fIsmall\fR compression ratio improvement for this level\.
-.TP
-\fB\-B#\fR
-Split input files into blocks of size # (default: no split)
-.TP
-\fB\-M#\fR, \fB\-\-memory=#\fR
-Limit the amount of sample data loaded for training (default: 2 GB)\. Note that the default (2 GB) is also the maximum\. This parameter can be useful in situations where the training set size is not well controlled and could be potentially very large\. Since speed of the training process is directly correlated to the size of the training sample set, a smaller sample set leads to faster training\.
-.IP
-In situations where the training set is larger than maximum memory, the CLI will randomly select samples among the available ones, up to the maximum allowed memory budget\. This is meant to improve dictionary relevance by mitigating the potential impact of clustering, such as selecting only files from the beginning of a list sorted by modification date, or sorted by alphabetical order\. The randomization process is deterministic, so training of the same list of files with the same parameters will lead to the creation of the same dictionary\.
-.TP
-\fB\-\-dictID=#\fR
-A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It\'s possible to provide an explicit number ID instead\. It\'s up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\.
-.IP
-Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2\e^31, so they should not be used in public\.
-.TP
-\fB\-\-train\-cover[=k#,d=#,steps=#,split=#,shrink[=#]]\fR
-Select parameters for the default dictionary builder algorithm named cover\. If \fId\fR is not specified, then it tries \fId\fR = 6 and \fId\fR = 8\. If \fIk\fR is not specified, then it tries \fIsteps\fR values in the range [50, 2000]\. If \fIsteps\fR is not specified, then the default value of 40 is used\. If \fIsplit\fR is not specified or split <= 0, then the default value of 100 is used\. Requires that \fId\fR <= \fIk\fR\. If \fIshrink\fR flag is not used, then the default value for \fIshrinkDict\fR of 0 is used\. If \fIshrink\fR is not specified, then the default value for \fIshrinkDictMaxRegression\fR of 1 is used\.
-.IP
-Selects segments of size \fIk\fR with highest score to put in the dictionary\. The score of a segment is computed by the sum of the frequencies of all the subsegments of size \fId\fR\. Generally \fId\fR should be in the range [6, 8], occasionally up to 16, but the algorithm will run faster with d <= \fI8\fR\. Good values for \fIk\fR vary widely based on the input data, but a safe range is [2 * \fId\fR, 2000]\. If \fIsplit\fR is 100, all input samples are used for both training and testing to find optimal \fId\fR and \fIk\fR to build dictionary\. Supports multithreading if \fBzstd\fR is compiled with threading support\. Having \fIshrink\fR enabled takes a truncated dictionary of minimum size and doubles in size until compression ratio of the truncated dictionary is at most \fIshrinkDictMaxRegression%\fR worse than the compression ratio of the largest dictionary\.
-.IP
-Examples:
-.IP
-\fBzstd \-\-train\-cover FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=k=50,d=8 FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=d=8,steps=500 FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=k=50 FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=k=50,split=60 FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=shrink FILEs\fR
-.IP
-\fBzstd \-\-train\-cover=shrink=2 FILEs\fR
-.TP
-\fB\-\-train\-fastcover[=k#,d=#,f=#,steps=#,split=#,accel=#]\fR
-Same as cover but with extra parameters \fIf\fR and \fIaccel\fR and different default value of split If \fIsplit\fR is not specified, then it tries \fIsplit\fR = 75\. If \fIf\fR is not specified, then it tries \fIf\fR = 20\. Requires that 0 < \fIf\fR < 32\. If \fIaccel\fR is not specified, then it tries \fIaccel\fR = 1\. Requires that 0 < \fIaccel\fR <= 10\. Requires that \fId\fR = 6 or \fId\fR = 8\.
-.IP
-\fIf\fR is log of size of array that keeps track of frequency of subsegments of size \fId\fR\. The subsegment is hashed to an index in the range [0,2^\fIf\fR \- 1]\. It is possible that 2 different subsegments are hashed to the same index, and they are considered as the same subsegment when computing frequency\. Using a higher \fIf\fR reduces collision but takes longer\.
-.IP
-Examples:
-.IP
-\fBzstd \-\-train\-fastcover FILEs\fR
-.IP
-\fBzstd \-\-train\-fastcover=d=8,f=15,accel=2 FILEs\fR
-.TP
-\fB\-\-train\-legacy[=selectivity=#]\fR
-Use legacy dictionary builder algorithm with the given dictionary \fIselectivity\fR (default: 9)\. The smaller the \fIselectivity\fR value, the denser the dictionary, improving its efficiency but reducing its achievable maximum size\. \fB\-\-train\-legacy=s=#\fR is also accepted\.
-.IP
-Examples:
-.IP
-\fBzstd \-\-train\-legacy FILEs\fR
-.IP
-\fBzstd \-\-train\-legacy=selectivity=8 FILEs\fR
-.SH "BENCHMARK"
-.TP
-\fB\-b#\fR
-benchmark file(s) using compression level #
-.TP
-\fB\-e#\fR
-benchmark file(s) using multiple compression levels, from \fB\-b#\fR to \fB\-e#\fR (inclusive)
-.TP
-\fB\-i#\fR
-minimum evaluation time, in seconds (default: 3s), benchmark mode only
-.TP
-\fB\-B#\fR, \fB\-\-block\-size=#\fR
-cut file(s) into independent chunks of size # (default: no chunking)
-.TP
-\fB\-\-priority=rt\fR
-set process priority to real\-time
-.P
-\fBOutput Format:\fR CompressionLevel#Filename: InputSize \-> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed
-.P
-\fBMethodology:\fR For both compression and decompression speed, the entire input is compressed/decompressed in\-memory to measure speed\. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy\.
+.
 .SH "ADVANCED COMPRESSION OPTIONS"
-### \-B#: Specify the size of each compression job\. This parameter is only available when multi\-threading is enabled\. Each compression job is run in parallel, so this value indirectly impacts the nb of active threads\. Default job size varies depending on compression level (generally \fB4 * windowSize\fR)\. \fB\-B#\fR makes it possible to manually select a custom size\. Note that job size must respect a minimum value which is enforced transparently\. This minimum is either 512 KB, or \fBoverlapSize\fR, whichever is largest\. Different job sizes will lead to non\-identical compressed frames\.
+zstd provides 22 predefined regular compression levels plus the fast levels\. A compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor (one can see the result of this translation with \-\-show\-default\-cparams)\. These specific parameters can be overridden with advanced compression options\.
+.
 .SS "\-\-zstd[=options]:"
 \fBzstd\fR provides 22 predefined regular compression levels plus the fast levels\. This compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor\. (You can see the result of this translation with \fB\-\-show\-default\-cparams\fR\.) These specific parameters can be overridden with advanced compression options\. The \fIoptions\fR are provided as a comma\-separated list\. You may specify only the options you want to change and the rest will be taken from the selected or default compression level\. The list of available \fIoptions\fR:
+.
 .TP
 \fBstrategy\fR=\fIstrat\fR, \fBstrat\fR=\fIstrat\fR
 Specify a strategy used by a match finder\.
+.
 .IP
 There are 9 strategies numbered from 1 to 9, from fastest to strongest: 1=\fBZSTD_fast\fR, 2=\fBZSTD_dfast\fR, 3=\fBZSTD_greedy\fR, 4=\fBZSTD_lazy\fR, 5=\fBZSTD_lazy2\fR, 6=\fBZSTD_btlazy2\fR, 7=\fBZSTD_btopt\fR, 8=\fBZSTD_btultra\fR, 9=\fBZSTD_btultra2\fR\.
+.
 .TP
 \fBwindowLog\fR=\fIwlog\fR, \fBwlog\fR=\fIwlog\fR
 Specify the maximum number of bits for a match distance\.
+.
 .IP
 The higher number of increases the chance to find a match which usually improves compression ratio\. It also increases memory requirements for the compressor and decompressor\. The minimum \fIwlog\fR is 10 (1 KiB) and the maximum is 30 (1 GiB) on 32\-bit platforms and 31 (2 GiB) on 64\-bit platforms\.
+.
 .IP
 Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\.
+.
 .TP
 \fBhashLog\fR=\fIhlog\fR, \fBhlog\fR=\fIhlog\fR
 Specify the maximum number of bits for a hash table\.
+.
 .IP
 Bigger hash tables cause fewer collisions which usually makes compression faster, but requires more memory during compression\.
+.
 .IP
 The minimum \fIhlog\fR is 6 (64 entries / 256 B) and the maximum is 30 (1B entries / 4 GiB)\.
+.
 .TP
 \fBchainLog\fR=\fIclog\fR, \fBclog\fR=\fIclog\fR
 Specify the maximum number of bits for the secondary search structure, whose form depends on the selected \fBstrategy\fR\.
+.
 .IP
 Higher numbers of bits increases the chance to find a match which usually improves compression ratio\. It also slows down compression speed and increases memory requirements for compression\. This option is ignored for the \fBZSTD_fast\fR \fBstrategy\fR, which only has the primary hash table\.
+.
 .IP
 The minimum \fIclog\fR is 6 (64 entries / 256 B) and the maximum is 29 (512M entries / 2 GiB) on 32\-bit platforms and 30 (1B entries / 4 GiB) on 64\-bit platforms\.
+.
 .TP
 \fBsearchLog\fR=\fIslog\fR, \fBslog\fR=\fIslog\fR
 Specify the maximum number of searches in a hash chain or a binary tree using logarithmic scale\.
+.
 .IP
 More searches increases the chance to find a match which usually increases compression ratio but decreases compression speed\.
+.
 .IP
 The minimum \fIslog\fR is 1 and the maximum is \'windowLog\' \- 1\.
+.
 .TP
 \fBminMatch\fR=\fImml\fR, \fBmml\fR=\fImml\fR
 Specify the minimum searched length of a match in a hash table\.
+.
 .IP
 Larger search lengths usually decrease compression ratio but improve decompression speed\.
+.
 .IP
 The minimum \fImml\fR is 3 and the maximum is 7\.
+.
 .TP
 \fBtargetLength\fR=\fItlen\fR, \fBtlen\fR=\fItlen\fR
 The impact of this field vary depending on selected strategy\.
+.
 .IP
 For \fBZSTD_btopt\fR, \fBZSTD_btultra\fR and \fBZSTD_btultra2\fR, it specifies the minimum match length that causes match finder to stop searching\. A larger \fBtargetLength\fR usually improves compression ratio but decreases compression speed\.
+.
 .IP
 For \fBZSTD_fast\fR, it triggers ultra\-fast mode when > 0\. The value represents the amount of data skipped between match sampling\. Impact is reversed: a larger \fBtargetLength\fR increases compression speed but decreases compression ratio\.
+.
 .IP
 For all other strategies, this field has no impact\.
+.
 .IP
 The minimum \fItlen\fR is 0 and the maximum is 128 KiB\.
+.
 .TP
 \fBoverlapLog\fR=\fIovlog\fR, \fBovlog\fR=\fIovlog\fR
 Determine \fBoverlapSize\fR, amount of data reloaded from previous job\. This parameter is only available when multithreading is enabled\. Reloading more data improves compression ratio, but decreases speed\.
+.
 .IP
 The minimum \fIovlog\fR is 0, and the maximum is 9\. 1 means "no overlap", hence completely independent jobs\. 9 means "full overlap", meaning up to \fBwindowSize\fR is reloaded from previous job\. Reducing \fIovlog\fR by 1 reduces the reloaded amount by a factor 2\. For example, 8 means "windowSize/2", and 6 means "windowSize/8"\. Value 0 is special and means "default": \fIovlog\fR is automatically determined by \fBzstd\fR\. In which case, \fIovlog\fR will range from 6 to 9, depending on selected \fIstrat\fR\.
+.
 .TP
 \fBldmHashLog\fR=\fIlhlog\fR, \fBlhlog\fR=\fIlhlog\fR
 Specify the maximum size for a hash table used for long distance matching\.
+.
 .IP
 This option is ignored unless long distance matching is enabled\.
+.
 .IP
 Bigger hash tables usually improve compression ratio at the expense of more memory during compression and a decrease in compression speed\.
+.
 .IP
 The minimum \fIlhlog\fR is 6 and the maximum is 30 (default: 20)\.
+.
 .TP
 \fBldmMinMatch\fR=\fIlmml\fR, \fBlmml\fR=\fIlmml\fR
 Specify the minimum searched length of a match for long distance matching\.
+.
 .IP
 This option is ignored unless long distance matching is enabled\.
+.
 .IP
 Larger/very small values usually decrease compression ratio\.
+.
 .IP
 The minimum \fIlmml\fR is 4 and the maximum is 4096 (default: 64)\.
+.
 .TP
 \fBldmBucketSizeLog\fR=\fIlblog\fR, \fBlblog\fR=\fIlblog\fR
 Specify the size of each bucket for the hash table used for long distance matching\.
+.
 .IP
 This option is ignored unless long distance matching is enabled\.
+.
 .IP
 Larger bucket sizes improve collision resolution but decrease compression speed\.
+.
 .IP
 The minimum \fIlblog\fR is 1 and the maximum is 8 (default: 3)\.
+.
 .TP
 \fBldmHashRateLog\fR=\fIlhrlog\fR, \fBlhrlog\fR=\fIlhrlog\fR
 Specify the frequency of inserting entries into the long distance matching hash table\.
+.
 .IP
 This option is ignored unless long distance matching is enabled\.
+.
 .IP
 Larger values will improve compression speed\. Deviating far from the default value will likely result in a decrease in compression ratio\.
+.
 .IP
 The default value is \fBwlog \- lhlog\fR\.
+.
 .SS "Example"
 The following parameters sets advanced compression options to something similar to predefined level 19 for files bigger than 256 KB:
+.
 .P
 \fB\-\-zstd\fR=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6
+.
+.SS "\-B#:"
+Specify the size of each compression job\. This parameter is only available when multi\-threading is enabled\. Each compression job is run in parallel, so this value indirectly impacts the nb of active threads\. Default job size varies depending on compression level (generally \fB4 * windowSize\fR)\. \fB\-B#\fR makes it possible to manually select a custom size\. Note that job size must respect a minimum value which is enforced transparently\. This minimum is either 512 KB, or \fBoverlapSize\fR, whichever is largest\. Different job sizes will lead to non\-identical compressed frames\.
+.
+.SH "DICTIONARY BUILDER"
+\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It\'s possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\.
+.
+.TP
+\fB\-\-train FILEs\fR
+Use FILEs as training set to create a dictionary\. The training set should ideally contain a lot of samples (> 100), and weight typically 100x the target dictionary size (for example, ~10 MB for a 100 KB dictionary)\. \fB\-\-train\fR can be combined with \fB\-r\fR to indicate a directory rather than listing all the files, which can be useful to circumvent shell expansion limits\.
+.
+.IP
+Since dictionary compression is mostly effective for small files, the expectation is that the training set will only contain small files\. In the case where some samples happen to be large, only the first 128 KiB of these samples will be used for training\.
+.
+.IP
+\fB\-\-train\fR supports multithreading if \fBzstd\fR is compiled with threading support (default)\. Additional advanced parameters can be specified with \fB\-\-train\-fastcover\fR\. The legacy dictionary builder can be accessed with \fB\-\-train\-legacy\fR\. The slower cover dictionary builder can be accessed with \fB\-\-train\-cover\fR\. Default \fB\-\-train\fR is equivalent to \fB\-\-train\-fastcover=d=8,steps=4\fR\.
+.
+.TP
+\fB\-o FILE\fR
+Dictionary saved into \fBFILE\fR (default name: dictionary)\.
+.
+.TP
+\fB\-\-maxdict=#\fR
+Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it\'s possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\.
+.
+.TP
+\fB\-#\fR
+Use \fB#\fR compression level during training (optional)\. Will generate statistics more tuned for selected compression level, resulting in a \fIsmall\fR compression ratio improvement for this level\.
+.
+.TP
+\fB\-B#\fR
+Split input files into blocks of size # (default: no split)
+.
+.TP
+\fB\-M#\fR, \fB\-\-memory=#\fR
+Limit the amount of sample data loaded for training (default: 2 GB)\. Note that the default (2 GB) is also the maximum\. This parameter can be useful in situations where the training set size is not well controlled and could be potentially very large\. Since speed of the training process is directly correlated to the size of the training sample set, a smaller sample set leads to faster training\.
+.
+.IP
+In situations where the training set is larger than maximum memory, the CLI will randomly select samples among the available ones, up to the maximum allowed memory budget\. This is meant to improve dictionary relevance by mitigating the potential impact of clustering, such as selecting only files from the beginning of a list sorted by modification date, or sorted by alphabetical order\. The randomization process is deterministic, so training of the same list of files with the same parameters will lead to the creation of the same dictionary\.
+.
+.TP
+\fB\-\-dictID=#\fR
+A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It\'s possible to provide an explicit number ID instead\. It\'s up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\.
+.
+.IP
+Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2^31, so they should not be used in public\.
+.
+.TP
+\fB\-\-train\-cover[=k#,d=#,steps=#,split=#,shrink[=#]]\fR
+Select parameters for the default dictionary builder algorithm named cover\. If \fId\fR is not specified, then it tries \fId\fR = 6 and \fId\fR = 8\. If \fIk\fR is not specified, then it tries \fIsteps\fR values in the range [50, 2000]\. If \fIsteps\fR is not specified, then the default value of 40 is used\. If \fIsplit\fR is not specified or split <= 0, then the default value of 100 is used\. Requires that \fId\fR <= \fIk\fR\. If \fIshrink\fR flag is not used, then the default value for \fIshrinkDict\fR of 0 is used\. If \fIshrink\fR is not specified, then the default value for \fIshrinkDictMaxRegression\fR of 1 is used\.
+.
+.IP
+Selects segments of size \fIk\fR with highest score to put in the dictionary\. The score of a segment is computed by the sum of the frequencies of all the subsegments of size \fId\fR\. Generally \fId\fR should be in the range [6, 8], occasionally up to 16, but the algorithm will run faster with d <= \fI8\fR\. Good values for \fIk\fR vary widely based on the input data, but a safe range is [2 * \fId\fR, 2000]\. If \fIsplit\fR is 100, all input samples are used for both training and testing to find optimal \fId\fR and \fIk\fR to build dictionary\. Supports multithreading if \fBzstd\fR is compiled with threading support\. Having \fIshrink\fR enabled takes a truncated dictionary of minimum size and doubles in size until compression ratio of the truncated dictionary is at most \fIshrinkDictMaxRegression%\fR worse than the compression ratio of the largest dictionary\.
+.
+.IP
+Examples:
+.
+.IP
+\fBzstd \-\-train\-cover FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=k=50,d=8 FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=d=8,steps=500 FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=k=50 FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=k=50,split=60 FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=shrink FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-cover=shrink=2 FILEs\fR
+.
+.TP
+\fB\-\-train\-fastcover[=k#,d=#,f=#,steps=#,split=#,accel=#]\fR
+Same as cover but with extra parameters \fIf\fR and \fIaccel\fR and different default value of split If \fIsplit\fR is not specified, then it tries \fIsplit\fR = 75\. If \fIf\fR is not specified, then it tries \fIf\fR = 20\. Requires that 0 < \fIf\fR < 32\. If \fIaccel\fR is not specified, then it tries \fIaccel\fR = 1\. Requires that 0 < \fIaccel\fR <= 10\. Requires that \fId\fR = 6 or \fId\fR = 8\.
+.
+.IP
+\fIf\fR is log of size of array that keeps track of frequency of subsegments of size \fId\fR\. The subsegment is hashed to an index in the range [0,2^\fIf\fR \- 1]\. It is possible that 2 different subsegments are hashed to the same index, and they are considered as the same subsegment when computing frequency\. Using a higher \fIf\fR reduces collision but takes longer\.
+.
+.IP
+Examples:
+.
+.IP
+\fBzstd \-\-train\-fastcover FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-fastcover=d=8,f=15,accel=2 FILEs\fR
+.
+.TP
+\fB\-\-train\-legacy[=selectivity=#]\fR
+Use legacy dictionary builder algorithm with the given dictionary \fIselectivity\fR (default: 9)\. The smaller the \fIselectivity\fR value, the denser the dictionary, improving its efficiency but reducing its achievable maximum size\. \fB\-\-train\-legacy=s=#\fR is also accepted\.
+.
+.IP
+Examples:
+.
+.IP
+\fBzstd \-\-train\-legacy FILEs\fR
+.
+.IP
+\fBzstd \-\-train\-legacy=selectivity=8 FILEs\fR
+.
+.SH "BENCHMARK"
+The \fBzstd\fR CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer\'s performance\. Note that the results are highly dependent on the content being compressed\.
+.
+.TP
+\fB\-b#\fR
+benchmark file(s) using compression level #
+.
+.TP
+\fB\-e#\fR
+benchmark file(s) using multiple compression levels, from \fB\-b#\fR to \fB\-e#\fR (inclusive)
+.
+.TP
+\fB\-d\fR
+benchmark decompression speed only (requires providing an already zstd\-compressed content)
+.
+.TP
+\fB\-i#\fR
+minimum evaluation time, in seconds (default: 3s), benchmark mode only
+.
+.TP
+\fB\-B#\fR, \fB\-\-block\-size=#\fR
+cut file(s) into independent chunks of size # (default: no chunking)
+.
+.TP
+\fB\-\-priority=rt\fR
+set process priority to real\-time (Windows)
+.
+.P
+\fBOutput Format:\fR CompressionLevel#Filename: InputSize \-> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed
+.
+.P
+\fBMethodology:\fR For both compression and decompression speed, the entire input is compressed/decompressed in\-memory to measure speed\. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy\.
+.
 .SH "SEE ALSO"
 \fBzstdgrep\fR(1), \fBzstdless\fR(1), \fBgzip\fR(1), \fBxz\fR(1)
+.
 .P
 The \fIzstandard\fR format is specified in Y\. Collet, "Zstandard Compression and the \'application/zstd\' Media Type", https://www\.ietf\.org/rfc/rfc8878\.txt, Internet RFC 8878 (February 2021)\.
+.
 .SH "BUGS"
 Report bugs at: https://github\.com/facebook/zstd/issues
+.
 .SH "AUTHOR"
 Yann Collet
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index a5046932e..f5abb141a 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -21,10 +21,11 @@ It is based on the **LZ77** family, with further FSE & huff0 entropy stages.
 `zstd` offers highly configurable compression speed,
 from fast modes at > 200 MB/s per core,
 to strong modes with excellent compression ratios.
-It also features a very fast decoder, with speeds > 500 MB/s per core.
+It also features a very fast decoder, with speeds > 500 MB/s per core,
+which remains roughly stable at all compression settings.
 
 `zstd` command line syntax is generally similar to gzip,
-but features the following differences:
+but features the following few differences:
 
   - Source files are preserved by default.
     It's possible to remove them automatically by using the `--rm` command.
@@ -105,7 +106,11 @@ the last one takes effect.
 ### Operation Modifiers
 
 * `-#`:
-    selects `#` compression level \[1-19\] (default: 3)
+    selects `#` compression level \[1-19\] (default: 3).
+    Higher compression levels *generally* produce higher compression ratio at the expense of speed and memory.
+    A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels.
+    Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below).
+    Because the compressor's behavior highly depends on the content to compress, there's no guarantee of a smooth progression from one level to another.
 * `--ultra`:
     unlocks high compression levels 20+ (maximum 22), using a lot more memory.
     Note that decompression will also require more memory when using these levels.
@@ -325,11 +330,10 @@ options that intend to mimic the `gzip` behavior:
 
 
 ### Environment Variables
-
 Employing environment variables to set parameters has security implications.
 Therefore, this avenue is intentionally limited.
 Only `ZSTD_CLEVEL` and `ZSTD_NBTHREADS` are currently supported.
-They set the compression level and number of threads to use during compression, respectively.
+They set the default compression level and number of threads to use during compression, respectively.
 
 `ZSTD_CLEVEL` can be used to set the level between 1 and 19 (the "normal" range).
 If the value of `ZSTD_CLEVEL` is not a valid integer, it will be ignored with a warning message.
@@ -338,12 +342,175 @@ If the value of `ZSTD_CLEVEL` is not a valid integer, it will be ignored with a
 `ZSTD_NBTHREADS` can be used to set the number of threads `zstd` will attempt to use during compression.
 If the value of `ZSTD_NBTHREADS` is not a valid unsigned integer, it will be ignored with a warning message.
 `ZSTD_NBTHREADS` has a default value of (`1`), and is capped at ZSTDMT_NBWORKERS_MAX==200.
-`zstd` must be compiled with multithread support for this to have any effect.
+`zstd` must be compiled with multithread support for this variable to have any effect.
 
 They can both be overridden by corresponding command line arguments:
 `-#` for compression level and `-T#` for number of compression threads.
 
 
+ADVANCED COMPRESSION OPTIONS
+----------------------------
+zstd provides 22 predefined regular compression levels plus the fast levels.
+A compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor
+(one can see the result of this translation with --show-default-cparams).
+These specific parameters can be overridden with advanced compression options.
+
+### --zstd[=options]:
+`zstd` provides 22 predefined regular compression levels plus the fast levels.
+This compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor.
+(You can see the result of this translation with `--show-default-cparams`.)
+These specific parameters can be overridden with advanced compression options.
+The _options_ are provided as a comma-separated list.
+You may specify only the options you want to change and the rest will be
+taken from the selected or default compression level.
+The list of available _options_:
+
+- `strategy`=_strat_, `strat`=_strat_:
+    Specify a strategy used by a match finder.
+
+    There are 9 strategies numbered from 1 to 9, from fastest to strongest:
+    1=`ZSTD_fast`, 2=`ZSTD_dfast`, 3=`ZSTD_greedy`,
+    4=`ZSTD_lazy`, 5=`ZSTD_lazy2`, 6=`ZSTD_btlazy2`,
+    7=`ZSTD_btopt`, 8=`ZSTD_btultra`, 9=`ZSTD_btultra2`.
+
+- `windowLog`=_wlog_, `wlog`=_wlog_:
+    Specify the maximum number of bits for a match distance.
+
+    The higher number of increases the chance to find a match which usually
+    improves compression ratio.
+    It also increases memory requirements for the compressor and decompressor.
+    The minimum _wlog_ is 10 (1 KiB) and the maximum is 30 (1 GiB) on 32-bit
+    platforms and 31 (2 GiB) on 64-bit platforms.
+
+    Note: If `windowLog` is set to larger than 27, `--long=windowLog` or
+    `--memory=windowSize` needs to be passed to the decompressor.
+
+- `hashLog`=_hlog_, `hlog`=_hlog_:
+    Specify the maximum number of bits for a hash table.
+
+    Bigger hash tables cause fewer collisions which usually makes compression
+    faster, but requires more memory during compression.
+
+    The minimum _hlog_ is 6 (64 entries / 256 B) and the maximum is 30 (1B entries / 4 GiB).
+
+- `chainLog`=_clog_, `clog`=_clog_:
+    Specify the maximum number of bits for the secondary search structure,
+    whose form depends on the selected `strategy`.
+
+    Higher numbers of bits increases the chance to find a match which usually
+    improves compression ratio.
+    It also slows down compression speed and increases memory requirements for
+    compression.
+    This option is ignored for the `ZSTD_fast` `strategy`, which only has the primary hash table.
+
+    The minimum _clog_ is 6 (64 entries / 256 B) and the maximum is 29 (512M entries / 2 GiB) on 32-bit platforms
+    and 30 (1B entries / 4 GiB) on 64-bit platforms.
+
+- `searchLog`=_slog_, `slog`=_slog_:
+    Specify the maximum number of searches in a hash chain or a binary tree
+    using logarithmic scale.
+
+    More searches increases the chance to find a match which usually increases
+    compression ratio but decreases compression speed.
+
+    The minimum _slog_ is 1 and the maximum is 'windowLog' - 1.
+
+- `minMatch`=_mml_, `mml`=_mml_:
+    Specify the minimum searched length of a match in a hash table.
+
+    Larger search lengths usually decrease compression ratio but improve
+    decompression speed.
+
+    The minimum _mml_ is 3 and the maximum is 7.
+
+- `targetLength`=_tlen_, `tlen`=_tlen_:
+    The impact of this field vary depending on selected strategy.
+
+    For `ZSTD_btopt`, `ZSTD_btultra` and `ZSTD_btultra2`, it specifies
+    the minimum match length that causes match finder to stop searching.
+    A larger `targetLength` usually improves compression ratio
+    but decreases compression speed.
+
+    For `ZSTD_fast`, it triggers ultra-fast mode when > 0.
+    The value represents the amount of data skipped between match sampling.
+    Impact is reversed: a larger `targetLength` increases compression speed
+    but decreases compression ratio.
+
+    For all other strategies, this field has no impact.
+
+    The minimum _tlen_ is 0 and the maximum is 128 KiB.
+
+- `overlapLog`=_ovlog_,  `ovlog`=_ovlog_:
+    Determine `overlapSize`, amount of data reloaded from previous job.
+    This parameter is only available when multithreading is enabled.
+    Reloading more data improves compression ratio, but decreases speed.
+
+    The minimum _ovlog_ is 0, and the maximum is 9.
+    1 means "no overlap", hence completely independent jobs.
+    9 means "full overlap", meaning up to `windowSize` is reloaded from previous job.
+    Reducing _ovlog_ by 1 reduces the reloaded amount by a factor 2.
+    For example, 8 means "windowSize/2", and 6 means "windowSize/8".
+    Value 0 is special and means "default": _ovlog_ is automatically determined by `zstd`.
+    In which case, _ovlog_ will range from 6 to 9, depending on selected _strat_.
+
+- `ldmHashLog`=_lhlog_, `lhlog`=_lhlog_:
+    Specify the maximum size for a hash table used for long distance matching.
+
+    This option is ignored unless long distance matching is enabled.
+
+    Bigger hash tables usually improve compression ratio at the expense of more
+    memory during compression and a decrease in compression speed.
+
+    The minimum _lhlog_ is 6 and the maximum is 30 (default: 20).
+
+- `ldmMinMatch`=_lmml_, `lmml`=_lmml_:
+    Specify the minimum searched length of a match for long distance matching.
+
+    This option is ignored unless long distance matching is enabled.
+
+    Larger/very small values usually decrease compression ratio.
+
+    The minimum _lmml_ is 4 and the maximum is 4096 (default: 64).
+
+- `ldmBucketSizeLog`=_lblog_, `lblog`=_lblog_:
+    Specify the size of each bucket for the hash table used for long distance
+    matching.
+
+    This option is ignored unless long distance matching is enabled.
+
+    Larger bucket sizes improve collision resolution but decrease compression
+    speed.
+
+    The minimum _lblog_ is 1 and the maximum is 8 (default: 3).
+
+- `ldmHashRateLog`=_lhrlog_, `lhrlog`=_lhrlog_:
+    Specify the frequency of inserting entries into the long distance matching
+    hash table.
+
+    This option is ignored unless long distance matching is enabled.
+
+    Larger values will improve compression speed. Deviating far from the
+    default value will likely result in a decrease in compression ratio.
+
+    The default value is `wlog - lhlog`.
+
+### Example
+The following parameters sets advanced compression options to something
+similar to predefined level 19 for files bigger than 256 KB:
+
+`--zstd`=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6
+
+### -B#:
+Specify the size of each compression job.
+This parameter is only available when multi-threading is enabled.
+Each compression job is run in parallel, so this value indirectly impacts the nb of active threads.
+Default job size varies depending on compression level (generally  `4 * windowSize`).
+`-B#` makes it possible to manually select a custom size.
+Note that job size must respect a minimum value which is enforced transparently.
+This minimum is either 512 KB, or `overlapSize`, whichever is largest.
+Different job sizes will lead to non-identical compressed frames.
+
+
 DICTIONARY BUILDER
 ------------------
 `zstd` offers _dictionary_ compression,
@@ -496,178 +663,26 @@ Compression of small files similar to the sample set will be greatly improved.
 
 BENCHMARK
 ---------
+The `zstd` CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer's performance.
+Note that the results are highly dependent on the content being compressed.
 
 * `-b#`:
     benchmark file(s) using compression level #
 * `-e#`:
     benchmark file(s) using multiple compression levels, from `-b#` to `-e#` (inclusive)
+* `-d`:
+    benchmark decompression speed only (requires providing an already zstd-compressed content)
 * `-i#`:
     minimum evaluation time, in seconds (default: 3s), benchmark mode only
 * `-B#`, `--block-size=#`:
     cut file(s) into independent chunks of size # (default: no chunking)
 * `--priority=rt`:
-    set process priority to real-time
+    set process priority to real-time (Windows)
 
 **Output Format:** CompressionLevel#Filename: InputSize -> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed
 
 **Methodology:** For both compression and decompression speed, the entire input is compressed/decompressed in-memory to measure speed. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy.
 
-ADVANCED COMPRESSION OPTIONS
-----------------------------
-### -B#:
-Specify the size of each compression job.
-This parameter is only available when multi-threading is enabled.
-Each compression job is run in parallel, so this value indirectly impacts the nb of active threads.
-Default job size varies depending on compression level (generally  `4 * windowSize`).
-`-B#` makes it possible to manually select a custom size.
-Note that job size must respect a minimum value which is enforced transparently.
-This minimum is either 512 KB, or `overlapSize`, whichever is largest.
-Different job sizes will lead to non-identical compressed frames.
-
-### --zstd[=options]:
-`zstd` provides 22 predefined regular compression levels plus the fast levels.
-This compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor.
-(You can see the result of this translation with `--show-default-cparams`.)
-These specific parameters can be overridden with advanced compression options.
-The _options_ are provided as a comma-separated list.
-You may specify only the options you want to change and the rest will be
-taken from the selected or default compression level.
-The list of available _options_:
-
-- `strategy`=_strat_, `strat`=_strat_:
-    Specify a strategy used by a match finder.
-
-    There are 9 strategies numbered from 1 to 9, from fastest to strongest:
-    1=`ZSTD_fast`, 2=`ZSTD_dfast`, 3=`ZSTD_greedy`,
-    4=`ZSTD_lazy`, 5=`ZSTD_lazy2`, 6=`ZSTD_btlazy2`,
-    7=`ZSTD_btopt`, 8=`ZSTD_btultra`, 9=`ZSTD_btultra2`.
-
-- `windowLog`=_wlog_, `wlog`=_wlog_:
-    Specify the maximum number of bits for a match distance.
-
-    The higher number of increases the chance to find a match which usually
-    improves compression ratio.
-    It also increases memory requirements for the compressor and decompressor.
-    The minimum _wlog_ is 10 (1 KiB) and the maximum is 30 (1 GiB) on 32-bit
-    platforms and 31 (2 GiB) on 64-bit platforms.
-
-    Note: If `windowLog` is set to larger than 27, `--long=windowLog` or
-    `--memory=windowSize` needs to be passed to the decompressor.
-
-- `hashLog`=_hlog_, `hlog`=_hlog_:
-    Specify the maximum number of bits for a hash table.
-
-    Bigger hash tables cause fewer collisions which usually makes compression
-    faster, but requires more memory during compression.
-
-    The minimum _hlog_ is 6 (64 entries / 256 B) and the maximum is 30 (1B entries / 4 GiB).
-
-- `chainLog`=_clog_, `clog`=_clog_:
-    Specify the maximum number of bits for the secondary search structure,
-    whose form depends on the selected `strategy`.
-
-    Higher numbers of bits increases the chance to find a match which usually
-    improves compression ratio.
-    It also slows down compression speed and increases memory requirements for
-    compression.
-    This option is ignored for the `ZSTD_fast` `strategy`, which only has the primary hash table.
-
-    The minimum _clog_ is 6 (64 entries / 256 B) and the maximum is 29 (512M entries / 2 GiB) on 32-bit platforms
-    and 30 (1B entries / 4 GiB) on 64-bit platforms.
-
-- `searchLog`=_slog_, `slog`=_slog_:
-    Specify the maximum number of searches in a hash chain or a binary tree
-    using logarithmic scale.
-
-    More searches increases the chance to find a match which usually increases
-    compression ratio but decreases compression speed.
-
-    The minimum _slog_ is 1 and the maximum is 'windowLog' - 1.
-
-- `minMatch`=_mml_, `mml`=_mml_:
-    Specify the minimum searched length of a match in a hash table.
-
-    Larger search lengths usually decrease compression ratio but improve
-    decompression speed.
-
-    The minimum _mml_ is 3 and the maximum is 7.
-
-- `targetLength`=_tlen_, `tlen`=_tlen_:
-    The impact of this field vary depending on selected strategy.
-
-    For `ZSTD_btopt`, `ZSTD_btultra` and `ZSTD_btultra2`, it specifies
-    the minimum match length that causes match finder to stop searching.
-    A larger `targetLength` usually improves compression ratio
-    but decreases compression speed.
-
-    For `ZSTD_fast`, it triggers ultra-fast mode when > 0.
-    The value represents the amount of data skipped between match sampling.
-    Impact is reversed: a larger `targetLength` increases compression speed
-    but decreases compression ratio.
-
-    For all other strategies, this field has no impact.
-
-    The minimum _tlen_ is 0 and the maximum is 128 KiB.
-
-- `overlapLog`=_ovlog_,  `ovlog`=_ovlog_:
-    Determine `overlapSize`, amount of data reloaded from previous job.
-    This parameter is only available when multithreading is enabled.
-    Reloading more data improves compression ratio, but decreases speed.
-
-    The minimum _ovlog_ is 0, and the maximum is 9.
-    1 means "no overlap", hence completely independent jobs.
-    9 means "full overlap", meaning up to `windowSize` is reloaded from previous job.
-    Reducing _ovlog_ by 1 reduces the reloaded amount by a factor 2.
-    For example, 8 means "windowSize/2", and 6 means "windowSize/8".
-    Value 0 is special and means "default": _ovlog_ is automatically determined by `zstd`.
-    In which case, _ovlog_ will range from 6 to 9, depending on selected _strat_.
-
-- `ldmHashLog`=_lhlog_, `lhlog`=_lhlog_:
-    Specify the maximum size for a hash table used for long distance matching.
-
-    This option is ignored unless long distance matching is enabled.
-
-    Bigger hash tables usually improve compression ratio at the expense of more
-    memory during compression and a decrease in compression speed.
-
-    The minimum _lhlog_ is 6 and the maximum is 30 (default: 20).
-
-- `ldmMinMatch`=_lmml_, `lmml`=_lmml_:
-    Specify the minimum searched length of a match for long distance matching.
-
-    This option is ignored unless long distance matching is enabled.
-
-    Larger/very small values usually decrease compression ratio.
-
-    The minimum _lmml_ is 4 and the maximum is 4096 (default: 64).
-
-- `ldmBucketSizeLog`=_lblog_, `lblog`=_lblog_:
-    Specify the size of each bucket for the hash table used for long distance
-    matching.
-
-    This option is ignored unless long distance matching is enabled.
-
-    Larger bucket sizes improve collision resolution but decrease compression
-    speed.
-
-    The minimum _lblog_ is 1 and the maximum is 8 (default: 3).
-
-- `ldmHashRateLog`=_lhrlog_, `lhrlog`=_lhrlog_:
-    Specify the frequency of inserting entries into the long distance matching
-    hash table.
-
-    This option is ignored unless long distance matching is enabled.
-
-    Larger values will improve compression speed. Deviating far from the
-    default value will likely result in a decrease in compression ratio.
-
-    The default value is `wlog - lhlog`.
-
-### Example
-The following parameters sets advanced compression options to something
-similar to predefined level 19 for files bigger than 256 KB:
-
-`--zstd`=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6
 
 SEE ALSO
 --------

From ff6713fd72b083ce8a7d1f2a89cd3749ce9f07a8 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 12 Mar 2024 13:09:10 -0700
Subject: [PATCH 252/937] fix duplicated paragraph

reported by @zougloub
---
 programs/zstd.1    |  4 ++--
 programs/zstd.1.md | 12 ++++--------
 2 files changed, 6 insertions(+), 10 deletions(-)

diff --git a/programs/zstd.1 b/programs/zstd.1
index 1eb9b9738..f7af55270 100644
--- a/programs/zstd.1
+++ b/programs/zstd.1
@@ -271,10 +271,10 @@ Employing environment variables to set parameters has security implications\. Th
 They can both be overridden by corresponding command line arguments: \fB\-#\fR for compression level and \fB\-T#\fR for number of compression threads\.
 .
 .SH "ADVANCED COMPRESSION OPTIONS"
-zstd provides 22 predefined regular compression levels plus the fast levels\. A compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor (one can see the result of this translation with \-\-show\-default\-cparams)\. These specific parameters can be overridden with advanced compression options\.
+\fBzstd\fR provides 22 predefined regular compression levels plus the fast levels\. A compression level is translated internally into multiple advanced parameters that control the behavior of the compressor (one can observe the result of this translation with \fB\-\-show\-default\-cparams\fR)\. These advanced parameters can be overridden using advanced compression options\.
 .
 .SS "\-\-zstd[=options]:"
-\fBzstd\fR provides 22 predefined regular compression levels plus the fast levels\. This compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor\. (You can see the result of this translation with \fB\-\-show\-default\-cparams\fR\.) These specific parameters can be overridden with advanced compression options\. The \fIoptions\fR are provided as a comma\-separated list\. You may specify only the options you want to change and the rest will be taken from the selected or default compression level\. The list of available \fIoptions\fR:
+The \fIoptions\fR are provided as a comma\-separated list\. You may specify only the options you want to change and the rest will be taken from the selected or default compression level\. The list of available \fIoptions\fR:
 .
 .TP
 \fBstrategy\fR=\fIstrat\fR, \fBstrat\fR=\fIstrat\fR
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index f5abb141a..fcbfb4573 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -350,16 +350,12 @@ They can both be overridden by corresponding command line arguments:
 
 ADVANCED COMPRESSION OPTIONS
 ----------------------------
-zstd provides 22 predefined regular compression levels plus the fast levels.
-A compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor
-(one can see the result of this translation with --show-default-cparams).
-These specific parameters can be overridden with advanced compression options.
+`zstd` provides 22 predefined regular compression levels plus the fast levels.
+A compression level is translated internally into multiple advanced parameters that control the behavior of the compressor
+(one can observe the result of this translation with `--show-default-cparams`).
+These advanced parameters can be overridden using advanced compression options.
 
 ### --zstd[=options]:
-`zstd` provides 22 predefined regular compression levels plus the fast levels.
-This compression level is translated internally into a number of specific parameters that actually control the behavior of the compressor.
-(You can see the result of this translation with `--show-default-cparams`.)
-These specific parameters can be overridden with advanced compression options.
 The _options_ are provided as a comma-separated list.
 You may specify only the options you want to change and the rest will be
 taken from the selected or default compression level.

From f65b9e27ce0b6e4ed096126659021359d004d1ab Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Tue, 12 Mar 2024 17:07:06 -0400
Subject: [PATCH 253/937] Exercise ZSTD_findDecompressedSize() in the simple
 decompression fuzzer (#3959)

* Improve decompression fuzzer

* Fix legacy frame header fuzzer crash, add unit test
---
 lib/decompress/zstd_decompress.c | 9 +++++++++
 tests/fuzz/simple_decompress.c   | 8 +++++++-
 tests/zstreamtest.c              | 9 +++++++++
 3 files changed, 25 insertions(+), 1 deletion(-)

diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index 173059085..42636d578 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -1093,6 +1093,15 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
             decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
             if (ZSTD_isError(decodedSize)) return decodedSize;
 
+            {
+                unsigned long long const expectedSize = ZSTD_getFrameContentSize(src, srcSize);
+                RETURN_ERROR_IF(expectedSize == ZSTD_CONTENTSIZE_ERROR, corruption_detected, "Corrupted frame header!");
+                if (expectedSize != ZSTD_CONTENTSIZE_UNKNOWN) {
+                    RETURN_ERROR_IF(expectedSize != decodedSize, corruption_detected,
+                        "Frame header size does not match decoded size!");
+                }
+            }
+
             assert(decodedSize <= dstCapacity);
             dst = (BYTE*)dst + decodedSize;
             dstCapacity -= decodedSize;
diff --git a/tests/fuzz/simple_decompress.c b/tests/fuzz/simple_decompress.c
index ce5f9f098..0ee61902c 100644
--- a/tests/fuzz/simple_decompress.c
+++ b/tests/fuzz/simple_decompress.c
@@ -37,7 +37,13 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size)
     size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size);
     void *rBuf = FUZZ_malloc(bufSize);
 
-    ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
+    size_t const dSize = ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size);
+    if (!ZSTD_isError(dSize)) {
+        /* If decompression was successful, the content size from the frame header(s) should be valid. */
+        size_t const expectedSize = ZSTD_findDecompressedSize(src, size);
+        FUZZ_ASSERT(expectedSize != ZSTD_CONTENTSIZE_ERROR);
+        FUZZ_ASSERT(expectedSize == ZSTD_CONTENTSIZE_UNKNOWN || expectedSize == dSize);
+    }
     free(rBuf);
 
     FUZZ_dataProducer_free(producer);
diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c
index 82aaf3db5..7cc4068bc 100644
--- a/tests/zstreamtest.c
+++ b/tests/zstreamtest.c
@@ -2408,6 +2408,15 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests)
     }
     DISPLAYLEVEL(3, "OK \n");
 
+    DISPLAYLEVEL(3, "test%3i : Decoder should reject invalid frame header on legacy frames: ", testNb++);
+    {
+        const unsigned char compressed[] = { 0x26,0xb5,0x2f,0xfd,0x50,0x91,0xfd,0xd8,0xb5 };
+        const size_t compressedSize = 9;
+        size_t const dSize = ZSTD_decompress(NULL, 0, compressed, compressedSize);
+        CHECK(!ZSTD_isError(dSize), "must reject when legacy frame header is invalid");
+    }
+    DISPLAYLEVEL(3, "OK \n");
+
 _end:
     FUZ_freeDictionary(dictionary);
     ZSTD_freeCStream(zc);

From b20703f273197589c8c70dd406b81ad601fa9b4a Mon Sep 17 00:00:00 2001
From: Yonatan Komornik <11005061+yoniko@users.noreply.github.com>
Date: Tue, 12 Mar 2024 15:10:07 -0700
Subject: [PATCH 254/937] Updates `ZSTD_RowFindBestMatch` comment (#3947)

Updates the comment on the head of `ZSTD_RowFindBestMatch` to make sure it's aligned with recent changes to the hash table.
---
 lib/compress/zstd_lazy.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c
index 3aba83c6f..67dd55fdb 100644
--- a/lib/compress/zstd_lazy.c
+++ b/lib/compress/zstd_lazy.c
@@ -1123,18 +1123,18 @@ ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGr
 
 /* The high-level approach of the SIMD row based match finder is as follows:
  * - Figure out where to insert the new entry:
- *      - Generate a hash from a byte along with an additional 1-byte "short hash". The additional byte is our "tag"
- *      - The hashTable is effectively split into groups or "rows" of 16 or 32 entries of U32, and the hash determines
+ *      - Generate a hash for current input posistion and split it into a one byte of tag and `rowHashLog` bits of index.
+ *           - The hash is salted by a value that changes on every contex reset, so when the same table is used
+ *             we will avoid collisions that would otherwise slow us down by intorducing phantom matches.
+ *      - The hashTable is effectively split into groups or "rows" of 15 or 31 entries of U32, and the index determines
  *        which row to insert into.
- *      - Determine the correct position within the row to insert the entry into. Each row of 16 or 32 can
- *        be considered as a circular buffer with a "head" index that resides in the tagTable.
- *      - Also insert the "tag" into the equivalent row and position in the tagTable.
- *          - Note: The tagTable has 17 or 33 1-byte entries per row, due to 16 or 32 tags, and 1 "head" entry.
- *                  The 17 or 33 entry rows are spaced out to occur every 32 or 64 bytes, respectively,
- *                  for alignment/performance reasons, leaving some bytes unused.
- * - Use SIMD to efficiently compare the tags in the tagTable to the 1-byte "short hash" and
+ *      - Determine the correct position within the row to insert the entry into. Each row of 15 or 31 can
+ *        be considered as a circular buffer with a "head" index that resides in the tagTable (overall 16 or 32 bytes
+ *        per row).
+ * - Use SIMD to efficiently compare the tags in the tagTable to the 1-byte tag calculated for the position and
  *   generate a bitfield that we can cycle through to check the collisions in the hash table.
  * - Pick the longest match.
+ * - Insert the tag into the equivalent row and position in the tagTable.
  */
 FORCE_INLINE_TEMPLATE
 ZSTD_ALLOW_POINTER_OVERFLOW_ATTR

From 94c102038b81ed89e3b013cb1977496612609f85 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Tue, 12 Mar 2024 12:16:55 -0700
Subject: [PATCH 255/937] [cpu] Backport fix for rbx clobbering on Windows with
 Clang

Backport folly fix for rbx clobbering: https://github.com/facebook/folly/commit/f22f88b8b9d70160388f0f149bc9abaeb82c250b

This supercedes PR #3646.
---
 lib/common/cpu.h | 36 ++++++++++++++++++++++++++++++++++++
 1 file changed, 36 insertions(+)

diff --git a/lib/common/cpu.h b/lib/common/cpu.h
index 8bc34a36d..0e684d9ad 100644
--- a/lib/common/cpu.h
+++ b/lib/common/cpu.h
@@ -35,6 +35,7 @@ MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) {
     U32 f7b = 0;
     U32 f7c = 0;
 #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
+#if !defined(__clang__)
     int reg[4];
     __cpuid((int*)reg, 0);
     {
@@ -50,6 +51,41 @@ MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) {
             f7c = (U32)reg[2];
         }
     }
+#else
+    /* Clang compiler has a bug (fixed in https://reviews.llvm.org/D101338) in
+     * which the `__cpuid` intrinsic does not save and restore `rbx` as it needs
+     * to due to being a reserved register. So in that case, do the `cpuid`
+     * ourselves. Clang supports inline assembly anyway.
+     */
+    U32 n;
+    __asm__(
+        "pushq %%rbx\n\t"
+        "cpuid\n\t"
+        "popq %%rbx\n\t"
+        : "=a"(n)
+        : "a"(0)
+        : "rcx", "rdx");
+    if (n >= 1) {
+      U32 f1a;
+      __asm__(
+          "pushq %%rbx\n\t"
+          "cpuid\n\t"
+          "popq %%rbx\n\t"
+          : "=a"(f1a), "=c"(f1c), "=d"(f1d)
+          : "a"(1)
+          :);
+    }
+    if (n >= 7) {
+      __asm__(
+          "pushq %%rbx\n\t"
+          "cpuid\n\t"
+          "movq %%rbx, %%rax\n\t"
+          "popq %%rbx"
+          : "=a"(f7b), "=c"(f7c)
+          : "a"(7), "c"(0)
+          : "rdx");
+    }
+#endif
 #elif defined(__i386__) && defined(__PIC__) && !defined(__clang__) && defined(__GNUC__)
     /* The following block like the normal cpuid branch below, but gcc
      * reserves ebx for use of its pic register so we must specially

From c1e995321e9d66a648818f7995999c4fe6d77878 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Tue, 12 Mar 2024 12:38:21 -0700
Subject: [PATCH 256/937] [CI] Run tests with CMake on Windows

Build and run tests on Windows with CMake
---
 .github/workflows/dev-short-tests.yml | 5 +++--
 build/cmake/tests/CMakeLists.txt      | 6 +++---
 2 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 9c36386a1..b2aaff89c 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -272,14 +272,15 @@ jobs:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: Add MSBuild to PATH
       uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0
-    - name: Build
+    - name: Build & Test
       working-directory: ${{env.GITHUB_WORKSPACE}}
       run: |
         cd build\cmake
         mkdir build
         cd build
-        cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} ..
+        cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 ..
         cmake.exe --build .
+        ctest.exe -V -C Debug
 
   msbuild-visual-studio:
     strategy:
diff --git a/build/cmake/tests/CMakeLists.txt b/build/cmake/tests/CMakeLists.txt
index 3ead07010..56104a4e3 100644
--- a/build/cmake/tests/CMakeLists.txt
+++ b/build/cmake/tests/CMakeLists.txt
@@ -61,7 +61,7 @@ if (NOT MSVC)
     target_compile_options(fullbench PRIVATE "-Wno-deprecated-declarations")
 endif()
 target_link_libraries(fullbench libzstd_static)
-add_test(NAME fullbench COMMAND fullbench ${ZSTD_FULLBENCH_FLAGS})
+add_test(NAME fullbench COMMAND "$" ${ZSTD_FULLBENCH_FLAGS})
 
 #
 # fuzzer
@@ -73,7 +73,7 @@ endif()
 target_link_libraries(fuzzer libzstd_static)
 AddTestFlagsOption(ZSTD_FUZZER_FLAGS "$ENV{FUZZERTEST} $ENV{FUZZER_FLAGS}"
     "Semicolon-separated list of flags to pass to the fuzzer test (see `fuzzer -h` for usage)")
-add_test(NAME fuzzer COMMAND fuzzer ${ZSTD_FUZZER_FLAGS})
+add_test(NAME fuzzer COMMAND "$" ${ZSTD_FUZZER_FLAGS})
 # Disable the timeout since the run time is too long for the default timeout of
 # 1500 seconds and varies considerably between low-end and high-end CPUs.
 # set_tests_properties(fuzzer PROPERTIES TIMEOUT 0)
@@ -88,7 +88,7 @@ endif()
 target_link_libraries(zstreamtest libzstd_static)
 AddTestFlagsOption(ZSTD_ZSTREAM_FLAGS "$ENV{ZSTREAM_TESTTIME} $ENV{FUZZER_FLAGS}"
     "Semicolon-separated list of flags to pass to the zstreamtest test (see `zstreamtest -h` for usage)")
-add_test(NAME zstreamtest COMMAND zstreamtest ${ZSTD_ZSTREAM_FLAGS})
+add_test(NAME zstreamtest COMMAND "$" ${ZSTD_ZSTREAM_FLAGS})
 
 #
 # playTests.sh

From c8ab027227536a543efd1b7bea04aabf9e97accf Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 13 Mar 2024 11:29:28 -0700
Subject: [PATCH 257/937] reduce the amount of includes in "cover.h"

---
 lib/compress/fse_compress.c |  2 +-
 lib/dictBuilder/cover.c     | 24 ++++++++++++++----------
 lib/dictBuilder/cover.h     | 10 ++--------
 3 files changed, 17 insertions(+), 19 deletions(-)

diff --git a/lib/compress/fse_compress.c b/lib/compress/fse_compress.c
index 158ba80ca..1ce3cf16a 100644
--- a/lib/compress/fse_compress.c
+++ b/lib/compress/fse_compress.c
@@ -25,7 +25,7 @@
 #include "../common/error_private.h"
 #define ZSTD_DEPS_NEED_MALLOC
 #define ZSTD_DEPS_NEED_MATH64
-#include "../common/zstd_deps.h"  /* ZSTD_malloc, ZSTD_free, ZSTD_memcpy, ZSTD_memset */
+#include "../common/zstd_deps.h"  /* ZSTD_memset */
 #include "../common/bits.h" /* ZSTD_highbit32 */
 
 
diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c
index e7fcfd209..44f9029ac 100644
--- a/lib/dictBuilder/cover.c
+++ b/lib/dictBuilder/cover.c
@@ -31,8 +31,8 @@
 #endif
 
 #include "../common/mem.h" /* read */
-#include "../common/pool.h"
-#include "../common/threading.h"
+#include "../common/pool.h" /* POOL_ctx */
+#include "../common/threading.h" /* ZSTD_pthread_mutex_t */
 #include "../common/zstd_internal.h" /* includes zstd.h */
 #include "../common/bits.h" /* ZSTD_highbit32 */
 #include "../zdict.h"
@@ -78,7 +78,7 @@ static clock_t g_time = 0;
 #undef  LOCALDISPLAYUPDATE
 #define LOCALDISPLAYUPDATE(displayLevel, l, ...)                               \
   if (displayLevel >= l) {                                                     \
-    if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) {             \
+    if ((clock() - g_time > g_refreshRate) || (displayLevel >= 4)) {           \
       g_time = clock();                                                        \
       DISPLAY(__VA_ARGS__);                                                    \
     }                                                                          \
@@ -301,9 +301,10 @@ static int WIN_CDECL COVER_strict_cmp8(const void *lp, const void *rp) {
  * Returns the first pointer in [first, last) whose element does not compare
  * less than value.  If no such element exists it returns last.
  */
-static const size_t *COVER_lower_bound(const size_t *first, const size_t *last,
+static const size_t *COVER_lower_bound(const size_t* first, const size_t* last,
                                        size_t value) {
-  size_t count = last - first;
+  size_t count = (size_t)(last - first);
+  assert(last >= first);
   while (count != 0) {
     size_t step = count / 2;
     const size_t *ptr = first;
@@ -549,7 +550,8 @@ 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)
+{
   const BYTE *const samples = (const BYTE *)samplesBuffer;
   const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
   /* Split samples into testing and training sets */
@@ -907,8 +909,10 @@ void COVER_best_start(COVER_best_t *best) {
  * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
  * If this dictionary is the best so far save it and its parameters.
  */
-void COVER_best_finish(COVER_best_t *best, ZDICT_cover_params_t parameters,
-                              COVER_dictSelection_t selection) {
+void COVER_best_finish(COVER_best_t* best,
+                      ZDICT_cover_params_t parameters,
+                      COVER_dictSelection_t selection)
+{
   void* dict = selection.dictContent;
   size_t compressedSize = selection.totalCompressedSize;
   size_t dictSize = selection.dictSize;
@@ -980,8 +984,8 @@ COVER_dictSelection_t COVER_selectDict(BYTE* customDictContent, size_t dictBuffe
   size_t largestCompressed = 0;
   BYTE* customDictContentEnd = customDictContent + dictContentSize;
 
-  BYTE * largestDictbuffer = (BYTE *)malloc(dictBufferCapacity);
-  BYTE * candidateDictBuffer = (BYTE *)malloc(dictBufferCapacity);
+  BYTE* largestDictbuffer = (BYTE*)malloc(dictBufferCapacity);
+  BYTE* candidateDictBuffer = (BYTE*)malloc(dictBufferCapacity);
   double regressionTolerance = ((double)params.shrinkDictMaxRegression / 100.0) + 1.00;
 
   if (!largestDictbuffer || !candidateDictBuffer) {
diff --git a/lib/dictBuilder/cover.h b/lib/dictBuilder/cover.h
index 252624bde..a5d7506ef 100644
--- a/lib/dictBuilder/cover.h
+++ b/lib/dictBuilder/cover.h
@@ -12,14 +12,8 @@
 #  define ZDICT_STATIC_LINKING_ONLY
 #endif
 
-#include   /* fprintf */
-#include  /* malloc, free, qsort */
-#include  /* memset */
-#include    /* clock */
-#include "../common/mem.h" /* read */
-#include "../common/pool.h"
-#include "../common/threading.h"
-#include "../common/zstd_internal.h" /* includes zstd.h */
+#include "../common/threading.h" /* ZSTD_pthread_mutex_t */
+#include "../common/mem.h"   /* U32, BYTE */
 #include "../zdict.h"
 
 /**

From ff0afbad58611d22b8b4477e9383b9b9ffdbaee6 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Wed, 13 Mar 2024 09:58:34 -0700
Subject: [PATCH 258/937] [asm][aarch64] Mark that BTI and PAC are supported

Mark that `huf_decompress_amd64.S` supports BTI and PAC, which it trivially does because it is empty for aarch64.

The issue only requested BTI markings, but it also makes sense to mark PAC, which is the only other feature.

Also run add a test for this mode to the ARM64 QEMU test. Before this PR it warns on `huf_decompress_amd64.S`, after it doesn't.

Fixes Issue #3841.
---
 .github/workflows/dev-short-tests.yml |  1 +
 lib/decompress/huf_decompress_amd64.S | 23 ++++++++++++++++++++++-
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index b2aaff89c..5324b38d9 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -409,6 +409,7 @@ jobs:
     - name: ARM64
       if: ${{ matrix.name == 'ARM64' }}
       run: |
+        LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make clean check
         LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check
     - name: PPC
       if: ${{ matrix.name == 'PPC' }}
diff --git a/lib/decompress/huf_decompress_amd64.S b/lib/decompress/huf_decompress_amd64.S
index 3b96b4461..78da291ee 100644
--- a/lib/decompress/huf_decompress_amd64.S
+++ b/lib/decompress/huf_decompress_amd64.S
@@ -10,11 +10,32 @@
 
 #include "../common/portability_macros.h"
 
+#if defined(__ELF__) && defined(__GNUC__)
 /* Stack marking
  * ref: https://wiki.gentoo.org/wiki/Hardened/GNU_stack_quickstart
  */
-#if defined(__ELF__) && defined(__GNUC__)
 .section .note.GNU-stack,"",%progbits
+
+#if defined(__aarch64__)
+/* Mark that this assembly supports BTI & PAC, because it is empty for aarch64.
+ * See: https://github.com/facebook/zstd/issues/3841
+ * See: https://gcc.godbolt.org/z/sqr5T4ffK
+ * See: https://lore.kernel.org/linux-arm-kernel/20200429211641.9279-8-broonie@kernel.org/
+ * See: https://reviews.llvm.org/D62609
+ */
+.pushsection .note.gnu.property, "a"
+.p2align 3
+.long 4                 /* size of the name - "GNU\0" */
+.long 0x10              /* size of descriptor */
+.long 0x5               /* NT_GNU_PROPERTY_TYPE_0 */
+.asciz "GNU"
+.long 0xc0000000        /* pr_type - GNU_PROPERTY_AARCH64_FEATURE_1_AND */
+.long 4                 /* pr_datasz - 4 bytes */
+.long 3                 /* pr_data - GNU_PROPERTY_AARCH64_FEATURE_1_BTI | GNU_PROPERTY_AARCH64_FEATURE_1_PAC */
+.p2align 3              /* pr_padding - bring everything to 8 byte alignment */
+.popsection
+#endif
+
 #endif
 
 #if ZSTD_ENABLE_ASM_X86_64_BMI2

From d6ee2d5d2454f5023c78d59e7464c9c902d6597b Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Tue, 12 Mar 2024 14:01:17 -0700
Subject: [PATCH 259/937] Use `utimensat()` on FreeBSD

FreeBSD only claims to support POSIX 2001 [0]. But they do in fact support
`utimensat()`. This adds a specific check to opt them in to using it. This
value was selected by consulting [1].

See discussion on #3952.

Further addresses #3748.

[0] https://github.com/freebsd/freebsd-src/blob/937a0055858a098027f464abf0b2b1ec5d36748f/sys/sys/unistd.h#L96

[1] https://docs.freebsd.org/en/books/porters-handbook/versions/
---
 programs/util.c | 25 ++++++++++++++++++++-----
 1 file changed, 20 insertions(+), 5 deletions(-)

diff --git a/programs/util.c b/programs/util.c
index 862fc8008..116f88e10 100644
--- a/programs/util.c
+++ b/programs/util.c
@@ -23,16 +23,27 @@ extern "C" {
 #include 
 #include 
 
+#if defined(__FreeBSD__)
+#include  /* __FreeBSD_version */
+#endif /* #ifdef __FreeBSD__ */
+
 #if defined(_WIN32)
 #  include   /* utime */
 #  include          /* _chmod */
+#  define ZSTD_USE_UTIMENSAT 0
 #else
 #  include      /* chown, stat */
-#  if PLATFORM_POSIX_VERSION < 200809L || !defined(st_mtime)
-#    include     /* utime */
+#  include    /* utimensat, st_mtime */
+#  if (PLATFORM_POSIX_VERSION >= 200809L && defined(st_mtime)) \
+      || (defined(__FreeBSD__) && __FreeBSD_version >= 1100056)
+#    define ZSTD_USE_UTIMENSAT 1
 #  else
+#    define ZSTD_USE_UTIMENSAT 0
+#  endif
+#  if ZSTD_USE_UTIMENSAT
 #    include     /* AT_FDCWD */
-#    include  /* utimensat */
+#  else
+#    include     /* utime */
 #  endif
 #endif
 
@@ -259,7 +270,12 @@ int UTIL_utime(const char* filename, const stat_t *statbuf)
      * that struct stat has a struct timespec st_mtim member. We need this
      * check because there are some platforms that claim to be POSIX 2008
      * compliant but which do not have st_mtim... */
-#if (PLATFORM_POSIX_VERSION >= 200809L) && defined(st_mtime)
+    /* FreeBSD has implemented POSIX 2008 for a long time but still only
+     * advertises support for POSIX 2001. They have a version macro that
+     * lets us safely gate them in.
+     * See https://docs.freebsd.org/en/books/porters-handbook/versions/.
+     */
+#if ZSTD_USE_UTIMENSAT
     {
         /* (atime, mtime) */
         struct timespec timebuf[2] = { {0, UTIME_NOW} };
@@ -1546,7 +1562,6 @@ failed:
 
 #elif defined(__FreeBSD__)
 
-#include 
 #include 
 
 /* Use physical core sysctl when available

From 2215101cad9d809e345e2e939fa1e125563d25cf Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Wed, 13 Mar 2024 16:32:04 -0400
Subject: [PATCH 260/937] Add a Few Tests

---
 .../file-handling/directory-mirror.sh         | 49 +++++++++++++++++++
 .../directory-mirror.sh.stderr.exact          |  0
 .../directory-mirror.sh.stdout.exact          |  0
 3 files changed, 49 insertions(+)
 create mode 100755 tests/cli-tests/file-handling/directory-mirror.sh
 create mode 100644 tests/cli-tests/file-handling/directory-mirror.sh.stderr.exact
 create mode 100644 tests/cli-tests/file-handling/directory-mirror.sh.stdout.exact

diff --git a/tests/cli-tests/file-handling/directory-mirror.sh b/tests/cli-tests/file-handling/directory-mirror.sh
new file mode 100755
index 000000000..b2f70b591
--- /dev/null
+++ b/tests/cli-tests/file-handling/directory-mirror.sh
@@ -0,0 +1,49 @@
+#!/bin/sh
+set -e
+
+# setup
+mkdir -p src/.hidden src/dir
+mkdir mid dst
+
+echo "file1" > src/file1
+echo "file2" > src/.file2
+echo "file3" > src/.hidden/.file3
+echo "file4" > src/dir/.file4
+
+# relative paths
+zstd -q -r --output-dir-mirror mid/ src/
+zstd -q -d -r --output-dir-mirror dst/ mid/src/
+
+diff --brief --recursive --new-file src/ dst/mid/src/
+
+# reset
+rm -rf mid dst
+mkdir mid dst
+
+# from inside the directory
+(cd src; zstd -q -r --output-dir-mirror ../mid/ ./)
+(cd mid; zstd -q -d -r --output-dir-mirror ../dst/ ./)
+
+diff --brief --recursive --new-file src/ dst/
+
+# reset
+rm -rf mid dst
+mkdir mid dst
+
+# absolute paths
+export BASE_PATH="$(pwd)"
+
+zstd -q -r --output-dir-mirror mid/ "${BASE_PATH}/src/"
+zstd -q -d -r --output-dir-mirror  dst/ "${BASE_PATH}/mid/${BASE_PATH}/src/"
+
+diff --brief --recursive --new-file src/ "dst/${BASE_PATH}/mid/${BASE_PATH}/src/"
+
+# reset
+rm -rf mid dst
+mkdir mid dst
+
+# dots
+zstd -q -r --output-dir-mirror mid/ ./src/./
+zstd -q -d -r --output-dir-mirror  dst/ ./mid/./src/./
+
+diff --brief --recursive --new-file src/ dst/mid/src/
diff --git a/tests/cli-tests/file-handling/directory-mirror.sh.stderr.exact b/tests/cli-tests/file-handling/directory-mirror.sh.stderr.exact
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/cli-tests/file-handling/directory-mirror.sh.stdout.exact b/tests/cli-tests/file-handling/directory-mirror.sh.stdout.exact
new file mode 100644
index 000000000..e69de29bb

From 86b8e39a84d15ebcae3fa4b36240db27f2ae74ac Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Wed, 13 Mar 2024 16:33:30 -0400
Subject: [PATCH 261/937] Remove Erroneous Exclusion of Hidden Files and
 Folders in `--output-dir-mirror`

---
 programs/util.c | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/programs/util.c b/programs/util.c
index 862fc8008..d6f33d4a8 100644
--- a/programs/util.c
+++ b/programs/util.c
@@ -1119,9 +1119,6 @@ static char* mallocAndJoin2Dir(const char *dir1, const char *dir2)
         memcpy(outDirBuffer, dir1, dir1Size);
         outDirBuffer[dir1Size] = '\0';
 
-        if (dir2[0] == '.')
-            return outDirBuffer;
-
         buffer = outDirBuffer + dir1Size;
         if (dir1Size > 0 && *(buffer - 1) != PATH_SEP) {
             *buffer = PATH_SEP;

From 3613448fb8623361dc6bd9b32c8d4b3d2da85823 Mon Sep 17 00:00:00 2001
From: "W. Felix Handte" 
Date: Wed, 13 Mar 2024 16:56:54 -0400
Subject: [PATCH 262/937] Promote `ZSTD_c_targetCBlockSize` Parameter to Stable
 API

This feature has demonstrated itself to be useful in web compression and we
want to encourage other folks to use it. But we currently make it difficult
to do so since it's locked away in the experimental API.

The API itself is really straightforward and I think it's fine to commit to
maintaining support / compatibility for this API even if in the future the
underlying implementation may continue to evolve.

Note that this commit changes its enum name and also its numeric value. Users
who respected the instructions of using the experimental API should be fine
with both of these changes since they should only have referred to it by the.

Conceivably someone could have done bad feature detection of this capability
by doing `#ifdef ZSTD_c_targetCBlockSize` which will now return false since
it's no longer a macro... but I think that's an acceptable hypothetical
breakage.
---
 lib/zstd.h | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/lib/zstd.h b/lib/zstd.h
index 841269305..d2621c5c9 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -390,6 +390,16 @@ typedef enum {
                               * The higher the value of selected strategy, the more complex it is,
                               * resulting in stronger and slower compression.
                               * Special: value 0 means "use default strategy". */
+    ZSTD_c_targetCBlockSize=130, /* Tries to fit compressed block size to be
+                                  * around targetCBlockSize. No target when
+                                  * targetCBlockSize == 0. There is no guarantee
+                                  * on compressed block size (default:0).
+                                  * Since the decoder has to buffer a complete
+                                  * block to begin decoding it, in low band-
+                                  * width streaming environments this may
+                                  * improve end-to-end latency. Bound by
+                                  * ZSTD_TARGETCBLOCKSIZE_MIN and
+                                  * ZSTD_TARGETCBLOCKSIZE_MAX. */
     /* LDM mode parameters */
     ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
                                      * This parameter is designed to improve compression ratio
@@ -469,7 +479,6 @@ typedef enum {
      * ZSTD_c_forceMaxWindow
      * ZSTD_c_forceAttachDict
      * ZSTD_c_literalCompressionMode
-     * ZSTD_c_targetCBlockSize
      * ZSTD_c_srcSizeHint
      * ZSTD_c_enableDedicatedDictSearch
      * ZSTD_c_stableInBuffer
@@ -490,7 +499,7 @@ typedef enum {
      ZSTD_c_experimentalParam3=1000,
      ZSTD_c_experimentalParam4=1001,
      ZSTD_c_experimentalParam5=1002,
-     ZSTD_c_experimentalParam6=1003,
+     /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */
      ZSTD_c_experimentalParam7=1004,
      ZSTD_c_experimentalParam8=1005,
      ZSTD_c_experimentalParam9=1006,
@@ -1951,11 +1960,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo
  */
 #define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5
 
-/* Tries to fit compressed block size to be around targetCBlockSize.
- * No target when targetCBlockSize == 0.
- * There is no guarantee on compressed block size (default:0) */
-#define ZSTD_c_targetCBlockSize ZSTD_c_experimentalParam6
-
 /* User's best guess of source size.
  * Hint is not valid when srcSizeHint == 0.
  * There is no guarantee that hint is close to actual source size,

From a0a9bc6c95436c85002ffca972ae545f862e1638 Mon Sep 17 00:00:00 2001
From: Nick Terrell 
Date: Thu, 14 Mar 2024 08:47:04 -0700
Subject: [PATCH 263/937] [cmake] Always create libzstd target

If both `ZSTD_BUILD_SHARED` and `ZSTD_BUILD_STATIC` are set, then cmake exports the libraries `libzstd_shared` and `libzstd_static` only.
It does not export `libzstd`, which is only exported when exactly one of `ZSTD_BUILD_SHARED` and `ZSTD_BUILD_STATIC` is set.
This PR exports `libzstd` in that case, based on the value of the standard CMake variable [`BUILD_SHARED_LIBS`](https://cmake.org/cmake/help/latest/variable/BUILD_SHARED_LIBS.html).
This ensures that `libzstd` can always be used to refer to the exported zstd library, since the build errors if neither `ZSTD_BUILD_SHARED` nor `ZSTD_BUILD_STATIC` are set.

I tested all the possible combinations of `ZSTD_BUILD_SHARED`, `ZSTD_BUILD_STATIC`, and `BUILD_SHARED_LIBS` and they always worked as expected:
* If only exactly one of `ZSTD_BUILD_SHARED` and `ZSTD_BUILD_STATIC` is set, that is used as `libzstd`.
* Otherwise, libzstd is set based on `BUILD_SHARED_LIBS`.

Fixes #3859.
---
 build/cmake/lib/CMakeLists.txt | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt
index f5820af57..53df541ff 100644
--- a/build/cmake/lib/CMakeLists.txt
+++ b/build/cmake/lib/CMakeLists.txt
@@ -159,6 +159,20 @@ if (ZSTD_BUILD_STATIC AND NOT ZSTD_BUILD_SHARED)
     target_link_libraries(libzstd INTERFACE libzstd_static)
     list(APPEND library_targets libzstd)
 endif ()
+if (ZSTD_BUILD_SHARED AND ZSTD_BUILD_STATIC)
+    # If both ZSTD_BUILD_SHARED and ZSTD_BUILD_STATIC are set, which is the
+    # default, fallback to using BUILD_SHARED_LIBS to determine whether to
+    # set libzstd to static or shared.
+    if (BUILD_SHARED_LIBS)
+        add_library(libzstd INTERFACE)
+        target_link_libraries(libzstd INTERFACE libzstd_shared)
+        list(APPEND library_targets libzstd)
+    else ()
+        add_library(libzstd INTERFACE)
+        target_link_libraries(libzstd INTERFACE libzstd_static)
+        list(APPEND library_targets libzstd)
+    endif ()
+endif ()
 
 # Add specific compile definitions for MSVC project
 if (MSVC)

From 9cc3304614f9ea28a870f9e94e1e449c6d7de1fc Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 14 Mar 2024 12:11:11 -0700
Subject: [PATCH 264/937] add line number to debug traces

---
 lib/common/debug.h | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/lib/common/debug.h b/lib/common/debug.h
index 8049e4b5d..a16b69e57 100644
--- a/lib/common/debug.h
+++ b/lib/common/debug.h
@@ -92,10 +92,14 @@ extern int g_debuglevel; /* the variable is only declared,
         }                                  \
     } while (0)
 
+#define STRINGIFY(x) #x
+#define TOSTRING(x) STRINGIFY(x)
+#define LINE_AS_STRING TOSTRING(__LINE__)
+
 #  define DEBUGLOG(l, ...)                               \
     do {                                                 \
         if (l<=g_debuglevel) {                           \
-            ZSTD_DEBUG_PRINT(__FILE__ ": " __VA_ARGS__); \
+            ZSTD_DEBUG_PRINT(__FILE__ ":" LINE_AS_STRING ": " __VA_ARGS__); \
             ZSTD_DEBUG_PRINT(" \n");                     \
         }                                                \
     } while (0)

From 559762da12f54712d44f619098aa4a7e7bc5727b Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Thu, 14 Mar 2024 15:55:01 -0400
Subject: [PATCH 265/937] Remove duplicate and incorrect docs in
 zstd_decompress.c (#3967)

---
 lib/decompress/zstd_decompress.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c
index 42636d578..f65797438 100644
--- a/lib/decompress/zstd_decompress.c
+++ b/lib/decompress/zstd_decompress.c
@@ -797,10 +797,8 @@ static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize
 }
 
 /** ZSTD_findFrameCompressedSize() :
- *  compatible with legacy mode
- *  `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
- *  `srcSize` must be at least as large as the frame contained
- *  @return : the compressed size of the frame starting at `src` */
+ * See docs in zstd.h
+ * Note: compatible with legacy mode */
 size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
 {
     ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize);

From 686e7e4b4b3821df4de0e7dd4722049ee2c5fb88 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 14 Mar 2024 15:38:14 -0700
Subject: [PATCH 266/937] updated version to v1.5.6

---
 doc/zstd_manual.html |  4 ++--
 lib/zstd.h           |  2 +-
 programs/zstd.1      |  2 +-
 programs/zstdgrep.1  | 13 +++++++++++--
 programs/zstdless.1  |  9 +++++++--
 5 files changed, 22 insertions(+), 8 deletions(-)

diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index c81627d87..58fe958dc 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -1,10 +1,10 @@
 
 
 
-zstd 1.5.5 Manual
+zstd 1.5.6 Manual
 
 
-

zstd 1.5.5 Manual

+

zstd 1.5.6 Manual


Contents

    diff --git a/lib/zstd.h b/lib/zstd.h index 841269305..79432eb88 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -106,7 +106,7 @@ extern "C" { /*------ Version ------*/ #define ZSTD_VERSION_MAJOR 1 #define ZSTD_VERSION_MINOR 5 -#define ZSTD_VERSION_RELEASE 5 +#define ZSTD_VERSION_RELEASE 6 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) /*! ZSTD_versionNumber() : diff --git a/programs/zstd.1 b/programs/zstd.1 index f7af55270..2b5a98511 100644 --- a/programs/zstd.1 +++ b/programs/zstd.1 @@ -1,5 +1,5 @@ . -.TH "ZSTD" "1" "March 2024" "zstd 1.5.5" "User Commands" +.TH "ZSTD" "1" "March 2024" "zstd 1.5.6" "User Commands" . .SH "NAME" \fBzstd\fR \- zstd, zstdmt, unzstd, zstdcat \- Compress or decompress \.zst files diff --git a/programs/zstdgrep.1 b/programs/zstdgrep.1 index 1204e5bb6..d7fda5833 100644 --- a/programs/zstdgrep.1 +++ b/programs/zstdgrep.1 @@ -1,17 +1,26 @@ -.TH "ZSTDGREP" "1" "March 2023" "zstd 1.5.5" "User Commands" +. +.TH "ZSTDGREP" "1" "March 2024" "zstd 1.5.6" "User Commands" +. .SH "NAME" \fBzstdgrep\fR \- print lines matching a pattern in zstandard\-compressed files +. .SH "SYNOPSIS" -\fBzstdgrep\fR [\fIgrep\-flags\fR] [\-\-] \fIpattern\fR [\fIfiles\fR \|\.\|\.\|\.] +\fBzstdgrep\fR [\fIgrep\-flags\fR] [\-\-] \fIpattern\fR [\fIfiles\fR \.\.\.] +. .SH "DESCRIPTION" \fBzstdgrep\fR runs \fBgrep\fR(1) on files, or \fBstdin\fR if no files argument is given, after decompressing them with \fBzstdcat\fR(1)\. +. .P The \fIgrep\-flags\fR and \fIpattern\fR arguments are passed on to \fBgrep\fR(1)\. If an \fB\-e\fR flag is found in the \fIgrep\-flags\fR, \fBzstdgrep\fR will not look for a \fIpattern\fR argument\. +. .P Note that modern \fBgrep\fR alternatives such as \fBripgrep\fR (\fBrg\fR(1)) support \fBzstd\fR\-compressed files out of the box, and can prove better alternatives than \fBzstdgrep\fR notably for unsupported complex pattern searches\. Note though that such alternatives may also feature some minor command line differences\. +. .SH "EXIT STATUS" In case of missing arguments or missing pattern, 1 will be returned, otherwise 0\. +. .SH "SEE ALSO" \fBzstd\fR(1) +. .SH "AUTHORS" Thomas Klausner \fIwiz@NetBSD\.org\fR diff --git a/programs/zstdless.1 b/programs/zstdless.1 index bc019b263..7dd65f8fc 100644 --- a/programs/zstdless.1 +++ b/programs/zstdless.1 @@ -1,9 +1,14 @@ -.TH "ZSTDLESS" "1" "March 2023" "zstd 1.5.5" "User Commands" +. +.TH "ZSTDLESS" "1" "March 2024" "zstd 1.5.6" "User Commands" +. .SH "NAME" \fBzstdless\fR \- view zstandard\-compressed files +. .SH "SYNOPSIS" -\fBzstdless\fR [\fIflags\fR] [\fIfile\fR \|\.\|\.\|\.] +\fBzstdless\fR [\fIflags\fR] [\fIfile\fR \.\.\.] +. .SH "DESCRIPTION" \fBzstdless\fR runs \fBless\fR(1) on files or stdin, if no \fIfile\fR argument is given, after decompressing them with \fBzstdcat\fR(1)\. +. .SH "SEE ALSO" \fBzstd\fR(1) From 351498b9320e9c03cbe4ed722e8967a5673f46a0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 14 Mar 2024 17:01:34 -0700 Subject: [PATCH 267/937] update CHANGELOG for v1.5.6 --- CHANGELOG | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index c7a7506ee..23c012820 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,38 @@ +V1.5.6 (Mar 2024) +api: Promote `ZSTD_c_targetCBlockSize` to Stable API by @felixhandte +api: new `ZSTD_d_maxBlockSize` experimental parameter, to reduce streaming decompression memory, by @terrelln +perf: improve performance of param `ZSTD_c_targetCBlockSize`, by @Cyan4973 +perf: improved compression of arrays of integers at high compression, by @Cyan4973 +lib: reduce binary size with selective built-time exclusion, by @felixhandte +lib: improved huffman speed on small data and linux kernel, by @terrelln +lib: accept dictionaries with partial literal tables, by @terrelln +lib: fix CCtx size estimation with external sequence producer, by @embg +lib: fix corner case decoder behaviors, by @Cyan4973 and @aimuz +lib: fix zdict prototype mismatch in static_only mode, by @ldv-alt +cli: add common compressed file types to `--exclude-compressed`` by @daniellerozenblit +cli: fix mixing `-c` and `-o` commands with `--rm`, by @Cyan4973 +cli: fix erroneous exclusion of hidden files with `--output-dir-mirror` by @felixhandte +cli: improved time accuracy on BSD, by @felixhandte +cli: better errors on argument parsing, by @KapJI +tests: better compatibility with older versions of `grep`, by @Cyan4973 +tests: lorem ipsum generator as default backup content, by @Cyan4973 +build: cmake improvements by @terrelln, @sighingnow, @gjasny, @JohanMabille, @Saverio976, @gruenich, @teo-tsirpanis +build: bazel support, by @jondo2010 +build: fix cross-compiling for AArch64 with lld by @jcelerier +build: fix Apple platform compatibility, by @nidhijaju +build: fix Visual 2012 and lower compatibility, by @Cyan4973 +build: improve win32 support, by @DimitriPapadopoulos +build: better C90 compliance for zlibWrapper, by @emaste +port: make: fat binaries on macos, by @mredig +port: ARM64EC compatibility for Windows, by @dunhor +port: QNX support by @klausholstjacobsen +port: MSYS2 and Cygwin makefile installation and test support, by @QBos07 +port: risc-v support validation in CI, by @Cyan4973 +port: sparc64 support validation in CI, by @Cyan4973 +port: AIX compatibility, by @likema +port: HP-UX compatibility, by @likema +doc: Improved specification accuracy, by @elasota + v1.5.5 (Apr 2023) fix: fix rare corruption bug affecting the high compression mode, reported by @danlark1 (#3517, @terrelln) perf: improve mid-level compression speed (#3529, #3533, #3543, @yoniko and #3552, @terrelln) @@ -98,7 +133,7 @@ build: support for m68k (Motorola 68000's), by @cyan4973 build: improved AIX support, by @Helflym build: improved meson unofficial build, by @eli-schwartz cli : custom memory limit when training dictionary (#2925), by @embg -cli : report advanced parameters information when compressing in very verbose mode (``-vv`), by @Svetlitski-FB +cli : report advanced parameters information when compressing in very verbose mode (`-vv`), by @Svetlitski-FB v1.5.0 (May 11, 2021) api: Various functions promoted from experimental to stable API: (#2579-2581, @senhuang42) @@ -165,7 +200,7 @@ api: Add Function to Generate Skippable Frame (#2439, @senhuang42) perf: New Algorithms for the Long Distance Matcher (#2483, @mpu) perf: Performance Improvements for Long Distance Matcher (#2464, @mpu) perf: Don't Shrink Window Log when Streaming with a Dictionary (#2451, @terrelln) -cli: Fix `--output-dir-mirror`'s Rejection of `..`-Containing Paths (#2512, @felixhandte) +cli: Fix `--output-dir-mirror` rejection of `..` -containing paths (#2512, @felixhandte) cli: Allow Input From Console When `-f`/`--force` is Passed (#2466, @felixhandte) cli: Improve Help Message (#2500, @senhuang42) tests: Remove Flaky Tests (#2455, #2486, #2445, @Cyan4973) From 88301b58c1b2f84e55f27fd7259db4f8afdafc22 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Mar 2024 05:37:52 +0000 Subject: [PATCH 268/937] Bump actions/cache from 3 to 4 Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/cache dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- .github/workflows/nightly.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 83a6412b9..5fc8cb1fd 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -59,7 +59,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: restore_cache - uses: actions/cache@v3 + uses: actions/cache@v4 with: key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 path: tests/regression/cache diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 0eb9ecbde..9206a07fd 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -18,7 +18,7 @@ jobs: CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - uses: actions/checkout@v4 - - uses: actions/cache@v3 + - uses: actions/cache@v4 with: key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 path: tests/regression/cache From 9dca0602f45e925c919ac130c9c9f37d88d4ab98 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Mar 2024 05:37:56 +0000 Subject: [PATCH 269/937] Bump github/codeql-action from 3.24.6 to 3.24.7 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.6 to 3.24.7. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/8a470fddafa5cbb6266ee11b37ef4d8aae19c571...3ab4101902695724f9365a384f86c1074d94e18c) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 513320271..a5d5f02a3 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # tag=v3.24.6 + uses: github/codeql-action/upload-sarif@3ab4101902695724f9365a384f86c1074d94e18c # tag=v3.24.7 with: sarif_file: results.sarif From 79cd0ff7120ed05ac9e52ba4c7a484752be4d758 Mon Sep 17 00:00:00 2001 From: dsvi <23555438+dsvi@users.noreply.github.com> Date: Sat, 5 Aug 2023 01:47:46 +0300 Subject: [PATCH 270/937] Makes it possible to use the lib through FetchContent or ExternalProject_Add --- build/cmake/lib/CMakeLists.txt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 53df541ff..365859690 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -33,9 +33,6 @@ if(NOT ZSTD_BUILD_SHARED AND NOT ZSTD_BUILD_STATIC) message(SEND_ERROR "You need to build at least one flavor of libzstd") endif() -# Define library directory, where sources and header files are located -include_directories(${LIBRARY_DIR} ${LIBRARY_DIR}/common) - file(GLOB CommonSources ${LIBRARY_DIR}/common/*.c) file(GLOB CompressSources ${LIBRARY_DIR}/compress/*.c) file(GLOB DecompressSources ${LIBRARY_DIR}/decompress/*.c) @@ -119,10 +116,14 @@ macro (add_definition target var) endif () endmacro () +# Define include directories, where header files are located +set(LIBRARY_INCLUDES "${LIBRARY_DIR} ${LIBRARY_DIR}/common") + # Split project to static and shared libraries build set(library_targets) if (ZSTD_BUILD_SHARED) add_library(libzstd_shared SHARED ${Sources} ${Headers} ${PlatformDependResources}) + target_include_directories(libzstd_shared PUBLIC $) list(APPEND library_targets libzstd_shared) if (ZSTD_MULTITHREAD_SUPPORT) set_property(TARGET libzstd_shared APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") @@ -136,6 +137,7 @@ if (ZSTD_BUILD_SHARED) endif () if (ZSTD_BUILD_STATIC) add_library(libzstd_static STATIC ${Sources} ${Headers}) + target_include_directories(libzstd_static PUBLIC $) list(APPEND library_targets libzstd_static) if (ZSTD_MULTITHREAD_SUPPORT) set_property(TARGET libzstd_static APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") From a595e5812a5c7e4ac47839383f931fb8000623f0 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 14 Mar 2024 12:12:55 -0700 Subject: [PATCH 271/937] [cmake] Fix up PR #3716 * Make a variable `PublicHeaders` for Zstd's public headers * Add `PublicHeaders` to `Headers`, which was missing * Only export `${LIBRARY_DIR}` publicly, not `common/` * Switch the `target_include_directories()` to `INTERFACE` because zstd uses relative includes internally, so doesn't need any include directories to build * Switch installation to use the `PublicHeaders` variable, and test that the right headers are installed --- build/cmake/lib/CMakeLists.txt | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 365859690..eb21b8b32 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -48,6 +48,7 @@ endif () file(GLOB DictBuilderSources ${LIBRARY_DIR}/dictBuilder/*.c) file(GLOB DeprecatedSources ${LIBRARY_DIR}/deprecated/*.c) +file(GLOB PublicHeaders ${LIBRARY_DIR}/*.h) file(GLOB CommonHeaders ${LIBRARY_DIR}/common/*.h) file(GLOB CompressHeaders ${LIBRARY_DIR}/compress/*.h) file(GLOB DecompressHeaders ${LIBRARY_DIR}/decompress/*.h) @@ -55,7 +56,7 @@ file(GLOB DictBuilderHeaders ${LIBRARY_DIR}/dictBuilder/*.h) file(GLOB DeprecatedHeaders ${LIBRARY_DIR}/deprecated/*.h) set(Sources ${CommonSources}) -set(Headers ${LIBRARY_DIR}/zstd.h ${CommonHeaders}) +set(Headers ${PublicHeaders} ${CommonHeaders}) if (ZSTD_BUILD_COMPRESSION) set(Sources ${Sources} ${CompressSources}) set(Headers ${Headers} ${CompressHeaders}) @@ -75,7 +76,6 @@ endif() if (ZSTD_LEGACY_SUPPORT) set(LIBRARY_LEGACY_DIR ${LIBRARY_DIR}/legacy) - include_directories(${LIBRARY_LEGACY_DIR}) set(Sources ${Sources} ${LIBRARY_LEGACY_DIR}/zstd_v01.c @@ -116,14 +116,14 @@ macro (add_definition target var) endif () endmacro () -# Define include directories, where header files are located -set(LIBRARY_INCLUDES "${LIBRARY_DIR} ${LIBRARY_DIR}/common") +# Define directories containing the library's public headers +set(PUBLIC_INCLUDE_DIRS ${LIBRARY_DIR}) # Split project to static and shared libraries build set(library_targets) if (ZSTD_BUILD_SHARED) add_library(libzstd_shared SHARED ${Sources} ${Headers} ${PlatformDependResources}) - target_include_directories(libzstd_shared PUBLIC $) + target_include_directories(libzstd_shared INTERFACE $) list(APPEND library_targets libzstd_shared) if (ZSTD_MULTITHREAD_SUPPORT) set_property(TARGET libzstd_shared APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") @@ -137,7 +137,7 @@ if (ZSTD_BUILD_SHARED) endif () if (ZSTD_BUILD_STATIC) add_library(libzstd_static STATIC ${Sources} ${Headers}) - target_include_directories(libzstd_static PUBLIC $) + target_include_directories(libzstd_static INTERFACE $) list(APPEND library_targets libzstd_static) if (ZSTD_MULTITHREAD_SUPPORT) set_property(TARGET libzstd_static APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") @@ -224,11 +224,7 @@ configure_file("${LIBRARY_DIR}/libzstd.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/libzs install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libzstd.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") # install target -install(FILES - "${LIBRARY_DIR}/zstd.h" - "${LIBRARY_DIR}/zdict.h" - "${LIBRARY_DIR}/zstd_errors.h" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") +install(FILES ${PublicHeaders} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install(TARGETS ${library_targets} EXPORT zstdExports From 7d970bd83c2323c5e78b4f15ae850373c70f055d Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Mon, 18 Mar 2024 10:55:53 -0400 Subject: [PATCH 272/937] Implement one-shot fallback for magicless format (#3971) --- lib/decompress/zstd_decompress.c | 22 ++++++++++++-------- tests/zstreamtest.c | 35 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index f65797438..ee2cda3b6 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -729,17 +729,17 @@ static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) return frameSizeInfo; } -static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize) +static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize, ZSTD_format_e format) { ZSTD_frameSizeInfo frameSizeInfo; ZSTD_memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo)); #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) - if (ZSTD_isLegacy(src, srcSize)) + if (format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) return ZSTD_findFrameSizeInfoLegacy(src, srcSize); #endif - if ((srcSize >= ZSTD_SKIPPABLEHEADERSIZE) + if (format == ZSTD_f_zstd1 && (srcSize >= ZSTD_SKIPPABLEHEADERSIZE) && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize); assert(ZSTD_isError(frameSizeInfo.compressedSize) || @@ -753,7 +753,7 @@ static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize ZSTD_frameHeader zfh; /* Extract Frame Header */ - { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize); + { size_t const ret = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, format); if (ZSTD_isError(ret)) return ZSTD_errorFrameSizeInfo(ret); if (ret > 0) @@ -796,13 +796,17 @@ static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize } } +static size_t ZSTD_findFrameCompressedSize_advanced(const void *src, size_t srcSize, ZSTD_format_e format) { + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, format); + return frameSizeInfo.compressedSize; +} + /** ZSTD_findFrameCompressedSize() : * See docs in zstd.h * Note: compatible with legacy mode */ size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) { - ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); - return frameSizeInfo.compressedSize; + return ZSTD_findFrameCompressedSize_advanced(src, srcSize, ZSTD_f_zstd1); } /** ZSTD_decompressBound() : @@ -816,7 +820,7 @@ unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize) unsigned long long bound = 0; /* Iterate over each frame */ while (srcSize > 0) { - ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1); size_t const compressedSize = frameSizeInfo.compressedSize; unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) @@ -836,7 +840,7 @@ size_t ZSTD_decompressionMargin(void const* src, size_t srcSize) /* Iterate over each frame */ while (srcSize > 0) { - ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize); + ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1); size_t const compressedSize = frameSizeInfo.compressedSize; unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; ZSTD_frameHeader zfh; @@ -2178,7 +2182,7 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB if (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(istart, (size_t)(iend-istart)); + 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)); diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 7cc4068bc..e0ee4c3e9 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -2417,6 +2417,41 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : Test single-shot fallback for magicless mode: ", testNb++); + { + // Aquire resources + size_t const srcSize = COMPRESSIBLE_NOISE_LENGTH; + void* src = malloc(srcSize); + size_t const dstSize = ZSTD_compressBound(srcSize); + void* dst = malloc(dstSize); + size_t const valSize = srcSize; + void* val = malloc(valSize); + ZSTD_inBuffer inBuf = { dst, dstSize, 0 }; + ZSTD_outBuffer outBuf = { val, valSize, 0 }; + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + CHECK(!src || !dst || !val || !dctx || !cctx, "memory allocation failure"); + + // Write test data for decompression to dst + RDG_genBuffer(src, srcSize, compressibility, 0.0, 0xdeadbeef); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_format, ZSTD_f_zstd1_magicless)); + CHECK_Z(ZSTD_compress2(cctx, dst, dstSize, src, srcSize)); + + // Run decompression + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless)); + CHECK_Z(ZSTD_decompressStream(dctx, &outBuf, &inBuf)); + + // Validate + CHECK(outBuf.pos != srcSize, "decompressed size must match"); + CHECK(memcmp(src, val, srcSize) != 0, "decompressed data must match"); + + // Cleanup + free(src); free(dst); free(val); + ZSTD_freeCCtx(cctx); + ZSTD_freeDCtx(dctx); + } + DISPLAYLEVEL(3, "OK \n"); + _end: FUZ_freeDictionary(dictionary); ZSTD_freeCStream(zc); From cd4dba74dea8a92f9e33d72fcb5b60224bc4e6c3 Mon Sep 17 00:00:00 2001 From: Alexander Kanavin Date: Mon, 19 Jun 2023 17:10:09 +0200 Subject: [PATCH 273/937] pzstd: use c++14 without conditions Doing this check with a direct c++ snippet is prone to portability problems: - \043 is not portable between shells: dash expands it to #, bash does not; - using # directly works with make 4.3 but does not with make 4.2. Let's just use the c++ version that covers both the code and the gtest. --- contrib/pzstd/Makefile | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/contrib/pzstd/Makefile b/contrib/pzstd/Makefile index 9604eb243..e4b3e8a21 100644 --- a/contrib/pzstd/Makefile +++ b/contrib/pzstd/Makefile @@ -37,11 +37,8 @@ CFLAGS += -Wno-deprecated-declarations PZSTD_INC = -I$(ZSTDDIR) -I$(ZSTDDIR)/common -I$(PROGDIR) -I. GTEST_INC = -isystem googletest/googletest/include -# If default C++ version is older than C++11, explicitly set C++11, which is the -# minimum required by the code. -ifeq ($(shell echo "\043if __cplusplus < 201103L\n\043error\n\043endif" | $(CXX) -x c++ -Werror -c - -o /dev/null 2>/dev/null && echo 1 || echo 0),0) -PZSTD_CXX_STD := -std=c++11 -endif +# Set the minimum required by gtest +PZSTD_CXX_STD := -std=c++14 PZSTD_CPPFLAGS = $(PZSTD_INC) PZSTD_CCXXFLAGS = From 42b02f5185393e5f71abaa4c532684de3569be85 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Mon, 18 Mar 2024 09:28:06 -0700 Subject: [PATCH 274/937] [cmake] Emit warnings for contradictory build settings Document that the `ZSTD_BUILD_{SHARED,STATIC}` take precedence over `BUILD_SHARED_LIBS` when exactly one is ON. Thanks to @teo-tsirpanis for pointing out the potentially confusing behavior. --- build/cmake/lib/CMakeLists.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index eb21b8b32..5d514ccb2 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -152,11 +152,17 @@ if (ZSTD_BUILD_STATIC) add_definition(libzstd_static ZDICTLIB_STATIC_API) endif () if (ZSTD_BUILD_SHARED AND NOT ZSTD_BUILD_STATIC) + if (NOT BUILD_SHARED_LIBS) + message(WARNING "BUILD_SHARED_LIBS is OFF, but ZSTD_BUILD_SHARED is ON and ZSTD_BUILD_STATIC is OFF, which takes precedence, so libzstd is a shared library") + endif () add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_shared) list(APPEND library_targets libzstd) endif () if (ZSTD_BUILD_STATIC AND NOT ZSTD_BUILD_SHARED) + if (BUILD_SHARED_LIBS) + message(WARNING "BUILD_SHARED_LIBS is ON, but ZSTD_BUILD_SHARED is OFF and ZSTD_BUILD_STATIC is ON, which takes precedence, is set so libzstd is a static library") + endif () add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_static) list(APPEND library_targets libzstd) From f5728da365e14a715a131434847f732ee84d8719 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 12:04:02 -0700 Subject: [PATCH 275/937] update targetCBlockSize documentation --- lib/compress/zstd_compress_superblock.c | 4 +-- lib/zstd.h | 38 ++++++++++++++----------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index 8c466c479..628a2dccd 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -469,8 +469,6 @@ static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs, return n; } -#define CBLOCK_TARGET_SIZE_MIN 1340 /* suitable to fit into an ethernet / wifi / 4G transport frame */ - /** ZSTD_compressSubBlock_multi() : * Breaks super-block into multiple sub-blocks and compresses them. * Entropy will be written into the first block. @@ -504,7 +502,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr, const BYTE* llCodePtr = seqStorePtr->llCode; const BYTE* mlCodePtr = seqStorePtr->mlCode; const BYTE* ofCodePtr = seqStorePtr->ofCode; - size_t const minTarget = CBLOCK_TARGET_SIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */ + size_t const minTarget = ZSTD_TARGETCBLOCKSIZE_MIN; /* enforce minimum size, to reduce undesirable side effects */ size_t const targetCBlockSize = MAX(minTarget, cctxParams->targetCBlockSize); int writeLitEntropy = (entropyMetadata->hufMetadata.hType == set_compressed); int writeSeqEntropy = 1; diff --git a/lib/zstd.h b/lib/zstd.h index ba611656f..115d7f2ac 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -262,9 +262,9 @@ ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* accept NULL pointer * /*! ZSTD_compressCCtx() : * Same as ZSTD_compress(), using an explicit ZSTD_CCtx. - * Important : in order to behave similarly to `ZSTD_compress()`, - * this function compresses at requested compression level, - * __ignoring any other parameter__ . + * Important : in order to mirror `ZSTD_compress()` behavior, + * this function compresses at the requested compression level, + * __ignoring any other advanced parameter__ . * If any advanced parameter was set using the advanced API, * they will all be reset. Only `compressionLevel` remains. */ @@ -286,7 +286,7 @@ ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer * /*! ZSTD_decompressDCtx() : * Same as ZSTD_decompress(), * requires an allocated ZSTD_DCtx. - * Compatible with sticky parameters. + * Compatible with sticky parameters (see below). */ ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, @@ -302,12 +302,12 @@ ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, * using ZSTD_CCtx_set*() functions. * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame. * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` ! - * __They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()__ . + * __They do not apply to one-shot variants such as ZSTD_compressCCtx()__ . * * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset(). * * This API supersedes all other "advanced" API entry points in the experimental section. - * In the future, we expect to remove from experimental API entry points which are redundant with this API. + * In the future, we expect to remove API entry points from experimental which are redundant with this API. */ @@ -390,16 +390,19 @@ typedef enum { * The higher the value of selected strategy, the more complex it is, * resulting in stronger and slower compression. * Special: value 0 means "use default strategy". */ - ZSTD_c_targetCBlockSize=130, /* Tries to fit compressed block size to be - * around targetCBlockSize. No target when - * targetCBlockSize == 0. There is no guarantee - * on compressed block size (default:0). - * Since the decoder has to buffer a complete - * block to begin decoding it, in low band- - * width streaming environments this may - * improve end-to-end latency. Bound by - * ZSTD_TARGETCBLOCKSIZE_MIN and - * ZSTD_TARGETCBLOCKSIZE_MAX. */ + + ZSTD_c_targetCBlockSize=130, /* v1.5.6+ + * Attempts to fit compressed block size into approximatively targetCBlockSize. + * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. + * Note that it's not a guarantee, just a convergence target (default:0). + * No target when targetCBlockSize == 0. + * This is helpful in low bandwidth streaming environments to improve end-to-end latency, + * when a client can make use of partial documents (a prominent example being Chrome). + * Note: this parameter is stable since v1.5.6. + * It was present as an experimental parameter in earlier versions, + * but we don't recomment using it with earlier library versions + * due to massive performance regressions. + */ /* LDM mode parameters */ ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching. * This parameter is designed to improve compression ratio @@ -584,6 +587,7 @@ ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset); /*! ZSTD_compress2() : * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. + * (note that this entry point doesn't even expose a compression level parameter). * ZSTD_compress2() always starts a new frame. * Should cctx hold data from a previously unfinished frame, everything about it is forgotten. * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() @@ -1250,7 +1254,7 @@ ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); #define ZSTD_LDM_HASHRATELOG_MAX (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN) /* Advanced parameter bounds */ -#define ZSTD_TARGETCBLOCKSIZE_MIN 64 +#define ZSTD_TARGETCBLOCKSIZE_MIN 1340 /* suitable to fit into an ethernet / wifi / 4G transport frame */ #define ZSTD_TARGETCBLOCKSIZE_MAX ZSTD_BLOCKSIZE_MAX #define ZSTD_SRCSIZEHINT_MIN 0 #define ZSTD_SRCSIZEHINT_MAX INT_MAX From 5d82c2b57c0f5f239ba712a7e6ec46c84a6ba02d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 12:17:41 -0700 Subject: [PATCH 276/937] add a paragraph on UB DCtx state after error --- lib/zstd.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/zstd.h b/lib/zstd.h index 115d7f2ac..d27e59317 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -904,6 +904,12 @@ ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); * @return : 0 when a frame is completely decoded and fully flushed, * or an error code, which can be tested using ZSTD_isError(), * or any other value > 0, which means there is some decoding or flushing to do to complete current frame. + * + * Note: when an operation returns with an error code, the @zds state if 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 reset first, + * which can be done explicitly (`ZSTD_DCtx_reset()`), + * or is sometimes implied (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) */ ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); From 902c7ec1fe833f7f8d542fe94acba9e3a0a013a1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 12:30:35 -0700 Subject: [PATCH 277/937] add doc on CCtx UB state --- lib/zstd.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index d27e59317..b13e7e959 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -791,6 +791,11 @@ typedef enum { * only ZSTD_e_end or ZSTD_e_flush operations are allowed. * Before starting a new compression job, or changing compression parameters, * it is required to fully flush internal buffers. + * - note: if an operation ends with an error, it may leave @cctx in an undefined state. + * Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state. + * In order to be re-employed after an error, a state must be reset, + * which can be done explicitly (ZSTD_CCtx_reset()), + * or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx()) */ ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx, ZSTD_outBuffer* output, @@ -905,11 +910,11 @@ ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); * or an error code, which can be tested using ZSTD_isError(), * or any other value > 0, which means there is some decoding or flushing to do to complete current frame. * - * Note: when an operation returns with an error code, the @zds state if left in undefined state. + * 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 reset first, + * In order to re-use such a state, it must be first reset, * which can be done explicitly (`ZSTD_DCtx_reset()`), - * or is sometimes implied (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) + * or is implied for operations starting some new decompression job (`ZSTD_initDStream`, `ZSTD_decompressDCtx()`, `ZSTD_decompress_usingDict()`) */ ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input); From 3d18d9a9ce5fd5a03c6389b17ee464cf2cf60e94 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 12:30:54 -0700 Subject: [PATCH 278/937] updated API manual --- doc/zstd_manual.html | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 58fe958dc..48db40e6b 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -190,9 +190,9 @@ size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx); /* accept NULL pointer */ const void* src, size_t srcSize, int compressionLevel);

    Same as ZSTD_compress(), using an explicit ZSTD_CCtx. - Important : in order to behave similarly to `ZSTD_compress()`, - this function compresses at requested compression level, - __ignoring any other parameter__ . + Important : in order to mirror `ZSTD_compress()` behavior, + this function compresses at the requested compression level, + __ignoring any other advanced parameter__ . If any advanced parameter was set using the advanced API, they will all be reset. Only `compressionLevel` remains. @@ -212,7 +212,7 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ const void* src, size_t srcSize);

    Same as ZSTD_decompress(), requires an allocated ZSTD_DCtx. - Compatible with sticky parameters. + Compatible with sticky parameters (see below).


@@ -296,6 +296,19 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ * The higher the value of selected strategy, the more complex it is, * resulting in stronger and slower compression. * Special: value 0 means "use default strategy". */ + + ZSTD_c_targetCBlockSize=130, /* v1.5.6+ + * Attempts to fit compressed block size into approximatively targetCBlockSize. + * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. + * Note that it's not a guarantee, just a convergence target (default:0). + * No target when targetCBlockSize == 0. + * This is helpful in low bandwidth streaming environments to improve end-to-end latency, + * when a client can make use of partial documents (a prominent example being Chrome). + * Note: this parameter is stable since v1.5.6. + * It was present as an experimental parameter in earlier versions, + * but we don't recomment using it with earlier library versions + * due to massive performance regressions. + */ /* LDM mode parameters */ ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching. * This parameter is designed to improve compression ratio @@ -375,7 +388,6 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ * ZSTD_c_forceMaxWindow * ZSTD_c_forceAttachDict * ZSTD_c_literalCompressionMode - * ZSTD_c_targetCBlockSize * ZSTD_c_srcSizeHint * ZSTD_c_enableDedicatedDictSearch * ZSTD_c_stableInBuffer @@ -396,7 +408,7 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ ZSTD_c_experimentalParam3=1000, ZSTD_c_experimentalParam4=1001, ZSTD_c_experimentalParam5=1002, - ZSTD_c_experimentalParam6=1003, + /* was ZSTD_c_experimentalParam6=1003; is now ZSTD_c_targetCBlockSize */ ZSTD_c_experimentalParam7=1004, ZSTD_c_experimentalParam8=1005, ZSTD_c_experimentalParam9=1006, @@ -483,6 +495,7 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ void* dst, size_t dstCapacity, const void* src, size_t srcSize);

Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API. + (note that this entry point doesn't even expose a compression level parameter). ZSTD_compress2() always starts a new frame. Should cctx hold data from a previously unfinished frame, everything about it is forgotten. - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*() @@ -668,6 +681,11 @@ size_t ZSTD_freeCStream(ZSTD_CStream* zcs); /* accept NULL pointer */ only ZSTD_e_end or ZSTD_e_flush operations are allowed. Before starting a new compression job, or changing compression parameters, it is required to fully flush internal buffers. + - note: if an operation ends with an error, it may leave @cctx in an undefined state. + Therefore, it's UB to invoke ZSTD_compressStream2() of ZSTD_compressStream() on such a state. + In order to be re-employed after an error, a state must be reset, + which can be done explicitly (ZSTD_CCtx_reset()), + or is sometimes implied by methods starting a new compression job (ZSTD_initCStream(), ZSTD_compressCCtx())


@@ -753,6 +771,12 @@ size_t ZSTD_freeDStream(ZSTD_DStream* zds);
/* accept NULL pointer */ @return : 0 when a frame is completely decoded and fully flushed, or an error code, which can be tested using ZSTD_isError(), or any other value > 0, which means there is some decoding or flushing to do to complete current frame. + + 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()`)


From c5da438dc0ca81ce697a73a02b060e3ba7550bab Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 12:33:22 -0700 Subject: [PATCH 279/937] fix typo --- doc/zstd_manual.html | 2 +- lib/zstd.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 48db40e6b..bc4a24036 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -306,7 +306,7 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx);
/* accept NULL pointer */ * when a client can make use of partial documents (a prominent example being Chrome). * Note: this parameter is stable since v1.5.6. * It was present as an experimental parameter in earlier versions, - * but we don't recomment using it with earlier library versions + * but it's not recommended using it with earlier library versions * due to massive performance regressions. */ /* LDM mode parameters */ diff --git a/lib/zstd.h b/lib/zstd.h index b13e7e959..b110874b7 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -400,7 +400,7 @@ typedef enum { * when a client can make use of partial documents (a prominent example being Chrome). * Note: this parameter is stable since v1.5.6. * It was present as an experimental parameter in earlier versions, - * but we don't recomment using it with earlier library versions + * but it's not recommended using it with earlier library versions * due to massive performance regressions. */ /* LDM mode parameters */ From 6f1215b874dbf74b50dcb64915e91e11ba198008 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 18 Mar 2024 14:10:08 -0700 Subject: [PATCH 280/937] fix ZSTD_TARGETCBLOCKSIZE_MIN test when requested CBlockSize is too low, bound it to the minimum instead of returning an error. --- lib/compress/zstd_compress.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 451f2f91e..38c91473e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -870,7 +870,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, #else FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), ""); CCtxParams->nbWorkers = value; - return CCtxParams->nbWorkers; + return (size_t)(CCtxParams->nbWorkers); #endif case ZSTD_c_jobSize : @@ -894,7 +894,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, #else FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), ""); CCtxParams->overlapLog = value; - return CCtxParams->overlapLog; + return (size_t)CCtxParams->overlapLog; #endif case ZSTD_c_rsyncable : @@ -904,7 +904,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, #else FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(ZSTD_c_overlapLog, &value), ""); CCtxParams->rsyncable = value; - return CCtxParams->rsyncable; + return (size_t)CCtxParams->rsyncable; #endif case ZSTD_c_enableDedicatedDictSearch : @@ -941,8 +941,10 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, return CCtxParams->ldmParams.hashRateLog; case ZSTD_c_targetCBlockSize : - if (value!=0) /* 0 ==> default */ + if (value!=0) { /* 0 ==> default */ + value = MAX(value, ZSTD_TARGETCBLOCKSIZE_MIN); BOUNDCHECK(ZSTD_c_targetCBlockSize, value); + } CCtxParams->targetCBlockSize = (U32)value; return CCtxParams->targetCBlockSize; @@ -970,7 +972,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_validateSequences: BOUNDCHECK(ZSTD_c_validateSequences, value); CCtxParams->validateSequences = value; - return CCtxParams->validateSequences; + return (size_t)CCtxParams->validateSequences; case ZSTD_c_useBlockSplitter: BOUNDCHECK(ZSTD_c_useBlockSplitter, value); @@ -985,7 +987,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_deterministicRefPrefix: BOUNDCHECK(ZSTD_c_deterministicRefPrefix, value); CCtxParams->deterministicRefPrefix = !!value; - return CCtxParams->deterministicRefPrefix; + return (size_t)CCtxParams->deterministicRefPrefix; case ZSTD_c_prefetchCDictTables: BOUNDCHECK(ZSTD_c_prefetchCDictTables, value); @@ -995,7 +997,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_enableSeqProducerFallback: BOUNDCHECK(ZSTD_c_enableSeqProducerFallback, value); CCtxParams->enableMatchFinderFallback = value; - return CCtxParams->enableMatchFinderFallback; + return (size_t)CCtxParams->enableMatchFinderFallback; case ZSTD_c_maxBlockSize: if (value!=0) /* 0 ==> default */ From 6a0052a409e2604bd40354b76b86272b712edd7d Mon Sep 17 00:00:00 2001 From: Yonatan Komornik <11005061+yoniko@users.noreply.github.com> Date: Mon, 18 Mar 2024 15:36:40 -0700 Subject: [PATCH 281/937] Fix bugs in simple decompression fuzzer (#3978) Fixes 2 issue in `simple_decompress.c`: 1. Wrong type used for storing the results of `ZSTD_findDecompressedSize` resulting in never matching to `ZSTD_CONTENTSIZE_ERROR` or `ZSTD_CONTENTSIZE_UNKNOWN`. 2. Experimental API is used (`ZSTD_findDecompressedSize`) without defining `ZSTD_STATIC_LINKING_ONLY`. --- tests/fuzz/simple_decompress.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/fuzz/simple_decompress.c b/tests/fuzz/simple_decompress.c index 0ee61902c..ab4697ff1 100644 --- a/tests/fuzz/simple_decompress.c +++ b/tests/fuzz/simple_decompress.c @@ -16,6 +16,9 @@ #include #include #include + +#define ZSTD_STATIC_LINKING_ONLY + #include "fuzz_helpers.h" #include "zstd.h" #include "fuzz_data_producer.h" @@ -40,7 +43,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) size_t const dSize = ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size); if (!ZSTD_isError(dSize)) { /* If decompression was successful, the content size from the frame header(s) should be valid. */ - size_t const expectedSize = ZSTD_findDecompressedSize(src, size); + unsigned long long const expectedSize = ZSTD_findDecompressedSize(src, size); FUZZ_ASSERT(expectedSize != ZSTD_CONTENTSIZE_ERROR); FUZZ_ASSERT(expectedSize == ZSTD_CONTENTSIZE_UNKNOWN || expectedSize == dSize); } From 3487a60950ea01e89883a3e807a18a6e155768b7 Mon Sep 17 00:00:00 2001 From: Yonatan Komornik Date: Mon, 18 Mar 2024 15:25:22 -0700 Subject: [PATCH 282/937] Fail on errors when building fuzzers Fails on errors when building fuzzers with `fuzz.py` (adds `Werror`). Currently allows `declaration-after-statement`, `c++-compat` and `deprecated` as they are abundant in code (some fixes to `declaration-after-statement` are presented in this commit). --- tests/fuzz/fuzz.py | 7 ++++++- tests/fuzz/fuzz_data_producer.c | 10 +++++----- tests/fuzz/regression_driver.c | 3 ++- tests/fuzz/simple_decompress.c | 21 +++++++++++---------- tests/fuzz/stream_round_trip.c | 2 +- 5 files changed, 25 insertions(+), 18 deletions(-) diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py index c489b8fa6..7e1f3c9df 100755 --- a/tests/fuzz/fuzz.py +++ b/tests/fuzz/fuzz.py @@ -405,7 +405,12 @@ def build(args): cxxflags = shlex.split(args.cxxflags) mflags = shlex.split(args.mflags) # Flags to be added to both cflags and cxxflags - common_flags = [] + common_flags = [ + '-Werror', + '-Wno-error=declaration-after-statement', + '-Wno-error=c++-compat', + '-Wno-error=deprecated' # C files are sometimes compiled with CXX + ] cppflags += [ '-DDEBUGLEVEL={}'.format(args.debug), diff --git a/tests/fuzz/fuzz_data_producer.c b/tests/fuzz/fuzz_data_producer.c index bf846b68f..056de3ee9 100644 --- a/tests/fuzz/fuzz_data_producer.c +++ b/tests/fuzz/fuzz_data_producer.c @@ -28,12 +28,12 @@ void FUZZ_dataProducer_free(FUZZ_dataProducer_t *producer) { free(producer); } uint32_t FUZZ_dataProducer_uint32Range(FUZZ_dataProducer_t *producer, uint32_t min, uint32_t max) { - FUZZ_ASSERT(min <= max); - uint32_t range = max - min; uint32_t rolling = range; uint32_t result = 0; + FUZZ_ASSERT(min <= max); + while (rolling > 0 && producer->size > 0) { uint8_t next = *(producer->data + producer->size - 1); producer->size -= 1; @@ -79,11 +79,11 @@ int FUZZ_dataProducer_empty(FUZZ_dataProducer_t *producer) { size_t FUZZ_dataProducer_contract(FUZZ_dataProducer_t *producer, size_t newSize) { - newSize = newSize > producer->size ? producer->size : newSize; + const size_t effectiveNewSize = newSize > producer->size ? producer->size : newSize; - size_t remaining = producer->size - newSize; + size_t remaining = producer->size - effectiveNewSize; producer->data = producer->data + remaining; - producer->size = newSize; + producer->size = effectiveNewSize; return remaining; } diff --git a/tests/fuzz/regression_driver.c b/tests/fuzz/regression_driver.c index 550c65d86..26e2b6af4 100644 --- a/tests/fuzz/regression_driver.c +++ b/tests/fuzz/regression_driver.c @@ -44,11 +44,12 @@ int main(int argc, char const **argv) { fprintf(stderr, "WARNING: No files passed to %s\n", argv[0]); for (i = 0; i < files->tableSize; ++i) { char const *fileName = files->fileNames[i]; - DEBUGLOG(3, "Running %s", fileName); size_t const fileSize = UTIL_getFileSize(fileName); size_t readSize; FILE *file; + DEBUGLOG(3, "Running %s", fileName); + /* Check that it is a regular file, and that the fileSize is valid. * If it is not a regular file, then it may have been deleted since we * constructed the list, so just skip it, but return an error exit code. diff --git a/tests/fuzz/simple_decompress.c b/tests/fuzz/simple_decompress.c index ab4697ff1..0dc9e5b7c 100644 --- a/tests/fuzz/simple_decompress.c +++ b/tests/fuzz/simple_decompress.c @@ -37,17 +37,18 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) FUZZ_ASSERT(dctx); } - size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size); - void *rBuf = FUZZ_malloc(bufSize); - - size_t const dSize = ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size); - if (!ZSTD_isError(dSize)) { - /* If decompression was successful, the content size from the frame header(s) should be valid. */ - unsigned long long const expectedSize = ZSTD_findDecompressedSize(src, size); - FUZZ_ASSERT(expectedSize != ZSTD_CONTENTSIZE_ERROR); - FUZZ_ASSERT(expectedSize == ZSTD_CONTENTSIZE_UNKNOWN || expectedSize == dSize); + { + size_t const bufSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size); + void *rBuf = FUZZ_malloc(bufSize); + size_t const dSize = ZSTD_decompressDCtx(dctx, rBuf, bufSize, src, size); + if (!ZSTD_isError(dSize)) { + /* If decompression was successful, the content size from the frame header(s) should be valid. */ + unsigned long long const expectedSize = ZSTD_findDecompressedSize(src, size); + FUZZ_ASSERT(expectedSize != ZSTD_CONTENTSIZE_ERROR); + FUZZ_ASSERT(expectedSize == ZSTD_CONTENTSIZE_UNKNOWN || expectedSize == dSize); + } + free(rBuf); } - free(rBuf); FUZZ_dataProducer_free(producer); diff --git a/tests/fuzz/stream_round_trip.c b/tests/fuzz/stream_round_trip.c index c2d6707a1..6e340c81d 100644 --- a/tests/fuzz/stream_round_trip.c +++ b/tests/fuzz/stream_round_trip.c @@ -136,7 +136,7 @@ static size_t compress(uint8_t *dst, size_t capacity, return dstSize; } -size_t decompress(void* dst, size_t dstCapacity, void const* src, size_t srcSize, FUZZ_dataProducer_t* producer) +static size_t decompress(void* dst, size_t dstCapacity, void const* src, size_t srcSize, FUZZ_dataProducer_t* producer) { ZSTD_inBuffer in = {src, srcSize, 0}; ZSTD_outBuffer out = {dst, dstCapacity, 0}; From f62b2663b96d440d3b9dd50b40dc911f9e0083d3 Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Tue, 19 Mar 2024 14:05:23 -0700 Subject: [PATCH 283/937] Add docs on how to add a new fuzzer --- tests/fuzz/README.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/fuzz/README.md b/tests/fuzz/README.md index 2a9bd4570..e2196e832 100644 --- a/tests/fuzz/README.md +++ b/tests/fuzz/README.md @@ -117,3 +117,45 @@ CC=clang CXX=clang++ ./fuzz.py build all --enable-msan ## Fuzzing a custom sequence producer plugin Sequence producer plugin authors can use the zstd fuzzers to stress-test their code. See the documentation in `fuzz_third_party_seq_prod.h` for details. + +## Adding a new fuzzer +There are several steps involved in adding a new fuzzer harness. + +### Build your harness +1. Create a new your fuzzer harness `tests/fuzz/your_harness.c`. + +2. Add your harness to the Makefile + + 2.1 Follow [this example](https://github.com/facebook/zstd/blob/e124e39301381de8f323436a3e4c46539747ba24/tests/fuzz/Makefile#L216) if your fuzzer requires both compression and decompression symbols (prefix `rt_`). If your fuzzer only requires decompression symbols, follow [this example](https://github.com/facebook/zstd/blob/6a0052a409e2604bd40354b76b86272b712edd7d/tests/fuzz/Makefile#L194) (prefix `d_`). + + 2.2 Add your target to [`FUZZ_TARGETS`](https://github.com/facebook/zstd/blob/6a0052a409e2604bd40354b76b86272b712edd7d/tests/fuzz/Makefile#L108). + +3. Add your harness to [`fuzz.py`](https://github.com/facebook/zstd/blob/6a0052a409e2604bd40354b76b86272b712edd7d/tests/fuzz/fuzz.py#L48). + +### Generate seed data +Follow the instructions above to generate seed data: +``` +make -C ../tests decodecorpus +./fuzz.py gen your_harness +``` + +### Run the harness +Follow the instructions above to run your harness and fix any crashes: +``` +./fuzz.py build your_harness --enable-fuzzer --enable-asan --enable-ubsan --cc clang --cxx clang++ +./fuzz.py libfuzzer your_harness +``` + +### Minimize and zip the corpus +After running the fuzzer for a while, you will have a large corpus at `tests/fuzz/corpora/your_harness*`. +This corpus must be minimized and zipped before uploading to GitHub for regression testing: +``` +./fuzz.py minimize your_harness +./fuzz.py zip your_harness +``` + +### Upload the zip file to GitHub +The previous step should produce a `.zip` file containing the corpus for your new harness. +This corpus must be uploaded to GitHub here: https://github.com/facebook/zstd/releases/tag/fuzz-corpora + + From 741b87bbe1c7c7e7292742f3b1ed9c4055c4743c Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Wed, 20 Mar 2024 19:22:34 -0400 Subject: [PATCH 284/937] Fuzzing and bugfixes for magicless-format decoding (#3976) * fuzzing and bugfixes for magicless format * reset dctx before each decompression * do not memcmp empty buffers * nit: decompressor errata --- CHANGELOG | 1 + doc/decompressor_errata.md | 21 +++++ lib/decompress/zstd_decompress.c | 8 +- tests/fuzz/Makefile | 6 +- tests/fuzz/decompress_cross_format.c | 130 +++++++++++++++++++++++++++ tests/fuzz/fuzz.py | 1 + 6 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 tests/fuzz/decompress_cross_format.c diff --git a/CHANGELOG b/CHANGELOG index 23c012820..afb80ed9e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -9,6 +9,7 @@ lib: accept dictionaries with partial literal tables, by @terrelln lib: fix CCtx size estimation with external sequence producer, by @embg lib: fix corner case decoder behaviors, by @Cyan4973 and @aimuz lib: fix zdict prototype mismatch in static_only mode, by @ldv-alt +lib: fix several bugs in magicless-format decoding, by @embg cli: add common compressed file types to `--exclude-compressed`` by @daniellerozenblit cli: fix mixing `-c` and `-o` commands with `--rm`, by @Cyan4973 cli: fix erroneous exclusion of hidden files with `--output-dir-mirror` by @felixhandte diff --git a/doc/decompressor_errata.md b/doc/decompressor_errata.md index 83d4071cb..b570f7314 100644 --- a/doc/decompressor_errata.md +++ b/doc/decompressor_errata.md @@ -125,3 +125,24 @@ The total `Block_Content` is `5` bytes, and `Last_Table_Offset` is `2`. See the compressor workaround code: https://github.com/facebook/zstd/blob/8814aa5bfa74f05a86e55e9d508da177a893ceeb/lib/compress/zstd_compress.c#L2667-L2682 + +Magicless format +---------------------- + +**Last affected version**: v1.5.5 + +**Affected decompressor component(s)**: Library + +**Produced by the reference compressor**: Yes (example: https://gist.github.com/embg/9940726094f4cf2cef162cffe9319232) + +**Example Frame**: `27 b5 2f fd 00 03 19 00 00 66 6f 6f 3f ba c4 59` + +v1.5.6 fixes several bugs in which the magicless-format decoder rejects valid frames. +These include but are not limited to: +* Valid frames that happen to begin with a legacy magic number (little-endian) +* Valid frames that happen to begin with a skippable magic number (little-endian) + +If you are affected by this issue and cannot update to v1.5.6 or later, there is a +workaround to recover affected data. Simply prepend the ZSTD magic number +`0xFD2FB528` (little-endian) to your data and decompress using the standard-format +decoder. diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index ee2cda3b6..2f03cf7b0 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -1085,7 +1085,7 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, while (srcSize >= ZSTD_startingInputLength(dctx->format)) { #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1) - if (ZSTD_isLegacy(src, srcSize)) { + if (dctx->format == ZSTD_f_zstd1 && ZSTD_isLegacy(src, srcSize)) { size_t decodedSize; size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize); if (ZSTD_isError(frameSize)) return frameSize; @@ -1115,7 +1115,7 @@ size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx, } #endif - if (srcSize >= 4) { + if (dctx->format == ZSTD_f_zstd1 && srcSize >= 4) { U32 const magicNumber = MEM_readLE32(src); DEBUGLOG(5, "reading magic number %08X", (unsigned)magicNumber); if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { @@ -1412,6 +1412,7 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, c case ZSTDds_decodeSkippableHeader: assert(src != NULL); assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE); + assert(dctx->format != ZSTD_f_zstd1_magicless); ZSTD_memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */ dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */ dctx->stage = ZSTDds_skipFrame; @@ -2209,7 +2210,8 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB DEBUGLOG(4, "Consume header"); FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), ""); - if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ + if (zds->format == ZSTD_f_zstd1 + && (MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */ zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE); zds->stage = ZSTDds_skipFrame; } else { diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index f96adcfae..2f5a25fb1 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -124,7 +124,8 @@ FUZZ_TARGETS := \ sequence_compression_api \ seekable_roundtrip \ huf_round_trip \ - huf_decompress + huf_decompress \ + decompress_cross_format all: libregression.a $(FUZZ_TARGETS) @@ -238,6 +239,9 @@ huf_round_trip: $(FUZZ_HEADERS) $(FUZZ_ROUND_TRIP_OBJ) rt_fuzz_huf_round_trip.o huf_decompress: $(FUZZ_HEADERS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_huf_decompress.o $(CXX) $(FUZZ_TARGET_FLAGS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_huf_decompress.o $(LIB_FUZZING_ENGINE) -o $@ + +decompress_cross_format: $(FUZZ_HEADERS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_decompress_cross_format.o + $(CXX) $(FUZZ_TARGET_FLAGS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_decompress_cross_format.o $(LIB_FUZZING_ENGINE) -o $@ libregression.a: $(FUZZ_HEADERS) $(PRGDIR)/util.h $(PRGDIR)/util.c d_fuzz_regression_driver.o $(AR) $(FUZZ_ARFLAGS) $@ d_fuzz_regression_driver.o diff --git a/tests/fuzz/decompress_cross_format.c b/tests/fuzz/decompress_cross_format.c new file mode 100644 index 000000000..78461e697 --- /dev/null +++ b/tests/fuzz/decompress_cross_format.c @@ -0,0 +1,130 @@ +/* + * 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. + */ + +// This fuzz target validates decompression of magicless-format compressed data. + +#include +#include +#include +#include +#include "fuzz_helpers.h" +#define ZSTD_STATIC_LINKING_ONLY +#include "zstd.h" +#include "fuzz_data_producer.h" + +static ZSTD_DCtx *dctx = NULL; + +int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) +{ + // Give a random portion of src data to the producer, to use for parameter generation. + // The rest will be interpreted as magicless compressed data. + FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size); + size_t magiclessSize = FUZZ_dataProducer_reserveDataPrefix(producer); + const void* const magiclessSrc = src; + size_t const dstSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size); + void* const standardDst = FUZZ_malloc(dstSize); + void* const magiclessDst = FUZZ_malloc(dstSize); + + // Create standard-format src from magicless-format src + const uint32_t zstd_magic = ZSTD_MAGICNUMBER; + size_t standardSize = sizeof(zstd_magic) + magiclessSize; + void* const standardSrc = FUZZ_malloc(standardSize); + memcpy(standardSrc, &zstd_magic, sizeof(zstd_magic)); // assume fuzzing on little-endian machine + memcpy(standardSrc + sizeof(zstd_magic), magiclessSrc, magiclessSize); + + // Truncate to a single frame + { + const size_t standardFrameCompressedSize = ZSTD_findFrameCompressedSize(standardSrc, standardSize); + if (ZSTD_isError(standardFrameCompressedSize)) { + goto cleanup_and_return; + } + standardSize = standardFrameCompressedSize; + magiclessSize = standardFrameCompressedSize - sizeof(zstd_magic); + } + + // Create DCtx if needed + if (!dctx) { + dctx = ZSTD_createDCtx(); + FUZZ_ASSERT(dctx); + } + + // Test one-shot decompression + { + FUZZ_ZASSERT(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1)); + const size_t standardRet = ZSTD_decompressDCtx( + dctx, standardDst, dstSize, standardSrc, standardSize); + + FUZZ_ZASSERT(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless)); + const size_t magiclessRet = ZSTD_decompressDCtx( + dctx, magiclessDst, dstSize, magiclessSrc, magiclessSize); + + // Standard accepts => magicless should accept + if (!ZSTD_isError(standardRet)) FUZZ_ZASSERT(magiclessRet); + + // Magicless accepts => standard should accept + // NOTE: this is nice-to-have, please disable this check if it is difficult to satisfy. + if (!ZSTD_isError(magiclessRet)) FUZZ_ZASSERT(standardRet); + + // If both accept, decompressed size and data should match + if (!ZSTD_isError(standardRet) && !ZSTD_isError(magiclessRet)) { + FUZZ_ASSERT(standardRet == magiclessRet); + if (standardRet > 0) { + FUZZ_ASSERT( + memcmp(standardDst, magiclessDst, standardRet) == 0 + ); + } + } + } + + // Test streaming decompression + { + ZSTD_inBuffer standardIn = { standardSrc, standardSize, 0 }; + ZSTD_inBuffer magiclessIn = { magiclessSrc, magiclessSize, 0 }; + ZSTD_outBuffer standardOut = { standardDst, dstSize, 0 }; + ZSTD_outBuffer magiclessOut = { magiclessDst, dstSize, 0 }; + + FUZZ_ZASSERT(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1)); + const size_t standardRet = ZSTD_decompressStream(dctx, &standardOut, &standardIn); + + FUZZ_ZASSERT(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); + FUZZ_ZASSERT(ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless)); + const size_t magiclessRet = ZSTD_decompressStream(dctx, &magiclessOut, &magiclessIn); + + // Standard accepts => magicless should accept + if (standardRet == 0) FUZZ_ASSERT(magiclessRet == 0); + + // Magicless accepts => standard should accept + // NOTE: this is nice-to-have, please disable this check if it is difficult to satisfy. + if (magiclessRet == 0) FUZZ_ASSERT(standardRet == 0); + + // If both accept, decompressed size and data should match + if (standardRet == 0 && magiclessRet == 0) { + FUZZ_ASSERT(standardOut.pos == magiclessOut.pos); + if (standardOut.pos > 0) { + FUZZ_ASSERT( + memcmp(standardOut.dst, magiclessOut.dst, standardOut.pos) == 0 + ); + } + } + } + +cleanup_and_return: +#ifndef STATEFUL_FUZZING + ZSTD_freeDCtx(dctx); dctx = NULL; +#endif + free(standardSrc); + free(standardDst); + free(magiclessDst); + FUZZ_dataProducer_free(producer); + return 0; +} diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py index c489b8fa6..f321002a7 100755 --- a/tests/fuzz/fuzz.py +++ b/tests/fuzz/fuzz.py @@ -65,6 +65,7 @@ TARGET_INFO = { 'seekable_roundtrip': TargetInfo(InputType.RAW_DATA), 'huf_round_trip': TargetInfo(InputType.RAW_DATA), 'huf_decompress': TargetInfo(InputType.RAW_DATA), + 'decompress_cross_format': TargetInfo(InputType.RAW_DATA), } TARGETS = list(TARGET_INFO.keys()) ALL_TARGETS = TARGETS + ['all'] From 731f4b70fcd22fc9badd4e51dc6d939ee6da6c54 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Tue, 19 Mar 2024 12:37:55 -0700 Subject: [PATCH 285/937] Fix & fuzz ZSTD_generateSequences This function was seriously flawed: * It didn't do output bounds checks * It produced invalid sequences when an uncompressed or RLE block was emitted * It produced invalid sequences when the block splitter was enabled * It produced invalid sequences when ZSTD_c_targetCBlockSize was enabled I've attempted to fix these issues, but this function is just a bad idea, so I've marked it as deprecated and unsafe. We should replace it with `ZSTD_extractSequences()` which operates on a compressed frame. --- CHANGELOG | 1 + lib/compress/zstd_compress.c | 127 +++++++++++++++++++++----------- lib/compress/zstdmt_compress.c | 4 +- lib/zstd.h | 33 ++++++--- tests/fuzz/Makefile | 8 +- tests/fuzz/fuzz.py | 1 + tests/fuzz/generate_sequences.c | 88 ++++++++++++++++++++++ tests/fuzzer.c | 25 +++++++ 8 files changed, 231 insertions(+), 56 deletions(-) create mode 100644 tests/fuzz/generate_sequences.c diff --git a/CHANGELOG b/CHANGELOG index afb80ed9e..33f43410f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -33,6 +33,7 @@ port: sparc64 support validation in CI, by @Cyan4973 port: AIX compatibility, by @likema port: HP-UX compatibility, by @likema doc: Improved specification accuracy, by @elasota +bug: Fix and deprecate ZSTD_generateSequences (#3981) v1.5.5 (Apr 2023) fix: fix rare corruption bug affecting the high compression mode, reported by @danlark1 (#3517, @terrelln) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 451f2f91e..f6a84e6b7 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3361,29 +3361,38 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) return ZSTDbss_compress; } -static void ZSTD_copyBlockSequences(ZSTD_CCtx* zc) +static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const seqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM]) { - const seqStore_t* seqStore = ZSTD_getSeqStore(zc); - const seqDef* seqStoreSeqs = seqStore->sequencesStart; - size_t seqStoreSeqSize = seqStore->sequences - seqStoreSeqs; - size_t seqStoreLiteralsSize = (size_t)(seqStore->lit - seqStore->litStart); - size_t literalsRead = 0; - size_t lastLLSize; + const seqDef* inSeqs = seqStore->sequencesStart; + const size_t nbInSequences = seqStore->sequences - inSeqs; + const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart); - ZSTD_Sequence* outSeqs = &zc->seqCollector.seqStart[zc->seqCollector.seqIndex]; + ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex; + const size_t nbOutSequences = nbInSequences + 1; + size_t nbOutLiterals = 0; + repcodes_t repcodes; size_t i; - repcodes_t updatedRepcodes; - assert(zc->seqCollector.seqIndex + 1 < zc->seqCollector.maxSequences); - /* Ensure we have enough space for last literals "sequence" */ - assert(zc->seqCollector.maxSequences >= seqStoreSeqSize + 1); - ZSTD_memcpy(updatedRepcodes.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t)); - for (i = 0; i < seqStoreSeqSize; ++i) { - U32 rawOffset = seqStoreSeqs[i].offBase - ZSTD_REP_NUM; - outSeqs[i].litLength = seqStoreSeqs[i].litLength; - outSeqs[i].matchLength = seqStoreSeqs[i].mlBase + MINMATCH; + /* Bounds check that we have enough space for every input sequence + * and the block delimiter + */ + assert(seqCollector->seqIndex <= seqCollector->maxSequences); + RETURN_ERROR_IF( + nbOutSequences > (size_t)(seqCollector->maxSequences - seqCollector->seqIndex), + dstSize_tooSmall, + "Not enough space to copy sequences"); + + ZSTD_memcpy(&repcodes, prevRepcodes, sizeof(repcodes)); + for (i = 0; i < nbInSequences; ++i) { + U32 rawOffset; + outSeqs[i].litLength = inSeqs[i].litLength; + outSeqs[i].matchLength = inSeqs[i].mlBase + MINMATCH; outSeqs[i].rep = 0; + /* Handle the possible single length >= 64K + * There can only be one because we add MINMATCH to every match length, + * and blocks are at most 128K. + */ if (i == seqStore->longLengthPos) { if (seqStore->longLengthType == ZSTD_llt_literalLength) { outSeqs[i].litLength += 0x10000; @@ -3392,41 +3401,55 @@ static void ZSTD_copyBlockSequences(ZSTD_CCtx* zc) } } - if (seqStoreSeqs[i].offBase <= ZSTD_REP_NUM) { - /* Derive the correct offset corresponding to a repcode */ - outSeqs[i].rep = seqStoreSeqs[i].offBase; + /* Determine the raw offset given the offBase, which may be a repcode. */ + if (OFFBASE_IS_REPCODE(inSeqs[i].offBase)) { + const U32 repcode = OFFBASE_TO_REPCODE(inSeqs[i].offBase); + assert(repcode > 0); + outSeqs[i].rep = repcode; if (outSeqs[i].litLength != 0) { - rawOffset = updatedRepcodes.rep[outSeqs[i].rep - 1]; + rawOffset = repcodes.rep[repcode - 1]; } else { - if (outSeqs[i].rep == 3) { - rawOffset = updatedRepcodes.rep[0] - 1; + if (repcode == 3) { + assert(repcodes.rep[0] > 1); + rawOffset = repcodes.rep[0] - 1; } else { - rawOffset = updatedRepcodes.rep[outSeqs[i].rep]; + rawOffset = repcodes.rep[repcode]; } } + } else { + rawOffset = OFFBASE_TO_OFFSET(inSeqs[i].offBase); } outSeqs[i].offset = rawOffset; - /* seqStoreSeqs[i].offset == offCode+1, and ZSTD_updateRep() expects offCode - so we provide seqStoreSeqs[i].offset - 1 */ - ZSTD_updateRep(updatedRepcodes.rep, - seqStoreSeqs[i].offBase, - seqStoreSeqs[i].litLength == 0); - literalsRead += outSeqs[i].litLength; + + /* Update repcode history for the sequence */ + ZSTD_updateRep(repcodes.rep, + inSeqs[i].offBase, + inSeqs[i].litLength == 0); + + nbOutLiterals += outSeqs[i].litLength; } /* Insert last literals (if any exist) in the block as a sequence with ml == off == 0. * If there are no last literals, then we'll emit (of: 0, ml: 0, ll: 0), which is a marker * for the block boundary, according to the API. */ - assert(seqStoreLiteralsSize >= literalsRead); - lastLLSize = seqStoreLiteralsSize - literalsRead; - outSeqs[i].litLength = (U32)lastLLSize; - outSeqs[i].matchLength = outSeqs[i].offset = outSeqs[i].rep = 0; - seqStoreSeqSize++; - zc->seqCollector.seqIndex += seqStoreSeqSize; + assert(nbInLiterals >= nbOutLiterals); + { + const size_t lastLLSize = nbInLiterals - nbOutLiterals; + outSeqs[nbInSequences].litLength = (U32)lastLLSize; + outSeqs[nbInSequences].matchLength = 0; + outSeqs[nbInSequences].offset = 0; + assert(nbOutSequences == nbInSequences + 1); + } + seqCollector->seqIndex += nbOutSequences; + assert(seqCollector->seqIndex <= seqCollector->maxSequences); + + return 0; } size_t ZSTD_sequenceBound(size_t srcSize) { - return (srcSize / ZSTD_MINMATCH_MIN) + 1; + const size_t maxNbSeq = (srcSize / ZSTD_MINMATCH_MIN) + 1; + const size_t maxNbDelims = (srcSize / ZSTD_BLOCKSIZE_MAX_MIN) + 1; + return maxNbSeq + maxNbDelims; } size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, @@ -3435,6 +3458,16 @@ size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, const size_t dstCapacity = ZSTD_compressBound(srcSize); void* dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem); SeqCollector seqCollector; + { + int targetCBlockSize; + FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_targetCBlockSize, &targetCBlockSize), ""); + RETURN_ERROR_IF(targetCBlockSize != 0, parameter_unsupported, "targetCBlockSize != 0"); + } + { + int nbWorkers; + FORWARD_IF_ERROR(ZSTD_CCtx_getParameter(zc, ZSTD_c_nbWorkers, &nbWorkers), ""); + RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0"); + } RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!"); @@ -3444,8 +3477,12 @@ size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, seqCollector.maxSequences = outSeqsSize; zc->seqCollector = seqCollector; - ZSTD_compress2(zc, dst, dstCapacity, src, srcSize); - ZSTD_customFree(dst, ZSTD_defaultCMem); + { + const size_t ret = ZSTD_compress2(zc, dst, dstCapacity, src, srcSize); + ZSTD_customFree(dst, ZSTD_defaultCMem); + FORWARD_IF_ERROR(ret, "ZSTD_compress2 failed"); + } + assert(zc->seqCollector.seqIndex <= ZSTD_sequenceBound(srcSize)); return zc->seqCollector.seqIndex; } @@ -4038,8 +4075,9 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, cSeqsSize = 1; } + /* Sequence collection not supported when block splitting */ if (zc->seqCollector.collectSequences) { - ZSTD_copyBlockSequences(zc); + FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, seqStore, dRepOriginal.rep), "copyBlockSequences failed"); ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState); return 0; } @@ -4261,6 +4299,7 @@ ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc, if (bss == ZSTDbss_noCompress) { if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid) zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check; + RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block"); cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock); FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed"); DEBUGLOG(4, "ZSTD_compressBlock_splitBlock: Nocompress block"); @@ -4293,11 +4332,15 @@ ZSTD_compressBlock_internal(ZSTD_CCtx* zc, { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize); FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed"); - if (bss == ZSTDbss_noCompress) { cSize = 0; goto out; } + if (bss == ZSTDbss_noCompress) { + RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block"); + cSize = 0; + goto out; + } } if (zc->seqCollector.collectSequences) { - ZSTD_copyBlockSequences(zc); + FORWARD_IF_ERROR(ZSTD_copyBlockSequences(&zc->seqCollector, ZSTD_getSeqStore(zc), zc->blockState.prevCBlock->rep), "copyBlockSequences failed"); ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState); return 0; } diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index e86fdb2ba..86ccce318 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -121,7 +121,7 @@ static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool) static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_customMem cMem) { - ZSTDMT_bufferPool* const bufPool = + ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_customCalloc(sizeof(ZSTDMT_bufferPool), cMem); if (bufPool==NULL) return NULL; if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) { @@ -380,7 +380,7 @@ static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool) static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers, ZSTD_customMem cMem) { - ZSTDMT_CCtxPool* const cctxPool = + ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtxPool), cMem); assert(nbWorkers > 0); if (!cctxPool) return NULL; diff --git a/lib/zstd.h b/lib/zstd.h index ba611656f..9b3876126 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1538,25 +1538,38 @@ typedef enum { ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize); /*! ZSTD_generateSequences() : + * WARNING: This function is meant for debugging and informational purposes ONLY! + * Its implementation is flawed, and it will be deleted in a future version. + * It is not guaranteed to succeed, as there are several cases where it will give + * up and fail. You should NOT use this function in production code. + * + * This function is deprecated, and will be removed in a future version. + * * Generate sequences using ZSTD_compress2(), given a source buffer. * + * @param zc The compression context to be used for ZSTD_compress2(). Set any + * compression parameters you need on this context. + * @param outSeqs The output sequences buffer of size @p outSeqsSize + * @param outSeqsSize The size of the output sequences buffer. + * ZSTD_sequenceBound(srcSize) is an upper bound on the number + * of sequences that can be generated. + * @param src The source buffer to generate sequences from of size @p srcSize. + * @param srcSize The size of the source buffer. + * * Each block will end with a dummy sequence * with offset == 0, matchLength == 0, and litLength == length of last literals. * litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) * simply acts as a block delimiter. * - * @zc can be used to insert custom compression params. - * This function invokes ZSTD_compress2(). - * - * The output of this function can be fed into ZSTD_compressSequences() with CCtx - * setting of ZSTD_c_blockDelimiters as ZSTD_sf_explicitBlockDelimiters - * @return : number of sequences generated + * @returns The number of sequences generated, necessarily less than + * ZSTD_sequenceBound(srcSize), or an error code that can be checked + * with ZSTD_isError(). */ - +ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()") ZSTDLIB_STATIC_API size_t -ZSTD_generateSequences( ZSTD_CCtx* zc, - ZSTD_Sequence* outSeqs, size_t outSeqsSize, - const void* src, size_t srcSize); +ZSTD_generateSequences(ZSTD_CCtx* zc, + ZSTD_Sequence* outSeqs, size_t outSeqsSize, + const void* src, size_t srcSize); /*! ZSTD_mergeBlockDelimiters() : * Given an array of ZSTD_Sequence, remove all sequences that represent block delimiters/last literals diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index 2f5a25fb1..430f6df15 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -125,7 +125,8 @@ FUZZ_TARGETS := \ seekable_roundtrip \ huf_round_trip \ huf_decompress \ - decompress_cross_format + decompress_cross_format \ + generate_sequences all: libregression.a $(FUZZ_TARGETS) @@ -239,10 +240,13 @@ huf_round_trip: $(FUZZ_HEADERS) $(FUZZ_ROUND_TRIP_OBJ) rt_fuzz_huf_round_trip.o huf_decompress: $(FUZZ_HEADERS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_huf_decompress.o $(CXX) $(FUZZ_TARGET_FLAGS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_huf_decompress.o $(LIB_FUZZING_ENGINE) -o $@ - + decompress_cross_format: $(FUZZ_HEADERS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_decompress_cross_format.o $(CXX) $(FUZZ_TARGET_FLAGS) $(FUZZ_DECOMPRESS_OBJ) d_fuzz_decompress_cross_format.o $(LIB_FUZZING_ENGINE) -o $@ +generate_sequences: $(FUZZ_HEADERS) $(FUZZ_ROUND_TRIP_OBJ) rt_fuzz_generate_sequences.o + $(CXX) $(FUZZ_TARGET_FLAGS) $(FUZZ_ROUND_TRIP_OBJ) rt_fuzz_generate_sequences.o $(LIB_FUZZING_ENGINE) -o $@ + libregression.a: $(FUZZ_HEADERS) $(PRGDIR)/util.h $(PRGDIR)/util.c d_fuzz_regression_driver.o $(AR) $(FUZZ_ARFLAGS) $@ d_fuzz_regression_driver.o diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py index f321002a7..d6b99171f 100755 --- a/tests/fuzz/fuzz.py +++ b/tests/fuzz/fuzz.py @@ -66,6 +66,7 @@ TARGET_INFO = { 'huf_round_trip': TargetInfo(InputType.RAW_DATA), 'huf_decompress': TargetInfo(InputType.RAW_DATA), 'decompress_cross_format': TargetInfo(InputType.RAW_DATA), + 'generate_sequences': TargetInfo(InputType.RAW_DATA), } TARGETS = list(TARGET_INFO.keys()) ALL_TARGETS = TARGETS + ['all'] diff --git a/tests/fuzz/generate_sequences.c b/tests/fuzz/generate_sequences.c new file mode 100644 index 000000000..1cc57e844 --- /dev/null +++ b/tests/fuzz/generate_sequences.c @@ -0,0 +1,88 @@ +/* + * 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. + */ + +#define ZSTD_STATIC_LINKING_ONLY + +#include +#include +#include +#include + +#include "fuzz_data_producer.h" +#include "fuzz_helpers.h" +#include "zstd_helpers.h" + +/** + * This fuzz target ensures that ZSTD_generateSequences() does not crash and + * if it succeeds that ZSTD_compressSequences() round trips. + */ + +static void testRoundTrip(ZSTD_CCtx* cctx, ZSTD_Sequence const* seqs, size_t nbSeqs, const void* src, size_t srcSize) { + /* Compress the sequences with block delimiters */ + const size_t compressBound = ZSTD_compressBound(srcSize); + void* dst = FUZZ_malloc(compressBound); + FUZZ_ASSERT(dst); + + size_t compressedSize = ZSTD_compressSequences(cctx, dst, compressBound, seqs, nbSeqs, src, srcSize); + FUZZ_ZASSERT(compressedSize); + + void* decompressed = FUZZ_malloc(srcSize); + FUZZ_ASSERT(srcSize == 0 || decompressed); + size_t decompressedSize = ZSTD_decompress(decompressed, srcSize, dst, compressedSize); + FUZZ_ZASSERT(decompressedSize); + FUZZ_ASSERT(decompressedSize == srcSize); + if (srcSize != 0) { + FUZZ_ASSERT(!memcmp(src, decompressed, srcSize)); + } + + free(decompressed); + free(dst); +} + +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + + FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(data, size); + size = FUZZ_dataProducer_reserveDataPrefix(producer); + + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + FUZZ_ASSERT(cctx); + + const size_t seqsCapacity = FUZZ_dataProducer_uint32Range(producer, 0, 2 * ZSTD_sequenceBound(size)); + ZSTD_Sequence* seqs = (ZSTD_Sequence*)FUZZ_malloc(sizeof(ZSTD_Sequence) * seqsCapacity); + FUZZ_ASSERT(seqsCapacity == 0 || seqs); + + FUZZ_setRandomParameters(cctx, size, producer); + FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetCBlockSize, 0)); + FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 0)); + + const size_t nbSeqs = ZSTD_generateSequences(cctx, seqs, seqsCapacity, data, size); + if (ZSTD_isError(nbSeqs)) { + /* Allowed to error if the destination is too small */ + if (ZSTD_getErrorCode(nbSeqs) == ZSTD_error_dstSize_tooSmall) { + FUZZ_ASSERT(seqsCapacity < ZSTD_sequenceBound(size)); + } + } else { + /* Ensure we round trip with and without block delimiters*/ + + FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters)); + testRoundTrip(cctx, seqs, nbSeqs, data, size); + + const size_t nbMergedSeqs = ZSTD_mergeBlockDelimiters(seqs, nbSeqs); + FUZZ_ASSERT(nbMergedSeqs <= nbSeqs); + FUZZ_ZASSERT(ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only)); + FUZZ_ZASSERT(ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockDelimiters, ZSTD_sf_noBlockDelimiters)); + testRoundTrip(cctx, seqs, nbMergedSeqs, data, size); + } + + free(seqs); + ZSTD_freeCCtx(cctx); + FUZZ_dataProducer_free(producer); + return 0; +} diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 093492181..f7bdae90e 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3701,6 +3701,31 @@ static int basicUnitTests(U32 const seed, double compressibility) } DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : ZSTD_generateSequences too small output buffer : ", testNb++); + { + const size_t seqsCapacity = 10; + const size_t srcSize = 150 KB; + const BYTE* src = (BYTE*)CNBuffer; + + ZSTD_CCtx* const cctx = ZSTD_createCCtx(); + ZSTD_Sequence* const seqs = (ZSTD_Sequence*)malloc(seqsCapacity * sizeof(ZSTD_Sequence)); + + if (seqs == NULL) goto _output_error; + if (cctx == NULL) goto _output_error; + /* Populate src with random data */ + RDG_genBuffer(CNBuffer, srcSize, compressibility, 0.5, seed); + + /* Test with block delimiters roundtrip */ + { + size_t const seqsSize = ZSTD_generateSequences(cctx, seqs, seqsCapacity, src, srcSize); + if (!ZSTD_isError(seqsSize)) goto _output_error; + } + + ZSTD_freeCCtx(cctx); + free(seqs); + } + DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : ZSTD_getSequences followed by ZSTD_compressSequences : ", testNb++); { const size_t srcSize = 500 KB; From dc1f7b560b23f5bd50a0fcddd677007c9c76ec0b Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Thu, 21 Mar 2024 15:16:38 -0400 Subject: [PATCH 286/937] fix -Werror=pointer-arith in fuzzers (#3983) --- tests/fuzz/decompress_cross_format.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/fuzz/decompress_cross_format.c b/tests/fuzz/decompress_cross_format.c index 78461e697..da10702a8 100644 --- a/tests/fuzz/decompress_cross_format.c +++ b/tests/fuzz/decompress_cross_format.c @@ -27,15 +27,15 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) // The rest will be interpreted as magicless compressed data. FUZZ_dataProducer_t *producer = FUZZ_dataProducer_create(src, size); size_t magiclessSize = FUZZ_dataProducer_reserveDataPrefix(producer); - const void* const magiclessSrc = src; + const uint8_t* const magiclessSrc = src; size_t const dstSize = FUZZ_dataProducer_uint32Range(producer, 0, 10 * size); - void* const standardDst = FUZZ_malloc(dstSize); - void* const magiclessDst = FUZZ_malloc(dstSize); + uint8_t* const standardDst = (uint8_t*)FUZZ_malloc(dstSize); + uint8_t* const magiclessDst = (uint8_t*)FUZZ_malloc(dstSize); // Create standard-format src from magicless-format src const uint32_t zstd_magic = ZSTD_MAGICNUMBER; size_t standardSize = sizeof(zstd_magic) + magiclessSize; - void* const standardSrc = FUZZ_malloc(standardSize); + uint8_t* const standardSrc = (uint8_t*)FUZZ_malloc(standardSize); memcpy(standardSrc, &zstd_magic, sizeof(zstd_magic)); // assume fuzzing on little-endian machine memcpy(standardSrc + sizeof(zstd_magic), magiclessSrc, magiclessSize); From 273d1279cab66ac9bccc862da17e35ee547d7610 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 21 Mar 2024 13:25:48 -0700 Subject: [PATCH 287/937] try to silence some scorecard warnings --- .github/workflows/commit.yml | 1 + .github/workflows/nightly.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 5fc8cb1fd..25d8c52f9 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -3,6 +3,7 @@ on: push: branches: - dev +permissions: read-all jobs: short-tests-0: runs-on: ubuntu-latest diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 9206a07fd..704e78922 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -7,6 +7,7 @@ on: - release - dev - master +permissions: read-all jobs: regression-test: runs-on: ubuntu-latest From 65ab6c267e74eb715f383763d8b9898c780ed5ab Mon Sep 17 00:00:00 2001 From: ManuelBlanc Date: Sat, 23 Mar 2024 08:44:52 -0400 Subject: [PATCH 288/937] Use vswhere to find MSBuild; add VS2022 support See: https://github.com/microsoft/vswhere/wiki/Find-MSBuild --- build/VS_scripts/build.generic.cmd | 34 ++++++++++++------------------ 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/build/VS_scripts/build.generic.cmd b/build/VS_scripts/build.generic.cmd index b24e6ed4b..d9a8b1602 100644 --- a/build/VS_scripts/build.generic.cmd +++ b/build/VS_scripts/build.generic.cmd @@ -2,7 +2,7 @@ IF "%1%" == "" GOTO display_help -SETLOCAL +SETLOCAL ENABLEDELAYEDEXPANSION SET msbuild_version=%1 @@ -29,29 +29,23 @@ EXIT /B 1 :build SET msbuild="%windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" -SET msbuild_vs2017community="%programfiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe" -SET msbuild_vs2017professional="%programfiles(x86)%\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe" -SET msbuild_vs2017enterprise="%programfiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe" IF %msbuild_version% == VS2013 SET msbuild="%programfiles(x86)%\MSBuild\12.0\Bin\MSBuild.exe" IF %msbuild_version% == VS2015 SET msbuild="%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" -IF %msbuild_version% == VS2017Community SET msbuild=%msbuild_vs2017community% -IF %msbuild_version% == VS2017Professional SET msbuild=%msbuild_vs2017professional% -IF %msbuild_version% == VS2017Enterprise SET msbuild=%msbuild_vs2017enterprise% -IF %msbuild_version% == VS2017 ( - IF EXIST %msbuild_vs2017community% SET msbuild=%msbuild_vs2017community% - IF EXIST %msbuild_vs2017professional% SET msbuild=%msbuild_vs2017professional% - IF EXIST %msbuild_vs2017enterprise% SET msbuild=%msbuild_vs2017enterprise% -) +IF %msbuild_version% == VS2017 SET vswhere_version=[15,16) +IF %msbuild_version% == VS2017Community SET vswhere_version=[15,16) & SET vswhere_products=Community +IF %msbuild_version% == VS2017Enterprise SET vswhere_version=[15,16) & SET vswhere_products=Enterprise +IF %msbuild_version% == VS2017Professional SET vswhere_version=[15,16) & SET vswhere_products=Professional +IF %msbuild_version% == VS2019 SET vswhere_version=[16,17) +IF %msbuild_version% == VS2022 SET vswhere_version=[17,18) +REM Add the next Visual Studio version here. -:: VS2019 -SET msbuild_vs2019community="%programfiles(x86)%\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe" -SET msbuild_vs2019professional="%programfiles(x86)%\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MSBuild.exe" -SET msbuild_vs2019enterprise="%programfiles(x86)%\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe" -IF %msbuild_version% == VS2019 ( - IF EXIST %msbuild_vs2019community% SET msbuild=%msbuild_vs2019community% - IF EXIST %msbuild_vs2019professional% SET msbuild=%msbuild_vs2019professional% - IF EXIST %msbuild_vs2019enterprise% SET msbuild=%msbuild_vs2019enterprise% +IF NOT DEFINED vswhere_version GOTO skip_vswhere +IF NOT DEFINED vswhere_products SET vswhere_products=* +SET vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +FOR /F "USEBACKQ TOKENS=*" %%F IN (`%vswhere% -utf8 -property installationPath -products !vswhere_products! -version !vswhere_version!`) DO ( + SET msbuild="%%F\MSBuild\Current\Bin\MSBuild.exe" ) +:skip_vswhere SET project="%~p0\..\VS2010\zstd.sln" From 9c442d6fc28e55e5379598d18082f8a31dd4931b Mon Sep 17 00:00:00 2001 From: ManuelBlanc Date: Sat, 23 Mar 2024 18:34:07 -0400 Subject: [PATCH 289/937] Improve MSBuild search; add latest option --- build/VS_scripts/build.generic.cmd | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/build/VS_scripts/build.generic.cmd b/build/VS_scripts/build.generic.cmd index d9a8b1602..6597d79ca 100644 --- a/build/VS_scripts/build.generic.cmd +++ b/build/VS_scripts/build.generic.cmd @@ -19,7 +19,7 @@ GOTO build :display_help echo Syntax: build.generic.cmd msbuild_version msbuild_platform msbuild_configuration msbuild_toolset -echo msbuild_version: VS installed version (VS2012, VS2013, VS2015, VS2017, VS2019, ...) +echo msbuild_version: VS installed version (latest, VS2012, VS2013, VS2015, VS2017, VS2019, ...) echo msbuild_platform: Platform (x64 or Win32) echo msbuild_configuration: VS configuration (Release or Debug) echo msbuild_toolset: Platform Toolset (v100, v110, v120, v140, v141, v142, ...) @@ -31,19 +31,19 @@ EXIT /B 1 SET msbuild="%windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" IF %msbuild_version% == VS2013 SET msbuild="%programfiles(x86)%\MSBuild\12.0\Bin\MSBuild.exe" IF %msbuild_version% == VS2015 SET msbuild="%programfiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe" -IF %msbuild_version% == VS2017 SET vswhere_version=[15,16) -IF %msbuild_version% == VS2017Community SET vswhere_version=[15,16) & SET vswhere_products=Community -IF %msbuild_version% == VS2017Enterprise SET vswhere_version=[15,16) & SET vswhere_products=Enterprise -IF %msbuild_version% == VS2017Professional SET vswhere_version=[15,16) & SET vswhere_products=Professional -IF %msbuild_version% == VS2019 SET vswhere_version=[16,17) -IF %msbuild_version% == VS2022 SET vswhere_version=[17,18) -REM Add the next Visual Studio version here. +IF %msbuild_version% == VS2017 SET vswhere_params=-version [15,16) -products * +IF %msbuild_version% == VS2017Community SET vswhere_params=-version [15,16) -products Community +IF %msbuild_version% == VS2017Enterprise SET vswhere_params=-version [15,16) -products Enterprise +IF %msbuild_version% == VS2017Professional SET vswhere_params=-version [15,16) -products Professional +IF %msbuild_version% == VS2019 SET vswhere_params=-version [16,17) -products * +IF %msbuild_version% == VS2022 SET vswhere_params=-version [17,18) -products * +REM Add the next Visual Studio version here. +IF %msbuild_version% == latest SET vswhere_params=-latest -products * -IF NOT DEFINED vswhere_version GOTO skip_vswhere -IF NOT DEFINED vswhere_products SET vswhere_products=* +IF NOT DEFINED vswhere_params GOTO skip_vswhere SET vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -FOR /F "USEBACKQ TOKENS=*" %%F IN (`%vswhere% -utf8 -property installationPath -products !vswhere_products! -version !vswhere_version!`) DO ( - SET msbuild="%%F\MSBuild\Current\Bin\MSBuild.exe" +FOR /F "USEBACKQ TOKENS=*" %%F IN (`%vswhere% !vswhere_params! -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe`) DO ( + SET msbuild="%%F" ) :skip_vswhere From 101e601c793e9d4dbdffaf05331774bca2aa12be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Mar 2024 05:31:42 +0000 Subject: [PATCH 290/937] Bump github/codeql-action from 3.24.7 to 3.24.9 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.7 to 3.24.9. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/3ab4101902695724f9365a384f86c1074d94e18c...1b1aada464948af03b950897e5eb522f92603cc2) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index a5d5f02a3..e91461280 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@3ab4101902695724f9365a384f86c1074d94e18c # tag=v3.24.7 + uses: github/codeql-action/upload-sarif@1b1aada464948af03b950897e5eb522f92603cc2 # tag=v3.24.9 with: sarif_file: results.sarif From 81a5e5d4384342c0312198f4db35b8cdabc30d96 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Tue, 26 Mar 2024 10:01:19 -0700 Subject: [PATCH 291/937] [fuzz] Turn off -Werror by default This was causing OSS-Fuzz errors, due to compiler differences. * Fix the issue * Also turn off -Werror so we don't fail fuzzer builds for warnings * Turn on -Werror in our CI --- Makefile | 4 ++-- tests/fuzz/fuzz.py | 1 - tests/fuzz/sequence_compression_api.c | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 11eca19ce..b2d985feb 100644 --- a/Makefile +++ b/Makefile @@ -293,10 +293,10 @@ regressiontest: $(MAKE) -C $(FUZZDIR) regressiontest uasanregressiontest: - $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=address,undefined" CXXFLAGS="-O3 -fsanitize=address,undefined" + $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=address,undefined -Werror" CXXFLAGS="-O3 -fsanitize=address,undefined -Werror" msanregressiontest: - $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=memory" CXXFLAGS="-O3 -fsanitize=memory" + $(MAKE) -C $(FUZZDIR) regressiontest CC=clang CXX=clang++ CFLAGS="-O3 -fsanitize=memory -Werror" CXXFLAGS="-O3 -fsanitize=memory -Werror" update_regressionResults : REGRESS_RESULTS_DIR := /tmp/regress_results_dir/ update_regressionResults: diff --git a/tests/fuzz/fuzz.py b/tests/fuzz/fuzz.py index d59df9261..492be3486 100755 --- a/tests/fuzz/fuzz.py +++ b/tests/fuzz/fuzz.py @@ -408,7 +408,6 @@ def build(args): mflags = shlex.split(args.mflags) # Flags to be added to both cflags and cxxflags common_flags = [ - '-Werror', '-Wno-error=declaration-after-statement', '-Wno-error=c++-compat', '-Wno-error=deprecated' # C files are sometimes compiled with CXX diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c index ec0106c18..3c60f42c6 100644 --- a/tests/fuzz/sequence_compression_api.c +++ b/tests/fuzz/sequence_compression_api.c @@ -127,7 +127,7 @@ static size_t decodeSequences(void* dst, size_t nbSequences, FUZZ_ASSERT(litPtr <= litEnd); if (mode == ZSTD_sf_noBlockDelimiters) { const uint32_t lastLLSize = (uint32_t)(litEnd - litPtr); - if (lastLLSize <= oend - op) { + if (lastLLSize <= (uint32_t)(oend - op)) { memcpy(op, litPtr, lastLLSize); generatedSrcBufferSize += lastLLSize; } } From 103a85e6f64f305684db354a0eb9a10d5c586d5c Mon Sep 17 00:00:00 2001 From: Po-Chuan Hsieh Date: Wed, 27 Mar 2024 20:53:52 +0800 Subject: [PATCH 292/937] Use md5sum rather than gmd5sum for FreeBSD Reference: https://man.freebsd.org/cgi/man.cgi?query=md5sum --- lib/libzstd.mk | 2 -- tests/cli-tests/common/platform.sh | 1 - tests/playTests.sh | 1 - 3 files changed, 4 deletions(-) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index a308a6ef6..14b3b11d6 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -213,8 +213,6 @@ ifeq ($(UNAME), Darwin) ifeq ($(shell md5 < /dev/null > /dev/null; echo $$?), 0) HASH ?= md5 endif -else ifeq ($(UNAME), FreeBSD) - HASH ?= gmd5sum else ifeq ($(UNAME), NetBSD) HASH ?= md5 -n else ifeq ($(UNAME), OpenBSD) diff --git a/tests/cli-tests/common/platform.sh b/tests/cli-tests/common/platform.sh index 6eb45eab9..a07f229dc 100644 --- a/tests/cli-tests/common/platform.sh +++ b/tests/cli-tests/common/platform.sh @@ -18,7 +18,6 @@ esac case "$UNAME" in Darwin) MD5SUM="md5 -r" ;; - FreeBSD) MD5SUM="gmd5sum" ;; NetBSD) MD5SUM="md5 -n" ;; OpenBSD) MD5SUM="md5" ;; *) MD5SUM="md5sum" ;; diff --git a/tests/playTests.sh b/tests/playTests.sh index e2a0694f5..026490051 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -123,7 +123,6 @@ esac case "$UNAME" in Darwin) MD5SUM="md5 -r" ;; - FreeBSD) MD5SUM="gmd5sum" ;; NetBSD) MD5SUM="md5 -n" ;; OpenBSD) MD5SUM="md5" ;; *) MD5SUM="md5sum" ;; From ebf24b7b77ed3b4430e7dd3ef45104d05d3585a6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 27 Mar 2024 16:10:15 -0700 Subject: [PATCH 293/937] fix nodejs deprecation warning by updating msys2 action --- .github/workflows/windows-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 52bc90a49..60c163123 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -24,7 +24,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3 - - uses: msys2/setup-msys2@5beef6d11f48bba68b9eb503e3adc60b23c0cc36 # tag=v2 + - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0 with: msystem: ${{ matrix.msystem }} install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc From e0ee0fccf8c591465be4c3f4872ef550e7939f73 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 27 Mar 2024 18:19:31 -0700 Subject: [PATCH 294/937] updated benchmarks for v1.5.6 --- README.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0f7478e10..54dfd4065 100644 --- a/README.md +++ b/README.md @@ -29,10 +29,10 @@ a list of known ports and bindings is provided on [Zstandard homepage](https://f ## Benchmarks For reference, several fast compression algorithms were tested and compared -on a desktop running Ubuntu 20.04 (`Linux 5.11.0-41-generic`), -with a Core i7-9700K CPU @ 4.9GHz, +on a desktop featuring a Core i7-9700K CPU @ 4.9GHz +and running Ubuntu 20.04 (`Linux ubu20 5.15.0-101-generic`), using [lzbench], an open-source in-memory benchmark by @inikep -compiled with [gcc] 9.3.0, +compiled with [gcc] 9.4.0, on the [Silesia compression corpus]. [lzbench]: https://github.com/inikep/lzbench @@ -41,24 +41,23 @@ on the [Silesia compression corpus]. | Compressor name | Ratio | Compression| Decompress.| | --------------- | ------| -----------| ---------- | -| **zstd 1.5.1 -1** | 2.887 | 530 MB/s | 1700 MB/s | +| **zstd 1.5.6 -1** | 2.887 | 510 MB/s | 1580 MB/s | | [zlib] 1.2.11 -1 | 2.743 | 95 MB/s | 400 MB/s | -| brotli 1.0.9 -0 | 2.702 | 395 MB/s | 450 MB/s | -| **zstd 1.5.1 --fast=1** | 2.437 | 600 MB/s | 2150 MB/s | -| **zstd 1.5.1 --fast=3** | 2.239 | 670 MB/s | 2250 MB/s | -| quicklz 1.5.0 -1 | 2.238 | 540 MB/s | 760 MB/s | -| **zstd 1.5.1 --fast=4** | 2.148 | 710 MB/s | 2300 MB/s | -| lzo1x 2.10 -1 | 2.106 | 660 MB/s | 845 MB/s | -| [lz4] 1.9.3 | 2.101 | 740 MB/s | 4500 MB/s | -| lzf 3.6 -1 | 2.077 | 410 MB/s | 830 MB/s | -| snappy 1.1.9 | 2.073 | 550 MB/s | 1750 MB/s | +| brotli 1.0.9 -0 | 2.702 | 395 MB/s | 430 MB/s | +| **zstd 1.5.6 --fast=1** | 2.437 | 545 MB/s | 1890 MB/s | +| **zstd 1.5.6 --fast=3** | 2.239 | 650 MB/s | 2000 MB/s | +| quicklz 1.5.0 -1 | 2.238 | 525 MB/s | 750 MB/s | +| lzo1x 2.10 -1 | 2.106 | 650 MB/s | 825 MB/s | +| [lz4] 1.9.4 | 2.101 | 700 MB/s | 4000 MB/s | +| lzf 3.6 -1 | 2.077 | 420 MB/s | 830 MB/s | +| snappy 1.1.9 | 2.073 | 530 MB/s | 1660 MB/s | [zlib]: https://www.zlib.net/ [lz4]: https://lz4.github.io/lz4/ The negative compression levels, specified with `--fast=#`, offer faster compression and decompression speed -at the cost of compression ratio (compared to level 1). +at the cost of compression ratio. Zstd can also offer stronger compression ratios at the cost of compression speed. Speed vs Compression trade-off is configurable by small increments. From 72c16b187d27016b7634f5c6b7290e7c66ba44b3 Mon Sep 17 00:00:00 2001 From: Yuriy Chernyshov Date: Thu, 28 Mar 2024 11:54:53 +0100 Subject: [PATCH 295/937] Fix building on windows-x86 if clang already includes [D101338](https://reviews.llvm.org/D101338) landed in 2021, so clang16 should have it --- lib/common/cpu.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/cpu.h b/lib/common/cpu.h index 0e684d9ad..d9cdf8feb 100644 --- a/lib/common/cpu.h +++ b/lib/common/cpu.h @@ -35,7 +35,7 @@ MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) { U32 f7b = 0; U32 f7c = 0; #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) -#if !defined(__clang__) +#if !defined(__clang__) || __clang_major__ >= 16 int reg[4]; __cpuid((int*)reg, 0); { From a2f145f059150744132639cf30a918ceadac9b77 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 1 Apr 2024 11:12:26 -0700 Subject: [PATCH 296/937] decompression errors always display the full origin filename instead of the truncated size-limited version. --- programs/fileio.c | 27 ++++++++++----------------- programs/fileio_asyncio.c | 2 +- 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index e3012a716..c6af36fbd 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -1494,7 +1494,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, int compressionLevel, U64* readsize) { cRess_t const ress = *ressPtr; - IOJob_t *writeJob = AIO_WritePool_acquireJob(ressPtr->writeCtx); + IOJob_t* writeJob = AIO_WritePool_acquireJob(ressPtr->writeCtx); U64 compressedfilesize = 0; ZSTD_EndDirective directive = ZSTD_e_continue; @@ -1526,8 +1526,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, CHECK( ZSTD_CCtx_setPledgedSrcSize(ress.cctx, prefs->streamSrcSize) ); } - { - int windowLog; + { int windowLog; UTIL_HumanReadableSize_t windowSize; CHECK(ZSTD_CCtx_getParameter(ress.cctx, ZSTD_c_windowLog, &windowLog)); if (windowLog == 0) { @@ -1542,7 +1541,6 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, windowSize = UTIL_makeHumanReadableSize(MAX(1ULL, MIN(1ULL << windowLog, pledgedSrcSize))); DISPLAYLEVEL(4, "Decompression will require %.*f%s of memory\n", windowSize.precision, windowSize.value, windowSize.suffix); } - (void)srcFileName; /* Main compression loop */ do { @@ -2439,12 +2437,14 @@ FIO_decompressZstdFrame(FIO_ctx_t* const fCtx, dRess_t* ress, U64 alreadyDecoded) /* for multi-frames streams */ { U64 frameSize = 0; - IOJob_t *writeJob = AIO_WritePool_acquireJob(ress->writeCtx); + const char* srcFName20 = srcFileName; + IOJob_t* writeJob = AIO_WritePool_acquireJob(ress->writeCtx); + assert(writeJob); /* display last 20 characters only when not --verbose */ { size_t const srcFileLength = strlen(srcFileName); if ((srcFileLength>20) && (g_display_prefs.displayLevel<3)) - srcFileName += srcFileLength-20; + srcFName20 += srcFileLength-20; } ZSTD_DCtx_reset(ress->dctx, ZSTD_reset_session_only); @@ -2471,19 +2471,12 @@ FIO_decompressZstdFrame(FIO_ctx_t* const fCtx, dRess_t* ress, AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); frameSize += outBuff.pos; if (fCtx->nbFilesTotal > 1) { - size_t srcFileNameSize = strlen(srcFileName); - if (srcFileNameSize > 18) { - const char* truncatedSrcFileName = srcFileName + srcFileNameSize - 15; - DISPLAYUPDATE_PROGRESS( - "\rDecompress: %2u/%2u files. Current: ...%s : %.*f%s... ", - fCtx->currFileIdx+1, fCtx->nbFilesTotal, truncatedSrcFileName, hrs.precision, hrs.value, hrs.suffix); - } else { - DISPLAYUPDATE_PROGRESS("\rDecompress: %2u/%2u files. Current: %s : %.*f%s... ", - fCtx->currFileIdx+1, fCtx->nbFilesTotal, srcFileName, hrs.precision, hrs.value, hrs.suffix); - } + DISPLAYUPDATE_PROGRESS( + "\rDecompress: %2u/%2u files. Current: %s : %.*f%s... ", + fCtx->currFileIdx+1, fCtx->nbFilesTotal, srcFName20, hrs.precision, hrs.value, hrs.suffix); } else { DISPLAYUPDATE_PROGRESS("\r%-20.20s : %.*f%s... ", - srcFileName, hrs.precision, hrs.value, hrs.suffix); + srcFName20, hrs.precision, hrs.value, hrs.suffix); } AIO_ReadPool_consumeBytes(ress->readCtx, inBuff.pos); diff --git a/programs/fileio_asyncio.c b/programs/fileio_asyncio.c index ae6db69e0..42a472016 100644 --- a/programs/fileio_asyncio.c +++ b/programs/fileio_asyncio.c @@ -268,7 +268,7 @@ static void AIO_IOPool_destroy(IOPoolCtx_t* ctx) { /* AIO_IOPool_acquireJob: * Returns an available io job to be used for a future io. */ static IOJob_t* AIO_IOPool_acquireJob(IOPoolCtx_t* ctx) { - IOJob_t *job; + IOJob_t* job; assert(ctx->file != NULL || ctx->prefs->testMode); AIO_IOPool_lockJobsMutex(ctx); assert(ctx->availableJobsCount > 0); From 8cff66f2f53fa41b8f5be65996600d88fbbe1a98 Mon Sep 17 00:00:00 2001 From: elasota <1137273+elasota@users.noreply.github.com> Date: Mon, 1 Apr 2024 20:08:42 -0400 Subject: [PATCH 297/937] Remove text specifying probability overflow as invalid, the variable-size value encoding scheme makes this impossible. --- doc/zstd_compression_format.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 7955dae4a..5cae85524 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -1125,8 +1125,6 @@ If it is a 3, another 2-bits repeat flag follows, and so on. When last symbol reaches cumulated total of `1 << Accuracy_Log`, decoding is complete. -If the last symbol makes cumulated total go above `1 << Accuracy_Log`, -distribution is considered corrupted. If this process results in a non-zero probability for a value outside of the valid range of values that the FSE table is defined for, even if that value is not used, then the data is considered corrupted. From c54f4783d0cd51d8aad1c0a4fd9fe564d461aae4 Mon Sep 17 00:00:00 2001 From: elasota <1137273+elasota@users.noreply.github.com> Date: Mon, 1 Apr 2024 20:13:18 -0400 Subject: [PATCH 298/937] Specify that decoders may reject non-zero probabilities for larger offset codes than supported by the implementation --- doc/zstd_compression_format.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 7955dae4a..8a60e56df 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -1129,7 +1129,10 @@ If the last symbol makes cumulated total go above `1 << Accuracy_Log`, distribution is considered corrupted. If this process results in a non-zero probability for a value outside of the valid range of values that the FSE table is defined for, even if that value is -not used, then the data is considered corrupted. +not used, then the data is considered corrupted. In the case of offset codes, +a decoder implementation may reject a frame containing a non-zero probability +for an offset code larger than the largest offset code supported by the decoder +implementation. Then the decoder can tell how many bytes were used in this process, and how many symbols are present. From fd5f8106a58601a963ee816e6a57aa7c61fafc53 Mon Sep 17 00:00:00 2001 From: BadWolf Date: Sat, 6 Apr 2024 00:05:58 +0200 Subject: [PATCH 299/937] fix missing include folder for resource compiler --- build/cmake/lib/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 5d514ccb2..43b14d175 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -118,7 +118,7 @@ endmacro () # Define directories containing the library's public headers set(PUBLIC_INCLUDE_DIRS ${LIBRARY_DIR}) - +set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} /I ${LIBRARY_DIR}") # Split project to static and shared libraries build set(library_targets) if (ZSTD_BUILD_SHARED) From 71def598906637866f1b165bc9113defdd36983c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Pawe=C5=82=20Stefaniak?= <3462925+pstef@users.noreply.github.com> Date: Sun, 7 Apr 2024 13:04:26 +0200 Subject: [PATCH 300/937] Fix zlibWrapper build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Just after a clone I'm getting this: ~/zstd/zlibWrapper$ cc -c zstd_zlibwrapper.o gz*.c -lz -lzstd -DSTDC gzwrite.c: In function ‘gz_write’: gzwrite.c:226:43: error: ‘z_uInt’ undeclared (first use in this function); did you mean ‘uInt’? 226 | state.state->strm.avail_in = (z_uInt)n; | ^~~~~~ | uInt gzwrite.c:226:43: note: each undeclared identifier is reported only once for each function it appears in gzwrite.c:226:50: error: expected ‘;’ before ‘n’ 226 | state.state->strm.avail_in = (z_uInt)n; | ^ | ; z_uInt is never used directly, zconf.h redefines uInt to z_uInt under the condition that Z_PREFIX is set. All examples use uInt, and the type of avail_in is also uInt. In this commit I modify the cast to refer to the same type as the type of lvalue. Arguably, the real fix here is to handle possible overflows, but that's beyond the scope of this commit. --- zlibWrapper/gzwrite.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zlibWrapper/gzwrite.c b/zlibWrapper/gzwrite.c index 81da15314..67f5eda6c 100644 --- a/zlibWrapper/gzwrite.c +++ b/zlibWrapper/gzwrite.c @@ -223,7 +223,7 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) { z_size_t n = (unsigned)-1; if (n > len) n = len; - state.state->strm.avail_in = (z_uInt)n; + state.state->strm.avail_in = (uInt)n; state.state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; From 7968c661af8ec976782ddcfde3ea609d9353a0cf Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Apr 2024 05:47:58 +0000 Subject: [PATCH 301/937] Bump github/codeql-action from 3.24.9 to 3.24.10 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.9 to 3.24.10. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/1b1aada464948af03b950897e5eb522f92603cc2...4355270be187e1b672a7a1c7c7bae5afdc1ab94a) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index e91461280..7a7750026 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@1b1aada464948af03b950897e5eb522f92603cc2 # tag=v3.24.9 + uses: github/codeql-action/upload-sarif@4355270be187e1b672a7a1c7c7bae5afdc1ab94a # tag=v3.24.10 with: sarif_file: results.sarif From f1f1ae369a4cefd3474b3528e8d1847b18750605 Mon Sep 17 00:00:00 2001 From: Christian Marangi Date: Sat, 6 Apr 2024 14:41:54 +0200 Subject: [PATCH 302/937] Provide variant pkg-config file for multi-threaded static lib Multi-threaded static library require -pthread to correctly link and works. The pkg-config we provide tho only works with dynamic multi-threaded library and won't provide the correct libs and cflags values if lib-mt is used. To handle this, introduce an env variable MT to permit advanced user to install and generate a correct pkg-config file for lib-mt or detect if lib-mt target is called. With MT env set on calling make install-pc, libzstd.pc.in is a pkg-config file for a multi-threaded static library. On calling make lib-mt, a libzstd.pc is generated for a multi-threaded static library as it's what asked by the user by forcing it. libzstd.pc is changed to PHONY to force regeneration of it on calling lib targets or install-pc to handle case where the same directory is used for mixed compilation. This was notice while migrating from meson to make build system where meson generates a correct .pc file while make doesn't. Signed-off-by: Christian Marangi --- lib/Makefile | 20 +++++++++++++++++++- lib/README.md | 4 ++++ lib/libzstd.pc.in | 4 ++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/lib/Makefile b/lib/Makefile index 8bfdade9f..57097ce3f 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -63,6 +63,8 @@ CPPFLAGS_DYNLIB += -DZSTD_MULTITHREAD # dynamic library build defaults to multi LDFLAGS_DYNLIB += -pthread CPPFLAGS_STATICLIB += # static library build defaults to single-threaded +# pkg-config Libs.private points to LDFLAGS_DYNLIB +PCLIB := $(LDFLAGS_DYNLIB) ifeq ($(findstring GCC,$(CCVER)),GCC) decompress/zstd_decompress_block.o : CFLAGS+=-fno-tree-vectorize @@ -186,12 +188,15 @@ lib : libzstd.a libzstd %-mt : CPPFLAGS_DYNLIB := -DZSTD_MULTITHREAD %-mt : CPPFLAGS_STATICLIB := -DZSTD_MULTITHREAD %-mt : LDFLAGS_DYNLIB := -pthread +%-mt : PCLIB := +%-mt : PCMTLIB := $(LDFLAGS_DYNLIB) %-mt : % @echo multi-threaded build completed %-nomt : CPPFLAGS_DYNLIB := %-nomt : LDFLAGS_DYNLIB := %-nomt : CPPFLAGS_STATICLIB := +%-nomt : PCLIB := %-nomt : % @echo single-threaded build completed @@ -292,6 +297,14 @@ PCLIBPREFIX := $(if $(findstring $(LIBDIR),$(PCLIBDIR)),,$${exec_prefix}) # to PREFIX, rather than as a resolved value. PCEXEC_PREFIX := $(if $(HAS_EXPLICIT_EXEC_PREFIX),$(EXEC_PREFIX),$${prefix}) + +ifneq ($(MT),) + PCLIB := + PCMTLIB := $(LDFLAGS_DYNLIB) +else + PCLIB := $(LDFLAGS_DYNLIB) +endif + ifneq (,$(filter $(UNAME),FreeBSD NetBSD DragonFly)) PKGCONFIGDIR ?= $(PREFIX)/libdata/pkgconfig else @@ -308,6 +321,10 @@ INSTALL_PROGRAM ?= $(INSTALL) INSTALL_DATA ?= $(INSTALL) -m 644 +# pkg-config library define. +# For static single-threaded library declare -pthread in Libs.private +# For static multi-threaded library declare -pthread in Libs and Cflags +.PHONY: libzstd.pc libzstd.pc: libzstd.pc.in @echo creating pkgconfig @sed \ @@ -316,7 +333,8 @@ libzstd.pc: libzstd.pc.in -e 's|@INCLUDEDIR@|$(PCINCPREFIX)$(PCINCDIR)|' \ -e 's|@LIBDIR@|$(PCLIBPREFIX)$(PCLIBDIR)|' \ -e 's|@VERSION@|$(VERSION)|' \ - -e 's|@LIBS_PRIVATE@|$(LDFLAGS_DYNLIB)|' \ + -e 's|@LIBS_MT@|$(PCMTLIB)|' \ + -e 's|@LIBS_PRIVATE@|$(PCLIB)|' \ $< >$@ .PHONY: install diff --git a/lib/README.md b/lib/README.md index a560f06ca..0f6c64745 100644 --- a/lib/README.md +++ b/lib/README.md @@ -27,12 +27,16 @@ Enabling multithreading requires 2 conditions : For convenience, we provide a build target to generate multi and single threaded libraries: - Force enable multithreading on both dynamic and static libraries by appending `-mt` to the target, e.g. `make lib-mt`. + Note that the `.pc` generated on calling `make lib-mt` will already include the require Libs and Cflags. - Force disable multithreading on both dynamic and static libraries by appending `-nomt` to the target, e.g. `make lib-nomt`. - By default, as mentioned before, dynamic library is multithreaded, and static library is single-threaded, e.g. `make lib`. When linking a POSIX program with a multithreaded version of `libzstd`, note that it's necessary to invoke the `-pthread` flag during link stage. +The `.pc` generated from `make install` or `make install-pc` always assume a single-threaded static library +is compiled. To correctly generate a `.pc` for the multi-threaded static library, set `MT=1` as ENV variable. + Multithreading capabilities are exposed via the [advanced API defined in `lib/zstd.h`](https://github.com/facebook/zstd/blob/v1.4.3/lib/zstd.h#L351). diff --git a/lib/libzstd.pc.in b/lib/libzstd.pc.in index d5cc0270c..d7b6c8582 100644 --- a/lib/libzstd.pc.in +++ b/lib/libzstd.pc.in @@ -11,6 +11,6 @@ Name: zstd Description: fast lossless compression algorithm library URL: https://facebook.github.io/zstd/ Version: @VERSION@ -Libs: -L${libdir} -lzstd +Libs: -L${libdir} -lzstd @LIBS_MT@ Libs.private: @LIBS_PRIVATE@ -Cflags: -I${includedir} +Cflags: -I${includedir} @LIBS_MT@ From 5be2a8721d527ae349539b459b35fb628467e00d Mon Sep 17 00:00:00 2001 From: Benjamin Gilbert Date: Thu, 7 Mar 2024 21:40:27 +0900 Subject: [PATCH 303/937] meson: don't add -pthread to static linking flags on Windows Meson always returns -pthread in dependency('threads') on non-MSVC compilers. On Windows we use Windows threading primitives, so we don't need this. Avoid adding -pthread to libzstd's link flags, either as a Meson subproject or via pkg-config Libs.private, so the application doesn't inadvertently depend on winpthreads. Add a Meson MinGW cross-compile CI test that checks for this. It turns out that pzstd fails to build in that environment, so have the test skip building contrib for now. --- .github/workflows/dev-short-tests.yml | 44 +++++++++++++++++++++++++++ build/meson/meson.build | 9 ++++-- build/meson/meson_options.txt | 2 +- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 5324b38d9..b8afcb76b 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -237,6 +237,50 @@ jobs: meson test -C builddir/ --print-errorlogs meson install -C builddir --destdir staging/ + meson-mingw-cross-compilation: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Install packages + run: | + sudo apt-get -qqq update + sudo apt-get -y install build-essential python3-pip ninja-build {gcc,g++}-mingw-w64-x86-64 + pip install --pre meson + - name: Build with Meson + run: | + cat > cross.ini < Date: Sat, 13 Apr 2024 02:24:14 +0700 Subject: [PATCH 304/937] fixed memory leaks and almost all undefined behaviour --- doc/educational_decoder/harness.c | 1 + lib/compress/zstd_compress.c | 2 +- lib/decompress/zstd_decompress.c | 2 +- programs/benchfn.c | 2 +- tests/bigdict.c | 11 ++++++++--- tests/paramgrill.c | 1 - tests/regression/result.c | 2 ++ tests/seqgen.c | 2 +- zlibWrapper/examples/minigzip.c | 4 ++-- zlibWrapper/gzwrite.c | 2 ++ 10 files changed, 19 insertions(+), 10 deletions(-) diff --git a/doc/educational_decoder/harness.c b/doc/educational_decoder/harness.c index 12c5a801b..eb79ceacd 100644 --- a/doc/educational_decoder/harness.c +++ b/doc/educational_decoder/harness.c @@ -50,6 +50,7 @@ static buffer_s read_file(const char *path) fclose(f); buffer_s const b = { ptr, size }; + free(ptr); return b; } diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9284e2a48..d17182a46 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2764,7 +2764,7 @@ ZSTD_buildSequencesStatistics( const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; - ZSTD_symbolEncodingTypeStats_t stats; + ZSTD_symbolEncodingTypeStats_t stats = {}; stats.lastCountSize = 0; /* convert length/distances into codes */ diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 2f03cf7b0..658cb2818 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -723,7 +723,7 @@ static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t he static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) { - ZSTD_frameSizeInfo frameSizeInfo; + ZSTD_frameSizeInfo frameSizeInfo = {}; frameSizeInfo.compressedSize = ret; frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; return frameSizeInfo; diff --git a/programs/benchfn.c b/programs/benchfn.c index 3e042cf38..74cd21b20 100644 --- a/programs/benchfn.c +++ b/programs/benchfn.c @@ -91,7 +91,7 @@ static BMK_runOutcome_t BMK_runOutcome_error(size_t errorResult) static BMK_runOutcome_t BMK_setValid_runTime(BMK_runTime_t runTime) { - BMK_runOutcome_t outcome; + BMK_runOutcome_t outcome = {}; outcome.error_tag_never_ever_use_directly = 0; outcome.internal_never_ever_use_directly = runTime; return outcome; diff --git a/tests/bigdict.c b/tests/bigdict.c index ff2bb2d70..748b60e79 100644 --- a/tests/bigdict.c +++ b/tests/bigdict.c @@ -70,12 +70,14 @@ int main(int argc, const char** argv) char* buffer = (char*)malloc(bufferSize); void* out = malloc(outSize); void* roundtrip = malloc(dataSize); + int _exit_code = 0; (void)argc; (void)argv; if (!buffer || !out || !roundtrip || !cctx || !dctx) { fprintf(stderr, "Allocation failure\n"); - return 1; + _exit_code = 1; + goto cleanup; } if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) @@ -119,10 +121,13 @@ int main(int argc, const char** argv) fprintf(stderr, "Success!\n"); + goto cleanup; + +cleanup: free(roundtrip); free(out); free(buffer); - ZSTD_freeDCtx(dctx); ZSTD_freeCCtx(cctx); - return 0; + ZSTD_freeDCtx(dctx); + return _exit_code; } diff --git a/tests/paramgrill.c b/tests/paramgrill.c index 8971c65d6..869e966e0 100644 --- a/tests/paramgrill.c +++ b/tests/paramgrill.c @@ -1273,7 +1273,6 @@ static int createBuffers(buffers_t* buff, const char* const * const fileNamesTab f = fopen(fileNamesTable[n], "rb"); if (f==NULL) { DISPLAY("impossible to open file %s\n", fileNamesTable[n]); - fclose(f); ret = 10; goto _cleanUp; } diff --git a/tests/regression/result.c b/tests/regression/result.c index 8ccb8751e..84a8a044d 100644 --- a/tests/regression/result.c +++ b/tests/regression/result.c @@ -24,5 +24,7 @@ char const* result_get_error_string(result_t result) { return "decompression error"; case result_error_round_trip_error: return "round trip error"; + default: + return "unknown error - " + result_get_error(result); } } diff --git a/tests/seqgen.c b/tests/seqgen.c index 0d8a766c8..efd528baa 100644 --- a/tests/seqgen.c +++ b/tests/seqgen.c @@ -31,7 +31,7 @@ static BYTE SEQ_randByte(unsigned* src) SEQ_stream SEQ_initStream(unsigned seed) { - SEQ_stream stream; + SEQ_stream stream = {}; stream.state = 0; XXH64_reset(&stream.xxh, 0); stream.seed = seed; diff --git a/zlibWrapper/examples/minigzip.c b/zlibWrapper/examples/minigzip.c index 1af815207..a06554212 100644 --- a/zlibWrapper/examples/minigzip.c +++ b/zlibWrapper/examples/minigzip.c @@ -234,7 +234,7 @@ int gzwrite _Z_OF((gzFile, const void *, unsigned)); int gzwrite(gzFile gz, const void *buf, unsigned len) { z_stream *strm; - unsigned char out[BUFLEN]; + unsigned char out[BUFLEN] = 0; if (gz == NULL || !gz->write) return 0; @@ -287,7 +287,7 @@ int gzclose _Z_OF((gzFile)); int gzclose(gzFile gz) { z_stream *strm; - unsigned char out[BUFLEN]; + unsigned char out[BUFLEN] = 0; if (gz == NULL) return Z_STREAM_ERROR; diff --git a/zlibWrapper/gzwrite.c b/zlibWrapper/gzwrite.c index 67f5eda6c..0a89c8d75 100644 --- a/zlibWrapper/gzwrite.c +++ b/zlibWrapper/gzwrite.c @@ -64,6 +64,8 @@ local int gz_init(gz_statep state) { strm->next_out = state.state->out; state.state->x.next = strm->next_out; } + + free(state.state); return 0; } From 4f41631aa4fffffac511d484ad10d603650e0156 Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sat, 13 Apr 2024 02:35:32 +0700 Subject: [PATCH 305/937] fixed ISO C incompatibility --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d17182a46..9284e2a48 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2764,7 +2764,7 @@ ZSTD_buildSequencesStatistics( const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; - ZSTD_symbolEncodingTypeStats_t stats = {}; + ZSTD_symbolEncodingTypeStats_t stats; stats.lastCountSize = 0; /* convert length/distances into codes */ From 01cea2e1e2cf1cafa4b61e1bc8eb85618cf18c76 Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sat, 13 Apr 2024 02:37:13 +0700 Subject: [PATCH 306/937] fixed ISO C incompatibility for good this time... probably --- lib/decompress/zstd_decompress.c | 2 +- programs/benchfn.c | 2 +- tests/seqgen.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 658cb2818..2f03cf7b0 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -723,7 +723,7 @@ static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t he static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret) { - ZSTD_frameSizeInfo frameSizeInfo = {}; + ZSTD_frameSizeInfo frameSizeInfo; frameSizeInfo.compressedSize = ret; frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR; return frameSizeInfo; diff --git a/programs/benchfn.c b/programs/benchfn.c index 74cd21b20..3e042cf38 100644 --- a/programs/benchfn.c +++ b/programs/benchfn.c @@ -91,7 +91,7 @@ static BMK_runOutcome_t BMK_runOutcome_error(size_t errorResult) static BMK_runOutcome_t BMK_setValid_runTime(BMK_runTime_t runTime) { - BMK_runOutcome_t outcome = {}; + BMK_runOutcome_t outcome; outcome.error_tag_never_ever_use_directly = 0; outcome.internal_never_ever_use_directly = runTime; return outcome; diff --git a/tests/seqgen.c b/tests/seqgen.c index efd528baa..0d8a766c8 100644 --- a/tests/seqgen.c +++ b/tests/seqgen.c @@ -31,7 +31,7 @@ static BYTE SEQ_randByte(unsigned* src) SEQ_stream SEQ_initStream(unsigned seed) { - SEQ_stream stream = {}; + SEQ_stream stream; stream.state = 0; XXH64_reset(&stream.xxh, 0); stream.seed = seed; From 75d0f66c879451e20f62f07162a38af2b314262a Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sat, 13 Apr 2024 12:51:20 +0700 Subject: [PATCH 307/937] reverted the addition of free at the gz_init() --- zlibWrapper/gzwrite.c | 1 - 1 file changed, 1 deletion(-) diff --git a/zlibWrapper/gzwrite.c b/zlibWrapper/gzwrite.c index 0a89c8d75..85b776a94 100644 --- a/zlibWrapper/gzwrite.c +++ b/zlibWrapper/gzwrite.c @@ -65,7 +65,6 @@ local int gz_init(gz_statep state) { state.state->x.next = strm->next_out; } - free(state.state); return 0; } From b4ecf724b15f0ab21a996339112680d3f4ba33eb Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sun, 14 Apr 2024 17:45:53 +0700 Subject: [PATCH 308/937] made initialize out char array with all elements set to 0 fixed where i made it to init with just the first one being set to 0 --- zlibWrapper/examples/minigzip.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zlibWrapper/examples/minigzip.c b/zlibWrapper/examples/minigzip.c index a06554212..c4ce5f479 100644 --- a/zlibWrapper/examples/minigzip.c +++ b/zlibWrapper/examples/minigzip.c @@ -234,7 +234,7 @@ int gzwrite _Z_OF((gzFile, const void *, unsigned)); int gzwrite(gzFile gz, const void *buf, unsigned len) { z_stream *strm; - unsigned char out[BUFLEN] = 0; + unsigned char out[BUFLEN] = { 0 }; if (gz == NULL || !gz->write) return 0; From 0b24fc0a113c92c5ba5ec78f7169a2ddfe0d700f Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sun, 14 Apr 2024 17:57:53 +0700 Subject: [PATCH 309/937] init out char array with all members as 0 x2 --- zlibWrapper/examples/minigzip.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zlibWrapper/examples/minigzip.c b/zlibWrapper/examples/minigzip.c index c4ce5f479..ef48d74d2 100644 --- a/zlibWrapper/examples/minigzip.c +++ b/zlibWrapper/examples/minigzip.c @@ -287,7 +287,7 @@ int gzclose _Z_OF((gzFile)); int gzclose(gzFile gz) { z_stream *strm; - unsigned char out[BUFLEN] = 0; + unsigned char out[BUFLEN] = { 0 }; if (gz == NULL) return Z_STREAM_ERROR; From 849b2ad907070c6a46cc4679f4f831eaebacc715 Mon Sep 17 00:00:00 2001 From: Alex Murkoff <413x1nkp@gmail.com> Date: Sun, 14 Apr 2024 20:44:12 +0700 Subject: [PATCH 310/937] removed freeing of the ptr --- doc/educational_decoder/harness.c | 1 - 1 file changed, 1 deletion(-) diff --git a/doc/educational_decoder/harness.c b/doc/educational_decoder/harness.c index eb79ceacd..12c5a801b 100644 --- a/doc/educational_decoder/harness.c +++ b/doc/educational_decoder/harness.c @@ -50,7 +50,6 @@ static buffer_s read_file(const char *path) fclose(f); buffer_s const b = { ptr, size }; - free(ptr); return b; } From ff7a151f2e6c009b657d9f798c2d9962b0e3feb5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 21 Apr 2024 10:44:50 -0700 Subject: [PATCH 311/937] update test name --- tests/Makefile | 10 ++-- tests/largeDictionary.c | 128 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 5 deletions(-) create mode 100644 tests/largeDictionary.c diff --git a/tests/Makefile b/tests/Makefile index ed3692a24..c458b682a 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -224,9 +224,9 @@ roundTripCrash : $(ZSTD_OBJECTS) roundTripCrash.c CLEAN += longmatch longmatch : $(ZSTD_OBJECTS) longmatch.c -CLEAN += bigdict -bigdict: CFLAGS += $(MULTITHREAD) -bigdict: $(ZSTDMT_OBJECTS) $(PRGDIR)/datagen.c bigdict.c +CLEAN += largeDictionary +largeDictionary: CFLAGS += $(MULTITHREAD) +largeDictionary: $(ZSTDMT_OBJECTS) $(PRGDIR)/datagen.c largeDictionary.c CLEAN += invalidDictionaries invalidDictionaries : $(ZSTD_OBJECTS) invalidDictionaries.c @@ -391,8 +391,8 @@ test-zstream32: zstreamtest32 test-longmatch: longmatch $(QEMU_SYS) ./longmatch -test-bigdict: bigdict - $(QEMU_SYS) ./bigdict +test-largeDictionary: largeDictionary + $(QEMU_SYS) ./largeDictionary test-invalidDictionaries: invalidDictionaries $(QEMU_SYS) ./invalidDictionaries diff --git a/tests/largeDictionary.c b/tests/largeDictionary.c new file mode 100644 index 000000000..ff2bb2d70 --- /dev/null +++ b/tests/largeDictionary.c @@ -0,0 +1,128 @@ +/* + * 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. + */ + +#include +#include +#include +#include +#include +#include "datagen.h" +#include "mem.h" +#define ZSTD_STATIC_LINKING_ONLY +#include "zstd.h" + +static int +compress(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx, + void* dst, size_t dstCapacity, + void const* src, size_t srcSize, + void* roundtrip, ZSTD_EndDirective end) +{ + ZSTD_inBuffer in = {src, srcSize, 0}; + ZSTD_outBuffer out = {dst, dstCapacity, 0}; + int ended = 0; + + while (!ended && (in.pos < in.size || out.pos > 0)) { + size_t rc; + out.pos = 0; + rc = ZSTD_compressStream2(cctx, &out, &in, end); + if (ZSTD_isError(rc)) + return 1; + if (end == ZSTD_e_end && rc == 0) + ended = 1; + { + ZSTD_inBuffer rtIn = {dst, out.pos, 0}; + ZSTD_outBuffer rtOut = {roundtrip, srcSize, 0}; + rc = 1; + while (rtIn.pos < rtIn.size || rtOut.pos > 0) { + rtOut.pos = 0; + rc = ZSTD_decompressStream(dctx, &rtOut, &rtIn); + if (ZSTD_isError(rc)) { + fprintf(stderr, "Decompression error: %s\n", ZSTD_getErrorName(rc)); + return 1; + } + if (rc == 0) + break; + } + if (ended && rc != 0) { + fprintf(stderr, "Frame not finished!\n"); + return 1; + } + } + } + + return 0; +} + +int main(int argc, const char** argv) +{ + ZSTD_CCtx* cctx = ZSTD_createCCtx(); + ZSTD_DCtx* dctx = ZSTD_createDCtx(); + const size_t dataSize = (size_t)1 << 30; + const size_t outSize = ZSTD_compressBound(dataSize); + const size_t bufferSize = (size_t)1 << 31; + char* buffer = (char*)malloc(bufferSize); + void* out = malloc(outSize); + void* roundtrip = malloc(dataSize); + (void)argc; + (void)argv; + + if (!buffer || !out || !roundtrip || !cctx || !dctx) { + fprintf(stderr, "Allocation failure\n"); + return 1; + } + + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) + return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) + return 1; + + if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) + return 1; + + RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); + + /* Compress 30 GB */ + { + int i; + for (i = 0; i < 10; ++i) { + fprintf(stderr, "Compressing 1 GB\n"); + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) + return 1; + } + } + fprintf(stderr, "Compressing 1 GB\n"); + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) + return 1; + + fprintf(stderr, "Success!\n"); + + free(roundtrip); + free(out); + free(buffer); + ZSTD_freeDCtx(dctx); + ZSTD_freeCCtx(cctx); + return 0; +} From 68a6d9b9f6ce605010ea1164590e4e015567dee7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 22 Apr 2024 05:20:46 +0000 Subject: [PATCH 312/937] Bump github/codeql-action from 3.24.10 to 3.25.1 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.24.10 to 3.25.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/4355270be187e1b672a7a1c7c7bae5afdc1ab94a...c7f9125735019aa87cfc361530512d50ea439c71) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 7a7750026..e117798ea 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@4355270be187e1b672a7a1c7c7bae5afdc1ab94a # tag=v3.24.10 + uses: github/codeql-action/upload-sarif@c7f9125735019aa87cfc361530512d50ea439c71 # tag=v3.25.1 with: sarif_file: results.sarif From a86f5f3f33f40945c0d1341827fabc6a22338499 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 23 Apr 2024 09:31:35 -0700 Subject: [PATCH 313/937] update documentation of ZSTD_decompressStream() slightly more precise, by recommending to check the return value. fix #4030 --- lib/zstd.h | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 5d1fef8a6..b79f675c3 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -855,7 +855,7 @@ ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); * * A ZSTD_DStream object is required to track streaming operations. * Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources. -* ZSTD_DStream objects can be reused multiple times. +* ZSTD_DStream objects can be re-employed multiple times. * * Use ZSTD_initDStream() to start a new decompression operation. * @return : recommended first input size @@ -865,16 +865,21 @@ ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output); * The function will update both `pos` fields. * If `input.pos < input.size`, some input has not been consumed. * It's up to the caller to present again remaining data. +* * The function tries to flush all data decoded immediately, respecting output buffer size. * If `output.pos < output.size`, decoder has flushed everything it could. -* But if `output.pos == output.size`, there might be some data left within internal buffers., +* +* However, when `output.pos == output.size`, it's more difficult to know. +* If @return > 0, the frame is not complete, meaning +* either there is still some data left to flush within internal buffers, +* or there is more input to read to complete the frame (or both). * In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer. * Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX. * @return : 0 when a frame is completely decoded and fully flushed, * or an error code, which can be tested using ZSTD_isError(), * or any other value > 0, which means there is still some decoding or flushing to do to complete current frame : * the return value is a suggested next input size (just a hint for better latency) -* that will never request more than the remaining frame size. +* that will never request more than the remaining content of the compressed frame. * *******************************************************************************/ typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */ @@ -901,9 +906,10 @@ ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds); * Function will update both input and output `pos` fields exposing current state via these fields: * - `input.pos < input.size`, some input remaining and caller should provide remaining input * on the next call. - * - `output.pos < output.size`, decoder finished and flushed all remaining buffers. - * - `output.pos == output.size`, potentially uncflushed data present in the internal buffers, - * call ZSTD_decompressStream() again to flush remaining data to output. + * - `output.pos < output.size`, decoder flushed internal output buffer. + * - `output.pos == output.size`, unflushed data potentially present in the internal buffers, + * check ZSTD_decompressStream() @return value, + * if > 0, invoke it again to flush remaining data to output. * Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX. * * @return : 0 when a frame is completely decoded and fully flushed, From d7cb47036cb78b3681aee4725107381a1b69abfc Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Fri, 26 Apr 2024 13:48:49 -0700 Subject: [PATCH 314/937] Make zstd.h compatible with -Wzero-as-null-pointer-constant --- lib/zstd.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/zstd.h b/lib/zstd.h index b79f675c3..e4c9ffc87 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1802,7 +1802,11 @@ static #ifdef __GNUC__ __attribute__((__unused__)) #endif +// Disable diagnostic for C++ compatibility +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */ +#pragma clang diagnostic pop ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); From 97291fc5020a8994019ab76cf0cda83a9824374c Mon Sep 17 00:00:00 2001 From: Richard Barnes Date: Fri, 26 Apr 2024 14:44:41 -0700 Subject: [PATCH 315/937] Increase x-compatibility --- lib/zstd.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/zstd.h b/lib/zstd.h index e4c9ffc87..aa4ea23af 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1802,11 +1802,15 @@ static #ifdef __GNUC__ __attribute__((__unused__)) #endif -// Disable diagnostic for C++ compatibility + +#if defined(__clang__) && __clang_major__ >= 5 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" +#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 +#endif ZSTDLIB_STATIC_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem); ZSTDLIB_STATIC_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem); From 4356192cb2a16975720a04ac5681a495e7ef1acc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 May 2024 05:18:11 +0000 Subject: [PATCH 316/937] Bump msys2/setup-msys2 from 2.22.0 to 2.23.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.22.0 to 2.23.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/cc11e9188b693c2b100158c3322424c4cc1dadea...d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index eb8f40a9a..cf73acac1 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -247,7 +247,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0 + - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index b8afcb76b..e8c25d283 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -499,7 +499,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0 + - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 60c163123..761b6c854 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -24,7 +24,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3 - - uses: msys2/setup-msys2@cc11e9188b693c2b100158c3322424c4cc1dadea # tag=v2.22.0 + - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 with: msystem: ${{ matrix.msystem }} install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc From 2955d92ac02eb60b6d0d00e7c6cd3f013ac020e6 Mon Sep 17 00:00:00 2001 From: Joseph Chen Date: Tue, 14 May 2024 16:51:10 +0800 Subject: [PATCH 317/937] Improve support for IAR compiler with attributes and intrinsics --- lib/common/bits.h | 8 ++++++++ lib/common/compiler.h | 10 ++++++---- lib/common/entropy_common.c | 4 ++++ lib/common/mem.h | 6 ++++++ lib/zstd.h | 2 +- 5 files changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/common/bits.h b/lib/common/bits.h index def56c474..992cc6925 100644 --- a/lib/common/bits.h +++ b/lib/common/bits.h @@ -43,6 +43,8 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros32(U32 val) # endif # elif defined(__GNUC__) && (__GNUC__ >= 4) return (unsigned)__builtin_ctz(val); +# elif defined(__ICCARM__) + return (unsigned)__builtin_ctz(val); # else return ZSTD_countTrailingZeros32_fallback(val); # endif @@ -82,6 +84,8 @@ MEM_STATIC unsigned ZSTD_countLeadingZeros32(U32 val) # endif # elif defined(__GNUC__) && (__GNUC__ >= 4) return (unsigned)__builtin_clz(val); +# elif defined(__ICCARM__) + return (unsigned)__builtin_clz(val); # else return ZSTD_countLeadingZeros32_fallback(val); # endif @@ -105,6 +109,8 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros64(U64 val) # endif # elif defined(__GNUC__) && (__GNUC__ >= 4) && defined(__LP64__) return (unsigned)__builtin_ctzll(val); +# elif defined(__ICCARM__) + return (unsigned)__builtin_ctzll(val); # else { U32 mostSignificantWord = (U32)(val >> 32); @@ -136,6 +142,8 @@ MEM_STATIC unsigned ZSTD_countLeadingZeros64(U64 val) # endif # elif defined(__GNUC__) && (__GNUC__ >= 4) return (unsigned)(__builtin_clzll(val)); +# elif defined(__ICCARM__) + return (unsigned)(__builtin_clzll(val)); # else { U32 mostSignificantWord = (U32)(val >> 32); diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 31880ecbe..1371212ef 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -27,7 +27,7 @@ # define INLINE_KEYWORD #endif -#if defined(__GNUC__) || defined(__ICCARM__) +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) # define FORCE_INLINE_ATTR __attribute__((always_inline)) #elif defined(_MSC_VER) # define FORCE_INLINE_ATTR __forceinline @@ -54,7 +54,7 @@ #endif /* UNUSED_ATTR tells the compiler it is okay if the function is unused. */ -#if defined(__GNUC__) +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) # define UNUSED_ATTR __attribute__((unused)) #else # define UNUSED_ATTR @@ -95,6 +95,8 @@ #ifndef MEM_STATIC /* already defined in Linux Kernel mem.h */ #if defined(__GNUC__) # define MEM_STATIC static __inline UNUSED_ATTR +#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 #elif defined(_MSC_VER) @@ -108,7 +110,7 @@ #ifdef _MSC_VER # define FORCE_NOINLINE static __declspec(noinline) #else -# if defined(__GNUC__) || defined(__ICCARM__) +# if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) # define FORCE_NOINLINE static __attribute__((__noinline__)) # else # define FORCE_NOINLINE static @@ -117,7 +119,7 @@ /* target attribute */ -#if defined(__GNUC__) || defined(__ICCARM__) +#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__) # define TARGET_ATTRIBUTE(target) __attribute__((__target__(target))) #else # define TARGET_ATTRIBUTE(target) diff --git a/lib/common/entropy_common.c b/lib/common/entropy_common.c index e2173afb0..abc8b543e 100644 --- a/lib/common/entropy_common.c +++ b/lib/common/entropy_common.c @@ -38,7 +38,11 @@ const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); } /*-************************************************************** * FSE NCount encoding-decoding ****************************************************************/ +#if defined(__IAR_SYSTEMS_ICC__) +MEM_STATIC +#else FORCE_INLINE_TEMPLATE +#endif size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, const void* headerBuffer, size_t hbSize) { diff --git a/lib/common/mem.h b/lib/common/mem.h index 096f4be51..a02141c9d 100644 --- a/lib/common/mem.h +++ b/lib/common/mem.h @@ -30,6 +30,8 @@ extern "C" { #if defined(_MSC_VER) /* Visual Studio */ # include /* _byteswap_ulong */ # include /* _byteswap_* */ +#elif defined(__ICCARM__) +# include #endif /*-************************************************************** @@ -154,6 +156,8 @@ MEM_STATIC unsigned MEM_isLittleEndian(void) return 1; #elif defined(__DMC__) && defined(_M_IX86) return 1; +#elif defined(__IAR_SYSTEMS_ICC__) && __LITTLE_ENDIAN__ + return 1; #else const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ return one.c[0]; @@ -246,6 +250,8 @@ MEM_STATIC U32 MEM_swap32(U32 in) #elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \ || (defined(__clang__) && __has_builtin(__builtin_bswap32)) return __builtin_bswap32(in); +#elif defined(__ICCARM__) + return __REV(in); #else return MEM_swap32_fallback(in); #endif diff --git a/lib/zstd.h b/lib/zstd.h index aa4ea23af..338bdb7ed 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -57,7 +57,7 @@ extern "C" { #else # if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ # define ZSTD_DEPRECATED(message) [[deprecated(message)]] -# elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) +# elif (defined(GNUC) && (GNUC > 4 || (GNUC == 4 && GNUC_MINOR >= 5))) || defined(__clang__) || defined(__IAR_SYSTEMS_ICC__) # define ZSTD_DEPRECATED(message) __attribute__((deprecated(message))) # elif defined(__GNUC__) && (__GNUC__ >= 3) # define ZSTD_DEPRECATED(message) __attribute__((deprecated)) From 5fadd8e6b1229e3116ba53a8cd34b678df403d97 Mon Sep 17 00:00:00 2001 From: Joseph Chen Date: Wed, 15 May 2024 10:47:50 +0800 Subject: [PATCH 318/937] revert FSE_readNCount_body attribute --- lib/common/entropy_common.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/common/entropy_common.c b/lib/common/entropy_common.c index abc8b543e..e2173afb0 100644 --- a/lib/common/entropy_common.c +++ b/lib/common/entropy_common.c @@ -38,11 +38,7 @@ const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); } /*-************************************************************** * FSE NCount encoding-decoding ****************************************************************/ -#if defined(__IAR_SYSTEMS_ICC__) -MEM_STATIC -#else FORCE_INLINE_TEMPLATE -#endif size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, const void* headerBuffer, size_t hbSize) { From 1872688e0adb630e8710cb3d17846ca49f596e46 Mon Sep 17 00:00:00 2001 From: Adenilson Cavalcanti Date: Fri, 17 May 2024 13:37:55 -0700 Subject: [PATCH 319/937] [fix] Add check on failed allocation in legacy/zstd_v06 As reported by Ben Hawkes in #4026, a failure to allocate a zstd context would lead to a dereference of a NULL pointer due to a missing check on the returned result of ZSTDv06_createDCtx(). This patch fix the issue by adding a check for valid returned pointer. --- lib/legacy/zstd_v06.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/legacy/zstd_v06.c b/lib/legacy/zstd_v06.c index 00d6ef79a..3a8bd0c93 100644 --- a/lib/legacy/zstd_v06.c +++ b/lib/legacy/zstd_v06.c @@ -3919,6 +3919,10 @@ ZBUFFv06_DCtx* ZBUFFv06_createDCtx(void) if (zbd==NULL) return NULL; memset(zbd, 0, sizeof(*zbd)); zbd->zd = ZSTDv06_createDCtx(); + if (zbd->zd==NULL) { + ZBUFFv06_freeDCtx(zbd); /* avoid leaking the context */ + return NULL; + } zbd->stage = ZBUFFds_init; return zbd; } From 4c6a519fdd8caef500244b838beab7f7a160f70f Mon Sep 17 00:00:00 2001 From: Jure Bajic Date: Sun, 26 May 2024 11:33:39 +0200 Subject: [PATCH 320/937] [fix] Add newline when file exceeds 128KB --- programs/dibio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/dibio.c b/programs/dibio.c index 26ebe5ca1..7ba22d15b 100644 --- a/programs/dibio.c +++ b/programs/dibio.c @@ -298,7 +298,7 @@ static fileStats DiB_fileStats(const char** fileNamesTable, int nbFiles, size_t fs.oneSampleTooLarge |= (fileSize > 2*SAMPLESIZE_MAX); /* Limit to the first SAMPLESIZE_MAX (128kB) of the file */ - DISPLAYLEVEL(3, "Sample file '%s' is too large, limiting to %d KB", + DISPLAYLEVEL(3, "Sample file '%s' is too large, limiting to %d KB\n", fileNamesTable[n], SAMPLESIZE_MAX / (1 KB)); } fs.nbSamples += 1; From 5e9a6c2fe4e4bfabeef750642871e3edcf6c6d79 Mon Sep 17 00:00:00 2001 From: Federico Maresca <62501138+Federico-Maresca@users.noreply.github.com> Date: Wed, 29 May 2024 18:35:24 +0200 Subject: [PATCH 321/937] Refactor dictionary matchfinder index safety check (#4039) --- lib/compress/zstd_compress_internal.h | 7 +++++++ lib/compress/zstd_double_fast.c | 8 ++++---- lib/compress/zstd_fast.c | 7 +++---- lib/compress/zstd_lazy.c | 16 ++++++++-------- lib/compress/zstd_opt.c | 4 ++-- 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index e41d7b78e..f8ec1c82e 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1315,6 +1315,13 @@ MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, return matchLowest; } +/* index_safety_check: + * intentional underflow : ensure repIndex isn't overlapping dict + prefix + * @return 1 if values are not overlapping, + * 0 otherwise */ +MEM_STATIC int ZSTD_index_overlap_check(const U32 prefixLowestIndex, const U32 repIndex) { + return ((U32)((prefixLowestIndex-1) - repIndex) >= 3); +} /* debug functions */ diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index a4e9c50d3..1b5f64f20 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -392,7 +392,7 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( hashLong[h2] = hashSmall[h] = curr; /* update hash tables */ /* check repcode */ - if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */) + if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend; mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4; @@ -513,7 +513,7 @@ _match_stored: const BYTE* repMatch2 = repIndex2 < prefixLowestIndex ? dictBase + repIndex2 - dictIndexDelta : base + repIndex2; - if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */) + if ( (ZSTD_index_overlap_check(prefixLowestIndex, repIndex2)) && (MEM_read32(repMatch2) == MEM_read32(ip)) ) { const BYTE* const repEnd2 = repIndex2 < prefixLowestIndex ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixLowest) + 4; @@ -651,7 +651,7 @@ size_t ZSTD_compressBlock_doubleFast_extDict_generic( size_t mLength; hashSmall[hSmall] = hashLong[hLong] = curr; /* update hash table */ - if ((((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow : ensure repIndex doesn't overlap dict + prefix */ + if (((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) & (offset_1 <= curr+1 - dictStartIndex)) /* note: we are searching at curr+1 */ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; @@ -719,7 +719,7 @@ size_t ZSTD_compressBlock_doubleFast_extDict_generic( U32 const current2 = (U32)(ip-base); U32 const repIndex2 = current2 - offset_2; const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2; - if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) /* intentional overflow : ensure repIndex2 doesn't overlap dict + prefix */ + if ( ((ZSTD_index_overlap_check(prefixStartIndex, repIndex2)) & (offset_2 <= current2 - dictStartIndex)) && (MEM_read32(repMatch2) == MEM_read32(ip)) ) { const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 6c4554cfc..c6baa49d4 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -546,8 +546,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( size_t const dictHashAndTag1 = ZSTD_hashPtr(ip1, dictHBits, mls); hashTable[hash0] = curr; /* update hash table */ - if (((U32) ((prefixStartIndex - 1) - repIndex) >= - 3) /* intentional underflow : ensure repIndex isn't overlapping dict + prefix */ + if ((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip0 + 1))) { const BYTE* const repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; mLength = ZSTD_count_2segments(ip0 + 1 + 4, repMatch + 4, iend, repMatchEnd, prefixStart) + 4; @@ -631,7 +630,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase - dictIndexDelta + repIndex2 : base + repIndex2; - if ( ((U32)((prefixStartIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */) + if ( (ZSTD_index_overlap_check(prefixStartIndex, repIndex2)) && (MEM_read32(repMatch2) == MEM_read32(ip0))) { const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip0+4, repMatch2+4, iend, repEnd2, prefixStart) + 4; @@ -925,7 +924,7 @@ _match: /* Requires: ip0, match0, offcode, matchEnd */ while (ip0 <= ilimit) { U32 const repIndex2 = (U32)(ip0-base) - offset_2; const BYTE* const repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2; - if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) & (offset_2 > 0)) /* intentional underflow */ + if ( ((ZSTD_index_overlap_check(prefixStartIndex, repIndex2)) & (offset_2 > 0)) && (MEM_read32(repMatch2) == MEM_read32(ip0)) ) { const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip0+4, repMatch2+4, iend, repEnd2, prefixStart) + 4; diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 67dd55fdb..9efaf4b25 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1590,7 +1590,7 @@ size_t ZSTD_compressBlock_lazy_generic( && repIndex < prefixLowestIndex) ? dictBase + (repIndex - dictIndexDelta) : base + repIndex; - if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */) + if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend; matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4; @@ -1642,7 +1642,7 @@ size_t ZSTD_compressBlock_lazy_generic( const BYTE* repMatch = repIndex < prefixLowestIndex ? dictBase + (repIndex - dictIndexDelta) : base + repIndex; - if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */) + if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip)) ) { const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend; size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4; @@ -1678,7 +1678,7 @@ size_t ZSTD_compressBlock_lazy_generic( const BYTE* repMatch = repIndex < prefixLowestIndex ? dictBase + (repIndex - dictIndexDelta) : base + repIndex; - if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */) + if ((ZSTD_index_overlap_check(prefixLowestIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip)) ) { const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend; size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4; @@ -1740,7 +1740,7 @@ _storeSequence: const BYTE* repMatch = repIndex < prefixLowestIndex ? dictBase - dictIndexDelta + repIndex : base + repIndex; - if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex) >= 3 /* intentional overflow */) + if ( (ZSTD_index_overlap_check(prefixLowestIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip)) ) { const BYTE* const repEnd2 = repIndex < prefixLowestIndex ? dictEnd : iend; matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd2, prefixLowest) + 4; @@ -1986,7 +1986,7 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr+1 - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow */ + if ( (ZSTD_index_overlap_check(dictLimit, repIndex)) & (offset_1 <= curr+1 - windowLow) ) /* note: we are searching at curr+1 */ if (MEM_read32(ip+1) == MEM_read32(repMatch)) { /* repcode detected we should take it */ @@ -2027,7 +2027,7 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + if ( (ZSTD_index_overlap_check(dictLimit, repIndex)) & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected */ @@ -2059,7 +2059,7 @@ size_t ZSTD_compressBlock_lazy_extDict_generic( const U32 repIndex = (U32)(curr - offset_1); const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + if ( (ZSTD_index_overlap_check(dictLimit, repIndex)) & (offset_1 <= curr - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected */ @@ -2113,7 +2113,7 @@ _storeSequence: const U32 repIndex = repCurrent - offset_2; const BYTE* const repBase = repIndex < dictLimit ? dictBase : base; const BYTE* const repMatch = repBase + repIndex; - if ( ((U32)((dictLimit-1) - repIndex) >= 3) /* intentional overflow : do not test positions overlapping 2 memory segments */ + if ( (ZSTD_index_overlap_check(dictLimit, repIndex)) & (offset_2 <= repCurrent - windowLow) ) /* equivalent to `curr > repIndex >= windowLow` */ if (MEM_read32(ip) == MEM_read32(repMatch)) { /* repcode detected we should take it */ diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index e63073e5a..8a4345b31 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -664,13 +664,13 @@ ZSTD_insertBtAndGetAllMatches ( assert(curr >= windowLow); if ( dictMode == ZSTD_extDict && ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow) /* equivalent to `curr > repIndex >= windowLow` */ - & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */) + & (ZSTD_index_overlap_check(dictLimit, repIndex)) ) && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) { repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch; } if (dictMode == ZSTD_dictMatchState && ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `curr > repIndex >= dmsLowLimit` */ - & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */ + & (ZSTD_index_overlap_check(dictLimit, repIndex)) ) && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) { repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch; } } From 949689facf96c4bce6953d07f0658412077bcbf1 Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Mon, 3 Jun 2024 08:36:07 -0700 Subject: [PATCH 322/937] Drop FreeBSD 13.2 CI --- .cirrus.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index bf3f0c415..f68e39ae1 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -3,7 +3,6 @@ task: freebsd_instance: matrix: image_family: freebsd-14-0 - image_family: freebsd-13-2 install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From be6a18200621dd21ce073b77fce7f57636a6f4f4 Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Mon, 3 Jun 2024 12:42:27 -0400 Subject: [PATCH 323/937] Unit test for external sequence producer + static CCtx + streaming (#4063) --- tests/zstreamtest.c | 63 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index e0ee4c3e9..e4110eb21 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -2356,7 +2356,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } DISPLAYLEVEL(3, "OK \n"); - DISPLAYLEVEL(3, "test%3i : Testing external sequence producer with static CCtx: ", testNb++); + DISPLAYLEVEL(3, "test%3i : Testing external sequence producer with static CCtx (one-shot): ", testNb++); { size_t const dstBufSize = ZSTD_compressBound(CNBufferSize); BYTE* const dstBuf = (BYTE*)malloc(dstBufSize); @@ -2375,7 +2375,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) size_t const cctxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params); cctxBuf = malloc(cctxSize); staticCCtx = ZSTD_initStaticCCtx(cctxBuf, cctxSize); - ZSTD_CCtx_setParametersUsingCCtxParams(staticCCtx, params); + CHECK_Z(ZSTD_CCtx_setParametersUsingCCtxParams(staticCCtx, params)); } // Check that compression with external sequence producer succeeds when expected @@ -2408,6 +2408,65 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : Testing external sequence producer with static CCtx (streaming): ", testNb++); + { + size_t const dstBufSize = ZSTD_compressBound(CNBufferSize); + BYTE* const dstBuf = (BYTE*)malloc(dstBufSize); + size_t const checkBufSize = CNBufferSize; + BYTE* const checkBuf = (BYTE*)malloc(checkBufSize); + ZSTD_CCtx_params* params = ZSTD_createCCtxParams(); + ZSTD_CCtx* staticCCtx; + void* cctxBuf; + EMF_testCase seqProdState; + + CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_validateSequences, 1)); + CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_enableSeqProducerFallback, 0)); + ZSTD_CCtxParams_registerSequenceProducer(params, &seqProdState, zstreamSequenceProducer); + + { + size_t const cctxSize = ZSTD_estimateCStreamSize_usingCCtxParams(params); + cctxBuf = malloc(cctxSize); + staticCCtx = ZSTD_initStaticCCtx(cctxBuf, cctxSize); + CHECK_Z(ZSTD_CCtx_setParametersUsingCCtxParams(staticCCtx, params)); + } + + // Check that compression with external sequence producer succeeds when expected + seqProdState = EMF_LOTS_OF_SEQS; + { + ZSTD_inBuffer inBuf = { CNBuffer, CNBufferSize, 0 }; + ZSTD_outBuffer outBuf = { dstBuf, dstBufSize, 0 }; + size_t dResult; + CHECK_Z(ZSTD_compressStream(staticCCtx, &outBuf, &inBuf)); + CHECK_Z(ZSTD_endStream(staticCCtx, &outBuf)); + CHECK(inBuf.pos != inBuf.size, "EMF: inBuf.pos != inBuf.size"); + dResult = ZSTD_decompress(checkBuf, checkBufSize, outBuf.dst, outBuf.pos); + CHECK(ZSTD_isError(dResult), "EMF: Decompression error: %s", ZSTD_getErrorName(dResult)); + CHECK(dResult != CNBufferSize, "EMF: Corruption!"); + CHECK(memcmp(CNBuffer, checkBuf, CNBufferSize) != 0, "EMF: Corruption!"); + } + + CHECK_Z(ZSTD_CCtx_reset(staticCCtx, ZSTD_reset_session_only)); + + // Check that compression with external sequence producer fails when expected + seqProdState = EMF_BIG_ERROR; + { + ZSTD_inBuffer inBuf = { CNBuffer, CNBufferSize, 0 }; + ZSTD_outBuffer outBuf = { dstBuf, dstBufSize, 0 }; + size_t const cResult = ZSTD_compressStream(staticCCtx, &outBuf, &inBuf); + CHECK(!ZSTD_isError(cResult), "EMF: Should have raised an error!"); + CHECK( + ZSTD_getErrorCode(cResult) != ZSTD_error_sequenceProducer_failed, + "EMF: Wrong error code: %s", ZSTD_getErrorName(cResult) + ); + } + + free(dstBuf); + free(checkBuf); + free(cctxBuf); + ZSTD_freeCCtxParams(params); + } + DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : Decoder should reject invalid frame header on legacy frames: ", testNb++); { const unsigned char compressed[] = { 0x26,0xb5,0x2f,0xfd,0x50,0x91,0xfd,0xd8,0xb5 }; From 2acf90431ab2ffdc7d85d1017cf344bac897e704 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 3 Jun 2024 18:30:23 -0700 Subject: [PATCH 324/937] minor:doc: specify decompression behavior in presence of multiple concatenated frames directly at ZSTD_decompress() level. --- lib/zstd.h | 59 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 338bdb7ed..ce2b1c7de 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -157,37 +157,40 @@ ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity, int compressionLevel); /*! ZSTD_decompress() : - * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. - * `dstCapacity` is an upper bound of originalSize to regenerate. - * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. - * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), - * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ + * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. + * Multiple compressed frames can be decompressed at once with this method. + * The result will be the concatenation of all decompressed frames, back to back. + * `dstCapacity` is an upper bound of originalSize to regenerate. + * First frame's decompressed size can be extracted using ZSTD_getFrameContentSize(). + * If maximum upper bound isn't known, prefer using streaming mode to decompress data. + * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + * or an errorCode if it fails (which can be tested using ZSTD_isError()). */ ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, const void* src, size_t compressedSize); /*! 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". - * 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() */ + * `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". + * 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() */ #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); @@ -1802,7 +1805,7 @@ 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" From f19c98228f773413850736b3aab574a63f03f2bc Mon Sep 17 00:00:00 2001 From: Quentin Boswank Date: Wed, 5 Jun 2024 18:21:34 +0200 Subject: [PATCH 325/937] Fix $filter and Msys/Cygwin - switched the patter and input of $filter into the right places - added pattern wildcard to MSYS_NT & CYGWIN_NT as they change with windows versions - correctly identify MSYS2, even in an env like MINGW64 --- Makefile | 8 ++++---- doc/educational_decoder/Makefile | 2 +- lib/Makefile | 14 +++++++++++--- lib/libzstd.mk | 2 +- programs/Makefile | 6 +++--- tests/Makefile | 8 ++++---- tests/fuzz/Makefile | 2 +- tests/gzip/Makefile | 2 +- 8 files changed, 26 insertions(+), 18 deletions(-) diff --git a/Makefile b/Makefile index b2d985feb..5598cdd03 100644 --- a/Makefile +++ b/Makefile @@ -151,7 +151,7 @@ clean: #------------------------------------------------------------------------------ # make install is validated only for Linux, macOS, Hurd and some BSD targets #------------------------------------------------------------------------------ -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT CYGWIN_NT Haiku AIX)) +ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT% CYGWIN_NT% Haiku AIX,$(shell sh -c 'MSYSTEM="MSYS" uname') )) HOST_OS = POSIX @@ -390,19 +390,19 @@ lz4install: endif -ifneq (,$(filter MSYS%,$(shell uname))) +ifneq (,$(filter MSYS%,$(shell sh -c 'MSYSTEM="MSYS" uname') )) HOST_OS = MSYS endif #------------------------------------------------------------------------ # target specific tests #------------------------------------------------------------------------ -ifneq (,$(filter $(HOST_OS),MSYS POSIX)) +ifneq (,$(filter MSYS POSIX,$(HOST_OS))) CMAKE ?= cmake CMAKE_PARAMS = -DZSTD_BUILD_CONTRIB:BOOL=ON -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZLIB_SUPPORT:BOOL=ON -DZSTD_LZMA_SUPPORT:BOOL=ON -ifneq (,$(filter MSYS%,$(shell uname))) +ifneq (,$(filter MSYS%,$(shell sh -c 'MSYSTEM="MSYS" uname'))) CMAKE_PARAMS = -G"MSYS Makefiles" -DZSTD_MULTITHREAD_SUPPORT:BOOL=OFF -DZSTD_BUILD_STATIC:BOOL=ON -DZSTD_BUILD_TESTS:BOOL=ON endif diff --git a/doc/educational_decoder/Makefile b/doc/educational_decoder/Makefile index f6deeb13d..b3154d9af 100644 --- a/doc/educational_decoder/Makefile +++ b/doc/educational_decoder/Makefile @@ -10,7 +10,7 @@ ZSTD ?= zstd # note: requires zstd installation on local system -UNAME?= $(shell uname) +UNAME?= $(shell sh -c 'MSYSTEM="MSYS" uname') ifeq ($(UNAME), SunOS) DIFF ?= gdiff else diff --git a/lib/Makefile b/lib/Makefile index 57097ce3f..ccfdfedd6 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -266,7 +266,7 @@ clean: #----------------------------------------------------------------------------- # make install is validated only for below listed environments #----------------------------------------------------------------------------- -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT CYGWIN_NT)) +ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT% CYGWIN_NT%,$(UNAME))) lib: libzstd.pc @@ -305,13 +305,21 @@ else PCLIB := $(LDFLAGS_DYNLIB) endif -ifneq (,$(filter $(UNAME),FreeBSD NetBSD DragonFly)) + +ifneq ($(MT),) + PCLIB := + PCMTLIB := $(LDFLAGS_DYNLIB) +else + PCLIB := $(LDFLAGS_DYNLIB) +endif + +ifneq (,$(filter FreeBSD NetBSD DragonFly,$(UNAME))) PKGCONFIGDIR ?= $(PREFIX)/libdata/pkgconfig else PKGCONFIGDIR ?= $(LIBDIR)/pkgconfig endif -ifneq (,$(filter $(UNAME),SunOS)) +ifneq (,$(filter SunOS,$(UNAME))) INSTALL ?= ginstall else INSTALL ?= install diff --git a/lib/libzstd.mk b/lib/libzstd.mk index 14b3b11d6..a2a965037 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -206,7 +206,7 @@ endif endif CPPFLAGS += -DZSTD_LEGACY_SUPPORT=$(ZSTD_LEGACY_SUPPORT) -UNAME := $(shell uname) +UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') ifndef BUILD_DIR ifeq ($(UNAME), Darwin) diff --git a/programs/Makefile b/programs/Makefile index 4dcd84105..e1a30fc2b 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -345,7 +345,7 @@ include $(wildcard $(DEPFILES)) #----------------------------------------------------------------------------- # make install is validated only for Linux, macOS, BSD, Hurd and Solaris targets #----------------------------------------------------------------------------- -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT CYGWIN_NT)) +ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT% CYGWIN_NT%,$(UNAME))) HAVE_COLORNEVER = $(shell echo a | egrep --color=never a > /dev/null 2> /dev/null && echo 1 || echo 0) EGREP_OPTIONS ?= @@ -388,14 +388,14 @@ datarootdir ?= $(PREFIX)/share mandir ?= $(datarootdir)/man man1dir ?= $(mandir)/man1 -ifneq (,$(filter $(UNAME),OpenBSD FreeBSD NetBSD DragonFly SunOS)) +ifneq (,$(filter OpenBSD FreeBSD NetBSD DragonFly SunOS,$(UNAME))) MANDIR ?= $(PREFIX)/man MAN1DIR ?= $(MANDIR)/man1 else MAN1DIR ?= $(man1dir) endif -ifneq (,$(filter $(UNAME),SunOS)) +ifneq (,$(filter SunOS,$(UNAME))) INSTALL ?= ginstall else INSTALL ?= install diff --git a/tests/Makefile b/tests/Makefile index c458b682a..5c0607d10 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -271,8 +271,8 @@ clean: #---------------------------------------------------------------------------------- # valgrind tests validated only for some posix platforms #---------------------------------------------------------------------------------- -UNAME := $(shell uname) -ifneq (,$(filter $(UNAME),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS AIX CYGWIN_NT)) +UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') +ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS AIX CYGWIN_NT%,$(UNAME))) HOST_OS = POSIX .PHONY: test-valgrind @@ -300,10 +300,10 @@ endif #----------------------------------------------------------------------------- # make tests validated only for below targets #----------------------------------------------------------------------------- -ifneq (,$(filter $(HOST_OS),MSYS POSIX)) +ifneq (,$(filter MSYS POSIX,$(HOST_OS))) DIFF:=diff -ifneq (,$(filter $(UNAME),SunOS)) +ifneq (,$(filter SunOS,$(UNAME))) DIFF:=gdiff endif diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index 430f6df15..1333675d0 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -17,7 +17,7 @@ LDFLAGS ?= ARFLAGS ?= LIB_FUZZING_ENGINE ?= libregression.a PYTHON ?= python -ifeq ($(shell uname), Darwin) +ifeq ($(shell sh -c 'MSYSTEM="MSYS" uname') , Darwin) DOWNLOAD?=curl -L -o else DOWNLOAD?=wget -O diff --git a/tests/gzip/Makefile b/tests/gzip/Makefile index cca310967..23f5cfdc3 100644 --- a/tests/gzip/Makefile +++ b/tests/gzip/Makefile @@ -36,7 +36,7 @@ clean: #------------------------------------------------------------------------------ # validated only for Linux, macOS, Hurd and some BSD targets #------------------------------------------------------------------------------ -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU FreeBSD DragonFly NetBSD)) +ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU FreeBSD DragonFly NetBSD,$(shell sh -c 'MSYSTEM="MSYS" uname') )) test-%: zstd @./test-driver.sh --test-name $* --log-file $*.log --trs-file $*.trs --expect-failure "no" --color-tests "yes" --enable-hard-errors "yes" ./$*.sh From d7a84a683fe345342139660b9d3a36328ed5f4b3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 12 Jun 2024 09:51:01 -0700 Subject: [PATCH 326/937] added cygwin install test --- .github/workflows/dev-short-tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index e8c25d283..0269e8369 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -576,6 +576,11 @@ jobs: make -j allzstd && make -C tests fuzzer && ./tests/fuzzer.exe -v -T1m + - name: cygwin install test + shell: C:\cygwin\bin\bash.exe --noprofile --norc -eo pipefail '{0}' + run: >- + make -j && + make install pkg-config: runs-on: ubuntu-latest From 3242ac598e6f17d8008f6110337a3b4c1205842b Mon Sep 17 00:00:00 2001 From: Elliot Gorokhovsky Date: Fri, 14 Jun 2024 14:38:48 -0400 Subject: [PATCH 327/937] Expose size estimation helpers for Linux (#4064) --- contrib/linux-kernel/linux_zstd.h | 36 +++++++++++++ contrib/linux-kernel/zstd_compress_module.c | 56 +++++++++++++++++++++ 2 files changed, 92 insertions(+) diff --git a/contrib/linux-kernel/linux_zstd.h b/contrib/linux-kernel/linux_zstd.h index f109d49f4..a7ce080dc 100644 --- a/contrib/linux-kernel/linux_zstd.h +++ b/contrib/linux-kernel/linux_zstd.h @@ -153,6 +153,20 @@ typedef ZSTD_CCtx zstd_cctx; */ size_t zstd_cctx_workspace_bound(const zstd_compression_parameters *parameters); +/** + * zstd_cctx_workspace_bound_with_ext_seq_prod() - max memory needed to + * initialize a zstd_cctx when using the block-level external sequence + * producer API. + * @parameters: The compression parameters to be used. + * + * If multiple compression parameters might be used, the caller must call + * this function for each set of parameters and use the maximum size. + * + * Return: A lower bound on the size of the workspace that is passed to + * zstd_init_cctx(). + */ +size_t zstd_cctx_workspace_bound_with_ext_seq_prod(const zstd_compression_parameters *parameters); + /** * zstd_init_cctx() - initialize a zstd compression context * @workspace: The workspace to emplace the context into. It must outlive @@ -257,6 +271,16 @@ typedef ZSTD_CStream zstd_cstream; */ size_t zstd_cstream_workspace_bound(const zstd_compression_parameters *cparams); +/** + * zstd_cstream_workspace_bound_with_ext_seq_prod() - memory needed to initialize + * a zstd_cstream when using the block-level external sequence producer API. + * @cparams: The compression parameters to be used for compression. + * + * Return: A lower bound on the size of the workspace that is passed to + * zstd_init_cstream(). + */ +size_t zstd_cstream_workspace_bound_with_ext_seq_prod(const zstd_compression_parameters *cparams); + /** * zstd_init_cstream() - initialize a zstd streaming compression context * @parameters The zstd parameters to use for compression. @@ -416,6 +440,18 @@ size_t zstd_decompress_stream(zstd_dstream *dstream, zstd_out_buffer *output, */ size_t zstd_find_frame_compressed_size(const void *src, size_t src_size); +/** + * zstd_register_sequence_producer() - exposes the zstd library function + * ZSTD_registerSequenceProducer(). This is used for the block-level external + * sequence producer API. See upstream zstd.h for detailed documentation. + */ +typedef ZSTD_sequenceProducer_F zstd_sequence_producer_f; +void zstd_register_sequence_producer( + zstd_cctx *cctx, + void* sequence_producer_state, + zstd_sequence_producer_f sequence_producer +); + /** * struct zstd_frame_params - zstd frame parameters stored in the frame header * @frameContentSize: The frame content size, or ZSTD_CONTENTSIZE_UNKNOWN if not diff --git a/contrib/linux-kernel/zstd_compress_module.c b/contrib/linux-kernel/zstd_compress_module.c index 8ecf43226..039db55f9 100644 --- a/contrib/linux-kernel/zstd_compress_module.c +++ b/contrib/linux-kernel/zstd_compress_module.c @@ -16,6 +16,7 @@ #include "common/zstd_deps.h" #include "common/zstd_internal.h" +#include "compress/zstd_compress_internal.h" #define ZSTD_FORWARD_IF_ERR(ret) \ do { \ @@ -85,6 +86,52 @@ size_t zstd_cctx_workspace_bound(const zstd_compression_parameters *cparams) } EXPORT_SYMBOL(zstd_cctx_workspace_bound); +// Used by zstd_cctx_workspace_bound_with_ext_seq_prod() +static size_t dummy_external_sequence_producer( + void *sequenceProducerState, + ZSTD_Sequence *outSeqs, size_t outSeqsCapacity, + const void *src, size_t srcSize, + const void *dict, size_t dictSize, + int compressionLevel, + size_t windowSize) +{ + (void)sequenceProducerState; + (void)outSeqs; (void)outSeqsCapacity; + (void)src; (void)srcSize; + (void)dict; (void)dictSize; + (void)compressionLevel; + (void)windowSize; + return ZSTD_SEQUENCE_PRODUCER_ERROR; +} + +static void init_cctx_params_from_compress_params( + ZSTD_CCtx_params *cctx_params, + const zstd_compression_parameters *compress_params) +{ + ZSTD_parameters zstd_params; + memset(&zstd_params, 0, sizeof(zstd_params)); + zstd_params.cParams = *compress_params; + ZSTD_CCtxParams_init_advanced(cctx_params, zstd_params); +} + +size_t zstd_cctx_workspace_bound_with_ext_seq_prod(const zstd_compression_parameters *compress_params) +{ + ZSTD_CCtx_params cctx_params; + init_cctx_params_from_compress_params(&cctx_params, compress_params); + ZSTD_CCtxParams_registerSequenceProducer(&cctx_params, NULL, dummy_external_sequence_producer); + return ZSTD_estimateCCtxSize_usingCCtxParams(&cctx_params); +} +EXPORT_SYMBOL(zstd_cctx_workspace_bound_with_ext_seq_prod); + +size_t zstd_cstream_workspace_bound_with_ext_seq_prod(const zstd_compression_parameters *compress_params) +{ + ZSTD_CCtx_params cctx_params; + init_cctx_params_from_compress_params(&cctx_params, compress_params); + ZSTD_CCtxParams_registerSequenceProducer(&cctx_params, NULL, dummy_external_sequence_producer); + return ZSTD_estimateCStreamSize_usingCCtxParams(&cctx_params); +} +EXPORT_SYMBOL(zstd_cstream_workspace_bound_with_ext_seq_prod); + zstd_cctx *zstd_init_cctx(void *workspace, size_t workspace_size) { if (workspace == NULL) @@ -160,5 +207,14 @@ size_t zstd_end_stream(zstd_cstream *cstream, zstd_out_buffer *output) } EXPORT_SYMBOL(zstd_end_stream); +void zstd_register_sequence_producer( + zstd_cctx *cctx, + void* sequence_producer_state, + zstd_sequence_producer_f sequence_producer +) { + ZSTD_registerSequenceProducer(cctx, sequence_producer_state, sequence_producer); +} +EXPORT_SYMBOL(zstd_register_sequence_producer); + MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("Zstd Compressor"); From 80170f6aad9f48574b108584e7504b0f9254958f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Jun 2024 20:21:25 -0700 Subject: [PATCH 328/937] fix macos build weird: after replacing the UNAME line with an identical one, it does work properly now(??). Possibly a case of hidden special character? --- .github/workflows/dev-long-tests.yml | 6 +++--- lib/Makefile | 8 -------- lib/libzstd.mk | 2 +- 3 files changed, 4 insertions(+), 12 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index cf73acac1..82e893cb9 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -31,12 +31,12 @@ jobs: run: make test # lasts ~26mn - make-test-osx: + make-test-macos: runs-on: macos-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: OS-X test - run: make test # make -c lib all doesn't work because of the fact that it's not a tty + - name: make test on macos + run: make test # lasts ~24mn make-test-32bit: diff --git a/lib/Makefile b/lib/Makefile index ccfdfedd6..020d2ff5d 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -298,14 +298,6 @@ PCLIBPREFIX := $(if $(findstring $(LIBDIR),$(PCLIBDIR)),,$${exec_prefix}) PCEXEC_PREFIX := $(if $(HAS_EXPLICIT_EXEC_PREFIX),$(EXEC_PREFIX),$${prefix}) -ifneq ($(MT),) - PCLIB := - PCMTLIB := $(LDFLAGS_DYNLIB) -else - PCLIB := $(LDFLAGS_DYNLIB) -endif - - ifneq ($(MT),) PCLIB := PCMTLIB := $(LDFLAGS_DYNLIB) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index a2a965037..d89817f14 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -206,7 +206,7 @@ endif endif CPPFLAGS += -DZSTD_LEGACY_SUPPORT=$(ZSTD_LEGACY_SUPPORT) -UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') +UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') ifndef BUILD_DIR ifeq ($(UNAME), Darwin) From 2d736d9c50057e6d1f33c175e126590816c54251 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 5 Jun 2024 19:41:43 +0200 Subject: [PATCH 329/937] Fix new typos found by codespell --- doc/zstd_manual.html | 2 +- lib/compress/zstd_lazy.c | 6 +++--- lib/zstd.h | 2 +- tests/zstreamtest.c | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index bc4a24036..56bfbcd81 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -298,7 +298,7 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ * Special: value 0 means "use default strategy". */ ZSTD_c_targetCBlockSize=130, /* v1.5.6+ - * Attempts to fit compressed block size into approximatively targetCBlockSize. + * Attempts to fit compressed block size into approximately targetCBlockSize. * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. * Note that it's not a guarantee, just a convergence target (default:0). * No target when targetCBlockSize == 0. diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 9efaf4b25..cfbadf458 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1123,9 +1123,9 @@ ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGr /* The high-level approach of the SIMD row based match finder is as follows: * - Figure out where to insert the new entry: - * - Generate a hash for current input posistion and split it into a one byte of tag and `rowHashLog` bits of index. - * - The hash is salted by a value that changes on every contex reset, so when the same table is used - * we will avoid collisions that would otherwise slow us down by intorducing phantom matches. + * - Generate a hash for current input position and split it into a one byte of tag and `rowHashLog` bits of index. + * - The hash is salted by a value that changes on every context reset, so when the same table is used + * we will avoid collisions that would otherwise slow us down by introducing phantom matches. * - The hashTable is effectively split into groups or "rows" of 15 or 31 entries of U32, and the index determines * which row to insert into. * - Determine the correct position within the row to insert the entry into. Each row of 15 or 31 can diff --git a/lib/zstd.h b/lib/zstd.h index ce2b1c7de..3a88c74d1 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -395,7 +395,7 @@ typedef enum { * Special: value 0 means "use default strategy". */ ZSTD_c_targetCBlockSize=130, /* v1.5.6+ - * Attempts to fit compressed block size into approximatively targetCBlockSize. + * Attempts to fit compressed block size into approximately targetCBlockSize. * Bound by ZSTD_TARGETCBLOCKSIZE_MIN and ZSTD_TARGETCBLOCKSIZE_MAX. * Note that it's not a guarantee, just a convergence target (default:0). * No target when targetCBlockSize == 0. diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index e4110eb21..8625b4a23 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -2478,7 +2478,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : Test single-shot fallback for magicless mode: ", testNb++); { - // Aquire resources + // Acquire resources size_t const srcSize = COMPRESSIBLE_NOISE_LENGTH; void* src = malloc(srcSize); size_t const dstSize = ZSTD_compressBound(srcSize); From 44e83e9180ee326353f98e680a7769d4b76f4c25 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 19 Jun 2024 21:04:50 +0200 Subject: [PATCH 330/937] Fix typos not found by codespell --- CHANGELOG | 4 ++-- build/cmake/CMakeModules/AddZstdCompilationFlags.cmake | 2 +- lib/common/compiler.h | 2 +- lib/common/portability_macros.h | 2 +- lib/compress/zstd_compress.c | 4 ++-- lib/decompress/zstd_decompress.c | 2 +- lib/decompress/zstd_decompress_block.c | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 33f43410f..ac44affce 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,7 +3,7 @@ api: Promote `ZSTD_c_targetCBlockSize` to Stable API by @felixhandte api: new `ZSTD_d_maxBlockSize` experimental parameter, to reduce streaming decompression memory, by @terrelln perf: improve performance of param `ZSTD_c_targetCBlockSize`, by @Cyan4973 perf: improved compression of arrays of integers at high compression, by @Cyan4973 -lib: reduce binary size with selective built-time exclusion, by @felixhandte +lib: reduce binary size with selective build-time exclusion, by @felixhandte lib: improved huffman speed on small data and linux kernel, by @terrelln lib: accept dictionaries with partial literal tables, by @terrelln lib: fix CCtx size estimation with external sequence producer, by @embg @@ -489,7 +489,7 @@ misc: added /contrib/docker script by @gyscos v1.3.3 (Dec 21, 2017) perf: faster zstd_opt strategy (levels 16-19) -fix : bug #944 : multithreading with shared ditionary and large data, reported by @gsliepen +fix : bug #944 : multithreading with shared dictionary and large data, reported by @gsliepen cli : fix : content size written in header by default cli : fix : improved LZ4 format support, by @felixhandte cli : new : hidden command `-S`, to benchmark multiple files while generating one result per file diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake index 5f179989b..6f55450c3 100644 --- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake +++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake @@ -57,7 +57,7 @@ macro(ADD_ZSTD_COMPILATION_FLAGS) # Note that zstd source code is compatible with both C++98 and above # and C-gnu90 (c90 + long long + variadic macros ) and above # EnableCompilerFlag("-std=c++11" false true) # Set C++ compilation to c++11 standard - # EnableCompilerFlag("-std=c99" true false) # Set C compiation to c99 standard + # EnableCompilerFlag("-std=c99" true false) # Set C compilation to c99 standard if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND MSVC) # clang-cl normally maps -Wall to -Weverything. EnableCompilerFlag("/clang:-Wall" true true false) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 1371212ef..fdf0dd18a 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -326,7 +326,7 @@ #endif /** - * Helper function to perform a wrapped pointer difference without trigging + * Helper function to perform a wrapped pointer difference without triggering * UBSAN. * * @returns lhs - rhs with wrapping diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index e50314a78..b1d9765fb 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -90,7 +90,7 @@ #endif /** - * Only enable assembly for GNUC compatible compilers, + * Only enable assembly for GNU C compatible compilers, * because other platforms may not support GAS assembly syntax. * * Only enable assembly for Linux / MacOS, other platforms may diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9284e2a48..18f929bbe 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2606,7 +2606,7 @@ ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerVa /* Protect special index values < ZSTD_WINDOW_START_INDEX. */ U32 const reducerThreshold = reducerValue + ZSTD_WINDOW_START_INDEX; assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */ - assert(size < (1U<<31)); /* can be casted to int */ + assert(size < (1U<<31)); /* can be cast to int */ #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE) /* To validate that the table reuse logic is sound, and that we don't @@ -5622,7 +5622,7 @@ size_t ZSTD_freeCDict(ZSTD_CDict* cdict) * workspaceSize: Use ZSTD_estimateCDictSize() * to determine how large workspace must be. * cParams : use ZSTD_getCParams() to transform a compression level - * into its relevants cParams. + * into its relevant cParams. * @return : pointer to ZSTD_CDict*, or NULL if error (size too small) * Note : there is no corresponding "free" function. * Since workspace was allocated externally, it must be freed externally. diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 2f03cf7b0..26c9457fb 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -811,7 +811,7 @@ size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize) /** ZSTD_decompressBound() : * compatible with legacy mode - * `src` must point to the start of a ZSTD frame or a skippeable frame + * `src` must point to the start of a ZSTD frame or a skippable frame * `srcSize` must be at least as large as the frame contained * @return : the maximum decompressed size of the compressed source */ diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 76d7332e8..f865692f5 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -358,7 +358,7 @@ size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, * - start from default distributions, present in /lib/common/zstd_internal.h * - generate tables normally, using ZSTD_buildFSETable() * - printout the content of tables - * - pretify output, report below, test with fuzzer to ensure it's correct */ + * - prettify output, report below, test with fuzzer to ensure it's correct */ /* Default FSE distribution table for Literal Lengths */ static const ZSTD_seqSymbol LL_defaultDTable[(1< Date: Thu, 20 Jun 2024 15:19:58 -0400 Subject: [PATCH 331/937] Throw error if Huffman weight initial states are truncated --- doc/decompressor_permissive.md | 20 ++++++++++++++++++ doc/zstd_compression_format.md | 4 ++++ lib/common/fse_decompress.c | 2 ++ .../truncated_huff_state.zst | Bin 0 -> 19 bytes 4 files changed, 26 insertions(+) create mode 100644 tests/golden-decompression-errors/truncated_huff_state.zst diff --git a/doc/decompressor_permissive.md b/doc/decompressor_permissive.md index bd77165f0..164d6c86d 100644 --- a/doc/decompressor_permissive.md +++ b/doc/decompressor_permissive.md @@ -18,6 +18,26 @@ This document lists a few known cases where invalid data was formerly accepted by the decoder, and what has changed since. +Truncated Huffman states +------------------------ + +**Last affected version**: v1.5.6 + +**Produced by the reference compressor**: No + +**Example Frame**: `28b5 2ffd 0000 5500 0072 8001 0420 7e1f 02aa 00` + +When using FSE-compressed Huffman weights, the compressed weight bitstream +could contain fewer bits than necessary to decode the initial states. + +The reference decompressor up to v1.5.6 will decode truncated or missing +initial states as zero, which can result in a valid Huffman tree if only +the second state is truncated. + +In newer versions, truncated initial states are reported as a corruption +error by the decoder. + + Offset == 0 ----------- diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 5cae85524..fb0090f9a 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -1362,6 +1362,10 @@ symbols for each of the final states are decoded and the process is complete. If this process would produce more weights than the maximum number of decoded weights (255), then the data is considered corrupted. +If either of the 2 initial states are absent or truncated, then the data is +considered corrupted. Consequently, it is not possible to encode fewer than +2 weights using this mode. + #### Conversion from weights to Huffman prefix codes All present symbols shall now have a `Weight` value. diff --git a/lib/common/fse_decompress.c b/lib/common/fse_decompress.c index 0dcc4640d..c8f1bb0cf 100644 --- a/lib/common/fse_decompress.c +++ b/lib/common/fse_decompress.c @@ -190,6 +190,8 @@ FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic( FSE_initDState(&state1, &bitD, dt); FSE_initDState(&state2, &bitD, dt); + RETURN_ERROR_IF(BIT_reloadDStream(&bitD)==BIT_DStream_overflow, corruption_detected, ""); + #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD) /* 4 symbols per loop */ diff --git a/tests/golden-decompression-errors/truncated_huff_state.zst b/tests/golden-decompression-errors/truncated_huff_state.zst new file mode 100644 index 0000000000000000000000000000000000000000..2ce18c0b7a9d14af8d167d7118b8560a5e90efaa GIT binary patch literal 19 acmdPcs{faPA(VlksDY71p-!G@6$1b@DFnX& literal 0 HcmV?d00001 From 345bcb5ff7001fbe2dfd59974808170c9e0f4d5d Mon Sep 17 00:00:00 2001 From: Adenilson Cavalcanti Date: Tue, 18 Jun 2024 17:20:35 -0700 Subject: [PATCH 332/937] [zstd][dict] Ensure that dictionary training functions are fully reentrant The two main functions used for dictionary training using the COVER algorithm require initialization of a COVER_ctx_t where a call to qsort() is performed. The issue is that the standard C99 qsort() function doesn't offer a way to pass an extra parameter for the comparison function callback (e.g. a pointer to a context) and currently zstd relies on a *global* static variable to hold a pointer to a context needed to perform the sort operation. If a zstd library user invokes either ZDICT_trainFromBuffer_cover or ZDICT_optimizeTrainFromBuffer_cover from multiple threads, the global context may be overwritten before/during the call/execution to qsort() in the initialization of the COVER_ctx_t, thus yielding to crashes and other bad things (Tm) as reported on issue #4045. Enters qsort_r(): it was designed to address precisely this situation, to quote from the documention [1]: "the comparison function does not need to use global variables to pass through arbitrary arguments, and is therefore reentrant and safe to use in threads." It is available with small variations for multiple OSes (GNU, BSD[2], Windows[3]), and the ISO C11 [4] standard features on annex B-21 qsort_s() as part of the . Let's hope that compilers eventually catch up with it. For now, we have to handle the small variations in function parameters for each platform. The current fix solves the problem by allowing each executing thread pass its own COVER_ctx_t instance to qsort_r(), removing the use of a global pointer and allowing the code to be reentrant. Unfortunately for *BSD, we cannot leverage qsort_r() given that its API has changed on newer versions of FreeBSD (14.0) and the other BSD variants (e.g. NetBSD, OpenBSD) don't implement it. For such cases we provide a fallback that will work only requiring support for compilers implementing support for C90. [1] https://man7.org/linux/man-pages/man3/qsort_r.3.html [2] https://man.freebsd.org/cgi/man.cgi?query=qsort_r [3] https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/qsort-s?view=msvc-170 [4] https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf --- lib/common/zstd_deps.h | 12 +++++++ lib/dictBuilder/cover.c | 79 +++++++++++++++++++++++++++++++---------- 2 files changed, 72 insertions(+), 19 deletions(-) diff --git a/lib/common/zstd_deps.h b/lib/common/zstd_deps.h index 4d767ae9b..f41a973c3 100644 --- a/lib/common/zstd_deps.h +++ b/lib/common/zstd_deps.h @@ -24,6 +24,18 @@ #ifndef ZSTD_DEPS_COMMON #define ZSTD_DEPS_COMMON +/* Even though we use qsort_r only for the dictionary builder, the macro + * _GNU_SOURCE has to be declared *before* the inclusion of any standard + * header and the script 'combine.sh' combines the whole zstd source code + * in a single file. + */ +#if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ + defined(__CYGWIN__) || defined(__MSYS__) +#if !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#endif + #include #include #include diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 44f9029ac..386a4d572 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -21,8 +21,17 @@ /*-************************************* * Dependencies ***************************************/ +/* qsort_r is an extension. */ +#if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ + defined(__CYGWIN__) || defined(__MSYS__) +#if !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif +#endif + #include /* fprintf */ -#include /* malloc, free, qsort */ +#include /* malloc, free, qsort_r */ + #include /* memset */ #include /* clock */ @@ -232,8 +241,10 @@ typedef struct { unsigned d; } COVER_ctx_t; -/* We need a global context for qsort... */ +#if !defined(_GNU_SOURCE) && !defined(__APPLE__) && !defined(_MSC_VER) +/* C90 only offers qsort() that needs a global context. */ static COVER_ctx_t *g_coverCtx = NULL; +#endif /*-************************************* * Helper functions @@ -276,11 +287,15 @@ 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 - * NOTE: g_coverCtx must be set to call this function. A global is required because - * qsort doesn't take an opaque pointer. */ -static int WIN_CDECL COVER_strict_cmp(const void *lp, const void *rp) { - int result = COVER_cmp(g_coverCtx, lp, rp); +#if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) +static int WIN_CDECL COVER_strict_cmp(void* g_coverCtx, const void* lp, const void* rp) { +#elif defined(_GNU_SOURCE) +static int COVER_strict_cmp(const void *lp, const void *rp, void *g_coverCtx) { +#else /* C90 fallback.*/ +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; } @@ -289,14 +304,50 @@ static int WIN_CDECL COVER_strict_cmp(const void *lp, const void *rp) { /** * Faster version for d <= 8. */ -static int WIN_CDECL COVER_strict_cmp8(const void *lp, const void *rp) { - int result = COVER_cmp8(g_coverCtx, lp, rp); +#if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) +static int WIN_CDECL COVER_strict_cmp8(void* g_coverCtx, const void* lp, const void* rp) { +#elif defined(_GNU_SOURCE) +static int COVER_strict_cmp8(const void *lp, const void *rp, void *g_coverCtx) { +#else /* C90 fallback.*/ +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; } return result; } +/** + * Abstract away divergence of qsort_r() parameters. + * Hopefully when C11 become the norm, we will be able + * to clean it up. + */ +static void stableSort(COVER_ctx_t *ctx) { +#if defined(__APPLE__) + qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), + ctx, + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); +#elif defined(_GNU_SOURCE) + qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), + ctx); +#elif defined(_WIN32) && defined(_MSC_VER) + qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32), + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), + ctx); +#elif defined(__OpenBSD__) + g_coverCtx = ctx; + mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32), + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); +#else /* C90 fallback.*/ + g_coverCtx = ctx; + /* TODO(cavalcanti): implement a reentrant qsort() when is not available. */ + qsort(ctx->suffix, ctx->suffixSize, sizeof(U32), + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); +#endif +} + /** * Returns the first pointer in [first, last) whose element does not compare * less than value. If no such element exists it returns last. @@ -620,17 +671,7 @@ static size_t COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer, for (i = 0; i < ctx->suffixSize; ++i) { ctx->suffix[i] = i; } - /* qsort doesn't take an opaque pointer, so pass as a global. - * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is. - */ - g_coverCtx = ctx; -#if defined(__OpenBSD__) - mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32), - (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); -#else - qsort(ctx->suffix, ctx->suffixSize, sizeof(U32), - (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); -#endif + stableSort(ctx); } DISPLAYLEVEL(2, "Computing frequencies\n"); /* For each dmer group (group of positions with the same first d bytes): From 1f72f52bc1efd943f390a3dec3b569cf49f7a83a Mon Sep 17 00:00:00 2001 From: Joseph Lee Date: Wed, 3 Jul 2024 12:26:15 +0900 Subject: [PATCH 333/937] gen_html: Fix build error in windows --- contrib/gen_html/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/gen_html/Makefile b/contrib/gen_html/Makefile index 26e870399..f93669e02 100644 --- a/contrib/gen_html/Makefile +++ b/contrib/gen_html/Makefile @@ -40,7 +40,7 @@ gen_html: gen_html.cpp $(ZSTDMANUAL): gen_html $(ZSTDAPI) echo "Update zstd manual in /doc" - ./gen_html $(LIBVER) $(ZSTDAPI) $(ZSTDMANUAL) + ./gen_html$(EXT) $(LIBVER) $(ZSTDAPI) $(ZSTDMANUAL) .PHONY: manual manual: gen_html $(ZSTDMANUAL) From b320d096a44b592d5f5bcda37e323b799c0cef57 Mon Sep 17 00:00:00 2001 From: "@RubenKelevra" Date: Sun, 7 Jul 2024 19:43:49 +0200 Subject: [PATCH 334/937] clarify when to use '--single-thread' with '--patch-from' Using '--single-thread' with '--patch-from' on compression levels above 15 will lead to significantly worse compression ratios. Corrected the man page not suggest anymore to do this. --- programs/zstd.1.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index fcbfb4573..5188be6a5 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -174,8 +174,10 @@ the last one takes effect. (_fileLog_ being the _windowLog_ required to cover the whole file). You can also manually force it. - Note: for all levels, you can use `--patch-from` in `--single-thread` mode - to improve compression ratio at the cost of speed. + Note: up to level 15, you can use `--patch-from` in `--single-thread` mode + to improve compression ratio marginally at the cost of speed. Using + '--single-thread' above level 15 will lead to lower compression + ratios. Note: for level 19, you can get increased compression ratio at the cost of speed by specifying `--zstd=targetLength=` to be something large From 5d63f186cce4bb21fde156492fe945f2ae69104c Mon Sep 17 00:00:00 2001 From: Thomas Petazzoni Date: Sat, 13 Jul 2024 13:53:53 +0200 Subject: [PATCH 335/937] lib/libzstd.mk: fix typo in the definition of LIB_BINDIR Commit f4dbfce79cb2b82fb496fcd2518ecd3315051b7d ("define LIB_SRCDIR and LIB_BINDIR") significantly reworked the build logic, but in its introduction of LIB_BINDIR a typo was made. It was introduced as such: +LIB_SRCDIR ?= $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) +LIB_BINDIR ?= $(LIBSRC_DIR) But the definition of LIB_BINDIR has a typo: it should use $(LIB_SRCDIR) not $(LIBSRC_DIR). Due to this, $(LIB_BINDIR) is empty, therefore in programs/Makefile, -L$(LIB_BINDIR) is expanded to just -L, and consequently when trying to link the "zstd" binary with the libzstd library, it cannot find it: host/lib/gcc/powerpc64-buildroot-linux-gnu/13.3.0/../../../../powerpc64-buildroot-linux-gnu/bin/ld: cannot find -lzstd: No such file or directory This commit fixes the build by fixing this typo. Signed-off-by: Thomas Petazzoni --- lib/libzstd.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index d89817f14..91bd4caf3 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -22,7 +22,7 @@ LIBZSTD_MK_INCLUDED := 1 # By default, library's directory is same as this included makefile LIB_SRCDIR ?= $(dir $(realpath $(lastword $(MAKEFILE_LIST)))) -LIB_BINDIR ?= $(LIBSRC_DIR) +LIB_BINDIR ?= $(LIB_SRCDIR) # ZSTD_LIB_MINIFY is a helper variable that # configures a bunch of other variables to space-optimized defaults. From 0986e1e630c0a4286ea07516bde3e6571c22274d Mon Sep 17 00:00:00 2001 From: Uilian Ries Date: Fri, 26 Jul 2024 09:45:06 +0200 Subject: [PATCH 336/937] Add Conan to readme Signed-off-by: Uilian Ries --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 54dfd4065..d91ef5df1 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,17 @@ You can build and install zstd [vcpkg](https://github.com/Microsoft/vcpkg/) depe The zstd port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. +### Conan + +You can install pre-built binaries for zstd or build it from source using [Conan](https://conan.io/). Use the following command: + +```bash +conan install --requires="zstd/[*]" --build=missing +``` + +The zstd Conan recipe is kept up to date by Conan maintainers and community contributors. +If the version is out of date, please [create an issue or pull request](https://github.com/conan-io/conan-center-index) on the ConanCenterIndex repository. + ### Visual Studio (Windows) Going into `build` directory, you will find additional possibilities: From 1f5df587fa3edbbf2faf24ef2f0941652663305f Mon Sep 17 00:00:00 2001 From: Pawel Czarnecki Date: Fri, 26 Jul 2024 09:47:16 +0200 Subject: [PATCH 337/937] tests/decodecorpus: add more advanced options - add option to force a specific block type - add option to force a specific literal tyle - add option to generate only frame headers - add option to skip generating magic numbers Co-authored-by: Maciej Dudek Co-authored-by: Pawel Czarnecki Co-authored-by: Robert Winkler Co-authored-by: Roman Dobrodii --- tests/decodecorpus.c | 78 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 70 insertions(+), 8 deletions(-) diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c index 1abc7df8b..f25e5dc7c 100644 --- a/tests/decodecorpus.c +++ b/tests/decodecorpus.c @@ -247,6 +247,12 @@ typedef enum { #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif +typedef enum { + lt_raw, + lt_rle, + lt_compressed, +} literalType_e; + /*-******************************************************* * Global variables (set from command line) *********************************************************/ @@ -259,7 +265,11 @@ U32 g_maxBlockSize = ZSTD_BLOCKSIZE_MAX; /* <= 128 KB */ struct { int contentSize; /* force the content size to be present */ -} opts; /* advanced options on generation */ + blockType_e *blockType; /* force specific block type */ + literalType_e *literalType; /* force specific literals type */ + int frame_header_only; /* generate only frame header */ + int no_magic; /* do not generate magic number */ +} opts; /* Generate and write a random frame header */ static void writeFrameHeader(U32* seed, frame_t* frame, dictInfo info) @@ -288,10 +298,19 @@ static void writeFrameHeader(U32* seed, frame_t* frame, dictInfo info) { /* Generate random content size */ + int force_block_type = opts.blockType != NULL; size_t highBit; if (RAND(seed) & 7 && g_maxDecompressedSizeLog > 7) { /* do content of at least 128 bytes */ highBit = 1ULL << RAND_range(seed, 7, g_maxDecompressedSizeLog); + } else if (force_block_type) { + if ((RAND(seed) & 3) || (*(opts.blockType) == bt_rle)) { + /* do small content */ + highBit = 1ULL << RAND_range(seed, 0, MIN(7, 1U << g_maxDecompressedSizeLog)); + } else { + /* 0 size frame */ + highBit = 0; + } } else if (RAND(seed) & 3) { /* do small content */ highBit = 1ULL << RAND_range(seed, 0, MIN(7, 1U << g_maxDecompressedSizeLog)); @@ -324,8 +343,10 @@ static void writeFrameHeader(U32* seed, frame_t* frame, dictInfo info) } /* write out the header */ - MEM_writeLE32(op + pos, ZSTD_MAGICNUMBER); - pos += 4; + if (!opts.no_magic) { + MEM_writeLE32(op + pos, ZSTD_MAGICNUMBER); + pos += 4; + } { /* @@ -370,8 +391,10 @@ static void writeFrameHeader(U32* seed, frame_t* frame, dictInfo info) /* Write a literal block in either raw or RLE form, return the literals size */ static size_t writeLiteralsBlockSimple(U32* seed, frame_t* frame, size_t contentSize) { + int force_literal_type = opts.literalType != NULL; + int const type = (force_literal_type) ? *(opts.literalType) : RAND(seed) % 2; + BYTE* op = (BYTE*)frame->data; - int const type = RAND(seed) % 2; int const sizeFormatDesc = RAND(seed) % 8; size_t litSize; size_t maxLitSize = MIN(contentSize, g_maxBlockSize); @@ -619,8 +642,15 @@ static size_t writeLiteralsBlockCompressed(U32* seed, frame_t* frame, size_t con static size_t writeLiteralsBlock(U32* seed, frame_t* frame, size_t contentSize) { - /* only do compressed for larger segments to avoid compressibility issues */ - if (RAND(seed) & 7 && contentSize >= 64) { + int select_compressed = 0; + if (opts.literalType) { + select_compressed = *(opts.literalType) == lt_compressed; + } else { + /* only do compressed for larger segments to avoid compressibility issues */ + select_compressed = RAND(seed) & 7 && contentSize >= 64; + } + + if (select_compressed) { return writeLiteralsBlockCompressed(seed, frame, contentSize); } else { return writeLiteralsBlockSimple(seed, frame, contentSize); @@ -1034,7 +1064,8 @@ static size_t writeCompressedBlock(U32* seed, frame_t* frame, size_t contentSize static void writeBlock(U32* seed, frame_t* frame, size_t contentSize, int lastBlock, dictInfo info) { - int const blockTypeDesc = RAND(seed) % 8; + int force_block_type = opts.blockType != NULL; + int const blockTypeDesc = (force_block_type) ? *(opts.blockType) : RAND(seed) % 8; size_t blockSize; int blockType; @@ -1073,7 +1104,7 @@ static void writeBlock(U32* seed, frame_t* frame, size_t contentSize, frame->data = op; compressedSize = writeCompressedBlock(seed, frame, contentSize, info); - if (compressedSize >= contentSize) { /* compressed block must be strictly smaller than uncompressed one */ + if (compressedSize >= contentSize && !force_block_type) { /* compressed block must be strictly smaller than uncompressed one */ blockType = 0; memcpy(op, frame->src, contentSize); @@ -1244,7 +1275,11 @@ static U32 generateFrame(U32 seed, frame_t* fr, dictInfo info) DISPLAYLEVEL(3, "frame seed: %u\n", (unsigned)seed); initFrame(fr); + writeFrameHeader(&seed, fr, info); + if (opts.frame_header_only) + return seed; + writeBlocks(&seed, fr, info); writeChecksum(fr); @@ -1772,6 +1807,9 @@ static void advancedUsage(const char* programName) DISPLAY( " --max-block-size-log=# : max block size log, must be in range [2, 17]\n"); DISPLAY( " --max-content-size-log=# : max content size log, must be <= 20\n"); DISPLAY( " (this is ignored with gen-blocks)\n"); + DISPLAY( " --block-type=# : force certain block type (raw=0, rle=1, compressed=2)\n"); + DISPLAY( " --frame-header-only : dump only frame header\n"); + DISPLAY( " --no-magic : do not add magic number\n"); } /*! readU32FromChar() : @@ -1893,6 +1931,18 @@ int main(int argc, char** argv) U32 value = readU32FromChar(&argument); g_maxDecompressedSizeLog = MIN(MAX_DECOMPRESSED_SIZE_LOG, value); + } else if (longCommandWArg(&argument, "block-type=")) { + U32 value = readU32FromChar(&argument); + opts.blockType = malloc(sizeof(blockType_e)); + *(opts.blockType) = value; + } else if (longCommandWArg(&argument, "literal-type=")) { + U32 value = readU32FromChar(&argument); + opts.literalType = malloc(sizeof(literalType_e)); + *(opts.literalType) = value; + } else if (strcmp(argument, "frame-header-only") == 0) { + opts.frame_header_only = 1; + } else if (strcmp(argument, "no-magic") == 0) { + opts.no_magic = 1; } else { advancedUsage(argv[0]); return 1; @@ -1904,6 +1954,18 @@ int main(int argc, char** argv) return 1; } } } } /* for (argNb=1; argNb Date: Mon, 29 Jul 2024 05:34:32 +0000 Subject: [PATCH 338/937] Bump ossf/scorecard-action from 2.3.1 to 2.4.0 Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.3.1 to 2.4.0. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/0864cf19026789058feabb7e87baa5f140aac736...62b2cac7ed8198b15735ed49ab1e5cf35480ba46) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index e117798ea..9ded4f1cd 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -32,7 +32,7 @@ jobs: persist-credentials: false - name: "Run analysis" - uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # tag=v2.3.1 + uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # tag=v2.4.0 with: results_file: results.sarif results_format: sarif From 46a3135524b1ea9cd46ea5cd61529f1231606465 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 29 Jul 2024 05:34:42 +0000 Subject: [PATCH 339/937] Bump msys2/setup-msys2 from 2.23.0 to 2.24.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.23.0 to 2.24.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8...5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 82e893cb9..ba43be3cb 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -247,7 +247,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 + - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 0269e8369..524e5929c 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -499,7 +499,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 + - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 761b6c854..92df8589b 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -24,7 +24,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3 - - uses: msys2/setup-msys2@d0e80f58dffbc64f6a3a1f43527d469b4fc7b6c8 # tag=v2.23.0 + - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 with: msystem: ${{ matrix.msystem }} install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc From c3c28c4d5a28bca93c97c4ce447f3c8ece42791d Mon Sep 17 00:00:00 2001 From: Adenilson Cavalcanti Date: Mon, 29 Jul 2024 16:37:41 -0700 Subject: [PATCH 340/937] [zstd][android] Fix build with NDK r27 The NDK cross compiler declares the target as __linux (which is not technically incorrect), which triggers the enablement of _GNU_SOURCE in the newly added code that requires the presence of qsort_r() used in the COVER dictionary code. Even though the NDK uses llvm/libc, it doesn't declare qsort_r() in the stdlib.h header. The build fix is to only activate the _GNU_SOURCE macro if the OS is *not* Android, as then we will fallback to the C90 compliant code. This patch should solve the reported issue number #4103. --- lib/common/zstd_deps.h | 2 +- lib/dictBuilder/cover.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/zstd_deps.h b/lib/common/zstd_deps.h index f41a973c3..8a9c7cc53 100644 --- a/lib/common/zstd_deps.h +++ b/lib/common/zstd_deps.h @@ -31,7 +31,7 @@ */ #if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ defined(__CYGWIN__) || defined(__MSYS__) -#if !defined(_GNU_SOURCE) +#if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ #define _GNU_SOURCE #endif #endif diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 386a4d572..2ef33c73e 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -24,7 +24,7 @@ /* qsort_r is an extension. */ #if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ defined(__CYGWIN__) || defined(__MSYS__) -#if !defined(_GNU_SOURCE) +#if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ #define _GNU_SOURCE #endif #endif From cb784edf5de07940c0f48bae6cf8c4b2f4993705 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 30 Jul 2024 11:02:16 -0700 Subject: [PATCH 341/937] added android-ndk-build --- .github/workflows/android-ndk-build.yml | 37 +++++++++++++++++++++++++ lib/compress/zstd_compress_internal.h | 4 +-- lib/compress/zstd_cwksp.h | 5 ++-- 3 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/android-ndk-build.yml diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml new file mode 100644 index 000000000..53b0fc978 --- /dev/null +++ b/.github/workflows/android-ndk-build.yml @@ -0,0 +1,37 @@ +name: Android NDK Build + +on: + pull_request: + branches: [ dev, release, actionsTest ] + push: + branches: [ actionsTest, '*ndk*' ] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + + - name: Setup Android SDK + uses: android-actions/setup-android@v3 + + - name: Install Android NDK + run: | + sdkmanager --install "ndk;27.0.12077973" + echo "ANDROID_NDK_HOME=$ANDROID_SDK_ROOT/ndk/27.0.12077973" >> $GITHUB_ENV + + - name: Build with NDK + run: | + export PATH=$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH + make CC=aarch64-linux-android21-clang \ + AR=llvm-ar \ + RANLIB=llvm-ranlib \ + STRIP=llvm-strip + diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index f8ec1c82e..ba1450852 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1246,8 +1246,8 @@ MEM_STATIC void ZSTD_window_init(ZSTD_window_t* window) { MEM_STATIC ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_window_update(ZSTD_window_t* window, - void const* src, size_t srcSize, - int forceNonContiguous) + const void* src, size_t srcSize, + int forceNonContiguous) { BYTE const* const ip = (BYTE const*)src; U32 contiguous = 1; diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index 3eddbd334..dcd485cb5 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -287,7 +287,7 @@ ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp* ws, size_t const bytes) { void* const alloc = (BYTE*)ws->allocStart - bytes; void* const bottom = ws->tableEnd; - DEBUGLOG(5, "cwksp: reserving %p %zd bytes, %zd bytes remaining", + DEBUGLOG(5, "cwksp: reserving [0x%p]:%zd bytes; %zd bytes remaining", alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes); ZSTD_cwksp_assert_internal_consistency(ws); assert(alloc >= bottom); @@ -577,7 +577,8 @@ MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) { * Invalidates table allocations. * All other allocations remain valid. */ -MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) { +MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) +{ DEBUGLOG(4, "cwksp: clearing tables!"); #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE) From 688a815c8643c8ea2475ac90bdd261bbcc43631b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 05:17:43 +0000 Subject: [PATCH 342/937] Bump msys2/setup-msys2 from 2.24.0 to 2.24.1 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.24.0 to 2.24.1. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2...ddf331adaebd714795f1042345e6ca57bd66cea8) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index ba43be3cb..d9f074369 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -247,7 +247,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 + - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 524e5929c..7713a897c 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -499,7 +499,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 + - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 92df8589b..ff81b504a 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -24,7 +24,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3 - - uses: msys2/setup-msys2@5df0ca6cbf14efcd08f8d5bd5e049a3cc8e07fd2 # tag=v2.24.0 + - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1 with: msystem: ${{ matrix.msystem }} install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc From 89451cafbd92a350b4a924d0020efbc775054378 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 6 Aug 2024 11:44:37 -0700 Subject: [PATCH 343/937] formatString_u() can display numbers > 100 fixes #4110 --- programs/benchzstd.c | 63 +++++++++++++++++++++++++------------------- 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index 29ee595c1..075640e82 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -139,52 +139,61 @@ static const size_t maxMemory = (sizeof(size_t) == 4) return r; \ } -/* replacement for snprintf(), which is not supported by C89 - * sprintf() would be the supported one, but it's labelled unsafe, - * so some modern static analyzer will flag it as such, making it unusable. - * formatString_u() replaces snprintf() for the specific case where there are only %u arguments */ +static size_t uintSize(unsigned value) +{ + size_t size = 1; + while (value >= 10) { + size++; + value /= 10; + } + return size; +} + +// Note: presume @buffer is large enough +static void writeUint_varLen(char* buffer, size_t capacity, unsigned value) +{ + int endPos = (int)uintSize(value) - 1; + assert(uintSize(value) >= 1); + assert(uintSize(value) < capacity); (void)capacity; + while (endPos >= 0) { + char c = '0' + (char)(value % 10); + buffer[endPos--] = c; + value /= 10; + } +} + +/* replacement for snprintf(), which is not supported by C89. + * sprintf() would be the supported one, but it's labelled unsafe: + * modern static analyzer will flag sprintf() as dangerous, making it unusable. + * formatString_u() replaces snprintf() for the specific case where there is only one %u argument */ static int formatString_u(char* buffer, size_t buffer_size, const char* formatString, unsigned int value) { + size_t const valueSize = uintSize(value); size_t written = 0; int i; - assert(value <= 100); - for (i = 0; formatString[i] != '\0' && written < buffer_size - 1; ++i) { + for (i = 0; formatString[i] != '\0' && written < buffer_size - 1; i++) { if (formatString[i] != '%') { buffer[written++] = formatString[i]; continue; } - if (formatString[++i] == 'u') { - /* Handle single digit */ - if (value < 10) { - buffer[written++] = '0' + (char)value; - } else if (value < 100) { - /* Handle two digits */ - if (written >= buffer_size - 2) { - return -1; /* buffer overflow */ - } - buffer[written++] = '0' + (char)(value / 10); - buffer[written++] = '0' + (char)(value % 10); - } else { /* 100 */ - if (written >= buffer_size - 3) { - return -1; /* buffer overflow */ - } - buffer[written++] = '1'; - buffer[written++] = '0'; - buffer[written++] = '0'; - } + i++; + if (formatString[i] == 'u') { + if (written + valueSize >= buffer_size) abort(); /* buffer not large enough */ + writeUint_varLen(buffer + written, buffer_size - written, value); + written += valueSize; } else if (formatString[i] == '%') { /* Check for escaped percent sign */ buffer[written++] = '%'; } else { - return -1; /* unsupported format */ + abort(); /* unsupported format */ } } if (written < buffer_size) { buffer[written] = '\0'; } else { - buffer[0] = '\0'; /* Handle truncation */ + abort(); /* buffer not large enough */ } return (int)written; From 14b8d398fd0f9155203031239748537e7df2ad75 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 6 Aug 2024 12:47:30 -0700 Subject: [PATCH 344/937] fix c90 comment style --- programs/benchzstd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index 075640e82..272af5924 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -149,7 +149,7 @@ static size_t uintSize(unsigned value) return size; } -// Note: presume @buffer is large enough +/* Note: presume @buffer is large enough */ static void writeUint_varLen(char* buffer, size_t capacity, unsigned value) { int endPos = (int)uintSize(value) - 1; From 6dbd49bcd04c42b0b4893d824b856563ae901b33 Mon Sep 17 00:00:00 2001 From: Adenilson Cavalcanti Date: Tue, 6 Aug 2024 16:55:32 -0700 Subject: [PATCH 345/937] [riscv] Enable support for weak symbols Both gcc and clang support weak symbols on RISC-V, therefore let's enable it. This should fix issue #4069. --- lib/common/zstd_trace.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/common/zstd_trace.h b/lib/common/zstd_trace.h index da20534eb..173d63fb1 100644 --- a/lib/common/zstd_trace.h +++ b/lib/common/zstd_trace.h @@ -21,13 +21,14 @@ extern "C" { * For now, enable conservatively: * - Only GNUC * - Only ELF - * - Only x86-64, i386 and aarch64 + * - Only x86-64, i386, aarch64 and risc-v. * Also, explicitly disable on platforms known not to work so they aren't * forgotten in the future. */ #if !defined(ZSTD_HAVE_WEAK_SYMBOLS) && \ defined(__GNUC__) && defined(__ELF__) && \ - (defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86) || defined(__aarch64__)) && \ + (defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \ + defined(_M_IX86) || defined(__aarch64__) || defined(__riscv)) && \ !defined(__APPLE__) && !defined(_WIN32) && !defined(__MINGW32__) && \ !defined(__CYGWIN__) && !defined(_AIX) # define ZSTD_HAVE_WEAK_SYMBOLS 1 From a40bad8ec06aeb992e8d8e58648a4024261b2a54 Mon Sep 17 00:00:00 2001 From: Adenilson Cavalcanti Date: Tue, 6 Aug 2024 17:16:28 -0700 Subject: [PATCH 346/937] [zstd][leak] Avoid memory leak on early return of ZSTD_generateSequence Sanity checks on a few of the context parameters (i.e. workers and block size) may prompt an early return on ZSTD_generateSequences. Allocating the destination buffer past those return points avoids a potential memory leak. This patch should fix issue #4112. --- lib/compress/zstd_compress.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 18f929bbe..aad25049d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3458,7 +3458,7 @@ size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, size_t outSeqsSize, const void* src, size_t srcSize) { const size_t dstCapacity = ZSTD_compressBound(srcSize); - void* dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem); + void* dst; /* Make C90 happy. */ SeqCollector seqCollector; { int targetCBlockSize; @@ -3471,6 +3471,7 @@ size_t ZSTD_generateSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs, RETURN_ERROR_IF(nbWorkers != 0, parameter_unsupported, "nbWorkers != 0"); } + dst = ZSTD_customMalloc(dstCapacity, ZSTD_defaultCMem); RETURN_ERROR_IF(dst == NULL, memory_allocation, "NULL pointer!"); seqCollector.collectSequences = 1; From bf4a43fcd45aea991d273160262a31925ea31ba3 Mon Sep 17 00:00:00 2001 From: Xionghu Luo Date: Thu, 8 Aug 2024 15:13:27 +0800 Subject: [PATCH 347/937] Fix zstd-pgo run error The -Werror=missing-profile caused thread/zlib/lzma/lz4 detection failure when build with profile-use, thus caused ZSTD_MULTITHREAD etc. is not defined for profile-use, then there will be many profile mismatch information in output and the final binary reports run error sometimes as below: Error : ZSTD_CCtx_setParameter(ctx, ZSTD_c_nbWorkers, adv->nbWorkers) failed : Unsupported parameter Signed-off-by: Xionghu Luo --- programs/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/Makefile b/programs/Makefile index e1a30fc2b..4d32e0fa8 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -232,7 +232,7 @@ zstd-dll : zstd .PHONY: zstd-pgo zstd-pgo : LLVM_PROFDATA?=llvm-profdata zstd-pgo : PROF_GENERATE_FLAGS=-fprofile-generate $(if $(findstring gcc,$(CC)),-fprofile-dir=.) -zstd-pgo : PROF_USE_FLAGS=-fprofile-use $(if $(findstring gcc,$(CC)),-fprofile-dir=. -Werror=missing-profile -Wno-error=coverage-mismatch) +zstd-pgo : PROF_USE_FLAGS=-fprofile-use $(if $(findstring gcc,$(CC)),-fprofile-dir=. -Wno-error=missing-profile -Wno-error=coverage-mismatch) zstd-pgo : $(MAKE) clean HASH_DIR=$(HASH_DIR) $(MAKE) zstd HASH_DIR=$(HASH_DIR) MOREFLAGS="$(PROF_GENERATE_FLAGS)" From aed3c7540a904b2dbb12fd88038bd09d743ca05d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 05:16:05 +0000 Subject: [PATCH 348/937] Bump actions/setup-java from 3 to 4 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/setup-java dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 53b0fc978..c77d5f0d1 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -14,7 +14,7 @@ jobs: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' From ec0c41414d5d41e6e49b5bd7402a7252ad91e7e7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 05:37:33 +0000 Subject: [PATCH 349/937] Bump github/codeql-action from 3.25.1 to 3.26.2 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.25.1 to 3.26.2. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/c7f9125735019aa87cfc361530512d50ea439c71...429e1977040da7a23b6822b13c129cd1ba93dbb2) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 9ded4f1cd..ccd7956a5 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@c7f9125735019aa87cfc361530512d50ea439c71 # tag=v3.25.1 + uses: github/codeql-action/upload-sarif@429e1977040da7a23b6822b13c129cd1ba93dbb2 # tag=v3.26.2 with: sarif_file: results.sarif From 09cb37cbb1be014756fbc00d3c5db8eaec20f32d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 21 Aug 2024 10:53:25 -0700 Subject: [PATCH 350/937] Limit range of operations on Indexes in 32-bit mode and use unsigned type. This reduce risks that an operation produces a negative number when crossing the 2 GB limit. --- lib/compress/zstd_compress_internal.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index ba1450852..6c76b5848 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -918,11 +918,12 @@ MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 /*-************************************* * Round buffer management ***************************************/ -#if (ZSTD_WINDOWLOG_MAX_64 > 31) -# error "ZSTD_WINDOWLOG_MAX is too large : would overflow ZSTD_CURRENT_MAX" -#endif -/* Max current allowed */ -#define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX)) +/* Max @current value allowed: + * In 32-bit mode: we want to avoid crossing the 2 GB limit, + * reducing risks of side effects in case of signed operations on indexes. + * In 64-bit mode: we want to ensure that adding the maximum job size (512 MB) + * doesn't overflow U32 index capacity (4 GB) */ +#define ZSTD_CURRENT_MAX (MEM_64bits() ? 3500U MB : 2000U MB) /* Maximum chunk size before overflow correction needs to be called again */ #define ZSTD_CHUNKSIZE_MAX \ ( ((U32)-1) /* Maximum ending current index */ \ @@ -1274,8 +1275,9 @@ U32 ZSTD_window_update(ZSTD_window_t* window, /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */ if ( (ip+srcSize > window->dictBase + window->lowLimit) & (ip < window->dictBase + window->dictLimit)) { - ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase; - U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx; + size_t const highInputIdx = (size_t)((ip + srcSize) - window->dictBase); + U32 const lowLimitMax = (highInputIdx > (size_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx; + assert(highInputIdx < UINT_MAX); window->lowLimit = lowLimitMax; DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit); } From 7a48dc230c42ba4d779fab4e68da14f44c92a7b3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Sep 2024 09:50:30 -0700 Subject: [PATCH 351/937] fix doc nit: ZDICT_DICTSIZE_MIN fix #4142 --- lib/zdict.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/zdict.h b/lib/zdict.h index 2268f948a..bcccf750e 100644 --- a/lib/zdict.h +++ b/lib/zdict.h @@ -248,7 +248,7 @@ typedef struct { * is presumed that the most profitable content is at the end of the dictionary, * since that is the cheapest to reference. * - * `maxDictSize` must be >= max(dictContentSize, ZSTD_DICTSIZE_MIN). + * `maxDictSize` must be >= max(dictContentSize, ZDICT_DICTSIZE_MIN). * * @return: size of dictionary stored into `dstDictBuffer` (<= `maxDictSize`), * or an error code, which can be tested by ZDICT_isError(). From e8fce38954efd6bc58a5b0ec72dd26f41c8365e6 Mon Sep 17 00:00:00 2001 From: Ilya Tokar Date: Wed, 18 Sep 2024 17:36:37 -0400 Subject: [PATCH 352/937] Optimize compression by avoiding unpredictable branches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Avoid unpredictable branch. Use conditional move to generate the address that is guaranteed to be safe and compare unconditionally. Instead of if (idx < limit && x[idx] == val ) // mispredicted idx < limit branch Do addr = cmov(safe,x+idx) if (*addr == val && idx < limit) // almost always false so well predicted Using microbenchmarks from https://github.com/google/fleetbench, I get about ~10% speed-up: name old cpu/op new cpu/op delta BM_ZSTD_COMPRESS_Fleet/compression_level:-7/window_log:15 1.46ns ± 3% 1.31ns ± 7% -9.88% (p=0.000 n=35+38) BM_ZSTD_COMPRESS_Fleet/compression_level:-7/window_log:16 1.41ns ± 3% 1.28ns ± 3% -9.56% (p=0.000 n=36+39) BM_ZSTD_COMPRESS_Fleet/compression_level:-5/window_log:15 1.61ns ± 1% 1.43ns ± 3% -10.70% (p=0.000 n=30+39) BM_ZSTD_COMPRESS_Fleet/compression_level:-5/window_log:16 1.54ns ± 2% 1.39ns ± 3% -9.21% (p=0.000 n=37+39) BM_ZSTD_COMPRESS_Fleet/compression_level:-3/window_log:15 1.82ns ± 2% 1.61ns ± 3% -11.31% (p=0.000 n=37+40) BM_ZSTD_COMPRESS_Fleet/compression_level:-3/window_log:16 1.73ns ± 3% 1.56ns ± 3% -9.50% (p=0.000 n=38+39) BM_ZSTD_COMPRESS_Fleet/compression_level:-1/window_log:15 2.12ns ± 2% 1.79ns ± 3% -15.55% (p=0.000 n=34+39) BM_ZSTD_COMPRESS_Fleet/compression_level:-1/window_log:16 1.99ns ± 3% 1.72ns ± 3% -13.70% (p=0.000 n=38+38) BM_ZSTD_COMPRESS_Fleet/compression_level:0/window_log:15 3.22ns ± 3% 2.94ns ± 3% -8.67% (p=0.000 n=38+40) BM_ZSTD_COMPRESS_Fleet/compression_level:0/window_log:16 3.19ns ± 4% 2.86ns ± 4% -10.55% (p=0.000 n=40+38) BM_ZSTD_COMPRESS_Fleet/compression_level:1/window_log:15 2.60ns ± 3% 2.22ns ± 3% -14.53% (p=0.000 n=40+39) BM_ZSTD_COMPRESS_Fleet/compression_level:1/window_log:16 2.46ns ± 3% 2.13ns ± 2% -13.67% (p=0.000 n=39+36) BM_ZSTD_COMPRESS_Fleet/compression_level:2/window_log:15 2.69ns ± 3% 2.46ns ± 3% -8.63% (p=0.000 n=37+39) BM_ZSTD_COMPRESS_Fleet/compression_level:2/window_log:16 2.63ns ± 3% 2.36ns ± 3% -10.47% (p=0.000 n=40+40) BM_ZSTD_COMPRESS_Fleet/compression_level:3/window_log:15 3.20ns ± 2% 2.95ns ± 3% -7.94% (p=0.000 n=35+40) BM_ZSTD_COMPRESS_Fleet/compression_level:3/window_log:16 3.20ns ± 4% 2.87ns ± 4% -10.33% (p=0.000 n=40+40) I've also measured the impact on internal workloads and saw similar ~10% improvement in performance, measured by cpu usage/byte of data. --- lib/compress/zstd_compress_internal.h | 17 ++++++++++++ lib/compress/zstd_double_fast.c | 37 +++++++++++++++++---------- lib/compress/zstd_fast.c | 32 ++++++++++++++--------- 3 files changed, 61 insertions(+), 25 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index ba1450852..cbcded28d 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -557,6 +557,23 @@ MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value) return 1; } +/* ZSTD_selectAddr: + * @return a >= b ? trueAddr : falseAddr, + * tries to force branchless codegen. */ +MEM_STATIC const BYTE* ZSTD_selectAddr(U32 a, U32 b, const BYTE* trueAddr, const BYTE* falseAddr) { +#if defined(__GNUC__) && defined(__x86_64__) + __asm__ ( + "cmp %1, %2\n" + "cmova %3, %0\n" + : "+r"(trueAddr) + : "r"(a), "r"(b), "r"(falseAddr) + ); + return trueAddr; +#else + return a >= b ? trueAddr : falseAddr; +#endif +} + /* ZSTD_noCompressBlock() : * Writes uncompressed block to dst buffer from given src. * Returns the size of the block */ diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 1b5f64f20..819658caf 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -140,11 +140,17 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( U32 idxl1; /* the long match index for ip1 */ const BYTE* matchl0; /* the long match for ip */ + const BYTE* matchl0_safe; /* matchl0 or safe address */ const BYTE* matchs0; /* the short match for ip */ const BYTE* matchl1; /* the long match for ip1 */ + const BYTE* matchs0_safe; /* matchs0 or safe address */ const BYTE* ip = istart; /* the current position */ const BYTE* ip1; /* the next position */ + /* Array of ~random data, should have low probability of matching data + * we load from here instead of from tables, if matchl0/matchl1 are + * invalid indices. Used to avoid unpredictable branches. */ + const BYTE dummy[] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0xe2,0xb4}; DEBUGLOG(5, "ZSTD_compressBlock_doubleFast_noDict_generic"); @@ -191,24 +197,29 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( hl1 = ZSTD_hashPtr(ip1, hBitsL, 8); - if (idxl0 > prefixLowestIndex) { - /* check prefix long match */ - if (MEM_read64(matchl0) == MEM_read64(ip)) { - mLength = ZSTD_count(ip+8, matchl0+8, iend) + 8; - offset = (U32)(ip-matchl0); - while (((ip>anchor) & (matchl0>prefixLowest)) && (ip[-1] == matchl0[-1])) { ip--; matchl0--; mLength++; } /* catch up */ - goto _match_found; - } + /* idxl0 > prefixLowestIndex is a (somewhat) unpredictable branch. + * However expression below complies into conditional move. Since + * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex + * if there is a match, all branches become predictable. */ + matchl0_safe = ZSTD_selectAddr(prefixLowestIndex, idxl0, &dummy[0], matchl0); + + /* check prefix long match */ + if (MEM_read64(matchl0_safe) == MEM_read64(ip) && matchl0_safe == matchl0) { + mLength = ZSTD_count(ip+8, matchl0+8, iend) + 8; + offset = (U32)(ip-matchl0); + while (((ip>anchor) & (matchl0>prefixLowest)) && (ip[-1] == matchl0[-1])) { ip--; matchl0--; mLength++; } /* catch up */ + goto _match_found; } idxl1 = hashLong[hl1]; matchl1 = base + idxl1; - if (idxs0 > prefixLowestIndex) { - /* check prefix short match */ - if (MEM_read32(matchs0) == MEM_read32(ip)) { - goto _search_next_long; - } + /* Same optimization as matchl0 above */ + matchs0_safe = ZSTD_selectAddr(prefixLowestIndex, idxs0, &dummy[0], matchs0); + + /* check prefix short match */ + if(MEM_read32(matchs0_safe) == MEM_read32(ip) && matchs0_safe == matchs0) { + goto _search_next_long; } if (ip1 >= nextStep) { diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index c6baa49d4..838a18ee5 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -162,6 +162,11 @@ size_t ZSTD_compressBlock_fast_noDict_generic( const BYTE* const prefixStart = base + prefixStartIndex; const BYTE* const iend = istart + srcSize; const BYTE* const ilimit = iend - HASH_READ_SIZE; + /* Array of ~random data, should have low probability of matching data + * we load from here instead of from tables, if the index is invalid. + * Used to avoid unpredictable branches. */ + const BYTE dummy[] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0xe2,0xb4}; + const BYTE *mvalAddr; const BYTE* anchor = istart; const BYTE* ip0 = istart; @@ -246,15 +251,18 @@ _start: /* Requires: ip0 */ goto _match; } + /* idx >= prefixStartIndex is a (somewhat) unpredictable branch. + * However expression below complies into conditional move. Since + * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex + * if there is a match, all branches become predictable. */ + mvalAddr = base + idx; + mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, mvalAddr, &dummy[0]); + /* load match for ip[0] */ - if (idx >= prefixStartIndex) { - mval = MEM_read32(base + idx); - } else { - mval = MEM_read32(ip0) ^ 1; /* guaranteed to not match. */ - } + mval = MEM_read32(mvalAddr); /* check match at ip[0] */ - if (MEM_read32(ip0) == mval) { + if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { /* found a match! */ /* First write next hash table entry; we've already calculated it. @@ -281,15 +289,15 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; + mvalAddr = base + idx; + mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, mvalAddr, &dummy[0]); + /* load match for ip[0] */ - if (idx >= prefixStartIndex) { - mval = MEM_read32(base + idx); - } else { - mval = MEM_read32(ip0) ^ 1; /* guaranteed to not match. */ - } + mval = MEM_read32(mvalAddr); + /* check match at ip[0] */ - if (MEM_read32(ip0) == mval) { + if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { /* found a match! */ /* first write next hash table entry; we've already calculated it */ From a8b544d460f3db9a79d630d95f1fa3564c29be12 Mon Sep 17 00:00:00 2001 From: inventor500 Date: Sat, 31 Aug 2024 07:23:51 -0500 Subject: [PATCH 353/937] Fixed warning when compiling pzstd with CPPFLAGS=-Wunused-result and CXXFLAGS=-std=c++17 --- contrib/pzstd/Options.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/pzstd/Options.cpp b/contrib/pzstd/Options.cpp index a77824edb..43ea2721d 100644 --- a/contrib/pzstd/Options.cpp +++ b/contrib/pzstd/Options.cpp @@ -322,7 +322,7 @@ Options::Status Options::parse(int argc, const char **argv) { g_utilDisplayLevel = verbosity; // Remove local input files that are symbolic links if (!followLinks) { - std::remove_if(localInputFiles.begin(), localInputFiles.end(), + std::ignore = std::remove_if(localInputFiles.begin(), localInputFiles.end(), [&](const char *path) { bool isLink = UTIL_isLink(path); if (isLink && verbosity >= 2) { From 9215de52c7029bdad06d5fa59a4777edf0c92df9 Mon Sep 17 00:00:00 2001 From: inventor500 Date: Wed, 25 Sep 2024 10:21:20 -0500 Subject: [PATCH 354/937] Included suggestion from @neheb --- contrib/pzstd/Options.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/pzstd/Options.cpp b/contrib/pzstd/Options.cpp index 43ea2721d..90841b9bb 100644 --- a/contrib/pzstd/Options.cpp +++ b/contrib/pzstd/Options.cpp @@ -322,7 +322,7 @@ Options::Status Options::parse(int argc, const char **argv) { g_utilDisplayLevel = verbosity; // Remove local input files that are symbolic links if (!followLinks) { - std::ignore = std::remove_if(localInputFiles.begin(), localInputFiles.end(), + localInputFiles.erase(std::remove_if(localInputFiles.begin(), localInputFiles.end(), [&](const char *path) { bool isLink = UTIL_isLink(path); if (isLink && verbosity >= 2) { @@ -332,7 +332,7 @@ Options::Status Options::parse(int argc, const char **argv) { path); } return isLink; - }); + }), localInputFiles.end()); } // Translate input files/directories into files to (de)compress From 039f404faa9230e389b360c80d6c842fae3f75a0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 25 Sep 2024 16:56:01 -0700 Subject: [PATCH 355/937] update documentation to specify that Dictionary can be used for benchmark fix #4139 --- programs/zstd.1.md | 4 ++++ programs/zstdcli.c | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 5188be6a5..d0473fa47 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -674,6 +674,10 @@ Note that the results are highly dependent on the content being compressed. minimum evaluation time, in seconds (default: 3s), benchmark mode only * `-B#`, `--block-size=#`: cut file(s) into independent chunks of size # (default: no chunking) +* `-S`: + output one benchmark result per input file (default: consolidated result) +* `-D dictionary` + benchmark using dictionary * `--priority=rt`: set process priority to real-time (Windows) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 9dd6b051a..d8e908d85 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -32,7 +32,6 @@ #include /* getenv */ #include /* strcmp, strlen */ #include /* fprintf(), stdin, stdout, stderr */ -#include /* errno */ #include /* assert */ #include "fileio.h" /* stdinmark, stdoutmark, ZSTD_EXTENSION */ @@ -311,6 +310,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" -i# Set the minimum evaluation to time # seconds. [Default: 3]\n"); DISPLAYOUT(" -B# Cut file into independent chunks of size #. [Default: No chunking]\n"); DISPLAYOUT(" -S Output one benchmark result per input file. [Default: Consolidated result]\n"); + DISPLAYOUT(" -D dictionary Benchmark using dictionary \n"); DISPLAYOUT(" --priority=rt Set process priority to real-time.\n"); #endif From a3b5c4521c954af9b2a2bf2b1df9a4bb70f0c46d Mon Sep 17 00:00:00 2001 From: dearblue Date: Mon, 30 Sep 2024 22:45:17 +0900 Subject: [PATCH 356/937] Update FreeBSD VM image to 14.1 FreeBSD 14.0 will reach the end of life on 2024-09-30. The updated 14.1 is scheduled to end-of-life on 2025-03-31. ref. https://www.freebsd.org/releases/14.2R/schedule/ --- .cirrus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index f68e39ae1..e3617a960 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -2,7 +2,7 @@ task: name: FreeBSD (shortest) freebsd_instance: matrix: - image_family: freebsd-14-0 + image_family: freebsd-14-1 install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From d2d49a11618bd3958b0501942b3525d9431008c1 Mon Sep 17 00:00:00 2001 From: Artem Labazov <123321artyom@gmail.com> Date: Mon, 30 Sep 2024 17:00:42 +0300 Subject: [PATCH 357/937] meson: Do not export private headers in libzstd_dep to avoid name clash This way libzstd_dep does not override, for instance, --- build/meson/lib/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/meson/lib/meson.build b/build/meson/lib/meson.build index 68db2ca6c..6c5d53d1a 100644 --- a/build/meson/lib/meson.build +++ b/build/meson/lib/meson.build @@ -124,7 +124,7 @@ libzstd = library('zstd', version: zstd_libversion) libzstd_dep = declare_dependency(link_with: libzstd, - include_directories: libzstd_includes) + include_directories: join_paths(zstd_rootdir,'lib')) # Do not expose private headers # we link to both: # - the shared library (for public symbols) From ccc02a9a7786c7556d31cfd3d7b08ba8d6895eea Mon Sep 17 00:00:00 2001 From: Artem Labazov Date: Mon, 30 Sep 2024 18:05:57 +0300 Subject: [PATCH 358/937] meson: Fix contrib and tests build --- build/meson/contrib/pzstd/meson.build | 2 +- build/meson/lib/meson.build | 9 ++++++--- build/meson/tests/meson.build | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/build/meson/contrib/pzstd/meson.build b/build/meson/contrib/pzstd/meson.build index b95dc7964..c3ee3d60a 100644 --- a/build/meson/contrib/pzstd/meson.build +++ b/build/meson/contrib/pzstd/meson.build @@ -20,6 +20,6 @@ pzstd = executable('pzstd', pzstd_sources, cpp_args: pzstd_warning_flags, include_directories: pzstd_includes, - dependencies: [ libzstd_dep, thread_dep ], + dependencies: [ libzstd_internal_dep, thread_dep ], override_options: ['b_ndebug=true'], install: true) diff --git a/build/meson/lib/meson.build b/build/meson/lib/meson.build index 6c5d53d1a..4ff926f9c 100644 --- a/build/meson/lib/meson.build +++ b/build/meson/lib/meson.build @@ -134,7 +134,8 @@ libzstd_dep = declare_dependency(link_with: libzstd, # -fvisibility=hidden means those cannot be found if get_option('default_library') == 'static' libzstd_static = libzstd - libzstd_internal_dep = libzstd_dep + libzstd_internal_dep = declare_dependency(link_with: libzstd, + include_directories: libzstd_includes) else if get_option('default_library') == 'shared' libzstd_static = static_library('zstd_objlib', @@ -147,11 +148,13 @@ else if cc_id == compiler_msvc # msvc does not actually support linking to both, but errors out with: # error LNK2005: ZSTD_ already defined in zstd.lib(zstd-1.dll) - libzstd_internal_dep = declare_dependency(link_with: libzstd_static) + libzstd_internal_dep = declare_dependency(link_with: libzstd_static, + include_directories: libzstd_includes) else libzstd_internal_dep = declare_dependency(link_with: libzstd, # the static library must be linked after the shared one - dependencies: declare_dependency(link_with: libzstd_static)) + dependencies: declare_dependency(link_with: libzstd_static), + include_directories: libzstd_includes) endif endif diff --git a/build/meson/tests/meson.build b/build/meson/tests/meson.build index 9847ab037..71ffc5069 100644 --- a/build/meson/tests/meson.build +++ b/build/meson/tests/meson.build @@ -93,7 +93,7 @@ roundTripCrash = executable('roundTripCrash', longmatch_sources = [join_paths(zstd_rootdir, 'tests/longmatch.c')] longmatch = executable('longmatch', longmatch_sources, - dependencies: [ libzstd_dep ], + dependencies: [ libzstd_internal_dep ], install: false) invalidDictionaries_sources = [join_paths(zstd_rootdir, 'tests/invalidDictionaries.c')] From 3d5d3f5630acdb14ddd94721b2011dca8eaf496a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 30 Sep 2024 21:38:29 -0700 Subject: [PATCH 359/937] removing nightly tests built on circleci --- .circleci/config.yml | 123 ---------------------------- .circleci/images/primary/Dockerfile | 9 -- .github/workflows/nightly.yml | 29 ------- 3 files changed, 161 deletions(-) delete mode 100644 .circleci/config.yml delete mode 100644 .circleci/images/primary/Dockerfile diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 621ac49ff..000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,123 +0,0 @@ -version: 2 - -jobs: - # the first half of the jobs are in this test - short-tests-0: - # TODO: Create a small custom docker image with all the dependencies we need - # preinstalled to reduce installation time. - docker: - - image: fbopensource/zstd-circleci-primary:0.0.1 - steps: - - checkout - - run: - name: Test - command: | - ./tests/test-license.py - cc -v - CFLAGS="-O0 -Werror -pedantic" make allmost; make clean - make c99build; make clean - make c11build; make clean - make -j regressiontest; make clean - make shortest; make clean - make cxxtest; make clean - # the second half of the jobs are in this test - short-tests-1: - docker: - - image: fbopensource/zstd-circleci-primary:0.0.1 - steps: - - checkout - - run: - name: Test - command: | - make gnu90build; make clean - make gnu99build; make clean - make ppc64build V=1; make clean - make ppcbuild V=1; make clean - make armbuild V=1; make clean - make aarch64build V=1; make clean - make -C tests test-legacy test-longmatch; make clean - make -C lib libzstd-nomt; make clean - # This step should only be run in a cron job - regression-test: - docker: - - image: fbopensource/zstd-circleci-primary:0.0.1 - environment: - CIRCLE_ARTIFACTS: /tmp/circleci-artifacts - steps: - - checkout - # Restore the cached resources. - - restore_cache: - # We try our best to bust the cache when the data changes by hashing - # data.c. If that doesn't work, simply update the version number here - # and below. If we fail to bust the cache, the regression testing will - # still work, since it has its own stamp, but will need to redownload - # everything. - keys: - - regression-cache-{{ checksum "tests/regression/data.c" }}-v0 - - run: - name: Regression Test - command: | - make -C programs zstd - make -C tests/regression test - mkdir -p $CIRCLE_ARTIFACTS - ./tests/regression/test \ - --cache tests/regression/cache \ - --output $CIRCLE_ARTIFACTS/results.csv \ - --zstd programs/zstd - echo "NOTE: The new results.csv is uploaded as an artifact to this job" - echo " If this fails, go to the Artifacts pane in CircleCI, " - echo " download /tmp/circleci-artifacts/results.csv, and if they " - echo " are still good, copy it into the repo and commit it." - echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" - diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv - # Only save the cache on success (default), since if the failure happened - # before we stamp the data cache, we will have a bad cache for this key. - - save_cache: - key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 - paths: - - tests/regression/cache - - store_artifacts: - path: /tmp/circleci-artifacts - - -workflows: - version: 2 - commit: - jobs: - # Run the tests in parallel - - short-tests-0 - - short-tests-1 - - regression-test - - nightly: - triggers: - - schedule: - cron: "0 0 * * *" - filters: - branches: - only: - - release - - dev - - master - jobs: - # Run daily regression tests - - regression-test - - - - # Longer tests - #- make -C tests test-zstd-nolegacy && make clean - #- pyenv global 3.4.4; make -C tests versionsTest && make clean - #- make zlibwrapper && make clean - #- gcc -v; make -C tests test32 MOREFLAGS="-I/usr/include/x86_64-linux-gnu" && make clean - #- make uasan && make clean - #- make asan32 && make clean - #- make -C tests test32 CC=clang MOREFLAGS="-g -fsanitize=address -I/usr/include/x86_64-linux-gnu" - # Valgrind tests - #- CFLAGS="-O1 -g" make -C zlibWrapper valgrindTest && make clean - #- make -C tests valgrindTest && make clean - # ARM, AArch64, PowerPC, PowerPC64 tests - #- make ppctest && make clean - #- make ppc64test && make clean - #- make armtest && make clean - #- make aarch64test && make clean diff --git a/.circleci/images/primary/Dockerfile b/.circleci/images/primary/Dockerfile deleted file mode 100644 index 4b77032b6..000000000 --- a/.circleci/images/primary/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM circleci/buildpack-deps@sha256:f6f10c11b7b8ccfd4f4a5b830c3256803604ce61292b60cb22e26b12f62b0e8c - -RUN sudo dpkg --add-architecture i386 -RUN sudo apt-get -y -qq update -RUN sudo apt-get -y install \ - gcc-multilib-powerpc-linux-gnu gcc-arm-linux-gnueabi \ - libc6-dev-armel-cross gcc-aarch64-linux-gnu libc6-dev-arm64-cross \ - libc6-dev-ppc64-powerpc-cross zstd gzip coreutils \ - libcurl4-openssl-dev diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 704e78922..98cbb352d 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -11,41 +11,12 @@ permissions: read-all jobs: regression-test: runs-on: ubuntu-latest - services: - docker: - image: fbopensource/zstd-circleci-primary:0.0.1 - options: --entrypoint /bin/bash - env: - CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - uses: actions/checkout@v4 - - uses: actions/cache@v4 - with: - key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 - path: tests/regression/cache - restore-keys: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 - - uses: actions/upload-artifact@v4 - with: - path: "/tmp/circleci-artifacts" - - name: Install Dependencies - run: | - sudo apt-get update - sudo apt-get install libcurl4-gnutls-dev - name: Regression Test run: | make -C programs zstd make -C tests/regression test - mkdir -p $CIRCLE_ARTIFACTS - ./tests/regression/test \ - --cache tests/regression/cache \ - --output $CIRCLE_ARTIFACTS/results.csv \ - --zstd programs/zstd - echo "NOTE: The new results.csv is uploaded as an artifact to this job" - echo " If this fails, go to the Artifacts pane in CircleCI, " - echo " download /tmp/circleci-artifacts/results.csv, and if they " - echo " are still good, copy it into the repo and commit it." - echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" - diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv # Longer tests #- make -C tests test-zstd-nolegacy && make clean From de6cc98e07e1770b9f4571ea25dd6bf61612c08f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 1 Oct 2024 09:25:26 -0700 Subject: [PATCH 360/937] fix incorrect pointer manipulation fix #4155 --- tests/regression/result.c | 4 ++-- tests/regression/result.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/regression/result.c b/tests/regression/result.c index 84a8a044d..a13ef9c17 100644 --- a/tests/regression/result.c +++ b/tests/regression/result.c @@ -10,7 +10,7 @@ #include "result.h" -char const* result_get_error_string(result_t result) { +const char* result_get_error_string(result_t result) { switch (result_get_error(result)) { case result_error_ok: return "okay"; @@ -25,6 +25,6 @@ char const* result_get_error_string(result_t result) { case result_error_round_trip_error: return "round trip error"; default: - return "unknown error - " + result_get_error(result); + return "unknown error"; } } diff --git a/tests/regression/result.h b/tests/regression/result.h index 8a761ea4d..818ec356c 100644 --- a/tests/regression/result.h +++ b/tests/regression/result.h @@ -94,7 +94,7 @@ static result_error_t result_get_error(result_t result) { return result.internal_error; } -char const* result_get_error_string(result_t result); +const char* result_get_error_string(result_t result); static result_data_t result_get_data(result_t result) { return result.internal_data; From 8edd1476862222c4f0e88511241b83ab0e1948c4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 1 Oct 2024 09:52:45 -0700 Subject: [PATCH 361/937] fix missing fclose() fix #4151 --- programs/benchzstd.c | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index 272af5924..0a1cba9e6 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -1067,11 +1067,12 @@ static int BMK_loadFiles( size_t pos = 0, totalSize = 0; unsigned n; for (n = 0; n < nbFiles; n++) { + const char* const filename = fileNamesTable[n]; U64 fileSize = UTIL_getFileSize( - fileNamesTable[n]); /* last file may be shortened */ - if (UTIL_isDirectory(fileNamesTable[n])) { + filename); /* last file may be shortened */ + if (UTIL_isDirectory(filename)) { DISPLAYLEVEL( - 2, "Ignoring %s directory... \n", fileNamesTable[n]); + 2, "Ignoring %s directory... \n", filename); fileSizes[n] = 0; continue; } @@ -1079,25 +1080,29 @@ static int BMK_loadFiles( DISPLAYLEVEL( 2, "Cannot evaluate size of %s, ignoring ... \n", - fileNamesTable[n]); + filename); fileSizes[n] = 0; continue; } - { - FILE* const f = fopen(fileNamesTable[n], "rb"); - if (f == NULL) + if (fileSize > bufferSize - pos) { + /* buffer too small - limit quantity loaded */ + fileSize = bufferSize - pos; + nbFiles = n; /* stop after this file */ + } + + { FILE* const f = fopen(filename, "rb"); + if (f == NULL) { RETURN_ERROR_INT( - 10, "impossible to open file %s", fileNamesTable[n]); - OUTPUTLEVEL(2, "Loading %s... \r", fileNamesTable[n]); - if (fileSize > bufferSize - pos) - fileSize = bufferSize - pos, - nbFiles = n; /* buffer too small - stop after this file */ - { - size_t const readSize = + 10, "cannot open file %s", filename); + } + OUTPUTLEVEL(2, "Loading %s... \r", filename); + { size_t const readSize = fread(((char*)buffer) + pos, 1, (size_t)fileSize, f); - if (readSize != (size_t)fileSize) + if (readSize != (size_t)fileSize) { + fclose(f); RETURN_ERROR_INT( - 11, "could not read %s", fileNamesTable[n]); + 11, "invalid read %s", filename); + } pos += readSize; } fileSizes[n] = (size_t)fileSize; From a8b86d024a2e5ca7029ab19f7638cd6ca42bde1a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 2 Oct 2024 22:57:36 -0700 Subject: [PATCH 362/937] refactor documentation of the FSE decoding table build process --- doc/zstd_compression_format.md | 179 ++++++++++++++++++--------------- 1 file changed, 100 insertions(+), 79 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index e1e66c830..3c1ec3ad9 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -0.4.0 (2023-06-05) +0.4.2 (2024-10-02) Introduction @@ -1038,53 +1038,54 @@ and to compress Huffman headers. FSE --- FSE, short for Finite State Entropy, is an entropy codec based on [ANS]. -FSE encoding/decoding involves a state that is carried over between symbols, -so decoding must be done in the opposite direction as encoding. +FSE encoding/decoding involves a state that is carried over between symbols. +Decoding must be done in the opposite direction as encoding. Therefore, all FSE bitstreams are read from end to beginning. Note that the order of the bits in the stream is not reversed, -we just read the elements in the reverse order they are written. +we just read each multi-bits element in the reverse order they are encoded. For additional details on FSE, see [Finite State Entropy]. [Finite State Entropy]:https://github.com/Cyan4973/FiniteStateEntropy/ -FSE decoding involves a decoding table which has a power of 2 size, and contain three elements: +FSE decoding is directed by a decoding table with a power of 2 size, each row containing three elements: `Symbol`, `Num_Bits`, and `Baseline`. The `log2` of the table size is its `Accuracy_Log`. An FSE state value represents an index in this table. To obtain the initial state value, consume `Accuracy_Log` bits from the stream as a __little-endian__ value. -The next symbol in the stream is the `Symbol` indicated in the table for that state. +The first symbol in the stream is the `Symbol` indicated in the table for that state. To obtain the next state value, the decoder should consume `Num_Bits` bits from the stream as a __little-endian__ value and add it to `Baseline`. [ANS]: https://en.wikipedia.org/wiki/Asymmetric_Numeral_Systems ### FSE Table Description -To decode FSE streams, it is necessary to construct the decoding table. -The Zstandard format encodes FSE table descriptions as follows: +To decode an FSE bitstream, it is necessary to build its FSE decoding table. +The decoding table is derived from a distribution of Probabilities. +The Zstandard format encodes distributions of Probabilities as follows: -An FSE distribution table describes the probabilities of all symbols -from `0` to the last present one (included) -on a normalized scale of `1 << Accuracy_Log` . -Note that there must be two or more symbols with nonzero probability. +The distribution of probabilities is described in a bitstream which is read forward, +in __little-endian__ fashion. +The amount of bytes consumed from the bitstream to describe the distribution +is discovered at the end of the decoding process. -It's a bitstream which is read forward, in __little-endian__ fashion. -It's not necessary to know bitstream exact size, -it will be discovered and reported by the decoding process. - -The bitstream starts by reporting on which scale it operates. +The bitstream starts by reporting on which scale the distribution operates. Let's `low4Bits` designate the lowest 4 bits of the first byte : `Accuracy_Log = low4bits + 5`. -Then follows each symbol value, from `0` to last present one. -The number of bits used by each field is variable. +An FSE distribution table describes the probabilities of all symbols +from `0` to the last present one (included) in natural order. +The sum of probabilities is normalized to reach a power of 2 total of `1 << Accuracy_Log` . +There must be two or more symbols with non-zero probabilities. + +The number of bits used to decode each probability is variable. It depends on : - Remaining probabilities + 1 : __example__ : Presuming an `Accuracy_Log` of 8, - and presuming 100 probabilities points have already been distributed, + and presuming 100 probability points have already been distributed, the decoder may read any value from `0` to `256 - 100 + 1 == 157` (inclusive). Therefore, it may read up to `log2sup(157) == 8` bits, where `log2sup(N)` is the smallest integer `T` that satisfies `(1 << T) > N`. @@ -1098,115 +1099,133 @@ It depends on : values from 98 to 157 use 8 bits. This is achieved through this scheme : - | Value read | Value decoded | Number of bits used | - | ---------- | ------------- | ------------------- | - | 0 - 97 | 0 - 97 | 7 | - | 98 - 127 | 98 - 127 | 8 | - | 128 - 225 | 0 - 97 | 7 | - | 226 - 255 | 128 - 157 | 8 | + | 8-bit field read | Value decoded | Nb of bits consumed | + | ---------------- | ------------- | ------------------- | + | 0 - 97 | 0 - 97 | 7 | + | 98 - 127 | 98 - 127 | 8 | + | 128 - 225 | 0 - 97 | 7 | + | 226 - 255 | 128 - 157 | 8 | -Symbols probabilities are read one by one, in order. +Probability is derived from Value decoded using the following formula: +`Probality = Value - 1` -Probability is obtained from Value decoded by following formula : -`Proba = value - 1` +Consequently, a Probability of `0` is described by a Value `1`. -It means value `0` becomes negative probability `-1`. -`-1` is a special probability, which means "less than 1". -Its effect on distribution table is described in the [next section]. -For the purpose of calculating total allocated probability points, it counts as one. +A Value `0` is used to signal a special case, named "Probability `-1`". +It describes a probability which should have been "less than 1". +Its effect on the decoding table building process is described in the [next section]. +For the purpose of counting total allocated probability points, it counts as one. [next section]:#from-normalized-distribution-to-decoding-tables -When a symbol has a __probability__ of `zero`, +Symbols probabilities are read one by one, in order. +After each probability is decoded, the total nb of probability points is updated. +This is used to dermine how many bits must be read to decode the probability of next symbol. + +When a symbol has a __probability__ of `zero` (decoded from reading a Value `1`), it is followed by a 2-bits repeat flag. This repeat flag tells how many probabilities of zeroes follow the current one. It provides a number ranging from 0 to 3. If it is a 3, another 2-bits repeat flag follows, and so on. -When last symbol reaches cumulated total of `1 << Accuracy_Log`, -decoding is complete. -If this process results in a non-zero probability for a value outside of the -valid range of values that the FSE table is defined for, even if that value is -not used, then the data is considered corrupted. In the case of offset codes, -a decoder implementation may reject a frame containing a non-zero probability -for an offset code larger than the largest offset code supported by the decoder -implementation. +When the Probability for a symbol makes cumulated total reach `1 << Accuracy_Log`, +then it's the last symbol, and decoding is complete. Then the decoder can tell how many bytes were used in this process, and how many symbols are present. The bitstream consumes a round number of bytes. Any remaining bit within the last byte is just unused. +If this process results in a non-zero probability for a symbol outside of the +valid range of symbols that the FSE table is defined for, even if that symbol is +not used, then the data is considered corrupted. +For the specific case of offset codes, +a decoder implementation may reject a frame containing a non-zero probability +for an offset code larger than the largest offset code supported by the decoder +implementation. + #### From normalized distribution to decoding tables -The distribution of normalized probabilities is enough +The normalized distribution of probabilities is enough to create a unique decoding table. - -It follows the following build rule : +It is generated using the following build rule : The table has a size of `Table_Size = 1 << Accuracy_Log`. -Each cell describes the symbol decoded, -and instructions to get the next state (`Number_of_Bits` and `Baseline`). +Each row specifies the decoded symbol, +and instructions to reach the next state (`Number_of_Bits` and `Baseline`). -Symbols are scanned in their natural order for "less than 1" probabilities. -Symbols with this probability are being attributed a single cell, +Symbols are first scanned in their natural order for "less than 1" probabilities +(previously decoded from a Value of `0`). +Symbols with this special probability are being attributed a single row, starting from the end of the table and retreating. These symbols define a full state reset, reading `Accuracy_Log` bits. -Then, all remaining symbols, sorted in natural order, are allocated cells. -Starting from symbol `0` (if it exists), and table position `0`, -each symbol gets allocated as many cells as its probability. -Cell allocation is spread, not linear : -each successor position follows this rule : +Then, all remaining symbols, sorted in natural order, are allocated rows. +Starting from smallest present symbol, and table position `0`, +each symbol gets allocated as many rows as its probability. +Row allocation is not linear, it follows this order, in modular arithmetic: ``` position += (tableSize>>1) + (tableSize>>3) + 3; position &= tableSize-1; ``` -A position is skipped if already occupied by a "less than 1" probability symbol. -`position` does not reset between symbols, it simply iterates through -each position in the table, switching to the next symbol when enough -states have been allocated to the current one. +Using above ordering rule, each symbol gets allocated as many rows as its probability. +If a position is already occupied by a "less than 1" probability symbol, +it is simply skipped, and the next position is allocated instead. +Once enough rows have been allocated for the current symbol, +the allocation process continues, using the next symbol, in natural order. +This process guarantees that the table is entirely and exactly filled. -The process guarantees that the table is entirely filled. -Each cell corresponds to a state value, which contains the symbol being decoded. +Each row specifies a decoded symbol, and is accessed by current state value. +It also specifies `Number_of_Bits` and `Baseline`, which are required to determine next state value. -To add the `Number_of_Bits` and `Baseline` required to retrieve next state, -it's first necessary to sort all occurrences of each symbol in state order. -Lower states will need 1 more bit than higher ones. -The process is repeated for each symbol. +To correctly set these fields, it's necessary to sort all occurrences of each symbol in state value order, +and then attribute N+1 bits to lower rows, and N bits to higher rows, +following the process described below (using an example): __Example__ : -Presuming a symbol has a probability of 5, -it receives 5 cells, corresponding to 5 state values. -These state values are then sorted in natural order. +Presuming an `Accuracy_Log` of 7, +let's imagine a symbol with a Probability of 5: +it receives 5 rows, corresponding to 5 state values between `0` and `127`. -Next power of 2 after 5 is 8. -Space of probabilities must be divided into 8 equal parts. -Presuming the `Accuracy_Log` is 7, it defines a space of 128 states. -Divided by 8, each share is 16 large. +In this example, the first state value happens to be `1` (after unspecified previous symbols). +The next 4 states are then determined using above modular arithmetic rule, +which specifies to add `64+16+3 = 83` modulo `128` to jump to next position, +producing the following series: `1`, `84`, `39`, `122`, `77` (modular arithmetic). +(note: the next symbol will then start at `32`). -In order to reach 8 shares, 8-5=3 lowest states will count "double", +These state values are then sorted in natural order, +resulting in the following series: `1`, `39`, `77`, `84`, `122`. + +The next power of 2 after 5 is 8. +Therefore, the probability space will be divided into 8 equal parts. +Since the probability space is `1<<7 = 128` large, each share is `128/8 = 16` large. + +In order to reach 8 shares, the `8-5 = 3` lowest states will count "double", doubling their shares (32 in width), hence requiring one more bit. -Baseline is assigned starting from the higher states using fewer bits, -increasing at each state, then resuming at the first state, -each state takes its allocated width from Baseline. +Baseline is assigned starting from the lowest state using fewer bits, +continuing in natural state order, looping back at the beginning. +Each state takes its allocated range from Baseline, sized by its `Number_of_Bits`. | state order | 0 | 1 | 2 | 3 | 4 | | ---------------- | ----- | ----- | ------ | ---- | ------ | | state value | 1 | 39 | 77 | 84 | 122 | | width | 32 | 32 | 32 | 16 | 16 | | `Number_of_Bits` | 5 | 5 | 5 | 4 | 4 | -| range number | 2 | 4 | 6 | 0 | 1 | +| allocation order | 3 | 4 | 5 | 1 | 2 | | `Baseline` | 32 | 64 | 96 | 0 | 16 | | range | 32-63 | 64-95 | 96-127 | 0-15 | 16-31 | -During decoding, the next state value is determined from current state value, -by reading the required `Number_of_Bits`, and adding the specified `Baseline`. +During decoding, the next state value is determined by using current state value as row number, +then reading the required `Number_of_Bits` from the bitstream, and adding the specified `Baseline`. -See [Appendix A] for the results of this process applied to the default distributions. +Note: +as a trivial example, it follows that, for a symbol with a Probability of `1`, +`Baseline` is necessarily `0`, and `Number_of_Bits` is necessarily `Accuracy_Log`. + +See [Appendix A] to see the outcome of this process applied to the default distributions. [Appendix A]: #appendix-a---decoding-tables-for-predefined-codes @@ -1716,6 +1735,8 @@ or at least provide a meaningful error code explaining for which reason it canno Version changes --------------- +- 0.4.2 : refactor FSE table construction process, inspired by Donald Pian +- 0.4.1 : clarifications on a few error scenarios, by Eric Lasota - 0.4.0 : fixed imprecise behavior for nbSeq==0, detected by Igor Pavlov - 0.3.9 : clarifications for Huffman-compressed literal sizes. - 0.3.8 : clarifications for Huffman Blocks and Huffman Tree descriptions. From b84653fc839367281481bc3fee9f9d7e8496701f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 3 Oct 2024 15:10:16 -0700 Subject: [PATCH 363/937] fix dependency for nightly github actions tests --- .github/workflows/nightly.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 98cbb352d..5e531d3b6 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,18 +1,20 @@ name: facebook/zstd/nightly on: schedule: - - cron: 0 0 * * * + - cron: '0 0 * * *' push: branches: - - release - - dev - - master + - release + - dev + - '*nightly*' permissions: read-all jobs: regression-test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - name: Install dependencies + run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev - name: Regression Test run: | make -C programs zstd From 1e7fa242f4aa71c3aec5e1e39ec69ad54e117051 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 7 Oct 2024 11:22:40 -0700 Subject: [PATCH 364/937] minor refactor zstd_fast make hot variables more local --- lib/compress/zstd_compress_internal.h | 4 +- lib/compress/zstd_fast.c | 71 +++++++++++++-------------- 2 files changed, 36 insertions(+), 39 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index cbcded28d..53c3bdee8 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -560,7 +560,9 @@ MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value) /* ZSTD_selectAddr: * @return a >= b ? trueAddr : falseAddr, * tries to force branchless codegen. */ -MEM_STATIC const BYTE* ZSTD_selectAddr(U32 a, U32 b, const BYTE* trueAddr, const BYTE* falseAddr) { +MEM_STATIC const BYTE* +ZSTD_selectAddr(U32 a, U32 b, const BYTE* trueAddr, const BYTE* falseAddr) +{ #if defined(__GNUC__) && defined(__x86_64__) __asm__ ( "cmp %1, %2\n" diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 838a18ee5..0b6230150 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -166,7 +166,6 @@ size_t ZSTD_compressBlock_fast_noDict_generic( * we load from here instead of from tables, if the index is invalid. * Used to avoid unpredictable branches. */ const BYTE dummy[] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0xe2,0xb4}; - const BYTE *mvalAddr; const BYTE* anchor = istart; const BYTE* ip0 = istart; @@ -182,7 +181,6 @@ size_t ZSTD_compressBlock_fast_noDict_generic( size_t hash0; /* hash for ip0 */ size_t hash1; /* hash for ip1 */ U32 idx; /* match idx for ip0 */ - U32 mval; /* src value at match idx */ U32 offcode; const BYTE* match0; @@ -255,22 +253,21 @@ _start: /* Requires: ip0 */ * However expression below complies into conditional move. Since * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex * if there is a match, all branches become predictable. */ - mvalAddr = base + idx; - mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, mvalAddr, &dummy[0]); + { const BYTE* mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, base + idx, &dummy[0]); + /* load match for ip[0] */ + U32 const mval = MEM_read32(mvalAddr); - /* load match for ip[0] */ - mval = MEM_read32(mvalAddr); + /* check match at ip[0] */ + if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { + /* found a match! */ - /* check match at ip[0] */ - if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { - /* found a match! */ + /* Write next hash table entry (it's already calculated). + * This write is known to be safe because the ip1 == ip0 + 1, + * so searching will resume after ip1 */ + hashTable[hash1] = (U32)(ip1 - base); - /* First write next hash table entry; we've already calculated it. - * This write is known to be safe because the ip1 == ip0 + 1, so - * we know we will resume searching after ip1 */ - hashTable[hash1] = (U32)(ip1 - base); - - goto _offset; + goto _offset; + } } /* lookup ip[1] */ @@ -289,32 +286,30 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - mvalAddr = base + idx; - mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, mvalAddr, &dummy[0]); + { const BYTE* mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, base + idx, &dummy[0]); + /* load match for ip[0] */ + U32 const mval = MEM_read32(mvalAddr); - /* load match for ip[0] */ - mval = MEM_read32(mvalAddr); + /* check match at ip[0] */ + if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { + /* found a match! */ + /* first write next hash table entry; we've already calculated it */ + if (step <= 4) { + /* We need to avoid writing an index into the hash table >= the + * position at which we will pick up our searching after we've + * taken this match. + * + * The minimum possible match has length 4, so the earliest ip0 + * can be after we take this match will be the current ip0 + 4. + * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely + * write this position. + */ + hashTable[hash1] = (U32)(ip1 - base); + } - /* check match at ip[0] */ - if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { - /* found a match! */ - - /* first write next hash table entry; we've already calculated it */ - if (step <= 4) { - /* We need to avoid writing an index into the hash table >= the - * position at which we will pick up our searching after we've - * taken this match. - * - * The minimum possible match has length 4, so the earliest ip0 - * can be after we take this match will be the current ip0 + 4. - * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely - * write this position. - */ - hashTable[hash1] = (U32)(ip1 - base); + goto _offset; } - - goto _offset; } /* lookup ip[1] */ @@ -554,7 +549,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( size_t const dictHashAndTag1 = ZSTD_hashPtr(ip1, dictHBits, mls); hashTable[hash0] = curr; /* update hash table */ - if ((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) + if ((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) && (MEM_read32(repMatch) == MEM_read32(ip0 + 1))) { const BYTE* const repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; mLength = ZSTD_count_2segments(ip0 + 1 + 4, repMatch + 4, iend, repMatchEnd, prefixStart) + 4; From 3b343dcfb140ccb278a781faa8116d273f36e4a1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 7 Oct 2024 17:15:07 -0700 Subject: [PATCH 365/937] refactor huffman prefix code paragraph --- doc/zstd_compression_format.md | 67 +++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 3c1ec3ad9..b4a6edf9e 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -0.4.2 (2024-10-02) +0.4.3 (2024-10-07) Introduction @@ -1270,13 +1270,13 @@ This specification limits maximum code length to 11 bits. #### Representation -All literal values from zero (included) to last present one (excluded) +All literal symbols from zero (included) to last present one (excluded) are represented by `Weight` with values from `0` to `Max_Number_of_Bits`. Transformation from `Weight` to `Number_of_Bits` follows this formula : ``` Number_of_Bits = Weight ? (Max_Number_of_Bits + 1 - Weight) : 0 ``` -When a literal value is not present, it receives a `Weight` of 0. +When a literal symbol is not present, it receives a `Weight` of 0. The least frequent symbol receives a `Weight` of 1. If no literal has a `Weight` of 1, then the data is considered corrupted. If there are not at least two literals with non-zero `Weight`, then the data @@ -1293,33 +1293,38 @@ otherwise the representation is considered corrupted. __Example__ : Let's presume the following Huffman tree must be described : -| literal value | 0 | 1 | 2 | 3 | 4 | 5 | +| literal symbol | A | B | C | D | E | F | | ---------------- | --- | --- | --- | --- | --- | --- | | `Number_of_Bits` | 1 | 2 | 3 | 0 | 4 | 4 | The tree depth is 4, since its longest elements uses 4 bits -(longest elements are the one with smallest frequency). -Literal value `5` will not be listed, as it can be determined from previous values 0-4, -nor will values above `5` as they are all 0. -Values from `0` to `4` will be listed using `Weight` instead of `Number_of_Bits`. +(longest elements are the ones with smallest frequency). + +All symbols will now receive a `Weight` instead of `Number_of_Bits`. Weight formula is : ``` Weight = Number_of_Bits ? (Max_Number_of_Bits + 1 - Number_of_Bits) : 0 ``` -It gives the following series of weights : +It gives the following series of Weights : -| literal value | 0 | 1 | 2 | 3 | 4 | -| ------------- | --- | --- | --- | --- | --- | -| `Weight` | 4 | 3 | 2 | 0 | 1 | +| literal symbol | A | B | C | D | E | F | +| -------------- | --- | --- | --- | --- | --- | --- | +| `Weight` | 4 | 3 | 2 | 0 | 1 | 1 | + +This list will be sent to the decoder, with the following modifications: + +- `F` will not be listed, because it can be determined from previous symbols +- nor will symbols above `F` as they are all 0 +- on the other hand, all symbols before `A`, starting with `\0`, will be listed, with a Weight of 0. The decoder will do the inverse operation : -having collected weights of literal symbols from `0` to `4`, -it knows the last literal, `5`, is present with a non-zero `Weight`. -The `Weight` of `5` can be determined by advancing to the next power of 2. +having collected weights of literal symbols from `A` to `E`, +it knows the last literal, `F`, is present with a non-zero `Weight`. +The `Weight` of `F` can be determined by advancing to the next power of 2. The sum of `2^(Weight-1)` (excluding 0's) is : `8 + 4 + 2 + 0 + 1 = 15`. Nearest larger power of 2 value is 16. -Therefore, `Max_Number_of_Bits = 4` and `Weight[5] = log_2(16 - 15) + 1 = 1`. +Therefore, `Max_Number_of_Bits = log2(16) = 4` and `Weight[F] = log_2(16 - 15) + 1 = 1`. #### Huffman Tree header @@ -1359,7 +1364,7 @@ sharing a single distribution table. To decode an FSE bitstream, it is necessary to know its compressed size. Compressed size is provided by `headerByte`. It's also necessary to know its _maximum possible_ decompressed size, -which is `255`, since literal values span from `0` to `255`, +which is `255`, since literal symbols span from `0` to `255`, and last symbol's `Weight` is not represented. An FSE bitstream starts by a header, describing probabilities distribution. @@ -1395,26 +1400,27 @@ It is possible to transform weights into `Number_of_Bits`, using this formula: ``` Number_of_Bits = (Weight>0) ? Max_Number_of_Bits + 1 - Weight : 0 ``` -Symbols are sorted by `Weight`. -Within same `Weight`, symbols keep natural sequential order. +In order to determine which prefix is assigned to each Symbol, +Symbols are first sorted by `Weight`, then by natural sequential order. Symbols with a `Weight` of zero are removed. -Then, starting from lowest `Weight`, prefix codes are distributed in sequential order. +Then, starting from lowest `Weight` (hence highest `Number_of_Bits`), +prefix codes are assigned in ascending order. __Example__ : -Let's presume the following list of weights has been decoded : +Let's assume the following list of weights has been decoded: -| Literal | 0 | 1 | 2 | 3 | 4 | 5 | +| Literal | A | B | C | D | E | F | | -------- | --- | --- | --- | --- | --- | --- | | `Weight` | 4 | 3 | 2 | 0 | 1 | 1 | Sorted by weight and then natural sequential order, -it gives the following distribution : +it gives the following prefix codes distribution: -| Literal | 3 | 4 | 5 | 2 | 1 | 0 | -| ---------------- | --- | --- | --- | --- | --- | ---- | -| `Weight` | 0 | 1 | 1 | 2 | 3 | 4 | -| `Number_of_Bits` | 0 | 4 | 4 | 3 | 2 | 1 | -| prefix codes | N/A | 0000| 0001| 001 | 01 | 1 | +| Literal | D | E | F | C | B | A | +| ---------------- | --- | ---- | ---- | --- | --- | --- | +| `Weight` | 0 | 1 | 1 | 2 | 3 | 4 | +| `Number_of_Bits` | 0 | 4 | 4 | 3 | 2 | 1 | +| prefix code | N/A | 0000 | 0001 | 001 | 01 | 1 | ### Huffman-coded Streams @@ -1437,10 +1443,10 @@ it's possible to read the bitstream in a __little-endian__ fashion, keeping track of already used bits. Since the bitstream is encoded in reverse order, starting from the end read symbols in forward order. -For example, if the literal sequence "0145" was encoded using above prefix code, +For example, if the literal sequence `ABEF` was encoded using above prefix code, it would be encoded (in reverse order) as: -|Symbol | 5 | 4 | 1 | 0 | Padding | +|Symbol | F | E | B | A | Padding | |--------|------|------|----|---|---------| |Encoding|`0000`|`0001`|`01`|`1`| `00001` | @@ -1735,6 +1741,7 @@ or at least provide a meaningful error code explaining for which reason it canno Version changes --------------- +- 0.4.3 : clarifications for Huffman prefix code assignment example - 0.4.2 : refactor FSE table construction process, inspired by Donald Pian - 0.4.1 : clarifications on a few error scenarios, by Eric Lasota - 0.4.0 : fixed imprecise behavior for nbSeq==0, detected by Igor Pavlov From 2cc600bab21657ccf966ceadfeb316e2eacff25c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 8 Oct 2024 11:10:48 -0700 Subject: [PATCH 366/937] refactor search into an inline function for easier swapping with a parameter --- lib/compress/zstd_compress_internal.h | 4 +- lib/compress/zstd_fast.c | 91 +++++++++++++-------------- 2 files changed, 47 insertions(+), 48 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 53c3bdee8..64618848d 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -561,14 +561,14 @@ MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value) * @return a >= b ? trueAddr : falseAddr, * tries to force branchless codegen. */ MEM_STATIC const BYTE* -ZSTD_selectAddr(U32 a, U32 b, const BYTE* trueAddr, const BYTE* falseAddr) +ZSTD_selectAddr(U32 index, U32 lowLimit, const BYTE* trueAddr, const BYTE* falseAddr) { #if defined(__GNUC__) && defined(__x86_64__) __asm__ ( "cmp %1, %2\n" "cmova %3, %0\n" : "+r"(trueAddr) - : "r"(a), "r"(b), "r"(falseAddr) + : "r"(index), "r"(lowLimit), "r"(falseAddr) ); return trueAddr; #else diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 0b6230150..94e6300eb 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -97,6 +97,18 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms, } +static int +ZSTD_findMatch_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) +{ + /* idx >= prefixStartIndex is a (somewhat) unpredictable branch. + * However expression below complies into conditional move. Since + * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex + * if there is a match, all branches become predictable. */ + const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, fakeAddress); + return ((MEM_read32(currentPtr) == MEM_read32(mvalAddr)) & (currentIdx >= lowLimit)); +} + + /** * If you squint hard enough (and ignore repcodes), the search operation at any * given position is broken into 4 stages: @@ -148,13 +160,12 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_noDict_generic( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, - U32 const mls, U32 const hasStep) + U32 const mls, U32 const unpredictable) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const hashTable = ms->hashTable; U32 const hlog = cParams->hashLog; - /* support stepSize of 0 */ - size_t const stepSize = hasStep ? (cParams->targetLength + !(cParams->targetLength) + 1) : 2; + size_t const stepSize = cParams->targetLength + !(cParams->targetLength) + 1; /* min 2 */ const BYTE* const base = ms->window.base; const BYTE* const istart = (const BYTE*)src; const U32 endIndex = (U32)((size_t)(istart - base) + srcSize); @@ -193,6 +204,7 @@ size_t ZSTD_compressBlock_fast_noDict_generic( size_t step; const BYTE* nextStep; const size_t kStepIncr = (1 << (kSearchStrength - 1)); + (void)unpredictable; DEBUGLOG(5, "ZSTD_compressBlock_fast_generic"); ip0 += (ip0 == prefixStart); @@ -249,25 +261,15 @@ _start: /* Requires: ip0 */ goto _match; } - /* idx >= prefixStartIndex is a (somewhat) unpredictable branch. - * However expression below complies into conditional move. Since - * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex - * if there is a match, all branches become predictable. */ - { const BYTE* mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, base + idx, &dummy[0]); - /* load match for ip[0] */ - U32 const mval = MEM_read32(mvalAddr); + if (ZSTD_findMatch_cmov(ip0, base + idx, idx, prefixStartIndex, dummy)) { + /* found a match! */ - /* check match at ip[0] */ - if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { - /* found a match! */ + /* Write next hash table entry (it's already calculated). + * This write is known to be safe because the ip1 == ip0 + 1, + * so searching will resume after ip1 */ + hashTable[hash1] = (U32)(ip1 - base); - /* Write next hash table entry (it's already calculated). - * This write is known to be safe because the ip1 == ip0 + 1, - * so searching will resume after ip1 */ - hashTable[hash1] = (U32)(ip1 - base); - - goto _offset; - } + goto _offset; } /* lookup ip[1] */ @@ -286,30 +288,24 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - { const BYTE* mvalAddr = ZSTD_selectAddr(idx, prefixStartIndex, base + idx, &dummy[0]); - /* load match for ip[0] */ - U32 const mval = MEM_read32(mvalAddr); + if (ZSTD_findMatch_cmov(ip0, base + idx, idx, prefixStartIndex, dummy)) { + /* found a match! */ - /* check match at ip[0] */ - if (MEM_read32(ip0) == mval && idx >= prefixStartIndex) { - /* found a match! */ - - /* first write next hash table entry; we've already calculated it */ - if (step <= 4) { - /* We need to avoid writing an index into the hash table >= the - * position at which we will pick up our searching after we've - * taken this match. - * - * The minimum possible match has length 4, so the earliest ip0 - * can be after we take this match will be the current ip0 + 4. - * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely - * write this position. - */ - hashTable[hash1] = (U32)(ip1 - base); - } - - goto _offset; + /* first write next hash table entry; it's already calculated */ + if (step <= 4) { + /* We need to avoid writing an index into the hash table >= the + * position at which we will pick up our searching after we've + * taken this match. + * + * The minimum possible match has length 4, so the earliest ip0 + * can be after we take this match will be the current ip0 + 4. + * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely + * write this position. + */ + hashTable[hash1] = (U32)(ip1 - base); } + + goto _offset; } /* lookup ip[1] */ @@ -409,12 +405,12 @@ _match: /* Requires: ip0, match0, offcode */ goto _start; } -#define ZSTD_GEN_FAST_FN(dictMode, mls, step) \ - static size_t ZSTD_compressBlock_fast_##dictMode##_##mls##_##step( \ +#define ZSTD_GEN_FAST_FN(dictMode, mls, cmov) \ + static size_t ZSTD_compressBlock_fast_##dictMode##_##mls##_##cmov( \ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ - return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mls, step); \ + return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mls, cmov); \ } ZSTD_GEN_FAST_FN(noDict, 4, 1) @@ -432,8 +428,10 @@ size_t ZSTD_compressBlock_fast( void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; + /* use cmov instead of branch when the branch is likely unpredictable */ + int const useCmov = 1; assert(ms->dictMatchState == NULL); - if (ms->cParams.targetLength > 1) { + if (useCmov) { switch(mls) { default: /* includes case 3 */ @@ -447,6 +445,7 @@ size_t ZSTD_compressBlock_fast( return ZSTD_compressBlock_fast_noDict_7_1(ms, seqStore, rep, src, srcSize); } } else { + /* use a branch instead */ switch(mls) { default: /* includes case 3 */ From 186b1324951f2505469a3415aaf8ddc3398b9fca Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 8 Oct 2024 11:43:07 -0700 Subject: [PATCH 367/937] made search strategy switchable between cmov and branch and use a simple heuristic based on wlog to select between them. note: performance is not good on clang (yet) --- lib/compress/zstd_compress_internal.h | 12 ++--- lib/compress/zstd_fast.c | 72 +++++++++++++++------------ 2 files changed, 47 insertions(+), 37 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 64618848d..0be7ae14e 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -558,21 +558,21 @@ MEM_STATIC int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value) } /* ZSTD_selectAddr: - * @return a >= b ? trueAddr : falseAddr, + * @return index >= lowLimit ? candidate : backup, * tries to force branchless codegen. */ MEM_STATIC const BYTE* -ZSTD_selectAddr(U32 index, U32 lowLimit, const BYTE* trueAddr, const BYTE* falseAddr) +ZSTD_selectAddr(U32 index, U32 lowLimit, const BYTE* candidate, const BYTE* backup) { #if defined(__GNUC__) && defined(__x86_64__) __asm__ ( "cmp %1, %2\n" "cmova %3, %0\n" - : "+r"(trueAddr) - : "r"(index), "r"(lowLimit), "r"(falseAddr) + : "+r"(candidate) + : "r"(index), "r"(lowLimit), "r"(backup) ); - return trueAddr; + return candidate; #else - return a >= b ? trueAddr : falseAddr; + return index >= lowLimit ? candidate : backup; #endif } diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 94e6300eb..3c6e75131 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -45,7 +45,7 @@ void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms, size_t const hashAndTag = ZSTD_hashPtr(ip + p, hBits, mls); if (hashTable[hashAndTag >> ZSTD_SHORT_CACHE_TAG_BITS] == 0) { /* not yet filled */ ZSTD_writeTaggedIndex(hashTable, hashAndTag, curr + p); - } } } } + } } } } } static @@ -97,17 +97,34 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms, } +typedef int (*ZSTD_match4Found) (const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress); + static int -ZSTD_findMatch_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) +ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) { - /* idx >= prefixStartIndex is a (somewhat) unpredictable branch. - * However expression below complies into conditional move. Since - * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex - * if there is a match, all branches become predictable. */ + /* currentIdx >= lowLimit is a (somewhat) unpredictable branch. + * However expression below compiles into conditional move. + */ const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, fakeAddress); return ((MEM_read32(currentPtr) == MEM_read32(mvalAddr)) & (currentIdx >= lowLimit)); } +static int +ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) +{ + /* using a branch instead of a cmov, + * because it's faster in scenarios where currentIdx >= lowLimit is generally true, + * aka almost all candidates are within range */ + U32 mval; (void)fakeAddress; + if (currentIdx >= lowLimit) { + mval = MEM_read32(matchAddress); + } else { + mval = MEM_read32(currentPtr) ^ 1; /* guaranteed to not match. */ + } + + return (MEM_read32(currentPtr) == mval); +} + /** * If you squint hard enough (and ignore repcodes), the search operation at any @@ -160,7 +177,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_noDict_generic( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, - U32 const mls, U32 const unpredictable) + U32 const mls, int useCmov) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const hashTable = ms->hashTable; @@ -204,7 +221,7 @@ size_t ZSTD_compressBlock_fast_noDict_generic( size_t step; const BYTE* nextStep; const size_t kStepIncr = (1 << (kSearchStrength - 1)); - (void)unpredictable; + const ZSTD_match4Found findMatch = useCmov ? ZSTD_match4Found_cmov : ZSTD_match4Found_branch; DEBUGLOG(5, "ZSTD_compressBlock_fast_generic"); ip0 += (ip0 == prefixStart); @@ -253,15 +270,15 @@ _start: /* Requires: ip0 */ offcode = REPCODE1_TO_OFFBASE; mLength += 4; - /* First write next hash table entry; we've already calculated it. - * This write is known to be safe because the ip1 is before the + /* Write next hash table entry: it's already calculated. + * This write is known to be safe because ip1 is before the * repcode (ip2). */ hashTable[hash1] = (U32)(ip1 - base); goto _match; } - if (ZSTD_findMatch_cmov(ip0, base + idx, idx, prefixStartIndex, dummy)) { + if (findMatch(ip0, base + idx, idx, prefixStartIndex, dummy)) { /* found a match! */ /* Write next hash table entry (it's already calculated). @@ -288,19 +305,13 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - if (ZSTD_findMatch_cmov(ip0, base + idx, idx, prefixStartIndex, dummy)) { + if (findMatch(ip0, base + idx, idx, prefixStartIndex, dummy)) { /* found a match! */ - /* first write next hash table entry; it's already calculated */ + /* Write next hash table entry; it's already calculated */ if (step <= 4) { - /* We need to avoid writing an index into the hash table >= the - * position at which we will pick up our searching after we've - * taken this match. - * - * The minimum possible match has length 4, so the earliest ip0 - * can be after we take this match will be the current ip0 + 4. - * ip1 is ip0 + step - 1. If ip1 is >= ip0 + 4, we can't safely - * write this position. + /* Avoid writing an index if it's >= position where search will resume. + * The minimum possible match has length 4, so search can resume at ip0 + 4. */ hashTable[hash1] = (U32)(ip1 - base); } @@ -331,7 +342,7 @@ _start: /* Requires: ip0 */ } while (ip3 < ilimit); _cleanup: - /* Note that there are probably still a couple positions we could search. + /* Note that there are probably still a couple positions one could search. * However, it seems to be a meaningful performance hit to try to search * them. So let's not. */ @@ -405,12 +416,12 @@ _match: /* Requires: ip0, match0, offcode */ goto _start; } -#define ZSTD_GEN_FAST_FN(dictMode, mls, cmov) \ - static size_t ZSTD_compressBlock_fast_##dictMode##_##mls##_##cmov( \ +#define ZSTD_GEN_FAST_FN(dictMode, mml, cmov) \ + static size_t ZSTD_compressBlock_fast_##dictMode##_##mml##_##cmov( \ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ - return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mls, cmov); \ + return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mml, cmov); \ } ZSTD_GEN_FAST_FN(noDict, 4, 1) @@ -427,12 +438,12 @@ size_t ZSTD_compressBlock_fast( ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { - U32 const mls = ms->cParams.minMatch; - /* use cmov instead of branch when the branch is likely unpredictable */ - int const useCmov = 1; + U32 const mml = ms->cParams.minMatch; + /* use cmov when "candidate in range" branch is likely unpredictable */ + int const useCmov = ms->cParams.windowLog < 19; assert(ms->dictMatchState == NULL); if (useCmov) { - switch(mls) + switch(mml) { default: /* includes case 3 */ case 4 : @@ -446,7 +457,7 @@ size_t ZSTD_compressBlock_fast( } } else { /* use a branch instead */ - switch(mls) + switch(mml) { default: /* includes case 3 */ case 4 : @@ -458,7 +469,6 @@ size_t ZSTD_compressBlock_fast( case 7 : return ZSTD_compressBlock_fast_noDict_7_0(ms, seqStore, rep, src, srcSize); } - } } From 197c258a79a94b60ec45020defc5fb6a2f570e80 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 8 Oct 2024 15:54:48 -0700 Subject: [PATCH 368/937] introduce memory barrier to force test order suggested by @terrelln --- lib/compress/zstd_fast.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 3c6e75131..9d0cefeac 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -106,7 +106,15 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 curr * However expression below compiles into conditional move. */ const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, fakeAddress); - return ((MEM_read32(currentPtr) == MEM_read32(mvalAddr)) & (currentIdx >= lowLimit)); + /* Note: this used to be written as : return test1 && test2; + * Unfortunately, once inlined, these tests become branches, + * in which case it becomes critical that they are executed in the right order (test1 then test2). + * So we have to write these tests in a specific manner to ensure their ordering. + */ + if (MEM_read32(currentPtr) != MEM_read32(mvalAddr)) return 0; + /* force ordering of these tests, which matters once the function is inlined, as they become branches */ + __asm__(""); + return currentIdx >= lowLimit; } static int From 741b860fc1e8171519a72bf3d30cdd20995b00ce Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 8 Oct 2024 16:02:54 -0700 Subject: [PATCH 369/937] store dummy bytes within ZSTD_match4Found_cmov() feels more logical, better contained --- lib/compress/zstd_fast.c | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 9d0cefeac..5bac5d9cf 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -97,15 +97,20 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms, } -typedef int (*ZSTD_match4Found) (const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress); +typedef int (*ZSTD_match4Found) (const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit); static int -ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) +ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit) { + /* Array of ~random data, should have low probability of matching data. + * Load from here if the index is invalid. + * Used to avoid unpredictable branches. */ + static const BYTE dummy[] = {0x12,0x34,0x56,0x78 }; + /* currentIdx >= lowLimit is a (somewhat) unpredictable branch. * However expression below compiles into conditional move. */ - const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, fakeAddress); + const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, dummy); /* Note: this used to be written as : return test1 && test2; * Unfortunately, once inlined, these tests become branches, * in which case it becomes critical that they are executed in the right order (test1 then test2). @@ -118,12 +123,12 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 curr } static int -ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit, const BYTE* fakeAddress) +ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit) { /* using a branch instead of a cmov, * because it's faster in scenarios where currentIdx >= lowLimit is generally true, * aka almost all candidates are within range */ - U32 mval; (void)fakeAddress; + U32 mval; if (currentIdx >= lowLimit) { mval = MEM_read32(matchAddress); } else { @@ -198,10 +203,6 @@ size_t ZSTD_compressBlock_fast_noDict_generic( const BYTE* const prefixStart = base + prefixStartIndex; const BYTE* const iend = istart + srcSize; const BYTE* const ilimit = iend - HASH_READ_SIZE; - /* Array of ~random data, should have low probability of matching data - * we load from here instead of from tables, if the index is invalid. - * Used to avoid unpredictable branches. */ - const BYTE dummy[] = {0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0xe2,0xb4}; const BYTE* anchor = istart; const BYTE* ip0 = istart; @@ -286,7 +287,7 @@ _start: /* Requires: ip0 */ goto _match; } - if (findMatch(ip0, base + idx, idx, prefixStartIndex, dummy)) { + if (findMatch(ip0, base + idx, idx, prefixStartIndex)) { /* found a match! */ /* Write next hash table entry (it's already calculated). @@ -313,7 +314,7 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - if (findMatch(ip0, base + idx, idx, prefixStartIndex, dummy)) { + if (findMatch(ip0, base + idx, idx, prefixStartIndex)) { /* found a match! */ /* Write next hash table entry; it's already calculated */ From d45aee43f4b1ac8ee0fbb182310b9b7622f85d1c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 8 Oct 2024 16:38:35 -0700 Subject: [PATCH 370/937] make __asm__ a __GNUC__ specific --- lib/compress/zstd_fast.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 5bac5d9cf..d4b8f0672 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -118,7 +118,9 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 curr */ if (MEM_read32(currentPtr) != MEM_read32(mvalAddr)) return 0; /* force ordering of these tests, which matters once the function is inlined, as they become branches */ +#if defined(__GNUC__) __asm__(""); +#endif return currentIdx >= lowLimit; } From 3e7c66acd1b6dab2473a996adac027dacf648d0a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 9 Oct 2024 01:06:24 -0700 Subject: [PATCH 371/937] added ascending order example --- doc/zstd_compression_format.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index b4a6edf9e..78279ce71 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -1400,7 +1400,7 @@ It is possible to transform weights into `Number_of_Bits`, using this formula: ``` Number_of_Bits = (Weight>0) ? Max_Number_of_Bits + 1 - Weight : 0 ``` -In order to determine which prefix is assigned to each Symbol, +In order to determine which prefix code is assigned to each Symbol, Symbols are first sorted by `Weight`, then by natural sequential order. Symbols with a `Weight` of zero are removed. Then, starting from lowest `Weight` (hence highest `Number_of_Bits`), @@ -1416,11 +1416,12 @@ Let's assume the following list of weights has been decoded: Sorted by weight and then natural sequential order, it gives the following prefix codes distribution: -| Literal | D | E | F | C | B | A | -| ---------------- | --- | ---- | ---- | --- | --- | --- | -| `Weight` | 0 | 1 | 1 | 2 | 3 | 4 | -| `Number_of_Bits` | 0 | 4 | 4 | 3 | 2 | 1 | -| prefix code | N/A | 0000 | 0001 | 001 | 01 | 1 | +| Literal | D | E | F | C | B | A | +| ---------------- | --- | ---- | ---- | ---- | ---- | ---- | +| `Weight` | 0 | 1 | 1 | 2 | 3 | 4 | +| `Number_of_Bits` | 0 | 4 | 4 | 3 | 2 | 1 | +| prefix code | N/A | 0000 | 0001 | 001 | 01 | 1 | +| ascending order | N/A | 0000 | 0001 | 001x | 01xx | 1xxx | ### Huffman-coded Streams From fa1fcb08ab447de8cdb4492d663779cad6841379 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 10 Oct 2024 16:07:20 -0700 Subject: [PATCH 372/937] minor: better variable naming --- lib/compress/zstd_fast.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index d4b8f0672..691bedc1e 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -97,10 +97,10 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms, } -typedef int (*ZSTD_match4Found) (const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit); +typedef int (*ZSTD_match4Found) (const BYTE* currentPtr, const BYTE* matchAddress, U32 matchIdx, U32 idxLowLimit); static int -ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit) +ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 matchIdx, U32 idxLowLimit) { /* Array of ~random data, should have low probability of matching data. * Load from here if the index is invalid. @@ -110,7 +110,7 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 curr /* currentIdx >= lowLimit is a (somewhat) unpredictable branch. * However expression below compiles into conditional move. */ - const BYTE* mvalAddr = ZSTD_selectAddr(currentIdx, lowLimit, matchAddress, dummy); + const BYTE* mvalAddr = ZSTD_selectAddr(matchIdx, idxLowLimit, matchAddress, dummy); /* Note: this used to be written as : return test1 && test2; * Unfortunately, once inlined, these tests become branches, * in which case it becomes critical that they are executed in the right order (test1 then test2). @@ -121,17 +121,17 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 curr #if defined(__GNUC__) __asm__(""); #endif - return currentIdx >= lowLimit; + return matchIdx >= idxLowLimit; } static int -ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 currentIdx, U32 lowLimit) +ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 matchIdx, U32 idxLowLimit) { /* using a branch instead of a cmov, - * because it's faster in scenarios where currentIdx >= lowLimit is generally true, + * because it's faster in scenarios where matchIdx >= idxLowLimit is generally true, * aka almost all candidates are within range */ U32 mval; - if (currentIdx >= lowLimit) { + if (matchIdx >= idxLowLimit) { mval = MEM_read32(matchAddress); } else { mval = MEM_read32(currentPtr) ^ 1; /* guaranteed to not match. */ @@ -219,7 +219,7 @@ size_t ZSTD_compressBlock_fast_noDict_generic( size_t hash0; /* hash for ip0 */ size_t hash1; /* hash for ip1 */ - U32 idx; /* match idx for ip0 */ + U32 matchIdx; /* match idx for ip0 */ U32 offcode; const BYTE* match0; @@ -261,7 +261,7 @@ _start: /* Requires: ip0 */ hash0 = ZSTD_hashPtr(ip0, hlog, mls); hash1 = ZSTD_hashPtr(ip1, hlog, mls); - idx = hashTable[hash0]; + matchIdx = hashTable[hash0]; do { /* load repcode match for ip[2]*/ @@ -289,7 +289,7 @@ _start: /* Requires: ip0 */ goto _match; } - if (findMatch(ip0, base + idx, idx, prefixStartIndex)) { + if (findMatch(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { /* found a match! */ /* Write next hash table entry (it's already calculated). @@ -301,7 +301,7 @@ _start: /* Requires: ip0 */ } /* lookup ip[1] */ - idx = hashTable[hash1]; + matchIdx = hashTable[hash1]; /* hash ip[2] */ hash0 = hash1; @@ -316,7 +316,7 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - if (findMatch(ip0, base + idx, idx, prefixStartIndex)) { + if (findMatch(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { /* found a match! */ /* Write next hash table entry; it's already calculated */ @@ -331,7 +331,7 @@ _start: /* Requires: ip0 */ } /* lookup ip[1] */ - idx = hashTable[hash1]; + matchIdx = hashTable[hash1]; /* hash ip[2] */ hash0 = hash1; @@ -382,7 +382,7 @@ _cleanup: _offset: /* Requires: ip0, idx */ /* Compute the offset code. */ - match0 = base + idx; + match0 = base + matchIdx; rep_offset2 = rep_offset1; rep_offset1 = (U32)(ip0-match0); offcode = OFFSET_TO_OFFBASE(rep_offset1); From 83de00316c29a7f5245a67733f6208c699b686c2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Oct 2024 15:36:15 -0700 Subject: [PATCH 373/937] fixed parameter ordering in `dfast` noticed by @terrelln --- lib/compress/zstd_double_fast.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 819658caf..c04010b11 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -201,7 +201,7 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( * However expression below complies into conditional move. Since * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex * if there is a match, all branches become predictable. */ - matchl0_safe = ZSTD_selectAddr(prefixLowestIndex, idxl0, &dummy[0], matchl0); + matchl0_safe = ZSTD_selectAddr(idxl0, prefixLowestIndex, matchl0, &dummy[0]); /* check prefix long match */ if (MEM_read64(matchl0_safe) == MEM_read64(ip) && matchl0_safe == matchl0) { @@ -215,7 +215,7 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( matchl1 = base + idxl1; /* Same optimization as matchl0 above */ - matchs0_safe = ZSTD_selectAddr(prefixLowestIndex, idxs0, &dummy[0], matchs0); + matchs0_safe = ZSTD_selectAddr(idxs0, prefixLowestIndex, matchs0, &dummy[0]); /* check prefix short match */ if(MEM_read32(matchs0_safe) == MEM_read32(ip) && matchs0_safe == matchs0) { @@ -662,7 +662,7 @@ size_t ZSTD_compressBlock_doubleFast_extDict_generic( size_t mLength; hashSmall[hSmall] = hashLong[hLong] = curr; /* update hash table */ - if (((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) + if (((ZSTD_index_overlap_check(prefixStartIndex, repIndex)) & (offset_1 <= curr+1 - dictStartIndex)) /* note: we are searching at curr+1 */ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) { const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; From 8e5823b65c6d0d1eb1c07be8428f427df5892d3a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Oct 2024 15:38:12 -0700 Subject: [PATCH 374/937] rename variable name findMatch -> matchFound since it's a test, as opposed to an active search operation. suggested by @terrelln --- lib/compress/zstd_fast.c | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 691bedc1e..e7edf9490 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -105,7 +105,7 @@ ZSTD_match4Found_cmov(const BYTE* currentPtr, const BYTE* matchAddress, U32 matc /* Array of ~random data, should have low probability of matching data. * Load from here if the index is invalid. * Used to avoid unpredictable branches. */ - static const BYTE dummy[] = {0x12,0x34,0x56,0x78 }; + static const BYTE dummy[] = {0x12,0x34,0x56,0x78}; /* currentIdx >= lowLimit is a (somewhat) unpredictable branch. * However expression below compiles into conditional move. @@ -232,7 +232,7 @@ size_t ZSTD_compressBlock_fast_noDict_generic( size_t step; const BYTE* nextStep; const size_t kStepIncr = (1 << (kSearchStrength - 1)); - const ZSTD_match4Found findMatch = useCmov ? ZSTD_match4Found_cmov : ZSTD_match4Found_branch; + const ZSTD_match4Found matchFound = useCmov ? ZSTD_match4Found_cmov : ZSTD_match4Found_branch; DEBUGLOG(5, "ZSTD_compressBlock_fast_generic"); ip0 += (ip0 == prefixStart); @@ -289,9 +289,7 @@ _start: /* Requires: ip0 */ goto _match; } - if (findMatch(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { - /* found a match! */ - + if (matchFound(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { /* Write next hash table entry (it's already calculated). * This write is known to be safe because the ip1 == ip0 + 1, * so searching will resume after ip1 */ @@ -316,17 +314,14 @@ _start: /* Requires: ip0 */ current0 = (U32)(ip0 - base); hashTable[hash0] = current0; - if (findMatch(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { - /* found a match! */ - - /* Write next hash table entry; it's already calculated */ + if (matchFound(ip0, base + matchIdx, matchIdx, prefixStartIndex)) { + /* Write next hash table entry, since it's already calculated */ if (step <= 4) { /* Avoid writing an index if it's >= position where search will resume. * The minimum possible match has length 4, so search can resume at ip0 + 4. */ hashTable[hash1] = (U32)(ip1 - base); } - goto _offset; } From 1024aa9252ff02ebc03511a2c0311957511d0be9 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Oct 2024 16:24:25 -0700 Subject: [PATCH 375/937] attempt to make 32-bit tests faster this is the longest CI test, reaching ~40mn on last PR --- .github/workflows/dev-long-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index d9f074369..3c2d1183b 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -50,7 +50,7 @@ jobs: run: | sudo apt-get -qqq update make libc6install - CFLAGS="-m32" make test + CFLAGS="-m32 -O1" make test V=1 no-intrinsics-fuzztest: runs-on: ubuntu-latest From 6f2e29a234c9f9ca63f1dd2748933a03f03ac731 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Oct 2024 17:30:55 -0700 Subject: [PATCH 376/937] measure if -O2 makes the test complete faster --- .github/workflows/dev-long-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 3c2d1183b..e4564c1d8 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -46,11 +46,11 @@ jobs: READFROMBLOCKDEVICE: 1 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: make test + - name: make test # note: make -j test seems to break when associated with `-m32` run: | sudo apt-get -qqq update make libc6install - CFLAGS="-m32 -O1" make test V=1 + CFLAGS="-m32 -O2" make test V=1 no-intrinsics-fuzztest: runs-on: ubuntu-latest From e6740355e35fa5695cb606e7bbda41b595175b3a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Oct 2024 18:01:28 -0700 Subject: [PATCH 377/937] attempt parallel test running with -j --- .github/workflows/dev-long-tests.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index e4564c1d8..deb5242b0 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -46,11 +46,12 @@ jobs: READFROMBLOCKDEVICE: 1 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: make test # note: make -j test seems to break when associated with `-m32` + - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update make libc6install - CFLAGS="-m32 -O2" make test V=1 + make clean + CFLAGS="-m32 -O2" make -j test V=1 no-intrinsics-fuzztest: runs-on: ubuntu-latest From e63896eb5844cb246aad7959ab208aa0a8f152bd Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 15 Oct 2024 17:46:01 -0700 Subject: [PATCH 378/937] small dictionary compression speed improvement not as good as small-blocks improvement, but generally positive. --- lib/compress/zstd_fast.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index e7edf9490..5373e3640 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -597,8 +597,8 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( } } - if (matchIndex > prefixStartIndex && MEM_read32(match) == MEM_read32(ip0)) { - /* found a regular match */ + if (ZSTD_match4Found_cmov(ip0, match, matchIndex, prefixStartIndex)) { + /* found a regular match of size >= 4 */ U32 const offset = (U32) (ip0 - match); mLength = ZSTD_count(ip0 + 4, match + 4, iend) + 4; while (((ip0 > anchor) & (match > prefixStart)) From c2abfc5ba40b2c7863080c937b728fb902b9cb5b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 15 Oct 2024 17:58:33 -0700 Subject: [PATCH 379/937] minor improvement to level 3 dictionary compression ratio --- lib/compress/zstd_double_fast.c | 45 +++++++++++++++------------------ 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index c04010b11..e2b3b4a14 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -140,7 +140,6 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( U32 idxl1; /* the long match index for ip1 */ const BYTE* matchl0; /* the long match for ip */ - const BYTE* matchl0_safe; /* matchl0 or safe address */ const BYTE* matchs0; /* the short match for ip */ const BYTE* matchl1; /* the long match for ip1 */ const BYTE* matchs0_safe; /* matchs0 or safe address */ @@ -201,15 +200,15 @@ size_t ZSTD_compressBlock_doubleFast_noDict_generic( * However expression below complies into conditional move. Since * match is unlikely and we only *branch* on idxl0 > prefixLowestIndex * if there is a match, all branches become predictable. */ - matchl0_safe = ZSTD_selectAddr(idxl0, prefixLowestIndex, matchl0, &dummy[0]); + { const BYTE* const matchl0_safe = ZSTD_selectAddr(idxl0, prefixLowestIndex, matchl0, &dummy[0]); - /* check prefix long match */ - if (MEM_read64(matchl0_safe) == MEM_read64(ip) && matchl0_safe == matchl0) { - mLength = ZSTD_count(ip+8, matchl0+8, iend) + 8; - offset = (U32)(ip-matchl0); - while (((ip>anchor) & (matchl0>prefixLowest)) && (ip[-1] == matchl0[-1])) { ip--; matchl0--; mLength++; } /* catch up */ - goto _match_found; - } + /* check prefix long match */ + if (MEM_read64(matchl0_safe) == MEM_read64(ip) && matchl0_safe == matchl0) { + mLength = ZSTD_count(ip+8, matchl0+8, iend) + 8; + offset = (U32)(ip-matchl0); + while (((ip>anchor) & (matchl0>prefixLowest)) && (ip[-1] == matchl0[-1])) { ip--; matchl0--; mLength++; } /* catch up */ + goto _match_found; + } } idxl1 = hashLong[hl1]; matchl1 = base + idxl1; @@ -412,14 +411,12 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( goto _match_stored; } - if (matchIndexL > prefixLowestIndex) { + if ((matchIndexL >= prefixLowestIndex) && (MEM_read64(matchLong) == MEM_read64(ip))) { /* check prefix long match */ - if (MEM_read64(matchLong) == MEM_read64(ip)) { - mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8; - offset = (U32)(ip-matchLong); - while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */ - goto _match_found; - } + mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8; + offset = (U32)(ip-matchLong); + while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */ + goto _match_found; } else if (dictTagsMatchL) { /* check dictMatchState long match */ U32 const dictMatchIndexL = dictMatchIndexAndTagL >> ZSTD_SHORT_CACHE_TAG_BITS; @@ -434,7 +431,7 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( } } if (matchIndexS > prefixLowestIndex) { - /* check prefix short match */ + /* short match candidate */ if (MEM_read32(match) == MEM_read32(ip)) { goto _search_next_long; } @@ -464,14 +461,12 @@ _search_next_long: hashLong[hl3] = curr + 1; /* check prefix long +1 match */ - if (matchIndexL3 > prefixLowestIndex) { - if (MEM_read64(matchL3) == MEM_read64(ip+1)) { - mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8; - ip++; - offset = (U32)(ip-matchL3); - while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */ - goto _match_found; - } + if ((matchIndexL3 >= prefixLowestIndex) && (MEM_read64(matchL3) == MEM_read64(ip+1))) { + mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8; + ip++; + offset = (U32)(ip-matchL3); + while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */ + goto _match_found; } else if (dictTagsMatchL3) { /* check dict long +1 match */ U32 const dictMatchIndexL3 = dictMatchIndexAndTagL3 >> ZSTD_SHORT_CACHE_TAG_BITS; From 730d2dce41800d2850726cdb0eefbf5fcb10b3de Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 15 Oct 2024 18:44:40 -0700 Subject: [PATCH 380/937] fix test --- tests/fuzzer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index f7bdae90e..ead3cc8dd 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -2450,7 +2450,7 @@ static int basicUnitTests(U32 const seed, double compressibility) 3742, 3675, 3674, 3665, 3664, 3663, 3662, 3661, 3660, 3660, 3660, 3660, 3660 }; - size_t const target_wdict_cSize[22+1] = { 2830, 2896, 2893, 2820, 2940, + size_t const target_wdict_cSize[22+1] = { 2830, 2896, 2893, 2840, 2950, 2950, 2950, 2925, 2900, 2892, 2910, 2910, 2910, 2780, 2775, 2765, 2760, 2755, 2754, 2753, From 632677516616434c312d2fff2d84dcf0c9b78012 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 16 Oct 2024 12:13:57 -0700 Subject: [PATCH 381/937] slightly improved compression ratio at levels 3 & 4 The compression ratio benefits are small but consistent, i.e. always positive. On `silesia.tar` corpus, this modification saves ~75 KB at level 3. The measured speed cost is negligible, i.e. below noise level, between 0 and -1%. --- lib/compress/zstd_double_fast.c | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index e2b3b4a14..72b541ea6 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -252,19 +252,23 @@ _cleanup: _search_next_long: - /* check prefix long +1 match */ + /* short match found: let's check for a longer one */ + mLength = ZSTD_count(ip+4, matchs0+4, iend) + 4; + + /* check long match at +1 position */ if (idxl1 > prefixLowestIndex) { if (MEM_read64(matchl1) == MEM_read64(ip1)) { - ip = ip1; - mLength = ZSTD_count(ip+8, matchl1+8, iend) + 8; - offset = (U32)(ip-matchl1); - while (((ip>anchor) & (matchl1>prefixLowest)) && (ip[-1] == matchl1[-1])) { ip--; matchl1--; mLength++; } /* catch up */ - goto _match_found; - } + size_t const llen = ZSTD_count(ip1+8, matchl1+8, iend) + 8; + if (llen > mLength) { + ip = ip1; + mLength = llen; + offset = (U32)(ip-matchl1); + while (((ip>anchor) & (matchl1>prefixLowest)) && (ip[-1] == matchl1[-1])) { ip--; matchl1--; mLength++; } /* catch up */ + goto _match_found; + } } } - /* if no long +1 match, explore the short match we found */ - mLength = ZSTD_count(ip+4, matchs0+4, iend) + 4; + /* validate short match previously found */ offset = (U32)(ip - matchs0); while (((ip>anchor) & (matchs0>prefixLowest)) && (ip[-1] == matchs0[-1])) { ip--; matchs0--; mLength++; } /* catch up */ From 61d08b0e42e7397af479ca9d1b66fe7235508f34 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 16 Oct 2024 12:55:52 -0700 Subject: [PATCH 382/937] fix test a margin of 4 is insufficient to guarantee compression success. --- tests/zstreamtest.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 8625b4a23..2c25adf3c 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -758,7 +758,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } streaming2KSize = ZSTD_sizeof_DCtx(dctx); CHECK_Z(streaming2KSize); - + CHECK_Z(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters)); inBuff.pos = 0; outBuff.pos = 0; @@ -769,7 +769,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) } streamingSize = ZSTD_sizeof_DCtx(dctx); CHECK_Z(streamingSize); - + CHECK_Z(ZSTD_DCtx_setParameter(dctx, ZSTD_d_maxBlockSize, 1024)); inBuff.pos = 0; outBuff.pos = 0; @@ -884,7 +884,8 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : ZSTD_compress2() uses stable input and output : ", testNb++); CHECK_Z(cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBufferSize)); CHECK(!(cSize < ZSTD_compressBound(CNBufferSize)), "cSize too large for test"); - CHECK_Z(cSize = ZSTD_compress2(cctx, compressedBuffer, cSize + 4, CNBuffer, CNBufferSize)); + /* check that compression fits with just a 8-bytes margin */ + CHECK_Z(cSize = ZSTD_compress2(cctx, compressedBuffer, cSize+8, CNBuffer, CNBufferSize)); CHECK_Z(cctxSize1 = ZSTD_sizeof_CCtx(cctx)); /* @cctxSize2 : sizeof_CCtx when doing full streaming (no stable in/out) */ { ZSTD_CCtx* const cctx2 = ZSTD_createCCtx(); @@ -2503,7 +2504,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) // Validate CHECK(outBuf.pos != srcSize, "decompressed size must match"); CHECK(memcmp(src, val, srcSize) != 0, "decompressed data must match"); - + // Cleanup free(src); free(dst); free(val); ZSTD_freeCCtx(cctx); From 47d4f5662df83c1a84476ab6c6f7fcb1d415f4f1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 09:36:56 -0700 Subject: [PATCH 383/937] rewrite code in the manner suggested by @terrelln --- lib/compress/zstd_double_fast.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 72b541ea6..50d698b37 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -254,23 +254,21 @@ _search_next_long: /* short match found: let's check for a longer one */ mLength = ZSTD_count(ip+4, matchs0+4, iend) + 4; + offset = (U32)(ip - matchs0); /* check long match at +1 position */ - if (idxl1 > prefixLowestIndex) { - if (MEM_read64(matchl1) == MEM_read64(ip1)) { - size_t const llen = ZSTD_count(ip1+8, matchl1+8, iend) + 8; - if (llen > mLength) { - ip = ip1; - mLength = llen; - offset = (U32)(ip-matchl1); - while (((ip>anchor) & (matchl1>prefixLowest)) && (ip[-1] == matchl1[-1])) { ip--; matchl1--; mLength++; } /* catch up */ - goto _match_found; - } } + if ((idxl1 > prefixLowestIndex) && (MEM_read64(matchl1) == MEM_read64(ip1))) { + size_t const l1len = ZSTD_count(ip1+8, matchl1+8, iend) + 8; + if (l1len > mLength) { + /* use the long match instead */ + ip = ip1; + mLength = l1len; + offset = (U32)(ip-matchl1); + matchs0 = matchl1; + } } - /* validate short match previously found */ - offset = (U32)(ip - matchs0); - while (((ip>anchor) & (matchs0>prefixLowest)) && (ip[-1] == matchs0[-1])) { ip--; matchs0--; mLength++; } /* catch up */ + while (((ip>anchor) & (matchs0>prefixLowest)) && (ip[-1] == matchs0[-1])) { ip--; matchs0--; mLength++; } /* complete backward */ /* fall-through */ From ff8e98bebee144321d7c39234deff43f9211dfbc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 09:45:16 -0700 Subject: [PATCH 384/937] enable regression tests at pull request time was transferred from circleci, but was only triggered on push into dev, i.e. after pull request is merged. --- .github/workflows/commit.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 25d8c52f9..ca5a85b8f 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -3,7 +3,12 @@ on: push: branches: - dev + pull_request: + branches: + - dev + permissions: read-all + jobs: short-tests-0: runs-on: ubuntu-latest @@ -27,6 +32,7 @@ jobs: make -j regressiontest; make clean make shortest; make clean make cxxtest; make clean + short-tests-1: runs-on: ubuntu-latest services: @@ -49,6 +55,7 @@ jobs: make aarch64build V=1; make clean make -C tests test-legacy test-longmatch; make clean make -C lib libzstd-nomt; make clean + regression-test: runs-on: ubuntu-latest services: From 41d870fbbf594c1ee1c0ac4113d1278ebf8301da Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 10:50:28 -0700 Subject: [PATCH 385/937] updated regression tests results --- tests/fuzz/.gitignore | 2 + tests/regression/results.csv | 604 +++++++++++++++++------------------ 2 files changed, 304 insertions(+), 302 deletions(-) diff --git a/tests/fuzz/.gitignore b/tests/fuzz/.gitignore index 28f2b8da4..b88ecb4ea 100644 --- a/tests/fuzz/.gitignore +++ b/tests/fuzz/.gitignore @@ -23,6 +23,8 @@ fuzz-*.log rt_lib_* d_lib_* crash-* +decompress_cross_format +generate_sequences # misc trace diff --git a/tests/regression/results.csv b/tests/regression/results.csv index fc3fbe7c7..e39abd66d 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -2,10 +2,10 @@ Data, Config, Method, silesia.tar, level -5, compress simple, 6861055 silesia.tar, level -3, compress simple, 6505483 silesia.tar, level -1, compress simple, 6179047 -silesia.tar, level 0, compress simple, 4854086 +silesia.tar, level 0, compress simple, 4851407 silesia.tar, level 1, compress simple, 5327717 -silesia.tar, level 3, compress simple, 4854086 -silesia.tar, level 4, compress simple, 4791503 +silesia.tar, level 3, compress simple, 4851407 +silesia.tar, level 4, compress simple, 4788821 silesia.tar, level 5, compress simple, 4679004 silesia.tar, level 6, compress simple, 4614561 silesia.tar, level 7, compress simple, 4579828 @@ -13,16 +13,16 @@ silesia.tar, level 9, compress silesia.tar, level 13, compress simple, 4502956 silesia.tar, level 16, compress simple, 4360385 silesia.tar, level 19, compress simple, 4260939 -silesia.tar, uncompressed literals, compress simple, 4854086 +silesia.tar, uncompressed literals, compress simple, 4851407 silesia.tar, uncompressed literals optimal, compress simple, 4260939 silesia.tar, huffman literals, compress simple, 6179047 github.tar, level -5, compress simple, 52115 github.tar, level -3, compress simple, 45678 github.tar, level -1, compress simple, 42560 -github.tar, level 0, compress simple, 38831 +github.tar, level 0, compress simple, 38884 github.tar, level 1, compress simple, 39200 -github.tar, level 3, compress simple, 38831 -github.tar, level 4, compress simple, 38893 +github.tar, level 3, compress simple, 38884 +github.tar, level 4, compress simple, 38880 github.tar, level 5, compress simple, 39651 github.tar, level 6, compress simple, 39282 github.tar, level 7, compress simple, 38005 @@ -30,16 +30,16 @@ github.tar, level 9, compress github.tar, level 13, compress simple, 35501 github.tar, level 16, compress simple, 40466 github.tar, level 19, compress simple, 32262 -github.tar, uncompressed literals, compress simple, 38831 +github.tar, uncompressed literals, compress simple, 38884 github.tar, uncompressed literals optimal, compress simple, 32262 github.tar, huffman literals, compress simple, 42560 silesia, level -5, compress cctx, 6857372 silesia, level -3, compress cctx, 6503412 silesia, level -1, compress cctx, 6172202 -silesia, level 0, compress cctx, 4842075 +silesia, level 0, compress cctx, 4839431 silesia, level 1, compress cctx, 5306632 -silesia, level 3, compress cctx, 4842075 -silesia, level 4, compress cctx, 4779186 +silesia, level 3, compress cctx, 4839431 +silesia, level 4, compress cctx, 4776557 silesia, level 5, compress cctx, 4667668 silesia, level 6, compress cctx, 4604351 silesia, level 7, compress cctx, 4570271 @@ -47,28 +47,28 @@ silesia, level 9, compress silesia, level 13, compress cctx, 4493990 silesia, level 16, compress cctx, 4359652 silesia, level 19, compress cctx, 4266582 -silesia, long distance mode, compress cctx, 4842075 -silesia, multithreaded, compress cctx, 4842075 -silesia, multithreaded long distance mode, compress cctx, 4842075 -silesia, small window log, compress cctx, 7082951 +silesia, long distance mode, compress cctx, 4839431 +silesia, multithreaded, compress cctx, 4839431 +silesia, multithreaded long distance mode, compress cctx, 4839431 +silesia, small window log, compress cctx, 7082907 silesia, small hash log, compress cctx, 6526141 silesia, small chain log, compress cctx, 4912197 silesia, explicit params, compress cctx, 4794318 -silesia, uncompressed literals, compress cctx, 4842075 +silesia, uncompressed literals, compress cctx, 4839431 silesia, uncompressed literals optimal, compress cctx, 4266582 silesia, huffman literals, compress cctx, 6172202 -silesia, multithreaded with advanced params, compress cctx, 4842075 +silesia, multithreaded with advanced params, compress cctx, 4839431 github, level -5, compress cctx, 204407 github, level -5 with dict, compress cctx, 47581 github, level -3, compress cctx, 193253 github, level -3 with dict, compress cctx, 43043 github, level -1, compress cctx, 175468 github, level -1 with dict, compress cctx, 42044 -github, level 0, compress cctx, 136332 +github, level 0, compress cctx, 136331 github, level 0 with dict, compress cctx, 41534 github, level 1, compress cctx, 142365 github, level 1 with dict, compress cctx, 41715 -github, level 3, compress cctx, 136332 +github, level 3, compress cctx, 136331 github, level 3 with dict, compress cctx, 41534 github, level 4, compress cctx, 136199 github, level 4 with dict, compress cctx, 41725 @@ -93,17 +93,17 @@ github, small window log, compress github, small hash log, compress cctx, 138949 github, small chain log, compress cctx, 139242 github, explicit params, compress cctx, 140932 -github, uncompressed literals, compress cctx, 136332 +github, uncompressed literals, compress cctx, 136331 github, uncompressed literals optimal, compress cctx, 132879 github, huffman literals, compress cctx, 175468 github, multithreaded with advanced params, compress cctx, 141069 silesia, level -5, zstdcli, 6857420 silesia, level -3, zstdcli, 6503460 silesia, level -1, zstdcli, 6172250 -silesia, level 0, zstdcli, 4842123 +silesia, level 0, zstdcli, 4839479 silesia, level 1, zstdcli, 5306680 -silesia, level 3, zstdcli, 4842123 -silesia, level 4, zstdcli, 4779234 +silesia, level 3, zstdcli, 4839479 +silesia, level 4, zstdcli, 4776605 silesia, level 5, zstdcli, 4667716 silesia, level 6, zstdcli, 4604399 silesia, level 7, zstdcli, 4570319 @@ -111,24 +111,24 @@ silesia, level 9, zstdcli, silesia, level 13, zstdcli, 4494038 silesia, level 16, zstdcli, 4359700 silesia, level 19, zstdcli, 4266630 -silesia, long distance mode, zstdcli, 4833785 -silesia, multithreaded, zstdcli, 4842123 -silesia, multithreaded long distance mode, zstdcli, 4833785 -silesia, small window log, zstdcli, 7095048 +silesia, long distance mode, zstdcli, 4831224 +silesia, multithreaded, zstdcli, 4839479 +silesia, multithreaded long distance mode, zstdcli, 4831224 +silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6526189 silesia, small chain log, zstdcli, 4912245 silesia, explicit params, zstdcli, 4795840 -silesia, uncompressed literals, zstdcli, 5120614 +silesia, uncompressed literals, zstdcli, 5117005 silesia, uncompressed literals optimal, zstdcli, 4316928 silesia, huffman literals, zstdcli, 5321417 -silesia, multithreaded with advanced params, zstdcli, 5120614 +silesia, multithreaded with advanced params, zstdcli, 5117005 silesia.tar, level -5, zstdcli, 6862049 silesia.tar, level -3, zstdcli, 6506509 silesia.tar, level -1, zstdcli, 6179789 -silesia.tar, level 0, zstdcli, 4854164 +silesia.tar, level 0, zstdcli, 4851482 silesia.tar, level 1, zstdcli, 5329010 -silesia.tar, level 3, zstdcli, 4854164 -silesia.tar, level 4, zstdcli, 4792352 +silesia.tar, level 3, zstdcli, 4851482 +silesia.tar, level 4, zstdcli, 4789729 silesia.tar, level 5, zstdcli, 4679860 silesia.tar, level 6, zstdcli, 4615355 silesia.tar, level 7, zstdcli, 4581791 @@ -136,32 +136,32 @@ silesia.tar, level 9, zstdcli, silesia.tar, level 13, zstdcli, 4502960 silesia.tar, level 16, zstdcli, 4360389 silesia.tar, level 19, zstdcli, 4260943 -silesia.tar, no source size, zstdcli, 4854160 -silesia.tar, long distance mode, zstdcli, 4845745 -silesia.tar, multithreaded, zstdcli, 4854164 -silesia.tar, multithreaded long distance mode, zstdcli, 4845745 -silesia.tar, small window log, zstdcli, 7100701 +silesia.tar, no source size, zstdcli, 4851478 +silesia.tar, long distance mode, zstdcli, 4843159 +silesia.tar, multithreaded, zstdcli, 4851482 +silesia.tar, multithreaded long distance mode, zstdcli, 4843159 +silesia.tar, small window log, zstdcli, 7100110 silesia.tar, small hash log, zstdcli, 6529264 silesia.tar, small chain log, zstdcli, 4917022 silesia.tar, explicit params, zstdcli, 4821112 -silesia.tar, uncompressed literals, zstdcli, 5122571 +silesia.tar, uncompressed literals, zstdcli, 5118944 silesia.tar, uncompressed literals optimal, zstdcli, 4308455 silesia.tar, huffman literals, zstdcli, 5342074 -silesia.tar, multithreaded with advanced params, zstdcli, 5122571 +silesia.tar, multithreaded with advanced params, zstdcli, 5118944 github, level -5, zstdcli, 206407 github, level -5 with dict, zstdcli, 47832 github, level -3, zstdcli, 195253 github, level -3 with dict, zstdcli, 46671 github, level -1, zstdcli, 177468 github, level -1 with dict, zstdcli, 43825 -github, level 0, zstdcli, 138332 -github, level 0 with dict, zstdcli, 43148 +github, level 0, zstdcli, 138331 +github, level 0 with dict, zstdcli, 43118 github, level 1, zstdcli, 144365 github, level 1 with dict, zstdcli, 43266 -github, level 3, zstdcli, 138332 -github, level 3 with dict, zstdcli, 43148 +github, level 3, zstdcli, 138331 +github, level 3 with dict, zstdcli, 43118 github, level 4, zstdcli, 138199 -github, level 4 with dict, zstdcli, 43251 +github, level 4 with dict, zstdcli, 43229 github, level 5, zstdcli, 137121 github, level 5 with dict, zstdcli, 40728 github, level 6, zstdcli, 137122 @@ -176,30 +176,30 @@ github, level 16, zstdcli, github, level 16 with dict, zstdcli, 39902 github, level 19, zstdcli, 134879 github, level 19 with dict, zstdcli, 39916 -github, long distance mode, zstdcli, 138332 -github, multithreaded, zstdcli, 138332 -github, multithreaded long distance mode, zstdcli, 138332 -github, small window log, zstdcli, 138332 +github, long distance mode, zstdcli, 138331 +github, multithreaded, zstdcli, 138331 +github, multithreaded long distance mode, zstdcli, 138331 +github, small window log, zstdcli, 138331 github, small hash log, zstdcli, 137590 github, small chain log, zstdcli, 138341 github, explicit params, zstdcli, 136197 -github, uncompressed literals, zstdcli, 167911 +github, uncompressed literals, zstdcli, 167909 github, uncompressed literals optimal, zstdcli, 154667 github, huffman literals, zstdcli, 144365 -github, multithreaded with advanced params, zstdcli, 167911 +github, multithreaded with advanced params, zstdcli, 167909 github.tar, level -5, zstdcli, 52119 github.tar, level -5 with dict, zstdcli, 51101 github.tar, level -3, zstdcli, 45682 github.tar, level -3 with dict, zstdcli, 44738 github.tar, level -1, zstdcli, 42564 github.tar, level -1 with dict, zstdcli, 41357 -github.tar, level 0, zstdcli, 38835 +github.tar, level 0, zstdcli, 38888 github.tar, level 0 with dict, zstdcli, 37999 github.tar, level 1, zstdcli, 39204 github.tar, level 1 with dict, zstdcli, 38123 -github.tar, level 3, zstdcli, 38835 +github.tar, level 3, zstdcli, 38888 github.tar, level 3 with dict, zstdcli, 37999 -github.tar, level 4, zstdcli, 38897 +github.tar, level 4, zstdcli, 38884 github.tar, level 4 with dict, zstdcli, 37952 github.tar, level 5, zstdcli, 39655 github.tar, level 5 with dict, zstdcli, 39073 @@ -215,26 +215,26 @@ github.tar, level 16, zstdcli, github.tar, level 16 with dict, zstdcli, 33379 github.tar, level 19, zstdcli, 32266 github.tar, level 19 with dict, zstdcli, 32705 -github.tar, no source size, zstdcli, 38832 -github.tar, no source size with dict, zstdcli, 38004 -github.tar, long distance mode, zstdcli, 40236 -github.tar, multithreaded, zstdcli, 38835 -github.tar, multithreaded long distance mode, zstdcli, 40236 -github.tar, small window log, zstdcli, 198544 +github.tar, no source size, zstdcli, 38885 +github.tar, no source size with dict, zstdcli, 38115 +github.tar, long distance mode, zstdcli, 40227 +github.tar, multithreaded, zstdcli, 38888 +github.tar, multithreaded long distance mode, zstdcli, 40227 +github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 github.tar, explicit params, zstdcli, 41385 -github.tar, uncompressed literals, zstdcli, 41529 +github.tar, uncompressed literals, zstdcli, 41566 github.tar, uncompressed literals optimal, zstdcli, 35360 github.tar, huffman literals, zstdcli, 38857 -github.tar, multithreaded with advanced params, zstdcli, 41529 +github.tar, multithreaded with advanced params, zstdcli, 41566 silesia, level -5, advanced one pass, 6857372 silesia, level -3, advanced one pass, 6503412 silesia, level -1, advanced one pass, 6172202 -silesia, level 0, advanced one pass, 4842075 +silesia, level 0, advanced one pass, 4839431 silesia, level 1, advanced one pass, 5306632 -silesia, level 3, advanced one pass, 4842075 -silesia, level 4, advanced one pass, 4779186 +silesia, level 3, advanced one pass, 4839431 +silesia, level 4, advanced one pass, 4776557 silesia, level 5 row 1, advanced one pass, 4667668 silesia, level 5 row 2, advanced one pass, 4670326 silesia, level 5, advanced one pass, 4667668 @@ -250,25 +250,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced one pass, 4493990 silesia, level 16, advanced one pass, 4359652 silesia, level 19, advanced one pass, 4266582 -silesia, no source size, advanced one pass, 4842075 -silesia, long distance mode, advanced one pass, 4833710 -silesia, multithreaded, advanced one pass, 4842075 -silesia, multithreaded long distance mode, advanced one pass, 4833737 -silesia, small window log, advanced one pass, 7095000 +silesia, no source size, advanced one pass, 4839431 +silesia, long distance mode, advanced one pass, 4831158 +silesia, multithreaded, advanced one pass, 4839431 +silesia, multithreaded long distance mode, advanced one pass, 4831176 +silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6526141 silesia, small chain log, advanced one pass, 4912197 silesia, explicit params, advanced one pass, 4795840 -silesia, uncompressed literals, advanced one pass, 5120566 +silesia, uncompressed literals, advanced one pass, 5116957 silesia, uncompressed literals optimal, advanced one pass, 4316880 silesia, huffman literals, advanced one pass, 5321369 -silesia, multithreaded with advanced params, advanced one pass, 5120566 +silesia, multithreaded with advanced params, advanced one pass, 5116957 silesia.tar, level -5, advanced one pass, 6861055 silesia.tar, level -3, advanced one pass, 6505483 silesia.tar, level -1, advanced one pass, 6179047 -silesia.tar, level 0, advanced one pass, 4854086 +silesia.tar, level 0, advanced one pass, 4851407 silesia.tar, level 1, advanced one pass, 5327717 -silesia.tar, level 3, advanced one pass, 4854086 -silesia.tar, level 4, advanced one pass, 4791503 +silesia.tar, level 3, advanced one pass, 4851407 +silesia.tar, level 4, advanced one pass, 4788821 silesia.tar, level 5 row 1, advanced one pass, 4679004 silesia.tar, level 5 row 2, advanced one pass, 4682334 silesia.tar, level 5, advanced one pass, 4679004 @@ -284,28 +284,28 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced one pass, 4502956 silesia.tar, level 16, advanced one pass, 4360385 silesia.tar, level 19, advanced one pass, 4260939 -silesia.tar, no source size, advanced one pass, 4854086 -silesia.tar, long distance mode, advanced one pass, 4840452 -silesia.tar, multithreaded, advanced one pass, 4854160 -silesia.tar, multithreaded long distance mode, advanced one pass, 4845741 -silesia.tar, small window log, advanced one pass, 7100655 +silesia.tar, no source size, advanced one pass, 4851407 +silesia.tar, long distance mode, advanced one pass, 4837775 +silesia.tar, multithreaded, advanced one pass, 4851478 +silesia.tar, multithreaded long distance mode, advanced one pass, 4843155 +silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6529206 silesia.tar, small chain log, advanced one pass, 4917041 silesia.tar, explicit params, advanced one pass, 4807274 -silesia.tar, uncompressed literals, advanced one pass, 5122473 +silesia.tar, uncompressed literals, advanced one pass, 5118848 silesia.tar, uncompressed literals optimal, advanced one pass, 4308451 silesia.tar, huffman literals, advanced one pass, 5341705 -silesia.tar, multithreaded with advanced params, advanced one pass, 5122567 +silesia.tar, multithreaded with advanced params, advanced one pass, 5118940 github, level -5, advanced one pass, 204407 github, level -5 with dict, advanced one pass, 45832 github, level -3, advanced one pass, 193253 github, level -3 with dict, advanced one pass, 44671 github, level -1, advanced one pass, 175468 github, level -1 with dict, advanced one pass, 41825 -github, level 0, advanced one pass, 136332 -github, level 0 with dict, advanced one pass, 41148 -github, level 0 with dict dms, advanced one pass, 41148 -github, level 0 with dict dds, advanced one pass, 41148 +github, level 0, advanced one pass, 136331 +github, level 0 with dict, advanced one pass, 41118 +github, level 0 with dict dms, advanced one pass, 41118 +github, level 0 with dict dds, advanced one pass, 41118 github, level 0 with dict copy, advanced one pass, 41124 github, level 0 with dict load, advanced one pass, 41847 github, level 1, advanced one pass, 142365 @@ -314,16 +314,16 @@ github, level 1 with dict dms, advanced github, level 1 with dict dds, advanced one pass, 41266 github, level 1 with dict copy, advanced one pass, 41279 github, level 1 with dict load, advanced one pass, 43331 -github, level 3, advanced one pass, 136332 -github, level 3 with dict, advanced one pass, 41148 -github, level 3 with dict dms, advanced one pass, 41148 -github, level 3 with dict dds, advanced one pass, 41148 +github, level 3, advanced one pass, 136331 +github, level 3 with dict, advanced one pass, 41118 +github, level 3 with dict dms, advanced one pass, 41118 +github, level 3 with dict dds, advanced one pass, 41118 github, level 3 with dict copy, advanced one pass, 41124 github, level 3 with dict load, advanced one pass, 41847 github, level 4, advanced one pass, 136199 -github, level 4 with dict, advanced one pass, 41251 -github, level 4 with dict dms, advanced one pass, 41251 -github, level 4 with dict dds, advanced one pass, 41251 +github, level 4 with dict, advanced one pass, 41229 +github, level 4 with dict dms, advanced one pass, 41229 +github, level 4 with dict dds, advanced one pass, 41229 github, level 4 with dict copy, advanced one pass, 41216 github, level 4 with dict load, advanced one pass, 41548 github, level 5 row 1, advanced one pass, 134584 @@ -408,29 +408,29 @@ github, level 19 with dict dms, advanced github, level 19 with dict dds, advanced one pass, 37916 github, level 19 with dict copy, advanced one pass, 37906 github, level 19 with dict load, advanced one pass, 39770 -github, no source size, advanced one pass, 136332 -github, no source size with dict, advanced one pass, 41148 -github, long distance mode, advanced one pass, 136332 -github, multithreaded, advanced one pass, 136332 -github, multithreaded long distance mode, advanced one pass, 136332 -github, small window log, advanced one pass, 136332 +github, no source size, advanced one pass, 136331 +github, no source size with dict, advanced one pass, 41118 +github, long distance mode, advanced one pass, 136331 +github, multithreaded, advanced one pass, 136331 +github, multithreaded long distance mode, advanced one pass, 136331 +github, small window log, advanced one pass, 136331 github, small hash log, advanced one pass, 135590 github, small chain log, advanced one pass, 136341 github, explicit params, advanced one pass, 137727 -github, uncompressed literals, advanced one pass, 165911 +github, uncompressed literals, advanced one pass, 165909 github, uncompressed literals optimal, advanced one pass, 152667 github, huffman literals, advanced one pass, 142365 -github, multithreaded with advanced params, advanced one pass, 165911 +github, multithreaded with advanced params, advanced one pass, 165909 github.tar, level -5, advanced one pass, 52115 github.tar, level -5 with dict, advanced one pass, 51097 github.tar, level -3, advanced one pass, 45678 github.tar, level -3 with dict, advanced one pass, 44734 github.tar, level -1, advanced one pass, 42560 github.tar, level -1 with dict, advanced one pass, 41353 -github.tar, level 0, advanced one pass, 38831 +github.tar, level 0, advanced one pass, 38884 github.tar, level 0 with dict, advanced one pass, 37995 -github.tar, level 0 with dict dms, advanced one pass, 38003 -github.tar, level 0 with dict dds, advanced one pass, 38003 +github.tar, level 0 with dict dms, advanced one pass, 38114 +github.tar, level 0 with dict dds, advanced one pass, 38114 github.tar, level 0 with dict copy, advanced one pass, 37995 github.tar, level 0 with dict load, advanced one pass, 37956 github.tar, level 1, advanced one pass, 39200 @@ -439,16 +439,16 @@ github.tar, level 1 with dict dms, advanced github.tar, level 1 with dict dds, advanced one pass, 38406 github.tar, level 1 with dict copy, advanced one pass, 38119 github.tar, level 1 with dict load, advanced one pass, 38364 -github.tar, level 3, advanced one pass, 38831 +github.tar, level 3, advanced one pass, 38884 github.tar, level 3 with dict, advanced one pass, 37995 -github.tar, level 3 with dict dms, advanced one pass, 38003 -github.tar, level 3 with dict dds, advanced one pass, 38003 +github.tar, level 3 with dict dms, advanced one pass, 38114 +github.tar, level 3 with dict dds, advanced one pass, 38114 github.tar, level 3 with dict copy, advanced one pass, 37995 github.tar, level 3 with dict load, advanced one pass, 37956 -github.tar, level 4, advanced one pass, 38893 +github.tar, level 4, advanced one pass, 38880 github.tar, level 4 with dict, advanced one pass, 37948 -github.tar, level 4 with dict dms, advanced one pass, 37954 -github.tar, level 4 with dict dds, advanced one pass, 37954 +github.tar, level 4 with dict dms, advanced one pass, 37995 +github.tar, level 4 with dict dds, advanced one pass, 37995 github.tar, level 4 with dict copy, advanced one pass, 37948 github.tar, level 4 with dict load, advanced one pass, 37927 github.tar, level 5 row 1, advanced one pass, 39651 @@ -533,26 +533,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass, 32565 github.tar, level 19 with dict copy, advanced one pass, 32701 github.tar, level 19 with dict load, advanced one pass, 32428 -github.tar, no source size, advanced one pass, 38831 +github.tar, no source size, advanced one pass, 38884 github.tar, no source size with dict, advanced one pass, 37995 -github.tar, long distance mode, advanced one pass, 40252 -github.tar, multithreaded, advanced one pass, 38831 -github.tar, multithreaded long distance mode, advanced one pass, 40232 -github.tar, small window log, advanced one pass, 198540 +github.tar, long distance mode, advanced one pass, 40242 +github.tar, multithreaded, advanced one pass, 38884 +github.tar, multithreaded long distance mode, advanced one pass, 40223 +github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 github.tar, explicit params, advanced one pass, 41385 -github.tar, uncompressed literals, advanced one pass, 41525 +github.tar, uncompressed literals, advanced one pass, 41562 github.tar, uncompressed literals optimal, advanced one pass, 35356 github.tar, huffman literals, advanced one pass, 38853 -github.tar, multithreaded with advanced params, advanced one pass, 41525 +github.tar, multithreaded with advanced params, advanced one pass, 41562 silesia, level -5, advanced one pass small out, 6857372 silesia, level -3, advanced one pass small out, 6503412 silesia, level -1, advanced one pass small out, 6172202 -silesia, level 0, advanced one pass small out, 4842075 +silesia, level 0, advanced one pass small out, 4839431 silesia, level 1, advanced one pass small out, 5306632 -silesia, level 3, advanced one pass small out, 4842075 -silesia, level 4, advanced one pass small out, 4779186 +silesia, level 3, advanced one pass small out, 4839431 +silesia, level 4, advanced one pass small out, 4776557 silesia, level 5 row 1, advanced one pass small out, 4667668 silesia, level 5 row 2, advanced one pass small out, 4670326 silesia, level 5, advanced one pass small out, 4667668 @@ -568,25 +568,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced one pass small out, 4493990 silesia, level 16, advanced one pass small out, 4359652 silesia, level 19, advanced one pass small out, 4266582 -silesia, no source size, advanced one pass small out, 4842075 -silesia, long distance mode, advanced one pass small out, 4833710 -silesia, multithreaded, advanced one pass small out, 4842075 -silesia, multithreaded long distance mode, advanced one pass small out, 4833737 -silesia, small window log, advanced one pass small out, 7095000 +silesia, no source size, advanced one pass small out, 4839431 +silesia, long distance mode, advanced one pass small out, 4831158 +silesia, multithreaded, advanced one pass small out, 4839431 +silesia, multithreaded long distance mode, advanced one pass small out, 4831176 +silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6526141 silesia, small chain log, advanced one pass small out, 4912197 silesia, explicit params, advanced one pass small out, 4795840 -silesia, uncompressed literals, advanced one pass small out, 5120566 +silesia, uncompressed literals, advanced one pass small out, 5116957 silesia, uncompressed literals optimal, advanced one pass small out, 4316880 silesia, huffman literals, advanced one pass small out, 5321369 -silesia, multithreaded with advanced params, advanced one pass small out, 5120566 +silesia, multithreaded with advanced params, advanced one pass small out, 5116957 silesia.tar, level -5, advanced one pass small out, 6861055 silesia.tar, level -3, advanced one pass small out, 6505483 silesia.tar, level -1, advanced one pass small out, 6179047 -silesia.tar, level 0, advanced one pass small out, 4854086 +silesia.tar, level 0, advanced one pass small out, 4851407 silesia.tar, level 1, advanced one pass small out, 5327717 -silesia.tar, level 3, advanced one pass small out, 4854086 -silesia.tar, level 4, advanced one pass small out, 4791503 +silesia.tar, level 3, advanced one pass small out, 4851407 +silesia.tar, level 4, advanced one pass small out, 4788821 silesia.tar, level 5 row 1, advanced one pass small out, 4679004 silesia.tar, level 5 row 2, advanced one pass small out, 4682334 silesia.tar, level 5, advanced one pass small out, 4679004 @@ -602,28 +602,28 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced one pass small out, 4502956 silesia.tar, level 16, advanced one pass small out, 4360385 silesia.tar, level 19, advanced one pass small out, 4260939 -silesia.tar, no source size, advanced one pass small out, 4854086 -silesia.tar, long distance mode, advanced one pass small out, 4840452 -silesia.tar, multithreaded, advanced one pass small out, 4854160 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4845741 -silesia.tar, small window log, advanced one pass small out, 7100655 +silesia.tar, no source size, advanced one pass small out, 4851407 +silesia.tar, long distance mode, advanced one pass small out, 4837775 +silesia.tar, multithreaded, advanced one pass small out, 4851478 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4843155 +silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6529206 silesia.tar, small chain log, advanced one pass small out, 4917041 silesia.tar, explicit params, advanced one pass small out, 4807274 -silesia.tar, uncompressed literals, advanced one pass small out, 5122473 +silesia.tar, uncompressed literals, advanced one pass small out, 5118848 silesia.tar, uncompressed literals optimal, advanced one pass small out, 4308451 silesia.tar, huffman literals, advanced one pass small out, 5341705 -silesia.tar, multithreaded with advanced params, advanced one pass small out, 5122567 +silesia.tar, multithreaded with advanced params, advanced one pass small out, 5118940 github, level -5, advanced one pass small out, 204407 github, level -5 with dict, advanced one pass small out, 45832 github, level -3, advanced one pass small out, 193253 github, level -3 with dict, advanced one pass small out, 44671 github, level -1, advanced one pass small out, 175468 github, level -1 with dict, advanced one pass small out, 41825 -github, level 0, advanced one pass small out, 136332 -github, level 0 with dict, advanced one pass small out, 41148 -github, level 0 with dict dms, advanced one pass small out, 41148 -github, level 0 with dict dds, advanced one pass small out, 41148 +github, level 0, advanced one pass small out, 136331 +github, level 0 with dict, advanced one pass small out, 41118 +github, level 0 with dict dms, advanced one pass small out, 41118 +github, level 0 with dict dds, advanced one pass small out, 41118 github, level 0 with dict copy, advanced one pass small out, 41124 github, level 0 with dict load, advanced one pass small out, 41847 github, level 1, advanced one pass small out, 142365 @@ -632,16 +632,16 @@ github, level 1 with dict dms, advanced github, level 1 with dict dds, advanced one pass small out, 41266 github, level 1 with dict copy, advanced one pass small out, 41279 github, level 1 with dict load, advanced one pass small out, 43331 -github, level 3, advanced one pass small out, 136332 -github, level 3 with dict, advanced one pass small out, 41148 -github, level 3 with dict dms, advanced one pass small out, 41148 -github, level 3 with dict dds, advanced one pass small out, 41148 +github, level 3, advanced one pass small out, 136331 +github, level 3 with dict, advanced one pass small out, 41118 +github, level 3 with dict dms, advanced one pass small out, 41118 +github, level 3 with dict dds, advanced one pass small out, 41118 github, level 3 with dict copy, advanced one pass small out, 41124 github, level 3 with dict load, advanced one pass small out, 41847 github, level 4, advanced one pass small out, 136199 -github, level 4 with dict, advanced one pass small out, 41251 -github, level 4 with dict dms, advanced one pass small out, 41251 -github, level 4 with dict dds, advanced one pass small out, 41251 +github, level 4 with dict, advanced one pass small out, 41229 +github, level 4 with dict dms, advanced one pass small out, 41229 +github, level 4 with dict dds, advanced one pass small out, 41229 github, level 4 with dict copy, advanced one pass small out, 41216 github, level 4 with dict load, advanced one pass small out, 41548 github, level 5 row 1, advanced one pass small out, 134584 @@ -726,29 +726,29 @@ github, level 19 with dict dms, advanced github, level 19 with dict dds, advanced one pass small out, 37916 github, level 19 with dict copy, advanced one pass small out, 37906 github, level 19 with dict load, advanced one pass small out, 39770 -github, no source size, advanced one pass small out, 136332 -github, no source size with dict, advanced one pass small out, 41148 -github, long distance mode, advanced one pass small out, 136332 -github, multithreaded, advanced one pass small out, 136332 -github, multithreaded long distance mode, advanced one pass small out, 136332 -github, small window log, advanced one pass small out, 136332 +github, no source size, advanced one pass small out, 136331 +github, no source size with dict, advanced one pass small out, 41118 +github, long distance mode, advanced one pass small out, 136331 +github, multithreaded, advanced one pass small out, 136331 +github, multithreaded long distance mode, advanced one pass small out, 136331 +github, small window log, advanced one pass small out, 136331 github, small hash log, advanced one pass small out, 135590 github, small chain log, advanced one pass small out, 136341 github, explicit params, advanced one pass small out, 137727 -github, uncompressed literals, advanced one pass small out, 165911 +github, uncompressed literals, advanced one pass small out, 165909 github, uncompressed literals optimal, advanced one pass small out, 152667 github, huffman literals, advanced one pass small out, 142365 -github, multithreaded with advanced params, advanced one pass small out, 165911 +github, multithreaded with advanced params, advanced one pass small out, 165909 github.tar, level -5, advanced one pass small out, 52115 github.tar, level -5 with dict, advanced one pass small out, 51097 github.tar, level -3, advanced one pass small out, 45678 github.tar, level -3 with dict, advanced one pass small out, 44734 github.tar, level -1, advanced one pass small out, 42560 github.tar, level -1 with dict, advanced one pass small out, 41353 -github.tar, level 0, advanced one pass small out, 38831 +github.tar, level 0, advanced one pass small out, 38884 github.tar, level 0 with dict, advanced one pass small out, 37995 -github.tar, level 0 with dict dms, advanced one pass small out, 38003 -github.tar, level 0 with dict dds, advanced one pass small out, 38003 +github.tar, level 0 with dict dms, advanced one pass small out, 38114 +github.tar, level 0 with dict dds, advanced one pass small out, 38114 github.tar, level 0 with dict copy, advanced one pass small out, 37995 github.tar, level 0 with dict load, advanced one pass small out, 37956 github.tar, level 1, advanced one pass small out, 39200 @@ -757,16 +757,16 @@ github.tar, level 1 with dict dms, advanced github.tar, level 1 with dict dds, advanced one pass small out, 38406 github.tar, level 1 with dict copy, advanced one pass small out, 38119 github.tar, level 1 with dict load, advanced one pass small out, 38364 -github.tar, level 3, advanced one pass small out, 38831 +github.tar, level 3, advanced one pass small out, 38884 github.tar, level 3 with dict, advanced one pass small out, 37995 -github.tar, level 3 with dict dms, advanced one pass small out, 38003 -github.tar, level 3 with dict dds, advanced one pass small out, 38003 +github.tar, level 3 with dict dms, advanced one pass small out, 38114 +github.tar, level 3 with dict dds, advanced one pass small out, 38114 github.tar, level 3 with dict copy, advanced one pass small out, 37995 github.tar, level 3 with dict load, advanced one pass small out, 37956 -github.tar, level 4, advanced one pass small out, 38893 +github.tar, level 4, advanced one pass small out, 38880 github.tar, level 4 with dict, advanced one pass small out, 37948 -github.tar, level 4 with dict dms, advanced one pass small out, 37954 -github.tar, level 4 with dict dds, advanced one pass small out, 37954 +github.tar, level 4 with dict dms, advanced one pass small out, 37995 +github.tar, level 4 with dict dds, advanced one pass small out, 37995 github.tar, level 4 with dict copy, advanced one pass small out, 37948 github.tar, level 4 with dict load, advanced one pass small out, 37927 github.tar, level 5 row 1, advanced one pass small out, 39651 @@ -851,26 +851,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass small out, 32565 github.tar, level 19 with dict copy, advanced one pass small out, 32701 github.tar, level 19 with dict load, advanced one pass small out, 32428 -github.tar, no source size, advanced one pass small out, 38831 +github.tar, no source size, advanced one pass small out, 38884 github.tar, no source size with dict, advanced one pass small out, 37995 -github.tar, long distance mode, advanced one pass small out, 40252 -github.tar, multithreaded, advanced one pass small out, 38831 -github.tar, multithreaded long distance mode, advanced one pass small out, 40232 -github.tar, small window log, advanced one pass small out, 198540 +github.tar, long distance mode, advanced one pass small out, 40242 +github.tar, multithreaded, advanced one pass small out, 38884 +github.tar, multithreaded long distance mode, advanced one pass small out, 40223 +github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 github.tar, explicit params, advanced one pass small out, 41385 -github.tar, uncompressed literals, advanced one pass small out, 41525 +github.tar, uncompressed literals, advanced one pass small out, 41562 github.tar, uncompressed literals optimal, advanced one pass small out, 35356 github.tar, huffman literals, advanced one pass small out, 38853 -github.tar, multithreaded with advanced params, advanced one pass small out, 41525 +github.tar, multithreaded with advanced params, advanced one pass small out, 41562 silesia, level -5, advanced streaming, 6854744 silesia, level -3, advanced streaming, 6503319 silesia, level -1, advanced streaming, 6172207 -silesia, level 0, advanced streaming, 4842075 +silesia, level 0, advanced streaming, 4839431 silesia, level 1, advanced streaming, 5306388 -silesia, level 3, advanced streaming, 4842075 -silesia, level 4, advanced streaming, 4779186 +silesia, level 3, advanced streaming, 4839431 +silesia, level 4, advanced streaming, 4776557 silesia, level 5 row 1, advanced streaming, 4667668 silesia, level 5 row 2, advanced streaming, 4670326 silesia, level 5, advanced streaming, 4667668 @@ -886,25 +886,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced streaming, 4493990 silesia, level 16, advanced streaming, 4359652 silesia, level 19, advanced streaming, 4266582 -silesia, no source size, advanced streaming, 4842039 -silesia, long distance mode, advanced streaming, 4833710 -silesia, multithreaded, advanced streaming, 4842075 -silesia, multithreaded long distance mode, advanced streaming, 4833737 -silesia, small window log, advanced streaming, 7111103 +silesia, no source size, advanced streaming, 4839395 +silesia, long distance mode, advanced streaming, 4831158 +silesia, multithreaded, advanced streaming, 4839431 +silesia, multithreaded long distance mode, advanced streaming, 4831176 +silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6526141 silesia, small chain log, advanced streaming, 4912197 silesia, explicit params, advanced streaming, 4795857 -silesia, uncompressed literals, advanced streaming, 5120566 +silesia, uncompressed literals, advanced streaming, 5116957 silesia, uncompressed literals optimal, advanced streaming, 4316880 silesia, huffman literals, advanced streaming, 5321370 -silesia, multithreaded with advanced params, advanced streaming, 5120566 +silesia, multithreaded with advanced params, advanced streaming, 5116957 silesia.tar, level -5, advanced streaming, 6856523 silesia.tar, level -3, advanced streaming, 6505954 silesia.tar, level -1, advanced streaming, 6179056 -silesia.tar, level 0, advanced streaming, 4859271 +silesia.tar, level 0, advanced streaming, 4858632 silesia.tar, level 1, advanced streaming, 5327708 -silesia.tar, level 3, advanced streaming, 4859271 -silesia.tar, level 4, advanced streaming, 4797470 +silesia.tar, level 3, advanced streaming, 4858632 +silesia.tar, level 4, advanced streaming, 4796895 silesia.tar, level 5 row 1, advanced streaming, 4679020 silesia.tar, level 5 row 2, advanced streaming, 4682355 silesia.tar, level 5, advanced streaming, 4679020 @@ -920,28 +920,28 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced streaming, 4502956 silesia.tar, level 16, advanced streaming, 4360385 silesia.tar, level 19, advanced streaming, 4260939 -silesia.tar, no source size, advanced streaming, 4859267 -silesia.tar, long distance mode, advanced streaming, 4840452 -silesia.tar, multithreaded, advanced streaming, 4854160 -silesia.tar, multithreaded long distance mode, advanced streaming, 4845741 -silesia.tar, small window log, advanced streaming, 7117559 +silesia.tar, no source size, advanced streaming, 4858628 +silesia.tar, long distance mode, advanced streaming, 4837775 +silesia.tar, multithreaded, advanced streaming, 4851478 +silesia.tar, multithreaded long distance mode, advanced streaming, 4843155 +silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529209 silesia.tar, small chain log, advanced streaming, 4917021 silesia.tar, explicit params, advanced streaming, 4807288 -silesia.tar, uncompressed literals, advanced streaming, 5127423 +silesia.tar, uncompressed literals, advanced streaming, 5126542 silesia.tar, uncompressed literals optimal, advanced streaming, 4308451 silesia.tar, huffman literals, advanced streaming, 5341712 -silesia.tar, multithreaded with advanced params, advanced streaming, 5122567 +silesia.tar, multithreaded with advanced params, advanced streaming, 5118940 github, level -5, advanced streaming, 204407 github, level -5 with dict, advanced streaming, 45832 github, level -3, advanced streaming, 193253 github, level -3 with dict, advanced streaming, 44671 github, level -1, advanced streaming, 175468 github, level -1 with dict, advanced streaming, 41825 -github, level 0, advanced streaming, 136332 -github, level 0 with dict, advanced streaming, 41148 -github, level 0 with dict dms, advanced streaming, 41148 -github, level 0 with dict dds, advanced streaming, 41148 +github, level 0, advanced streaming, 136331 +github, level 0 with dict, advanced streaming, 41118 +github, level 0 with dict dms, advanced streaming, 41118 +github, level 0 with dict dds, advanced streaming, 41118 github, level 0 with dict copy, advanced streaming, 41124 github, level 0 with dict load, advanced streaming, 41847 github, level 1, advanced streaming, 142365 @@ -950,16 +950,16 @@ github, level 1 with dict dms, advanced github, level 1 with dict dds, advanced streaming, 41266 github, level 1 with dict copy, advanced streaming, 41279 github, level 1 with dict load, advanced streaming, 43331 -github, level 3, advanced streaming, 136332 -github, level 3 with dict, advanced streaming, 41148 -github, level 3 with dict dms, advanced streaming, 41148 -github, level 3 with dict dds, advanced streaming, 41148 +github, level 3, advanced streaming, 136331 +github, level 3 with dict, advanced streaming, 41118 +github, level 3 with dict dms, advanced streaming, 41118 +github, level 3 with dict dds, advanced streaming, 41118 github, level 3 with dict copy, advanced streaming, 41124 github, level 3 with dict load, advanced streaming, 41847 github, level 4, advanced streaming, 136199 -github, level 4 with dict, advanced streaming, 41251 -github, level 4 with dict dms, advanced streaming, 41251 -github, level 4 with dict dds, advanced streaming, 41251 +github, level 4 with dict, advanced streaming, 41229 +github, level 4 with dict dms, advanced streaming, 41229 +github, level 4 with dict dds, advanced streaming, 41229 github, level 4 with dict copy, advanced streaming, 41216 github, level 4 with dict load, advanced streaming, 41548 github, level 5 row 1, advanced streaming, 134584 @@ -1044,29 +1044,29 @@ github, level 19 with dict dms, advanced github, level 19 with dict dds, advanced streaming, 37916 github, level 19 with dict copy, advanced streaming, 37906 github, level 19 with dict load, advanced streaming, 39770 -github, no source size, advanced streaming, 136332 -github, no source size with dict, advanced streaming, 41148 -github, long distance mode, advanced streaming, 136332 -github, multithreaded, advanced streaming, 136332 -github, multithreaded long distance mode, advanced streaming, 136332 -github, small window log, advanced streaming, 136332 +github, no source size, advanced streaming, 136331 +github, no source size with dict, advanced streaming, 41118 +github, long distance mode, advanced streaming, 136331 +github, multithreaded, advanced streaming, 136331 +github, multithreaded long distance mode, advanced streaming, 136331 +github, small window log, advanced streaming, 136331 github, small hash log, advanced streaming, 135590 github, small chain log, advanced streaming, 136341 github, explicit params, advanced streaming, 137727 -github, uncompressed literals, advanced streaming, 165911 +github, uncompressed literals, advanced streaming, 165909 github, uncompressed literals optimal, advanced streaming, 152667 github, huffman literals, advanced streaming, 142365 -github, multithreaded with advanced params, advanced streaming, 165911 +github, multithreaded with advanced params, advanced streaming, 165909 github.tar, level -5, advanced streaming, 52152 github.tar, level -5 with dict, advanced streaming, 51181 github.tar, level -3, advanced streaming, 45678 github.tar, level -3 with dict, advanced streaming, 44734 github.tar, level -1, advanced streaming, 42560 github.tar, level -1 with dict, advanced streaming, 41353 -github.tar, level 0, advanced streaming, 38831 +github.tar, level 0, advanced streaming, 38884 github.tar, level 0 with dict, advanced streaming, 37995 -github.tar, level 0 with dict dms, advanced streaming, 38003 -github.tar, level 0 with dict dds, advanced streaming, 38003 +github.tar, level 0 with dict dms, advanced streaming, 38114 +github.tar, level 0 with dict dds, advanced streaming, 38114 github.tar, level 0 with dict copy, advanced streaming, 37995 github.tar, level 0 with dict load, advanced streaming, 37956 github.tar, level 1, advanced streaming, 39200 @@ -1075,16 +1075,16 @@ github.tar, level 1 with dict dms, advanced github.tar, level 1 with dict dds, advanced streaming, 38406 github.tar, level 1 with dict copy, advanced streaming, 38119 github.tar, level 1 with dict load, advanced streaming, 38364 -github.tar, level 3, advanced streaming, 38831 +github.tar, level 3, advanced streaming, 38884 github.tar, level 3 with dict, advanced streaming, 37995 -github.tar, level 3 with dict dms, advanced streaming, 38003 -github.tar, level 3 with dict dds, advanced streaming, 38003 +github.tar, level 3 with dict dms, advanced streaming, 38114 +github.tar, level 3 with dict dds, advanced streaming, 38114 github.tar, level 3 with dict copy, advanced streaming, 37995 github.tar, level 3 with dict load, advanced streaming, 37956 -github.tar, level 4, advanced streaming, 38893 +github.tar, level 4, advanced streaming, 38880 github.tar, level 4 with dict, advanced streaming, 37948 -github.tar, level 4 with dict dms, advanced streaming, 37954 -github.tar, level 4 with dict dds, advanced streaming, 37954 +github.tar, level 4 with dict dms, advanced streaming, 37995 +github.tar, level 4 with dict dds, advanced streaming, 37995 github.tar, level 4 with dict copy, advanced streaming, 37948 github.tar, level 4 with dict load, advanced streaming, 37927 github.tar, level 5 row 1, advanced streaming, 39651 @@ -1169,26 +1169,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced streaming, 32565 github.tar, level 19 with dict copy, advanced streaming, 32701 github.tar, level 19 with dict load, advanced streaming, 32428 -github.tar, no source size, advanced streaming, 38828 -github.tar, no source size with dict, advanced streaming, 38000 -github.tar, long distance mode, advanced streaming, 40252 -github.tar, multithreaded, advanced streaming, 38831 -github.tar, multithreaded long distance mode, advanced streaming, 40232 -github.tar, small window log, advanced streaming, 199558 +github.tar, no source size, advanced streaming, 38881 +github.tar, no source size with dict, advanced streaming, 38111 +github.tar, long distance mode, advanced streaming, 40242 +github.tar, multithreaded, advanced streaming, 38884 +github.tar, multithreaded long distance mode, advanced streaming, 40223 +github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 github.tar, explicit params, advanced streaming, 41385 -github.tar, uncompressed literals, advanced streaming, 41525 +github.tar, uncompressed literals, advanced streaming, 41562 github.tar, uncompressed literals optimal, advanced streaming, 35356 github.tar, huffman literals, advanced streaming, 38853 -github.tar, multithreaded with advanced params, advanced streaming, 41525 +github.tar, multithreaded with advanced params, advanced streaming, 41562 silesia, level -5, old streaming, 6854744 silesia, level -3, old streaming, 6503319 silesia, level -1, old streaming, 6172207 -silesia, level 0, old streaming, 4842075 +silesia, level 0, old streaming, 4839431 silesia, level 1, old streaming, 5306388 -silesia, level 3, old streaming, 4842075 -silesia, level 4, old streaming, 4779186 +silesia, level 3, old streaming, 4839431 +silesia, level 4, old streaming, 4776557 silesia, level 5, old streaming, 4667668 silesia, level 6, old streaming, 4604351 silesia, level 7, old streaming, 4570271 @@ -1196,17 +1196,17 @@ silesia, level 9, old stre silesia, level 13, old streaming, 4493990 silesia, level 16, old streaming, 4359652 silesia, level 19, old streaming, 4266582 -silesia, no source size, old streaming, 4842039 -silesia, uncompressed literals, old streaming, 4842075 +silesia, no source size, old streaming, 4839395 +silesia, uncompressed literals, old streaming, 4839431 silesia, uncompressed literals optimal, old streaming, 4266582 silesia, huffman literals, old streaming, 6172207 silesia.tar, level -5, old streaming, 6856523 silesia.tar, level -3, old streaming, 6505954 silesia.tar, level -1, old streaming, 6179056 -silesia.tar, level 0, old streaming, 4859271 +silesia.tar, level 0, old streaming, 4858632 silesia.tar, level 1, old streaming, 5327708 -silesia.tar, level 3, old streaming, 4859271 -silesia.tar, level 4, old streaming, 4797470 +silesia.tar, level 3, old streaming, 4858632 +silesia.tar, level 4, old streaming, 4796895 silesia.tar, level 5, old streaming, 4679020 silesia.tar, level 6, old streaming, 4614558 silesia.tar, level 7, old streaming, 4579823 @@ -1214,8 +1214,8 @@ silesia.tar, level 9, old stre silesia.tar, level 13, old streaming, 4502956 silesia.tar, level 16, old streaming, 4360385 silesia.tar, level 19, old streaming, 4260939 -silesia.tar, no source size, old streaming, 4859267 -silesia.tar, uncompressed literals, old streaming, 4859271 +silesia.tar, no source size, old streaming, 4858628 +silesia.tar, uncompressed literals, old streaming, 4858632 silesia.tar, uncompressed literals optimal, old streaming, 4260939 silesia.tar, huffman literals, old streaming, 6179056 github, level -5, old streaming, 204407 @@ -1224,14 +1224,14 @@ github, level -3, old stre github, level -3 with dict, old streaming, 44671 github, level -1, old streaming, 175468 github, level -1 with dict, old streaming, 41825 -github, level 0, old streaming, 136332 -github, level 0 with dict, old streaming, 41148 +github, level 0, old streaming, 136331 +github, level 0 with dict, old streaming, 41118 github, level 1, old streaming, 142365 github, level 1 with dict, old streaming, 41266 -github, level 3, old streaming, 136332 -github, level 3 with dict, old streaming, 41148 +github, level 3, old streaming, 136331 +github, level 3 with dict, old streaming, 41118 github, level 4, old streaming, 136199 -github, level 4 with dict, old streaming, 41251 +github, level 4 with dict, old streaming, 41229 github, level 5, old streaming, 135121 github, level 5 with dict, old streaming, 38754 github, level 6, old streaming, 135122 @@ -1247,8 +1247,8 @@ github, level 16 with dict, old stre github, level 19, old streaming, 132879 github, level 19 with dict, old streaming, 37916 github, no source size, old streaming, 140599 -github, no source size with dict, old streaming, 40654 -github, uncompressed literals, old streaming, 136332 +github, no source size with dict, old streaming, 40652 +github, uncompressed literals, old streaming, 136331 github, uncompressed literals optimal, old streaming, 132879 github, huffman literals, old streaming, 175468 github.tar, level -5, old streaming, 52152 @@ -1257,13 +1257,13 @@ github.tar, level -3, old stre github.tar, level -3 with dict, old streaming, 44734 github.tar, level -1, old streaming, 42560 github.tar, level -1 with dict, old streaming, 41353 -github.tar, level 0, old streaming, 38831 +github.tar, level 0, old streaming, 38884 github.tar, level 0 with dict, old streaming, 37995 github.tar, level 1, old streaming, 39200 github.tar, level 1 with dict, old streaming, 38119 -github.tar, level 3, old streaming, 38831 +github.tar, level 3, old streaming, 38884 github.tar, level 3 with dict, old streaming, 37995 -github.tar, level 4, old streaming, 38893 +github.tar, level 4, old streaming, 38880 github.tar, level 4 with dict, old streaming, 37948 github.tar, level 5, old streaming, 39651 github.tar, level 5 with dict, old streaming, 39145 @@ -1279,18 +1279,18 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming, 33375 github.tar, level 19, old streaming, 32262 github.tar, level 19 with dict, old streaming, 32701 -github.tar, no source size, old streaming, 38828 -github.tar, no source size with dict, old streaming, 38000 -github.tar, uncompressed literals, old streaming, 38831 +github.tar, no source size, old streaming, 38881 +github.tar, no source size with dict, old streaming, 38111 +github.tar, uncompressed literals, old streaming, 38884 github.tar, uncompressed literals optimal, old streaming, 32262 github.tar, huffman literals, old streaming, 42560 silesia, level -5, old streaming advanced, 6854744 silesia, level -3, old streaming advanced, 6503319 silesia, level -1, old streaming advanced, 6172207 -silesia, level 0, old streaming advanced, 4842075 +silesia, level 0, old streaming advanced, 4839431 silesia, level 1, old streaming advanced, 5306388 -silesia, level 3, old streaming advanced, 4842075 -silesia, level 4, old streaming advanced, 4779186 +silesia, level 3, old streaming advanced, 4839431 +silesia, level 4, old streaming advanced, 4776557 silesia, level 5, old streaming advanced, 4667668 silesia, level 6, old streaming advanced, 4604351 silesia, level 7, old streaming advanced, 4570271 @@ -1298,25 +1298,25 @@ silesia, level 9, old stre silesia, level 13, old streaming advanced, 4493990 silesia, level 16, old streaming advanced, 4359652 silesia, level 19, old streaming advanced, 4266582 -silesia, no source size, old streaming advanced, 4842039 -silesia, long distance mode, old streaming advanced, 4842075 -silesia, multithreaded, old streaming advanced, 4842075 -silesia, multithreaded long distance mode, old streaming advanced, 4842075 -silesia, small window log, old streaming advanced, 7111103 +silesia, no source size, old streaming advanced, 4839395 +silesia, long distance mode, old streaming advanced, 4839431 +silesia, multithreaded, old streaming advanced, 4839431 +silesia, multithreaded long distance mode, old streaming advanced, 4839431 +silesia, small window log, old streaming advanced, 7110591 silesia, small hash log, old streaming advanced, 6526141 silesia, small chain log, old streaming advanced, 4912197 silesia, explicit params, old streaming advanced, 4795857 -silesia, uncompressed literals, old streaming advanced, 4842075 +silesia, uncompressed literals, old streaming advanced, 4839431 silesia, uncompressed literals optimal, old streaming advanced, 4266582 silesia, huffman literals, old streaming advanced, 6172207 -silesia, multithreaded with advanced params, old streaming advanced, 4842075 +silesia, multithreaded with advanced params, old streaming advanced, 4839431 silesia.tar, level -5, old streaming advanced, 6856523 silesia.tar, level -3, old streaming advanced, 6505954 silesia.tar, level -1, old streaming advanced, 6179056 -silesia.tar, level 0, old streaming advanced, 4859271 +silesia.tar, level 0, old streaming advanced, 4858632 silesia.tar, level 1, old streaming advanced, 5327708 -silesia.tar, level 3, old streaming advanced, 4859271 -silesia.tar, level 4, old streaming advanced, 4797470 +silesia.tar, level 3, old streaming advanced, 4858632 +silesia.tar, level 4, old streaming advanced, 4796895 silesia.tar, level 5, old streaming advanced, 4679020 silesia.tar, level 6, old streaming advanced, 4614558 silesia.tar, level 7, old streaming advanced, 4579823 @@ -1324,32 +1324,32 @@ silesia.tar, level 9, old stre silesia.tar, level 13, old streaming advanced, 4502956 silesia.tar, level 16, old streaming advanced, 4360385 silesia.tar, level 19, old streaming advanced, 4260939 -silesia.tar, no source size, old streaming advanced, 4859267 -silesia.tar, long distance mode, old streaming advanced, 4859271 -silesia.tar, multithreaded, old streaming advanced, 4859271 -silesia.tar, multithreaded long distance mode, old streaming advanced, 4859271 -silesia.tar, small window log, old streaming advanced, 7117562 +silesia.tar, no source size, old streaming advanced, 4858628 +silesia.tar, long distance mode, old streaming advanced, 4858632 +silesia.tar, multithreaded, old streaming advanced, 4858632 +silesia.tar, multithreaded long distance mode, old streaming advanced, 4858632 +silesia.tar, small window log, old streaming advanced, 7117027 silesia.tar, small hash log, old streaming advanced, 6529209 silesia.tar, small chain log, old streaming advanced, 4917021 silesia.tar, explicit params, old streaming advanced, 4807288 -silesia.tar, uncompressed literals, old streaming advanced, 4859271 +silesia.tar, uncompressed literals, old streaming advanced, 4858632 silesia.tar, uncompressed literals optimal, old streaming advanced, 4260939 silesia.tar, huffman literals, old streaming advanced, 6179056 -silesia.tar, multithreaded with advanced params, old streaming advanced, 4859271 +silesia.tar, multithreaded with advanced params, old streaming advanced, 4858632 github, level -5, old streaming advanced, 213265 github, level -5 with dict, old streaming advanced, 46708 github, level -3, old streaming advanced, 196126 github, level -3 with dict, old streaming advanced, 45476 github, level -1, old streaming advanced, 181107 github, level -1 with dict, old streaming advanced, 42060 -github, level 0, old streaming advanced, 141104 -github, level 0 with dict, old streaming advanced, 41113 +github, level 0, old streaming advanced, 141101 +github, level 0 with dict, old streaming advanced, 41074 github, level 1, old streaming advanced, 143693 github, level 1 with dict, old streaming advanced, 42430 -github, level 3, old streaming advanced, 141104 -github, level 3 with dict, old streaming advanced, 41113 -github, level 4, old streaming advanced, 141104 -github, level 4 with dict, old streaming advanced, 41084 +github, level 3, old streaming advanced, 141101 +github, level 3 with dict, old streaming advanced, 41074 +github, level 4, old streaming advanced, 141101 +github, level 4 with dict, old streaming advanced, 41046 github, level 5, old streaming advanced, 139402 github, level 5 with dict, old streaming advanced, 38723 github, level 6, old streaming advanced, 138676 @@ -1366,30 +1366,30 @@ github, level 19, old stre github, level 19 with dict, old streaming advanced, 37916 github, no source size, old streaming advanced, 140599 github, no source size with dict, old streaming advanced, 40608 -github, long distance mode, old streaming advanced, 141104 -github, multithreaded, old streaming advanced, 141104 -github, multithreaded long distance mode, old streaming advanced, 141104 -github, small window log, old streaming advanced, 141104 +github, long distance mode, old streaming advanced, 141101 +github, multithreaded, old streaming advanced, 141101 +github, multithreaded long distance mode, old streaming advanced, 141101 +github, small window log, old streaming advanced, 141101 github, small hash log, old streaming advanced, 141597 github, small chain log, old streaming advanced, 139275 github, explicit params, old streaming advanced, 140937 -github, uncompressed literals, old streaming advanced, 141104 +github, uncompressed literals, old streaming advanced, 141101 github, uncompressed literals optimal, old streaming advanced, 132879 github, huffman literals, old streaming advanced, 181107 -github, multithreaded with advanced params, old streaming advanced, 141104 +github, multithreaded with advanced params, old streaming advanced, 141101 github.tar, level -5, old streaming advanced, 52152 github.tar, level -5 with dict, old streaming advanced, 51129 github.tar, level -3, old streaming advanced, 45678 github.tar, level -3 with dict, old streaming advanced, 44986 github.tar, level -1, old streaming advanced, 42560 github.tar, level -1 with dict, old streaming advanced, 41650 -github.tar, level 0, old streaming advanced, 38831 +github.tar, level 0, old streaming advanced, 38884 github.tar, level 0 with dict, old streaming advanced, 38013 github.tar, level 1, old streaming advanced, 39200 github.tar, level 1 with dict, old streaming advanced, 38359 -github.tar, level 3, old streaming advanced, 38831 +github.tar, level 3, old streaming advanced, 38884 github.tar, level 3 with dict, old streaming advanced, 38013 -github.tar, level 4, old streaming advanced, 38893 +github.tar, level 4, old streaming advanced, 38880 github.tar, level 4 with dict, old streaming advanced, 38063 github.tar, level 5, old streaming advanced, 39651 github.tar, level 5 with dict, old streaming advanced, 39018 @@ -1405,26 +1405,26 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming advanced, 38578 github.tar, level 19, old streaming advanced, 32262 github.tar, level 19 with dict, old streaming advanced, 32678 -github.tar, no source size, old streaming advanced, 38828 -github.tar, no source size with dict, old streaming advanced, 38015 -github.tar, long distance mode, old streaming advanced, 38831 -github.tar, multithreaded, old streaming advanced, 38831 -github.tar, multithreaded long distance mode, old streaming advanced, 38831 -github.tar, small window log, old streaming advanced, 199561 +github.tar, no source size, old streaming advanced, 38881 +github.tar, no source size with dict, old streaming advanced, 38076 +github.tar, long distance mode, old streaming advanced, 38884 +github.tar, multithreaded, old streaming advanced, 38884 +github.tar, multithreaded long distance mode, old streaming advanced, 38884 +github.tar, small window log, old streaming advanced, 199556 github.tar, small hash log, old streaming advanced, 129870 github.tar, small chain log, old streaming advanced, 41669 github.tar, explicit params, old streaming advanced, 41385 -github.tar, uncompressed literals, old streaming advanced, 38831 +github.tar, uncompressed literals, old streaming advanced, 38884 github.tar, uncompressed literals optimal, old streaming advanced, 32262 github.tar, huffman literals, old streaming advanced, 42560 -github.tar, multithreaded with advanced params, old streaming advanced, 38831 +github.tar, multithreaded with advanced params, old streaming advanced, 38884 github, level -5 with dict, old streaming cdict, 45832 github, level -3 with dict, old streaming cdict, 44671 github, level -1 with dict, old streaming cdict, 41825 -github, level 0 with dict, old streaming cdict, 41148 +github, level 0 with dict, old streaming cdict, 41118 github, level 1 with dict, old streaming cdict, 41266 -github, level 3 with dict, old streaming cdict, 41148 -github, level 4 with dict, old streaming cdict, 41251 +github, level 3 with dict, old streaming cdict, 41118 +github, level 4 with dict, old streaming cdict, 41229 github, level 5 with dict, old streaming cdict, 38754 github, level 6 with dict, old streaming cdict, 38669 github, level 7 with dict, old streaming cdict, 38765 @@ -1432,7 +1432,7 @@ github, level 9 with dict, old stre github, level 13 with dict, old streaming cdict, 39900 github, level 16 with dict, old streaming cdict, 37902 github, level 19 with dict, old streaming cdict, 37916 -github, no source size with dict, old streaming cdict, 40654 +github, no source size with dict, old streaming cdict, 40652 github.tar, level -5 with dict, old streaming cdict, 51286 github.tar, level -3 with dict, old streaming cdict, 45147 github.tar, level -1 with dict, old streaming cdict, 41865 @@ -1447,14 +1447,14 @@ github.tar, level 9 with dict, old stre github.tar, level 13 with dict, old streaming cdict, 36010 github.tar, level 16 with dict, old streaming cdict, 39081 github.tar, level 19 with dict, old streaming cdict, 32428 -github.tar, no source size with dict, old streaming cdict, 38000 +github.tar, no source size with dict, old streaming cdict, 38111 github, level -5 with dict, old streaming advanced cdict, 46708 github, level -3 with dict, old streaming advanced cdict, 45476 github, level -1 with dict, old streaming advanced cdict, 42060 -github, level 0 with dict, old streaming advanced cdict, 41113 +github, level 0 with dict, old streaming advanced cdict, 41074 github, level 1 with dict, old streaming advanced cdict, 42430 -github, level 3 with dict, old streaming advanced cdict, 41113 -github, level 4 with dict, old streaming advanced cdict, 41084 +github, level 3 with dict, old streaming advanced cdict, 41074 +github, level 4 with dict, old streaming advanced cdict, 41046 github, level 5 with dict, old streaming advanced cdict, 38723 github, level 6 with dict, old streaming advanced cdict, 38744 github, level 7 with dict, old streaming advanced cdict, 38875 @@ -1477,4 +1477,4 @@ github.tar, level 9 with dict, old stre github.tar, level 13 with dict, old streaming advanced cdict, 35807 github.tar, level 16 with dict, old streaming advanced cdict, 38578 github.tar, level 19 with dict, old streaming advanced cdict, 32678 -github.tar, no source size with dict, old streaming advanced cdict, 38015 +github.tar, no source size with dict, old streaming advanced cdict, 38076 From 0079d515b1673a7deba3dfa46204a1af61d81dce Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 02:18:48 -0700 Subject: [PATCH 386/937] Modify benchmark to only load sources once After a regrettable update, the benchmark module ended up reloading sources for every compression level. While the delay itself is likely torelable, the main issue is that the `--quiet` mode now also displays a loading summary between each compression line. This wasn't the original intention, which is to produce a compact view of all compressions. This is fixed in this version, where sources are loaded only once, for all compression levels, and loading summary is only displayed once. --- programs/benchzstd.c | 87 +++++++++++++++++++++++--------------------- programs/benchzstd.h | 10 +++-- programs/zstdcli.c | 16 +++----- 3 files changed, 57 insertions(+), 56 deletions(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index 0a1cba9e6..5ea7bb72e 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -928,12 +928,13 @@ BMK_benchOutcome_t BMK_benchMem( &adv); } -static BMK_benchOutcome_t BMK_benchCLevel( +/* @return: 0 on success, !0 if error */ +static int BMK_benchCLevels( const void* srcBuffer, size_t benchedSize, const size_t* fileSizes, unsigned nbFiles, - int cLevel, + int startCLevel, int endCLevel, const ZSTD_compressionParameters* comprParams, const void* dictBuffer, size_t dictBufferSize, @@ -941,12 +942,22 @@ static BMK_benchOutcome_t BMK_benchCLevel( const char* displayName, BMK_advancedParams_t const* const adv) { + int level; const char* pch = strrchr(displayName, '\\'); /* Windows */ if (!pch) pch = strrchr(displayName, '/'); /* Linux */ if (pch) displayName = pch + 1; + if (endCLevel > ZSTD_maxCLevel()) { + DISPLAYLEVEL(1, "Invalid Compression Level \n"); + return 15; + } + if (endCLevel < startCLevel) { + DISPLAYLEVEL(1, "Invalid Compression Level Range \n"); + return 15; + } + if (adv->realTime) { DISPLAYLEVEL(2, "Note : switching to real-time priority \n"); SET_REALTIME_PRIORITY; @@ -960,25 +971,29 @@ static BMK_benchOutcome_t BMK_benchCLevel( adv->nbSeconds, (unsigned)(adv->blockSize >> 10)); - return BMK_benchMemAdvanced( + for (level = startCLevel; level <= endCLevel; level++) { + BMK_benchOutcome_t res = BMK_benchMemAdvanced( srcBuffer, benchedSize, NULL, 0, fileSizes, nbFiles, - cLevel, + level, comprParams, dictBuffer, dictBufferSize, displayLevel, displayName, adv); + if (!BMK_isSuccessful_benchOutcome(res)) return 1; + } + return 0; } int BMK_syntheticTest( - int cLevel, double compressibility, + int startingCLevel, int endCLevel, const ZSTD_compressionParameters* compressionParams, int displayLevel, const BMK_advancedParams_t* adv) @@ -986,18 +1001,11 @@ int BMK_syntheticTest( char nameBuff[20] = { 0 }; const char* name = nameBuff; size_t const benchedSize = adv->blockSize ? adv->blockSize : 10000000; - void* srcBuffer; - BMK_benchOutcome_t res; - - if (cLevel > ZSTD_maxCLevel()) { - DISPLAYLEVEL(1, "Invalid Compression Level"); - return 15; - } /* Memory allocation */ - srcBuffer = malloc(benchedSize); + void* const srcBuffer = malloc(benchedSize); if (!srcBuffer) { - DISPLAYLEVEL(1, "allocation error : not enough memory"); + DISPLAYLEVEL(1, "allocation error : not enough memory \n"); return 16; } @@ -1015,23 +1023,21 @@ int BMK_syntheticTest( } /* Bench */ - res = BMK_benchCLevel( - srcBuffer, - benchedSize, - &benchedSize /* ? */, - 1 /* ? */, - cLevel, - compressionParams, - NULL, - 0, /* dictionary */ - displayLevel, - name, - adv); - - /* clean up */ - free(srcBuffer); - - return !BMK_isSuccessful_benchOutcome(res); + { int res = BMK_benchCLevels( + srcBuffer, + benchedSize, + &benchedSize, + 1, + startingCLevel, endCLevel, + compressionParams, + NULL, + 0, /* dictionary */ + displayLevel, + name, + adv); + free(srcBuffer); + return res; + } } static size_t BMK_findMaxMem(U64 requiredMem) @@ -1120,7 +1126,7 @@ int BMK_benchFilesAdvanced( const char* const* fileNamesTable, unsigned nbFiles, const char* dictFileName, - int cLevel, + int startCLevel, int endCLevel, const ZSTD_compressionParameters* compressionParams, int displayLevel, const BMK_advancedParams_t* adv) @@ -1130,7 +1136,7 @@ int BMK_benchFilesAdvanced( void* dictBuffer = NULL; size_t dictBufferSize = 0; size_t* fileSizes = NULL; - BMK_benchOutcome_t res; + int res = 1; U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles); if (!nbFiles) { @@ -1138,7 +1144,7 @@ int BMK_benchFilesAdvanced( return 13; } - if (cLevel > ZSTD_maxCLevel()) { + if (endCLevel > ZSTD_maxCLevel()) { DISPLAYLEVEL(1, "Invalid Compression Level"); return 14; } @@ -1192,7 +1198,6 @@ int BMK_benchFilesAdvanced( 1 /*?*/, displayLevel); if (errorCode) { - res = BMK_benchOutcome_error(); goto _cleanUp; } } @@ -1224,7 +1229,6 @@ int BMK_benchFilesAdvanced( nbFiles, displayLevel); if (errorCode) { - res = BMK_benchOutcome_error(); goto _cleanUp; } } @@ -1233,15 +1237,14 @@ int BMK_benchFilesAdvanced( { char mfName[20] = { 0 }; formatString_u(mfName, sizeof(mfName), " %u files", nbFiles); - { - const char* const displayName = + { const char* const displayName = (nbFiles > 1) ? mfName : fileNamesTable[0]; - res = BMK_benchCLevel( + res = BMK_benchCLevels( srcBuffer, benchedSize, fileSizes, nbFiles, - cLevel, + startCLevel, endCLevel, compressionParams, dictBuffer, dictBufferSize, @@ -1255,7 +1258,7 @@ _cleanUp: free(srcBuffer); free(dictBuffer); free(fileSizes); - return !BMK_isSuccessful_benchOutcome(res); + return res; } int BMK_benchFiles( @@ -1271,7 +1274,7 @@ int BMK_benchFiles( fileNamesTable, nbFiles, dictFileName, - cLevel, + cLevel, cLevel, compressionParams, displayLevel, &adv); diff --git a/programs/benchzstd.h b/programs/benchzstd.h index ad3088cd4..6388d4d58 100644 --- a/programs/benchzstd.h +++ b/programs/benchzstd.h @@ -122,12 +122,13 @@ BMK_advancedParams_t BMK_initAdvancedParams(void); int BMK_benchFilesAdvanced( const char* const * fileNamesTable, unsigned nbFiles, const char* dictFileName, - int cLevel, const ZSTD_compressionParameters* compressionParams, + int startCLevel, int endCLevel, + const ZSTD_compressionParameters* compressionParams, int displayLevel, const BMK_advancedParams_t* adv); /*! BMK_syntheticTest() -- called from zstdcli */ -/* Generates a sample with datagen, using compressibility argument */ -/* @cLevel - compression level to benchmark, errors if invalid +/* Generates a sample with datagen, using @compressibility argument + * @cLevel - compression level to benchmark, errors if invalid * @compressibility - determines compressibility of sample, range [0.0 - 1.0] * if @compressibility < 0.0, uses the lorem ipsum generator * @compressionParams - basic compression Parameters @@ -135,7 +136,8 @@ int BMK_benchFilesAdvanced( * @adv - see advanced_Params_t * @return: 0 on success, !0 on error */ -int BMK_syntheticTest(int cLevel, double compressibility, +int BMK_syntheticTest(double compressibility, + int startingCLevel, int endCLevel, const ZSTD_compressionParameters* compressionParams, int displayLevel, const BMK_advancedParams_t* adv); diff --git a/programs/zstdcli.c b/programs/zstdcli.c index d8e908d85..438e9c970 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1400,19 +1400,15 @@ int main(int argCount, const char* argv[]) if(separateFiles) { unsigned i; for(i = 0; i < filenames->tableSize; i++) { - int c; DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]); - for(c = cLevel; c <= cLevelLast; c++) { - operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, c, &compressionParams, g_displayLevel, &benchParams); - } } + operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams); + } } else { - for(; cLevel <= cLevelLast; cLevel++) { - operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, &compressionParams, g_displayLevel, &benchParams); - } } + operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams); + } } else { - for(; cLevel <= cLevelLast; cLevel++) { - operationResult = BMK_syntheticTest(cLevel, compressibility, &compressionParams, g_displayLevel, &benchParams); - } } + operationResult = BMK_syntheticTest(compressibility, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams); + } #else (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility; From f34bc9cee63759a85011db66e5cb9187c88ea843 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 23:53:56 -0700 Subject: [PATCH 387/937] improve man page on benchmark mode update the man page in troff format, and the README with latest `--help` content and complementary details about benchmark mode. also: display level 0 when doing decompression benchmark --- programs/README.md | 178 +++++++++++++++++++------------ programs/zstd.1 | 260 ++++++++------------------------------------- programs/zstd.1.md | 11 +- programs/zstdcli.c | 1 + 4 files changed, 162 insertions(+), 288 deletions(-) diff --git a/programs/README.md b/programs/README.md index 1b9f47cbb..43ef07a45 100644 --- a/programs/README.md +++ b/programs/README.md @@ -129,89 +129,131 @@ CLI includes in-memory compression benchmark module for zstd. The benchmark is conducted using given filenames. The files are read into memory and joined together. It makes benchmark more precise as it eliminates I/O overhead. Multiple filenames can be supplied, as multiple parameters, with wildcards, -or names of directories can be used as parameters with `-r` option. +or directory names can be used with `-r` option. +If no file is provided, the benchmark will use a procedurally generated "lorem ipsum" content. The benchmark measures ratio, compressed size, compression and decompression speed. One can select compression levels starting from `-b` and ending with `-e`. The `-i` parameter selects minimal time used for each of tested levels. +The benchmark can also be used to test specific parameters, +such as number of threads (`-T#`), or advanced parameters (`--zstd=#`), or dictionary compression (`-D DICTIONARY`), +and many others available on command for regular compression and decompression. + ### Usage of Command Line Interface The full list of options can be obtained with `-h` or `-H` parameter: ``` -Usage : - zstd [args] [FILE(s)] [-o file] +*** Zstandard CLI (64-bit) v1.5.6, by Yann Collet *** -FILE : a filename - with no FILE, or when FILE is - , read standard input -Arguments : - -# : # compression level (1-19, default: 3) - -d : decompression - -D DICT: use DICT as Dictionary for compression or decompression - -o file: result stored into `file` (only 1 output file) - -f : overwrite output without prompting, also (de)compress links ---rm : remove source file(s) after successful de/compression - -k : preserve source file(s) (default) - -h/-H : display help/long help and exit +Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided. -Advanced arguments : - -V : display Version number and exit - -c : write to standard output (even if it is the console) - -v : verbose mode; specify multiple times to increase verbosity - -q : suppress warnings; specify twice to suppress errors too ---no-progress : do not display the progress counter - -r : operate recursively on directories ---filelist FILE : read list of files to operate upon from FILE ---output-dir-flat DIR : processed files are stored into DIR ---output-dir-mirror DIR : processed files are stored into DIR respecting original directory structure ---[no-]asyncio : use asynchronous IO (default: enabled) ---[no-]check : during compression, add XXH64 integrity checksum to frame (default: enabled). If specified with -d, decompressor will ignore/validate checksums in compressed frame (default: validate). --- : All arguments after "--" are treated as files +Usage: zstd [OPTIONS...] [INPUT... | -] [-o OUTPUT] -Advanced compression arguments : ---ultra : enable levels beyond 19, up to 22 (requires more memory) ---long[=#]: enable long distance matching with given window log (default: 27) ---fast[=#]: switch to very fast compression levels (default: 1) ---adapt : dynamically adapt compression level to I/O conditions ---patch-from=FILE : specify the file to be used as a reference point for zstd's diff engine - -T# : spawns # compression threads (default: 1, 0==# cores) - -B# : select size of each job (default: 0==automatic) ---single-thread : use a single thread for both I/O and compression (result slightly different than -T1) ---rsyncable : compress using a rsync-friendly method (-B sets block size) ---exclude-compressed: only compress files that are not already compressed ---stream-size=# : specify size of streaming input from `stdin` ---size-hint=# optimize compression parameters for streaming input of approximately this size ---target-compressed-block-size=# : generate compressed block of approximately targeted size ---no-dictID : don't write dictID into header (dictionary compression only) ---[no-]compress-literals : force (un)compressed literals ---format=zstd : compress files to the .zst format (default) ---format=gzip : compress files to the .gz format ---format=xz : compress files to the .xz format ---format=lzma : compress files to the .lzma format ---format=lz4 : compress files to the .lz4 format +Options: + -o OUTPUT Write output to a single file, OUTPUT. + -k, --keep Preserve INPUT file(s). [Default] + --rm Remove INPUT file(s) after successful (de)compression. -Advanced decompression arguments : - -l : print information about zstd compressed files ---test : test compressed file integrity - -M# : Set a memory usage limit for decompression ---[no-]sparse : sparse mode (default: disabled) + -# Desired compression level, where `#` is a number between 1 and 19; + lower numbers provide faster compression, higher numbers yield + better compression ratios. [Default: 3] -Dictionary builder : ---train ## : create a dictionary from a training set of files ---train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]] : use the cover algorithm with optional args ---train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]] : use the fast cover algorithm with optional args ---train-legacy[=s=#] : use the legacy algorithm with selectivity (default: 9) - -o DICT : DICT is dictionary name (default: dictionary) ---maxdict=# : limit dictionary to specified size (default: 112640) ---dictID=# : force dictionary ID to specified value (default: random) + -d, --decompress Perform decompression. + -D DICT Use DICT as the dictionary for compression or decompression. -Benchmark arguments : - -b# : benchmark file(s), using # compression level (default: 3) - -e# : test all compression levels successively from -b# to -e# (default: 1) - -i# : minimum evaluation time in seconds (default: 3s) - -B# : cut file into independent chunks of size # (default: no chunking) - -S : output one benchmark result per input file (default: consolidated result) ---priority=rt : set process priority to real-time + -f, --force Disable input and output checks. Allows overwriting existing files, + receiving input from the console, printing output to STDOUT, and + operating on links, block devices, etc. Unrecognized formats will be + passed-through through as-is. + + -h Display short usage and exit. + -H, --help Display full help and exit. + -V, --version Display the program version and exit. + +Advanced options: + -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s). + + -v, --verbose Enable verbose output; pass multiple times to increase verbosity. + -q, --quiet Suppress warnings; pass twice to suppress errors. + --trace LOG Log tracing information to LOG. + + --[no-]progress Forcibly show/hide the progress counter. NOTE: Any (de)compressed + output to terminal will mix with progress counter text. + + -r Operate recursively on directories. + --filelist LIST Read a list of files to operate on from LIST. + --output-dir-flat DIR Store processed files in DIR. + --output-dir-mirror DIR Store processed files in DIR, respecting original directory structure. + --[no-]asyncio Use asynchronous IO. [Default: Enabled] + + --[no-]check Add XXH64 integrity checksums during compression. [Default: Add, Validate] + If `-d` is present, ignore/validate checksums during decompression. + + -- Treat remaining arguments after `--` as files. + +Advanced compression options: + --ultra Enable levels beyond 19, up to 22; requires more memory. + --fast[=#] Use to very fast compression levels. [Default: 1] + --adapt Dynamically adapt compression level to I/O conditions. + --long[=#] Enable long distance matching with window log #. [Default: 27] + --patch-from=REF Use REF as the reference point for Zstandard's diff engine. + + -T# Spawn # compression threads. [Default: 1; pass 0 for core count.] + --single-thread Share a single thread for I/O and compression (slightly different than `-T1`). + --auto-threads={physical|logical} + Use physical/logical cores when using `-T0`. [Default: Physical] + + -B# Set job size to #. [Default: 0 (automatic)] + --rsyncable Compress using a rsync-friendly method (`-B` sets block size). + + --exclude-compressed Only compress files that are not already compressed. + + --stream-size=# Specify size of streaming input from STDIN. + --size-hint=# Optimize compression parameters for streaming input of approximately size #. + --target-compressed-block-size=# + Generate compressed blocks of approximately # size. + + --no-dictID Don't write `dictID` into the header (dictionary compression only). + --[no-]compress-literals Force (un)compressed literals. + --[no-]row-match-finder Explicitly enable/disable the fast, row-based matchfinder for + the 'greedy', 'lazy', and 'lazy2' strategies. + + --format=zstd Compress files to the `.zst` format. [Default] + --[no-]mmap-dict Memory-map dictionary file rather than mallocing and loading all at once + --format=gzip Compress files to the `.gz` format. + --format=xz Compress files to the `.xz` format. + --format=lzma Compress files to the `.lzma` format. + --format=lz4 Compress files to the `.lz4` format. + +Advanced decompression options: + -l Print information about Zstandard-compressed files. + --test Test compressed file integrity. + -M# Set the memory usage limit to # megabytes. + --[no-]sparse Enable sparse mode. [Default: Enabled for files, disabled for STDOUT.] + --[no-]pass-through Pass through uncompressed files as-is. [Default: Disabled] + +Dictionary builder: + --train Create a dictionary from a training set of files. + + --train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]] + Use the cover algorithm (with optional arguments). + --train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]] + Use the fast cover algorithm (with optional arguments). + + --train-legacy[=s=#] Use the legacy algorithm with selectivity #. [Default: 9] + -o NAME Use NAME as dictionary name. [Default: dictionary] + --maxdict=# Limit dictionary to specified size #. [Default: 112640] + --dictID=# Force dictionary ID to #. [Default: Random] + +Benchmark options: + -b# Perform benchmarking with compression level #. [Default: 3] + -e# Test all compression levels up to #; starting level is `-b#`. [Default: 1] + -i# Set the minimum evaluation to time # seconds. [Default: 3] + -B# Cut file into independent chunks of size #. [Default: No chunking] + -S Output one benchmark result per input file. [Default: Consolidated result] + -D dictionary Benchmark using dictionary + --priority=rt Set process priority to real-time. ``` ### Passing parameters through Environment Variables diff --git a/programs/zstd.1 b/programs/zstd.1 index 2b5a98511..5f1519f33 100644 --- a/programs/zstd.1 +++ b/programs/zstd.1 @@ -1,566 +1,392 @@ -. -.TH "ZSTD" "1" "March 2024" "zstd 1.5.6" "User Commands" -. +.TH "ZSTD" "1" "October 2024" "zstd 1.5.6" "User Commands" .SH "NAME" \fBzstd\fR \- zstd, zstdmt, unzstd, zstdcat \- Compress or decompress \.zst files -. .SH "SYNOPSIS" -\fBzstd\fR [\fIOPTIONS\fR] [\-|\fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR] -. +.TS +allbox; +\fBzstd\fR [\fIOPTIONS\fR] [\- \fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR] +.TE .P \fBzstdmt\fR is equivalent to \fBzstd \-T0\fR -. .P \fBunzstd\fR is equivalent to \fBzstd \-d\fR -. .P \fBzstdcat\fR is equivalent to \fBzstd \-dcf\fR -. .SH "DESCRIPTION" \fBzstd\fR is a fast lossless compression algorithm and data compression tool, with command line syntax similar to \fBgzip\fR(1) and \fBxz\fR(1)\. It is based on the \fBLZ77\fR family, with further FSE & huff0 entropy stages\. \fBzstd\fR offers highly configurable compression speed, from fast modes at > 200 MB/s per core, to strong modes with excellent compression ratios\. It also features a very fast decoder, with speeds > 500 MB/s per core, which remains roughly stable at all compression settings\. -. .P \fBzstd\fR command line syntax is generally similar to gzip, but features the following few differences: -. .IP "\(bu" 4 -Source files are preserved by default\. It\'s possible to remove them automatically by using the \fB\-\-rm\fR command\. -. +Source files are preserved by default\. It's possible to remove them automatically by using the \fB\-\-rm\fR command\. .IP "\(bu" 4 When compressing a single file, \fBzstd\fR displays progress notifications and result summary by default\. Use \fB\-q\fR to turn them off\. -. .IP "\(bu" 4 \fBzstd\fR displays a short help page when command line is an error\. Use \fB\-q\fR to turn it off\. -. .IP "\(bu" 4 -\fBzstd\fR does not accept input from console, though it does accept \fBstdin\fR when it\'s not the console\. -. +\fBzstd\fR does not accept input from console, though it does accept \fBstdin\fR when it's not the console\. .IP "\(bu" 4 -\fBzstd\fR does not store the input\'s filename or attributes, only its contents\. -. +\fBzstd\fR does not store the input's filename or attributes, only its contents\. .IP "" 0 -. .P \fBzstd\fR processes each \fIfile\fR according to the selected operation mode\. If no \fIfiles\fR are given or \fIfile\fR is \fB\-\fR, \fBzstd\fR reads from standard input and writes the processed data to standard output\. \fBzstd\fR will refuse to write compressed data to standard output if it is a terminal: it will display an error message and skip the file\. Similarly, \fBzstd\fR will refuse to read compressed data from standard input if it is a terminal\. -. .P Unless \fB\-\-stdout\fR or \fB\-o\fR is specified, \fIfiles\fR are written to a new file whose name is derived from the source \fIfile\fR name: -. .IP "\(bu" 4 When compressing, the suffix \fB\.zst\fR is appended to the source filename to get the target filename\. -. .IP "\(bu" 4 When decompressing, the \fB\.zst\fR suffix is removed from the source filename to get the target filename -. .IP "" 0 -. .SS "Concatenation with \.zst Files" It is possible to concatenate multiple \fB\.zst\fR files\. \fBzstd\fR will decompress such agglomerated file as if it was a single \fB\.zst\fR file\. -. .SH "OPTIONS" -. .SS "Integer Suffixes and Special Values" In most places where an integer argument is expected, an optional suffix is supported to easily indicate large integers\. There must be no space between the integer and the suffix\. -. .TP \fBKiB\fR -Multiply the integer by 1,024 (2^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\. -. +Multiply the integer by 1,024 (2\e^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\. .TP \fBMiB\fR -Multiply the integer by 1,048,576 (2^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\. -. +Multiply the integer by 1,048,576 (2\e^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\. .SS "Operation Mode" If multiple operation mode options are given, the last one takes effect\. -. .TP \fB\-z\fR, \fB\-\-compress\fR Compress\. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, \fBunzstd\fR implies \fB\-\-decompress\fR)\. -. .TP \fB\-d\fR, \fB\-\-decompress\fR, \fB\-\-uncompress\fR Decompress\. -. .TP \fB\-t\fR, \fB\-\-test\fR Test the integrity of compressed \fIfiles\fR\. This option is equivalent to \fB\-\-decompress \-\-stdout > /dev/null\fR, decompressed data is discarded and checksummed for errors\. No files are created or removed\. -. .TP \fB\-b#\fR Benchmark file(s) using compression level \fI#\fR\. See \fIBENCHMARK\fR below for a description of this operation\. -. .TP \fB\-\-train FILES\fR Use \fIFILES\fR as a training set to create a dictionary\. The training set should contain a lot of small files (> 100)\. See \fIDICTIONARY BUILDER\fR below for a description of this operation\. -. .TP \fB\-l\fR, \fB\-\-list\fR -Display information related to a zstd compressed file, such as size, ratio, and checksum\. Some of these fields may not be available\. This command\'s output can be augmented with the \fB\-v\fR modifier\. -. +Display information related to a zstd compressed file, such as size, ratio, and checksum\. Some of these fields may not be available\. This command's output can be augmented with the \fB\-v\fR modifier\. .SS "Operation Modifiers" -. .IP "\(bu" 4 -\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)\. Higher compression levels \fIgenerally\fR produce higher compression ratio at the expense of speed and memory\. A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels\. Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below)\. Because the compressor\'s behavior highly depends on the content to compress, there\'s no guarantee of a smooth progression from one level to another\. -. +\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)\. Higher compression levels \fIgenerally\fR produce higher compression ratio at the expense of speed and memory\. A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels\. Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below)\. Because the compressor's behavior highly depends on the content to compress, there's no guarantee of a smooth progression from one level to another\. .IP "\(bu" 4 \fB\-\-ultra\fR: unlocks high compression levels 20+ (maximum 22), using a lot more memory\. Note that decompression will also require more memory when using these levels\. -. .IP "\(bu" 4 \fB\-\-fast[=#]\fR: switch to ultra\-fast compression levels\. If \fB=#\fR is not present, it defaults to \fB1\fR\. The higher the value, the faster the compression speed, at the cost of some compression ratio\. This setting overwrites compression level if one was set previously\. Similarly, if a compression level is set after \fB\-\-fast\fR, it overrides it\. -. .IP "\(bu" 4 \fB\-T#\fR, \fB\-\-threads=#\fR: Compress using \fB#\fR working threads (default: 1)\. If \fB#\fR is 0, attempt to detect and use the number of physical CPU cores\. In all cases, the nb of threads is capped to \fBZSTDMT_NBWORKERS_MAX\fR, which is either 64 in 32\-bit mode, or 256 for 64\-bit environments\. This modifier does nothing if \fBzstd\fR is compiled without multithread support\. -. .IP "\(bu" 4 \fB\-\-single\-thread\fR: Use a single thread for both I/O and compression\. As compression is serialized with I/O, this can be slightly slower\. Single\-thread mode features significantly lower memory usage, which can be useful for systems with limited amount of memory, such as 32\-bit systems\. -. .IP Note 1: this mode is the only available one when multithread support is disabled\. -. .IP Note 2: this mode is different from \fB\-T1\fR, which spawns 1 compression thread in parallel with I/O\. Final compressed result is also slightly different from \fB\-T1\fR\. -. .IP "\(bu" 4 \fB\-\-auto\-threads={physical,logical} (default: physical)\fR: When using a default amount of threads via \fB\-T0\fR, choose the default based on the number of detected physical or logical cores\. -. .IP "\(bu" 4 \fB\-\-adapt[=min=#,max=#]\fR: \fBzstd\fR will dynamically adapt compression level to perceived I/O conditions\. Compression level adaptation can be observed live by using command \fB\-v\fR\. Adaptation can be constrained between supplied \fBmin\fR and \fBmax\fR levels\. The feature works when combined with multi\-threading and \fB\-\-long\fR mode\. It does not work with \fB\-\-single\-thread\fR\. It sets window size to 8 MiB by default (can be changed manually, see \fBwlog\fR)\. Due to the chaotic nature of dynamic adaptation, compressed result is not reproducible\. -. .IP \fINote\fR: at the time of this writing, \fB\-\-adapt\fR can remain stuck at low speed when combined with multiple worker threads (>=2)\. -. .IP "\(bu" 4 \fB\-\-long[=#]\fR: enables long distance matching with \fB#\fR \fBwindowLog\fR, if \fB#\fR is not present it defaults to \fB27\fR\. This increases the window size (\fBwindowLog\fR) and memory usage for both the compressor and decompressor\. This setting is designed to improve the compression ratio for files with long matches at a large distance\. -. .IP Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\. -. .IP "\(bu" 4 \fB\-D DICT\fR: use \fBDICT\fR as Dictionary to compress or decompress FILE(s) -. .IP "\(bu" 4 -\fB\-\-patch\-from FILE\fR: Specify the file to be used as a reference point for zstd\'s diff engine\. This is effectively dictionary compression with some convenient parameter selection, namely that \fIwindowSize\fR > \fIsrcSize\fR\. -. +\fB\-\-patch\-from FILE\fR: Specify the file to be used as a reference point for zstd's diff engine\. This is effectively dictionary compression with some convenient parameter selection, namely that \fIwindowSize\fR > \fIsrcSize\fR\. .IP Note: cannot use both this and \fB\-D\fR together\. -. .IP Note: \fB\-\-long\fR mode will be automatically activated if \fIchainLog\fR < \fIfileLog\fR (\fIfileLog\fR being the \fIwindowLog\fR required to cover the whole file)\. You can also manually force it\. -. .IP -Note: for all levels, you can use \fB\-\-patch\-from\fR in \fB\-\-single\-thread\fR mode to improve compression ratio at the cost of speed\. -. +Note: up to level 15, you can use \fB\-\-patch\-from\fR in \fB\-\-single\-thread\fR mode to improve compression ratio marginally at the cost of speed\. Using '\-\-single\-thread' above level 15 will lead to lower compression ratios\. .IP Note: for level 19, you can get increased compression ratio at the cost of speed by specifying \fB\-\-zstd=targetLength=\fR to be something large (i\.e\. 4096), and by setting a large \fB\-\-zstd=chainLog=\fR\. -. .IP "\(bu" 4 -\fB\-\-rsyncable\fR: \fBzstd\fR will periodically synchronize the compression state to make the compressed file more rsync\-friendly\. There is a negligible impact to compression ratio, and a potential impact to compression speed, perceptible at higher speeds, for example when combining \fB\-\-rsyncable\fR with many parallel worker threads\. This feature does not work with \fB\-\-single\-thread\fR\. You probably don\'t want to use it with long range mode, since it will decrease the effectiveness of the synchronization points, but your mileage may vary\. -. +\fB\-\-rsyncable\fR: \fBzstd\fR will periodically synchronize the compression state to make the compressed file more rsync\-friendly\. There is a negligible impact to compression ratio, and a potential impact to compression speed, perceptible at higher speeds, for example when combining \fB\-\-rsyncable\fR with many parallel worker threads\. This feature does not work with \fB\-\-single\-thread\fR\. You probably don't want to use it with long range mode, since it will decrease the effectiveness of the synchronization points, but your mileage may vary\. .IP "\(bu" 4 \fB\-C\fR, \fB\-\-[no\-]check\fR: add integrity check computed from uncompressed data (default: enabled) -. .IP "\(bu" 4 \fB\-\-[no\-]content\-size\fR: enable / disable whether or not the original size of the file is placed in the header of the compressed file\. The default option is \fB\-\-content\-size\fR (meaning that the original size will be placed in the header)\. -. .IP "\(bu" 4 -\fB\-\-no\-dictID\fR: do not store dictionary ID within frame header (dictionary compression)\. The decoder will have to rely on implicit knowledge about which dictionary to use, it won\'t be able to check if it\'s correct\. -. +\fB\-\-no\-dictID\fR: do not store dictionary ID within frame header (dictionary compression)\. The decoder will have to rely on implicit knowledge about which dictionary to use, it won't be able to check if it's correct\. .IP "\(bu" 4 \fB\-M#\fR, \fB\-\-memory=#\fR: Set a memory usage limit\. By default, \fBzstd\fR uses 128 MiB for decompression as the maximum amount of memory the decompressor is allowed to use, but you can override this manually if need be in either direction (i\.e\. you can increase or decrease it)\. -. .IP This is also used during compression when using with \fB\-\-patch\-from=\fR\. In this case, this parameter overrides that maximum size allowed for a dictionary\. (128 MiB)\. -. .IP Additionally, this can be used to limit memory for dictionary training\. This parameter overrides the default limit of 2 GiB\. zstd will load training samples up to the memory limit and ignore the rest\. -. .IP "\(bu" 4 \fB\-\-stream\-size=#\fR: Sets the pledged source size of input coming from a stream\. This value must be exact, as it will be included in the produced frame header\. Incorrect stream sizes will cause an error\. This information will be used to better optimize compression parameters, resulting in better and potentially faster compression, especially for smaller source sizes\. -. .IP "\(bu" 4 \fB\-\-size\-hint=#\fR: When handling input from a stream, \fBzstd\fR must guess how large the source size will be when optimizing compression parameters\. If the stream size is relatively small, this guess may be a poor one, resulting in a higher compression ratio than expected\. This feature allows for controlling the guess when needed\. Exact guesses result in better compression ratios\. Overestimates result in slightly degraded compression ratios, while underestimates may result in significant degradation\. -. .IP "\(bu" 4 \fB\-\-target\-compressed\-block\-size=#\fR: Attempt to produce compressed blocks of approximately this size\. This will split larger blocks in order to approach this target\. This feature is notably useful for improved latency, when the receiver can leverage receiving early incomplete data\. This parameter defines a loose target: compressed blocks will target this size "on average", but individual blocks can still be larger or smaller\. Enabling this feature can decrease compression speed by up to ~10% at level 1\. Higher levels will see smaller relative speed regression, becoming invisible at higher settings\. -. .IP "\(bu" 4 \fB\-f\fR, \fB\-\-force\fR: disable input and output checks\. Allows overwriting existing files, input from console, output to stdout, operating on links, block devices, etc\. During decompression and when the output destination is stdout, pass\-through unrecognized formats as\-is\. -. .IP "\(bu" 4 \fB\-c\fR, \fB\-\-stdout\fR: write to standard output (even if it is the console); keep original files (disable \fB\-\-rm\fR)\. -. .IP "\(bu" 4 \fB\-o FILE\fR: save result into \fBFILE\fR\. Note that this operation is in conflict with \fB\-c\fR\. If both operations are present on the command line, the last expressed one wins\. -. .IP "\(bu" 4 \fB\-\-[no\-]sparse\fR: enable / disable sparse FS support, to make files with many zeroes smaller on disk\. Creating sparse files may save disk space and speed up decompression by reducing the amount of disk I/O\. default: enabled when output is into a file, and disabled when output is stdout\. This setting overrides default and can force sparse mode over stdout\. -. .IP "\(bu" 4 \fB\-\-[no\-]pass\-through\fR enable / disable passing through uncompressed files as\-is\. During decompression when pass\-through is enabled, unrecognized formats will be copied as\-is from the input to the output\. By default, pass\-through will occur when the output destination is stdout and the force (\fB\-f\fR) option is set\. -. .IP "\(bu" 4 \fB\-\-rm\fR: remove source file(s) after successful compression or decompression\. This command is silently ignored if output is \fBstdout\fR\. If used in combination with \fB\-o\fR, triggers a confirmation prompt (which can be silenced with \fB\-f\fR), as this is a destructive operation\. -. .IP "\(bu" 4 \fB\-k\fR, \fB\-\-keep\fR: keep source file(s) after successful compression or decompression\. This is the default behavior\. -. .IP "\(bu" 4 \fB\-r\fR: operate recursively on directories\. It selects all files in the named directory and all its subdirectories\. This can be useful both to reduce command line typing, and to circumvent shell expansion limitations, when there are a lot of files and naming breaks the maximum size of a command line\. -. .IP "\(bu" 4 \fB\-\-filelist FILE\fR read a list of files to process as content from \fBFILE\fR\. Format is compatible with \fBls\fR output, with one file per line\. -. .IP "\(bu" 4 \fB\-\-output\-dir\-flat DIR\fR: resulting files are stored into target \fBDIR\fR directory, instead of same directory as origin file\. Be aware that this command can introduce name collision issues, if multiple files, from different directories, end up having the same name\. Collision resolution ensures first file with a given name will be present in \fBDIR\fR, while in combination with \fB\-f\fR, the last file will be present instead\. -. .IP "\(bu" 4 \fB\-\-output\-dir\-mirror DIR\fR: similar to \fB\-\-output\-dir\-flat\fR, the output files are stored underneath target \fBDIR\fR directory, but this option will replicate input directory hierarchy into output \fBDIR\fR\. -. .IP If input directory contains "\.\.", the files in this directory will be ignored\. If input directory is an absolute directory (i\.e\. "/var/tmp/abc"), it will be stored into the "output\-dir/var/tmp/abc"\. If there are multiple input files or directories, name collision resolution will follow the same rules as \fB\-\-output\-dir\-flat\fR\. -. .IP "\(bu" 4 \fB\-\-format=FORMAT\fR: compress and decompress in other formats\. If compiled with support, zstd can compress to or decompress from other compression algorithm formats\. Possibly available options are \fBzstd\fR, \fBgzip\fR, \fBxz\fR, \fBlzma\fR, and \fBlz4\fR\. If no such format is provided, \fBzstd\fR is the default\. -. .IP "\(bu" 4 \fB\-h\fR/\fB\-H\fR, \fB\-\-help\fR: display help/long help and exit -. .IP "\(bu" 4 \fB\-V\fR, \fB\-\-version\fR: display version number and immediately exit\. note that, since it exits, flags specified after \fB\-V\fR are effectively ignored\. Advanced: \fB\-vV\fR also displays supported formats\. \fB\-vvV\fR also displays POSIX support\. \fB\-qV\fR will only display the version number, suitable for machine reading\. -. .IP "\(bu" 4 \fB\-v\fR, \fB\-\-verbose\fR: verbose mode, display more information -. .IP "\(bu" 4 \fB\-q\fR, \fB\-\-quiet\fR: suppress warnings, interactivity, and notifications\. specify twice to suppress errors too\. -. .IP "\(bu" 4 \fB\-\-no\-progress\fR: do not display the progress bar, but keep all other messages\. -. .IP "\(bu" 4 \fB\-\-show\-default\-cparams\fR: shows the default compression parameters that will be used for a particular input file, based on the provided compression level and the input size\. If the provided file is not a regular file (e\.g\. a pipe), this flag will output the parameters used for inputs of unknown size\. -. .IP "\(bu" 4 \fB\-\-exclude\-compressed\fR: only compress files that are not already compressed\. -. .IP "\(bu" 4 \fB\-\-\fR: All arguments after \fB\-\-\fR are treated as files -. .IP "" 0 -. .SS "gzip Operation Modifiers" When invoked via a \fBgzip\fR symlink, \fBzstd\fR will support further options that intend to mimic the \fBgzip\fR behavior: -. .TP \fB\-n\fR, \fB\-\-no\-name\fR do not store the original filename and timestamps when compressing a file\. This is the default behavior and hence a no\-op\. -. .TP \fB\-\-best\fR alias to the option \fB\-9\fR\. -. .SS "Environment Variables" Employing environment variables to set parameters has security implications\. Therefore, this avenue is intentionally limited\. Only \fBZSTD_CLEVEL\fR and \fBZSTD_NBTHREADS\fR are currently supported\. They set the default compression level and number of threads to use during compression, respectively\. -. .P \fBZSTD_CLEVEL\fR can be used to set the level between 1 and 19 (the "normal" range)\. If the value of \fBZSTD_CLEVEL\fR is not a valid integer, it will be ignored with a warning message\. \fBZSTD_CLEVEL\fR just replaces the default compression level (\fB3\fR)\. -. .P \fBZSTD_NBTHREADS\fR can be used to set the number of threads \fBzstd\fR will attempt to use during compression\. If the value of \fBZSTD_NBTHREADS\fR is not a valid unsigned integer, it will be ignored with a warning message\. \fBZSTD_NBTHREADS\fR has a default value of (\fB1\fR), and is capped at ZSTDMT_NBWORKERS_MAX==200\. \fBzstd\fR must be compiled with multithread support for this variable to have any effect\. -. .P They can both be overridden by corresponding command line arguments: \fB\-#\fR for compression level and \fB\-T#\fR for number of compression threads\. -. .SH "ADVANCED COMPRESSION OPTIONS" \fBzstd\fR provides 22 predefined regular compression levels plus the fast levels\. A compression level is translated internally into multiple advanced parameters that control the behavior of the compressor (one can observe the result of this translation with \fB\-\-show\-default\-cparams\fR)\. These advanced parameters can be overridden using advanced compression options\. -. .SS "\-\-zstd[=options]:" The \fIoptions\fR are provided as a comma\-separated list\. You may specify only the options you want to change and the rest will be taken from the selected or default compression level\. The list of available \fIoptions\fR: -. .TP \fBstrategy\fR=\fIstrat\fR, \fBstrat\fR=\fIstrat\fR Specify a strategy used by a match finder\. -. .IP There are 9 strategies numbered from 1 to 9, from fastest to strongest: 1=\fBZSTD_fast\fR, 2=\fBZSTD_dfast\fR, 3=\fBZSTD_greedy\fR, 4=\fBZSTD_lazy\fR, 5=\fBZSTD_lazy2\fR, 6=\fBZSTD_btlazy2\fR, 7=\fBZSTD_btopt\fR, 8=\fBZSTD_btultra\fR, 9=\fBZSTD_btultra2\fR\. -. .TP \fBwindowLog\fR=\fIwlog\fR, \fBwlog\fR=\fIwlog\fR Specify the maximum number of bits for a match distance\. -. .IP The higher number of increases the chance to find a match which usually improves compression ratio\. It also increases memory requirements for the compressor and decompressor\. The minimum \fIwlog\fR is 10 (1 KiB) and the maximum is 30 (1 GiB) on 32\-bit platforms and 31 (2 GiB) on 64\-bit platforms\. -. .IP Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\. -. .TP \fBhashLog\fR=\fIhlog\fR, \fBhlog\fR=\fIhlog\fR Specify the maximum number of bits for a hash table\. -. .IP Bigger hash tables cause fewer collisions which usually makes compression faster, but requires more memory during compression\. -. .IP The minimum \fIhlog\fR is 6 (64 entries / 256 B) and the maximum is 30 (1B entries / 4 GiB)\. -. .TP \fBchainLog\fR=\fIclog\fR, \fBclog\fR=\fIclog\fR Specify the maximum number of bits for the secondary search structure, whose form depends on the selected \fBstrategy\fR\. -. .IP Higher numbers of bits increases the chance to find a match which usually improves compression ratio\. It also slows down compression speed and increases memory requirements for compression\. This option is ignored for the \fBZSTD_fast\fR \fBstrategy\fR, which only has the primary hash table\. -. .IP The minimum \fIclog\fR is 6 (64 entries / 256 B) and the maximum is 29 (512M entries / 2 GiB) on 32\-bit platforms and 30 (1B entries / 4 GiB) on 64\-bit platforms\. -. .TP \fBsearchLog\fR=\fIslog\fR, \fBslog\fR=\fIslog\fR Specify the maximum number of searches in a hash chain or a binary tree using logarithmic scale\. -. .IP More searches increases the chance to find a match which usually increases compression ratio but decreases compression speed\. -. .IP -The minimum \fIslog\fR is 1 and the maximum is \'windowLog\' \- 1\. -. +The minimum \fIslog\fR is 1 and the maximum is 'windowLog' \- 1\. .TP \fBminMatch\fR=\fImml\fR, \fBmml\fR=\fImml\fR Specify the minimum searched length of a match in a hash table\. -. .IP Larger search lengths usually decrease compression ratio but improve decompression speed\. -. .IP The minimum \fImml\fR is 3 and the maximum is 7\. -. .TP \fBtargetLength\fR=\fItlen\fR, \fBtlen\fR=\fItlen\fR The impact of this field vary depending on selected strategy\. -. .IP For \fBZSTD_btopt\fR, \fBZSTD_btultra\fR and \fBZSTD_btultra2\fR, it specifies the minimum match length that causes match finder to stop searching\. A larger \fBtargetLength\fR usually improves compression ratio but decreases compression speed\. -. .IP For \fBZSTD_fast\fR, it triggers ultra\-fast mode when > 0\. The value represents the amount of data skipped between match sampling\. Impact is reversed: a larger \fBtargetLength\fR increases compression speed but decreases compression ratio\. -. .IP For all other strategies, this field has no impact\. -. .IP The minimum \fItlen\fR is 0 and the maximum is 128 KiB\. -. .TP \fBoverlapLog\fR=\fIovlog\fR, \fBovlog\fR=\fIovlog\fR Determine \fBoverlapSize\fR, amount of data reloaded from previous job\. This parameter is only available when multithreading is enabled\. Reloading more data improves compression ratio, but decreases speed\. -. .IP The minimum \fIovlog\fR is 0, and the maximum is 9\. 1 means "no overlap", hence completely independent jobs\. 9 means "full overlap", meaning up to \fBwindowSize\fR is reloaded from previous job\. Reducing \fIovlog\fR by 1 reduces the reloaded amount by a factor 2\. For example, 8 means "windowSize/2", and 6 means "windowSize/8"\. Value 0 is special and means "default": \fIovlog\fR is automatically determined by \fBzstd\fR\. In which case, \fIovlog\fR will range from 6 to 9, depending on selected \fIstrat\fR\. -. .TP \fBldmHashLog\fR=\fIlhlog\fR, \fBlhlog\fR=\fIlhlog\fR Specify the maximum size for a hash table used for long distance matching\. -. .IP This option is ignored unless long distance matching is enabled\. -. .IP Bigger hash tables usually improve compression ratio at the expense of more memory during compression and a decrease in compression speed\. -. .IP The minimum \fIlhlog\fR is 6 and the maximum is 30 (default: 20)\. -. .TP \fBldmMinMatch\fR=\fIlmml\fR, \fBlmml\fR=\fIlmml\fR Specify the minimum searched length of a match for long distance matching\. -. .IP This option is ignored unless long distance matching is enabled\. -. .IP Larger/very small values usually decrease compression ratio\. -. .IP The minimum \fIlmml\fR is 4 and the maximum is 4096 (default: 64)\. -. .TP \fBldmBucketSizeLog\fR=\fIlblog\fR, \fBlblog\fR=\fIlblog\fR Specify the size of each bucket for the hash table used for long distance matching\. -. .IP This option is ignored unless long distance matching is enabled\. -. .IP Larger bucket sizes improve collision resolution but decrease compression speed\. -. .IP The minimum \fIlblog\fR is 1 and the maximum is 8 (default: 3)\. -. .TP \fBldmHashRateLog\fR=\fIlhrlog\fR, \fBlhrlog\fR=\fIlhrlog\fR Specify the frequency of inserting entries into the long distance matching hash table\. -. .IP This option is ignored unless long distance matching is enabled\. -. .IP Larger values will improve compression speed\. Deviating far from the default value will likely result in a decrease in compression ratio\. -. .IP The default value is \fBwlog \- lhlog\fR\. -. .SS "Example" The following parameters sets advanced compression options to something similar to predefined level 19 for files bigger than 256 KB: -. .P \fB\-\-zstd\fR=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6 -. .SS "\-B#:" Specify the size of each compression job\. This parameter is only available when multi\-threading is enabled\. Each compression job is run in parallel, so this value indirectly impacts the nb of active threads\. Default job size varies depending on compression level (generally \fB4 * windowSize\fR)\. \fB\-B#\fR makes it possible to manually select a custom size\. Note that job size must respect a minimum value which is enforced transparently\. This minimum is either 512 KB, or \fBoverlapSize\fR, whichever is largest\. Different job sizes will lead to non\-identical compressed frames\. -. .SH "DICTIONARY BUILDER" -\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It\'s possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\. -. +\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It's possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\. .TP \fB\-\-train FILEs\fR Use FILEs as training set to create a dictionary\. The training set should ideally contain a lot of samples (> 100), and weight typically 100x the target dictionary size (for example, ~10 MB for a 100 KB dictionary)\. \fB\-\-train\fR can be combined with \fB\-r\fR to indicate a directory rather than listing all the files, which can be useful to circumvent shell expansion limits\. -. .IP Since dictionary compression is mostly effective for small files, the expectation is that the training set will only contain small files\. In the case where some samples happen to be large, only the first 128 KiB of these samples will be used for training\. -. .IP \fB\-\-train\fR supports multithreading if \fBzstd\fR is compiled with threading support (default)\. Additional advanced parameters can be specified with \fB\-\-train\-fastcover\fR\. The legacy dictionary builder can be accessed with \fB\-\-train\-legacy\fR\. The slower cover dictionary builder can be accessed with \fB\-\-train\-cover\fR\. Default \fB\-\-train\fR is equivalent to \fB\-\-train\-fastcover=d=8,steps=4\fR\. -. .TP \fB\-o FILE\fR Dictionary saved into \fBFILE\fR (default name: dictionary)\. -. .TP \fB\-\-maxdict=#\fR -Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it\'s possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\. -. +Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it's possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\. .TP \fB\-#\fR Use \fB#\fR compression level during training (optional)\. Will generate statistics more tuned for selected compression level, resulting in a \fIsmall\fR compression ratio improvement for this level\. -. .TP \fB\-B#\fR Split input files into blocks of size # (default: no split) -. .TP \fB\-M#\fR, \fB\-\-memory=#\fR Limit the amount of sample data loaded for training (default: 2 GB)\. Note that the default (2 GB) is also the maximum\. This parameter can be useful in situations where the training set size is not well controlled and could be potentially very large\. Since speed of the training process is directly correlated to the size of the training sample set, a smaller sample set leads to faster training\. -. .IP In situations where the training set is larger than maximum memory, the CLI will randomly select samples among the available ones, up to the maximum allowed memory budget\. This is meant to improve dictionary relevance by mitigating the potential impact of clustering, such as selecting only files from the beginning of a list sorted by modification date, or sorted by alphabetical order\. The randomization process is deterministic, so training of the same list of files with the same parameters will lead to the creation of the same dictionary\. -. .TP \fB\-\-dictID=#\fR -A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It\'s possible to provide an explicit number ID instead\. It\'s up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\. -. +A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It's possible to provide an explicit number ID instead\. It's up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\. .IP -Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2^31, so they should not be used in public\. -. +Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2\e^31, so they should not be used in public\. .TP \fB\-\-train\-cover[=k#,d=#,steps=#,split=#,shrink[=#]]\fR Select parameters for the default dictionary builder algorithm named cover\. If \fId\fR is not specified, then it tries \fId\fR = 6 and \fId\fR = 8\. If \fIk\fR is not specified, then it tries \fIsteps\fR values in the range [50, 2000]\. If \fIsteps\fR is not specified, then the default value of 40 is used\. If \fIsplit\fR is not specified or split <= 0, then the default value of 100 is used\. Requires that \fId\fR <= \fIk\fR\. If \fIshrink\fR flag is not used, then the default value for \fIshrinkDict\fR of 0 is used\. If \fIshrink\fR is not specified, then the default value for \fIshrinkDictMaxRegression\fR of 1 is used\. -. .IP Selects segments of size \fIk\fR with highest score to put in the dictionary\. The score of a segment is computed by the sum of the frequencies of all the subsegments of size \fId\fR\. Generally \fId\fR should be in the range [6, 8], occasionally up to 16, but the algorithm will run faster with d <= \fI8\fR\. Good values for \fIk\fR vary widely based on the input data, but a safe range is [2 * \fId\fR, 2000]\. If \fIsplit\fR is 100, all input samples are used for both training and testing to find optimal \fId\fR and \fIk\fR to build dictionary\. Supports multithreading if \fBzstd\fR is compiled with threading support\. Having \fIshrink\fR enabled takes a truncated dictionary of minimum size and doubles in size until compression ratio of the truncated dictionary is at most \fIshrinkDictMaxRegression%\fR worse than the compression ratio of the largest dictionary\. -. .IP Examples: -. .IP \fBzstd \-\-train\-cover FILEs\fR -. .IP \fBzstd \-\-train\-cover=k=50,d=8 FILEs\fR -. .IP \fBzstd \-\-train\-cover=d=8,steps=500 FILEs\fR -. .IP \fBzstd \-\-train\-cover=k=50 FILEs\fR -. .IP \fBzstd \-\-train\-cover=k=50,split=60 FILEs\fR -. .IP \fBzstd \-\-train\-cover=shrink FILEs\fR -. .IP \fBzstd \-\-train\-cover=shrink=2 FILEs\fR -. .TP \fB\-\-train\-fastcover[=k#,d=#,f=#,steps=#,split=#,accel=#]\fR Same as cover but with extra parameters \fIf\fR and \fIaccel\fR and different default value of split If \fIsplit\fR is not specified, then it tries \fIsplit\fR = 75\. If \fIf\fR is not specified, then it tries \fIf\fR = 20\. Requires that 0 < \fIf\fR < 32\. If \fIaccel\fR is not specified, then it tries \fIaccel\fR = 1\. Requires that 0 < \fIaccel\fR <= 10\. Requires that \fId\fR = 6 or \fId\fR = 8\. -. .IP \fIf\fR is log of size of array that keeps track of frequency of subsegments of size \fId\fR\. The subsegment is hashed to an index in the range [0,2^\fIf\fR \- 1]\. It is possible that 2 different subsegments are hashed to the same index, and they are considered as the same subsegment when computing frequency\. Using a higher \fIf\fR reduces collision but takes longer\. -. .IP Examples: -. .IP \fBzstd \-\-train\-fastcover FILEs\fR -. .IP \fBzstd \-\-train\-fastcover=d=8,f=15,accel=2 FILEs\fR -. .TP \fB\-\-train\-legacy[=selectivity=#]\fR Use legacy dictionary builder algorithm with the given dictionary \fIselectivity\fR (default: 9)\. The smaller the \fIselectivity\fR value, the denser the dictionary, improving its efficiency but reducing its achievable maximum size\. \fB\-\-train\-legacy=s=#\fR is also accepted\. -. .IP Examples: -. .IP \fBzstd \-\-train\-legacy FILEs\fR -. .IP \fBzstd \-\-train\-legacy=selectivity=8 FILEs\fR -. .SH "BENCHMARK" -The \fBzstd\fR CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer\'s performance\. Note that the results are highly dependent on the content being compressed\. -. -.TP -\fB\-b#\fR -benchmark file(s) using compression level # -. -.TP -\fB\-e#\fR -benchmark file(s) using multiple compression levels, from \fB\-b#\fR to \fB\-e#\fR (inclusive) -. -.TP -\fB\-d\fR -benchmark decompression speed only (requires providing an already zstd\-compressed content) -. -.TP -\fB\-i#\fR -minimum evaluation time, in seconds (default: 3s), benchmark mode only -. -.TP -\fB\-B#\fR, \fB\-\-block\-size=#\fR -cut file(s) into independent chunks of size # (default: no chunking) -. -.TP -\fB\-\-priority=rt\fR -set process priority to real\-time (Windows) -. +The \fBzstd\fR CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer's performance\. \fBzstd \-b [FILE(s)]\fR will benchmark \fBzstd\fR for both compression and decompression using default compression level\. Note that results are very dependent on the content being compressed\. It's possible to pass multiple files to the benchmark, and even a directory with \fB\-r DIRECTORY\fR\. When no \fBFILE\fR is provided, the benchmark will use a procedurally generated \fBlorem ipsum\fR text\. +.IP "\(bu" 4 +\fB\-b#\fR: benchmark file(s) using compression level # +.IP "\(bu" 4 +\fB\-e#\fR: benchmark file(s) using multiple compression levels, from \fB\-b#\fR to \fB\-e#\fR (inclusive) +.IP "\(bu" 4 +\fB\-d\fR: benchmark decompression speed only (requires providing a zstd\-compressed content) +.IP "\(bu" 4 +\fB\-i#\fR: minimum evaluation time, in seconds (default: 3s), benchmark mode only +.IP "\(bu" 4 +\fB\-B#\fR, \fB\-\-block\-size=#\fR: cut file(s) into independent chunks of size # (default: no chunking) +.IP "\(bu" 4 +\fB\-S\fR: output one benchmark result per input file (default: consolidated result) +.IP "\(bu" 4 +\fB\-D dictionary\fR benchmark using dictionary +.IP "\(bu" 4 +\fB\-\-priority=rt\fR: set process priority to real\-time (Windows) +.IP "" 0 +.P +Beyond compression levels, benchmarking is also compatible with other parameters, such as number of threads (\fB\-T#\fR), advanced compression parameters (\fB\-\-zstd=###\fR), dictionary compression (\fB\-D dictionary\fR), or even disabling checksum verification for example\. .P \fBOutput Format:\fR CompressionLevel#Filename: InputSize \-> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed -. .P -\fBMethodology:\fR For both compression and decompression speed, the entire input is compressed/decompressed in\-memory to measure speed\. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy\. -. +\fBMethodology:\fR For speed measurement, the entire input is compressed/decompressed in\-memory to measure speed\. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy\. .SH "SEE ALSO" \fBzstdgrep\fR(1), \fBzstdless\fR(1), \fBgzip\fR(1), \fBxz\fR(1) -. .P -The \fIzstandard\fR format is specified in Y\. Collet, "Zstandard Compression and the \'application/zstd\' Media Type", https://www\.ietf\.org/rfc/rfc8878\.txt, Internet RFC 8878 (February 2021)\. -. +The \fIzstandard\fR format is specified in Y\. Collet, "Zstandard Compression and the 'application/zstd' Media Type", https://www\.ietf\.org/rfc/rfc8878\.txt, Internet RFC 8878 (February 2021)\. .SH "BUGS" Report bugs at: https://github\.com/facebook/zstd/issues -. .SH "AUTHOR" Yann Collet diff --git a/programs/zstd.1.md b/programs/zstd.1.md index d0473fa47..fabf8d6fc 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -662,14 +662,17 @@ Compression of small files similar to the sample set will be greatly improved. BENCHMARK --------- The `zstd` CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer's performance. -Note that the results are highly dependent on the content being compressed. +`zstd -b [FILE(s)]` will benchmark `zstd` for both compression and decompression using default compression level. +Note that results are very dependent on the content being compressed. +It's possible to pass multiple files to the benchmark, and even a directory with `-r DIRECTORY`. +When no `FILE` is provided, the benchmark will use a procedurally generated `lorem ipsum` text. * `-b#`: benchmark file(s) using compression level # * `-e#`: benchmark file(s) using multiple compression levels, from `-b#` to `-e#` (inclusive) * `-d`: - benchmark decompression speed only (requires providing an already zstd-compressed content) + benchmark decompression speed only (requires providing a zstd-compressed content) * `-i#`: minimum evaluation time, in seconds (default: 3s), benchmark mode only * `-B#`, `--block-size=#`: @@ -681,9 +684,11 @@ Note that the results are highly dependent on the content being compressed. * `--priority=rt`: set process priority to real-time (Windows) +Beyond compression levels, benchmarking is also compatible with other parameters, such as number of threads (`-T#`), advanced compression parameters (`--zstd=###`), dictionary compression (`-D dictionary`), or even disabling checksum verification for example. + **Output Format:** CompressionLevel#Filename: InputSize -> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed -**Methodology:** For both compression and decompression speed, the entire input is compressed/decompressed in-memory to measure speed. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy. +**Methodology:** For speed measurement, the entire input is compressed/decompressed in-memory to measure speed. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy. SEE ALSO diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 438e9c970..8f94352fe 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1391,6 +1391,7 @@ int main(int argCount, const char* argv[]) } benchParams.literalCompressionMode = literalCompressionMode; + if (benchParams.mode == BMK_decodeOnly) cLevel = cLevelLast = 0; if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel(); if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel(); if (cLevelLast < cLevel) cLevelLast = cLevel; From a5bce4ae84daa5885e61753fa98903964c3348bd Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 14:35:29 -0700 Subject: [PATCH 388/937] XP: add a pre-splitter instead of ingesting only full blocks, make an analysis of data, and infer where to split. --- lib/compress/zstd_compress.c | 31 ++++++-- lib/compress/zstd_preSplit.c | 139 +++++++++++++++++++++++++++++++++++ lib/compress/zstd_preSplit.h | 26 +++++++ 3 files changed, 188 insertions(+), 8 deletions(-) create mode 100644 lib/compress/zstd_preSplit.c create mode 100644 lib/compress/zstd_preSplit.h diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index aad25049d..040333e59 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -883,7 +883,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, value = ZSTDMT_JOBSIZE_MIN; FORWARD_IF_ERROR(ZSTD_cParam_clampBounds(param, &value), ""); assert(value >= 0); - CCtxParams->jobSize = value; + CCtxParams->jobSize = (size_t)value; return CCtxParams->jobSize; #endif @@ -1002,7 +1002,8 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_maxBlockSize: if (value!=0) /* 0 ==> default */ BOUNDCHECK(ZSTD_c_maxBlockSize, value); - CCtxParams->maxBlockSize = value; + assert(value>=0); + CCtxParams->maxBlockSize = (size_t)value; return CCtxParams->maxBlockSize; case ZSTD_c_searchForExternalRepcodes: @@ -2444,7 +2445,8 @@ static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx, } /* Zero the hashTable3, since the cdict never fills it */ - { int const h3log = cctx->blockState.matchState.hashLog3; + assert(cctx->blockState.matchState.hashLog3 <= 31); + { U32 const h3log = cctx->blockState.matchState.hashLog3; size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0; assert(cdict->matchState.hashLog3 == 0); ZSTD_memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32)); @@ -4484,6 +4486,18 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, } } +#include "zstd_preSplit.h" + +static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat) +{ + if (srcSize <= 128 KB || blockSizeMax < 128 KB) + return MIN(srcSize, blockSizeMax); + (void)strat; + if (strat >= ZSTD_btlazy2) + return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); + return 92 KB; +} + /*! ZSTD_compress_frameChunk() : * Compress a chunk of data into one or multiple blocks. * All blocks will be terminated, all input will be consumed. @@ -4496,7 +4510,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, const void* src, size_t srcSize, U32 lastFrameChunk) { - size_t blockSize = cctx->blockSize; + size_t blockSizeMax = cctx->blockSize; size_t remaining = srcSize; const BYTE* ip = (const BYTE*)src; BYTE* const ostart = (BYTE*)dst; @@ -4505,20 +4519,21 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX); - DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize); + DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSizeMax=%u)", (unsigned)blockSizeMax); if (cctx->appliedParams.fParams.checksumFlag && srcSize) XXH64_update(&cctx->xxhState, src, srcSize); while (remaining) { ZSTD_matchState_t* const ms = &cctx->blockState.matchState; - U32 const lastBlock = lastFrameChunk & (blockSize >= remaining); + U32 const lastBlock = lastFrameChunk & (blockSizeMax >= remaining); + size_t blockSize = ZSTD_optimalBlockSize(ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy); + assert(blockSize <= remaining); /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding * additional 1. We need to revisit and change this logic to be more consistent */ RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE + 1, dstSize_tooSmall, "not enough space to store compressed block"); - if (remaining < blockSize) blockSize = remaining; ZSTD_overflowCorrectIfNeeded( ms, &cctx->workspace, &cctx->appliedParams, ip, ip + blockSize); @@ -5022,7 +5037,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, RETURN_ERROR_IF(bs->rep[u] > dictContentSize, dictionary_corrupted, ""); } } } - return dictPtr - (const BYTE*)dict; + return (size_t)(dictPtr - (const BYTE*)dict); } /* Dictionary format : diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c new file mode 100644 index 000000000..eaa1c0516 --- /dev/null +++ b/lib/compress/zstd_preSplit.c @@ -0,0 +1,139 @@ +/* + * 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. + */ + +#include "../common/mem.h" /* U64 */ +#include "zstd_preSplit.h" + + +#define BLOCKSIZE_MIN 3500 +#define THRESHOLD_PENALTY_RATE 16 +#define THRESHOLD_BASE (THRESHOLD_PENALTY_RATE - 2) +#define THRESHOLD_PENALTY 4 + +#define HASHLENGTH 2 +#define HASHLOG 10 +#define HASHTABLESIZE (1 << HASHLOG) +#define HASHMASK (HASHTABLESIZE - 1) +#define KNUTH 0x9e3779b9 + +static unsigned hash2(const void *p) +{ + return (U32)(MEM_read16(p)) * KNUTH >> (32 - HASHLOG); +} + + +/* ==================================== */ +/* Global array -> for testing only !!! */ +/* ==================================== */ +typedef struct { + int events[HASHTABLESIZE]; + S64 nbEvents; +} FingerPrint; +static FingerPrint pastEvents = {}; +static FingerPrint newEvents = {}; + +static void initStats(void) { + memset(&pastEvents, 0, sizeof(pastEvents)); + memset(&newEvents, 0, sizeof(newEvents)); +} +/* ==================================== */ + +static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) { + const char* p = src; + size_t limit = s - HASHLENGTH + 1; + assert(s >= HASHLENGTH); + for (size_t n = 0; n < limit; n++) { + fp->events[hash2(p++)]++; + } + fp->nbEvents += limit; +} + +static void recordFingerprint(FingerPrint *fp, const void *src, size_t s) { + memset(fp, 0, sizeof(*fp)); + addToFingerprint(fp, src, s); +} + +static S64 abs64(S64 i) { return (i < 0) ? -i : i; } + +static S64 fpDistance(const FingerPrint *fp1, const FingerPrint *fp2) { + S64 distance = 0; + for (size_t n = 0; n < HASHTABLESIZE; n++) { + distance += + abs64(fp1->events[n] * fp2->nbEvents - fp2->events[n] * fp1->nbEvents); + } + return distance; +} + +// Compare newEvents with pastEvents +// return 1 when considered "too different" +// debug:write Deviation value in % +static int compareFingerprints(const FingerPrint *ref, + const FingerPrint *new, + int penalty) +{ + if (ref->nbEvents <= BLOCKSIZE_MIN) + return 0; + { S64 p50 = ref->nbEvents * new->nbEvents; + S64 deviation = fpDistance(ref, new); + // printf("Deviation: %.2f%% \n", (double)deviation / (double)ref * 100.); + S64 threshold = p50 * (THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; + return deviation >= threshold; + } +} + +static void mergeEvents(FingerPrint *acc, const FingerPrint *new) { + for (size_t n = 0; n < HASHTABLESIZE; n++) { + acc->events[n] += new->events[n]; + } + acc->nbEvents += new->nbEvents; +} + +static void flushEvents(void) { + for (size_t n = 0; n < HASHTABLESIZE; n++) { + pastEvents.events[n] = newEvents.events[n]; + } + pastEvents.nbEvents = newEvents.nbEvents; + memset(&newEvents, 0, sizeof(newEvents)); +} + +static void removeEvents(FingerPrint *acc, const FingerPrint *slice) { + for (size_t n = 0; n < HASHTABLESIZE; n++) { + assert(acc->events[n] >= slice->events[n]); + acc->events[n] -= slice->events[n]; + } + acc->nbEvents -= slice->nbEvents; +} + +#define CHUNKSIZE (8 << 10) +/* Note: technically, we use CHUNKSIZE, so that's 8 KB */ +size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax) +{ + const char* p = src; + int penalty = THRESHOLD_PENALTY; + size_t pos = 0; + if (srcSize <= blockSizeMax) return srcSize; + assert(blockSizeMax == (128 << 10)); + + initStats(); + for (pos = 0; pos < blockSizeMax;) { + assert(pos <= blockSizeMax - CHUNKSIZE); + recordFingerprint(&newEvents, p + pos, CHUNKSIZE); + if (compareFingerprints(&pastEvents, &newEvents, penalty)) { + return pos; + } else { + mergeEvents(&pastEvents, &newEvents); + memset(&newEvents, 0, sizeof(newEvents)); + penalty = penalty - 1 + (penalty == 0); + } + pos += CHUNKSIZE; + } + return blockSizeMax; + (void)flushEvents; (void)removeEvents; +} diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h new file mode 100644 index 000000000..148fc1936 --- /dev/null +++ b/lib/compress/zstd_preSplit.h @@ -0,0 +1,26 @@ +/* + * 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_PRESPLIT_H +#define ZSTD_PRESPLIT_H + +#include /* size_t */ + +#if defined (__cplusplus) +extern "C" { +#endif + +size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax); + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_PRESPLIT_H */ From 9e52789962bc5d47ee62bc3e499c52435c693e89 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 16:44:30 -0700 Subject: [PATCH 389/937] fixed strict C90 semantic --- lib/compress/zstd_preSplit.c | 56 ++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index eaa1c0516..f2319986c 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -36,8 +36,8 @@ typedef struct { int events[HASHTABLESIZE]; S64 nbEvents; } FingerPrint; -static FingerPrint pastEvents = {}; -static FingerPrint newEvents = {}; +static FingerPrint pastEvents; +static FingerPrint newEvents; static void initStats(void) { memset(&pastEvents, 0, sizeof(pastEvents)); @@ -48,8 +48,9 @@ static void initStats(void) { static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) { const char* p = src; size_t limit = s - HASHLENGTH + 1; + size_t n; assert(s >= HASHLENGTH); - for (size_t n = 0; n < limit; n++) { + for (n = 0; n < limit; n++) { fp->events[hash2(p++)]++; } fp->nbEvents += limit; @@ -64,7 +65,8 @@ static S64 abs64(S64 i) { return (i < 0) ? -i : i; } static S64 fpDistance(const FingerPrint *fp1, const FingerPrint *fp2) { S64 distance = 0; - for (size_t n = 0; n < HASHTABLESIZE; n++) { + size_t n; + for (n = 0; n < HASHTABLESIZE; n++) { distance += abs64(fp1->events[n] * fp2->nbEvents - fp2->events[n] * fp1->nbEvents); } @@ -73,42 +75,46 @@ static S64 fpDistance(const FingerPrint *fp1, const FingerPrint *fp2) { // Compare newEvents with pastEvents // return 1 when considered "too different" -// debug:write Deviation value in % -static int compareFingerprints(const FingerPrint *ref, - const FingerPrint *new, +static int compareFingerprints(const FingerPrint* ref, + const FingerPrint* new, int penalty) { if (ref->nbEvents <= BLOCKSIZE_MIN) return 0; { S64 p50 = ref->nbEvents * new->nbEvents; S64 deviation = fpDistance(ref, new); - // printf("Deviation: %.2f%% \n", (double)deviation / (double)ref * 100.); S64 threshold = p50 * (THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; return deviation >= threshold; } } -static void mergeEvents(FingerPrint *acc, const FingerPrint *new) { - for (size_t n = 0; n < HASHTABLESIZE; n++) { - acc->events[n] += new->events[n]; - } - acc->nbEvents += new->nbEvents; +static void mergeEvents(FingerPrint* acc, const FingerPrint* new) +{ + size_t n; + for (n = 0; n < HASHTABLESIZE; n++) { + acc->events[n] += new->events[n]; + } + acc->nbEvents += new->nbEvents; } -static void flushEvents(void) { - for (size_t n = 0; n < HASHTABLESIZE; n++) { - pastEvents.events[n] = newEvents.events[n]; - } - pastEvents.nbEvents = newEvents.nbEvents; - memset(&newEvents, 0, sizeof(newEvents)); +static void flushEvents(void) +{ + size_t n; + for (n = 0; n < HASHTABLESIZE; n++) { + pastEvents.events[n] = newEvents.events[n]; + } + pastEvents.nbEvents = newEvents.nbEvents; + memset(&newEvents, 0, sizeof(newEvents)); } -static void removeEvents(FingerPrint *acc, const FingerPrint *slice) { - for (size_t n = 0; n < HASHTABLESIZE; n++) { - assert(acc->events[n] >= slice->events[n]); - acc->events[n] -= slice->events[n]; - } - acc->nbEvents -= slice->nbEvents; +static void removeEvents(FingerPrint* acc, const FingerPrint* slice) +{ + size_t n; + for (n = 0; n < HASHTABLESIZE; n++) { + assert(acc->events[n] >= slice->events[n]); + acc->events[n] -= slice->events[n]; + } + acc->nbEvents -= slice->nbEvents; } #define CHUNKSIZE (8 << 10) From 586ca96fec794cde09f4aa01fe792a9779b62368 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 16:48:52 -0700 Subject: [PATCH 390/937] do not use `new` as variable name --- lib/compress/zstd_preSplit.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index f2319986c..bba348927 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -76,25 +76,25 @@ static S64 fpDistance(const FingerPrint *fp1, const FingerPrint *fp2) { // Compare newEvents with pastEvents // return 1 when considered "too different" static int compareFingerprints(const FingerPrint* ref, - const FingerPrint* new, + const FingerPrint* newfp, int penalty) { if (ref->nbEvents <= BLOCKSIZE_MIN) return 0; - { S64 p50 = ref->nbEvents * new->nbEvents; - S64 deviation = fpDistance(ref, new); + { S64 p50 = ref->nbEvents * newfp->nbEvents; + S64 deviation = fpDistance(ref, newfp); S64 threshold = p50 * (THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; return deviation >= threshold; } } -static void mergeEvents(FingerPrint* acc, const FingerPrint* new) +static void mergeEvents(FingerPrint* acc, const FingerPrint* newfp) { size_t n; for (n = 0; n < HASHTABLESIZE; n++) { - acc->events[n] += new->events[n]; + acc->events[n] += newfp->events[n]; } - acc->nbEvents += new->nbEvents; + acc->nbEvents += newfp->nbEvents; } static void flushEvents(void) From e2d7d08888f915667c94e6dbbadaee38a5d50fa5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 16:52:10 -0700 Subject: [PATCH 391/937] use ZSTD_memset() for better portability on Linux kernel --- lib/compress/zstd_preSplit.c | 50 +++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index bba348927..8db742c4d 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -39,38 +39,42 @@ typedef struct { static FingerPrint pastEvents; static FingerPrint newEvents; -static void initStats(void) { - memset(&pastEvents, 0, sizeof(pastEvents)); - memset(&newEvents, 0, sizeof(newEvents)); +static void initStats(void) +{ + ZSTD_memset(&pastEvents, 0, sizeof(pastEvents)); + ZSTD_memset(&newEvents, 0, sizeof(newEvents)); } /* ==================================== */ -static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) { - const char* p = src; - size_t limit = s - HASHLENGTH + 1; - size_t n; - assert(s >= HASHLENGTH); - for (n = 0; n < limit; n++) { - fp->events[hash2(p++)]++; - } - fp->nbEvents += limit; +static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) +{ + const char* p = src; + size_t limit = s - HASHLENGTH + 1; + size_t n; + assert(s >= HASHLENGTH); + for (n = 0; n < limit; n++) { + fp->events[hash2(p++)]++; + } + fp->nbEvents += limit; } -static void recordFingerprint(FingerPrint *fp, const void *src, size_t s) { - memset(fp, 0, sizeof(*fp)); - addToFingerprint(fp, src, s); +static void recordFingerprint(FingerPrint* fp, const void* src, size_t s) +{ + memset(fp, 0, sizeof(*fp)); + addToFingerprint(fp, src, s); } static S64 abs64(S64 i) { return (i < 0) ? -i : i; } -static S64 fpDistance(const FingerPrint *fp1, const FingerPrint *fp2) { - S64 distance = 0; - size_t n; - for (n = 0; n < HASHTABLESIZE; n++) { - distance += - abs64(fp1->events[n] * fp2->nbEvents - fp2->events[n] * fp1->nbEvents); - } - return distance; +static S64 fpDistance(const FingerPrint* fp1, const FingerPrint* fp2) +{ + S64 distance = 0; + size_t n; + for (n = 0; n < HASHTABLESIZE; n++) { + distance += + abs64(fp1->events[n] * fp2->nbEvents - fp2->events[n] * fp1->nbEvents); + } + return distance; } // Compare newEvents with pastEvents From 6021b6663a4705f446f7cf856d944819caa575c3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 16:54:36 -0700 Subject: [PATCH 392/937] minor C++-ism though I really wonder if this is a property worth maintaining. --- lib/compress/zstd_preSplit.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 8db742c4d..7d9a32c8f 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -48,7 +48,7 @@ static void initStats(void) static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) { - const char* p = src; + const char* p = (const char*)src; size_t limit = s - HASHLENGTH + 1; size_t n; assert(s >= HASHLENGTH); @@ -125,7 +125,7 @@ static void removeEvents(FingerPrint* acc, const FingerPrint* slice) /* Note: technically, we use CHUNKSIZE, so that's 8 KB */ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax) { - const char* p = src; + const char* p = (const char*)src; int penalty = THRESHOLD_PENALTY; size_t pos = 0; if (srcSize <= blockSizeMax) return srcSize; From fa147cbb4d3fbd8c31b1f35c7984ae62f4c6ea03 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 3 Sep 2024 16:59:06 -0700 Subject: [PATCH 393/937] more ZSTD_memset() to apply --- lib/compress/zstd_preSplit.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 7d9a32c8f..9c84c2b4a 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -60,7 +60,7 @@ static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) static void recordFingerprint(FingerPrint* fp, const void* src, size_t s) { - memset(fp, 0, sizeof(*fp)); + ZSTD_memset(fp, 0, sizeof(*fp)); addToFingerprint(fp, src, s); } @@ -108,7 +108,7 @@ static void flushEvents(void) pastEvents.events[n] = newEvents.events[n]; } pastEvents.nbEvents = newEvents.nbEvents; - memset(&newEvents, 0, sizeof(newEvents)); + ZSTD_memset(&newEvents, 0, sizeof(newEvents)); } static void removeEvents(FingerPrint* acc, const FingerPrint* slice) @@ -139,7 +139,7 @@ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax) return pos; } else { mergeEvents(&pastEvents, &newEvents); - memset(&newEvents, 0, sizeof(newEvents)); + ZSTD_memset(&newEvents, 0, sizeof(newEvents)); penalty = penalty - 1 + (penalty == 0); } pos += CHUNKSIZE; From 83a3402a928ef07700b1431c86534bec902ad11d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 12:55:08 -0700 Subject: [PATCH 394/937] fix overlap write scenario in presence of incompressible data --- lib/compress/zstd_compress.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 040333e59..eb7b06df9 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1631,7 +1631,8 @@ ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams( { ZSTD_compressionParameters cParams; if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) { - srcSizeHint = CCtxParams->srcSizeHint; + assert(srcSizeHint>=0); + srcSizeHint = (U64)CCtxParams->srcSizeHint; } cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode); if (CCtxParams->ldmParams.enableLdm == ZSTD_ps_enable) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG; @@ -4488,14 +4489,18 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, #include "zstd_preSplit.h" -static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat) +static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { if (srcSize <= 128 KB || blockSizeMax < 128 KB) return MIN(srcSize, blockSizeMax); (void)strat; if (strat >= ZSTD_btlazy2) return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); - return 92 KB; + /* blind split strategy + * heuristic, just tested as being "generally better" + * do not split incompressible data though: just respect the 3 bytes per block overhead limit. + */ + return savings ? 92 KB : 128 KB; } /*! ZSTD_compress_frameChunk() : @@ -4516,6 +4521,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, BYTE* const ostart = (BYTE*)dst; BYTE* op = ostart; U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog; + S64 savings = (S64)cctx->consumedSrcSize - (S64)cctx->producedCSize; assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX); @@ -4526,7 +4532,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, while (remaining) { ZSTD_matchState_t* const ms = &cctx->blockState.matchState; U32 const lastBlock = lastFrameChunk & (blockSizeMax >= remaining); - size_t blockSize = ZSTD_optimalBlockSize(ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy); + size_t const blockSize = ZSTD_optimalBlockSize(ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy, savings); assert(blockSize <= remaining); /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding @@ -4571,7 +4577,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, } } /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/ - + if (cSize < blockSize) savings += (blockSize - cSize); ip += blockSize; assert(remaining >= blockSize); remaining -= blockSize; From f83ed087f6310a8cf51267ea431ec4a7b7ffd94f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 13:21:55 -0700 Subject: [PATCH 395/937] fixed RLE detection test --- lib/compress/zstd_compress.c | 10 +++++----- tests/fuzzer.c | 19 +++++++++++-------- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index eb7b06df9..25a11f070 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4491,14 +4491,14 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { - if (srcSize <= 128 KB || blockSizeMax < 128 KB) - return MIN(srcSize, blockSizeMax); - (void)strat; if (strat >= ZSTD_btlazy2) return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); + if (srcSize <= 128 KB || blockSizeMax < 128 KB) + return MIN(srcSize, blockSizeMax); /* blind split strategy - * heuristic, just tested as being "generally better" - * do not split incompressible data though: just respect the 3 bytes per block overhead limit. + * no cpu cost, but can over-split homegeneous data. + * heuristic, tested as being "generally better". + * do not split incompressible data though: respect the 3 bytes per block overhead limit. */ return savings ? 92 KB : 128 KB; } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index ead3cc8dd..f5a894354 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3653,16 +3653,19 @@ static int basicUnitTests(U32 const seed, double compressibility) ZSTD_freeDCtx(dctx); } - /* long rle test */ + /* rle detection test: must compress better blocks with a single identical byte repeated */ { size_t sampleSize = 0; - size_t expectedCompressedSize = 39; /* block 1, 2: compressed, block 3: RLE, zstd 1.4.4 */ - DISPLAYLEVEL(3, "test%3i : Long RLE test : ", testNb++); - memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1); - sampleSize += 256 KB - 1; - memset((char*)CNBuffer+sampleSize, 'A', 96 KB); - sampleSize += 96 KB; + size_t maxCompressedSize = 46; /* block 1, 2: compressed, block 3: RLE, zstd 1.4.4 */ + DISPLAYLEVEL(3, "test%3i : RLE detection test : ", testNb++); + memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 2); + sampleSize += 256 KB - 2; + memset((char*)CNBuffer+sampleSize, 'A', 100 KB); + sampleSize += 100 KB; cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1); - if (ZSTD_isError(cSize) || cSize > expectedCompressedSize) goto _output_error; + if (ZSTD_isError(cSize) || cSize > maxCompressedSize) { + DISPLAYLEVEL(4, "error: cSize %u > %u expected ! \n", (unsigned)cSize, (unsigned)maxCompressedSize); + goto _output_error; + } { CHECK_NEWV(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize)); if (regenSize!=sampleSize) goto _output_error; } DISPLAYLEVEL(3, "OK \n"); From 8b3887f579f7e98d09ec3823736b467ceaebbcd1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 13:26:57 -0700 Subject: [PATCH 396/937] fixed kernel build --- lib/compress/zstd_preSplit.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 9c84c2b4a..93e77248b 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -8,7 +8,8 @@ * You may select, at your option, one of the above-listed licenses. */ -#include "../common/mem.h" /* U64 */ +#include "../common/mem.h" /* S64 */ +#include "../common/zstd_deps.h" /* ZSTD_memset */ #include "zstd_preSplit.h" From dd38c677ebd680f29afdf4eab5c08d7a01eb8f39 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 14:41:26 -0700 Subject: [PATCH 397/937] fixed single-library build --- build/single_file_libs/zstd-in.c | 1 + 1 file changed, 1 insertion(+) diff --git a/build/single_file_libs/zstd-in.c b/build/single_file_libs/zstd-in.c index e6fca9e4a..f381ecc4f 100644 --- a/build/single_file_libs/zstd-in.c +++ b/build/single_file_libs/zstd-in.c @@ -69,6 +69,7 @@ #include "compress/zstd_compress_literals.c" #include "compress/zstd_compress_sequences.c" #include "compress/zstd_compress_superblock.c" +#include "compress/zstd_preSplit.c" #include "compress/zstd_compress.c" #include "compress/zstd_double_fast.c" #include "compress/zstd_fast.c" From 0d4b52065791a8e96faf8eb7665cb701b29d186e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 14:46:47 -0700 Subject: [PATCH 398/937] only split full blocks short term simplification --- lib/compress/zstd_compress.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 25a11f070..11c8ceabd 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4491,10 +4491,15 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { - if (strat >= ZSTD_btlazy2) - return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); + /* note: we currenly only split full blocks (128 KB) + * and when there is more than 128 KB input remaining + */ if (srcSize <= 128 KB || blockSizeMax < 128 KB) return MIN(srcSize, blockSizeMax); + /* dynamic splitting has a cpu cost for analysis, + * due to that cost it's only used for btlazy2+ strategies */ + if (strat >= ZSTD_btlazy2) + return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); /* blind split strategy * no cpu cost, but can over-split homegeneous data. * heuristic, tested as being "generally better". From 20c3d176cd8871d01fe8135bdc7693a208d739bc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 14:50:46 -0700 Subject: [PATCH 399/937] fix assert --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 11c8ceabd..d9f10f849 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1631,7 +1631,7 @@ ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams( { ZSTD_compressionParameters cParams; if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) { - assert(srcSizeHint>=0); + assert(CCtxParams->srcSizeHint>=0); srcSizeHint = (U64)CCtxParams->srcSizeHint; } cParams = ZSTD_getCParams_internal(CCtxParams->compressionLevel, srcSizeHint, dictSize, mode); From 6dc52122e6e8b28b8477a202726dfff7d0ce0b9c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 14:52:49 -0700 Subject: [PATCH 400/937] fixed c90 comment style --- lib/compress/zstd_preSplit.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 93e77248b..3256905df 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -78,8 +78,9 @@ static S64 fpDistance(const FingerPrint* fp1, const FingerPrint* fp2) return distance; } -// Compare newEvents with pastEvents -// return 1 when considered "too different" +/* Compare newEvents with pastEvents + * return 1 when considered "too different" + */ static int compareFingerprints(const FingerPrint* ref, const FingerPrint* newfp, int penalty) From 80a912dec1e5ec1fad6e6a698cfe04685c0d865e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 15:16:57 -0700 Subject: [PATCH 401/937] fixed zstreamtest --- tests/zstreamtest.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 2c25adf3c..93032d21e 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -958,7 +958,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) break; out.size = MIN(out.size + cSize / 4, compressedBufferSize); } - CHECK_Z(ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, cSize)); + CHECK_Z(ZSTD_decompress(decodedBuffer, CNBufferSize, compressedBuffer, out.pos)); DISPLAYLEVEL(3, "OK \n"); DISPLAYLEVEL(3, "test%3i : ZSTD_compressStream2() ZSTD_c_stableInBuffer modify buffer : ", testNb++); From 6939235f010255bbe513dc5b18b1796cbee39d52 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 15:35:56 -0700 Subject: [PATCH 402/937] fixed meson build --- build/meson/lib/meson.build | 1 + 1 file changed, 1 insertion(+) diff --git a/build/meson/lib/meson.build b/build/meson/lib/meson.build index 4ff926f9c..d086fc2d7 100644 --- a/build/meson/lib/meson.build +++ b/build/meson/lib/meson.build @@ -30,6 +30,7 @@ libzstd_sources = [join_paths(zstd_rootdir, 'lib/common/entropy_common.c'), join_paths(zstd_rootdir, 'lib/compress/zstd_compress_literals.c'), join_paths(zstd_rootdir, 'lib/compress/zstd_compress_sequences.c'), join_paths(zstd_rootdir, 'lib/compress/zstd_compress_superblock.c'), + join_paths(zstd_rootdir, 'lib/compress/zstd_preSplit.c'), join_paths(zstd_rootdir, 'lib/compress/zstdmt_compress.c'), join_paths(zstd_rootdir, 'lib/compress/zstd_fast.c'), join_paths(zstd_rootdir, 'lib/compress/zstd_double_fast.c'), From cdddcaaec9111c4ab086a55e4d0337131ca13fd0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 15:42:02 -0700 Subject: [PATCH 403/937] new Makefile target mesonbuild for easier local testing --- .github/workflows/dev-short-tests.yml | 8 ++++---- Makefile | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7713a897c..99aa166c9 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -232,10 +232,10 @@ jobs: -Dbin_tests=true \ -Dbin_contrib=true \ -Ddefault_library=both \ - build/meson builddir - ninja -C builddir/ - meson test -C builddir/ --print-errorlogs - meson install -C builddir --destdir staging/ + build/meson mesonBuild + ninja -C mesonBuild/ + meson test -C mesonBuild/ --print-errorlogs + meson install -C mesonBuild --destdir staging/ meson-mingw-cross-compilation: runs-on: ubuntu-latest diff --git a/Makefile b/Makefile index 5598cdd03..95d45afb4 100644 --- a/Makefile +++ b/Makefile @@ -145,7 +145,7 @@ clean: $(Q)$(MAKE) -C contrib/largeNbDicts $@ > $(VOID) $(Q)$(MAKE) -C contrib/externalSequenceProducer $@ > $(VOID) $(Q)$(RM) zstd$(EXT) zstdmt$(EXT) tmp* - $(Q)$(RM) -r lz4 cmakebuild install + $(Q)$(RM) -r lz4 cmakebuild mesonbuild install @echo Cleaning completed #------------------------------------------------------------------------------ @@ -415,6 +415,24 @@ cmakebuild: $(CMAKE) --build cmakebuild --target install -- -j V=1 cd cmakebuild; ctest -V -L Medium +MESON ?= meson +NINJA ?= ninja + +.PHONY: mesonbuild +mesonbuild: + $(MESON) setup \ + --buildtype=debugoptimized \ + -Db_lundef=false \ + -Dauto_features=enabled \ + -Dbin_programs=true \ + -Dbin_tests=true \ + -Dbin_contrib=true \ + -Ddefault_library=both \ + build/meson mesonbuild + $(NINJA) -C mesonbuild/ + $(MESON) test -C mesonbuild/ --print-errorlogs + $(MESON) install -C mesonbuild --destdir staging/ + .PHONY: c89build gnu90build c99build gnu99build c11build bmix64build bmix32build bmi32build staticAnalyze c89build: clean $(CC) -v From 76ad1d69039c4900e5a0dca8eec7f3da2bebc050 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 15:44:51 -0700 Subject: [PATCH 404/937] fixed VS2010 solution --- build/VS2010/fullbench/fullbench.vcxproj | 1 + build/VS2010/fuzzer/fuzzer.vcxproj | 1 + build/VS2010/libzstd-dll/libzstd-dll.vcxproj | 1 + build/VS2010/libzstd/libzstd.vcxproj | 1 + build/VS2010/zstd/zstd.vcxproj | 1 + 5 files changed, 5 insertions(+) diff --git a/build/VS2010/fullbench/fullbench.vcxproj b/build/VS2010/fullbench/fullbench.vcxproj index 2e0a042b0..f60cfe726 100644 --- a/build/VS2010/fullbench/fullbench.vcxproj +++ b/build/VS2010/fullbench/fullbench.vcxproj @@ -170,6 +170,7 @@ + diff --git a/build/VS2010/fuzzer/fuzzer.vcxproj b/build/VS2010/fuzzer/fuzzer.vcxproj index 91974ec7f..ccbd2517d 100644 --- a/build/VS2010/fuzzer/fuzzer.vcxproj +++ b/build/VS2010/fuzzer/fuzzer.vcxproj @@ -170,6 +170,7 @@ + diff --git a/build/VS2010/libzstd-dll/libzstd-dll.vcxproj b/build/VS2010/libzstd-dll/libzstd-dll.vcxproj index 97ad2fcb2..6925e0f9e 100644 --- a/build/VS2010/libzstd-dll/libzstd-dll.vcxproj +++ b/build/VS2010/libzstd-dll/libzstd-dll.vcxproj @@ -34,6 +34,7 @@ + diff --git a/build/VS2010/libzstd/libzstd.vcxproj b/build/VS2010/libzstd/libzstd.vcxproj index 614e6292a..82a2d8268 100644 --- a/build/VS2010/libzstd/libzstd.vcxproj +++ b/build/VS2010/libzstd/libzstd.vcxproj @@ -34,6 +34,7 @@ + diff --git a/build/VS2010/zstd/zstd.vcxproj b/build/VS2010/zstd/zstd.vcxproj index 5a5237f0e..0558687f5 100644 --- a/build/VS2010/zstd/zstd.vcxproj +++ b/build/VS2010/zstd/zstd.vcxproj @@ -35,6 +35,7 @@ + From 31d48e9ffadde779e5fd9b290dee44f616b050fa Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 16:23:05 -0700 Subject: [PATCH 405/937] fixing minor formatting issue in 32-bit mode with logs enabled --- lib/compress/zstd_compress_internal.h | 4 ++-- lib/compress/zstd_opt.c | 18 +++++++++--------- lib/decompress/zstd_decompress.c | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 622903398..042b5e5ca 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -798,8 +798,8 @@ ZSTD_count_2segments(const BYTE* ip, const BYTE* match, size_t const matchLength = ZSTD_count(ip, match, vEnd); if (match + matchLength != mEnd) return matchLength; DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength); - DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match); - DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip); + DEBUGLOG(7, "distance from match beginning to end dictionary = %i", (int)(mEnd - match)); + DEBUGLOG(7, "distance from current pos to end buffer = %i", (int)(iEnd - ip)); DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart); DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd)); return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd); diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 8a4345b31..e4a8ee81e 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1197,7 +1197,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, for (cur = 1; cur <= last_pos; cur++) { const BYTE* const inr = ip + cur; assert(cur <= ZSTD_OPT_NUM); - DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur); + DEBUGLOG(7, "cPos:%i==rPos:%u", (int)(inr-istart), cur); /* Fix current position with one literal if cheaper */ { U32 const litlen = opt[cur-1].litlen + 1; @@ -1207,8 +1207,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, assert(price < 1000000000); /* overflow check */ if (price <= opt[cur].price) { ZSTD_optimal_t const prevMatch = opt[cur]; - DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)", - inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen, + DEBUGLOG(7, "cPos:%i==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)", + (int)(inr-istart), cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen, opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]); opt[cur] = opt[cur-1]; opt[cur].litlen = litlen; @@ -1240,8 +1240,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, } } } else { - DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f)", - inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price)); + DEBUGLOG(7, "cPos:%i==rPos:%u : literal would cost more (%.2f>%.2f)", + (int)(inr-istart), cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price)); } } @@ -1284,8 +1284,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, } { U32 const longestML = matches[nbMatches-1].len; - DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of longest ML=%u", - inr-istart, cur, nbMatches, longestML); + DEBUGLOG(7, "cPos:%i==rPos:%u, found %u matches, of longest ML=%u", + (int)(inr-istart), cur, nbMatches, longestML); if ( (longestML > sufficient_len) || (cur + longestML >= ZSTD_OPT_NUM) @@ -1411,8 +1411,8 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ U32 const mlen = opt[storePos].mlen; U32 const offBase = opt[storePos].off; U32 const advance = llen + mlen; - DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u", - anchor - istart, (unsigned)llen, (unsigned)mlen); + DEBUGLOG(6, "considering seq starting at %i, llen=%u, mlen=%u", + (int)(anchor - istart), (unsigned)llen, (unsigned)mlen); if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */ assert(storePos == storeEnd); /* must be last sequence */ diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 26c9457fb..6aac5dd3f 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -1057,7 +1057,7 @@ static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx, } ZSTD_DCtx_trace_end(dctx, (U64)(op-ostart), (U64)(ip-istart), /* streaming */ 0); /* Allow caller to get size read */ - DEBUGLOG(4, "ZSTD_decompressFrame: decompressed frame of size %zi, consuming %zi bytes of input", op-ostart, ip - (const BYTE*)*srcPtr); + DEBUGLOG(4, "ZSTD_decompressFrame: decompressed frame of size %i, consuming %i bytes of input", (int)(op-ostart), (int)(ip - (const BYTE*)*srcPtr)); *srcPtr = ip; *srcSizePtr = remainingSrcSize; return (size_t)(op-ostart); From 7f015c2fd799d3c273c5986a63059ef9536b701e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 17:05:17 -0700 Subject: [PATCH 406/937] replaced uasan32 test by asan32 test --- .github/workflows/dev-long-tests.yml | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index deb5242b0..fa603e401 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -156,15 +156,30 @@ jobs: make libc6install CFLAGS="-O3 -m32" FUZZER_FLAGS="--long-tests" make uasan-fuzztest - clang-asan-ubsan-fuzz32: + clang-asan-fuzz32: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: clang + ASan + UBSan + Fuzz Test 32bit + - name: clang + ASan + Fuzz Test 32bit run: | sudo apt-get -qqq update make libc6install - CC=clang CFLAGS="-O3 -m32" FUZZER_FLAGS="--long-tests" make uasan-fuzztest + CC=clang CFLAGS="-O3 -m32" FUZZER_FLAGS="--long-tests" make asan-fuzztest + +# The following test seems to have issues on github CI specifically, +# it does not provide the `__mulodi4` instruction emulation +# required for signed 64-bit multiplication. +# Replaced by asan-only test (above) +# +# clang-asan-ubsan-fuzz32: +# runs-on: ubuntu-20.04 +# steps: +# - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 +# - name: clang + ASan + UBSan + Fuzz Test 32bit +# run: | +# sudo apt-get -qqq update +# make libc6install +# CC=clang CFLAGS="-O3 -m32" FUZZER_FLAGS="--long-tests" make uasan-fuzztest asan-ubsan-regression: runs-on: ubuntu-20.04 From 73a665365350668757ec542277472ca73267603a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 17 Oct 2024 18:40:47 -0700 Subject: [PATCH 407/937] ZSTD_splitBlock_4k() uses externally provided workspace ideally, this workspace would be provided from the ZSTD_CCtx* state --- lib/compress/zstd_compress.c | 9 +++++--- lib/compress/zstd_preSplit.c | 43 ++++++++++++++++++++---------------- lib/compress/zstd_preSplit.h | 8 ++++++- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d9f10f849..37b87336c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4489,8 +4489,11 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, #include "zstd_preSplit.h" -static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) + +static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { + S64 workspace[ZSTD_SLIPBLOCK_WORKSPACESIZE / 8]; + (void)cctx; /* note: we currenly only split full blocks (128 KB) * and when there is more than 128 KB input remaining */ @@ -4499,7 +4502,7 @@ static size_t ZSTD_optimalBlockSize(const void* src, size_t srcSize, size_t bloc /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for btlazy2+ strategies */ if (strat >= ZSTD_btlazy2) - return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax); + return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax, workspace, sizeof(workspace)); /* blind split strategy * no cpu cost, but can over-split homegeneous data. * heuristic, tested as being "generally better". @@ -4537,7 +4540,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, while (remaining) { ZSTD_matchState_t* const ms = &cctx->blockState.matchState; U32 const lastBlock = lastFrameChunk & (blockSizeMax >= remaining); - size_t const blockSize = ZSTD_optimalBlockSize(ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy, savings); + size_t const blockSize = ZSTD_optimalBlockSize(cctx, ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy, savings); assert(blockSize <= remaining); /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 3256905df..ba9dc6487 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -10,6 +10,7 @@ #include "../common/mem.h" /* S64 */ #include "../common/zstd_deps.h" /* ZSTD_memset */ +#include "../common/zstd_internal.h" /* ZSTD_STATIC_ASSERT */ #include "zstd_preSplit.h" @@ -30,22 +31,19 @@ static unsigned hash2(const void *p) } -/* ==================================== */ -/* Global array -> for testing only !!! */ -/* ==================================== */ typedef struct { int events[HASHTABLESIZE]; S64 nbEvents; } FingerPrint; -static FingerPrint pastEvents; -static FingerPrint newEvents; +typedef struct { + FingerPrint pastEvents; + FingerPrint newEvents; +} FPStats; -static void initStats(void) +static void initStats(FPStats* fpstats) { - ZSTD_memset(&pastEvents, 0, sizeof(pastEvents)); - ZSTD_memset(&newEvents, 0, sizeof(newEvents)); + ZSTD_memset(fpstats, 0, sizeof(FPStats)); } -/* ==================================== */ static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) { @@ -103,14 +101,14 @@ static void mergeEvents(FingerPrint* acc, const FingerPrint* newfp) acc->nbEvents += newfp->nbEvents; } -static void flushEvents(void) +static void flushEvents(FPStats* fpstats) { size_t n; for (n = 0; n < HASHTABLESIZE; n++) { - pastEvents.events[n] = newEvents.events[n]; + fpstats->pastEvents.events[n] = fpstats->newEvents.events[n]; } - pastEvents.nbEvents = newEvents.nbEvents; - ZSTD_memset(&newEvents, 0, sizeof(newEvents)); + fpstats->pastEvents.nbEvents = fpstats->newEvents.nbEvents; + ZSTD_memset(&fpstats->newEvents, 0, sizeof(fpstats->newEvents)); } static void removeEvents(FingerPrint* acc, const FingerPrint* slice) @@ -125,23 +123,30 @@ static void removeEvents(FingerPrint* acc, const FingerPrint* slice) #define CHUNKSIZE (8 << 10) /* Note: technically, we use CHUNKSIZE, so that's 8 KB */ -size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax) +size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, + size_t blockSizeMax, + void* workspace, size_t wkspSize) { + FPStats* const fpstats = (FPStats*)workspace; const char* p = (const char*)src; int penalty = THRESHOLD_PENALTY; size_t pos = 0; if (srcSize <= blockSizeMax) return srcSize; assert(blockSizeMax == (128 << 10)); + assert(workspace != NULL); + assert((size_t)workspace % 8 == 0); + ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE == sizeof(FPStats)); + assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; - initStats(); + initStats(fpstats); for (pos = 0; pos < blockSizeMax;) { assert(pos <= blockSizeMax - CHUNKSIZE); - recordFingerprint(&newEvents, p + pos, CHUNKSIZE); - if (compareFingerprints(&pastEvents, &newEvents, penalty)) { + recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE); + if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { return pos; } else { - mergeEvents(&pastEvents, &newEvents); - ZSTD_memset(&newEvents, 0, sizeof(newEvents)); + mergeEvents(&fpstats->pastEvents, &fpstats->newEvents); + ZSTD_memset(&fpstats->newEvents, 0, sizeof(fpstats->newEvents)); penalty = penalty - 1 + (penalty == 0); } pos += CHUNKSIZE; diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index 148fc1936..b0b6bb762 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -17,7 +17,13 @@ extern "C" { #endif -size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax); +#define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 + +/* note: + * @workspace must be aligned on 8-bytes boundaries + * @wkspSize must be at least >= ZSTD_SLIPBLOCK_WORKSPACESIZE + */ +size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax, void* workspace, size_t wkspSize); #if defined (__cplusplus) } From 433f4598ad96a4e661cfd877b50c9000ea174897 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 18 Oct 2024 11:16:49 -0700 Subject: [PATCH 408/937] fixed minor conversion warnings on Visual --- tests/zstreamtest.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 93032d21e..8df86d985 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -441,7 +441,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) size_t const gfhError = ZSTD_getFrameHeader(&fhi, cStart, cSize); if (gfhError!=0) goto _output_error; DISPLAYLEVEL(5, " (windowSize : %u) ", (unsigned)fhi.windowSize); - { size_t const s = ZSTD_estimateDStreamSize(fhi.windowSize) + { size_t const s = ZSTD_estimateDStreamSize((size_t)fhi.windowSize) /* uses ZSTD_initDStream_usingDict() */ + ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy); if (ZSTD_isError(s)) goto _output_error; @@ -1551,7 +1551,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : check dictionary FSE tables can represent every code : ", testNb++); { unsigned const kMaxWindowLog = 24; unsigned value; - ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1U << kMaxWindowLog, 1024); + ZSTD_compressionParameters cParams = ZSTD_getCParams(3, 1ULL << kMaxWindowLog, 1024); ZSTD_CDict* cdict; ZSTD_DDict* ddict; SEQ_stream seq = SEQ_initStream(0x87654321); From 4685eafa81d4c31048577aeb461883043ca96c2f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 18 Oct 2024 11:20:54 -0700 Subject: [PATCH 409/937] fix alignment test for non 64-bit systems --- lib/compress/zstd_preSplit.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index ba9dc6487..ceac5c91f 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -8,6 +8,7 @@ * You may select, at your option, one of the above-listed licenses. */ +#include "../common/compiler.h" /* ZSTD_ALIGNOF */ #include "../common/mem.h" /* S64 */ #include "../common/zstd_deps.h" /* ZSTD_memset */ #include "../common/zstd_internal.h" /* ZSTD_STATIC_ASSERT */ @@ -134,7 +135,7 @@ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, if (srcSize <= blockSizeMax) return srcSize; assert(blockSizeMax == (128 << 10)); assert(workspace != NULL); - assert((size_t)workspace % 8 == 0); + assert((size_t)workspace % ZSTD_ALIGNOF(FPStats) == 0); ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE == sizeof(FPStats)); assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; From cae8d13294904c0b6095a5533d0cda72d7e6a7ff Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 18 Oct 2024 16:00:36 -0700 Subject: [PATCH 410/937] splitter workspace is now provided by ZSTD_CCtx* --- lib/compress/zstd_compress.c | 59 ++++++++++++------------- lib/compress/zstd_compress_internal.h | 5 ++- lib/compress/zstd_compress_superblock.c | 4 +- lib/compress/zstd_cwksp.h | 36 ++++++++++----- 4 files changed, 60 insertions(+), 44 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 37b87336c..40d3afaae 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -137,11 +137,12 @@ ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize) ZSTD_cwksp_move(&cctx->workspace, &ws); cctx->staticSize = workspaceSize; - /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */ + /* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */ if (!ZSTD_cwksp_check_available(&cctx->workspace, ENTROPY_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL; cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); - cctx->entropyWorkspace = (U32*)ZSTD_cwksp_reserve_object(&cctx->workspace, ENTROPY_WORKSPACE_SIZE); + cctx->tmpWorkspace = ZSTD_cwksp_reserve_object_aligned(&cctx->workspace, TMP_WORKSPACE_SIZE, sizeof(S64)); + cctx->tmpWkspSize = TMP_WORKSPACE_SIZE; cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); return cctx; } @@ -1661,14 +1662,14 @@ ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams, + hSize * sizeof(U32) + h3Size * sizeof(U32); size_t const optPotentialSpace = - ZSTD_cwksp_aligned_alloc_size((MaxML+1) * sizeof(U32)) - + ZSTD_cwksp_aligned_alloc_size((MaxLL+1) * sizeof(U32)) - + ZSTD_cwksp_aligned_alloc_size((MaxOff+1) * sizeof(U32)) - + ZSTD_cwksp_aligned_alloc_size((1<strategy, useRowMatchFinder) - ? ZSTD_cwksp_aligned_alloc_size(hSize) + ? ZSTD_cwksp_aligned64_alloc_size(hSize) : 0; size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt)) ? optPotentialSpace @@ -1706,16 +1707,16 @@ static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal( size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize); size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer); size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize) - + ZSTD_cwksp_aligned_alloc_size(maxNbSeq * sizeof(seqDef)) + + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(seqDef)) + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE)); - size_t const entropySpace = ZSTD_cwksp_alloc_size(ENTROPY_WORKSPACE_SIZE); + size_t const tmpWorkSpace = ZSTD_cwksp_aligned_alloc_size(TMP_WORKSPACE_SIZE, sizeof(S64)); size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t)); size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1); size_t const ldmSpace = ZSTD_ldm_getTableSize(*ldmParams); size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(*ldmParams, blockSize); size_t const ldmSeqSpace = ldmParams->enableLdm == ZSTD_ps_enable ? - ZSTD_cwksp_aligned_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0; + ZSTD_cwksp_aligned64_alloc_size(maxNbLdmSeq * sizeof(rawSeq)) : 0; size_t const bufferSpace = ZSTD_cwksp_alloc_size(buffInSize) @@ -1725,12 +1726,12 @@ static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal( size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize); size_t const externalSeqSpace = useSequenceProducer - ? ZSTD_cwksp_aligned_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence)) + ? ZSTD_cwksp_aligned64_alloc_size(maxNbExternalSeq * sizeof(ZSTD_Sequence)) : 0; size_t const neededSpace = cctxSpace + - entropySpace + + tmpWorkSpace + blockStateSpace + ldmSpace + ldmSeqSpace + @@ -2166,15 +2167,16 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, DEBUGLOG(5, "reserving object space"); /* Statically sized space. - * entropyWorkspace never moves, + * tmpWorkspace never moves, * though prev/next block swap places */ assert(ZSTD_cwksp_check_available(ws, 2 * sizeof(ZSTD_compressedBlockState_t))); zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t)); RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock"); zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t)); RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock"); - zc->entropyWorkspace = (U32*) ZSTD_cwksp_reserve_object(ws, ENTROPY_WORKSPACE_SIZE); - RETURN_ERROR_IF(zc->entropyWorkspace == NULL, memory_allocation, "couldn't allocate entropyWorkspace"); + zc->tmpWorkspace = ZSTD_cwksp_reserve_object_aligned(ws, TMP_WORKSPACE_SIZE, sizeof(S64)); + RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace"); + zc->tmpWkspSize = TMP_WORKSPACE_SIZE; } } ZSTD_cwksp_clear(ws); @@ -3894,14 +3896,14 @@ ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t* seqStore, ZSTD_CC &zc->blockState.nextCBlock->entropy, &zc->appliedParams, entropyMetadata, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE), ""); + zc->tmpWorkspace, zc->tmpWkspSize), ""); return ZSTD_estimateBlockSize( seqStore->litStart, (size_t)(seqStore->lit - seqStore->litStart), seqStore->ofCode, seqStore->llCode, seqStore->mlCode, (size_t)(seqStore->sequences - seqStore->sequencesStart), &zc->blockState.nextCBlock->entropy, entropyMetadata, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE, + zc->tmpWorkspace, zc->tmpWkspSize, (int)(entropyMetadata->hufMetadata.hType == set_compressed), 1); } @@ -4067,7 +4069,7 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, &zc->appliedParams, op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize, srcSize, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */, + zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */, zc->bmi2); FORWARD_IF_ERROR(cSeqsSize, "ZSTD_entropyCompressSeqStore failed!"); @@ -4357,7 +4359,7 @@ ZSTD_compressBlock_internal(ZSTD_CCtx* zc, &zc->appliedParams, dst, dstCapacity, srcSize, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */, + zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */, zc->bmi2); if (frame && @@ -4489,20 +4491,17 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, #include "zstd_preSplit.h" - static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { - S64 workspace[ZSTD_SLIPBLOCK_WORKSPACESIZE / 8]; - (void)cctx; - /* note: we currenly only split full blocks (128 KB) - * and when there is more than 128 KB input remaining + /* note: conservatively only split full blocks (128 KB) currently, + * and even then only if there is more than 128 KB input remaining. */ if (srcSize <= 128 KB || blockSizeMax < 128 KB) return MIN(srcSize, blockSizeMax); /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for btlazy2+ strategies */ if (strat >= ZSTD_btlazy2) - return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax, workspace, sizeof(workspace)); + return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy * no cpu cost, but can over-split homegeneous data. * heuristic, tested as being "generally better". @@ -5174,11 +5173,11 @@ static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx, cctx->blockState.prevCBlock, &cctx->blockState.matchState, &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, cdict->dictContent, cdict->dictContentSize, cdict->dictContentType, dtlm, - ZSTD_tfp_forCCtx, cctx->entropyWorkspace) + ZSTD_tfp_forCCtx, cctx->tmpWorkspace) : ZSTD_compress_insertDictionary( cctx->blockState.prevCBlock, &cctx->blockState.matchState, &cctx->ldmState, &cctx->workspace, &cctx->appliedParams, dict, dictSize, - dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->entropyWorkspace); + dictContentType, dtlm, ZSTD_tfp_forCCtx, cctx->tmpWorkspace); FORWARD_IF_ERROR(dictID, "ZSTD_compress_insertDictionary failed"); assert(dictID <= UINT_MAX); cctx->dictID = (U32)dictID; @@ -6876,7 +6875,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, &cctx->appliedParams, op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, blockSize, - cctx->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */, + cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, cctx->bmi2); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 042b5e5ca..e76bbda71 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -24,6 +24,7 @@ # include "zstdmt_compress.h" #endif #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */ +#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */ #if defined (__cplusplus) extern "C" { @@ -376,6 +377,7 @@ struct ZSTD_CCtx_params_s { #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2)) #define ENTROPY_WORKSPACE_SIZE (HUF_WORKSPACE_SIZE + COMPRESS_SEQUENCES_WORKSPACE_SIZE) +#define TMP_WORKSPACE_SIZE (MAX(ENTROPY_WORKSPACE_SIZE, ZSTD_SLIPBLOCK_WORKSPACESIZE)) /** * Indicates whether this compression proceeds directly from user-provided @@ -432,7 +434,8 @@ struct ZSTD_CCtx_s { size_t maxNbLdmSequences; rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */ ZSTD_blockState_t blockState; - U32* entropyWorkspace; /* entropy workspace of ENTROPY_WORKSPACE_SIZE bytes */ + void* tmpWorkspace; /* used as substitute of stack space - must be aligned for S64 type */ + size_t tmpWkspSize; /* Whether we are streaming or not */ ZSTD_buffered_policy_e bufferedPolicy; diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index 628a2dccd..97321bc76 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -674,7 +674,7 @@ size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc, &zc->blockState.nextCBlock->entropy, &zc->appliedParams, &entropyMetadata, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */), ""); + zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */), ""); return ZSTD_compressSubBlock_multi(&zc->seqStore, zc->blockState.prevCBlock, @@ -684,5 +684,5 @@ size_t ZSTD_compressSuperBlock(ZSTD_CCtx* zc, dst, dstCapacity, src, srcSize, zc->bmi2, lastBlock, - zc->entropyWorkspace, ENTROPY_WORKSPACE_SIZE /* statically allocated in resetCCtx */); + zc->tmpWorkspace, zc->tmpWkspSize /* statically allocated in resetCCtx */); } diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index dcd485cb5..239fcf6d2 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -222,7 +222,7 @@ MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t const align) { * to figure out how much space you need for the matchState tables. Everything * else is though. * - * Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned_alloc_size(). + * Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned64_alloc_size(). */ MEM_STATIC size_t ZSTD_cwksp_alloc_size(size_t size) { if (size == 0) @@ -234,12 +234,16 @@ MEM_STATIC size_t ZSTD_cwksp_alloc_size(size_t size) { #endif } +MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size, size_t alignment) { + return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, alignment)); +} + /** * Returns an adjusted alloc size that is the nearest larger multiple of 64 bytes. * Used to determine the number of bytes required for a given "aligned". */ -MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size) { - return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, ZSTD_CWKSP_ALIGNMENT_BYTES)); +MEM_STATIC size_t ZSTD_cwksp_aligned64_alloc_size(size_t size) { + return ZSTD_cwksp_aligned_alloc_size(size, ZSTD_CWKSP_ALIGNMENT_BYTES); } /** @@ -272,7 +276,7 @@ MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignByt * which we can allocate from the end of the workspace. */ MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws) { - return (void*)((size_t)ws->workspaceEnd & ~(ZSTD_CWKSP_ALIGNMENT_BYTES-1)); + return (void*)((size_t)ws->workspaceEnd & (size_t)~(ZSTD_CWKSP_ALIGNMENT_BYTES-1)); } /** @@ -426,8 +430,9 @@ MEM_STATIC void* ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp* ws, size_t byt */ MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes) { - void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES), - ZSTD_cwksp_alloc_aligned); + void* const ptr = ZSTD_cwksp_reserve_internal(ws, + ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES), + ZSTD_cwksp_alloc_aligned); assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0); return ptr; } @@ -479,12 +484,12 @@ MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes) } /** - * Aligned on sizeof(void*). * Note : should happen only once, at workspace first initialization */ -MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) +MEM_STATIC void* +ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t bytes, size_t alignment) { - size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*)); + size_t const roundedBytes = ZSTD_cwksp_align(bytes, alignment); void* alloc = ws->objectEnd; void* end = (BYTE*)alloc + roundedBytes; @@ -496,8 +501,8 @@ MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) DEBUGLOG(4, "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining", alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes); - assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0); - assert(bytes % ZSTD_ALIGNOF(void*) == 0); + assert((size_t)alloc % alignment == 0); + assert(bytes % alignment == 0); ZSTD_cwksp_assert_internal_consistency(ws); /* we must be in the first phase, no advance is possible */ if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) { @@ -521,6 +526,15 @@ MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) return alloc; } +/** + * Aligned on sizeof(void*). + * Note : should happen only once, at workspace first initialization + */ +MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) +{ + return ZSTD_cwksp_reserve_object_aligned(ws, bytes, sizeof(void*)); +} + MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws) { DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty"); From 4ce91cbf2bfecefcd99973a5e68711c388684d41 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 18 Oct 2024 16:47:41 -0700 Subject: [PATCH 411/937] fixed workspace alignment on non 64-bit systems --- lib/common/compiler.h | 2 ++ lib/compress/zstd_compress.c | 22 ++++++++++----------- lib/compress/zstd_cwksp.h | 37 ++++++++++++++++++++---------------- 3 files changed, 34 insertions(+), 27 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index fdf0dd18a..f4caeb5c0 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -278,6 +278,8 @@ * Alignment check *****************************************************************/ +#define ZSTD_IS_POWER_2(a) (((a) & ((a)-1)) == 0) + /* this test was initially positioned in mem.h, * but this file is removed (or replaced) for linux kernel * so it's now hosted in compiler.h, diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 40d3afaae..fcef55bf1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2032,7 +2032,7 @@ ZSTD_reset_matchState(ZSTD_matchState_t* ms, ZSTD_advanceHashSalt(ms); } else { /* When we are not salting we want to always memset the memory */ - ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned(ws, tagTableSize); + ms->tagTable = (BYTE*) ZSTD_cwksp_reserve_aligned64(ws, tagTableSize); ZSTD_memset(ms->tagTable, 0, tagTableSize); ms->hashSalt = 0; } @@ -2046,12 +2046,12 @@ ZSTD_reset_matchState(ZSTD_matchState_t* ms, /* opt parser space */ if ((forWho == ZSTD_resetTarget_CCtx) && (cParams->strategy >= ZSTD_btopt)) { DEBUGLOG(4, "reserving optimal parser space"); - ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (1<opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxLL+1) * sizeof(unsigned)); - ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxML+1) * sizeof(unsigned)); - ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned(ws, (MaxOff+1) * sizeof(unsigned)); - ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t)); - ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t)); + ms->opt.litFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (1<opt.litLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxLL+1) * sizeof(unsigned)); + ms->opt.matchLengthFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxML+1) * sizeof(unsigned)); + ms->opt.offCodeFreq = (unsigned*)ZSTD_cwksp_reserve_aligned64(ws, (MaxOff+1) * sizeof(unsigned)); + ms->opt.matchTable = (ZSTD_match_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_match_t)); + ms->opt.priceTable = (ZSTD_optimal_t*)ZSTD_cwksp_reserve_aligned64(ws, ZSTD_OPT_SIZE * sizeof(ZSTD_optimal_t)); } ms->cParams = *cParams; @@ -2209,15 +2209,15 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, needsIndexReset, ZSTD_resetTarget_CCtx), ""); - zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned(ws, maxNbSeq * sizeof(seqDef)); + zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(seqDef)); /* ldm hash table */ if (params->ldmParams.enableLdm == ZSTD_ps_enable) { /* TODO: avoid memset? */ size_t const ldmHSize = ((size_t)1) << params->ldmParams.hashLog; - zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned(ws, ldmHSize * sizeof(ldmEntry_t)); + zc->ldmState.hashTable = (ldmEntry_t*)ZSTD_cwksp_reserve_aligned64(ws, ldmHSize * sizeof(ldmEntry_t)); ZSTD_memset(zc->ldmState.hashTable, 0, ldmHSize * sizeof(ldmEntry_t)); - zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned(ws, maxNbLdmSeq * sizeof(rawSeq)); + zc->ldmSequences = (rawSeq*)ZSTD_cwksp_reserve_aligned64(ws, maxNbLdmSeq * sizeof(rawSeq)); zc->maxNbLdmSequences = maxNbLdmSeq; ZSTD_window_init(&zc->ldmState.window); @@ -2229,7 +2229,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, size_t const maxNbExternalSeq = ZSTD_sequenceBound(blockSize); zc->extSeqBufCapacity = maxNbExternalSeq; zc->extSeqBuf = - (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence)); + (ZSTD_Sequence*)ZSTD_cwksp_reserve_aligned64(ws, maxNbExternalSeq * sizeof(ZSTD_Sequence)); } /* buffers */ diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index 239fcf6d2..dc0142098 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -206,9 +206,9 @@ MEM_STATIC void ZSTD_cwksp_assert_internal_consistency(ZSTD_cwksp* ws) { /** * Align must be a power of 2. */ -MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t const align) { +MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t align) { size_t const mask = align - 1; - assert((align & mask) == 0); + assert(ZSTD_IS_POWER_2(align)); return (size + mask) & ~mask; } @@ -266,7 +266,7 @@ MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void) { MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignBytes) { size_t const alignBytesMask = alignBytes - 1; size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask; - assert((alignBytes & alignBytesMask) == 0); + assert(ZSTD_IS_POWER_2(alignBytes)); assert(bytes < alignBytes); return bytes; } @@ -408,7 +408,7 @@ MEM_STATIC void* ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp* ws, size_t byt { size_t const alignedBytes = ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES); void* ptr = ZSTD_cwksp_reserve_internal(ws, alignedBytes, ZSTD_cwksp_alloc_aligned_init_once); - assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0); + assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0); if(ptr && ptr < ws->initOnceStart) { /* We assume the memory following the current allocation is either: * 1. Not usable as initOnce memory (end of workspace) @@ -428,12 +428,12 @@ MEM_STATIC void* ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp* ws, size_t byt /** * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes). */ -MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes) +MEM_STATIC void* ZSTD_cwksp_reserve_aligned64(ZSTD_cwksp* ws, size_t bytes) { void* const ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES), ZSTD_cwksp_alloc_aligned); - assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0); + assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0); return ptr; } @@ -479,17 +479,17 @@ MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes) #endif assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0); - assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0); + assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0); return alloc; } /** + * Aligned on sizeof(void*). * Note : should happen only once, at workspace first initialization */ -MEM_STATIC void* -ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t bytes, size_t alignment) +MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) { - size_t const roundedBytes = ZSTD_cwksp_align(bytes, alignment); + size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*)); void* alloc = ws->objectEnd; void* end = (BYTE*)alloc + roundedBytes; @@ -501,8 +501,8 @@ ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t bytes, size_t alignment DEBUGLOG(4, "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining", alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes); - assert((size_t)alloc % alignment == 0); - assert(bytes % alignment == 0); + assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0); + assert(bytes % ZSTD_ALIGNOF(void*) == 0); ZSTD_cwksp_assert_internal_consistency(ws); /* we must be in the first phase, no advance is possible */ if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) { @@ -525,14 +525,19 @@ ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t bytes, size_t alignment return alloc; } - /** - * Aligned on sizeof(void*). + * with alignment control * Note : should happen only once, at workspace first initialization */ -MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes) +MEM_STATIC void* ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t byteSize, size_t alignment) { - return ZSTD_cwksp_reserve_object_aligned(ws, bytes, sizeof(void*)); + size_t const mask = alignment - 1; + size_t const surplus = (alignment > sizeof(void*)) ? alignment - sizeof(void*) : 0; + void* const start = ZSTD_cwksp_reserve_object(ws, byteSize + surplus); + if (start == NULL) return NULL; + if (surplus == 0) return start; + assert(ZSTD_IS_POWER_2(alignment)); + return (void*)(((size_t)start + surplus) & ~mask); } MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws) From dac26eaeac5f500a3dd2ada7f51fbdbf937ce2ac Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 20 Oct 2024 17:07:43 -0700 Subject: [PATCH 412/937] updated regression test results --- tests/regression/results.csv | 914 +++++++++++++++++------------------ 1 file changed, 457 insertions(+), 457 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index e39abd66d..b32db43de 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -1,63 +1,63 @@ Data, Config, Method, Total compressed size -silesia.tar, level -5, compress simple, 6861055 -silesia.tar, level -3, compress simple, 6505483 -silesia.tar, level -1, compress simple, 6179047 -silesia.tar, level 0, compress simple, 4851407 -silesia.tar, level 1, compress simple, 5327717 -silesia.tar, level 3, compress simple, 4851407 -silesia.tar, level 4, compress simple, 4788821 -silesia.tar, level 5, compress simple, 4679004 -silesia.tar, level 6, compress simple, 4614561 -silesia.tar, level 7, compress simple, 4579828 -silesia.tar, level 9, compress simple, 4555448 -silesia.tar, level 13, compress simple, 4502956 -silesia.tar, level 16, compress simple, 4360385 -silesia.tar, level 19, compress simple, 4260939 -silesia.tar, uncompressed literals, compress simple, 4851407 -silesia.tar, uncompressed literals optimal, compress simple, 4260939 -silesia.tar, huffman literals, compress simple, 6179047 -github.tar, level -5, compress simple, 52115 -github.tar, level -3, compress simple, 45678 -github.tar, level -1, compress simple, 42560 -github.tar, level 0, compress simple, 38884 -github.tar, level 1, compress simple, 39200 -github.tar, level 3, compress simple, 38884 -github.tar, level 4, compress simple, 38880 -github.tar, level 5, compress simple, 39651 -github.tar, level 6, compress simple, 39282 -github.tar, level 7, compress simple, 38005 -github.tar, level 9, compress simple, 36723 +silesia.tar, level -5, compress simple, 6860782 +silesia.tar, level -3, compress simple, 6507448 +silesia.tar, level -1, compress simple, 6175582 +silesia.tar, level 0, compress simple, 4843429 +silesia.tar, level 1, compress simple, 5316794 +silesia.tar, level 3, compress simple, 4843429 +silesia.tar, level 4, compress simple, 4780657 +silesia.tar, level 5, compress simple, 4669650 +silesia.tar, level 6, compress simple, 4604925 +silesia.tar, level 7, compress simple, 4570873 +silesia.tar, level 9, compress simple, 4546477 +silesia.tar, level 13, compress simple, 4486256 +silesia.tar, level 16, compress simple, 4355572 +silesia.tar, level 19, compress simple, 4257629 +silesia.tar, uncompressed literals, compress simple, 4843429 +silesia.tar, uncompressed literals optimal, compress simple, 4257629 +silesia.tar, huffman literals, compress simple, 6175582 +github.tar, level -5, compress simple, 52320 +github.tar, level -3, compress simple, 45823 +github.tar, level -1, compress simple, 42740 +github.tar, level 0, compress simple, 39073 +github.tar, level 1, compress simple, 39444 +github.tar, level 3, compress simple, 39073 +github.tar, level 4, compress simple, 39068 +github.tar, level 5, compress simple, 39808 +github.tar, level 6, compress simple, 39455 +github.tar, level 7, compress simple, 38168 +github.tar, level 9, compress simple, 36897 github.tar, level 13, compress simple, 35501 github.tar, level 16, compress simple, 40466 github.tar, level 19, compress simple, 32262 -github.tar, uncompressed literals, compress simple, 38884 +github.tar, uncompressed literals, compress simple, 39073 github.tar, uncompressed literals optimal, compress simple, 32262 -github.tar, huffman literals, compress simple, 42560 -silesia, level -5, compress cctx, 6857372 -silesia, level -3, compress cctx, 6503412 -silesia, level -1, compress cctx, 6172202 -silesia, level 0, compress cctx, 4839431 -silesia, level 1, compress cctx, 5306632 -silesia, level 3, compress cctx, 4839431 -silesia, level 4, compress cctx, 4776557 -silesia, level 5, compress cctx, 4667668 -silesia, level 6, compress cctx, 4604351 -silesia, level 7, compress cctx, 4570271 -silesia, level 9, compress cctx, 4545850 -silesia, level 13, compress cctx, 4493990 -silesia, level 16, compress cctx, 4359652 -silesia, level 19, compress cctx, 4266582 -silesia, long distance mode, compress cctx, 4839431 -silesia, multithreaded, compress cctx, 4839431 -silesia, multithreaded long distance mode, compress cctx, 4839431 +github.tar, huffman literals, compress simple, 42740 +silesia, level -5, compress cctx, 6857776 +silesia, level -3, compress cctx, 6504756 +silesia, level -1, compress cctx, 6174127 +silesia, level 0, compress cctx, 4838417 +silesia, level 1, compress cctx, 5306931 +silesia, level 3, compress cctx, 4838417 +silesia, level 4, compress cctx, 4775359 +silesia, level 5, compress cctx, 4666524 +silesia, level 6, compress cctx, 4602031 +silesia, level 7, compress cctx, 4567954 +silesia, level 9, compress cctx, 4543669 +silesia, level 13, compress cctx, 4484875 +silesia, level 16, compress cctx, 4356207 +silesia, level 19, compress cctx, 4266751 +silesia, long distance mode, compress cctx, 4838417 +silesia, multithreaded, compress cctx, 4838417 +silesia, multithreaded long distance mode, compress cctx, 4838417 silesia, small window log, compress cctx, 7082907 -silesia, small hash log, compress cctx, 6526141 -silesia, small chain log, compress cctx, 4912197 -silesia, explicit params, compress cctx, 4794318 -silesia, uncompressed literals, compress cctx, 4839431 -silesia, uncompressed literals optimal, compress cctx, 4266582 -silesia, huffman literals, compress cctx, 6172202 -silesia, multithreaded with advanced params, compress cctx, 4839431 +silesia, small hash log, compress cctx, 6524931 +silesia, small chain log, compress cctx, 4912322 +silesia, explicit params, compress cctx, 4792640 +silesia, uncompressed literals, compress cctx, 4838417 +silesia, uncompressed literals optimal, compress cctx, 4266751 +silesia, huffman literals, compress cctx, 6174127 +silesia, multithreaded with advanced params, compress cctx, 4838417 github, level -5, compress cctx, 204407 github, level -5 with dict, compress cctx, 47581 github, level -3, compress cctx, 193253 @@ -97,57 +97,57 @@ github, uncompressed literals, compress github, uncompressed literals optimal, compress cctx, 132879 github, huffman literals, compress cctx, 175468 github, multithreaded with advanced params, compress cctx, 141069 -silesia, level -5, zstdcli, 6857420 -silesia, level -3, zstdcli, 6503460 -silesia, level -1, zstdcli, 6172250 -silesia, level 0, zstdcli, 4839479 -silesia, level 1, zstdcli, 5306680 -silesia, level 3, zstdcli, 4839479 -silesia, level 4, zstdcli, 4776605 -silesia, level 5, zstdcli, 4667716 -silesia, level 6, zstdcli, 4604399 -silesia, level 7, zstdcli, 4570319 -silesia, level 9, zstdcli, 4545898 -silesia, level 13, zstdcli, 4494038 -silesia, level 16, zstdcli, 4359700 -silesia, level 19, zstdcli, 4266630 -silesia, long distance mode, zstdcli, 4831224 -silesia, multithreaded, zstdcli, 4839479 -silesia, multithreaded long distance mode, zstdcli, 4831224 +silesia, level -5, zstdcli, 6856076 +silesia, level -3, zstdcli, 6505583 +silesia, level -1, zstdcli, 6172652 +silesia, level 0, zstdcli, 4838997 +silesia, level 1, zstdcli, 5306179 +silesia, level 3, zstdcli, 4838997 +silesia, level 4, zstdcli, 4775769 +silesia, level 5, zstdcli, 4666931 +silesia, level 6, zstdcli, 4602509 +silesia, level 7, zstdcli, 4568265 +silesia, level 9, zstdcli, 4544068 +silesia, level 13, zstdcli, 4484443 +silesia, level 16, zstdcli, 4357591 +silesia, level 19, zstdcli, 4266865 +silesia, long distance mode, zstdcli, 4830467 +silesia, multithreaded, zstdcli, 4838997 +silesia, multithreaded long distance mode, zstdcli, 4830467 silesia, small window log, zstdcli, 7094528 -silesia, small hash log, zstdcli, 6526189 -silesia, small chain log, zstdcli, 4912245 -silesia, explicit params, zstdcli, 4795840 -silesia, uncompressed literals, zstdcli, 5117005 -silesia, uncompressed literals optimal, zstdcli, 4316928 -silesia, huffman literals, zstdcli, 5321417 -silesia, multithreaded with advanced params, zstdcli, 5117005 -silesia.tar, level -5, zstdcli, 6862049 -silesia.tar, level -3, zstdcli, 6506509 -silesia.tar, level -1, zstdcli, 6179789 -silesia.tar, level 0, zstdcli, 4851482 -silesia.tar, level 1, zstdcli, 5329010 -silesia.tar, level 3, zstdcli, 4851482 -silesia.tar, level 4, zstdcli, 4789729 -silesia.tar, level 5, zstdcli, 4679860 -silesia.tar, level 6, zstdcli, 4615355 -silesia.tar, level 7, zstdcli, 4581791 -silesia.tar, level 9, zstdcli, 4555452 -silesia.tar, level 13, zstdcli, 4502960 -silesia.tar, level 16, zstdcli, 4360389 -silesia.tar, level 19, zstdcli, 4260943 -silesia.tar, no source size, zstdcli, 4851478 -silesia.tar, long distance mode, zstdcli, 4843159 -silesia.tar, multithreaded, zstdcli, 4851482 -silesia.tar, multithreaded long distance mode, zstdcli, 4843159 +silesia, small hash log, zstdcli, 6526639 +silesia, small chain log, zstdcli, 4911746 +silesia, explicit params, zstdcli, 4794378 +silesia, uncompressed literals, zstdcli, 5117843 +silesia, uncompressed literals optimal, zstdcli, 4317311 +silesia, huffman literals, zstdcli, 5320793 +silesia, multithreaded with advanced params, zstdcli, 5117843 +silesia.tar, level -5, zstdcli, 6860173 +silesia.tar, level -3, zstdcli, 6507196 +silesia.tar, level -1, zstdcli, 6177719 +silesia.tar, level 0, zstdcli, 4841906 +silesia.tar, level 1, zstdcli, 5313917 +silesia.tar, level 3, zstdcli, 4841906 +silesia.tar, level 4, zstdcli, 4780121 +silesia.tar, level 5, zstdcli, 4671144 +silesia.tar, level 6, zstdcli, 4606407 +silesia.tar, level 7, zstdcli, 4572666 +silesia.tar, level 9, zstdcli, 4546557 +silesia.tar, level 13, zstdcli, 4491076 +silesia.tar, level 16, zstdcli, 4356959 +silesia.tar, level 19, zstdcli, 4259787 +silesia.tar, no source size, zstdcli, 4841902 +silesia.tar, long distance mode, zstdcli, 4834266 +silesia.tar, multithreaded, zstdcli, 4841906 +silesia.tar, multithreaded long distance mode, zstdcli, 4834266 silesia.tar, small window log, zstdcli, 7100110 -silesia.tar, small hash log, zstdcli, 6529264 -silesia.tar, small chain log, zstdcli, 4917022 -silesia.tar, explicit params, zstdcli, 4821112 -silesia.tar, uncompressed literals, zstdcli, 5118944 -silesia.tar, uncompressed literals optimal, zstdcli, 4308455 -silesia.tar, huffman literals, zstdcli, 5342074 -silesia.tar, multithreaded with advanced params, zstdcli, 5118944 +silesia.tar, small hash log, zstdcli, 6530007 +silesia.tar, small chain log, zstdcli, 4916091 +silesia.tar, explicit params, zstdcli, 4809323 +silesia.tar, uncompressed literals, zstdcli, 5116446 +silesia.tar, uncompressed literals optimal, zstdcli, 4306844 +silesia.tar, huffman literals, zstdcli, 5326463 +silesia.tar, multithreaded with advanced params, zstdcli, 5116446 github, level -5, zstdcli, 206407 github, level -5 with dict, zstdcli, 47832 github, level -3, zstdcli, 195253 @@ -187,115 +187,115 @@ github, uncompressed literals, zstdcli, github, uncompressed literals optimal, zstdcli, 154667 github, huffman literals, zstdcli, 144365 github, multithreaded with advanced params, zstdcli, 167909 -github.tar, level -5, zstdcli, 52119 -github.tar, level -5 with dict, zstdcli, 51101 -github.tar, level -3, zstdcli, 45682 -github.tar, level -3 with dict, zstdcli, 44738 -github.tar, level -1, zstdcli, 42564 -github.tar, level -1 with dict, zstdcli, 41357 -github.tar, level 0, zstdcli, 38888 -github.tar, level 0 with dict, zstdcli, 37999 -github.tar, level 1, zstdcli, 39204 -github.tar, level 1 with dict, zstdcli, 38123 -github.tar, level 3, zstdcli, 38888 -github.tar, level 3 with dict, zstdcli, 37999 -github.tar, level 4, zstdcli, 38884 -github.tar, level 4 with dict, zstdcli, 37952 -github.tar, level 5, zstdcli, 39655 -github.tar, level 5 with dict, zstdcli, 39073 -github.tar, level 6, zstdcli, 39286 -github.tar, level 6 with dict, zstdcli, 38647 -github.tar, level 7, zstdcli, 38009 -github.tar, level 7 with dict, zstdcli, 37861 -github.tar, level 9, zstdcli, 36727 -github.tar, level 9 with dict, zstdcli, 36686 +github.tar, level -5, zstdcli, 52308 +github.tar, level -5 with dict, zstdcli, 51318 +github.tar, level -3, zstdcli, 45815 +github.tar, level -3 with dict, zstdcli, 44883 +github.tar, level -1, zstdcli, 42688 +github.tar, level -1 with dict, zstdcli, 41510 +github.tar, level 0, zstdcli, 39071 +github.tar, level 0 with dict, zstdcli, 38140 +github.tar, level 1, zstdcli, 39404 +github.tar, level 1 with dict, zstdcli, 38320 +github.tar, level 3, zstdcli, 39071 +github.tar, level 3 with dict, zstdcli, 38140 +github.tar, level 4, zstdcli, 39067 +github.tar, level 4 with dict, zstdcli, 38082 +github.tar, level 5, zstdcli, 39815 +github.tar, level 5 with dict, zstdcli, 39221 +github.tar, level 6, zstdcli, 39455 +github.tar, level 6 with dict, zstdcli, 38787 +github.tar, level 7, zstdcli, 38177 +github.tar, level 7 with dict, zstdcli, 38009 +github.tar, level 9, zstdcli, 36893 +github.tar, level 9 with dict, zstdcli, 36827 github.tar, level 13, zstdcli, 35505 github.tar, level 13 with dict, zstdcli, 37134 github.tar, level 16, zstdcli, 40470 github.tar, level 16 with dict, zstdcli, 33379 github.tar, level 19, zstdcli, 32266 github.tar, level 19 with dict, zstdcli, 32705 -github.tar, no source size, zstdcli, 38885 -github.tar, no source size with dict, zstdcli, 38115 -github.tar, long distance mode, zstdcli, 40227 -github.tar, multithreaded, zstdcli, 38888 -github.tar, multithreaded long distance mode, zstdcli, 40227 +github.tar, no source size, zstdcli, 39068 +github.tar, no source size with dict, zstdcli, 38274 +github.tar, long distance mode, zstdcli, 40381 +github.tar, multithreaded, zstdcli, 39071 +github.tar, multithreaded long distance mode, zstdcli, 40381 github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 -github.tar, explicit params, zstdcli, 41385 -github.tar, uncompressed literals, zstdcli, 41566 +github.tar, explicit params, zstdcli, 41588 +github.tar, uncompressed literals, zstdcli, 41704 github.tar, uncompressed literals optimal, zstdcli, 35360 -github.tar, huffman literals, zstdcli, 38857 -github.tar, multithreaded with advanced params, zstdcli, 41566 -silesia, level -5, advanced one pass, 6857372 -silesia, level -3, advanced one pass, 6503412 -silesia, level -1, advanced one pass, 6172202 -silesia, level 0, advanced one pass, 4839431 -silesia, level 1, advanced one pass, 5306632 -silesia, level 3, advanced one pass, 4839431 -silesia, level 4, advanced one pass, 4776557 -silesia, level 5 row 1, advanced one pass, 4667668 -silesia, level 5 row 2, advanced one pass, 4670326 -silesia, level 5, advanced one pass, 4667668 -silesia, level 6, advanced one pass, 4604351 -silesia, level 7 row 1, advanced one pass, 4570271 -silesia, level 7 row 2, advanced one pass, 4565169 -silesia, level 7, advanced one pass, 4570271 -silesia, level 9, advanced one pass, 4545850 -silesia, level 11 row 1, advanced one pass, 4505658 -silesia, level 11 row 2, advanced one pass, 4503429 -silesia, level 12 row 1, advanced one pass, 4505658 -silesia, level 12 row 2, advanced one pass, 4503429 -silesia, level 13, advanced one pass, 4493990 -silesia, level 16, advanced one pass, 4359652 -silesia, level 19, advanced one pass, 4266582 -silesia, no source size, advanced one pass, 4839431 -silesia, long distance mode, advanced one pass, 4831158 -silesia, multithreaded, advanced one pass, 4839431 -silesia, multithreaded long distance mode, advanced one pass, 4831176 +github.tar, huffman literals, zstdcli, 39046 +github.tar, multithreaded with advanced params, zstdcli, 41704 +silesia, level -5, advanced one pass, 6857776 +silesia, level -3, advanced one pass, 6504756 +silesia, level -1, advanced one pass, 6174127 +silesia, level 0, advanced one pass, 4838417 +silesia, level 1, advanced one pass, 5306931 +silesia, level 3, advanced one pass, 4838417 +silesia, level 4, advanced one pass, 4775359 +silesia, level 5 row 1, advanced one pass, 4666524 +silesia, level 5 row 2, advanced one pass, 4668976 +silesia, level 5, advanced one pass, 4666524 +silesia, level 6, advanced one pass, 4602031 +silesia, level 7 row 1, advanced one pass, 4567954 +silesia, level 7 row 2, advanced one pass, 4562774 +silesia, level 7, advanced one pass, 4567954 +silesia, level 9, advanced one pass, 4543669 +silesia, level 11 row 1, advanced one pass, 4503577 +silesia, level 11 row 2, advanced one pass, 4501229 +silesia, level 12 row 1, advanced one pass, 4503577 +silesia, level 12 row 2, advanced one pass, 4501229 +silesia, level 13, advanced one pass, 4484875 +silesia, level 16, advanced one pass, 4356207 +silesia, level 19, advanced one pass, 4266751 +silesia, no source size, advanced one pass, 4838417 +silesia, long distance mode, advanced one pass, 4830097 +silesia, multithreaded, advanced one pass, 4838949 +silesia, multithreaded long distance mode, advanced one pass, 4830419 silesia, small window log, advanced one pass, 7094480 -silesia, small hash log, advanced one pass, 6526141 -silesia, small chain log, advanced one pass, 4912197 -silesia, explicit params, advanced one pass, 4795840 -silesia, uncompressed literals, advanced one pass, 5116957 -silesia, uncompressed literals optimal, advanced one pass, 4316880 -silesia, huffman literals, advanced one pass, 5321369 -silesia, multithreaded with advanced params, advanced one pass, 5116957 -silesia.tar, level -5, advanced one pass, 6861055 -silesia.tar, level -3, advanced one pass, 6505483 -silesia.tar, level -1, advanced one pass, 6179047 -silesia.tar, level 0, advanced one pass, 4851407 -silesia.tar, level 1, advanced one pass, 5327717 -silesia.tar, level 3, advanced one pass, 4851407 -silesia.tar, level 4, advanced one pass, 4788821 -silesia.tar, level 5 row 1, advanced one pass, 4679004 -silesia.tar, level 5 row 2, advanced one pass, 4682334 -silesia.tar, level 5, advanced one pass, 4679004 -silesia.tar, level 6, advanced one pass, 4614561 -silesia.tar, level 7 row 1, advanced one pass, 4579828 -silesia.tar, level 7 row 2, advanced one pass, 4575602 -silesia.tar, level 7, advanced one pass, 4579828 -silesia.tar, level 9, advanced one pass, 4555448 -silesia.tar, level 11 row 1, advanced one pass, 4514962 -silesia.tar, level 11 row 2, advanced one pass, 4513816 -silesia.tar, level 12 row 1, advanced one pass, 4514517 -silesia.tar, level 12 row 2, advanced one pass, 4514007 -silesia.tar, level 13, advanced one pass, 4502956 -silesia.tar, level 16, advanced one pass, 4360385 -silesia.tar, level 19, advanced one pass, 4260939 -silesia.tar, no source size, advanced one pass, 4851407 -silesia.tar, long distance mode, advanced one pass, 4837775 -silesia.tar, multithreaded, advanced one pass, 4851478 -silesia.tar, multithreaded long distance mode, advanced one pass, 4843155 +silesia, small hash log, advanced one pass, 6524931 +silesia, small chain log, advanced one pass, 4912322 +silesia, explicit params, advanced one pass, 4794219 +silesia, uncompressed literals, advanced one pass, 5117482 +silesia, uncompressed literals optimal, advanced one pass, 4317186 +silesia, huffman literals, advanced one pass, 5321686 +silesia, multithreaded with advanced params, advanced one pass, 5117795 +silesia.tar, level -5, advanced one pass, 6860782 +silesia.tar, level -3, advanced one pass, 6507448 +silesia.tar, level -1, advanced one pass, 6175582 +silesia.tar, level 0, advanced one pass, 4843429 +silesia.tar, level 1, advanced one pass, 5316794 +silesia.tar, level 3, advanced one pass, 4843429 +silesia.tar, level 4, advanced one pass, 4780657 +silesia.tar, level 5 row 1, advanced one pass, 4669650 +silesia.tar, level 5 row 2, advanced one pass, 4673119 +silesia.tar, level 5, advanced one pass, 4669650 +silesia.tar, level 6, advanced one pass, 4604925 +silesia.tar, level 7 row 1, advanced one pass, 4570873 +silesia.tar, level 7 row 2, advanced one pass, 4566314 +silesia.tar, level 7, advanced one pass, 4570873 +silesia.tar, level 9, advanced one pass, 4546477 +silesia.tar, level 11 row 1, advanced one pass, 4505875 +silesia.tar, level 11 row 2, advanced one pass, 4504435 +silesia.tar, level 12 row 1, advanced one pass, 4505461 +silesia.tar, level 12 row 2, advanced one pass, 4504644 +silesia.tar, level 13, advanced one pass, 4486256 +silesia.tar, level 16, advanced one pass, 4355572 +silesia.tar, level 19, advanced one pass, 4257629 +silesia.tar, no source size, advanced one pass, 4843429 +silesia.tar, long distance mode, advanced one pass, 4830453 +silesia.tar, multithreaded, advanced one pass, 4841902 +silesia.tar, multithreaded long distance mode, advanced one pass, 4834262 silesia.tar, small window log, advanced one pass, 7100064 -silesia.tar, small hash log, advanced one pass, 6529206 -silesia.tar, small chain log, advanced one pass, 4917041 -silesia.tar, explicit params, advanced one pass, 4807274 -silesia.tar, uncompressed literals, advanced one pass, 5118848 -silesia.tar, uncompressed literals optimal, advanced one pass, 4308451 -silesia.tar, huffman literals, advanced one pass, 5341705 -silesia.tar, multithreaded with advanced params, advanced one pass, 5118940 +silesia.tar, small hash log, advanced one pass, 6530222 +silesia.tar, small chain log, advanced one pass, 4915689 +silesia.tar, explicit params, advanced one pass, 4797958 +silesia.tar, uncompressed literals, advanced one pass, 5116329 +silesia.tar, uncompressed literals optimal, advanced one pass, 4306289 +silesia.tar, huffman literals, advanced one pass, 5331382 +silesia.tar, multithreaded with advanced params, advanced one pass, 5116442 github, level -5, advanced one pass, 204407 github, level -5 with dict, advanced one pass, 45832 github, level -3, advanced one pass, 193253 @@ -421,100 +421,100 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced one pass, 152667 github, huffman literals, advanced one pass, 142365 github, multithreaded with advanced params, advanced one pass, 165909 -github.tar, level -5, advanced one pass, 52115 -github.tar, level -5 with dict, advanced one pass, 51097 -github.tar, level -3, advanced one pass, 45678 -github.tar, level -3 with dict, advanced one pass, 44734 -github.tar, level -1, advanced one pass, 42560 -github.tar, level -1 with dict, advanced one pass, 41353 -github.tar, level 0, advanced one pass, 38884 -github.tar, level 0 with dict, advanced one pass, 37995 -github.tar, level 0 with dict dms, advanced one pass, 38114 -github.tar, level 0 with dict dds, advanced one pass, 38114 -github.tar, level 0 with dict copy, advanced one pass, 37995 -github.tar, level 0 with dict load, advanced one pass, 37956 -github.tar, level 1, advanced one pass, 39200 -github.tar, level 1 with dict, advanced one pass, 38119 -github.tar, level 1 with dict dms, advanced one pass, 38406 -github.tar, level 1 with dict dds, advanced one pass, 38406 -github.tar, level 1 with dict copy, advanced one pass, 38119 -github.tar, level 1 with dict load, advanced one pass, 38364 -github.tar, level 3, advanced one pass, 38884 -github.tar, level 3 with dict, advanced one pass, 37995 -github.tar, level 3 with dict dms, advanced one pass, 38114 -github.tar, level 3 with dict dds, advanced one pass, 38114 -github.tar, level 3 with dict copy, advanced one pass, 37995 -github.tar, level 3 with dict load, advanced one pass, 37956 -github.tar, level 4, advanced one pass, 38880 -github.tar, level 4 with dict, advanced one pass, 37948 -github.tar, level 4 with dict dms, advanced one pass, 37995 -github.tar, level 4 with dict dds, advanced one pass, 37995 -github.tar, level 4 with dict copy, advanced one pass, 37948 -github.tar, level 4 with dict load, advanced one pass, 37927 -github.tar, level 5 row 1, advanced one pass, 39651 -github.tar, level 5 row 1 with dict dms, advanced one pass, 39043 -github.tar, level 5 row 1 with dict dds, advanced one pass, 39069 -github.tar, level 5 row 1 with dict copy, advanced one pass, 39145 -github.tar, level 5 row 1 with dict load, advanced one pass, 39000 -github.tar, level 5 row 2, advanced one pass, 39701 -github.tar, level 5 row 2 with dict dms, advanced one pass, 39365 -github.tar, level 5 row 2 with dict dds, advanced one pass, 39233 -github.tar, level 5 row 2 with dict copy, advanced one pass, 39715 -github.tar, level 5 row 2 with dict load, advanced one pass, 39158 -github.tar, level 5, advanced one pass, 39651 -github.tar, level 5 with dict, advanced one pass, 39145 -github.tar, level 5 with dict dms, advanced one pass, 39043 -github.tar, level 5 with dict dds, advanced one pass, 39069 -github.tar, level 5 with dict copy, advanced one pass, 39145 -github.tar, level 5 with dict load, advanced one pass, 39000 -github.tar, level 6, advanced one pass, 39282 -github.tar, level 6 with dict, advanced one pass, 38656 -github.tar, level 6 with dict dms, advanced one pass, 38640 -github.tar, level 6 with dict dds, advanced one pass, 38643 -github.tar, level 6 with dict copy, advanced one pass, 38656 -github.tar, level 6 with dict load, advanced one pass, 38647 -github.tar, level 7 row 1, advanced one pass, 38005 -github.tar, level 7 row 1 with dict dms, advanced one pass, 37832 -github.tar, level 7 row 1 with dict dds, advanced one pass, 37857 -github.tar, level 7 row 1 with dict copy, advanced one pass, 37839 -github.tar, level 7 row 1 with dict load, advanced one pass, 37286 -github.tar, level 7 row 2, advanced one pass, 38077 -github.tar, level 7 row 2 with dict dms, advanced one pass, 38012 -github.tar, level 7 row 2 with dict dds, advanced one pass, 38014 -github.tar, level 7 row 2 with dict copy, advanced one pass, 38101 -github.tar, level 7 row 2 with dict load, advanced one pass, 37402 -github.tar, level 7, advanced one pass, 38005 -github.tar, level 7 with dict, advanced one pass, 37839 -github.tar, level 7 with dict dms, advanced one pass, 37832 -github.tar, level 7 with dict dds, advanced one pass, 37857 -github.tar, level 7 with dict copy, advanced one pass, 37839 -github.tar, level 7 with dict load, advanced one pass, 37286 -github.tar, level 9, advanced one pass, 36723 -github.tar, level 9 with dict, advanced one pass, 36531 -github.tar, level 9 with dict dms, advanced one pass, 36615 -github.tar, level 9 with dict dds, advanced one pass, 36682 -github.tar, level 9 with dict copy, advanced one pass, 36531 -github.tar, level 9 with dict load, advanced one pass, 36322 -github.tar, level 11 row 1, advanced one pass, 36085 +github.tar, level -5, advanced one pass, 52320 +github.tar, level -5 with dict, advanced one pass, 51321 +github.tar, level -3, advanced one pass, 45823 +github.tar, level -3 with dict, advanced one pass, 44882 +github.tar, level -1, advanced one pass, 42740 +github.tar, level -1 with dict, advanced one pass, 41506 +github.tar, level 0, advanced one pass, 39073 +github.tar, level 0 with dict, advanced one pass, 38146 +github.tar, level 0 with dict dms, advanced one pass, 38262 +github.tar, level 0 with dict dds, advanced one pass, 38262 +github.tar, level 0 with dict copy, advanced one pass, 38146 +github.tar, level 0 with dict load, advanced one pass, 38107 +github.tar, level 1, advanced one pass, 39444 +github.tar, level 1 with dict, advanced one pass, 38338 +github.tar, level 1 with dict dms, advanced one pass, 38641 +github.tar, level 1 with dict dds, advanced one pass, 38641 +github.tar, level 1 with dict copy, advanced one pass, 38338 +github.tar, level 1 with dict load, advanced one pass, 38592 +github.tar, level 3, advanced one pass, 39073 +github.tar, level 3 with dict, advanced one pass, 38146 +github.tar, level 3 with dict dms, advanced one pass, 38262 +github.tar, level 3 with dict dds, advanced one pass, 38262 +github.tar, level 3 with dict copy, advanced one pass, 38146 +github.tar, level 3 with dict load, advanced one pass, 38107 +github.tar, level 4, advanced one pass, 39068 +github.tar, level 4 with dict, advanced one pass, 38081 +github.tar, level 4 with dict dms, advanced one pass, 38135 +github.tar, level 4 with dict dds, advanced one pass, 38135 +github.tar, level 4 with dict copy, advanced one pass, 38081 +github.tar, level 4 with dict load, advanced one pass, 38088 +github.tar, level 5 row 1, advanced one pass, 39808 +github.tar, level 5 row 1 with dict dms, advanced one pass, 39185 +github.tar, level 5 row 1 with dict dds, advanced one pass, 39213 +github.tar, level 5 row 1 with dict copy, advanced one pass, 39284 +github.tar, level 5 row 1 with dict load, advanced one pass, 39155 +github.tar, level 5 row 2, advanced one pass, 39851 +github.tar, level 5 row 2 with dict dms, advanced one pass, 39498 +github.tar, level 5 row 2 with dict dds, advanced one pass, 39364 +github.tar, level 5 row 2 with dict copy, advanced one pass, 39843 +github.tar, level 5 row 2 with dict load, advanced one pass, 39312 +github.tar, level 5, advanced one pass, 39808 +github.tar, level 5 with dict, advanced one pass, 39284 +github.tar, level 5 with dict dms, advanced one pass, 39185 +github.tar, level 5 with dict dds, advanced one pass, 39213 +github.tar, level 5 with dict copy, advanced one pass, 39284 +github.tar, level 5 with dict load, advanced one pass, 39155 +github.tar, level 6, advanced one pass, 39455 +github.tar, level 6 with dict, advanced one pass, 38808 +github.tar, level 6 with dict dms, advanced one pass, 38792 +github.tar, level 6 with dict dds, advanced one pass, 38790 +github.tar, level 6 with dict copy, advanced one pass, 38808 +github.tar, level 6 with dict load, advanced one pass, 38796 +github.tar, level 7 row 1, advanced one pass, 38168 +github.tar, level 7 row 1 with dict dms, advanced one pass, 38001 +github.tar, level 7 row 1 with dict dds, advanced one pass, 38008 +github.tar, level 7 row 1 with dict copy, advanced one pass, 37975 +github.tar, level 7 row 1 with dict load, advanced one pass, 37445 +github.tar, level 7 row 2, advanced one pass, 38235 +github.tar, level 7 row 2 with dict dms, advanced one pass, 38164 +github.tar, level 7 row 2 with dict dds, advanced one pass, 38169 +github.tar, level 7 row 2 with dict copy, advanced one pass, 38294 +github.tar, level 7 row 2 with dict load, advanced one pass, 37552 +github.tar, level 7, advanced one pass, 38168 +github.tar, level 7 with dict, advanced one pass, 37975 +github.tar, level 7 with dict dms, advanced one pass, 38001 +github.tar, level 7 with dict dds, advanced one pass, 38008 +github.tar, level 7 with dict copy, advanced one pass, 37975 +github.tar, level 7 with dict load, advanced one pass, 37445 +github.tar, level 9, advanced one pass, 36897 +github.tar, level 9 with dict, advanced one pass, 36689 +github.tar, level 9 with dict dms, advanced one pass, 36756 +github.tar, level 9 with dict dds, advanced one pass, 36817 +github.tar, level 9 with dict copy, advanced one pass, 36689 +github.tar, level 9 with dict load, advanced one pass, 36484 +github.tar, level 11 row 1, advanced one pass, 36234 github.tar, level 11 row 1 with dict dms, advanced one pass, 36963 github.tar, level 11 row 1 with dict dds, advanced one pass, 36963 github.tar, level 11 row 1 with dict copy, advanced one pass, 36557 -github.tar, level 11 row 1 with dict load, advanced one pass, 36423 -github.tar, level 11 row 2, advanced one pass, 36110 +github.tar, level 11 row 1 with dict load, advanced one pass, 36567 +github.tar, level 11 row 2, advanced one pass, 36217 github.tar, level 11 row 2 with dict dms, advanced one pass, 36963 github.tar, level 11 row 2 with dict dds, advanced one pass, 36963 github.tar, level 11 row 2 with dict copy, advanced one pass, 36557 -github.tar, level 11 row 2 with dict load, advanced one pass, 36459 -github.tar, level 12 row 1, advanced one pass, 36085 +github.tar, level 11 row 2 with dict load, advanced one pass, 36586 +github.tar, level 12 row 1, advanced one pass, 36234 github.tar, level 12 row 1 with dict dms, advanced one pass, 36986 github.tar, level 12 row 1 with dict dds, advanced one pass, 36986 github.tar, level 12 row 1 with dict copy, advanced one pass, 36609 -github.tar, level 12 row 1 with dict load, advanced one pass, 36423 -github.tar, level 12 row 2, advanced one pass, 36110 +github.tar, level 12 row 1 with dict load, advanced one pass, 36567 +github.tar, level 12 row 2, advanced one pass, 36217 github.tar, level 12 row 2 with dict dms, advanced one pass, 36986 github.tar, level 12 row 2 with dict dds, advanced one pass, 36986 github.tar, level 12 row 2 with dict copy, advanced one pass, 36609 -github.tar, level 12 row 2 with dict load, advanced one pass, 36459 +github.tar, level 12 row 2 with dict load, advanced one pass, 36586 github.tar, level 13, advanced one pass, 35501 github.tar, level 13 with dict, advanced one pass, 37130 github.tar, level 13 with dict dms, advanced one pass, 37220 @@ -533,87 +533,87 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass, 32565 github.tar, level 19 with dict copy, advanced one pass, 32701 github.tar, level 19 with dict load, advanced one pass, 32428 -github.tar, no source size, advanced one pass, 38884 -github.tar, no source size with dict, advanced one pass, 37995 -github.tar, long distance mode, advanced one pass, 40242 -github.tar, multithreaded, advanced one pass, 38884 -github.tar, multithreaded long distance mode, advanced one pass, 40223 +github.tar, no source size, advanced one pass, 39073 +github.tar, no source size with dict, advanced one pass, 38146 +github.tar, long distance mode, advanced one pass, 40402 +github.tar, multithreaded, advanced one pass, 39067 +github.tar, multithreaded long distance mode, advanced one pass, 40377 github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 -github.tar, explicit params, advanced one pass, 41385 -github.tar, uncompressed literals, advanced one pass, 41562 +github.tar, explicit params, advanced one pass, 41605 +github.tar, uncompressed literals, advanced one pass, 41709 github.tar, uncompressed literals optimal, advanced one pass, 35356 -github.tar, huffman literals, advanced one pass, 38853 -github.tar, multithreaded with advanced params, advanced one pass, 41562 -silesia, level -5, advanced one pass small out, 6857372 -silesia, level -3, advanced one pass small out, 6503412 -silesia, level -1, advanced one pass small out, 6172202 -silesia, level 0, advanced one pass small out, 4839431 -silesia, level 1, advanced one pass small out, 5306632 -silesia, level 3, advanced one pass small out, 4839431 -silesia, level 4, advanced one pass small out, 4776557 -silesia, level 5 row 1, advanced one pass small out, 4667668 -silesia, level 5 row 2, advanced one pass small out, 4670326 -silesia, level 5, advanced one pass small out, 4667668 -silesia, level 6, advanced one pass small out, 4604351 -silesia, level 7 row 1, advanced one pass small out, 4570271 -silesia, level 7 row 2, advanced one pass small out, 4565169 -silesia, level 7, advanced one pass small out, 4570271 -silesia, level 9, advanced one pass small out, 4545850 -silesia, level 11 row 1, advanced one pass small out, 4505658 -silesia, level 11 row 2, advanced one pass small out, 4503429 -silesia, level 12 row 1, advanced one pass small out, 4505658 -silesia, level 12 row 2, advanced one pass small out, 4503429 -silesia, level 13, advanced one pass small out, 4493990 -silesia, level 16, advanced one pass small out, 4359652 -silesia, level 19, advanced one pass small out, 4266582 -silesia, no source size, advanced one pass small out, 4839431 -silesia, long distance mode, advanced one pass small out, 4831158 -silesia, multithreaded, advanced one pass small out, 4839431 -silesia, multithreaded long distance mode, advanced one pass small out, 4831176 +github.tar, huffman literals, advanced one pass, 39099 +github.tar, multithreaded with advanced params, advanced one pass, 41700 +silesia, level -5, advanced one pass small out, 6857776 +silesia, level -3, advanced one pass small out, 6504756 +silesia, level -1, advanced one pass small out, 6174127 +silesia, level 0, advanced one pass small out, 4838417 +silesia, level 1, advanced one pass small out, 5306931 +silesia, level 3, advanced one pass small out, 4838417 +silesia, level 4, advanced one pass small out, 4775359 +silesia, level 5 row 1, advanced one pass small out, 4666524 +silesia, level 5 row 2, advanced one pass small out, 4668976 +silesia, level 5, advanced one pass small out, 4666524 +silesia, level 6, advanced one pass small out, 4602031 +silesia, level 7 row 1, advanced one pass small out, 4567954 +silesia, level 7 row 2, advanced one pass small out, 4562774 +silesia, level 7, advanced one pass small out, 4567954 +silesia, level 9, advanced one pass small out, 4543669 +silesia, level 11 row 1, advanced one pass small out, 4503577 +silesia, level 11 row 2, advanced one pass small out, 4501229 +silesia, level 12 row 1, advanced one pass small out, 4503577 +silesia, level 12 row 2, advanced one pass small out, 4501229 +silesia, level 13, advanced one pass small out, 4484875 +silesia, level 16, advanced one pass small out, 4356207 +silesia, level 19, advanced one pass small out, 4266751 +silesia, no source size, advanced one pass small out, 4838417 +silesia, long distance mode, advanced one pass small out, 4830097 +silesia, multithreaded, advanced one pass small out, 4838949 +silesia, multithreaded long distance mode, advanced one pass small out, 4830419 silesia, small window log, advanced one pass small out, 7094480 -silesia, small hash log, advanced one pass small out, 6526141 -silesia, small chain log, advanced one pass small out, 4912197 -silesia, explicit params, advanced one pass small out, 4795840 -silesia, uncompressed literals, advanced one pass small out, 5116957 -silesia, uncompressed literals optimal, advanced one pass small out, 4316880 -silesia, huffman literals, advanced one pass small out, 5321369 -silesia, multithreaded with advanced params, advanced one pass small out, 5116957 -silesia.tar, level -5, advanced one pass small out, 6861055 -silesia.tar, level -3, advanced one pass small out, 6505483 -silesia.tar, level -1, advanced one pass small out, 6179047 -silesia.tar, level 0, advanced one pass small out, 4851407 -silesia.tar, level 1, advanced one pass small out, 5327717 -silesia.tar, level 3, advanced one pass small out, 4851407 -silesia.tar, level 4, advanced one pass small out, 4788821 -silesia.tar, level 5 row 1, advanced one pass small out, 4679004 -silesia.tar, level 5 row 2, advanced one pass small out, 4682334 -silesia.tar, level 5, advanced one pass small out, 4679004 -silesia.tar, level 6, advanced one pass small out, 4614561 -silesia.tar, level 7 row 1, advanced one pass small out, 4579828 -silesia.tar, level 7 row 2, advanced one pass small out, 4575602 -silesia.tar, level 7, advanced one pass small out, 4579828 -silesia.tar, level 9, advanced one pass small out, 4555448 -silesia.tar, level 11 row 1, advanced one pass small out, 4514962 -silesia.tar, level 11 row 2, advanced one pass small out, 4513816 -silesia.tar, level 12 row 1, advanced one pass small out, 4514517 -silesia.tar, level 12 row 2, advanced one pass small out, 4514007 -silesia.tar, level 13, advanced one pass small out, 4502956 -silesia.tar, level 16, advanced one pass small out, 4360385 -silesia.tar, level 19, advanced one pass small out, 4260939 -silesia.tar, no source size, advanced one pass small out, 4851407 -silesia.tar, long distance mode, advanced one pass small out, 4837775 -silesia.tar, multithreaded, advanced one pass small out, 4851478 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4843155 +silesia, small hash log, advanced one pass small out, 6524931 +silesia, small chain log, advanced one pass small out, 4912322 +silesia, explicit params, advanced one pass small out, 4794219 +silesia, uncompressed literals, advanced one pass small out, 5117482 +silesia, uncompressed literals optimal, advanced one pass small out, 4317186 +silesia, huffman literals, advanced one pass small out, 5321686 +silesia, multithreaded with advanced params, advanced one pass small out, 5117795 +silesia.tar, level -5, advanced one pass small out, 6860782 +silesia.tar, level -3, advanced one pass small out, 6507448 +silesia.tar, level -1, advanced one pass small out, 6175582 +silesia.tar, level 0, advanced one pass small out, 4843429 +silesia.tar, level 1, advanced one pass small out, 5316794 +silesia.tar, level 3, advanced one pass small out, 4843429 +silesia.tar, level 4, advanced one pass small out, 4780657 +silesia.tar, level 5 row 1, advanced one pass small out, 4669650 +silesia.tar, level 5 row 2, advanced one pass small out, 4673119 +silesia.tar, level 5, advanced one pass small out, 4669650 +silesia.tar, level 6, advanced one pass small out, 4604925 +silesia.tar, level 7 row 1, advanced one pass small out, 4570873 +silesia.tar, level 7 row 2, advanced one pass small out, 4566314 +silesia.tar, level 7, advanced one pass small out, 4570873 +silesia.tar, level 9, advanced one pass small out, 4546477 +silesia.tar, level 11 row 1, advanced one pass small out, 4505875 +silesia.tar, level 11 row 2, advanced one pass small out, 4504435 +silesia.tar, level 12 row 1, advanced one pass small out, 4505461 +silesia.tar, level 12 row 2, advanced one pass small out, 4504644 +silesia.tar, level 13, advanced one pass small out, 4486256 +silesia.tar, level 16, advanced one pass small out, 4355572 +silesia.tar, level 19, advanced one pass small out, 4257629 +silesia.tar, no source size, advanced one pass small out, 4843429 +silesia.tar, long distance mode, advanced one pass small out, 4830453 +silesia.tar, multithreaded, advanced one pass small out, 4841902 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4834262 silesia.tar, small window log, advanced one pass small out, 7100064 -silesia.tar, small hash log, advanced one pass small out, 6529206 -silesia.tar, small chain log, advanced one pass small out, 4917041 -silesia.tar, explicit params, advanced one pass small out, 4807274 -silesia.tar, uncompressed literals, advanced one pass small out, 5118848 -silesia.tar, uncompressed literals optimal, advanced one pass small out, 4308451 -silesia.tar, huffman literals, advanced one pass small out, 5341705 -silesia.tar, multithreaded with advanced params, advanced one pass small out, 5118940 +silesia.tar, small hash log, advanced one pass small out, 6530222 +silesia.tar, small chain log, advanced one pass small out, 4915689 +silesia.tar, explicit params, advanced one pass small out, 4797958 +silesia.tar, uncompressed literals, advanced one pass small out, 5116329 +silesia.tar, uncompressed literals optimal, advanced one pass small out, 4306289 +silesia.tar, huffman literals, advanced one pass small out, 5331382 +silesia.tar, multithreaded with advanced params, advanced one pass small out, 5116442 github, level -5, advanced one pass small out, 204407 github, level -5 with dict, advanced one pass small out, 45832 github, level -3, advanced one pass small out, 193253 @@ -739,100 +739,100 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced one pass small out, 152667 github, huffman literals, advanced one pass small out, 142365 github, multithreaded with advanced params, advanced one pass small out, 165909 -github.tar, level -5, advanced one pass small out, 52115 -github.tar, level -5 with dict, advanced one pass small out, 51097 -github.tar, level -3, advanced one pass small out, 45678 -github.tar, level -3 with dict, advanced one pass small out, 44734 -github.tar, level -1, advanced one pass small out, 42560 -github.tar, level -1 with dict, advanced one pass small out, 41353 -github.tar, level 0, advanced one pass small out, 38884 -github.tar, level 0 with dict, advanced one pass small out, 37995 -github.tar, level 0 with dict dms, advanced one pass small out, 38114 -github.tar, level 0 with dict dds, advanced one pass small out, 38114 -github.tar, level 0 with dict copy, advanced one pass small out, 37995 -github.tar, level 0 with dict load, advanced one pass small out, 37956 -github.tar, level 1, advanced one pass small out, 39200 -github.tar, level 1 with dict, advanced one pass small out, 38119 -github.tar, level 1 with dict dms, advanced one pass small out, 38406 -github.tar, level 1 with dict dds, advanced one pass small out, 38406 -github.tar, level 1 with dict copy, advanced one pass small out, 38119 -github.tar, level 1 with dict load, advanced one pass small out, 38364 -github.tar, level 3, advanced one pass small out, 38884 -github.tar, level 3 with dict, advanced one pass small out, 37995 -github.tar, level 3 with dict dms, advanced one pass small out, 38114 -github.tar, level 3 with dict dds, advanced one pass small out, 38114 -github.tar, level 3 with dict copy, advanced one pass small out, 37995 -github.tar, level 3 with dict load, advanced one pass small out, 37956 -github.tar, level 4, advanced one pass small out, 38880 -github.tar, level 4 with dict, advanced one pass small out, 37948 -github.tar, level 4 with dict dms, advanced one pass small out, 37995 -github.tar, level 4 with dict dds, advanced one pass small out, 37995 -github.tar, level 4 with dict copy, advanced one pass small out, 37948 -github.tar, level 4 with dict load, advanced one pass small out, 37927 -github.tar, level 5 row 1, advanced one pass small out, 39651 -github.tar, level 5 row 1 with dict dms, advanced one pass small out, 39043 -github.tar, level 5 row 1 with dict dds, advanced one pass small out, 39069 -github.tar, level 5 row 1 with dict copy, advanced one pass small out, 39145 -github.tar, level 5 row 1 with dict load, advanced one pass small out, 39000 -github.tar, level 5 row 2, advanced one pass small out, 39701 -github.tar, level 5 row 2 with dict dms, advanced one pass small out, 39365 -github.tar, level 5 row 2 with dict dds, advanced one pass small out, 39233 -github.tar, level 5 row 2 with dict copy, advanced one pass small out, 39715 -github.tar, level 5 row 2 with dict load, advanced one pass small out, 39158 -github.tar, level 5, advanced one pass small out, 39651 -github.tar, level 5 with dict, advanced one pass small out, 39145 -github.tar, level 5 with dict dms, advanced one pass small out, 39043 -github.tar, level 5 with dict dds, advanced one pass small out, 39069 -github.tar, level 5 with dict copy, advanced one pass small out, 39145 -github.tar, level 5 with dict load, advanced one pass small out, 39000 -github.tar, level 6, advanced one pass small out, 39282 -github.tar, level 6 with dict, advanced one pass small out, 38656 -github.tar, level 6 with dict dms, advanced one pass small out, 38640 -github.tar, level 6 with dict dds, advanced one pass small out, 38643 -github.tar, level 6 with dict copy, advanced one pass small out, 38656 -github.tar, level 6 with dict load, advanced one pass small out, 38647 -github.tar, level 7 row 1, advanced one pass small out, 38005 -github.tar, level 7 row 1 with dict dms, advanced one pass small out, 37832 -github.tar, level 7 row 1 with dict dds, advanced one pass small out, 37857 -github.tar, level 7 row 1 with dict copy, advanced one pass small out, 37839 -github.tar, level 7 row 1 with dict load, advanced one pass small out, 37286 -github.tar, level 7 row 2, advanced one pass small out, 38077 -github.tar, level 7 row 2 with dict dms, advanced one pass small out, 38012 -github.tar, level 7 row 2 with dict dds, advanced one pass small out, 38014 -github.tar, level 7 row 2 with dict copy, advanced one pass small out, 38101 -github.tar, level 7 row 2 with dict load, advanced one pass small out, 37402 -github.tar, level 7, advanced one pass small out, 38005 -github.tar, level 7 with dict, advanced one pass small out, 37839 -github.tar, level 7 with dict dms, advanced one pass small out, 37832 -github.tar, level 7 with dict dds, advanced one pass small out, 37857 -github.tar, level 7 with dict copy, advanced one pass small out, 37839 -github.tar, level 7 with dict load, advanced one pass small out, 37286 -github.tar, level 9, advanced one pass small out, 36723 -github.tar, level 9 with dict, advanced one pass small out, 36531 -github.tar, level 9 with dict dms, advanced one pass small out, 36615 -github.tar, level 9 with dict dds, advanced one pass small out, 36682 -github.tar, level 9 with dict copy, advanced one pass small out, 36531 -github.tar, level 9 with dict load, advanced one pass small out, 36322 -github.tar, level 11 row 1, advanced one pass small out, 36085 +github.tar, level -5, advanced one pass small out, 52320 +github.tar, level -5 with dict, advanced one pass small out, 51321 +github.tar, level -3, advanced one pass small out, 45823 +github.tar, level -3 with dict, advanced one pass small out, 44882 +github.tar, level -1, advanced one pass small out, 42740 +github.tar, level -1 with dict, advanced one pass small out, 41506 +github.tar, level 0, advanced one pass small out, 39073 +github.tar, level 0 with dict, advanced one pass small out, 38146 +github.tar, level 0 with dict dms, advanced one pass small out, 38262 +github.tar, level 0 with dict dds, advanced one pass small out, 38262 +github.tar, level 0 with dict copy, advanced one pass small out, 38146 +github.tar, level 0 with dict load, advanced one pass small out, 38107 +github.tar, level 1, advanced one pass small out, 39444 +github.tar, level 1 with dict, advanced one pass small out, 38338 +github.tar, level 1 with dict dms, advanced one pass small out, 38641 +github.tar, level 1 with dict dds, advanced one pass small out, 38641 +github.tar, level 1 with dict copy, advanced one pass small out, 38338 +github.tar, level 1 with dict load, advanced one pass small out, 38592 +github.tar, level 3, advanced one pass small out, 39073 +github.tar, level 3 with dict, advanced one pass small out, 38146 +github.tar, level 3 with dict dms, advanced one pass small out, 38262 +github.tar, level 3 with dict dds, advanced one pass small out, 38262 +github.tar, level 3 with dict copy, advanced one pass small out, 38146 +github.tar, level 3 with dict load, advanced one pass small out, 38107 +github.tar, level 4, advanced one pass small out, 39068 +github.tar, level 4 with dict, advanced one pass small out, 38081 +github.tar, level 4 with dict dms, advanced one pass small out, 38135 +github.tar, level 4 with dict dds, advanced one pass small out, 38135 +github.tar, level 4 with dict copy, advanced one pass small out, 38081 +github.tar, level 4 with dict load, advanced one pass small out, 38088 +github.tar, level 5 row 1, advanced one pass small out, 39808 +github.tar, level 5 row 1 with dict dms, advanced one pass small out, 39185 +github.tar, level 5 row 1 with dict dds, advanced one pass small out, 39213 +github.tar, level 5 row 1 with dict copy, advanced one pass small out, 39284 +github.tar, level 5 row 1 with dict load, advanced one pass small out, 39155 +github.tar, level 5 row 2, advanced one pass small out, 39851 +github.tar, level 5 row 2 with dict dms, advanced one pass small out, 39498 +github.tar, level 5 row 2 with dict dds, advanced one pass small out, 39364 +github.tar, level 5 row 2 with dict copy, advanced one pass small out, 39843 +github.tar, level 5 row 2 with dict load, advanced one pass small out, 39312 +github.tar, level 5, advanced one pass small out, 39808 +github.tar, level 5 with dict, advanced one pass small out, 39284 +github.tar, level 5 with dict dms, advanced one pass small out, 39185 +github.tar, level 5 with dict dds, advanced one pass small out, 39213 +github.tar, level 5 with dict copy, advanced one pass small out, 39284 +github.tar, level 5 with dict load, advanced one pass small out, 39155 +github.tar, level 6, advanced one pass small out, 39455 +github.tar, level 6 with dict, advanced one pass small out, 38808 +github.tar, level 6 with dict dms, advanced one pass small out, 38792 +github.tar, level 6 with dict dds, advanced one pass small out, 38790 +github.tar, level 6 with dict copy, advanced one pass small out, 38808 +github.tar, level 6 with dict load, advanced one pass small out, 38796 +github.tar, level 7 row 1, advanced one pass small out, 38168 +github.tar, level 7 row 1 with dict dms, advanced one pass small out, 38001 +github.tar, level 7 row 1 with dict dds, advanced one pass small out, 38008 +github.tar, level 7 row 1 with dict copy, advanced one pass small out, 37975 +github.tar, level 7 row 1 with dict load, advanced one pass small out, 37445 +github.tar, level 7 row 2, advanced one pass small out, 38235 +github.tar, level 7 row 2 with dict dms, advanced one pass small out, 38164 +github.tar, level 7 row 2 with dict dds, advanced one pass small out, 38169 +github.tar, level 7 row 2 with dict copy, advanced one pass small out, 38294 +github.tar, level 7 row 2 with dict load, advanced one pass small out, 37552 +github.tar, level 7, advanced one pass small out, 38168 +github.tar, level 7 with dict, advanced one pass small out, 37975 +github.tar, level 7 with dict dms, advanced one pass small out, 38001 +github.tar, level 7 with dict dds, advanced one pass small out, 38008 +github.tar, level 7 with dict copy, advanced one pass small out, 37975 +github.tar, level 7 with dict load, advanced one pass small out, 37445 +github.tar, level 9, advanced one pass small out, 36897 +github.tar, level 9 with dict, advanced one pass small out, 36689 +github.tar, level 9 with dict dms, advanced one pass small out, 36756 +github.tar, level 9 with dict dds, advanced one pass small out, 36817 +github.tar, level 9 with dict copy, advanced one pass small out, 36689 +github.tar, level 9 with dict load, advanced one pass small out, 36484 +github.tar, level 11 row 1, advanced one pass small out, 36234 github.tar, level 11 row 1 with dict dms, advanced one pass small out, 36963 github.tar, level 11 row 1 with dict dds, advanced one pass small out, 36963 github.tar, level 11 row 1 with dict copy, advanced one pass small out, 36557 -github.tar, level 11 row 1 with dict load, advanced one pass small out, 36423 -github.tar, level 11 row 2, advanced one pass small out, 36110 +github.tar, level 11 row 1 with dict load, advanced one pass small out, 36567 +github.tar, level 11 row 2, advanced one pass small out, 36217 github.tar, level 11 row 2 with dict dms, advanced one pass small out, 36963 github.tar, level 11 row 2 with dict dds, advanced one pass small out, 36963 github.tar, level 11 row 2 with dict copy, advanced one pass small out, 36557 -github.tar, level 11 row 2 with dict load, advanced one pass small out, 36459 -github.tar, level 12 row 1, advanced one pass small out, 36085 +github.tar, level 11 row 2 with dict load, advanced one pass small out, 36586 +github.tar, level 12 row 1, advanced one pass small out, 36234 github.tar, level 12 row 1 with dict dms, advanced one pass small out, 36986 github.tar, level 12 row 1 with dict dds, advanced one pass small out, 36986 github.tar, level 12 row 1 with dict copy, advanced one pass small out, 36609 -github.tar, level 12 row 1 with dict load, advanced one pass small out, 36423 -github.tar, level 12 row 2, advanced one pass small out, 36110 +github.tar, level 12 row 1 with dict load, advanced one pass small out, 36567 +github.tar, level 12 row 2, advanced one pass small out, 36217 github.tar, level 12 row 2 with dict dms, advanced one pass small out, 36986 github.tar, level 12 row 2 with dict dds, advanced one pass small out, 36986 github.tar, level 12 row 2 with dict copy, advanced one pass small out, 36609 -github.tar, level 12 row 2 with dict load, advanced one pass small out, 36459 +github.tar, level 12 row 2 with dict load, advanced one pass small out, 36586 github.tar, level 13, advanced one pass small out, 35501 github.tar, level 13 with dict, advanced one pass small out, 37130 github.tar, level 13 with dict dms, advanced one pass small out, 37220 @@ -851,19 +851,19 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass small out, 32565 github.tar, level 19 with dict copy, advanced one pass small out, 32701 github.tar, level 19 with dict load, advanced one pass small out, 32428 -github.tar, no source size, advanced one pass small out, 38884 -github.tar, no source size with dict, advanced one pass small out, 37995 -github.tar, long distance mode, advanced one pass small out, 40242 -github.tar, multithreaded, advanced one pass small out, 38884 -github.tar, multithreaded long distance mode, advanced one pass small out, 40223 +github.tar, no source size, advanced one pass small out, 39073 +github.tar, no source size with dict, advanced one pass small out, 38146 +github.tar, long distance mode, advanced one pass small out, 40402 +github.tar, multithreaded, advanced one pass small out, 39067 +github.tar, multithreaded long distance mode, advanced one pass small out, 40377 github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 -github.tar, explicit params, advanced one pass small out, 41385 -github.tar, uncompressed literals, advanced one pass small out, 41562 +github.tar, explicit params, advanced one pass small out, 41605 +github.tar, uncompressed literals, advanced one pass small out, 41709 github.tar, uncompressed literals optimal, advanced one pass small out, 35356 -github.tar, huffman literals, advanced one pass small out, 38853 -github.tar, multithreaded with advanced params, advanced one pass small out, 41562 +github.tar, huffman literals, advanced one pass small out, 39099 +github.tar, multithreaded with advanced params, advanced one pass small out, 41700 silesia, level -5, advanced streaming, 6854744 silesia, level -3, advanced streaming, 6503319 silesia, level -1, advanced streaming, 6172207 @@ -888,8 +888,8 @@ silesia, level 16, advanced silesia, level 19, advanced streaming, 4266582 silesia, no source size, advanced streaming, 4839395 silesia, long distance mode, advanced streaming, 4831158 -silesia, multithreaded, advanced streaming, 4839431 -silesia, multithreaded long distance mode, advanced streaming, 4831176 +silesia, multithreaded, advanced streaming, 4838949 +silesia, multithreaded long distance mode, advanced streaming, 4830419 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6526141 silesia, small chain log, advanced streaming, 4912197 @@ -897,7 +897,7 @@ silesia, explicit params, advanced silesia, uncompressed literals, advanced streaming, 5116957 silesia, uncompressed literals optimal, advanced streaming, 4316880 silesia, huffman literals, advanced streaming, 5321370 -silesia, multithreaded with advanced params, advanced streaming, 5116957 +silesia, multithreaded with advanced params, advanced streaming, 5117795 silesia.tar, level -5, advanced streaming, 6856523 silesia.tar, level -3, advanced streaming, 6505954 silesia.tar, level -1, advanced streaming, 6179056 @@ -922,8 +922,8 @@ silesia.tar, level 16, advanced silesia.tar, level 19, advanced streaming, 4260939 silesia.tar, no source size, advanced streaming, 4858628 silesia.tar, long distance mode, advanced streaming, 4837775 -silesia.tar, multithreaded, advanced streaming, 4851478 -silesia.tar, multithreaded long distance mode, advanced streaming, 4843155 +silesia.tar, multithreaded, advanced streaming, 4841902 +silesia.tar, multithreaded long distance mode, advanced streaming, 4834262 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529209 silesia.tar, small chain log, advanced streaming, 4917021 @@ -931,7 +931,7 @@ silesia.tar, explicit params, advanced silesia.tar, uncompressed literals, advanced streaming, 5126542 silesia.tar, uncompressed literals optimal, advanced streaming, 4308451 silesia.tar, huffman literals, advanced streaming, 5341712 -silesia.tar, multithreaded with advanced params, advanced streaming, 5118940 +silesia.tar, multithreaded with advanced params, advanced streaming, 5116442 github, level -5, advanced streaming, 204407 github, level -5 with dict, advanced streaming, 45832 github, level -3, advanced streaming, 193253 @@ -1172,8 +1172,8 @@ github.tar, level 19 with dict load, advanced github.tar, no source size, advanced streaming, 38881 github.tar, no source size with dict, advanced streaming, 38111 github.tar, long distance mode, advanced streaming, 40242 -github.tar, multithreaded, advanced streaming, 38884 -github.tar, multithreaded long distance mode, advanced streaming, 40223 +github.tar, multithreaded, advanced streaming, 39067 +github.tar, multithreaded long distance mode, advanced streaming, 40377 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 @@ -1181,7 +1181,7 @@ github.tar, explicit params, advanced github.tar, uncompressed literals, advanced streaming, 41562 github.tar, uncompressed literals optimal, advanced streaming, 35356 github.tar, huffman literals, advanced streaming, 38853 -github.tar, multithreaded with advanced params, advanced streaming, 41562 +github.tar, multithreaded with advanced params, advanced streaming, 41700 silesia, level -5, old streaming, 6854744 silesia, level -3, old streaming, 6503319 silesia, level -1, old streaming, 6172207 From 1c62e714ab9f53aefd6478e033ce448597b68fab Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 20 Oct 2024 17:16:17 -0700 Subject: [PATCH 413/937] minor split optimization let's fill the initial stats directly into target fingerprint --- lib/compress/zstd_preSplit.c | 10 +++++----- lib/compress/zstd_preSplit.h | 4 ++++ 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index ceac5c91f..f831dabde 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -18,7 +18,7 @@ #define BLOCKSIZE_MIN 3500 #define THRESHOLD_PENALTY_RATE 16 #define THRESHOLD_BASE (THRESHOLD_PENALTY_RATE - 2) -#define THRESHOLD_PENALTY 4 +#define THRESHOLD_PENALTY 3 #define HASHLENGTH 2 #define HASHLOG 10 @@ -84,8 +84,8 @@ static int compareFingerprints(const FingerPrint* ref, const FingerPrint* newfp, int penalty) { - if (ref->nbEvents <= BLOCKSIZE_MIN) - return 0; + assert(ref->nbEvents > 0); + assert(newfp->nbEvents > 0); { S64 p50 = ref->nbEvents * newfp->nbEvents; S64 deviation = fpDistance(ref, newfp); S64 threshold = p50 * (THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; @@ -140,7 +140,8 @@ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; initStats(fpstats); - for (pos = 0; pos < blockSizeMax;) { + recordFingerprint(&fpstats->pastEvents, p, CHUNKSIZE); + for (pos = CHUNKSIZE; pos < blockSizeMax; pos += CHUNKSIZE) { assert(pos <= blockSizeMax - CHUNKSIZE); recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE); if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { @@ -150,7 +151,6 @@ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, ZSTD_memset(&fpstats->newEvents, 0, sizeof(fpstats->newEvents)); penalty = penalty - 1 + (penalty == 0); } - pos += CHUNKSIZE; } return blockSizeMax; (void)flushEvents; (void)removeEvents; diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index b0b6bb762..7b6aadd0b 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -22,6 +22,10 @@ extern "C" { /* note: * @workspace must be aligned on 8-bytes boundaries * @wkspSize must be at least >= ZSTD_SLIPBLOCK_WORKSPACESIZE + * note2: + * for the time being, this function only accepts full 128 KB blocks, + * therefore @blockSizeMax must be == 128 KB. + * This could be extended to smaller sizes in the future. */ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax, void* workspace, size_t wkspSize); From a167571db535377070c43098932a7747d859177c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 21 Oct 2024 14:56:43 -0700 Subject: [PATCH 414/937] added a faster block splitter variant that samples 1 in 5 positions. This variant is fast enough for lazy2 and btlazy2, but it's less good in combination with post-splitter at higher levels (>= btopt). --- lib/compress/zstd_compress.c | 6 +++-- lib/compress/zstd_preSplit.c | 50 ++++++++++++++++++++++++++---------- lib/compress/zstd_preSplit.h | 6 ++++- 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index fcef55bf1..e7a07a484 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4500,8 +4500,10 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src return MIN(srcSize, blockSizeMax); /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for btlazy2+ strategies */ - if (strat >= ZSTD_btlazy2) - return ZSTD_splitBlock_4k(src, srcSize, blockSizeMax, cctx->tmpWorkspace, cctx->tmpWkspSize); + if (strat >= ZSTD_btopt) + return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); + if (strat >= ZSTD_lazy2) + return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy * no cpu cost, but can over-split homegeneous data. * heuristic, tested as being "generally better". diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index f831dabde..721a52deb 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -46,22 +46,36 @@ static void initStats(FPStats* fpstats) ZSTD_memset(fpstats, 0, sizeof(FPStats)); } -static void addToFingerprint(FingerPrint* fp, const void* src, size_t s) +FORCE_INLINE_TEMPLATE void addEvents_generic(FingerPrint* fp, const void* src, size_t srcSize, size_t samplingRate) { const char* p = (const char*)src; - size_t limit = s - HASHLENGTH + 1; + size_t limit = srcSize - HASHLENGTH + 1; size_t n; - assert(s >= HASHLENGTH); - for (n = 0; n < limit; n++) { - fp->events[hash2(p++)]++; + assert(srcSize >= HASHLENGTH); + for (n = 0; n < limit; n+=samplingRate) { + fp->events[hash2(p+n)]++; } - fp->nbEvents += limit; + fp->nbEvents += limit/samplingRate; } -static void recordFingerprint(FingerPrint* fp, const void* src, size_t s) +#define ADDEVENTS_RATE(_rate) ZSTD_addEvents_##_rate + +#define ZSTD_GEN_ADDEVENTS_SAMPLE(_rate) \ + static void ADDEVENTS_RATE(_rate)(FingerPrint* fp, const void* src, size_t srcSize) \ + { \ + return addEvents_generic(fp, src, srcSize, _rate); \ + } + +ZSTD_GEN_ADDEVENTS_SAMPLE(1); +ZSTD_GEN_ADDEVENTS_SAMPLE(5); + + +typedef void (*addEvents_f)(FingerPrint* fp, const void* src, size_t srcSize); + +static void recordFingerprint(FingerPrint* fp, const void* src, size_t s, addEvents_f addEvents) { ZSTD_memset(fp, 0, sizeof(*fp)); - addToFingerprint(fp, src, s); + addEvents(fp, src, s); } static S64 abs64(S64 i) { return (i < 0) ? -i : i; } @@ -124,8 +138,8 @@ static void removeEvents(FingerPrint* acc, const FingerPrint* slice) #define CHUNKSIZE (8 << 10) /* Note: technically, we use CHUNKSIZE, so that's 8 KB */ -size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, - size_t blockSizeMax, +static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, + size_t blockSizeMax, addEvents_f f, void* workspace, size_t wkspSize) { FPStats* const fpstats = (FPStats*)workspace; @@ -140,18 +154,28 @@ size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; initStats(fpstats); - recordFingerprint(&fpstats->pastEvents, p, CHUNKSIZE); + recordFingerprint(&fpstats->pastEvents, p, CHUNKSIZE, f); for (pos = CHUNKSIZE; pos < blockSizeMax; pos += CHUNKSIZE) { assert(pos <= blockSizeMax - CHUNKSIZE); - recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE); + recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE, f); if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { return pos; } else { mergeEvents(&fpstats->pastEvents, &fpstats->newEvents); - ZSTD_memset(&fpstats->newEvents, 0, sizeof(fpstats->newEvents)); penalty = penalty - 1 + (penalty == 0); } } return blockSizeMax; (void)flushEvents; (void)removeEvents; } + +size_t ZSTD_splitBlock(const void* src, size_t srcSize, + size_t blockSizeMax, ZSTD_SplitBlock_strategy_e splitStrat, + void* workspace, size_t wkspSize) +{ + if (splitStrat == split_lvl2) + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(1), workspace, wkspSize); + + assert(splitStrat == split_lvl1); + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(5), workspace, wkspSize); +} diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index 7b6aadd0b..2c87d34a6 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -17,6 +17,8 @@ extern "C" { #endif +typedef enum { split_lvl1, split_lvl2 } ZSTD_SplitBlock_strategy_e; + #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 /* note: @@ -27,7 +29,9 @@ extern "C" { * therefore @blockSizeMax must be == 128 KB. * This could be extended to smaller sizes in the future. */ -size_t ZSTD_splitBlock_4k(const void* src, size_t srcSize, size_t blockSizeMax, void* workspace, size_t wkspSize); +size_t ZSTD_splitBlock(const void* src, size_t srcSize, + size_t blockSizeMax, ZSTD_SplitBlock_strategy_e splitStrat, + void* workspace, size_t wkspSize); #if defined (__cplusplus) } From 7bad787d8bcae57cf0bdcbca00b3f106ae557b75 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 15:12:46 -0700 Subject: [PATCH 415/937] made ZSTD_isPower2() an inline function --- lib/common/compiler.h | 6 +++++- lib/compress/zstd_cwksp.h | 6 +++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index f4caeb5c0..b6cbcee03 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -278,7 +278,11 @@ * Alignment check *****************************************************************/ -#define ZSTD_IS_POWER_2(a) (((a) & ((a)-1)) == 0) +/* @return 1 if @u is a 2^n value, 0 otherwise + * useful to check a value is valid for alignment restrictions */ +MEM_STATIC int ZSTD_isPower2(size_t u) { + return (u & (u-1)) == 0; +} /* this test was initially positioned in mem.h, * but this file is removed (or replaced) for linux kernel diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index dc0142098..77715e22e 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -208,7 +208,7 @@ MEM_STATIC void ZSTD_cwksp_assert_internal_consistency(ZSTD_cwksp* ws) { */ MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t align) { size_t const mask = align - 1; - assert(ZSTD_IS_POWER_2(align)); + assert(ZSTD_isPower2(align)); return (size + mask) & ~mask; } @@ -266,7 +266,7 @@ MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void) { MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignBytes) { size_t const alignBytesMask = alignBytes - 1; size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask; - assert(ZSTD_IS_POWER_2(alignBytes)); + assert(ZSTD_isPower2(alignBytes)); assert(bytes < alignBytes); return bytes; } @@ -536,7 +536,7 @@ MEM_STATIC void* ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t byteSi void* const start = ZSTD_cwksp_reserve_object(ws, byteSize + surplus); if (start == NULL) return NULL; if (surplus == 0) return start; - assert(ZSTD_IS_POWER_2(alignment)); + assert(ZSTD_isPower2(alignment)); return (void*)(((size_t)start + surplus) & ~mask); } From 5ae34e4c96265f1face970f3458836b3edf2e76d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 15:19:06 -0700 Subject: [PATCH 416/937] ensure `lastBlock` is correctly determined reported by @terrelln --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index e7a07a484..edb71ae50 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4540,8 +4540,8 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, while (remaining) { ZSTD_matchState_t* const ms = &cctx->blockState.matchState; - U32 const lastBlock = lastFrameChunk & (blockSizeMax >= remaining); size_t const blockSize = ZSTD_optimalBlockSize(cctx, ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy, savings); + U32 const lastBlock = lastFrameChunk & (blockSize == remaining); assert(blockSize <= remaining); /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding From ea85dc7af6f97cbfc7fd1e6ff1515660e58501a3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 15:25:45 -0700 Subject: [PATCH 417/937] conservatively estimate over-splitting in presence of incompressible loss ensure data can never be expanded by more than 3 bytes per full block. --- lib/compress/zstd_compress.c | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index edb71ae50..85966d888 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4587,6 +4587,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, } /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/ if (cSize < blockSize) savings += (blockSize - cSize); + else if (savings) savings--; ip += blockSize; assert(remaining >= blockSize); remaining -= blockSize; From 4662f6e646395b3f1902bc280991b82aefc1ba5d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 15:32:11 -0700 Subject: [PATCH 418/937] renamed: FingerPrint => Fingerprint suggested by @terrelln --- lib/compress/zstd_preSplit.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 721a52deb..e0ac9a9e9 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -35,10 +35,10 @@ static unsigned hash2(const void *p) typedef struct { int events[HASHTABLESIZE]; S64 nbEvents; -} FingerPrint; +} Fingerprint; typedef struct { - FingerPrint pastEvents; - FingerPrint newEvents; + Fingerprint pastEvents; + Fingerprint newEvents; } FPStats; static void initStats(FPStats* fpstats) @@ -46,7 +46,7 @@ static void initStats(FPStats* fpstats) ZSTD_memset(fpstats, 0, sizeof(FPStats)); } -FORCE_INLINE_TEMPLATE void addEvents_generic(FingerPrint* fp, const void* src, size_t srcSize, size_t samplingRate) +FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) { const char* p = (const char*)src; size_t limit = srcSize - HASHLENGTH + 1; @@ -61,7 +61,7 @@ FORCE_INLINE_TEMPLATE void addEvents_generic(FingerPrint* fp, const void* src, s #define ADDEVENTS_RATE(_rate) ZSTD_addEvents_##_rate #define ZSTD_GEN_ADDEVENTS_SAMPLE(_rate) \ - static void ADDEVENTS_RATE(_rate)(FingerPrint* fp, const void* src, size_t srcSize) \ + static void ADDEVENTS_RATE(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ { \ return addEvents_generic(fp, src, srcSize, _rate); \ } @@ -70,9 +70,9 @@ ZSTD_GEN_ADDEVENTS_SAMPLE(1); ZSTD_GEN_ADDEVENTS_SAMPLE(5); -typedef void (*addEvents_f)(FingerPrint* fp, const void* src, size_t srcSize); +typedef void (*addEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); -static void recordFingerprint(FingerPrint* fp, const void* src, size_t s, addEvents_f addEvents) +static void recordFingerprint(Fingerprint* fp, const void* src, size_t s, addEvents_f addEvents) { ZSTD_memset(fp, 0, sizeof(*fp)); addEvents(fp, src, s); @@ -80,7 +80,7 @@ static void recordFingerprint(FingerPrint* fp, const void* src, size_t s, addEve static S64 abs64(S64 i) { return (i < 0) ? -i : i; } -static S64 fpDistance(const FingerPrint* fp1, const FingerPrint* fp2) +static S64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) { S64 distance = 0; size_t n; @@ -94,8 +94,8 @@ static S64 fpDistance(const FingerPrint* fp1, const FingerPrint* fp2) /* Compare newEvents with pastEvents * return 1 when considered "too different" */ -static int compareFingerprints(const FingerPrint* ref, - const FingerPrint* newfp, +static int compareFingerprints(const Fingerprint* ref, + const Fingerprint* newfp, int penalty) { assert(ref->nbEvents > 0); @@ -107,7 +107,7 @@ static int compareFingerprints(const FingerPrint* ref, } } -static void mergeEvents(FingerPrint* acc, const FingerPrint* newfp) +static void mergeEvents(Fingerprint* acc, const Fingerprint* newfp) { size_t n; for (n = 0; n < HASHTABLESIZE; n++) { @@ -126,7 +126,7 @@ static void flushEvents(FPStats* fpstats) ZSTD_memset(&fpstats->newEvents, 0, sizeof(fpstats->newEvents)); } -static void removeEvents(FingerPrint* acc, const FingerPrint* slice) +static void removeEvents(Fingerprint* acc, const Fingerprint* slice) { size_t n; for (n = 0; n < HASHTABLESIZE; n++) { From 1ec5f9f1f6b187095d996248471a6c6f128e9001 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:03:19 -0700 Subject: [PATCH 419/937] changed loop exit condition so that there is no need to assert() within the loop. --- lib/compress/zstd_preSplit.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index e0ac9a9e9..02751a0d4 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -155,8 +155,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, initStats(fpstats); recordFingerprint(&fpstats->pastEvents, p, CHUNKSIZE, f); - for (pos = CHUNKSIZE; pos < blockSizeMax; pos += CHUNKSIZE) { - assert(pos <= blockSizeMax - CHUNKSIZE); + for (pos = CHUNKSIZE; pos <= blockSizeMax - CHUNKSIZE; pos += CHUNKSIZE) { recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE, f); if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { return pos; @@ -165,6 +164,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, penalty = penalty - 1 + (penalty == 0); } } + assert(pos == blockSizeMax); return blockSizeMax; (void)flushEvents; (void)removeEvents; } From 16450d0732ff84e3ad367f616d84cee1567cfb8e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:06:07 -0700 Subject: [PATCH 420/937] rewrite penalty update suggested by @terrelln --- lib/compress/zstd_preSplit.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 02751a0d4..2e65f88d9 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -161,7 +161,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, return pos; } else { mergeEvents(&fpstats->pastEvents, &fpstats->newEvents); - penalty = penalty - 1 + (penalty == 0); + if (penalty > 0) penalty--; } } assert(pos == blockSizeMax); From 06b7cfabf8f5f3ba48694758cf85aaf7671504d2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:22:17 -0700 Subject: [PATCH 421/937] rewrote ZSTD_cwksp_initialAllocStart() to be easier to read following a discussion with @felixhandte --- lib/compress/zstd_cwksp.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h index 77715e22e..aa4c3e49e 100644 --- a/lib/compress/zstd_cwksp.h +++ b/lib/compress/zstd_cwksp.h @@ -17,6 +17,7 @@ #include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customFree */ #include "../common/zstd_internal.h" #include "../common/portability_macros.h" +#include "../common/compiler.h" /* ZS2_isPower2 */ #if defined (__cplusplus) extern "C" { @@ -275,8 +276,12 @@ MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignByt * Returns the initial value for allocStart which is used to determine the position from * which we can allocate from the end of the workspace. */ -MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws) { - return (void*)((size_t)ws->workspaceEnd & (size_t)~(ZSTD_CWKSP_ALIGNMENT_BYTES-1)); +MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws) +{ + char* endPtr = (char*)ws->workspaceEnd; + assert(ZSTD_isPower2(ZSTD_CWKSP_ALIGNMENT_BYTES)); + endPtr = endPtr - ((size_t)endPtr % ZSTD_CWKSP_ALIGNMENT_BYTES); + return (void*)endPtr; } /** From 0be334d208b9fadd805a401ebcfdf6f253adae2a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:25:44 -0700 Subject: [PATCH 422/937] fixes static state allocation check detected by @felixhandte --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 85966d888..05c1faa9f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -138,7 +138,7 @@ ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize) cctx->staticSize = workspaceSize; /* statically sized space. tmpWorkspace never moves (but prev/next block swap places) */ - if (!ZSTD_cwksp_check_available(&cctx->workspace, ENTROPY_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL; + if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL; cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); cctx->tmpWorkspace = ZSTD_cwksp_reserve_object_aligned(&cctx->workspace, TMP_WORKSPACE_SIZE, sizeof(S64)); From d2eeed53dc8782be8dff36e1ff20e1e41e1d4199 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:33:55 -0700 Subject: [PATCH 423/937] updated compression results due to integration of `sample5` strategy, leading to better compression ratios on a range of levels --- tests/regression/results.csv | 168 +++++++++++++++++------------------ 1 file changed, 84 insertions(+), 84 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index b32db43de..3a14793dd 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -9,8 +9,8 @@ silesia.tar, level 4, compress silesia.tar, level 5, compress simple, 4669650 silesia.tar, level 6, compress simple, 4604925 silesia.tar, level 7, compress simple, 4570873 -silesia.tar, level 9, compress simple, 4546477 -silesia.tar, level 13, compress simple, 4486256 +silesia.tar, level 9, compress simple, 4537558 +silesia.tar, level 13, compress simple, 4484732 silesia.tar, level 16, compress simple, 4355572 silesia.tar, level 19, compress simple, 4257629 silesia.tar, uncompressed literals, compress simple, 4843429 @@ -26,7 +26,7 @@ github.tar, level 4, compress github.tar, level 5, compress simple, 39808 github.tar, level 6, compress simple, 39455 github.tar, level 7, compress simple, 38168 -github.tar, level 9, compress simple, 36897 +github.tar, level 9, compress simple, 36723 github.tar, level 13, compress simple, 35501 github.tar, level 16, compress simple, 40466 github.tar, level 19, compress simple, 32262 @@ -43,8 +43,8 @@ silesia, level 4, compress silesia, level 5, compress cctx, 4666524 silesia, level 6, compress cctx, 4602031 silesia, level 7, compress cctx, 4567954 -silesia, level 9, compress cctx, 4543669 -silesia, level 13, compress cctx, 4484875 +silesia, level 9, compress cctx, 4535624 +silesia, level 13, compress cctx, 4484013 silesia, level 16, compress cctx, 4356207 silesia, level 19, compress cctx, 4266751 silesia, long distance mode, compress cctx, 4838417 @@ -107,8 +107,8 @@ silesia, level 4, zstdcli, silesia, level 5, zstdcli, 4666931 silesia, level 6, zstdcli, 4602509 silesia, level 7, zstdcli, 4568265 -silesia, level 9, zstdcli, 4544068 -silesia, level 13, zstdcli, 4484443 +silesia, level 9, zstdcli, 4535309 +silesia, level 13, zstdcli, 4483601 silesia, level 16, zstdcli, 4357591 silesia, level 19, zstdcli, 4266865 silesia, long distance mode, zstdcli, 4830467 @@ -132,8 +132,8 @@ silesia.tar, level 4, zstdcli, silesia.tar, level 5, zstdcli, 4671144 silesia.tar, level 6, zstdcli, 4606407 silesia.tar, level 7, zstdcli, 4572666 -silesia.tar, level 9, zstdcli, 4546557 -silesia.tar, level 13, zstdcli, 4491076 +silesia.tar, level 9, zstdcli, 4542599 +silesia.tar, level 13, zstdcli, 4489976 silesia.tar, level 16, zstdcli, 4356959 silesia.tar, level 19, zstdcli, 4259787 silesia.tar, no source size, zstdcli, 4841902 @@ -206,9 +206,9 @@ github.tar, level 5 with dict, zstdcli, github.tar, level 6, zstdcli, 39455 github.tar, level 6 with dict, zstdcli, 38787 github.tar, level 7, zstdcli, 38177 -github.tar, level 7 with dict, zstdcli, 38009 -github.tar, level 9, zstdcli, 36893 -github.tar, level 9 with dict, zstdcli, 36827 +github.tar, level 7 with dict, zstdcli, 37861 +github.tar, level 9, zstdcli, 36727 +github.tar, level 9 with dict, zstdcli, 36686 github.tar, level 13, zstdcli, 35505 github.tar, level 13 with dict, zstdcli, 37134 github.tar, level 16, zstdcli, 40470 @@ -242,12 +242,12 @@ silesia, level 6, advanced silesia, level 7 row 1, advanced one pass, 4567954 silesia, level 7 row 2, advanced one pass, 4562774 silesia, level 7, advanced one pass, 4567954 -silesia, level 9, advanced one pass, 4543669 -silesia, level 11 row 1, advanced one pass, 4503577 -silesia, level 11 row 2, advanced one pass, 4501229 -silesia, level 12 row 1, advanced one pass, 4503577 -silesia, level 12 row 2, advanced one pass, 4501229 -silesia, level 13, advanced one pass, 4484875 +silesia, level 9, advanced one pass, 4535624 +silesia, level 11 row 1, advanced one pass, 4495623 +silesia, level 11 row 2, advanced one pass, 4493258 +silesia, level 12 row 1, advanced one pass, 4495623 +silesia, level 12 row 2, advanced one pass, 4493258 +silesia, level 13, advanced one pass, 4484013 silesia, level 16, advanced one pass, 4356207 silesia, level 19, advanced one pass, 4266751 silesia, no source size, advanced one pass, 4838417 @@ -276,12 +276,12 @@ silesia.tar, level 6, advanced silesia.tar, level 7 row 1, advanced one pass, 4570873 silesia.tar, level 7 row 2, advanced one pass, 4566314 silesia.tar, level 7, advanced one pass, 4570873 -silesia.tar, level 9, advanced one pass, 4546477 -silesia.tar, level 11 row 1, advanced one pass, 4505875 -silesia.tar, level 11 row 2, advanced one pass, 4504435 -silesia.tar, level 12 row 1, advanced one pass, 4505461 -silesia.tar, level 12 row 2, advanced one pass, 4504644 -silesia.tar, level 13, advanced one pass, 4486256 +silesia.tar, level 9, advanced one pass, 4537558 +silesia.tar, level 11 row 1, advanced one pass, 4496590 +silesia.tar, level 11 row 2, advanced one pass, 4495225 +silesia.tar, level 12 row 1, advanced one pass, 4496084 +silesia.tar, level 12 row 2, advanced one pass, 4495434 +silesia.tar, level 13, advanced one pass, 4484732 silesia.tar, level 16, advanced one pass, 4355572 silesia.tar, level 19, advanced one pass, 4257629 silesia.tar, no source size, advanced one pass, 4843429 @@ -474,47 +474,47 @@ github.tar, level 6 with dict dds, advanced github.tar, level 6 with dict copy, advanced one pass, 38808 github.tar, level 6 with dict load, advanced one pass, 38796 github.tar, level 7 row 1, advanced one pass, 38168 -github.tar, level 7 row 1 with dict dms, advanced one pass, 38001 -github.tar, level 7 row 1 with dict dds, advanced one pass, 38008 -github.tar, level 7 row 1 with dict copy, advanced one pass, 37975 +github.tar, level 7 row 1 with dict dms, advanced one pass, 37832 +github.tar, level 7 row 1 with dict dds, advanced one pass, 37857 +github.tar, level 7 row 1 with dict copy, advanced one pass, 37839 github.tar, level 7 row 1 with dict load, advanced one pass, 37445 github.tar, level 7 row 2, advanced one pass, 38235 -github.tar, level 7 row 2 with dict dms, advanced one pass, 38164 -github.tar, level 7 row 2 with dict dds, advanced one pass, 38169 -github.tar, level 7 row 2 with dict copy, advanced one pass, 38294 +github.tar, level 7 row 2 with dict dms, advanced one pass, 38012 +github.tar, level 7 row 2 with dict dds, advanced one pass, 38014 +github.tar, level 7 row 2 with dict copy, advanced one pass, 38101 github.tar, level 7 row 2 with dict load, advanced one pass, 37552 github.tar, level 7, advanced one pass, 38168 -github.tar, level 7 with dict, advanced one pass, 37975 -github.tar, level 7 with dict dms, advanced one pass, 38001 -github.tar, level 7 with dict dds, advanced one pass, 38008 -github.tar, level 7 with dict copy, advanced one pass, 37975 +github.tar, level 7 with dict, advanced one pass, 37839 +github.tar, level 7 with dict dms, advanced one pass, 37832 +github.tar, level 7 with dict dds, advanced one pass, 37857 +github.tar, level 7 with dict copy, advanced one pass, 37839 github.tar, level 7 with dict load, advanced one pass, 37445 -github.tar, level 9, advanced one pass, 36897 -github.tar, level 9 with dict, advanced one pass, 36689 -github.tar, level 9 with dict dms, advanced one pass, 36756 -github.tar, level 9 with dict dds, advanced one pass, 36817 -github.tar, level 9 with dict copy, advanced one pass, 36689 -github.tar, level 9 with dict load, advanced one pass, 36484 -github.tar, level 11 row 1, advanced one pass, 36234 +github.tar, level 9, advanced one pass, 36723 +github.tar, level 9 with dict, advanced one pass, 36531 +github.tar, level 9 with dict dms, advanced one pass, 36615 +github.tar, level 9 with dict dds, advanced one pass, 36682 +github.tar, level 9 with dict copy, advanced one pass, 36531 +github.tar, level 9 with dict load, advanced one pass, 36322 +github.tar, level 11 row 1, advanced one pass, 36085 github.tar, level 11 row 1 with dict dms, advanced one pass, 36963 github.tar, level 11 row 1 with dict dds, advanced one pass, 36963 github.tar, level 11 row 1 with dict copy, advanced one pass, 36557 -github.tar, level 11 row 1 with dict load, advanced one pass, 36567 -github.tar, level 11 row 2, advanced one pass, 36217 +github.tar, level 11 row 1 with dict load, advanced one pass, 36423 +github.tar, level 11 row 2, advanced one pass, 36110 github.tar, level 11 row 2 with dict dms, advanced one pass, 36963 github.tar, level 11 row 2 with dict dds, advanced one pass, 36963 github.tar, level 11 row 2 with dict copy, advanced one pass, 36557 -github.tar, level 11 row 2 with dict load, advanced one pass, 36586 -github.tar, level 12 row 1, advanced one pass, 36234 +github.tar, level 11 row 2 with dict load, advanced one pass, 36459 +github.tar, level 12 row 1, advanced one pass, 36085 github.tar, level 12 row 1 with dict dms, advanced one pass, 36986 github.tar, level 12 row 1 with dict dds, advanced one pass, 36986 github.tar, level 12 row 1 with dict copy, advanced one pass, 36609 -github.tar, level 12 row 1 with dict load, advanced one pass, 36567 -github.tar, level 12 row 2, advanced one pass, 36217 +github.tar, level 12 row 1 with dict load, advanced one pass, 36423 +github.tar, level 12 row 2, advanced one pass, 36110 github.tar, level 12 row 2 with dict dms, advanced one pass, 36986 github.tar, level 12 row 2 with dict dds, advanced one pass, 36986 github.tar, level 12 row 2 with dict copy, advanced one pass, 36609 -github.tar, level 12 row 2 with dict load, advanced one pass, 36586 +github.tar, level 12 row 2 with dict load, advanced one pass, 36459 github.tar, level 13, advanced one pass, 35501 github.tar, level 13 with dict, advanced one pass, 37130 github.tar, level 13 with dict dms, advanced one pass, 37220 @@ -560,12 +560,12 @@ silesia, level 6, advanced silesia, level 7 row 1, advanced one pass small out, 4567954 silesia, level 7 row 2, advanced one pass small out, 4562774 silesia, level 7, advanced one pass small out, 4567954 -silesia, level 9, advanced one pass small out, 4543669 -silesia, level 11 row 1, advanced one pass small out, 4503577 -silesia, level 11 row 2, advanced one pass small out, 4501229 -silesia, level 12 row 1, advanced one pass small out, 4503577 -silesia, level 12 row 2, advanced one pass small out, 4501229 -silesia, level 13, advanced one pass small out, 4484875 +silesia, level 9, advanced one pass small out, 4535624 +silesia, level 11 row 1, advanced one pass small out, 4495623 +silesia, level 11 row 2, advanced one pass small out, 4493258 +silesia, level 12 row 1, advanced one pass small out, 4495623 +silesia, level 12 row 2, advanced one pass small out, 4493258 +silesia, level 13, advanced one pass small out, 4484013 silesia, level 16, advanced one pass small out, 4356207 silesia, level 19, advanced one pass small out, 4266751 silesia, no source size, advanced one pass small out, 4838417 @@ -594,12 +594,12 @@ silesia.tar, level 6, advanced silesia.tar, level 7 row 1, advanced one pass small out, 4570873 silesia.tar, level 7 row 2, advanced one pass small out, 4566314 silesia.tar, level 7, advanced one pass small out, 4570873 -silesia.tar, level 9, advanced one pass small out, 4546477 -silesia.tar, level 11 row 1, advanced one pass small out, 4505875 -silesia.tar, level 11 row 2, advanced one pass small out, 4504435 -silesia.tar, level 12 row 1, advanced one pass small out, 4505461 -silesia.tar, level 12 row 2, advanced one pass small out, 4504644 -silesia.tar, level 13, advanced one pass small out, 4486256 +silesia.tar, level 9, advanced one pass small out, 4537558 +silesia.tar, level 11 row 1, advanced one pass small out, 4496590 +silesia.tar, level 11 row 2, advanced one pass small out, 4495225 +silesia.tar, level 12 row 1, advanced one pass small out, 4496084 +silesia.tar, level 12 row 2, advanced one pass small out, 4495434 +silesia.tar, level 13, advanced one pass small out, 4484732 silesia.tar, level 16, advanced one pass small out, 4355572 silesia.tar, level 19, advanced one pass small out, 4257629 silesia.tar, no source size, advanced one pass small out, 4843429 @@ -792,47 +792,47 @@ github.tar, level 6 with dict dds, advanced github.tar, level 6 with dict copy, advanced one pass small out, 38808 github.tar, level 6 with dict load, advanced one pass small out, 38796 github.tar, level 7 row 1, advanced one pass small out, 38168 -github.tar, level 7 row 1 with dict dms, advanced one pass small out, 38001 -github.tar, level 7 row 1 with dict dds, advanced one pass small out, 38008 -github.tar, level 7 row 1 with dict copy, advanced one pass small out, 37975 +github.tar, level 7 row 1 with dict dms, advanced one pass small out, 37832 +github.tar, level 7 row 1 with dict dds, advanced one pass small out, 37857 +github.tar, level 7 row 1 with dict copy, advanced one pass small out, 37839 github.tar, level 7 row 1 with dict load, advanced one pass small out, 37445 github.tar, level 7 row 2, advanced one pass small out, 38235 -github.tar, level 7 row 2 with dict dms, advanced one pass small out, 38164 -github.tar, level 7 row 2 with dict dds, advanced one pass small out, 38169 -github.tar, level 7 row 2 with dict copy, advanced one pass small out, 38294 +github.tar, level 7 row 2 with dict dms, advanced one pass small out, 38012 +github.tar, level 7 row 2 with dict dds, advanced one pass small out, 38014 +github.tar, level 7 row 2 with dict copy, advanced one pass small out, 38101 github.tar, level 7 row 2 with dict load, advanced one pass small out, 37552 github.tar, level 7, advanced one pass small out, 38168 -github.tar, level 7 with dict, advanced one pass small out, 37975 -github.tar, level 7 with dict dms, advanced one pass small out, 38001 -github.tar, level 7 with dict dds, advanced one pass small out, 38008 -github.tar, level 7 with dict copy, advanced one pass small out, 37975 +github.tar, level 7 with dict, advanced one pass small out, 37839 +github.tar, level 7 with dict dms, advanced one pass small out, 37832 +github.tar, level 7 with dict dds, advanced one pass small out, 37857 +github.tar, level 7 with dict copy, advanced one pass small out, 37839 github.tar, level 7 with dict load, advanced one pass small out, 37445 -github.tar, level 9, advanced one pass small out, 36897 -github.tar, level 9 with dict, advanced one pass small out, 36689 -github.tar, level 9 with dict dms, advanced one pass small out, 36756 -github.tar, level 9 with dict dds, advanced one pass small out, 36817 -github.tar, level 9 with dict copy, advanced one pass small out, 36689 -github.tar, level 9 with dict load, advanced one pass small out, 36484 -github.tar, level 11 row 1, advanced one pass small out, 36234 +github.tar, level 9, advanced one pass small out, 36723 +github.tar, level 9 with dict, advanced one pass small out, 36531 +github.tar, level 9 with dict dms, advanced one pass small out, 36615 +github.tar, level 9 with dict dds, advanced one pass small out, 36682 +github.tar, level 9 with dict copy, advanced one pass small out, 36531 +github.tar, level 9 with dict load, advanced one pass small out, 36322 +github.tar, level 11 row 1, advanced one pass small out, 36085 github.tar, level 11 row 1 with dict dms, advanced one pass small out, 36963 github.tar, level 11 row 1 with dict dds, advanced one pass small out, 36963 github.tar, level 11 row 1 with dict copy, advanced one pass small out, 36557 -github.tar, level 11 row 1 with dict load, advanced one pass small out, 36567 -github.tar, level 11 row 2, advanced one pass small out, 36217 +github.tar, level 11 row 1 with dict load, advanced one pass small out, 36423 +github.tar, level 11 row 2, advanced one pass small out, 36110 github.tar, level 11 row 2 with dict dms, advanced one pass small out, 36963 github.tar, level 11 row 2 with dict dds, advanced one pass small out, 36963 github.tar, level 11 row 2 with dict copy, advanced one pass small out, 36557 -github.tar, level 11 row 2 with dict load, advanced one pass small out, 36586 -github.tar, level 12 row 1, advanced one pass small out, 36234 +github.tar, level 11 row 2 with dict load, advanced one pass small out, 36459 +github.tar, level 12 row 1, advanced one pass small out, 36085 github.tar, level 12 row 1 with dict dms, advanced one pass small out, 36986 github.tar, level 12 row 1 with dict dds, advanced one pass small out, 36986 github.tar, level 12 row 1 with dict copy, advanced one pass small out, 36609 -github.tar, level 12 row 1 with dict load, advanced one pass small out, 36567 -github.tar, level 12 row 2, advanced one pass small out, 36217 +github.tar, level 12 row 1 with dict load, advanced one pass small out, 36423 +github.tar, level 12 row 2, advanced one pass small out, 36110 github.tar, level 12 row 2 with dict dms, advanced one pass small out, 36986 github.tar, level 12 row 2 with dict dds, advanced one pass small out, 36986 github.tar, level 12 row 2 with dict copy, advanced one pass small out, 36609 -github.tar, level 12 row 2 with dict load, advanced one pass small out, 36586 +github.tar, level 12 row 2 with dict load, advanced one pass small out, 36459 github.tar, level 13, advanced one pass small out, 35501 github.tar, level 13 with dict, advanced one pass small out, 37130 github.tar, level 13 with dict dms, advanced one pass small out, 37220 From 18b1e67223823e48a96ed9f2ae489e8989802e42 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 16:51:52 -0700 Subject: [PATCH 424/937] fixed extraneous return strict C90 compliance test --- lib/compress/zstd_preSplit.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 2e65f88d9..4ca30dfce 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -63,7 +63,7 @@ FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, s #define ZSTD_GEN_ADDEVENTS_SAMPLE(_rate) \ static void ADDEVENTS_RATE(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ { \ - return addEvents_generic(fp, src, srcSize, _rate); \ + addEvents_generic(fp, src, srcSize, _rate); \ } ZSTD_GEN_ADDEVENTS_SAMPLE(1); From 57239c4d3b5a21529ade206241f3f0a4815f2295 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 22 Oct 2024 21:49:35 -0700 Subject: [PATCH 425/937] fixed minor strict pedantic C90 issue --- lib/compress/zstd_preSplit.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 4ca30dfce..e8994dcde 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -66,8 +66,8 @@ FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, s addEvents_generic(fp, src, srcSize, _rate); \ } -ZSTD_GEN_ADDEVENTS_SAMPLE(1); -ZSTD_GEN_ADDEVENTS_SAMPLE(5); +ZSTD_GEN_ADDEVENTS_SAMPLE(1) +ZSTD_GEN_ADDEVENTS_SAMPLE(5) typedef void (*addEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); From b68ddce818c274b9651ba47d45e46f7ffb4592ae Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 11:10:07 -0700 Subject: [PATCH 426/937] rewrite fingerprint storage to no longer need 64-bit members so that it can be stored using standard alignment requirement (sizeof(void*)). Distance function still requires 64-bit signed multiplication though, so it won't change the issue regarding the bug in ubsan for clang 32-bit on github ci. --- lib/compress/zstd_compress.c | 6 +++--- lib/compress/zstd_preSplit.c | 20 ++++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 05c1faa9f..b064e382c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -141,7 +141,7 @@ ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize) if (!ZSTD_cwksp_check_available(&cctx->workspace, TMP_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t))) return NULL; cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); cctx->blockState.nextCBlock = (ZSTD_compressedBlockState_t*)ZSTD_cwksp_reserve_object(&cctx->workspace, sizeof(ZSTD_compressedBlockState_t)); - cctx->tmpWorkspace = ZSTD_cwksp_reserve_object_aligned(&cctx->workspace, TMP_WORKSPACE_SIZE, sizeof(S64)); + cctx->tmpWorkspace = ZSTD_cwksp_reserve_object(&cctx->workspace, TMP_WORKSPACE_SIZE); cctx->tmpWkspSize = TMP_WORKSPACE_SIZE; cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid()); return cctx; @@ -1709,7 +1709,7 @@ static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal( size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize) + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(seqDef)) + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE)); - size_t const tmpWorkSpace = ZSTD_cwksp_aligned_alloc_size(TMP_WORKSPACE_SIZE, sizeof(S64)); + size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE); size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t)); size_t const matchStateSize = ZSTD_sizeof_matchState(cParams, useRowMatchFinder, /* enableDedicatedDictSearch */ 0, /* forCCtx */ 1); @@ -2174,7 +2174,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, RETURN_ERROR_IF(zc->blockState.prevCBlock == NULL, memory_allocation, "couldn't allocate prevCBlock"); zc->blockState.nextCBlock = (ZSTD_compressedBlockState_t*) ZSTD_cwksp_reserve_object(ws, sizeof(ZSTD_compressedBlockState_t)); RETURN_ERROR_IF(zc->blockState.nextCBlock == NULL, memory_allocation, "couldn't allocate nextCBlock"); - zc->tmpWorkspace = ZSTD_cwksp_reserve_object_aligned(ws, TMP_WORKSPACE_SIZE, sizeof(S64)); + zc->tmpWorkspace = ZSTD_cwksp_reserve_object(ws, TMP_WORKSPACE_SIZE); RETURN_ERROR_IF(zc->tmpWorkspace == NULL, memory_allocation, "couldn't allocate tmpWorkspace"); zc->tmpWkspSize = TMP_WORKSPACE_SIZE; } } diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index e8994dcde..c658f6fe5 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -33,8 +33,8 @@ static unsigned hash2(const void *p) typedef struct { - int events[HASHTABLESIZE]; - S64 nbEvents; + unsigned events[HASHTABLESIZE]; + size_t nbEvents; } Fingerprint; typedef struct { Fingerprint pastEvents; @@ -78,15 +78,15 @@ static void recordFingerprint(Fingerprint* fp, const void* src, size_t s, addEve addEvents(fp, src, s); } -static S64 abs64(S64 i) { return (i < 0) ? -i : i; } +static U64 abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } -static S64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) +static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) { - S64 distance = 0; + U64 distance = 0; size_t n; for (n = 0; n < HASHTABLESIZE; n++) { distance += - abs64(fp1->events[n] * fp2->nbEvents - fp2->events[n] * fp1->nbEvents); + abs64((S64)fp1->events[n] * (S64)fp2->nbEvents - (S64)fp2->events[n] * (S64)fp1->nbEvents); } return distance; } @@ -100,9 +100,9 @@ static int compareFingerprints(const Fingerprint* ref, { assert(ref->nbEvents > 0); assert(newfp->nbEvents > 0); - { S64 p50 = ref->nbEvents * newfp->nbEvents; - S64 deviation = fpDistance(ref, newfp); - S64 threshold = p50 * (THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; + { U64 p50 = (U64)ref->nbEvents * (U64)newfp->nbEvents; + U64 deviation = fpDistance(ref, newfp); + U64 threshold = p50 * (U64)(THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; return deviation >= threshold; } } @@ -150,7 +150,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, assert(blockSizeMax == (128 << 10)); assert(workspace != NULL); assert((size_t)workspace % ZSTD_ALIGNOF(FPStats) == 0); - ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE == sizeof(FPStats)); + ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE >= sizeof(FPStats)); assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; initStats(fpstats); From 7d3e5e3ba1007635fc991a3b208353463cb2712d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 14:11:49 -0700 Subject: [PATCH 427/937] split all full 128 KB blocks this helps make the streaming behavior more consistent, since it does no longer depend on having more data presented on the input. suggested by @terrelln --- lib/compress/zstd_compress.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index b064e382c..9de92cef2 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4493,20 +4493,21 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) { - /* note: conservatively only split full blocks (128 KB) currently, - * and even then only if there is more than 128 KB input remaining. + /* note: conservatively only split full blocks (128 KB) currently. + * While it's possible to go lower, let's keep it simple for a first implementation. + * Besides, benefits of splitting are reduced when blocks are already small. */ - if (srcSize <= 128 KB || blockSizeMax < 128 KB) + if (srcSize < 128 KB || blockSizeMax < 128 KB) return MIN(srcSize, blockSizeMax); /* dynamic splitting has a cpu cost for analysis, - * due to that cost it's only used for btlazy2+ strategies */ + * due to that cost it's only used for higher levels */ if (strat >= ZSTD_btopt) return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_lazy2) return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy - * no cpu cost, but can over-split homegeneous data. * heuristic, tested as being "generally better". + * no cpu cost, but can over-split homegeneous data. * do not split incompressible data though: respect the 3 bytes per block overhead limit. */ return savings ? 92 KB : 128 KB; From c80645a055d19f7e77cff3c268d818f811b9e1bb Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 14:55:10 -0700 Subject: [PATCH 428/937] stricter limits to ensure expansion factor with blind-split strategy issue reported by @terrelln --- lib/compress/zstd_compress.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9de92cef2..3ab7414d4 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4506,11 +4506,11 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src if (strat >= ZSTD_lazy2) return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy - * heuristic, tested as being "generally better". + * heuristic value, tested as being "generally better". * no cpu cost, but can over-split homegeneous data. * do not split incompressible data though: respect the 3 bytes per block overhead limit. */ - return savings ? 92 KB : 128 KB; + return (savings > 3) ? 92 KB : 128 KB; } /*! ZSTD_compress_frameChunk() : @@ -4587,8 +4587,22 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, } } /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/ + /* @savings is employed by the blind-split strategy, + * to authorize splitting into less-than-full blocks, + * and thus avoid oversplitting blocks in case of incompressible data: + * when @savings is not large enough, blind split is disactivated, and full block is used instead. + * If data is incompressible, it's allowed to expand it by 3-bytes per full block. + * For large data, a full block is 128 KB. + * blind-split will instead use 92 KB as block size. + * So it expands incompressible data by 3-bytes per 92 KB block. + * That's an over-expansion of ((128*3) - (92*3)) / 128 = 0.84 bytes per block. + * Therefore, when data doesn't shrink, we subtract a 1 byte malus from @savings. + * This is a conservative estimate, especially as we don't count the 3-bytes header when there are savings, + * but it doesn't matter, the goal is not accuracy, + * the goal is to ensure the 3-bytes expansion limit per 128 KB input can never be breached */ if (cSize < blockSize) savings += (blockSize - cSize); - else if (savings) savings--; + else savings--; + ip += blockSize; assert(remaining >= blockSize); remaining -= blockSize; From bbda1acf85d8e2f4045156e14943817c0a389503 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 15:56:56 -0700 Subject: [PATCH 429/937] update regression results --- tests/regression/results.csv | 482 +++++++++++++++++------------------ 1 file changed, 241 insertions(+), 241 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 3a14793dd..2ac686962 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -97,9 +97,9 @@ github, uncompressed literals, compress github, uncompressed literals optimal, compress cctx, 132879 github, huffman literals, compress cctx, 175468 github, multithreaded with advanced params, compress cctx, 141069 -silesia, level -5, zstdcli, 6856076 -silesia, level -3, zstdcli, 6505583 -silesia, level -1, zstdcli, 6172652 +silesia, level -5, zstdcli, 6856073 +silesia, level -3, zstdcli, 6505580 +silesia, level -1, zstdcli, 6172649 silesia, level 0, zstdcli, 4838997 silesia, level 1, zstdcli, 5306179 silesia, level 3, zstdcli, 4838997 @@ -864,20 +864,20 @@ github.tar, uncompressed literals, advanced github.tar, uncompressed literals optimal, advanced one pass small out, 35356 github.tar, huffman literals, advanced one pass small out, 39099 github.tar, multithreaded with advanced params, advanced one pass small out, 41700 -silesia, level -5, advanced streaming, 6854744 -silesia, level -3, advanced streaming, 6503319 -silesia, level -1, advanced streaming, 6172207 -silesia, level 0, advanced streaming, 4839431 -silesia, level 1, advanced streaming, 5306388 -silesia, level 3, advanced streaming, 4839431 -silesia, level 4, advanced streaming, 4776557 -silesia, level 5 row 1, advanced streaming, 4667668 -silesia, level 5 row 2, advanced streaming, 4670326 -silesia, level 5, advanced streaming, 4667668 -silesia, level 6, advanced streaming, 4604351 -silesia, level 7 row 1, advanced streaming, 4570271 -silesia, level 7 row 2, advanced streaming, 4565169 -silesia, level 7, advanced streaming, 4570271 +silesia, level -5, advanced streaming, 6856699 +silesia, level -3, advanced streaming, 6505694 +silesia, level -1, advanced streaming, 6174139 +silesia, level 0, advanced streaming, 4839173 +silesia, level 1, advanced streaming, 5305682 +silesia, level 3, advanced streaming, 4839173 +silesia, level 4, advanced streaming, 4776074 +silesia, level 5 row 1, advanced streaming, 4667049 +silesia, level 5 row 2, advanced streaming, 4669474 +silesia, level 5, advanced streaming, 4667049 +silesia, level 6, advanced streaming, 4602956 +silesia, level 7 row 1, advanced streaming, 4568785 +silesia, level 7 row 2, advanced streaming, 4563722 +silesia, level 7, advanced streaming, 4568785 silesia, level 9, advanced streaming, 4545850 silesia, level 11 row 1, advanced streaming, 4505658 silesia, level 11 row 2, advanced streaming, 4503429 @@ -886,32 +886,32 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced streaming, 4493990 silesia, level 16, advanced streaming, 4359652 silesia, level 19, advanced streaming, 4266582 -silesia, no source size, advanced streaming, 4839395 -silesia, long distance mode, advanced streaming, 4831158 +silesia, no source size, advanced streaming, 4839137 +silesia, long distance mode, advanced streaming, 4831125 silesia, multithreaded, advanced streaming, 4838949 silesia, multithreaded long distance mode, advanced streaming, 4830419 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6526141 silesia, small chain log, advanced streaming, 4912197 -silesia, explicit params, advanced streaming, 4795857 -silesia, uncompressed literals, advanced streaming, 5116957 +silesia, explicit params, advanced streaming, 4795053 +silesia, uncompressed literals, advanced streaming, 5117625 silesia, uncompressed literals optimal, advanced streaming, 4316880 -silesia, huffman literals, advanced streaming, 5321370 +silesia, huffman literals, advanced streaming, 5321812 silesia, multithreaded with advanced params, advanced streaming, 5117795 -silesia.tar, level -5, advanced streaming, 6856523 -silesia.tar, level -3, advanced streaming, 6505954 -silesia.tar, level -1, advanced streaming, 6179056 -silesia.tar, level 0, advanced streaming, 4858632 -silesia.tar, level 1, advanced streaming, 5327708 -silesia.tar, level 3, advanced streaming, 4858632 -silesia.tar, level 4, advanced streaming, 4796895 -silesia.tar, level 5 row 1, advanced streaming, 4679020 -silesia.tar, level 5 row 2, advanced streaming, 4682355 -silesia.tar, level 5, advanced streaming, 4679020 -silesia.tar, level 6, advanced streaming, 4614558 -silesia.tar, level 7 row 1, advanced streaming, 4579823 -silesia.tar, level 7 row 2, advanced streaming, 4575601 -silesia.tar, level 7, advanced streaming, 4579823 +silesia.tar, level -5, advanced streaming, 6857458 +silesia.tar, level -3, advanced streaming, 6508562 +silesia.tar, level -1, advanced streaming, 6178057 +silesia.tar, level 0, advanced streaming, 4849720 +silesia.tar, level 1, advanced streaming, 5311452 +silesia.tar, level 3, advanced streaming, 4849720 +silesia.tar, level 4, advanced streaming, 4787534 +silesia.tar, level 5 row 1, advanced streaming, 4669420 +silesia.tar, level 5 row 2, advanced streaming, 4673610 +silesia.tar, level 5, advanced streaming, 4669420 +silesia.tar, level 6, advanced streaming, 4604125 +silesia.tar, level 7 row 1, advanced streaming, 4570206 +silesia.tar, level 7 row 2, advanced streaming, 4565792 +silesia.tar, level 7, advanced streaming, 4570206 silesia.tar, level 9, advanced streaming, 4555445 silesia.tar, level 11 row 1, advanced streaming, 4514959 silesia.tar, level 11 row 2, advanced streaming, 4513810 @@ -920,17 +920,17 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced streaming, 4502956 silesia.tar, level 16, advanced streaming, 4360385 silesia.tar, level 19, advanced streaming, 4260939 -silesia.tar, no source size, advanced streaming, 4858628 -silesia.tar, long distance mode, advanced streaming, 4837775 +silesia.tar, no source size, advanced streaming, 4849716 +silesia.tar, long distance mode, advanced streaming, 4829339 silesia.tar, multithreaded, advanced streaming, 4841902 silesia.tar, multithreaded long distance mode, advanced streaming, 4834262 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529209 silesia.tar, small chain log, advanced streaming, 4917021 -silesia.tar, explicit params, advanced streaming, 4807288 -silesia.tar, uncompressed literals, advanced streaming, 5126542 +silesia.tar, explicit params, advanced streaming, 4797673 +silesia.tar, uncompressed literals, advanced streaming, 5124811 silesia.tar, uncompressed literals optimal, advanced streaming, 4308451 -silesia.tar, huffman literals, advanced streaming, 5341712 +silesia.tar, huffman literals, advanced streaming, 5326278 silesia.tar, multithreaded with advanced params, advanced streaming, 5116442 github, level -5, advanced streaming, 204407 github, level -5 with dict, advanced streaming, 45832 @@ -1057,74 +1057,74 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced streaming, 152667 github, huffman literals, advanced streaming, 142365 github, multithreaded with advanced params, advanced streaming, 165909 -github.tar, level -5, advanced streaming, 52152 -github.tar, level -5 with dict, advanced streaming, 51181 -github.tar, level -3, advanced streaming, 45678 -github.tar, level -3 with dict, advanced streaming, 44734 -github.tar, level -1, advanced streaming, 42560 -github.tar, level -1 with dict, advanced streaming, 41353 -github.tar, level 0, advanced streaming, 38884 -github.tar, level 0 with dict, advanced streaming, 37995 -github.tar, level 0 with dict dms, advanced streaming, 38114 -github.tar, level 0 with dict dds, advanced streaming, 38114 -github.tar, level 0 with dict copy, advanced streaming, 37995 -github.tar, level 0 with dict load, advanced streaming, 37956 -github.tar, level 1, advanced streaming, 39200 -github.tar, level 1 with dict, advanced streaming, 38119 -github.tar, level 1 with dict dms, advanced streaming, 38406 -github.tar, level 1 with dict dds, advanced streaming, 38406 -github.tar, level 1 with dict copy, advanced streaming, 38119 -github.tar, level 1 with dict load, advanced streaming, 38364 -github.tar, level 3, advanced streaming, 38884 -github.tar, level 3 with dict, advanced streaming, 37995 -github.tar, level 3 with dict dms, advanced streaming, 38114 -github.tar, level 3 with dict dds, advanced streaming, 38114 -github.tar, level 3 with dict copy, advanced streaming, 37995 -github.tar, level 3 with dict load, advanced streaming, 37956 -github.tar, level 4, advanced streaming, 38880 -github.tar, level 4 with dict, advanced streaming, 37948 -github.tar, level 4 with dict dms, advanced streaming, 37995 -github.tar, level 4 with dict dds, advanced streaming, 37995 -github.tar, level 4 with dict copy, advanced streaming, 37948 -github.tar, level 4 with dict load, advanced streaming, 37927 -github.tar, level 5 row 1, advanced streaming, 39651 -github.tar, level 5 row 1 with dict dms, advanced streaming, 39043 -github.tar, level 5 row 1 with dict dds, advanced streaming, 39069 -github.tar, level 5 row 1 with dict copy, advanced streaming, 39145 -github.tar, level 5 row 1 with dict load, advanced streaming, 39000 -github.tar, level 5 row 2, advanced streaming, 39701 -github.tar, level 5 row 2 with dict dms, advanced streaming, 39365 -github.tar, level 5 row 2 with dict dds, advanced streaming, 39233 -github.tar, level 5 row 2 with dict copy, advanced streaming, 39715 -github.tar, level 5 row 2 with dict load, advanced streaming, 39158 -github.tar, level 5, advanced streaming, 39651 -github.tar, level 5 with dict, advanced streaming, 39145 -github.tar, level 5 with dict dms, advanced streaming, 39043 -github.tar, level 5 with dict dds, advanced streaming, 39069 -github.tar, level 5 with dict copy, advanced streaming, 39145 -github.tar, level 5 with dict load, advanced streaming, 39000 -github.tar, level 6, advanced streaming, 39282 -github.tar, level 6 with dict, advanced streaming, 38656 -github.tar, level 6 with dict dms, advanced streaming, 38640 -github.tar, level 6 with dict dds, advanced streaming, 38643 -github.tar, level 6 with dict copy, advanced streaming, 38656 -github.tar, level 6 with dict load, advanced streaming, 38647 -github.tar, level 7 row 1, advanced streaming, 38005 +github.tar, level -5, advanced streaming, 52384 +github.tar, level -5 with dict, advanced streaming, 51420 +github.tar, level -3, advanced streaming, 45907 +github.tar, level -3 with dict, advanced streaming, 44973 +github.tar, level -1, advanced streaming, 42777 +github.tar, level -1 with dict, advanced streaming, 41603 +github.tar, level 0, advanced streaming, 39249 +github.tar, level 0 with dict, advanced streaming, 38309 +github.tar, level 0 with dict dms, advanced streaming, 38445 +github.tar, level 0 with dict dds, advanced streaming, 38445 +github.tar, level 0 with dict copy, advanced streaming, 38309 +github.tar, level 0 with dict load, advanced streaming, 38281 +github.tar, level 1, advanced streaming, 39550 +github.tar, level 1 with dict, advanced streaming, 38502 +github.tar, level 1 with dict dms, advanced streaming, 38770 +github.tar, level 1 with dict dds, advanced streaming, 38770 +github.tar, level 1 with dict copy, advanced streaming, 38502 +github.tar, level 1 with dict load, advanced streaming, 38716 +github.tar, level 3, advanced streaming, 39249 +github.tar, level 3 with dict, advanced streaming, 38309 +github.tar, level 3 with dict dms, advanced streaming, 38445 +github.tar, level 3 with dict dds, advanced streaming, 38445 +github.tar, level 3 with dict copy, advanced streaming, 38309 +github.tar, level 3 with dict load, advanced streaming, 38281 +github.tar, level 4, advanced streaming, 39247 +github.tar, level 4 with dict, advanced streaming, 38270 +github.tar, level 4 with dict dms, advanced streaming, 38317 +github.tar, level 4 with dict dds, advanced streaming, 38317 +github.tar, level 4 with dict copy, advanced streaming, 38270 +github.tar, level 4 with dict load, advanced streaming, 38259 +github.tar, level 5 row 1, advanced streaming, 39986 +github.tar, level 5 row 1 with dict dms, advanced streaming, 39370 +github.tar, level 5 row 1 with dict dds, advanced streaming, 39396 +github.tar, level 5 row 1 with dict copy, advanced streaming, 39465 +github.tar, level 5 row 1 with dict load, advanced streaming, 39332 +github.tar, level 5 row 2, advanced streaming, 40038 +github.tar, level 5 row 2 with dict dms, advanced streaming, 39690 +github.tar, level 5 row 2 with dict dds, advanced streaming, 39555 +github.tar, level 5 row 2 with dict copy, advanced streaming, 40036 +github.tar, level 5 row 2 with dict load, advanced streaming, 39498 +github.tar, level 5, advanced streaming, 39986 +github.tar, level 5 with dict, advanced streaming, 39465 +github.tar, level 5 with dict dms, advanced streaming, 39370 +github.tar, level 5 with dict dds, advanced streaming, 39396 +github.tar, level 5 with dict copy, advanced streaming, 39465 +github.tar, level 5 with dict load, advanced streaming, 39332 +github.tar, level 6, advanced streaming, 39565 +github.tar, level 6 with dict, advanced streaming, 38894 +github.tar, level 6 with dict dms, advanced streaming, 38901 +github.tar, level 6 with dict dds, advanced streaming, 38903 +github.tar, level 6 with dict copy, advanced streaming, 38894 +github.tar, level 6 with dict load, advanced streaming, 38906 +github.tar, level 7 row 1, advanced streaming, 38295 github.tar, level 7 row 1 with dict dms, advanced streaming, 37832 github.tar, level 7 row 1 with dict dds, advanced streaming, 37857 github.tar, level 7 row 1 with dict copy, advanced streaming, 37839 -github.tar, level 7 row 1 with dict load, advanced streaming, 37286 -github.tar, level 7 row 2, advanced streaming, 38077 +github.tar, level 7 row 1 with dict load, advanced streaming, 37565 +github.tar, level 7 row 2, advanced streaming, 38369 github.tar, level 7 row 2 with dict dms, advanced streaming, 38012 github.tar, level 7 row 2 with dict dds, advanced streaming, 38014 github.tar, level 7 row 2 with dict copy, advanced streaming, 38101 -github.tar, level 7 row 2 with dict load, advanced streaming, 37402 -github.tar, level 7, advanced streaming, 38005 +github.tar, level 7 row 2 with dict load, advanced streaming, 37688 +github.tar, level 7, advanced streaming, 38295 github.tar, level 7 with dict, advanced streaming, 37839 github.tar, level 7 with dict dms, advanced streaming, 37832 github.tar, level 7 with dict dds, advanced streaming, 37857 github.tar, level 7 with dict copy, advanced streaming, 37839 -github.tar, level 7 with dict load, advanced streaming, 37286 +github.tar, level 7 with dict load, advanced streaming, 37565 github.tar, level 9, advanced streaming, 36723 github.tar, level 9 with dict, advanced streaming, 36531 github.tar, level 9 with dict dms, advanced streaming, 36615 @@ -1169,55 +1169,55 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced streaming, 32565 github.tar, level 19 with dict copy, advanced streaming, 32701 github.tar, level 19 with dict load, advanced streaming, 32428 -github.tar, no source size, advanced streaming, 38881 -github.tar, no source size with dict, advanced streaming, 38111 -github.tar, long distance mode, advanced streaming, 40242 +github.tar, no source size, advanced streaming, 39246 +github.tar, no source size with dict, advanced streaming, 38442 +github.tar, long distance mode, advanced streaming, 40569 github.tar, multithreaded, advanced streaming, 39067 github.tar, multithreaded long distance mode, advanced streaming, 40377 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 -github.tar, explicit params, advanced streaming, 41385 -github.tar, uncompressed literals, advanced streaming, 41562 +github.tar, explicit params, advanced streaming, 41768 +github.tar, uncompressed literals, advanced streaming, 41784 github.tar, uncompressed literals optimal, advanced streaming, 35356 -github.tar, huffman literals, advanced streaming, 38853 +github.tar, huffman literals, advanced streaming, 39226 github.tar, multithreaded with advanced params, advanced streaming, 41700 -silesia, level -5, old streaming, 6854744 -silesia, level -3, old streaming, 6503319 -silesia, level -1, old streaming, 6172207 -silesia, level 0, old streaming, 4839431 -silesia, level 1, old streaming, 5306388 -silesia, level 3, old streaming, 4839431 -silesia, level 4, old streaming, 4776557 -silesia, level 5, old streaming, 4667668 -silesia, level 6, old streaming, 4604351 -silesia, level 7, old streaming, 4570271 +silesia, level -5, old streaming, 6856699 +silesia, level -3, old streaming, 6505694 +silesia, level -1, old streaming, 6174139 +silesia, level 0, old streaming, 4839173 +silesia, level 1, old streaming, 5305682 +silesia, level 3, old streaming, 4839173 +silesia, level 4, old streaming, 4776074 +silesia, level 5, old streaming, 4667049 +silesia, level 6, old streaming, 4602956 +silesia, level 7, old streaming, 4568785 silesia, level 9, old streaming, 4545850 silesia, level 13, old streaming, 4493990 silesia, level 16, old streaming, 4359652 silesia, level 19, old streaming, 4266582 -silesia, no source size, old streaming, 4839395 -silesia, uncompressed literals, old streaming, 4839431 +silesia, no source size, old streaming, 4839137 +silesia, uncompressed literals, old streaming, 4839173 silesia, uncompressed literals optimal, old streaming, 4266582 -silesia, huffman literals, old streaming, 6172207 -silesia.tar, level -5, old streaming, 6856523 -silesia.tar, level -3, old streaming, 6505954 -silesia.tar, level -1, old streaming, 6179056 -silesia.tar, level 0, old streaming, 4858632 -silesia.tar, level 1, old streaming, 5327708 -silesia.tar, level 3, old streaming, 4858632 -silesia.tar, level 4, old streaming, 4796895 -silesia.tar, level 5, old streaming, 4679020 -silesia.tar, level 6, old streaming, 4614558 -silesia.tar, level 7, old streaming, 4579823 +silesia, huffman literals, old streaming, 6174139 +silesia.tar, level -5, old streaming, 6857458 +silesia.tar, level -3, old streaming, 6508562 +silesia.tar, level -1, old streaming, 6178057 +silesia.tar, level 0, old streaming, 4849720 +silesia.tar, level 1, old streaming, 5311452 +silesia.tar, level 3, old streaming, 4849720 +silesia.tar, level 4, old streaming, 4787534 +silesia.tar, level 5, old streaming, 4669420 +silesia.tar, level 6, old streaming, 4604125 +silesia.tar, level 7, old streaming, 4570206 silesia.tar, level 9, old streaming, 4555445 silesia.tar, level 13, old streaming, 4502956 silesia.tar, level 16, old streaming, 4360385 silesia.tar, level 19, old streaming, 4260939 -silesia.tar, no source size, old streaming, 4858628 -silesia.tar, uncompressed literals, old streaming, 4858632 +silesia.tar, no source size, old streaming, 4849716 +silesia.tar, uncompressed literals, old streaming, 4849720 silesia.tar, uncompressed literals optimal, old streaming, 4260939 -silesia.tar, huffman literals, old streaming, 6179056 +silesia.tar, huffman literals, old streaming, 6178057 github, level -5, old streaming, 204407 github, level -5 with dict, old streaming, 45832 github, level -3, old streaming, 193253 @@ -1251,25 +1251,25 @@ github, no source size with dict, old stre github, uncompressed literals, old streaming, 136331 github, uncompressed literals optimal, old streaming, 132879 github, huffman literals, old streaming, 175468 -github.tar, level -5, old streaming, 52152 -github.tar, level -5 with dict, old streaming, 51181 -github.tar, level -3, old streaming, 45678 -github.tar, level -3 with dict, old streaming, 44734 -github.tar, level -1, old streaming, 42560 -github.tar, level -1 with dict, old streaming, 41353 -github.tar, level 0, old streaming, 38884 -github.tar, level 0 with dict, old streaming, 37995 -github.tar, level 1, old streaming, 39200 -github.tar, level 1 with dict, old streaming, 38119 -github.tar, level 3, old streaming, 38884 -github.tar, level 3 with dict, old streaming, 37995 -github.tar, level 4, old streaming, 38880 -github.tar, level 4 with dict, old streaming, 37948 -github.tar, level 5, old streaming, 39651 -github.tar, level 5 with dict, old streaming, 39145 -github.tar, level 6, old streaming, 39282 -github.tar, level 6 with dict, old streaming, 38656 -github.tar, level 7, old streaming, 38005 +github.tar, level -5, old streaming, 52384 +github.tar, level -5 with dict, old streaming, 51420 +github.tar, level -3, old streaming, 45907 +github.tar, level -3 with dict, old streaming, 44973 +github.tar, level -1, old streaming, 42777 +github.tar, level -1 with dict, old streaming, 41603 +github.tar, level 0, old streaming, 39249 +github.tar, level 0 with dict, old streaming, 38309 +github.tar, level 1, old streaming, 39550 +github.tar, level 1 with dict, old streaming, 38502 +github.tar, level 3, old streaming, 39249 +github.tar, level 3 with dict, old streaming, 38309 +github.tar, level 4, old streaming, 39247 +github.tar, level 4 with dict, old streaming, 38270 +github.tar, level 5, old streaming, 39986 +github.tar, level 5 with dict, old streaming, 39465 +github.tar, level 6, old streaming, 39565 +github.tar, level 6 with dict, old streaming, 38894 +github.tar, level 7, old streaming, 38295 github.tar, level 7 with dict, old streaming, 37839 github.tar, level 9, old streaming, 36723 github.tar, level 9 with dict, old streaming, 36531 @@ -1279,63 +1279,63 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming, 33375 github.tar, level 19, old streaming, 32262 github.tar, level 19 with dict, old streaming, 32701 -github.tar, no source size, old streaming, 38881 -github.tar, no source size with dict, old streaming, 38111 -github.tar, uncompressed literals, old streaming, 38884 +github.tar, no source size, old streaming, 39246 +github.tar, no source size with dict, old streaming, 38442 +github.tar, uncompressed literals, old streaming, 39249 github.tar, uncompressed literals optimal, old streaming, 32262 -github.tar, huffman literals, old streaming, 42560 -silesia, level -5, old streaming advanced, 6854744 -silesia, level -3, old streaming advanced, 6503319 -silesia, level -1, old streaming advanced, 6172207 -silesia, level 0, old streaming advanced, 4839431 -silesia, level 1, old streaming advanced, 5306388 -silesia, level 3, old streaming advanced, 4839431 -silesia, level 4, old streaming advanced, 4776557 -silesia, level 5, old streaming advanced, 4667668 -silesia, level 6, old streaming advanced, 4604351 -silesia, level 7, old streaming advanced, 4570271 +github.tar, huffman literals, old streaming, 42777 +silesia, level -5, old streaming advanced, 6856699 +silesia, level -3, old streaming advanced, 6505694 +silesia, level -1, old streaming advanced, 6174139 +silesia, level 0, old streaming advanced, 4839173 +silesia, level 1, old streaming advanced, 5305682 +silesia, level 3, old streaming advanced, 4839173 +silesia, level 4, old streaming advanced, 4776074 +silesia, level 5, old streaming advanced, 4667049 +silesia, level 6, old streaming advanced, 4602956 +silesia, level 7, old streaming advanced, 4568785 silesia, level 9, old streaming advanced, 4545850 silesia, level 13, old streaming advanced, 4493990 silesia, level 16, old streaming advanced, 4359652 silesia, level 19, old streaming advanced, 4266582 -silesia, no source size, old streaming advanced, 4839395 -silesia, long distance mode, old streaming advanced, 4839431 -silesia, multithreaded, old streaming advanced, 4839431 -silesia, multithreaded long distance mode, old streaming advanced, 4839431 +silesia, no source size, old streaming advanced, 4839137 +silesia, long distance mode, old streaming advanced, 4839173 +silesia, multithreaded, old streaming advanced, 4839173 +silesia, multithreaded long distance mode, old streaming advanced, 4839173 silesia, small window log, old streaming advanced, 7110591 silesia, small hash log, old streaming advanced, 6526141 silesia, small chain log, old streaming advanced, 4912197 -silesia, explicit params, old streaming advanced, 4795857 -silesia, uncompressed literals, old streaming advanced, 4839431 +silesia, explicit params, old streaming advanced, 4795053 +silesia, uncompressed literals, old streaming advanced, 4839173 silesia, uncompressed literals optimal, old streaming advanced, 4266582 -silesia, huffman literals, old streaming advanced, 6172207 -silesia, multithreaded with advanced params, old streaming advanced, 4839431 -silesia.tar, level -5, old streaming advanced, 6856523 -silesia.tar, level -3, old streaming advanced, 6505954 -silesia.tar, level -1, old streaming advanced, 6179056 -silesia.tar, level 0, old streaming advanced, 4858632 -silesia.tar, level 1, old streaming advanced, 5327708 -silesia.tar, level 3, old streaming advanced, 4858632 -silesia.tar, level 4, old streaming advanced, 4796895 -silesia.tar, level 5, old streaming advanced, 4679020 -silesia.tar, level 6, old streaming advanced, 4614558 -silesia.tar, level 7, old streaming advanced, 4579823 +silesia, huffman literals, old streaming advanced, 6174139 +silesia, multithreaded with advanced params, old streaming advanced, 4839173 +silesia.tar, level -5, old streaming advanced, 6857458 +silesia.tar, level -3, old streaming advanced, 6508562 +silesia.tar, level -1, old streaming advanced, 6178057 +silesia.tar, level 0, old streaming advanced, 4849720 +silesia.tar, level 1, old streaming advanced, 5311452 +silesia.tar, level 3, old streaming advanced, 4849720 +silesia.tar, level 4, old streaming advanced, 4787534 +silesia.tar, level 5, old streaming advanced, 4669420 +silesia.tar, level 6, old streaming advanced, 4604125 +silesia.tar, level 7, old streaming advanced, 4570206 silesia.tar, level 9, old streaming advanced, 4555445 silesia.tar, level 13, old streaming advanced, 4502956 silesia.tar, level 16, old streaming advanced, 4360385 silesia.tar, level 19, old streaming advanced, 4260939 -silesia.tar, no source size, old streaming advanced, 4858628 -silesia.tar, long distance mode, old streaming advanced, 4858632 -silesia.tar, multithreaded, old streaming advanced, 4858632 -silesia.tar, multithreaded long distance mode, old streaming advanced, 4858632 +silesia.tar, no source size, old streaming advanced, 4849716 +silesia.tar, long distance mode, old streaming advanced, 4849720 +silesia.tar, multithreaded, old streaming advanced, 4849720 +silesia.tar, multithreaded long distance mode, old streaming advanced, 4849720 silesia.tar, small window log, old streaming advanced, 7117027 silesia.tar, small hash log, old streaming advanced, 6529209 silesia.tar, small chain log, old streaming advanced, 4917021 -silesia.tar, explicit params, old streaming advanced, 4807288 -silesia.tar, uncompressed literals, old streaming advanced, 4858632 +silesia.tar, explicit params, old streaming advanced, 4797673 +silesia.tar, uncompressed literals, old streaming advanced, 4849720 silesia.tar, uncompressed literals optimal, old streaming advanced, 4260939 -silesia.tar, huffman literals, old streaming advanced, 6179056 -silesia.tar, multithreaded with advanced params, old streaming advanced, 4858632 +silesia.tar, huffman literals, old streaming advanced, 6178057 +silesia.tar, multithreaded with advanced params, old streaming advanced, 4849720 github, level -5, old streaming advanced, 213265 github, level -5 with dict, old streaming advanced, 46708 github, level -3, old streaming advanced, 196126 @@ -1377,26 +1377,26 @@ github, uncompressed literals, old stre github, uncompressed literals optimal, old streaming advanced, 132879 github, huffman literals, old streaming advanced, 181107 github, multithreaded with advanced params, old streaming advanced, 141101 -github.tar, level -5, old streaming advanced, 52152 -github.tar, level -5 with dict, old streaming advanced, 51129 -github.tar, level -3, old streaming advanced, 45678 -github.tar, level -3 with dict, old streaming advanced, 44986 -github.tar, level -1, old streaming advanced, 42560 -github.tar, level -1 with dict, old streaming advanced, 41650 -github.tar, level 0, old streaming advanced, 38884 -github.tar, level 0 with dict, old streaming advanced, 38013 -github.tar, level 1, old streaming advanced, 39200 -github.tar, level 1 with dict, old streaming advanced, 38359 -github.tar, level 3, old streaming advanced, 38884 -github.tar, level 3 with dict, old streaming advanced, 38013 -github.tar, level 4, old streaming advanced, 38880 -github.tar, level 4 with dict, old streaming advanced, 38063 -github.tar, level 5, old streaming advanced, 39651 -github.tar, level 5 with dict, old streaming advanced, 39018 -github.tar, level 6, old streaming advanced, 39282 -github.tar, level 6 with dict, old streaming advanced, 38635 -github.tar, level 7, old streaming advanced, 38005 -github.tar, level 7 with dict, old streaming advanced, 37264 +github.tar, level -5, old streaming advanced, 52384 +github.tar, level -5 with dict, old streaming advanced, 51359 +github.tar, level -3, old streaming advanced, 45907 +github.tar, level -3 with dict, old streaming advanced, 45211 +github.tar, level -1, old streaming advanced, 42777 +github.tar, level -1 with dict, old streaming advanced, 41865 +github.tar, level 0, old streaming advanced, 39249 +github.tar, level 0 with dict, old streaming advanced, 38327 +github.tar, level 1, old streaming advanced, 39550 +github.tar, level 1 with dict, old streaming advanced, 38714 +github.tar, level 3, old streaming advanced, 39249 +github.tar, level 3 with dict, old streaming advanced, 38327 +github.tar, level 4, old streaming advanced, 39247 +github.tar, level 4 with dict, old streaming advanced, 38382 +github.tar, level 5, old streaming advanced, 39986 +github.tar, level 5 with dict, old streaming advanced, 39347 +github.tar, level 6, old streaming advanced, 39565 +github.tar, level 6 with dict, old streaming advanced, 38889 +github.tar, level 7, old streaming advanced, 38295 +github.tar, level 7 with dict, old streaming advanced, 37534 github.tar, level 9, old streaming advanced, 36723 github.tar, level 9 with dict, old streaming advanced, 36241 github.tar, level 13, old streaming advanced, 35501 @@ -1405,19 +1405,19 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming advanced, 38578 github.tar, level 19, old streaming advanced, 32262 github.tar, level 19 with dict, old streaming advanced, 32678 -github.tar, no source size, old streaming advanced, 38881 -github.tar, no source size with dict, old streaming advanced, 38076 -github.tar, long distance mode, old streaming advanced, 38884 -github.tar, multithreaded, old streaming advanced, 38884 -github.tar, multithreaded long distance mode, old streaming advanced, 38884 +github.tar, no source size, old streaming advanced, 39246 +github.tar, no source size with dict, old streaming advanced, 38399 +github.tar, long distance mode, old streaming advanced, 39249 +github.tar, multithreaded, old streaming advanced, 39249 +github.tar, multithreaded long distance mode, old streaming advanced, 39249 github.tar, small window log, old streaming advanced, 199556 github.tar, small hash log, old streaming advanced, 129870 github.tar, small chain log, old streaming advanced, 41669 -github.tar, explicit params, old streaming advanced, 41385 -github.tar, uncompressed literals, old streaming advanced, 38884 +github.tar, explicit params, old streaming advanced, 41768 +github.tar, uncompressed literals, old streaming advanced, 39249 github.tar, uncompressed literals optimal, old streaming advanced, 32262 -github.tar, huffman literals, old streaming advanced, 42560 -github.tar, multithreaded with advanced params, old streaming advanced, 38884 +github.tar, huffman literals, old streaming advanced, 42777 +github.tar, multithreaded with advanced params, old streaming advanced, 39249 github, level -5 with dict, old streaming cdict, 45832 github, level -3 with dict, old streaming cdict, 44671 github, level -1 with dict, old streaming cdict, 41825 @@ -1433,21 +1433,21 @@ github, level 13 with dict, old stre github, level 16 with dict, old streaming cdict, 37902 github, level 19 with dict, old streaming cdict, 37916 github, no source size with dict, old streaming cdict, 40652 -github.tar, level -5 with dict, old streaming cdict, 51286 -github.tar, level -3 with dict, old streaming cdict, 45147 -github.tar, level -1 with dict, old streaming cdict, 41865 -github.tar, level 0 with dict, old streaming cdict, 37956 -github.tar, level 1 with dict, old streaming cdict, 38364 -github.tar, level 3 with dict, old streaming cdict, 37956 -github.tar, level 4 with dict, old streaming cdict, 37927 -github.tar, level 5 with dict, old streaming cdict, 39000 -github.tar, level 6 with dict, old streaming cdict, 38647 -github.tar, level 7 with dict, old streaming cdict, 37286 +github.tar, level -5 with dict, old streaming cdict, 51512 +github.tar, level -3 with dict, old streaming cdict, 45379 +github.tar, level -1 with dict, old streaming cdict, 42084 +github.tar, level 0 with dict, old streaming cdict, 38281 +github.tar, level 1 with dict, old streaming cdict, 38716 +github.tar, level 3 with dict, old streaming cdict, 38281 +github.tar, level 4 with dict, old streaming cdict, 38259 +github.tar, level 5 with dict, old streaming cdict, 39332 +github.tar, level 6 with dict, old streaming cdict, 38906 +github.tar, level 7 with dict, old streaming cdict, 37565 github.tar, level 9 with dict, old streaming cdict, 36322 github.tar, level 13 with dict, old streaming cdict, 36010 github.tar, level 16 with dict, old streaming cdict, 39081 github.tar, level 19 with dict, old streaming cdict, 32428 -github.tar, no source size with dict, old streaming cdict, 38111 +github.tar, no source size with dict, old streaming cdict, 38442 github, level -5 with dict, old streaming advanced cdict, 46708 github, level -3 with dict, old streaming advanced cdict, 45476 github, level -1 with dict, old streaming advanced cdict, 42060 @@ -1463,18 +1463,18 @@ github, level 13 with dict, old stre github, level 16 with dict, old streaming advanced cdict, 40804 github, level 19 with dict, old streaming advanced cdict, 37916 github, no source size with dict, old streaming advanced cdict, 40608 -github.tar, level -5 with dict, old streaming advanced cdict, 50791 -github.tar, level -3 with dict, old streaming advanced cdict, 44926 -github.tar, level -1 with dict, old streaming advanced cdict, 41482 -github.tar, level 0 with dict, old streaming advanced cdict, 38013 -github.tar, level 1 with dict, old streaming advanced cdict, 38168 -github.tar, level 3 with dict, old streaming advanced cdict, 38013 -github.tar, level 4 with dict, old streaming advanced cdict, 38063 -github.tar, level 5 with dict, old streaming advanced cdict, 39018 -github.tar, level 6 with dict, old streaming advanced cdict, 38635 -github.tar, level 7 with dict, old streaming advanced cdict, 37264 +github.tar, level -5 with dict, old streaming advanced cdict, 51019 +github.tar, level -3 with dict, old streaming advanced cdict, 45149 +github.tar, level -1 with dict, old streaming advanced cdict, 41694 +github.tar, level 0 with dict, old streaming advanced cdict, 38327 +github.tar, level 1 with dict, old streaming advanced cdict, 38513 +github.tar, level 3 with dict, old streaming advanced cdict, 38327 +github.tar, level 4 with dict, old streaming advanced cdict, 38382 +github.tar, level 5 with dict, old streaming advanced cdict, 39347 +github.tar, level 6 with dict, old streaming advanced cdict, 38889 +github.tar, level 7 with dict, old streaming advanced cdict, 37534 github.tar, level 9 with dict, old streaming advanced cdict, 36241 github.tar, level 13 with dict, old streaming advanced cdict, 35807 github.tar, level 16 with dict, old streaming advanced cdict, 38578 github.tar, level 19 with dict, old streaming advanced cdict, 32678 -github.tar, no source size with dict, old streaming advanced cdict, 38076 +github.tar, no source size with dict, old streaming advanced cdict, 38399 From 90095f056d4ccb8e0ed0942b2e30a664f0489932 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 11:36:56 -0700 Subject: [PATCH 430/937] apply limit conditions for all splitting strategies instead of just for blind split. This is in anticipation of adversarial input, that would intentionally target the sampling pattern of the split detector. Note that, even without this protection, splitting can never expand beyond ZSTD_COMPRESSBOUND(), because this upper limit uses a 1KB block size worst case scenario, and splitting never creates blocks thath small. The protection is more to ensure that data is not expanded by more than 3-bytes per 128 KB full block, which is a much stricter limit. --- lib/compress/zstd_compress.c | 38 ++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 3ab7414d4..437bd1fbe 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4499,6 +4499,11 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src */ if (srcSize < 128 KB || blockSizeMax < 128 KB) return MIN(srcSize, blockSizeMax); + /* do not split incompressible data though: + * ensure a 3 bytes per full block overhead limit. + * Note: as a consequence, the first full block skips the splitting detector. + */ + if (savings < 3) return 128 KB; /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for higher levels */ if (strat >= ZSTD_btopt) @@ -4508,9 +4513,8 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src /* blind split strategy * heuristic value, tested as being "generally better". * no cpu cost, but can over-split homegeneous data. - * do not split incompressible data though: respect the 3 bytes per block overhead limit. */ - return (savings > 3) ? 92 KB : 128 KB; + return 92 KB; } /*! ZSTD_compress_frameChunk() : @@ -4587,21 +4591,21 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, } } /* if (ZSTD_useTargetCBlockSize(&cctx->appliedParams))*/ - /* @savings is employed by the blind-split strategy, - * to authorize splitting into less-than-full blocks, - * and thus avoid oversplitting blocks in case of incompressible data: - * when @savings is not large enough, blind split is disactivated, and full block is used instead. - * If data is incompressible, it's allowed to expand it by 3-bytes per full block. - * For large data, a full block is 128 KB. - * blind-split will instead use 92 KB as block size. - * So it expands incompressible data by 3-bytes per 92 KB block. - * That's an over-expansion of ((128*3) - (92*3)) / 128 = 0.84 bytes per block. - * Therefore, when data doesn't shrink, we subtract a 1 byte malus from @savings. - * This is a conservative estimate, especially as we don't count the 3-bytes header when there are savings, - * but it doesn't matter, the goal is not accuracy, - * the goal is to ensure the 3-bytes expansion limit per 128 KB input can never be breached */ - if (cSize < blockSize) savings += (blockSize - cSize); - else savings--; + /* @savings is employed to ensure that splitting doesn't worsen expansion of incompressible data. + * Without splitting, the maximum expansion is 3 bytes per full block. + * An adversarial input could attempt to fudge the split detector, + * and make it split incompressible data, resulting in more block headers. + * Note that, since ZSTD_COMPRESSBOUND() assumes a worst case scenario of 1KB per block, + * and the splitter never creates blocks that small (current lower limit is 8 KB), + * there is already no risk to expand beyond ZSTD_COMPRESSBOUND() limit. + * But if the goal is to not expand by more than 3-bytes per 128 KB full block, + * then yes, it becomes possible to make the block splitter oversplit incompressible data. + * Using @savings, we enforce an even more conservative condition, + * requiring the presence of enough savings (at least 3 bytes) to authorize splitting, + * otherwise only full blocks are used. + * But being conservative is fine, + * since splitting barely compressible blocks is not fruitful anyway */ + savings += (S64)blockSize - (S64)cSize; ip += blockSize; assert(remaining >= blockSize); From 70c77d20d63454b58e220c235e215147a357220c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 11:43:16 -0700 Subject: [PATCH 431/937] update regression results first block is no longer splitted since adding the @savings over-split protection --- tests/regression/results.csv | 72 ++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 2ac686962..ea5ed58d5 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -43,19 +43,19 @@ silesia, level 4, compress silesia, level 5, compress cctx, 4666524 silesia, level 6, compress cctx, 4602031 silesia, level 7, compress cctx, 4567954 -silesia, level 9, compress cctx, 4535624 -silesia, level 13, compress cctx, 4484013 -silesia, level 16, compress cctx, 4356207 -silesia, level 19, compress cctx, 4266751 +silesia, level 9, compress cctx, 4540520 +silesia, level 13, compress cctx, 4488969 +silesia, level 16, compress cctx, 4356799 +silesia, level 19, compress cctx, 4265851 silesia, long distance mode, compress cctx, 4838417 silesia, multithreaded, compress cctx, 4838417 silesia, multithreaded long distance mode, compress cctx, 4838417 silesia, small window log, compress cctx, 7082907 -silesia, small hash log, compress cctx, 6524931 -silesia, small chain log, compress cctx, 4912322 +silesia, small hash log, compress cctx, 6525510 +silesia, small chain log, compress cctx, 4912248 silesia, explicit params, compress cctx, 4792640 silesia, uncompressed literals, compress cctx, 4838417 -silesia, uncompressed literals optimal, compress cctx, 4266751 +silesia, uncompressed literals optimal, compress cctx, 4265851 silesia, huffman literals, compress cctx, 6174127 silesia, multithreaded with advanced params, compress cctx, 4838417 github, level -5, compress cctx, 204407 @@ -107,19 +107,19 @@ silesia, level 4, zstdcli, silesia, level 5, zstdcli, 4666931 silesia, level 6, zstdcli, 4602509 silesia, level 7, zstdcli, 4568265 -silesia, level 9, zstdcli, 4535309 -silesia, level 13, zstdcli, 4483601 -silesia, level 16, zstdcli, 4357591 -silesia, level 19, zstdcli, 4266865 +silesia, level 9, zstdcli, 4540123 +silesia, level 13, zstdcli, 4488478 +silesia, level 16, zstdcli, 4358150 +silesia, level 19, zstdcli, 4265929 silesia, long distance mode, zstdcli, 4830467 silesia, multithreaded, zstdcli, 4838997 silesia, multithreaded long distance mode, zstdcli, 4830467 silesia, small window log, zstdcli, 7094528 -silesia, small hash log, zstdcli, 6526639 -silesia, small chain log, zstdcli, 4911746 +silesia, small hash log, zstdcli, 6527214 +silesia, small chain log, zstdcli, 4911647 silesia, explicit params, zstdcli, 4794378 silesia, uncompressed literals, zstdcli, 5117843 -silesia, uncompressed literals optimal, zstdcli, 4317311 +silesia, uncompressed literals optimal, zstdcli, 4316761 silesia, huffman literals, zstdcli, 5320793 silesia, multithreaded with advanced params, zstdcli, 5117843 silesia.tar, level -5, zstdcli, 6860173 @@ -242,24 +242,24 @@ silesia, level 6, advanced silesia, level 7 row 1, advanced one pass, 4567954 silesia, level 7 row 2, advanced one pass, 4562774 silesia, level 7, advanced one pass, 4567954 -silesia, level 9, advanced one pass, 4535624 -silesia, level 11 row 1, advanced one pass, 4495623 -silesia, level 11 row 2, advanced one pass, 4493258 -silesia, level 12 row 1, advanced one pass, 4495623 -silesia, level 12 row 2, advanced one pass, 4493258 -silesia, level 13, advanced one pass, 4484013 -silesia, level 16, advanced one pass, 4356207 -silesia, level 19, advanced one pass, 4266751 +silesia, level 9, advanced one pass, 4540520 +silesia, level 11 row 1, advanced one pass, 4500472 +silesia, level 11 row 2, advanced one pass, 4498174 +silesia, level 12 row 1, advanced one pass, 4500472 +silesia, level 12 row 2, advanced one pass, 4498174 +silesia, level 13, advanced one pass, 4488969 +silesia, level 16, advanced one pass, 4356799 +silesia, level 19, advanced one pass, 4265851 silesia, no source size, advanced one pass, 4838417 silesia, long distance mode, advanced one pass, 4830097 silesia, multithreaded, advanced one pass, 4838949 silesia, multithreaded long distance mode, advanced one pass, 4830419 silesia, small window log, advanced one pass, 7094480 -silesia, small hash log, advanced one pass, 6524931 -silesia, small chain log, advanced one pass, 4912322 +silesia, small hash log, advanced one pass, 6525510 +silesia, small chain log, advanced one pass, 4912248 silesia, explicit params, advanced one pass, 4794219 silesia, uncompressed literals, advanced one pass, 5117482 -silesia, uncompressed literals optimal, advanced one pass, 4317186 +silesia, uncompressed literals optimal, advanced one pass, 4316644 silesia, huffman literals, advanced one pass, 5321686 silesia, multithreaded with advanced params, advanced one pass, 5117795 silesia.tar, level -5, advanced one pass, 6860782 @@ -560,24 +560,24 @@ silesia, level 6, advanced silesia, level 7 row 1, advanced one pass small out, 4567954 silesia, level 7 row 2, advanced one pass small out, 4562774 silesia, level 7, advanced one pass small out, 4567954 -silesia, level 9, advanced one pass small out, 4535624 -silesia, level 11 row 1, advanced one pass small out, 4495623 -silesia, level 11 row 2, advanced one pass small out, 4493258 -silesia, level 12 row 1, advanced one pass small out, 4495623 -silesia, level 12 row 2, advanced one pass small out, 4493258 -silesia, level 13, advanced one pass small out, 4484013 -silesia, level 16, advanced one pass small out, 4356207 -silesia, level 19, advanced one pass small out, 4266751 +silesia, level 9, advanced one pass small out, 4540520 +silesia, level 11 row 1, advanced one pass small out, 4500472 +silesia, level 11 row 2, advanced one pass small out, 4498174 +silesia, level 12 row 1, advanced one pass small out, 4500472 +silesia, level 12 row 2, advanced one pass small out, 4498174 +silesia, level 13, advanced one pass small out, 4488969 +silesia, level 16, advanced one pass small out, 4356799 +silesia, level 19, advanced one pass small out, 4265851 silesia, no source size, advanced one pass small out, 4838417 silesia, long distance mode, advanced one pass small out, 4830097 silesia, multithreaded, advanced one pass small out, 4838949 silesia, multithreaded long distance mode, advanced one pass small out, 4830419 silesia, small window log, advanced one pass small out, 7094480 -silesia, small hash log, advanced one pass small out, 6524931 -silesia, small chain log, advanced one pass small out, 4912322 +silesia, small hash log, advanced one pass small out, 6525510 +silesia, small chain log, advanced one pass small out, 4912248 silesia, explicit params, advanced one pass small out, 4794219 silesia, uncompressed literals, advanced one pass small out, 5117482 -silesia, uncompressed literals optimal, advanced one pass small out, 4317186 +silesia, uncompressed literals optimal, advanced one pass small out, 4316644 silesia, huffman literals, advanced one pass small out, 5321686 silesia, multithreaded with advanced params, advanced one pass small out, 5117795 silesia.tar, level -5, advanced one pass small out, 6860782 From 566763fdc9b54220e8e419446331dc15fb1c183b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 11:57:23 -0700 Subject: [PATCH 432/937] new variant, sampling by 11 --- lib/compress/zstd_compress.c | 4 +++- lib/compress/zstd_preSplit.c | 8 ++++++-- lib/compress/zstd_preSplit.h | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 437bd1fbe..f917ca12c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4507,8 +4507,10 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for higher levels */ if (strat >= ZSTD_btopt) - return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl3, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_lazy2) + return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); + if (strat >= ZSTD_greedy) return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy * heuristic value, tested as being "generally better". diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index c658f6fe5..504664d67 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -68,6 +68,7 @@ FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, s ZSTD_GEN_ADDEVENTS_SAMPLE(1) ZSTD_GEN_ADDEVENTS_SAMPLE(5) +ZSTD_GEN_ADDEVENTS_SAMPLE(11) typedef void (*addEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); @@ -173,9 +174,12 @@ size_t ZSTD_splitBlock(const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_SplitBlock_strategy_e splitStrat, void* workspace, size_t wkspSize) { - if (splitStrat == split_lvl2) + if (splitStrat == split_lvl3) return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(1), workspace, wkspSize); + if (splitStrat == split_lvl2) + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(5), workspace, wkspSize); + assert(splitStrat == split_lvl1); - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(5), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(11), workspace, wkspSize); } diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index 2c87d34a6..19ad337b0 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -17,7 +17,7 @@ extern "C" { #endif -typedef enum { split_lvl1, split_lvl2 } ZSTD_SplitBlock_strategy_e; +typedef enum { split_lvl1, split_lvl2, split_lvl3 } ZSTD_SplitBlock_strategy_e; #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 From 94d7b0742500ecb02546c562c68f6e095068ce35 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 16:43:44 -0700 Subject: [PATCH 433/937] organize specialization at recordFingerprint level --- lib/compress/zstd_preSplit.c | 50 +++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 504664d67..e8d6c5ff2 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -46,7 +46,8 @@ static void initStats(FPStats* fpstats) ZSTD_memset(fpstats, 0, sizeof(FPStats)); } -FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) +FORCE_INLINE_TEMPLATE void +addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) { const char* p = (const char*)src; size_t limit = srcSize - HASHLENGTH + 1; @@ -58,27 +59,28 @@ FORCE_INLINE_TEMPLATE void addEvents_generic(Fingerprint* fp, const void* src, s fp->nbEvents += limit/samplingRate; } -#define ADDEVENTS_RATE(_rate) ZSTD_addEvents_##_rate - -#define ZSTD_GEN_ADDEVENTS_SAMPLE(_rate) \ - static void ADDEVENTS_RATE(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ - { \ - addEvents_generic(fp, src, srcSize, _rate); \ - } - -ZSTD_GEN_ADDEVENTS_SAMPLE(1) -ZSTD_GEN_ADDEVENTS_SAMPLE(5) -ZSTD_GEN_ADDEVENTS_SAMPLE(11) - - -typedef void (*addEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); - -static void recordFingerprint(Fingerprint* fp, const void* src, size_t s, addEvents_f addEvents) +FORCE_INLINE_TEMPLATE void +recordFingerprint_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) { ZSTD_memset(fp, 0, sizeof(*fp)); - addEvents(fp, src, s); + addEvents_generic(fp, src, srcSize, samplingRate); } +typedef void (*RecordEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); + +#define FP_RECORD_RATE(_rate) ZSTD_recordFingerprint_##_rate + +#define ZSTD_GEN_RECORD_FINGERPRINT_RATE(_rate) \ + static void FP_RECORD_RATE(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ + { \ + recordFingerprint_generic(fp, src, srcSize, _rate); \ + } + +ZSTD_GEN_RECORD_FINGERPRINT_RATE(1) +ZSTD_GEN_RECORD_FINGERPRINT_RATE(5) +ZSTD_GEN_RECORD_FINGERPRINT_RATE(11) + + static U64 abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) @@ -140,7 +142,7 @@ static void removeEvents(Fingerprint* acc, const Fingerprint* slice) #define CHUNKSIZE (8 << 10) /* Note: technically, we use CHUNKSIZE, so that's 8 KB */ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, - size_t blockSizeMax, addEvents_f f, + size_t blockSizeMax, RecordEvents_f record_f, void* workspace, size_t wkspSize) { FPStats* const fpstats = (FPStats*)workspace; @@ -155,9 +157,9 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; initStats(fpstats); - recordFingerprint(&fpstats->pastEvents, p, CHUNKSIZE, f); + record_f(&fpstats->pastEvents, p, CHUNKSIZE); for (pos = CHUNKSIZE; pos <= blockSizeMax - CHUNKSIZE; pos += CHUNKSIZE) { - recordFingerprint(&fpstats->newEvents, p + pos, CHUNKSIZE, f); + record_f(&fpstats->newEvents, p + pos, CHUNKSIZE); if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { return pos; } else { @@ -175,11 +177,11 @@ size_t ZSTD_splitBlock(const void* src, size_t srcSize, void* workspace, size_t wkspSize) { if (splitStrat == split_lvl3) - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(1), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(1), workspace, wkspSize); if (splitStrat == split_lvl2) - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(5), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(5), workspace, wkspSize); assert(splitStrat == split_lvl1); - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, ADDEVENTS_RATE(11), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(11), workspace, wkspSize); } From ca6e55cbf5bf3739520dd6ee07ae2785629f1b1e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 19:59:03 -0700 Subject: [PATCH 434/937] reduce splitBlock arguments --- lib/compress/zstd_compress.c | 6 +++--- lib/compress/zstd_preSplit.c | 25 ++++++++++++------------- lib/compress/zstd_preSplit.h | 4 ++-- 3 files changed, 17 insertions(+), 18 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index f917ca12c..e78de2ba8 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4507,11 +4507,11 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for higher levels */ if (strat >= ZSTD_btopt) - return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl3, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, split_lvl3, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_lazy2) - return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_greedy) - return ZSTD_splitBlock(src, srcSize, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy * heuristic value, tested as being "generally better". * no cpu cost, but can over-split homegeneous data. diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index e8d6c5ff2..c4c693955 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -141,16 +141,15 @@ static void removeEvents(Fingerprint* acc, const Fingerprint* slice) #define CHUNKSIZE (8 << 10) /* Note: technically, we use CHUNKSIZE, so that's 8 KB */ -static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, - size_t blockSizeMax, RecordEvents_f record_f, +static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, + RecordEvents_f record_f, void* workspace, size_t wkspSize) { FPStats* const fpstats = (FPStats*)workspace; - const char* p = (const char*)src; + const char* p = (const char*)blockStart; int penalty = THRESHOLD_PENALTY; size_t pos = 0; - if (srcSize <= blockSizeMax) return srcSize; - assert(blockSizeMax == (128 << 10)); + assert(blockSize == (128 << 10)); assert(workspace != NULL); assert((size_t)workspace % ZSTD_ALIGNOF(FPStats) == 0); ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE >= sizeof(FPStats)); @@ -158,7 +157,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, initStats(fpstats); record_f(&fpstats->pastEvents, p, CHUNKSIZE); - for (pos = CHUNKSIZE; pos <= blockSizeMax - CHUNKSIZE; pos += CHUNKSIZE) { + for (pos = CHUNKSIZE; pos <= blockSize - CHUNKSIZE; pos += CHUNKSIZE) { record_f(&fpstats->newEvents, p + pos, CHUNKSIZE); if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { return pos; @@ -167,21 +166,21 @@ static size_t ZSTD_splitBlock_byChunks(const void* src, size_t srcSize, if (penalty > 0) penalty--; } } - assert(pos == blockSizeMax); - return blockSizeMax; + assert(pos == blockSize); + return blockSize; (void)flushEvents; (void)removeEvents; } -size_t ZSTD_splitBlock(const void* src, size_t srcSize, - size_t blockSizeMax, ZSTD_SplitBlock_strategy_e splitStrat, +size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, + ZSTD_SplitBlock_strategy_e splitStrat, void* workspace, size_t wkspSize) { if (splitStrat == split_lvl3) - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(1), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(1), workspace, wkspSize); if (splitStrat == split_lvl2) - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(5), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(5), workspace, wkspSize); assert(splitStrat == split_lvl1); - return ZSTD_splitBlock_byChunks(src, srcSize, blockSizeMax, FP_RECORD_RATE(11), workspace, wkspSize); + return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(11), workspace, wkspSize); } diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index 19ad337b0..cf829ecee 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -29,8 +29,8 @@ typedef enum { split_lvl1, split_lvl2, split_lvl3 } ZSTD_SplitBlock_strategy_e; * therefore @blockSizeMax must be == 128 KB. * This could be extended to smaller sizes in the future. */ -size_t ZSTD_splitBlock(const void* src, size_t srcSize, - size_t blockSizeMax, ZSTD_SplitBlock_strategy_e splitStrat, +size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, + ZSTD_SplitBlock_strategy_e splitStrat, void* workspace, size_t wkspSize); #if defined (__cplusplus) From 326c45bb8ed8f9f9e7dce1721db5d5e1ec1cb818 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Oct 2024 20:20:32 -0700 Subject: [PATCH 435/937] complete sample11 with reduced fingerprint size --- lib/compress/zstd_preSplit.c | 64 +++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index c4c693955..63ff0ded8 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -21,14 +21,15 @@ #define THRESHOLD_PENALTY 3 #define HASHLENGTH 2 -#define HASHLOG 10 -#define HASHTABLESIZE (1 << HASHLOG) +#define HASHLOG_MAX 10 +#define HASHTABLESIZE (1 << HASHLOG_MAX) #define HASHMASK (HASHTABLESIZE - 1) #define KNUTH 0x9e3779b9 -static unsigned hash2(const void *p) +FORCE_INLINE_TEMPLATE unsigned hash2(const void *p, unsigned hashLog) { - return (U32)(MEM_read16(p)) * KNUTH >> (32 - HASHLOG); + assert(hashLog <= HASHLOG_MAX); + return (U32)(MEM_read16(p)) * KNUTH >> (32 - hashLog); } @@ -47,47 +48,49 @@ static void initStats(FPStats* fpstats) } FORCE_INLINE_TEMPLATE void -addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) +addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate, unsigned hashLog) { const char* p = (const char*)src; size_t limit = srcSize - HASHLENGTH + 1; size_t n; assert(srcSize >= HASHLENGTH); for (n = 0; n < limit; n+=samplingRate) { - fp->events[hash2(p+n)]++; + fp->events[hash2(p+n, hashLog)]++; } fp->nbEvents += limit/samplingRate; } FORCE_INLINE_TEMPLATE void -recordFingerprint_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate) +recordFingerprint_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate, unsigned hashLog) { - ZSTD_memset(fp, 0, sizeof(*fp)); - addEvents_generic(fp, src, srcSize, samplingRate); + ZSTD_memset(fp, 0, sizeof(unsigned) * (1 << hashLog)); + fp->nbEvents = 0; + addEvents_generic(fp, src, srcSize, samplingRate, hashLog); } typedef void (*RecordEvents_f)(Fingerprint* fp, const void* src, size_t srcSize); -#define FP_RECORD_RATE(_rate) ZSTD_recordFingerprint_##_rate +#define FP_RECORD(_rate) ZSTD_recordFingerprint_##_rate -#define ZSTD_GEN_RECORD_FINGERPRINT_RATE(_rate) \ - static void FP_RECORD_RATE(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ +#define ZSTD_GEN_RECORD_FINGERPRINT(_rate, _hSize) \ + static void FP_RECORD(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ { \ - recordFingerprint_generic(fp, src, srcSize, _rate); \ + recordFingerprint_generic(fp, src, srcSize, _rate, _hSize); \ } -ZSTD_GEN_RECORD_FINGERPRINT_RATE(1) -ZSTD_GEN_RECORD_FINGERPRINT_RATE(5) -ZSTD_GEN_RECORD_FINGERPRINT_RATE(11) +ZSTD_GEN_RECORD_FINGERPRINT(1, 10) +ZSTD_GEN_RECORD_FINGERPRINT(5, 10) +ZSTD_GEN_RECORD_FINGERPRINT(11, 9) static U64 abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } -static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) +static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2, unsigned hashLog) { U64 distance = 0; size_t n; - for (n = 0; n < HASHTABLESIZE; n++) { + 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); } @@ -99,12 +102,13 @@ static U64 fpDistance(const Fingerprint* fp1, const Fingerprint* fp2) */ static int compareFingerprints(const Fingerprint* ref, const Fingerprint* newfp, - int penalty) + int penalty, + unsigned hashLog) { assert(ref->nbEvents > 0); assert(newfp->nbEvents > 0); { U64 p50 = (U64)ref->nbEvents * (U64)newfp->nbEvents; - U64 deviation = fpDistance(ref, newfp); + U64 deviation = fpDistance(ref, newfp, hashLog); U64 threshold = p50 * (U64)(THRESHOLD_BASE + penalty) / THRESHOLD_PENALTY_RATE; return deviation >= threshold; } @@ -140,11 +144,15 @@ static void removeEvents(Fingerprint* acc, const Fingerprint* slice) } #define CHUNKSIZE (8 << 10) -/* Note: technically, we use CHUNKSIZE, so that's 8 KB */ static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, - RecordEvents_f record_f, + ZSTD_SplitBlock_strategy_e splitStrat, void* workspace, size_t wkspSize) { + static const RecordEvents_f records_fs[] = { + FP_RECORD(11), FP_RECORD(5), FP_RECORD(1) + }; + static const unsigned hashParams[] = { 9, 10, 10 }; + const RecordEvents_f record_f = (assert(splitStrat<=split_lvl3), records_fs[splitStrat]); FPStats* const fpstats = (FPStats*)workspace; const char* p = (const char*)blockStart; int penalty = THRESHOLD_PENALTY; @@ -159,7 +167,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, record_f(&fpstats->pastEvents, p, CHUNKSIZE); for (pos = CHUNKSIZE; pos <= blockSize - CHUNKSIZE; pos += CHUNKSIZE) { record_f(&fpstats->newEvents, p + pos, CHUNKSIZE); - if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty)) { + if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty, hashParams[splitStrat])) { return pos; } else { mergeEvents(&fpstats->pastEvents, &fpstats->newEvents); @@ -175,12 +183,6 @@ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, ZSTD_SplitBlock_strategy_e splitStrat, void* workspace, size_t wkspSize) { - if (splitStrat == split_lvl3) - return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(1), workspace, wkspSize); - - if (splitStrat == split_lvl2) - return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(5), workspace, wkspSize); - - assert(splitStrat == split_lvl1); - return ZSTD_splitBlock_byChunks(blockStart, blockSize, FP_RECORD_RATE(11), workspace, wkspSize); + assert(splitStrat <= split_lvl3); + return ZSTD_splitBlock_byChunks(blockStart, blockSize, splitStrat, workspace, wkspSize); } From ea082692aaff79abebecd97e77b3bf79ab58f43f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 13:27:01 -0700 Subject: [PATCH 436/937] added block splitter variant for greedy & lazy (levels 5 to 7) --- tests/regression/results.csv | 492 +++++++++++++++++------------------ 1 file changed, 246 insertions(+), 246 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index ea5ed58d5..b46c4ca5c 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -6,9 +6,9 @@ silesia.tar, level 0, compress silesia.tar, level 1, compress simple, 5316794 silesia.tar, level 3, compress simple, 4843429 silesia.tar, level 4, compress simple, 4780657 -silesia.tar, level 5, compress simple, 4669650 -silesia.tar, level 6, compress simple, 4604925 -silesia.tar, level 7, compress simple, 4570873 +silesia.tar, level 5, compress simple, 4662847 +silesia.tar, level 6, compress simple, 4597877 +silesia.tar, level 7, compress simple, 4563998 silesia.tar, level 9, compress simple, 4537558 silesia.tar, level 13, compress simple, 4484732 silesia.tar, level 16, compress simple, 4355572 @@ -23,9 +23,9 @@ github.tar, level 0, compress github.tar, level 1, compress simple, 39444 github.tar, level 3, compress simple, 39073 github.tar, level 4, compress simple, 39068 -github.tar, level 5, compress simple, 39808 -github.tar, level 6, compress simple, 39455 -github.tar, level 7, compress simple, 38168 +github.tar, level 5, compress simple, 39651 +github.tar, level 6, compress simple, 39282 +github.tar, level 7, compress simple, 38005 github.tar, level 9, compress simple, 36723 github.tar, level 13, compress simple, 35501 github.tar, level 16, compress simple, 40466 @@ -40,9 +40,9 @@ silesia, level 0, compress silesia, level 1, compress cctx, 5306931 silesia, level 3, compress cctx, 4838417 silesia, level 4, compress cctx, 4775359 -silesia, level 5, compress cctx, 4666524 -silesia, level 6, compress cctx, 4602031 -silesia, level 7, compress cctx, 4567954 +silesia, level 5, compress cctx, 4663718 +silesia, level 6, compress cctx, 4600034 +silesia, level 7, compress cctx, 4566069 silesia, level 9, compress cctx, 4540520 silesia, level 13, compress cctx, 4488969 silesia, level 16, compress cctx, 4356799 @@ -53,7 +53,7 @@ silesia, multithreaded long distance mode, compress silesia, small window log, compress cctx, 7082907 silesia, small hash log, compress cctx, 6525510 silesia, small chain log, compress cctx, 4912248 -silesia, explicit params, compress cctx, 4792640 +silesia, explicit params, compress cctx, 4789676 silesia, uncompressed literals, compress cctx, 4838417 silesia, uncompressed literals optimal, compress cctx, 4265851 silesia, huffman literals, compress cctx, 6174127 @@ -104,11 +104,11 @@ silesia, level 0, zstdcli, silesia, level 1, zstdcli, 5306179 silesia, level 3, zstdcli, 4838997 silesia, level 4, zstdcli, 4775769 -silesia, level 5, zstdcli, 4666931 -silesia, level 6, zstdcli, 4602509 -silesia, level 7, zstdcli, 4568265 -silesia, level 9, zstdcli, 4540123 -silesia, level 13, zstdcli, 4488478 +silesia, level 5, zstdcli, 4663332 +silesia, level 6, zstdcli, 4599601 +silesia, level 7, zstdcli, 4565601 +silesia, level 9, zstdcli, 4540082 +silesia, level 13, zstdcli, 4488438 silesia, level 16, zstdcli, 4358150 silesia, level 19, zstdcli, 4265929 silesia, long distance mode, zstdcli, 4830467 @@ -117,7 +117,7 @@ silesia, multithreaded long distance mode, zstdcli, silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6527214 silesia, small chain log, zstdcli, 4911647 -silesia, explicit params, zstdcli, 4794378 +silesia, explicit params, zstdcli, 4790803 silesia, uncompressed literals, zstdcli, 5117843 silesia, uncompressed literals optimal, zstdcli, 4316761 silesia, huffman literals, zstdcli, 5320793 @@ -129,23 +129,23 @@ silesia.tar, level 0, zstdcli, silesia.tar, level 1, zstdcli, 5313917 silesia.tar, level 3, zstdcli, 4841906 silesia.tar, level 4, zstdcli, 4780121 -silesia.tar, level 5, zstdcli, 4671144 -silesia.tar, level 6, zstdcli, 4606407 -silesia.tar, level 7, zstdcli, 4572666 -silesia.tar, level 9, zstdcli, 4542599 -silesia.tar, level 13, zstdcli, 4489976 -silesia.tar, level 16, zstdcli, 4356959 -silesia.tar, level 19, zstdcli, 4259787 +silesia.tar, level 5, zstdcli, 4667310 +silesia.tar, level 6, zstdcli, 4602398 +silesia.tar, level 7, zstdcli, 4568891 +silesia.tar, level 9, zstdcli, 4541098 +silesia.tar, level 13, zstdcli, 4488484 +silesia.tar, level 16, zstdcli, 4357018 +silesia.tar, level 19, zstdcli, 4259593 silesia.tar, no source size, zstdcli, 4841902 silesia.tar, long distance mode, zstdcli, 4834266 silesia.tar, multithreaded, zstdcli, 4841906 silesia.tar, multithreaded long distance mode, zstdcli, 4834266 silesia.tar, small window log, zstdcli, 7100110 -silesia.tar, small hash log, zstdcli, 6530007 -silesia.tar, small chain log, zstdcli, 4916091 -silesia.tar, explicit params, zstdcli, 4809323 +silesia.tar, small hash log, zstdcli, 6530127 +silesia.tar, small chain log, zstdcli, 4915865 +silesia.tar, explicit params, zstdcli, 4808370 silesia.tar, uncompressed literals, zstdcli, 5116446 -silesia.tar, uncompressed literals optimal, zstdcli, 4306844 +silesia.tar, uncompressed literals optimal, zstdcli, 4306520 silesia.tar, huffman literals, zstdcli, 5326463 silesia.tar, multithreaded with advanced params, zstdcli, 5116446 github, level -5, zstdcli, 206407 @@ -201,11 +201,11 @@ github.tar, level 3, zstdcli, github.tar, level 3 with dict, zstdcli, 38140 github.tar, level 4, zstdcli, 39067 github.tar, level 4 with dict, zstdcli, 38082 -github.tar, level 5, zstdcli, 39815 -github.tar, level 5 with dict, zstdcli, 39221 -github.tar, level 6, zstdcli, 39455 -github.tar, level 6 with dict, zstdcli, 38787 -github.tar, level 7, zstdcli, 38177 +github.tar, level 5, zstdcli, 39655 +github.tar, level 5 with dict, zstdcli, 39073 +github.tar, level 6, zstdcli, 39286 +github.tar, level 6 with dict, zstdcli, 38647 +github.tar, level 7, zstdcli, 38009 github.tar, level 7 with dict, zstdcli, 37861 github.tar, level 9, zstdcli, 36727 github.tar, level 9 with dict, zstdcli, 36686 @@ -223,7 +223,7 @@ github.tar, multithreaded long distance mode, zstdcli, github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 -github.tar, explicit params, zstdcli, 41588 +github.tar, explicit params, zstdcli, 41385 github.tar, uncompressed literals, zstdcli, 41704 github.tar, uncompressed literals optimal, zstdcli, 35360 github.tar, huffman literals, zstdcli, 39046 @@ -235,13 +235,13 @@ silesia, level 0, advanced silesia, level 1, advanced one pass, 5306931 silesia, level 3, advanced one pass, 4838417 silesia, level 4, advanced one pass, 4775359 -silesia, level 5 row 1, advanced one pass, 4666524 -silesia, level 5 row 2, advanced one pass, 4668976 -silesia, level 5, advanced one pass, 4666524 -silesia, level 6, advanced one pass, 4602031 -silesia, level 7 row 1, advanced one pass, 4567954 -silesia, level 7 row 2, advanced one pass, 4562774 -silesia, level 7, advanced one pass, 4567954 +silesia, level 5 row 1, advanced one pass, 4663718 +silesia, level 5 row 2, advanced one pass, 4666272 +silesia, level 5, advanced one pass, 4663718 +silesia, level 6, advanced one pass, 4600034 +silesia, level 7 row 1, advanced one pass, 4566069 +silesia, level 7 row 2, advanced one pass, 4560893 +silesia, level 7, advanced one pass, 4566069 silesia, level 9, advanced one pass, 4540520 silesia, level 11 row 1, advanced one pass, 4500472 silesia, level 11 row 2, advanced one pass, 4498174 @@ -257,7 +257,7 @@ silesia, multithreaded long distance mode, advanced silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6525510 silesia, small chain log, advanced one pass, 4912248 -silesia, explicit params, advanced one pass, 4794219 +silesia, explicit params, advanced one pass, 4791219 silesia, uncompressed literals, advanced one pass, 5117482 silesia, uncompressed literals optimal, advanced one pass, 4316644 silesia, huffman literals, advanced one pass, 5321686 @@ -269,13 +269,13 @@ silesia.tar, level 0, advanced silesia.tar, level 1, advanced one pass, 5316794 silesia.tar, level 3, advanced one pass, 4843429 silesia.tar, level 4, advanced one pass, 4780657 -silesia.tar, level 5 row 1, advanced one pass, 4669650 -silesia.tar, level 5 row 2, advanced one pass, 4673119 -silesia.tar, level 5, advanced one pass, 4669650 -silesia.tar, level 6, advanced one pass, 4604925 -silesia.tar, level 7 row 1, advanced one pass, 4570873 -silesia.tar, level 7 row 2, advanced one pass, 4566314 -silesia.tar, level 7, advanced one pass, 4570873 +silesia.tar, level 5 row 1, advanced one pass, 4662847 +silesia.tar, level 5 row 2, advanced one pass, 4666825 +silesia.tar, level 5, advanced one pass, 4662847 +silesia.tar, level 6, advanced one pass, 4597877 +silesia.tar, level 7 row 1, advanced one pass, 4563998 +silesia.tar, level 7 row 2, advanced one pass, 4559520 +silesia.tar, level 7, advanced one pass, 4563998 silesia.tar, level 9, advanced one pass, 4537558 silesia.tar, level 11 row 1, advanced one pass, 4496590 silesia.tar, level 11 row 2, advanced one pass, 4495225 @@ -291,7 +291,7 @@ silesia.tar, multithreaded long distance mode, advanced silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6530222 silesia.tar, small chain log, advanced one pass, 4915689 -silesia.tar, explicit params, advanced one pass, 4797958 +silesia.tar, explicit params, advanced one pass, 4790421 silesia.tar, uncompressed literals, advanced one pass, 5116329 silesia.tar, uncompressed literals optimal, advanced one pass, 4306289 silesia.tar, huffman literals, advanced one pass, 5331382 @@ -451,44 +451,44 @@ github.tar, level 4 with dict dms, advanced github.tar, level 4 with dict dds, advanced one pass, 38135 github.tar, level 4 with dict copy, advanced one pass, 38081 github.tar, level 4 with dict load, advanced one pass, 38088 -github.tar, level 5 row 1, advanced one pass, 39808 -github.tar, level 5 row 1 with dict dms, advanced one pass, 39185 -github.tar, level 5 row 1 with dict dds, advanced one pass, 39213 -github.tar, level 5 row 1 with dict copy, advanced one pass, 39284 -github.tar, level 5 row 1 with dict load, advanced one pass, 39155 -github.tar, level 5 row 2, advanced one pass, 39851 -github.tar, level 5 row 2 with dict dms, advanced one pass, 39498 -github.tar, level 5 row 2 with dict dds, advanced one pass, 39364 -github.tar, level 5 row 2 with dict copy, advanced one pass, 39843 -github.tar, level 5 row 2 with dict load, advanced one pass, 39312 -github.tar, level 5, advanced one pass, 39808 -github.tar, level 5 with dict, advanced one pass, 39284 -github.tar, level 5 with dict dms, advanced one pass, 39185 -github.tar, level 5 with dict dds, advanced one pass, 39213 -github.tar, level 5 with dict copy, advanced one pass, 39284 -github.tar, level 5 with dict load, advanced one pass, 39155 -github.tar, level 6, advanced one pass, 39455 -github.tar, level 6 with dict, advanced one pass, 38808 -github.tar, level 6 with dict dms, advanced one pass, 38792 -github.tar, level 6 with dict dds, advanced one pass, 38790 -github.tar, level 6 with dict copy, advanced one pass, 38808 -github.tar, level 6 with dict load, advanced one pass, 38796 -github.tar, level 7 row 1, advanced one pass, 38168 +github.tar, level 5 row 1, advanced one pass, 39651 +github.tar, level 5 row 1 with dict dms, advanced one pass, 39043 +github.tar, level 5 row 1 with dict dds, advanced one pass, 39069 +github.tar, level 5 row 1 with dict copy, advanced one pass, 39145 +github.tar, level 5 row 1 with dict load, advanced one pass, 39000 +github.tar, level 5 row 2, advanced one pass, 39701 +github.tar, level 5 row 2 with dict dms, advanced one pass, 39365 +github.tar, level 5 row 2 with dict dds, advanced one pass, 39233 +github.tar, level 5 row 2 with dict copy, advanced one pass, 39715 +github.tar, level 5 row 2 with dict load, advanced one pass, 39158 +github.tar, level 5, advanced one pass, 39651 +github.tar, level 5 with dict, advanced one pass, 39145 +github.tar, level 5 with dict dms, advanced one pass, 39043 +github.tar, level 5 with dict dds, advanced one pass, 39069 +github.tar, level 5 with dict copy, advanced one pass, 39145 +github.tar, level 5 with dict load, advanced one pass, 39000 +github.tar, level 6, advanced one pass, 39282 +github.tar, level 6 with dict, advanced one pass, 38656 +github.tar, level 6 with dict dms, advanced one pass, 38640 +github.tar, level 6 with dict dds, advanced one pass, 38643 +github.tar, level 6 with dict copy, advanced one pass, 38656 +github.tar, level 6 with dict load, advanced one pass, 38647 +github.tar, level 7 row 1, advanced one pass, 38005 github.tar, level 7 row 1 with dict dms, advanced one pass, 37832 github.tar, level 7 row 1 with dict dds, advanced one pass, 37857 github.tar, level 7 row 1 with dict copy, advanced one pass, 37839 -github.tar, level 7 row 1 with dict load, advanced one pass, 37445 -github.tar, level 7 row 2, advanced one pass, 38235 +github.tar, level 7 row 1 with dict load, advanced one pass, 37286 +github.tar, level 7 row 2, advanced one pass, 38077 github.tar, level 7 row 2 with dict dms, advanced one pass, 38012 github.tar, level 7 row 2 with dict dds, advanced one pass, 38014 github.tar, level 7 row 2 with dict copy, advanced one pass, 38101 -github.tar, level 7 row 2 with dict load, advanced one pass, 37552 -github.tar, level 7, advanced one pass, 38168 +github.tar, level 7 row 2 with dict load, advanced one pass, 37402 +github.tar, level 7, advanced one pass, 38005 github.tar, level 7 with dict, advanced one pass, 37839 github.tar, level 7 with dict dms, advanced one pass, 37832 github.tar, level 7 with dict dds, advanced one pass, 37857 github.tar, level 7 with dict copy, advanced one pass, 37839 -github.tar, level 7 with dict load, advanced one pass, 37445 +github.tar, level 7 with dict load, advanced one pass, 37286 github.tar, level 9, advanced one pass, 36723 github.tar, level 9 with dict, advanced one pass, 36531 github.tar, level 9 with dict dms, advanced one pass, 36615 @@ -541,7 +541,7 @@ github.tar, multithreaded long distance mode, advanced github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 -github.tar, explicit params, advanced one pass, 41605 +github.tar, explicit params, advanced one pass, 41385 github.tar, uncompressed literals, advanced one pass, 41709 github.tar, uncompressed literals optimal, advanced one pass, 35356 github.tar, huffman literals, advanced one pass, 39099 @@ -553,13 +553,13 @@ silesia, level 0, advanced silesia, level 1, advanced one pass small out, 5306931 silesia, level 3, advanced one pass small out, 4838417 silesia, level 4, advanced one pass small out, 4775359 -silesia, level 5 row 1, advanced one pass small out, 4666524 -silesia, level 5 row 2, advanced one pass small out, 4668976 -silesia, level 5, advanced one pass small out, 4666524 -silesia, level 6, advanced one pass small out, 4602031 -silesia, level 7 row 1, advanced one pass small out, 4567954 -silesia, level 7 row 2, advanced one pass small out, 4562774 -silesia, level 7, advanced one pass small out, 4567954 +silesia, level 5 row 1, advanced one pass small out, 4663718 +silesia, level 5 row 2, advanced one pass small out, 4666272 +silesia, level 5, advanced one pass small out, 4663718 +silesia, level 6, advanced one pass small out, 4600034 +silesia, level 7 row 1, advanced one pass small out, 4566069 +silesia, level 7 row 2, advanced one pass small out, 4560893 +silesia, level 7, advanced one pass small out, 4566069 silesia, level 9, advanced one pass small out, 4540520 silesia, level 11 row 1, advanced one pass small out, 4500472 silesia, level 11 row 2, advanced one pass small out, 4498174 @@ -575,7 +575,7 @@ silesia, multithreaded long distance mode, advanced silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6525510 silesia, small chain log, advanced one pass small out, 4912248 -silesia, explicit params, advanced one pass small out, 4794219 +silesia, explicit params, advanced one pass small out, 4791219 silesia, uncompressed literals, advanced one pass small out, 5117482 silesia, uncompressed literals optimal, advanced one pass small out, 4316644 silesia, huffman literals, advanced one pass small out, 5321686 @@ -587,13 +587,13 @@ silesia.tar, level 0, advanced silesia.tar, level 1, advanced one pass small out, 5316794 silesia.tar, level 3, advanced one pass small out, 4843429 silesia.tar, level 4, advanced one pass small out, 4780657 -silesia.tar, level 5 row 1, advanced one pass small out, 4669650 -silesia.tar, level 5 row 2, advanced one pass small out, 4673119 -silesia.tar, level 5, advanced one pass small out, 4669650 -silesia.tar, level 6, advanced one pass small out, 4604925 -silesia.tar, level 7 row 1, advanced one pass small out, 4570873 -silesia.tar, level 7 row 2, advanced one pass small out, 4566314 -silesia.tar, level 7, advanced one pass small out, 4570873 +silesia.tar, level 5 row 1, advanced one pass small out, 4662847 +silesia.tar, level 5 row 2, advanced one pass small out, 4666825 +silesia.tar, level 5, advanced one pass small out, 4662847 +silesia.tar, level 6, advanced one pass small out, 4597877 +silesia.tar, level 7 row 1, advanced one pass small out, 4563998 +silesia.tar, level 7 row 2, advanced one pass small out, 4559520 +silesia.tar, level 7, advanced one pass small out, 4563998 silesia.tar, level 9, advanced one pass small out, 4537558 silesia.tar, level 11 row 1, advanced one pass small out, 4496590 silesia.tar, level 11 row 2, advanced one pass small out, 4495225 @@ -609,7 +609,7 @@ silesia.tar, multithreaded long distance mode, advanced silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6530222 silesia.tar, small chain log, advanced one pass small out, 4915689 -silesia.tar, explicit params, advanced one pass small out, 4797958 +silesia.tar, explicit params, advanced one pass small out, 4790421 silesia.tar, uncompressed literals, advanced one pass small out, 5116329 silesia.tar, uncompressed literals optimal, advanced one pass small out, 4306289 silesia.tar, huffman literals, advanced one pass small out, 5331382 @@ -769,44 +769,44 @@ github.tar, level 4 with dict dms, advanced github.tar, level 4 with dict dds, advanced one pass small out, 38135 github.tar, level 4 with dict copy, advanced one pass small out, 38081 github.tar, level 4 with dict load, advanced one pass small out, 38088 -github.tar, level 5 row 1, advanced one pass small out, 39808 -github.tar, level 5 row 1 with dict dms, advanced one pass small out, 39185 -github.tar, level 5 row 1 with dict dds, advanced one pass small out, 39213 -github.tar, level 5 row 1 with dict copy, advanced one pass small out, 39284 -github.tar, level 5 row 1 with dict load, advanced one pass small out, 39155 -github.tar, level 5 row 2, advanced one pass small out, 39851 -github.tar, level 5 row 2 with dict dms, advanced one pass small out, 39498 -github.tar, level 5 row 2 with dict dds, advanced one pass small out, 39364 -github.tar, level 5 row 2 with dict copy, advanced one pass small out, 39843 -github.tar, level 5 row 2 with dict load, advanced one pass small out, 39312 -github.tar, level 5, advanced one pass small out, 39808 -github.tar, level 5 with dict, advanced one pass small out, 39284 -github.tar, level 5 with dict dms, advanced one pass small out, 39185 -github.tar, level 5 with dict dds, advanced one pass small out, 39213 -github.tar, level 5 with dict copy, advanced one pass small out, 39284 -github.tar, level 5 with dict load, advanced one pass small out, 39155 -github.tar, level 6, advanced one pass small out, 39455 -github.tar, level 6 with dict, advanced one pass small out, 38808 -github.tar, level 6 with dict dms, advanced one pass small out, 38792 -github.tar, level 6 with dict dds, advanced one pass small out, 38790 -github.tar, level 6 with dict copy, advanced one pass small out, 38808 -github.tar, level 6 with dict load, advanced one pass small out, 38796 -github.tar, level 7 row 1, advanced one pass small out, 38168 +github.tar, level 5 row 1, advanced one pass small out, 39651 +github.tar, level 5 row 1 with dict dms, advanced one pass small out, 39043 +github.tar, level 5 row 1 with dict dds, advanced one pass small out, 39069 +github.tar, level 5 row 1 with dict copy, advanced one pass small out, 39145 +github.tar, level 5 row 1 with dict load, advanced one pass small out, 39000 +github.tar, level 5 row 2, advanced one pass small out, 39701 +github.tar, level 5 row 2 with dict dms, advanced one pass small out, 39365 +github.tar, level 5 row 2 with dict dds, advanced one pass small out, 39233 +github.tar, level 5 row 2 with dict copy, advanced one pass small out, 39715 +github.tar, level 5 row 2 with dict load, advanced one pass small out, 39158 +github.tar, level 5, advanced one pass small out, 39651 +github.tar, level 5 with dict, advanced one pass small out, 39145 +github.tar, level 5 with dict dms, advanced one pass small out, 39043 +github.tar, level 5 with dict dds, advanced one pass small out, 39069 +github.tar, level 5 with dict copy, advanced one pass small out, 39145 +github.tar, level 5 with dict load, advanced one pass small out, 39000 +github.tar, level 6, advanced one pass small out, 39282 +github.tar, level 6 with dict, advanced one pass small out, 38656 +github.tar, level 6 with dict dms, advanced one pass small out, 38640 +github.tar, level 6 with dict dds, advanced one pass small out, 38643 +github.tar, level 6 with dict copy, advanced one pass small out, 38656 +github.tar, level 6 with dict load, advanced one pass small out, 38647 +github.tar, level 7 row 1, advanced one pass small out, 38005 github.tar, level 7 row 1 with dict dms, advanced one pass small out, 37832 github.tar, level 7 row 1 with dict dds, advanced one pass small out, 37857 github.tar, level 7 row 1 with dict copy, advanced one pass small out, 37839 -github.tar, level 7 row 1 with dict load, advanced one pass small out, 37445 -github.tar, level 7 row 2, advanced one pass small out, 38235 +github.tar, level 7 row 1 with dict load, advanced one pass small out, 37286 +github.tar, level 7 row 2, advanced one pass small out, 38077 github.tar, level 7 row 2 with dict dms, advanced one pass small out, 38012 github.tar, level 7 row 2 with dict dds, advanced one pass small out, 38014 github.tar, level 7 row 2 with dict copy, advanced one pass small out, 38101 -github.tar, level 7 row 2 with dict load, advanced one pass small out, 37552 -github.tar, level 7, advanced one pass small out, 38168 +github.tar, level 7 row 2 with dict load, advanced one pass small out, 37402 +github.tar, level 7, advanced one pass small out, 38005 github.tar, level 7 with dict, advanced one pass small out, 37839 github.tar, level 7 with dict dms, advanced one pass small out, 37832 github.tar, level 7 with dict dds, advanced one pass small out, 37857 github.tar, level 7 with dict copy, advanced one pass small out, 37839 -github.tar, level 7 with dict load, advanced one pass small out, 37445 +github.tar, level 7 with dict load, advanced one pass small out, 37286 github.tar, level 9, advanced one pass small out, 36723 github.tar, level 9 with dict, advanced one pass small out, 36531 github.tar, level 9 with dict dms, advanced one pass small out, 36615 @@ -859,7 +859,7 @@ github.tar, multithreaded long distance mode, advanced github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 -github.tar, explicit params, advanced one pass small out, 41605 +github.tar, explicit params, advanced one pass small out, 41385 github.tar, uncompressed literals, advanced one pass small out, 41709 github.tar, uncompressed literals optimal, advanced one pass small out, 35356 github.tar, huffman literals, advanced one pass small out, 39099 @@ -871,31 +871,31 @@ silesia, level 0, advanced silesia, level 1, advanced streaming, 5305682 silesia, level 3, advanced streaming, 4839173 silesia, level 4, advanced streaming, 4776074 -silesia, level 5 row 1, advanced streaming, 4667049 -silesia, level 5 row 2, advanced streaming, 4669474 -silesia, level 5, advanced streaming, 4667049 -silesia, level 6, advanced streaming, 4602956 -silesia, level 7 row 1, advanced streaming, 4568785 -silesia, level 7 row 2, advanced streaming, 4563722 -silesia, level 7, advanced streaming, 4568785 -silesia, level 9, advanced streaming, 4545850 -silesia, level 11 row 1, advanced streaming, 4505658 -silesia, level 11 row 2, advanced streaming, 4503429 -silesia, level 12 row 1, advanced streaming, 4505658 -silesia, level 12 row 2, advanced streaming, 4503429 -silesia, level 13, advanced streaming, 4493990 -silesia, level 16, advanced streaming, 4359652 -silesia, level 19, advanced streaming, 4266582 +silesia, level 5 row 1, advanced streaming, 4664679 +silesia, level 5 row 2, advanced streaming, 4667307 +silesia, level 5, advanced streaming, 4664679 +silesia, level 6, advanced streaming, 4601116 +silesia, level 7 row 1, advanced streaming, 4567082 +silesia, level 7 row 2, advanced streaming, 4561992 +silesia, level 7, advanced streaming, 4567082 +silesia, level 9, advanced streaming, 4542474 +silesia, level 11 row 1, advanced streaming, 4502322 +silesia, level 11 row 2, advanced streaming, 4500050 +silesia, level 12 row 1, advanced streaming, 4502322 +silesia, level 12 row 2, advanced streaming, 4500050 +silesia, level 13, advanced streaming, 4490650 +silesia, level 16, advanced streaming, 4358094 +silesia, level 19, advanced streaming, 4265908 silesia, no source size, advanced streaming, 4839137 silesia, long distance mode, advanced streaming, 4831125 silesia, multithreaded, advanced streaming, 4838949 silesia, multithreaded long distance mode, advanced streaming, 4830419 silesia, small window log, advanced streaming, 7110591 -silesia, small hash log, advanced streaming, 6526141 -silesia, small chain log, advanced streaming, 4912197 -silesia, explicit params, advanced streaming, 4795053 +silesia, small hash log, advanced streaming, 6525259 +silesia, small chain log, advanced streaming, 4911577 +silesia, explicit params, advanced streaming, 4792505 silesia, uncompressed literals, advanced streaming, 5117625 -silesia, uncompressed literals optimal, advanced streaming, 4316880 +silesia, uncompressed literals optimal, advanced streaming, 4316533 silesia, huffman literals, advanced streaming, 5321812 silesia, multithreaded with advanced params, advanced streaming, 5117795 silesia.tar, level -5, advanced streaming, 6857458 @@ -905,31 +905,31 @@ silesia.tar, level 0, advanced silesia.tar, level 1, advanced streaming, 5311452 silesia.tar, level 3, advanced streaming, 4849720 silesia.tar, level 4, advanced streaming, 4787534 -silesia.tar, level 5 row 1, advanced streaming, 4669420 -silesia.tar, level 5 row 2, advanced streaming, 4673610 -silesia.tar, level 5, advanced streaming, 4669420 -silesia.tar, level 6, advanced streaming, 4604125 -silesia.tar, level 7 row 1, advanced streaming, 4570206 -silesia.tar, level 7 row 2, advanced streaming, 4565792 -silesia.tar, level 7, advanced streaming, 4570206 -silesia.tar, level 9, advanced streaming, 4555445 -silesia.tar, level 11 row 1, advanced streaming, 4514959 -silesia.tar, level 11 row 2, advanced streaming, 4513810 -silesia.tar, level 12 row 1, advanced streaming, 4514514 -silesia.tar, level 12 row 2, advanced streaming, 4514003 -silesia.tar, level 13, advanced streaming, 4502956 -silesia.tar, level 16, advanced streaming, 4360385 -silesia.tar, level 19, advanced streaming, 4260939 +silesia.tar, level 5 row 1, advanced streaming, 4664523 +silesia.tar, level 5 row 2, advanced streaming, 4668292 +silesia.tar, level 5, advanced streaming, 4664523 +silesia.tar, level 6, advanced streaming, 4599420 +silesia.tar, level 7 row 1, advanced streaming, 4565332 +silesia.tar, level 7 row 2, advanced streaming, 4561064 +silesia.tar, level 7, advanced streaming, 4565332 +silesia.tar, level 9, advanced streaming, 4539391 +silesia.tar, level 11 row 1, advanced streaming, 4498530 +silesia.tar, level 11 row 2, advanced streaming, 4497297 +silesia.tar, level 12 row 1, advanced streaming, 4498097 +silesia.tar, level 12 row 2, advanced streaming, 4497497 +silesia.tar, level 13, advanced streaming, 4486652 +silesia.tar, level 16, advanced streaming, 4358029 +silesia.tar, level 19, advanced streaming, 4258228 silesia.tar, no source size, advanced streaming, 4849716 silesia.tar, long distance mode, advanced streaming, 4829339 silesia.tar, multithreaded, advanced streaming, 4841902 silesia.tar, multithreaded long distance mode, advanced streaming, 4834262 silesia.tar, small window log, advanced streaming, 7117024 -silesia.tar, small hash log, advanced streaming, 6529209 -silesia.tar, small chain log, advanced streaming, 4917021 -silesia.tar, explicit params, advanced streaming, 4797673 +silesia.tar, small hash log, advanced streaming, 6529503 +silesia.tar, small chain log, advanced streaming, 4915956 +silesia.tar, explicit params, advanced streaming, 4791739 silesia.tar, uncompressed literals, advanced streaming, 5124811 -silesia.tar, uncompressed literals optimal, advanced streaming, 4308451 +silesia.tar, uncompressed literals optimal, advanced streaming, 4306968 silesia.tar, huffman literals, advanced streaming, 5326278 silesia.tar, multithreaded with advanced params, advanced streaming, 5116442 github, level -5, advanced streaming, 204407 @@ -1087,44 +1087,44 @@ github.tar, level 4 with dict dms, advanced github.tar, level 4 with dict dds, advanced streaming, 38317 github.tar, level 4 with dict copy, advanced streaming, 38270 github.tar, level 4 with dict load, advanced streaming, 38259 -github.tar, level 5 row 1, advanced streaming, 39986 -github.tar, level 5 row 1 with dict dms, advanced streaming, 39370 -github.tar, level 5 row 1 with dict dds, advanced streaming, 39396 -github.tar, level 5 row 1 with dict copy, advanced streaming, 39465 -github.tar, level 5 row 1 with dict load, advanced streaming, 39332 -github.tar, level 5 row 2, advanced streaming, 40038 -github.tar, level 5 row 2 with dict dms, advanced streaming, 39690 -github.tar, level 5 row 2 with dict dds, advanced streaming, 39555 -github.tar, level 5 row 2 with dict copy, advanced streaming, 40036 -github.tar, level 5 row 2 with dict load, advanced streaming, 39498 -github.tar, level 5, advanced streaming, 39986 -github.tar, level 5 with dict, advanced streaming, 39465 -github.tar, level 5 with dict dms, advanced streaming, 39370 -github.tar, level 5 with dict dds, advanced streaming, 39396 -github.tar, level 5 with dict copy, advanced streaming, 39465 -github.tar, level 5 with dict load, advanced streaming, 39332 -github.tar, level 6, advanced streaming, 39565 -github.tar, level 6 with dict, advanced streaming, 38894 -github.tar, level 6 with dict dms, advanced streaming, 38901 -github.tar, level 6 with dict dds, advanced streaming, 38903 -github.tar, level 6 with dict copy, advanced streaming, 38894 -github.tar, level 6 with dict load, advanced streaming, 38906 -github.tar, level 7 row 1, advanced streaming, 38295 +github.tar, level 5 row 1, advanced streaming, 39651 +github.tar, level 5 row 1 with dict dms, advanced streaming, 39043 +github.tar, level 5 row 1 with dict dds, advanced streaming, 39069 +github.tar, level 5 row 1 with dict copy, advanced streaming, 39145 +github.tar, level 5 row 1 with dict load, advanced streaming, 39000 +github.tar, level 5 row 2, advanced streaming, 39701 +github.tar, level 5 row 2 with dict dms, advanced streaming, 39365 +github.tar, level 5 row 2 with dict dds, advanced streaming, 39233 +github.tar, level 5 row 2 with dict copy, advanced streaming, 39715 +github.tar, level 5 row 2 with dict load, advanced streaming, 39158 +github.tar, level 5, advanced streaming, 39651 +github.tar, level 5 with dict, advanced streaming, 39145 +github.tar, level 5 with dict dms, advanced streaming, 39043 +github.tar, level 5 with dict dds, advanced streaming, 39069 +github.tar, level 5 with dict copy, advanced streaming, 39145 +github.tar, level 5 with dict load, advanced streaming, 39000 +github.tar, level 6, advanced streaming, 39282 +github.tar, level 6 with dict, advanced streaming, 38656 +github.tar, level 6 with dict dms, advanced streaming, 38640 +github.tar, level 6 with dict dds, advanced streaming, 38643 +github.tar, level 6 with dict copy, advanced streaming, 38656 +github.tar, level 6 with dict load, advanced streaming, 38647 +github.tar, level 7 row 1, advanced streaming, 38005 github.tar, level 7 row 1 with dict dms, advanced streaming, 37832 github.tar, level 7 row 1 with dict dds, advanced streaming, 37857 github.tar, level 7 row 1 with dict copy, advanced streaming, 37839 -github.tar, level 7 row 1 with dict load, advanced streaming, 37565 -github.tar, level 7 row 2, advanced streaming, 38369 +github.tar, level 7 row 1 with dict load, advanced streaming, 37286 +github.tar, level 7 row 2, advanced streaming, 38077 github.tar, level 7 row 2 with dict dms, advanced streaming, 38012 github.tar, level 7 row 2 with dict dds, advanced streaming, 38014 github.tar, level 7 row 2 with dict copy, advanced streaming, 38101 -github.tar, level 7 row 2 with dict load, advanced streaming, 37688 -github.tar, level 7, advanced streaming, 38295 +github.tar, level 7 row 2 with dict load, advanced streaming, 37402 +github.tar, level 7, advanced streaming, 38005 github.tar, level 7 with dict, advanced streaming, 37839 github.tar, level 7 with dict dms, advanced streaming, 37832 github.tar, level 7 with dict dds, advanced streaming, 37857 github.tar, level 7 with dict copy, advanced streaming, 37839 -github.tar, level 7 with dict load, advanced streaming, 37565 +github.tar, level 7 with dict load, advanced streaming, 37286 github.tar, level 9, advanced streaming, 36723 github.tar, level 9 with dict, advanced streaming, 36531 github.tar, level 9 with dict dms, advanced streaming, 36615 @@ -1177,7 +1177,7 @@ github.tar, multithreaded long distance mode, advanced github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 -github.tar, explicit params, advanced streaming, 41768 +github.tar, explicit params, advanced streaming, 41385 github.tar, uncompressed literals, advanced streaming, 41784 github.tar, uncompressed literals optimal, advanced streaming, 35356 github.tar, huffman literals, advanced streaming, 39226 @@ -1189,16 +1189,16 @@ silesia, level 0, old stre silesia, level 1, old streaming, 5305682 silesia, level 3, old streaming, 4839173 silesia, level 4, old streaming, 4776074 -silesia, level 5, old streaming, 4667049 -silesia, level 6, old streaming, 4602956 -silesia, level 7, old streaming, 4568785 -silesia, level 9, old streaming, 4545850 -silesia, level 13, old streaming, 4493990 -silesia, level 16, old streaming, 4359652 -silesia, level 19, old streaming, 4266582 +silesia, level 5, old streaming, 4664679 +silesia, level 6, old streaming, 4601116 +silesia, level 7, old streaming, 4567082 +silesia, level 9, old streaming, 4542474 +silesia, level 13, old streaming, 4490650 +silesia, level 16, old streaming, 4358094 +silesia, level 19, old streaming, 4265908 silesia, no source size, old streaming, 4839137 silesia, uncompressed literals, old streaming, 4839173 -silesia, uncompressed literals optimal, old streaming, 4266582 +silesia, uncompressed literals optimal, old streaming, 4265908 silesia, huffman literals, old streaming, 6174139 silesia.tar, level -5, old streaming, 6857458 silesia.tar, level -3, old streaming, 6508562 @@ -1207,16 +1207,16 @@ silesia.tar, level 0, old stre silesia.tar, level 1, old streaming, 5311452 silesia.tar, level 3, old streaming, 4849720 silesia.tar, level 4, old streaming, 4787534 -silesia.tar, level 5, old streaming, 4669420 -silesia.tar, level 6, old streaming, 4604125 -silesia.tar, level 7, old streaming, 4570206 -silesia.tar, level 9, old streaming, 4555445 -silesia.tar, level 13, old streaming, 4502956 -silesia.tar, level 16, old streaming, 4360385 -silesia.tar, level 19, old streaming, 4260939 +silesia.tar, level 5, old streaming, 4664523 +silesia.tar, level 6, old streaming, 4599420 +silesia.tar, level 7, old streaming, 4565332 +silesia.tar, level 9, old streaming, 4539391 +silesia.tar, level 13, old streaming, 4486652 +silesia.tar, level 16, old streaming, 4358029 +silesia.tar, level 19, old streaming, 4258228 silesia.tar, no source size, old streaming, 4849716 silesia.tar, uncompressed literals, old streaming, 4849720 -silesia.tar, uncompressed literals optimal, old streaming, 4260939 +silesia.tar, uncompressed literals optimal, old streaming, 4258228 silesia.tar, huffman literals, old streaming, 6178057 github, level -5, old streaming, 204407 github, level -5 with dict, old streaming, 45832 @@ -1265,11 +1265,11 @@ github.tar, level 3, old stre github.tar, level 3 with dict, old streaming, 38309 github.tar, level 4, old streaming, 39247 github.tar, level 4 with dict, old streaming, 38270 -github.tar, level 5, old streaming, 39986 -github.tar, level 5 with dict, old streaming, 39465 -github.tar, level 6, old streaming, 39565 -github.tar, level 6 with dict, old streaming, 38894 -github.tar, level 7, old streaming, 38295 +github.tar, level 5, old streaming, 39651 +github.tar, level 5 with dict, old streaming, 39145 +github.tar, level 6, old streaming, 39282 +github.tar, level 6 with dict, old streaming, 38656 +github.tar, level 7, old streaming, 38005 github.tar, level 7 with dict, old streaming, 37839 github.tar, level 9, old streaming, 36723 github.tar, level 9 with dict, old streaming, 36531 @@ -1291,23 +1291,23 @@ silesia, level 0, old stre silesia, level 1, old streaming advanced, 5305682 silesia, level 3, old streaming advanced, 4839173 silesia, level 4, old streaming advanced, 4776074 -silesia, level 5, old streaming advanced, 4667049 -silesia, level 6, old streaming advanced, 4602956 -silesia, level 7, old streaming advanced, 4568785 -silesia, level 9, old streaming advanced, 4545850 -silesia, level 13, old streaming advanced, 4493990 -silesia, level 16, old streaming advanced, 4359652 -silesia, level 19, old streaming advanced, 4266582 +silesia, level 5, old streaming advanced, 4664679 +silesia, level 6, old streaming advanced, 4601116 +silesia, level 7, old streaming advanced, 4567082 +silesia, level 9, old streaming advanced, 4542474 +silesia, level 13, old streaming advanced, 4490650 +silesia, level 16, old streaming advanced, 4358094 +silesia, level 19, old streaming advanced, 4265908 silesia, no source size, old streaming advanced, 4839137 silesia, long distance mode, old streaming advanced, 4839173 silesia, multithreaded, old streaming advanced, 4839173 silesia, multithreaded long distance mode, old streaming advanced, 4839173 silesia, small window log, old streaming advanced, 7110591 -silesia, small hash log, old streaming advanced, 6526141 -silesia, small chain log, old streaming advanced, 4912197 -silesia, explicit params, old streaming advanced, 4795053 +silesia, small hash log, old streaming advanced, 6525259 +silesia, small chain log, old streaming advanced, 4911577 +silesia, explicit params, old streaming advanced, 4792505 silesia, uncompressed literals, old streaming advanced, 4839173 -silesia, uncompressed literals optimal, old streaming advanced, 4266582 +silesia, uncompressed literals optimal, old streaming advanced, 4265908 silesia, huffman literals, old streaming advanced, 6174139 silesia, multithreaded with advanced params, old streaming advanced, 4839173 silesia.tar, level -5, old streaming advanced, 6857458 @@ -1317,23 +1317,23 @@ silesia.tar, level 0, old stre silesia.tar, level 1, old streaming advanced, 5311452 silesia.tar, level 3, old streaming advanced, 4849720 silesia.tar, level 4, old streaming advanced, 4787534 -silesia.tar, level 5, old streaming advanced, 4669420 -silesia.tar, level 6, old streaming advanced, 4604125 -silesia.tar, level 7, old streaming advanced, 4570206 -silesia.tar, level 9, old streaming advanced, 4555445 -silesia.tar, level 13, old streaming advanced, 4502956 -silesia.tar, level 16, old streaming advanced, 4360385 -silesia.tar, level 19, old streaming advanced, 4260939 +silesia.tar, level 5, old streaming advanced, 4664523 +silesia.tar, level 6, old streaming advanced, 4599420 +silesia.tar, level 7, old streaming advanced, 4565332 +silesia.tar, level 9, old streaming advanced, 4539391 +silesia.tar, level 13, old streaming advanced, 4486652 +silesia.tar, level 16, old streaming advanced, 4358029 +silesia.tar, level 19, old streaming advanced, 4258228 silesia.tar, no source size, old streaming advanced, 4849716 silesia.tar, long distance mode, old streaming advanced, 4849720 silesia.tar, multithreaded, old streaming advanced, 4849720 silesia.tar, multithreaded long distance mode, old streaming advanced, 4849720 silesia.tar, small window log, old streaming advanced, 7117027 -silesia.tar, small hash log, old streaming advanced, 6529209 -silesia.tar, small chain log, old streaming advanced, 4917021 -silesia.tar, explicit params, old streaming advanced, 4797673 +silesia.tar, small hash log, old streaming advanced, 6529503 +silesia.tar, small chain log, old streaming advanced, 4915956 +silesia.tar, explicit params, old streaming advanced, 4791739 silesia.tar, uncompressed literals, old streaming advanced, 4849720 -silesia.tar, uncompressed literals optimal, old streaming advanced, 4260939 +silesia.tar, uncompressed literals optimal, old streaming advanced, 4258228 silesia.tar, huffman literals, old streaming advanced, 6178057 silesia.tar, multithreaded with advanced params, old streaming advanced, 4849720 github, level -5, old streaming advanced, 213265 @@ -1391,12 +1391,12 @@ github.tar, level 3, old stre github.tar, level 3 with dict, old streaming advanced, 38327 github.tar, level 4, old streaming advanced, 39247 github.tar, level 4 with dict, old streaming advanced, 38382 -github.tar, level 5, old streaming advanced, 39986 -github.tar, level 5 with dict, old streaming advanced, 39347 -github.tar, level 6, old streaming advanced, 39565 -github.tar, level 6 with dict, old streaming advanced, 38889 -github.tar, level 7, old streaming advanced, 38295 -github.tar, level 7 with dict, old streaming advanced, 37534 +github.tar, level 5, old streaming advanced, 39651 +github.tar, level 5 with dict, old streaming advanced, 39018 +github.tar, level 6, old streaming advanced, 39282 +github.tar, level 6 with dict, old streaming advanced, 38635 +github.tar, level 7, old streaming advanced, 38005 +github.tar, level 7 with dict, old streaming advanced, 37264 github.tar, level 9, old streaming advanced, 36723 github.tar, level 9 with dict, old streaming advanced, 36241 github.tar, level 13, old streaming advanced, 35501 @@ -1413,7 +1413,7 @@ github.tar, multithreaded long distance mode, old stre github.tar, small window log, old streaming advanced, 199556 github.tar, small hash log, old streaming advanced, 129870 github.tar, small chain log, old streaming advanced, 41669 -github.tar, explicit params, old streaming advanced, 41768 +github.tar, explicit params, old streaming advanced, 41385 github.tar, uncompressed literals, old streaming advanced, 39249 github.tar, uncompressed literals optimal, old streaming advanced, 32262 github.tar, huffman literals, old streaming advanced, 42777 @@ -1440,9 +1440,9 @@ github.tar, level 0 with dict, old stre github.tar, level 1 with dict, old streaming cdict, 38716 github.tar, level 3 with dict, old streaming cdict, 38281 github.tar, level 4 with dict, old streaming cdict, 38259 -github.tar, level 5 with dict, old streaming cdict, 39332 -github.tar, level 6 with dict, old streaming cdict, 38906 -github.tar, level 7 with dict, old streaming cdict, 37565 +github.tar, level 5 with dict, old streaming cdict, 39000 +github.tar, level 6 with dict, old streaming cdict, 38647 +github.tar, level 7 with dict, old streaming cdict, 37286 github.tar, level 9 with dict, old streaming cdict, 36322 github.tar, level 13 with dict, old streaming cdict, 36010 github.tar, level 16 with dict, old streaming cdict, 39081 @@ -1470,9 +1470,9 @@ github.tar, level 0 with dict, old stre github.tar, level 1 with dict, old streaming advanced cdict, 38513 github.tar, level 3 with dict, old streaming advanced cdict, 38327 github.tar, level 4 with dict, old streaming advanced cdict, 38382 -github.tar, level 5 with dict, old streaming advanced cdict, 39347 -github.tar, level 6 with dict, old streaming advanced cdict, 38889 -github.tar, level 7 with dict, old streaming advanced cdict, 37534 +github.tar, level 5 with dict, old streaming advanced cdict, 39018 +github.tar, level 6 with dict, old streaming advanced cdict, 38635 +github.tar, level 7 with dict, old streaming advanced cdict, 37264 github.tar, level 9 with dict, old streaming advanced cdict, 36241 github.tar, level 13 with dict, old streaming advanced cdict, 35807 github.tar, level 16 with dict, old streaming advanced cdict, 38578 From 2366a87ddc7ed9ad54944404c57e506ea8bd79bc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 13:38:12 -0700 Subject: [PATCH 437/937] fix minor visual conversion warning --- lib/compress/zstd_preSplit.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 63ff0ded8..77f4534dc 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -63,7 +63,7 @@ addEvents_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t sampl FORCE_INLINE_TEMPLATE void recordFingerprint_generic(Fingerprint* fp, const void* src, size_t srcSize, size_t samplingRate, unsigned hashLog) { - ZSTD_memset(fp, 0, sizeof(unsigned) * (1 << hashLog)); + ZSTD_memset(fp, 0, sizeof(unsigned) * ((size_t)1 << hashLog)); fp->nbEvents = 0; addEvents_generic(fp, src, srcSize, samplingRate, hashLog); } From da2c0dffd8c3e6306fcf2e8e5bd5f8ef97d7a999 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 14:37:00 -0700 Subject: [PATCH 438/937] add faster block splitting heuristic, suitable for dfast strategy --- lib/compress/zstd_compress.c | 8 +++++--- lib/compress/zstd_preSplit.c | 22 ++++++++++++++-------- lib/compress/zstd_preSplit.h | 7 +++---- 3 files changed, 22 insertions(+), 15 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index e78de2ba8..ee939f227 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4507,11 +4507,13 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src /* dynamic splitting has a cpu cost for analysis, * due to that cost it's only used for higher levels */ if (strat >= ZSTD_btopt) - return ZSTD_splitBlock(src, blockSizeMax, split_lvl3, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, 3, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_lazy2) - return ZSTD_splitBlock(src, blockSizeMax, split_lvl2, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, 2, cctx->tmpWorkspace, cctx->tmpWkspSize); if (strat >= ZSTD_greedy) - return ZSTD_splitBlock(src, blockSizeMax, split_lvl1, cctx->tmpWorkspace, cctx->tmpWkspSize); + return ZSTD_splitBlock(src, blockSizeMax, 1, cctx->tmpWorkspace, cctx->tmpWkspSize); + if (strat >= ZSTD_dfast) + return ZSTD_splitBlock(src, blockSizeMax, 0, cctx->tmpWorkspace, cctx->tmpWkspSize); /* blind split strategy * heuristic value, tested as being "generally better". * no cpu cost, but can over-split homegeneous data. diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 77f4534dc..3f6edb612 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -26,8 +26,13 @@ #define HASHMASK (HASHTABLESIZE - 1) #define KNUTH 0x9e3779b9 +/* for hashLog > 8, hash 2 bytes. + * for hashLog == 8, just take the byte, no hashing. + * The speed of this method relies on compile-time constant propagation */ FORCE_INLINE_TEMPLATE unsigned hash2(const void *p, unsigned hashLog) { + assert(hashLog >= 8); + if (hashLog == 8) return (U32)((const BYTE*)p)[0]; assert(hashLog <= HASHLOG_MAX); return (U32)(MEM_read16(p)) * KNUTH >> (32 - hashLog); } @@ -81,6 +86,7 @@ typedef void (*RecordEvents_f)(Fingerprint* fp, const void* src, size_t srcSize) ZSTD_GEN_RECORD_FINGERPRINT(1, 10) ZSTD_GEN_RECORD_FINGERPRINT(5, 10) ZSTD_GEN_RECORD_FINGERPRINT(11, 9) +ZSTD_GEN_RECORD_FINGERPRINT(43, 8) static U64 abs64(S64 s64) { return (U64)((s64 < 0) ? -s64 : s64); } @@ -145,14 +151,14 @@ static void removeEvents(Fingerprint* acc, const Fingerprint* slice) #define CHUNKSIZE (8 << 10) static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, - ZSTD_SplitBlock_strategy_e splitStrat, + int level, void* workspace, size_t wkspSize) { static const RecordEvents_f records_fs[] = { - FP_RECORD(11), FP_RECORD(5), FP_RECORD(1) + FP_RECORD(43), FP_RECORD(11), FP_RECORD(5), FP_RECORD(1) }; - static const unsigned hashParams[] = { 9, 10, 10 }; - const RecordEvents_f record_f = (assert(splitStrat<=split_lvl3), records_fs[splitStrat]); + static const unsigned hashParams[] = { 8, 9, 10, 10 }; + const RecordEvents_f record_f = (assert(0<=level && level<=3), records_fs[level]); FPStats* const fpstats = (FPStats*)workspace; const char* p = (const char*)blockStart; int penalty = THRESHOLD_PENALTY; @@ -167,7 +173,7 @@ static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, record_f(&fpstats->pastEvents, p, CHUNKSIZE); for (pos = CHUNKSIZE; pos <= blockSize - CHUNKSIZE; pos += CHUNKSIZE) { record_f(&fpstats->newEvents, p + pos, CHUNKSIZE); - if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty, hashParams[splitStrat])) { + if (compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, penalty, hashParams[level])) { return pos; } else { mergeEvents(&fpstats->pastEvents, &fpstats->newEvents); @@ -180,9 +186,9 @@ static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, } size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, - ZSTD_SplitBlock_strategy_e splitStrat, + int level, void* workspace, size_t wkspSize) { - assert(splitStrat <= split_lvl3); - return ZSTD_splitBlock_byChunks(blockStart, blockSize, splitStrat, workspace, wkspSize); + assert(0<=level && level<=3); + return ZSTD_splitBlock_byChunks(blockStart, blockSize, level, workspace, wkspSize); } diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index cf829ecee..07d7d4ef5 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -17,11 +17,10 @@ extern "C" { #endif -typedef enum { split_lvl1, split_lvl2, split_lvl3 } ZSTD_SplitBlock_strategy_e; - #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 -/* note: +/* @level must be a value between 0 and 3. + * higher levels spend more energy to find block boundaries * @workspace must be aligned on 8-bytes boundaries * @wkspSize must be at least >= ZSTD_SLIPBLOCK_WORKSPACESIZE * note2: @@ -30,7 +29,7 @@ typedef enum { split_lvl1, split_lvl2, split_lvl3 } ZSTD_SplitBlock_strategy_e; * This could be extended to smaller sizes in the future. */ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, - ZSTD_SplitBlock_strategy_e splitStrat, + int level, void* workspace, size_t wkspSize); #if defined (__cplusplus) From c63b5d2294cf6d185a5b284725e5db09646a3296 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 14:47:55 -0700 Subject: [PATCH 439/937] update regression results --- tests/regression/results.csv | 466 +++++++++++++++++------------------ 1 file changed, 233 insertions(+), 233 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index b46c4ca5c..0b1a79b85 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -2,10 +2,10 @@ Data, Config, Method, silesia.tar, level -5, compress simple, 6860782 silesia.tar, level -3, compress simple, 6507448 silesia.tar, level -1, compress simple, 6175582 -silesia.tar, level 0, compress simple, 4843429 +silesia.tar, level 0, compress simple, 4829268 silesia.tar, level 1, compress simple, 5316794 -silesia.tar, level 3, compress simple, 4843429 -silesia.tar, level 4, compress simple, 4780657 +silesia.tar, level 3, compress simple, 4829268 +silesia.tar, level 4, compress simple, 4767074 silesia.tar, level 5, compress simple, 4662847 silesia.tar, level 6, compress simple, 4597877 silesia.tar, level 7, compress simple, 4563998 @@ -13,16 +13,16 @@ silesia.tar, level 9, compress silesia.tar, level 13, compress simple, 4484732 silesia.tar, level 16, compress simple, 4355572 silesia.tar, level 19, compress simple, 4257629 -silesia.tar, uncompressed literals, compress simple, 4843429 +silesia.tar, uncompressed literals, compress simple, 4829268 silesia.tar, uncompressed literals optimal, compress simple, 4257629 silesia.tar, huffman literals, compress simple, 6175582 github.tar, level -5, compress simple, 52320 github.tar, level -3, compress simple, 45823 github.tar, level -1, compress simple, 42740 -github.tar, level 0, compress simple, 39073 +github.tar, level 0, compress simple, 38884 github.tar, level 1, compress simple, 39444 -github.tar, level 3, compress simple, 39073 -github.tar, level 4, compress simple, 39068 +github.tar, level 3, compress simple, 38884 +github.tar, level 4, compress simple, 38880 github.tar, level 5, compress simple, 39651 github.tar, level 6, compress simple, 39282 github.tar, level 7, compress simple, 38005 @@ -30,16 +30,16 @@ github.tar, level 9, compress github.tar, level 13, compress simple, 35501 github.tar, level 16, compress simple, 40466 github.tar, level 19, compress simple, 32262 -github.tar, uncompressed literals, compress simple, 39073 +github.tar, uncompressed literals, compress simple, 38884 github.tar, uncompressed literals optimal, compress simple, 32262 github.tar, huffman literals, compress simple, 42740 silesia, level -5, compress cctx, 6857776 silesia, level -3, compress cctx, 6504756 silesia, level -1, compress cctx, 6174127 -silesia, level 0, compress cctx, 4838417 +silesia, level 0, compress cctx, 4832054 silesia, level 1, compress cctx, 5306931 -silesia, level 3, compress cctx, 4838417 -silesia, level 4, compress cctx, 4775359 +silesia, level 3, compress cctx, 4832054 +silesia, level 4, compress cctx, 4768799 silesia, level 5, compress cctx, 4663718 silesia, level 6, compress cctx, 4600034 silesia, level 7, compress cctx, 4566069 @@ -47,17 +47,17 @@ silesia, level 9, compress silesia, level 13, compress cctx, 4488969 silesia, level 16, compress cctx, 4356799 silesia, level 19, compress cctx, 4265851 -silesia, long distance mode, compress cctx, 4838417 -silesia, multithreaded, compress cctx, 4838417 -silesia, multithreaded long distance mode, compress cctx, 4838417 +silesia, long distance mode, compress cctx, 4832054 +silesia, multithreaded, compress cctx, 4832054 +silesia, multithreaded long distance mode, compress cctx, 4832054 silesia, small window log, compress cctx, 7082907 silesia, small hash log, compress cctx, 6525510 silesia, small chain log, compress cctx, 4912248 silesia, explicit params, compress cctx, 4789676 -silesia, uncompressed literals, compress cctx, 4838417 +silesia, uncompressed literals, compress cctx, 4832054 silesia, uncompressed literals optimal, compress cctx, 4265851 silesia, huffman literals, compress cctx, 6174127 -silesia, multithreaded with advanced params, compress cctx, 4838417 +silesia, multithreaded with advanced params, compress cctx, 4832054 github, level -5, compress cctx, 204407 github, level -5 with dict, compress cctx, 47581 github, level -3, compress cctx, 193253 @@ -100,10 +100,10 @@ github, multithreaded with advanced params, compress silesia, level -5, zstdcli, 6856073 silesia, level -3, zstdcli, 6505580 silesia, level -1, zstdcli, 6172649 -silesia, level 0, zstdcli, 4838997 +silesia, level 0, zstdcli, 4833113 silesia, level 1, zstdcli, 5306179 -silesia, level 3, zstdcli, 4838997 -silesia, level 4, zstdcli, 4775769 +silesia, level 3, zstdcli, 4833113 +silesia, level 4, zstdcli, 4770061 silesia, level 5, zstdcli, 4663332 silesia, level 6, zstdcli, 4599601 silesia, level 7, zstdcli, 4565601 @@ -111,24 +111,24 @@ silesia, level 9, zstdcli, silesia, level 13, zstdcli, 4488438 silesia, level 16, zstdcli, 4358150 silesia, level 19, zstdcli, 4265929 -silesia, long distance mode, zstdcli, 4830467 -silesia, multithreaded, zstdcli, 4838997 -silesia, multithreaded long distance mode, zstdcli, 4830467 +silesia, long distance mode, zstdcli, 4824875 +silesia, multithreaded, zstdcli, 4833113 +silesia, multithreaded long distance mode, zstdcli, 4824875 silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6527214 silesia, small chain log, zstdcli, 4911647 silesia, explicit params, zstdcli, 4790803 -silesia, uncompressed literals, zstdcli, 5117843 +silesia, uncompressed literals, zstdcli, 5118235 silesia, uncompressed literals optimal, zstdcli, 4316761 silesia, huffman literals, zstdcli, 5320793 -silesia, multithreaded with advanced params, zstdcli, 5117843 +silesia, multithreaded with advanced params, zstdcli, 5118235 silesia.tar, level -5, zstdcli, 6860173 silesia.tar, level -3, zstdcli, 6507196 silesia.tar, level -1, zstdcli, 6177719 -silesia.tar, level 0, zstdcli, 4841906 +silesia.tar, level 0, zstdcli, 4836004 silesia.tar, level 1, zstdcli, 5313917 -silesia.tar, level 3, zstdcli, 4841906 -silesia.tar, level 4, zstdcli, 4780121 +silesia.tar, level 3, zstdcli, 4836004 +silesia.tar, level 4, zstdcli, 4774061 silesia.tar, level 5, zstdcli, 4667310 silesia.tar, level 6, zstdcli, 4602398 silesia.tar, level 7, zstdcli, 4568891 @@ -136,18 +136,18 @@ silesia.tar, level 9, zstdcli, silesia.tar, level 13, zstdcli, 4488484 silesia.tar, level 16, zstdcli, 4357018 silesia.tar, level 19, zstdcli, 4259593 -silesia.tar, no source size, zstdcli, 4841902 -silesia.tar, long distance mode, zstdcli, 4834266 -silesia.tar, multithreaded, zstdcli, 4841906 -silesia.tar, multithreaded long distance mode, zstdcli, 4834266 +silesia.tar, no source size, zstdcli, 4836000 +silesia.tar, long distance mode, zstdcli, 4828171 +silesia.tar, multithreaded, zstdcli, 4836004 +silesia.tar, multithreaded long distance mode, zstdcli, 4828171 silesia.tar, small window log, zstdcli, 7100110 silesia.tar, small hash log, zstdcli, 6530127 silesia.tar, small chain log, zstdcli, 4915865 silesia.tar, explicit params, zstdcli, 4808370 -silesia.tar, uncompressed literals, zstdcli, 5116446 +silesia.tar, uncompressed literals, zstdcli, 5116583 silesia.tar, uncompressed literals optimal, zstdcli, 4306520 silesia.tar, huffman literals, zstdcli, 5326463 -silesia.tar, multithreaded with advanced params, zstdcli, 5116446 +silesia.tar, multithreaded with advanced params, zstdcli, 5116583 github, level -5, zstdcli, 206407 github, level -5 with dict, zstdcli, 47832 github, level -3, zstdcli, 195253 @@ -193,14 +193,14 @@ github.tar, level -3, zstdcli, github.tar, level -3 with dict, zstdcli, 44883 github.tar, level -1, zstdcli, 42688 github.tar, level -1 with dict, zstdcli, 41510 -github.tar, level 0, zstdcli, 39071 -github.tar, level 0 with dict, zstdcli, 38140 +github.tar, level 0, zstdcli, 38888 +github.tar, level 0 with dict, zstdcli, 37999 github.tar, level 1, zstdcli, 39404 github.tar, level 1 with dict, zstdcli, 38320 -github.tar, level 3, zstdcli, 39071 -github.tar, level 3 with dict, zstdcli, 38140 -github.tar, level 4, zstdcli, 39067 -github.tar, level 4 with dict, zstdcli, 38082 +github.tar, level 3, zstdcli, 38888 +github.tar, level 3 with dict, zstdcli, 37999 +github.tar, level 4, zstdcli, 38884 +github.tar, level 4 with dict, zstdcli, 37952 github.tar, level 5, zstdcli, 39655 github.tar, level 5 with dict, zstdcli, 39073 github.tar, level 6, zstdcli, 39286 @@ -215,26 +215,26 @@ github.tar, level 16, zstdcli, github.tar, level 16 with dict, zstdcli, 33379 github.tar, level 19, zstdcli, 32266 github.tar, level 19 with dict, zstdcli, 32705 -github.tar, no source size, zstdcli, 39068 -github.tar, no source size with dict, zstdcli, 38274 -github.tar, long distance mode, zstdcli, 40381 -github.tar, multithreaded, zstdcli, 39071 -github.tar, multithreaded long distance mode, zstdcli, 40381 +github.tar, no source size, zstdcli, 38885 +github.tar, no source size with dict, zstdcli, 38115 +github.tar, long distance mode, zstdcli, 40227 +github.tar, multithreaded, zstdcli, 38888 +github.tar, multithreaded long distance mode, zstdcli, 40227 github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 github.tar, explicit params, zstdcli, 41385 -github.tar, uncompressed literals, zstdcli, 41704 +github.tar, uncompressed literals, zstdcli, 41566 github.tar, uncompressed literals optimal, zstdcli, 35360 github.tar, huffman literals, zstdcli, 39046 -github.tar, multithreaded with advanced params, zstdcli, 41704 +github.tar, multithreaded with advanced params, zstdcli, 41566 silesia, level -5, advanced one pass, 6857776 silesia, level -3, advanced one pass, 6504756 silesia, level -1, advanced one pass, 6174127 -silesia, level 0, advanced one pass, 4838417 +silesia, level 0, advanced one pass, 4832054 silesia, level 1, advanced one pass, 5306931 -silesia, level 3, advanced one pass, 4838417 -silesia, level 4, advanced one pass, 4775359 +silesia, level 3, advanced one pass, 4832054 +silesia, level 4, advanced one pass, 4768799 silesia, level 5 row 1, advanced one pass, 4663718 silesia, level 5 row 2, advanced one pass, 4666272 silesia, level 5, advanced one pass, 4663718 @@ -250,25 +250,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced one pass, 4488969 silesia, level 16, advanced one pass, 4356799 silesia, level 19, advanced one pass, 4265851 -silesia, no source size, advanced one pass, 4838417 -silesia, long distance mode, advanced one pass, 4830097 -silesia, multithreaded, advanced one pass, 4838949 -silesia, multithreaded long distance mode, advanced one pass, 4830419 +silesia, no source size, advanced one pass, 4832054 +silesia, long distance mode, advanced one pass, 4823833 +silesia, multithreaded, advanced one pass, 4833065 +silesia, multithreaded long distance mode, advanced one pass, 4824827 silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6525510 silesia, small chain log, advanced one pass, 4912248 silesia, explicit params, advanced one pass, 4791219 -silesia, uncompressed literals, advanced one pass, 5117482 +silesia, uncompressed literals, advanced one pass, 5117526 silesia, uncompressed literals optimal, advanced one pass, 4316644 silesia, huffman literals, advanced one pass, 5321686 -silesia, multithreaded with advanced params, advanced one pass, 5117795 +silesia, multithreaded with advanced params, advanced one pass, 5118187 silesia.tar, level -5, advanced one pass, 6860782 silesia.tar, level -3, advanced one pass, 6507448 silesia.tar, level -1, advanced one pass, 6175582 -silesia.tar, level 0, advanced one pass, 4843429 +silesia.tar, level 0, advanced one pass, 4829268 silesia.tar, level 1, advanced one pass, 5316794 -silesia.tar, level 3, advanced one pass, 4843429 -silesia.tar, level 4, advanced one pass, 4780657 +silesia.tar, level 3, advanced one pass, 4829268 +silesia.tar, level 4, advanced one pass, 4767074 silesia.tar, level 5 row 1, advanced one pass, 4662847 silesia.tar, level 5 row 2, advanced one pass, 4666825 silesia.tar, level 5, advanced one pass, 4662847 @@ -284,18 +284,18 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced one pass, 4484732 silesia.tar, level 16, advanced one pass, 4355572 silesia.tar, level 19, advanced one pass, 4257629 -silesia.tar, no source size, advanced one pass, 4843429 -silesia.tar, long distance mode, advanced one pass, 4830453 -silesia.tar, multithreaded, advanced one pass, 4841902 -silesia.tar, multithreaded long distance mode, advanced one pass, 4834262 +silesia.tar, no source size, advanced one pass, 4829268 +silesia.tar, long distance mode, advanced one pass, 4816169 +silesia.tar, multithreaded, advanced one pass, 4836000 +silesia.tar, multithreaded long distance mode, advanced one pass, 4828167 silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6530222 silesia.tar, small chain log, advanced one pass, 4915689 silesia.tar, explicit params, advanced one pass, 4790421 -silesia.tar, uncompressed literals, advanced one pass, 5116329 +silesia.tar, uncompressed literals, advanced one pass, 5114702 silesia.tar, uncompressed literals optimal, advanced one pass, 4306289 silesia.tar, huffman literals, advanced one pass, 5331382 -silesia.tar, multithreaded with advanced params, advanced one pass, 5116442 +silesia.tar, multithreaded with advanced params, advanced one pass, 5116579 github, level -5, advanced one pass, 204407 github, level -5 with dict, advanced one pass, 45832 github, level -3, advanced one pass, 193253 @@ -427,30 +427,30 @@ github.tar, level -3, advanced github.tar, level -3 with dict, advanced one pass, 44882 github.tar, level -1, advanced one pass, 42740 github.tar, level -1 with dict, advanced one pass, 41506 -github.tar, level 0, advanced one pass, 39073 -github.tar, level 0 with dict, advanced one pass, 38146 -github.tar, level 0 with dict dms, advanced one pass, 38262 -github.tar, level 0 with dict dds, advanced one pass, 38262 -github.tar, level 0 with dict copy, advanced one pass, 38146 -github.tar, level 0 with dict load, advanced one pass, 38107 +github.tar, level 0, advanced one pass, 38884 +github.tar, level 0 with dict, advanced one pass, 37995 +github.tar, level 0 with dict dms, advanced one pass, 38114 +github.tar, level 0 with dict dds, advanced one pass, 38114 +github.tar, level 0 with dict copy, advanced one pass, 37995 +github.tar, level 0 with dict load, advanced one pass, 37956 github.tar, level 1, advanced one pass, 39444 github.tar, level 1 with dict, advanced one pass, 38338 github.tar, level 1 with dict dms, advanced one pass, 38641 github.tar, level 1 with dict dds, advanced one pass, 38641 github.tar, level 1 with dict copy, advanced one pass, 38338 github.tar, level 1 with dict load, advanced one pass, 38592 -github.tar, level 3, advanced one pass, 39073 -github.tar, level 3 with dict, advanced one pass, 38146 -github.tar, level 3 with dict dms, advanced one pass, 38262 -github.tar, level 3 with dict dds, advanced one pass, 38262 -github.tar, level 3 with dict copy, advanced one pass, 38146 -github.tar, level 3 with dict load, advanced one pass, 38107 -github.tar, level 4, advanced one pass, 39068 -github.tar, level 4 with dict, advanced one pass, 38081 -github.tar, level 4 with dict dms, advanced one pass, 38135 -github.tar, level 4 with dict dds, advanced one pass, 38135 -github.tar, level 4 with dict copy, advanced one pass, 38081 -github.tar, level 4 with dict load, advanced one pass, 38088 +github.tar, level 3, advanced one pass, 38884 +github.tar, level 3 with dict, advanced one pass, 37995 +github.tar, level 3 with dict dms, advanced one pass, 38114 +github.tar, level 3 with dict dds, advanced one pass, 38114 +github.tar, level 3 with dict copy, advanced one pass, 37995 +github.tar, level 3 with dict load, advanced one pass, 37956 +github.tar, level 4, advanced one pass, 38880 +github.tar, level 4 with dict, advanced one pass, 37948 +github.tar, level 4 with dict dms, advanced one pass, 37995 +github.tar, level 4 with dict dds, advanced one pass, 37995 +github.tar, level 4 with dict copy, advanced one pass, 37948 +github.tar, level 4 with dict load, advanced one pass, 37927 github.tar, level 5 row 1, advanced one pass, 39651 github.tar, level 5 row 1 with dict dms, advanced one pass, 39043 github.tar, level 5 row 1 with dict dds, advanced one pass, 39069 @@ -533,26 +533,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass, 32565 github.tar, level 19 with dict copy, advanced one pass, 32701 github.tar, level 19 with dict load, advanced one pass, 32428 -github.tar, no source size, advanced one pass, 39073 -github.tar, no source size with dict, advanced one pass, 38146 -github.tar, long distance mode, advanced one pass, 40402 -github.tar, multithreaded, advanced one pass, 39067 -github.tar, multithreaded long distance mode, advanced one pass, 40377 +github.tar, no source size, advanced one pass, 38884 +github.tar, no source size with dict, advanced one pass, 37995 +github.tar, long distance mode, advanced one pass, 40242 +github.tar, multithreaded, advanced one pass, 38884 +github.tar, multithreaded long distance mode, advanced one pass, 40223 github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 github.tar, explicit params, advanced one pass, 41385 -github.tar, uncompressed literals, advanced one pass, 41709 +github.tar, uncompressed literals, advanced one pass, 41562 github.tar, uncompressed literals optimal, advanced one pass, 35356 github.tar, huffman literals, advanced one pass, 39099 -github.tar, multithreaded with advanced params, advanced one pass, 41700 +github.tar, multithreaded with advanced params, advanced one pass, 41562 silesia, level -5, advanced one pass small out, 6857776 silesia, level -3, advanced one pass small out, 6504756 silesia, level -1, advanced one pass small out, 6174127 -silesia, level 0, advanced one pass small out, 4838417 +silesia, level 0, advanced one pass small out, 4832054 silesia, level 1, advanced one pass small out, 5306931 -silesia, level 3, advanced one pass small out, 4838417 -silesia, level 4, advanced one pass small out, 4775359 +silesia, level 3, advanced one pass small out, 4832054 +silesia, level 4, advanced one pass small out, 4768799 silesia, level 5 row 1, advanced one pass small out, 4663718 silesia, level 5 row 2, advanced one pass small out, 4666272 silesia, level 5, advanced one pass small out, 4663718 @@ -568,25 +568,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced one pass small out, 4488969 silesia, level 16, advanced one pass small out, 4356799 silesia, level 19, advanced one pass small out, 4265851 -silesia, no source size, advanced one pass small out, 4838417 -silesia, long distance mode, advanced one pass small out, 4830097 -silesia, multithreaded, advanced one pass small out, 4838949 -silesia, multithreaded long distance mode, advanced one pass small out, 4830419 +silesia, no source size, advanced one pass small out, 4832054 +silesia, long distance mode, advanced one pass small out, 4823833 +silesia, multithreaded, advanced one pass small out, 4833065 +silesia, multithreaded long distance mode, advanced one pass small out, 4824827 silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6525510 silesia, small chain log, advanced one pass small out, 4912248 silesia, explicit params, advanced one pass small out, 4791219 -silesia, uncompressed literals, advanced one pass small out, 5117482 +silesia, uncompressed literals, advanced one pass small out, 5117526 silesia, uncompressed literals optimal, advanced one pass small out, 4316644 silesia, huffman literals, advanced one pass small out, 5321686 -silesia, multithreaded with advanced params, advanced one pass small out, 5117795 +silesia, multithreaded with advanced params, advanced one pass small out, 5118187 silesia.tar, level -5, advanced one pass small out, 6860782 silesia.tar, level -3, advanced one pass small out, 6507448 silesia.tar, level -1, advanced one pass small out, 6175582 -silesia.tar, level 0, advanced one pass small out, 4843429 +silesia.tar, level 0, advanced one pass small out, 4829268 silesia.tar, level 1, advanced one pass small out, 5316794 -silesia.tar, level 3, advanced one pass small out, 4843429 -silesia.tar, level 4, advanced one pass small out, 4780657 +silesia.tar, level 3, advanced one pass small out, 4829268 +silesia.tar, level 4, advanced one pass small out, 4767074 silesia.tar, level 5 row 1, advanced one pass small out, 4662847 silesia.tar, level 5 row 2, advanced one pass small out, 4666825 silesia.tar, level 5, advanced one pass small out, 4662847 @@ -602,18 +602,18 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced one pass small out, 4484732 silesia.tar, level 16, advanced one pass small out, 4355572 silesia.tar, level 19, advanced one pass small out, 4257629 -silesia.tar, no source size, advanced one pass small out, 4843429 -silesia.tar, long distance mode, advanced one pass small out, 4830453 -silesia.tar, multithreaded, advanced one pass small out, 4841902 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4834262 +silesia.tar, no source size, advanced one pass small out, 4829268 +silesia.tar, long distance mode, advanced one pass small out, 4816169 +silesia.tar, multithreaded, advanced one pass small out, 4836000 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4828167 silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6530222 silesia.tar, small chain log, advanced one pass small out, 4915689 silesia.tar, explicit params, advanced one pass small out, 4790421 -silesia.tar, uncompressed literals, advanced one pass small out, 5116329 +silesia.tar, uncompressed literals, advanced one pass small out, 5114702 silesia.tar, uncompressed literals optimal, advanced one pass small out, 4306289 silesia.tar, huffman literals, advanced one pass small out, 5331382 -silesia.tar, multithreaded with advanced params, advanced one pass small out, 5116442 +silesia.tar, multithreaded with advanced params, advanced one pass small out, 5116579 github, level -5, advanced one pass small out, 204407 github, level -5 with dict, advanced one pass small out, 45832 github, level -3, advanced one pass small out, 193253 @@ -745,30 +745,30 @@ github.tar, level -3, advanced github.tar, level -3 with dict, advanced one pass small out, 44882 github.tar, level -1, advanced one pass small out, 42740 github.tar, level -1 with dict, advanced one pass small out, 41506 -github.tar, level 0, advanced one pass small out, 39073 -github.tar, level 0 with dict, advanced one pass small out, 38146 -github.tar, level 0 with dict dms, advanced one pass small out, 38262 -github.tar, level 0 with dict dds, advanced one pass small out, 38262 -github.tar, level 0 with dict copy, advanced one pass small out, 38146 -github.tar, level 0 with dict load, advanced one pass small out, 38107 +github.tar, level 0, advanced one pass small out, 38884 +github.tar, level 0 with dict, advanced one pass small out, 37995 +github.tar, level 0 with dict dms, advanced one pass small out, 38114 +github.tar, level 0 with dict dds, advanced one pass small out, 38114 +github.tar, level 0 with dict copy, advanced one pass small out, 37995 +github.tar, level 0 with dict load, advanced one pass small out, 37956 github.tar, level 1, advanced one pass small out, 39444 github.tar, level 1 with dict, advanced one pass small out, 38338 github.tar, level 1 with dict dms, advanced one pass small out, 38641 github.tar, level 1 with dict dds, advanced one pass small out, 38641 github.tar, level 1 with dict copy, advanced one pass small out, 38338 github.tar, level 1 with dict load, advanced one pass small out, 38592 -github.tar, level 3, advanced one pass small out, 39073 -github.tar, level 3 with dict, advanced one pass small out, 38146 -github.tar, level 3 with dict dms, advanced one pass small out, 38262 -github.tar, level 3 with dict dds, advanced one pass small out, 38262 -github.tar, level 3 with dict copy, advanced one pass small out, 38146 -github.tar, level 3 with dict load, advanced one pass small out, 38107 -github.tar, level 4, advanced one pass small out, 39068 -github.tar, level 4 with dict, advanced one pass small out, 38081 -github.tar, level 4 with dict dms, advanced one pass small out, 38135 -github.tar, level 4 with dict dds, advanced one pass small out, 38135 -github.tar, level 4 with dict copy, advanced one pass small out, 38081 -github.tar, level 4 with dict load, advanced one pass small out, 38088 +github.tar, level 3, advanced one pass small out, 38884 +github.tar, level 3 with dict, advanced one pass small out, 37995 +github.tar, level 3 with dict dms, advanced one pass small out, 38114 +github.tar, level 3 with dict dds, advanced one pass small out, 38114 +github.tar, level 3 with dict copy, advanced one pass small out, 37995 +github.tar, level 3 with dict load, advanced one pass small out, 37956 +github.tar, level 4, advanced one pass small out, 38880 +github.tar, level 4 with dict, advanced one pass small out, 37948 +github.tar, level 4 with dict dms, advanced one pass small out, 37995 +github.tar, level 4 with dict dds, advanced one pass small out, 37995 +github.tar, level 4 with dict copy, advanced one pass small out, 37948 +github.tar, level 4 with dict load, advanced one pass small out, 37927 github.tar, level 5 row 1, advanced one pass small out, 39651 github.tar, level 5 row 1 with dict dms, advanced one pass small out, 39043 github.tar, level 5 row 1 with dict dds, advanced one pass small out, 39069 @@ -851,26 +851,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced one pass small out, 32565 github.tar, level 19 with dict copy, advanced one pass small out, 32701 github.tar, level 19 with dict load, advanced one pass small out, 32428 -github.tar, no source size, advanced one pass small out, 39073 -github.tar, no source size with dict, advanced one pass small out, 38146 -github.tar, long distance mode, advanced one pass small out, 40402 -github.tar, multithreaded, advanced one pass small out, 39067 -github.tar, multithreaded long distance mode, advanced one pass small out, 40377 +github.tar, no source size, advanced one pass small out, 38884 +github.tar, no source size with dict, advanced one pass small out, 37995 +github.tar, long distance mode, advanced one pass small out, 40242 +github.tar, multithreaded, advanced one pass small out, 38884 +github.tar, multithreaded long distance mode, advanced one pass small out, 40223 github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 github.tar, explicit params, advanced one pass small out, 41385 -github.tar, uncompressed literals, advanced one pass small out, 41709 +github.tar, uncompressed literals, advanced one pass small out, 41562 github.tar, uncompressed literals optimal, advanced one pass small out, 35356 github.tar, huffman literals, advanced one pass small out, 39099 -github.tar, multithreaded with advanced params, advanced one pass small out, 41700 +github.tar, multithreaded with advanced params, advanced one pass small out, 41562 silesia, level -5, advanced streaming, 6856699 silesia, level -3, advanced streaming, 6505694 silesia, level -1, advanced streaming, 6174139 -silesia, level 0, advanced streaming, 4839173 +silesia, level 0, advanced streaming, 4835804 silesia, level 1, advanced streaming, 5305682 -silesia, level 3, advanced streaming, 4839173 -silesia, level 4, advanced streaming, 4776074 +silesia, level 3, advanced streaming, 4835804 +silesia, level 4, advanced streaming, 4773049 silesia, level 5 row 1, advanced streaming, 4664679 silesia, level 5 row 2, advanced streaming, 4667307 silesia, level 5, advanced streaming, 4664679 @@ -886,25 +886,25 @@ silesia, level 12 row 2, advanced silesia, level 13, advanced streaming, 4490650 silesia, level 16, advanced streaming, 4358094 silesia, level 19, advanced streaming, 4265908 -silesia, no source size, advanced streaming, 4839137 -silesia, long distance mode, advanced streaming, 4831125 -silesia, multithreaded, advanced streaming, 4838949 -silesia, multithreaded long distance mode, advanced streaming, 4830419 +silesia, no source size, advanced streaming, 4835768 +silesia, long distance mode, advanced streaming, 4827592 +silesia, multithreaded, advanced streaming, 4833065 +silesia, multithreaded long distance mode, advanced streaming, 4824827 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6525259 silesia, small chain log, advanced streaming, 4911577 silesia, explicit params, advanced streaming, 4792505 -silesia, uncompressed literals, advanced streaming, 5117625 +silesia, uncompressed literals, advanced streaming, 5116404 silesia, uncompressed literals optimal, advanced streaming, 4316533 silesia, huffman literals, advanced streaming, 5321812 -silesia, multithreaded with advanced params, advanced streaming, 5117795 +silesia, multithreaded with advanced params, advanced streaming, 5118187 silesia.tar, level -5, advanced streaming, 6857458 silesia.tar, level -3, advanced streaming, 6508562 silesia.tar, level -1, advanced streaming, 6178057 -silesia.tar, level 0, advanced streaming, 4849720 +silesia.tar, level 0, advanced streaming, 4846783 silesia.tar, level 1, advanced streaming, 5311452 -silesia.tar, level 3, advanced streaming, 4849720 -silesia.tar, level 4, advanced streaming, 4787534 +silesia.tar, level 3, advanced streaming, 4846783 +silesia.tar, level 4, advanced streaming, 4785332 silesia.tar, level 5 row 1, advanced streaming, 4664523 silesia.tar, level 5 row 2, advanced streaming, 4668292 silesia.tar, level 5, advanced streaming, 4664523 @@ -920,18 +920,18 @@ silesia.tar, level 12 row 2, advanced silesia.tar, level 13, advanced streaming, 4486652 silesia.tar, level 16, advanced streaming, 4358029 silesia.tar, level 19, advanced streaming, 4258228 -silesia.tar, no source size, advanced streaming, 4849716 -silesia.tar, long distance mode, advanced streaming, 4829339 -silesia.tar, multithreaded, advanced streaming, 4841902 -silesia.tar, multithreaded long distance mode, advanced streaming, 4834262 +silesia.tar, no source size, advanced streaming, 4846779 +silesia.tar, long distance mode, advanced streaming, 4826177 +silesia.tar, multithreaded, advanced streaming, 4836000 +silesia.tar, multithreaded long distance mode, advanced streaming, 4828167 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529503 silesia.tar, small chain log, advanced streaming, 4915956 silesia.tar, explicit params, advanced streaming, 4791739 -silesia.tar, uncompressed literals, advanced streaming, 5124811 +silesia.tar, uncompressed literals, advanced streaming, 5123274 silesia.tar, uncompressed literals optimal, advanced streaming, 4306968 silesia.tar, huffman literals, advanced streaming, 5326278 -silesia.tar, multithreaded with advanced params, advanced streaming, 5116442 +silesia.tar, multithreaded with advanced params, advanced streaming, 5116579 github, level -5, advanced streaming, 204407 github, level -5 with dict, advanced streaming, 45832 github, level -3, advanced streaming, 193253 @@ -1063,30 +1063,30 @@ github.tar, level -3, advanced github.tar, level -3 with dict, advanced streaming, 44973 github.tar, level -1, advanced streaming, 42777 github.tar, level -1 with dict, advanced streaming, 41603 -github.tar, level 0, advanced streaming, 39249 -github.tar, level 0 with dict, advanced streaming, 38309 -github.tar, level 0 with dict dms, advanced streaming, 38445 -github.tar, level 0 with dict dds, advanced streaming, 38445 -github.tar, level 0 with dict copy, advanced streaming, 38309 -github.tar, level 0 with dict load, advanced streaming, 38281 +github.tar, level 0, advanced streaming, 38884 +github.tar, level 0 with dict, advanced streaming, 37995 +github.tar, level 0 with dict dms, advanced streaming, 38114 +github.tar, level 0 with dict dds, advanced streaming, 38114 +github.tar, level 0 with dict copy, advanced streaming, 37995 +github.tar, level 0 with dict load, advanced streaming, 37956 github.tar, level 1, advanced streaming, 39550 github.tar, level 1 with dict, advanced streaming, 38502 github.tar, level 1 with dict dms, advanced streaming, 38770 github.tar, level 1 with dict dds, advanced streaming, 38770 github.tar, level 1 with dict copy, advanced streaming, 38502 github.tar, level 1 with dict load, advanced streaming, 38716 -github.tar, level 3, advanced streaming, 39249 -github.tar, level 3 with dict, advanced streaming, 38309 -github.tar, level 3 with dict dms, advanced streaming, 38445 -github.tar, level 3 with dict dds, advanced streaming, 38445 -github.tar, level 3 with dict copy, advanced streaming, 38309 -github.tar, level 3 with dict load, advanced streaming, 38281 -github.tar, level 4, advanced streaming, 39247 -github.tar, level 4 with dict, advanced streaming, 38270 -github.tar, level 4 with dict dms, advanced streaming, 38317 -github.tar, level 4 with dict dds, advanced streaming, 38317 -github.tar, level 4 with dict copy, advanced streaming, 38270 -github.tar, level 4 with dict load, advanced streaming, 38259 +github.tar, level 3, advanced streaming, 38884 +github.tar, level 3 with dict, advanced streaming, 37995 +github.tar, level 3 with dict dms, advanced streaming, 38114 +github.tar, level 3 with dict dds, advanced streaming, 38114 +github.tar, level 3 with dict copy, advanced streaming, 37995 +github.tar, level 3 with dict load, advanced streaming, 37956 +github.tar, level 4, advanced streaming, 38880 +github.tar, level 4 with dict, advanced streaming, 37948 +github.tar, level 4 with dict dms, advanced streaming, 37995 +github.tar, level 4 with dict dds, advanced streaming, 37995 +github.tar, level 4 with dict copy, advanced streaming, 37948 +github.tar, level 4 with dict load, advanced streaming, 37927 github.tar, level 5 row 1, advanced streaming, 39651 github.tar, level 5 row 1 with dict dms, advanced streaming, 39043 github.tar, level 5 row 1 with dict dds, advanced streaming, 39069 @@ -1169,26 +1169,26 @@ github.tar, level 19 with dict dms, advanced github.tar, level 19 with dict dds, advanced streaming, 32565 github.tar, level 19 with dict copy, advanced streaming, 32701 github.tar, level 19 with dict load, advanced streaming, 32428 -github.tar, no source size, advanced streaming, 39246 -github.tar, no source size with dict, advanced streaming, 38442 -github.tar, long distance mode, advanced streaming, 40569 -github.tar, multithreaded, advanced streaming, 39067 -github.tar, multithreaded long distance mode, advanced streaming, 40377 +github.tar, no source size, advanced streaming, 38881 +github.tar, no source size with dict, advanced streaming, 38111 +github.tar, long distance mode, advanced streaming, 40242 +github.tar, multithreaded, advanced streaming, 38884 +github.tar, multithreaded long distance mode, advanced streaming, 40223 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 github.tar, explicit params, advanced streaming, 41385 -github.tar, uncompressed literals, advanced streaming, 41784 +github.tar, uncompressed literals, advanced streaming, 41562 github.tar, uncompressed literals optimal, advanced streaming, 35356 github.tar, huffman literals, advanced streaming, 39226 -github.tar, multithreaded with advanced params, advanced streaming, 41700 +github.tar, multithreaded with advanced params, advanced streaming, 41562 silesia, level -5, old streaming, 6856699 silesia, level -3, old streaming, 6505694 silesia, level -1, old streaming, 6174139 -silesia, level 0, old streaming, 4839173 +silesia, level 0, old streaming, 4835804 silesia, level 1, old streaming, 5305682 -silesia, level 3, old streaming, 4839173 -silesia, level 4, old streaming, 4776074 +silesia, level 3, old streaming, 4835804 +silesia, level 4, old streaming, 4773049 silesia, level 5, old streaming, 4664679 silesia, level 6, old streaming, 4601116 silesia, level 7, old streaming, 4567082 @@ -1196,17 +1196,17 @@ silesia, level 9, old stre silesia, level 13, old streaming, 4490650 silesia, level 16, old streaming, 4358094 silesia, level 19, old streaming, 4265908 -silesia, no source size, old streaming, 4839137 -silesia, uncompressed literals, old streaming, 4839173 +silesia, no source size, old streaming, 4835768 +silesia, uncompressed literals, old streaming, 4835804 silesia, uncompressed literals optimal, old streaming, 4265908 silesia, huffman literals, old streaming, 6174139 silesia.tar, level -5, old streaming, 6857458 silesia.tar, level -3, old streaming, 6508562 silesia.tar, level -1, old streaming, 6178057 -silesia.tar, level 0, old streaming, 4849720 +silesia.tar, level 0, old streaming, 4846783 silesia.tar, level 1, old streaming, 5311452 -silesia.tar, level 3, old streaming, 4849720 -silesia.tar, level 4, old streaming, 4787534 +silesia.tar, level 3, old streaming, 4846783 +silesia.tar, level 4, old streaming, 4785332 silesia.tar, level 5, old streaming, 4664523 silesia.tar, level 6, old streaming, 4599420 silesia.tar, level 7, old streaming, 4565332 @@ -1214,8 +1214,8 @@ silesia.tar, level 9, old stre silesia.tar, level 13, old streaming, 4486652 silesia.tar, level 16, old streaming, 4358029 silesia.tar, level 19, old streaming, 4258228 -silesia.tar, no source size, old streaming, 4849716 -silesia.tar, uncompressed literals, old streaming, 4849720 +silesia.tar, no source size, old streaming, 4846779 +silesia.tar, uncompressed literals, old streaming, 4846783 silesia.tar, uncompressed literals optimal, old streaming, 4258228 silesia.tar, huffman literals, old streaming, 6178057 github, level -5, old streaming, 204407 @@ -1257,14 +1257,14 @@ github.tar, level -3, old stre github.tar, level -3 with dict, old streaming, 44973 github.tar, level -1, old streaming, 42777 github.tar, level -1 with dict, old streaming, 41603 -github.tar, level 0, old streaming, 39249 -github.tar, level 0 with dict, old streaming, 38309 +github.tar, level 0, old streaming, 38884 +github.tar, level 0 with dict, old streaming, 37995 github.tar, level 1, old streaming, 39550 github.tar, level 1 with dict, old streaming, 38502 -github.tar, level 3, old streaming, 39249 -github.tar, level 3 with dict, old streaming, 38309 -github.tar, level 4, old streaming, 39247 -github.tar, level 4 with dict, old streaming, 38270 +github.tar, level 3, old streaming, 38884 +github.tar, level 3 with dict, old streaming, 37995 +github.tar, level 4, old streaming, 38880 +github.tar, level 4 with dict, old streaming, 37948 github.tar, level 5, old streaming, 39651 github.tar, level 5 with dict, old streaming, 39145 github.tar, level 6, old streaming, 39282 @@ -1279,18 +1279,18 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming, 33375 github.tar, level 19, old streaming, 32262 github.tar, level 19 with dict, old streaming, 32701 -github.tar, no source size, old streaming, 39246 -github.tar, no source size with dict, old streaming, 38442 -github.tar, uncompressed literals, old streaming, 39249 +github.tar, no source size, old streaming, 38881 +github.tar, no source size with dict, old streaming, 38111 +github.tar, uncompressed literals, old streaming, 38884 github.tar, uncompressed literals optimal, old streaming, 32262 github.tar, huffman literals, old streaming, 42777 silesia, level -5, old streaming advanced, 6856699 silesia, level -3, old streaming advanced, 6505694 silesia, level -1, old streaming advanced, 6174139 -silesia, level 0, old streaming advanced, 4839173 +silesia, level 0, old streaming advanced, 4835804 silesia, level 1, old streaming advanced, 5305682 -silesia, level 3, old streaming advanced, 4839173 -silesia, level 4, old streaming advanced, 4776074 +silesia, level 3, old streaming advanced, 4835804 +silesia, level 4, old streaming advanced, 4773049 silesia, level 5, old streaming advanced, 4664679 silesia, level 6, old streaming advanced, 4601116 silesia, level 7, old streaming advanced, 4567082 @@ -1298,25 +1298,25 @@ silesia, level 9, old stre silesia, level 13, old streaming advanced, 4490650 silesia, level 16, old streaming advanced, 4358094 silesia, level 19, old streaming advanced, 4265908 -silesia, no source size, old streaming advanced, 4839137 -silesia, long distance mode, old streaming advanced, 4839173 -silesia, multithreaded, old streaming advanced, 4839173 -silesia, multithreaded long distance mode, old streaming advanced, 4839173 +silesia, no source size, old streaming advanced, 4835768 +silesia, long distance mode, old streaming advanced, 4835804 +silesia, multithreaded, old streaming advanced, 4835804 +silesia, multithreaded long distance mode, old streaming advanced, 4835804 silesia, small window log, old streaming advanced, 7110591 silesia, small hash log, old streaming advanced, 6525259 silesia, small chain log, old streaming advanced, 4911577 silesia, explicit params, old streaming advanced, 4792505 -silesia, uncompressed literals, old streaming advanced, 4839173 +silesia, uncompressed literals, old streaming advanced, 4835804 silesia, uncompressed literals optimal, old streaming advanced, 4265908 silesia, huffman literals, old streaming advanced, 6174139 -silesia, multithreaded with advanced params, old streaming advanced, 4839173 +silesia, multithreaded with advanced params, old streaming advanced, 4835804 silesia.tar, level -5, old streaming advanced, 6857458 silesia.tar, level -3, old streaming advanced, 6508562 silesia.tar, level -1, old streaming advanced, 6178057 -silesia.tar, level 0, old streaming advanced, 4849720 +silesia.tar, level 0, old streaming advanced, 4846783 silesia.tar, level 1, old streaming advanced, 5311452 -silesia.tar, level 3, old streaming advanced, 4849720 -silesia.tar, level 4, old streaming advanced, 4787534 +silesia.tar, level 3, old streaming advanced, 4846783 +silesia.tar, level 4, old streaming advanced, 4785332 silesia.tar, level 5, old streaming advanced, 4664523 silesia.tar, level 6, old streaming advanced, 4599420 silesia.tar, level 7, old streaming advanced, 4565332 @@ -1324,18 +1324,18 @@ silesia.tar, level 9, old stre silesia.tar, level 13, old streaming advanced, 4486652 silesia.tar, level 16, old streaming advanced, 4358029 silesia.tar, level 19, old streaming advanced, 4258228 -silesia.tar, no source size, old streaming advanced, 4849716 -silesia.tar, long distance mode, old streaming advanced, 4849720 -silesia.tar, multithreaded, old streaming advanced, 4849720 -silesia.tar, multithreaded long distance mode, old streaming advanced, 4849720 +silesia.tar, no source size, old streaming advanced, 4846779 +silesia.tar, long distance mode, old streaming advanced, 4846783 +silesia.tar, multithreaded, old streaming advanced, 4846783 +silesia.tar, multithreaded long distance mode, old streaming advanced, 4846783 silesia.tar, small window log, old streaming advanced, 7117027 silesia.tar, small hash log, old streaming advanced, 6529503 silesia.tar, small chain log, old streaming advanced, 4915956 silesia.tar, explicit params, old streaming advanced, 4791739 -silesia.tar, uncompressed literals, old streaming advanced, 4849720 +silesia.tar, uncompressed literals, old streaming advanced, 4846783 silesia.tar, uncompressed literals optimal, old streaming advanced, 4258228 silesia.tar, huffman literals, old streaming advanced, 6178057 -silesia.tar, multithreaded with advanced params, old streaming advanced, 4849720 +silesia.tar, multithreaded with advanced params, old streaming advanced, 4846783 github, level -5, old streaming advanced, 213265 github, level -5 with dict, old streaming advanced, 46708 github, level -3, old streaming advanced, 196126 @@ -1383,14 +1383,14 @@ github.tar, level -3, old stre github.tar, level -3 with dict, old streaming advanced, 45211 github.tar, level -1, old streaming advanced, 42777 github.tar, level -1 with dict, old streaming advanced, 41865 -github.tar, level 0, old streaming advanced, 39249 -github.tar, level 0 with dict, old streaming advanced, 38327 +github.tar, level 0, old streaming advanced, 38884 +github.tar, level 0 with dict, old streaming advanced, 38013 github.tar, level 1, old streaming advanced, 39550 github.tar, level 1 with dict, old streaming advanced, 38714 -github.tar, level 3, old streaming advanced, 39249 -github.tar, level 3 with dict, old streaming advanced, 38327 -github.tar, level 4, old streaming advanced, 39247 -github.tar, level 4 with dict, old streaming advanced, 38382 +github.tar, level 3, old streaming advanced, 38884 +github.tar, level 3 with dict, old streaming advanced, 38013 +github.tar, level 4, old streaming advanced, 38880 +github.tar, level 4 with dict, old streaming advanced, 38063 github.tar, level 5, old streaming advanced, 39651 github.tar, level 5 with dict, old streaming advanced, 39018 github.tar, level 6, old streaming advanced, 39282 @@ -1405,19 +1405,19 @@ github.tar, level 16, old stre github.tar, level 16 with dict, old streaming advanced, 38578 github.tar, level 19, old streaming advanced, 32262 github.tar, level 19 with dict, old streaming advanced, 32678 -github.tar, no source size, old streaming advanced, 39246 -github.tar, no source size with dict, old streaming advanced, 38399 -github.tar, long distance mode, old streaming advanced, 39249 -github.tar, multithreaded, old streaming advanced, 39249 -github.tar, multithreaded long distance mode, old streaming advanced, 39249 +github.tar, no source size, old streaming advanced, 38881 +github.tar, no source size with dict, old streaming advanced, 38076 +github.tar, long distance mode, old streaming advanced, 38884 +github.tar, multithreaded, old streaming advanced, 38884 +github.tar, multithreaded long distance mode, old streaming advanced, 38884 github.tar, small window log, old streaming advanced, 199556 github.tar, small hash log, old streaming advanced, 129870 github.tar, small chain log, old streaming advanced, 41669 github.tar, explicit params, old streaming advanced, 41385 -github.tar, uncompressed literals, old streaming advanced, 39249 +github.tar, uncompressed literals, old streaming advanced, 38884 github.tar, uncompressed literals optimal, old streaming advanced, 32262 github.tar, huffman literals, old streaming advanced, 42777 -github.tar, multithreaded with advanced params, old streaming advanced, 39249 +github.tar, multithreaded with advanced params, old streaming advanced, 38884 github, level -5 with dict, old streaming cdict, 45832 github, level -3 with dict, old streaming cdict, 44671 github, level -1 with dict, old streaming cdict, 41825 @@ -1436,10 +1436,10 @@ github, no source size with dict, old stre github.tar, level -5 with dict, old streaming cdict, 51512 github.tar, level -3 with dict, old streaming cdict, 45379 github.tar, level -1 with dict, old streaming cdict, 42084 -github.tar, level 0 with dict, old streaming cdict, 38281 +github.tar, level 0 with dict, old streaming cdict, 37956 github.tar, level 1 with dict, old streaming cdict, 38716 -github.tar, level 3 with dict, old streaming cdict, 38281 -github.tar, level 4 with dict, old streaming cdict, 38259 +github.tar, level 3 with dict, old streaming cdict, 37956 +github.tar, level 4 with dict, old streaming cdict, 37927 github.tar, level 5 with dict, old streaming cdict, 39000 github.tar, level 6 with dict, old streaming cdict, 38647 github.tar, level 7 with dict, old streaming cdict, 37286 @@ -1447,7 +1447,7 @@ github.tar, level 9 with dict, old stre github.tar, level 13 with dict, old streaming cdict, 36010 github.tar, level 16 with dict, old streaming cdict, 39081 github.tar, level 19 with dict, old streaming cdict, 32428 -github.tar, no source size with dict, old streaming cdict, 38442 +github.tar, no source size with dict, old streaming cdict, 38111 github, level -5 with dict, old streaming advanced cdict, 46708 github, level -3 with dict, old streaming advanced cdict, 45476 github, level -1 with dict, old streaming advanced cdict, 42060 @@ -1466,10 +1466,10 @@ github, no source size with dict, old stre github.tar, level -5 with dict, old streaming advanced cdict, 51019 github.tar, level -3 with dict, old streaming advanced cdict, 45149 github.tar, level -1 with dict, old streaming advanced cdict, 41694 -github.tar, level 0 with dict, old streaming advanced cdict, 38327 +github.tar, level 0 with dict, old streaming advanced cdict, 38013 github.tar, level 1 with dict, old streaming advanced cdict, 38513 -github.tar, level 3 with dict, old streaming advanced cdict, 38327 -github.tar, level 4 with dict, old streaming advanced cdict, 38382 +github.tar, level 3 with dict, old streaming advanced cdict, 38013 +github.tar, level 4 with dict, old streaming advanced cdict, 38063 github.tar, level 5 with dict, old streaming advanced cdict, 39018 github.tar, level 6 with dict, old streaming advanced cdict, 38635 github.tar, level 7 with dict, old streaming advanced cdict, 37264 @@ -1477,4 +1477,4 @@ github.tar, level 9 with dict, old stre github.tar, level 13 with dict, old streaming advanced cdict, 35807 github.tar, level 16 with dict, old streaming advanced cdict, 38578 github.tar, level 19 with dict, old streaming advanced cdict, 32678 -github.tar, no source size with dict, old streaming advanced cdict, 38399 +github.tar, no source size with dict, old streaming advanced cdict, 38076 From e557abc8a0380b095b14623ca7c4105a38fdb981 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 24 Oct 2024 15:57:29 -0700 Subject: [PATCH 440/937] new block splitting variant _fromBorders less precise but still suitable for `fast` strategy. --- lib/compress/hist.c | 10 +++++++ lib/compress/hist.h | 7 +++++ lib/compress/zstd_compress.c | 22 ++++----------- lib/compress/zstd_preSplit.c | 53 ++++++++++++++++++++++++++++++++---- 4 files changed, 71 insertions(+), 21 deletions(-) diff --git a/lib/compress/hist.c b/lib/compress/hist.c index e2fb431f0..4ccf9a90a 100644 --- a/lib/compress/hist.c +++ b/lib/compress/hist.c @@ -26,6 +26,16 @@ unsigned HIST_isError(size_t code) { return ERR_isError(code); } /*-************************************************************** * Histogram functions ****************************************************************/ +void HIST_add(unsigned* count, const void* src, size_t srcSize) +{ + const BYTE* ip = (const BYTE*)src; + const BYTE* const end = ip + srcSize; + + while (ip= ZSTD_btopt) - return ZSTD_splitBlock(src, blockSizeMax, 3, cctx->tmpWorkspace, cctx->tmpWkspSize); - if (strat >= ZSTD_lazy2) - return ZSTD_splitBlock(src, blockSizeMax, 2, cctx->tmpWorkspace, cctx->tmpWkspSize); - if (strat >= ZSTD_greedy) - return ZSTD_splitBlock(src, blockSizeMax, 1, cctx->tmpWorkspace, cctx->tmpWkspSize); - if (strat >= ZSTD_dfast) - return ZSTD_splitBlock(src, blockSizeMax, 0, cctx->tmpWorkspace, cctx->tmpWkspSize); - /* blind split strategy - * heuristic value, tested as being "generally better". - * no cpu cost, but can over-split homegeneous data. - */ - return 92 KB; + * select a variant among multiple gradual speed/accuracy tradeoffs */ + return ZSTD_splitBlock(src, blockSizeMax, splitLevels[strat], cctx->tmpWorkspace, cctx->tmpWkspSize); } /*! ZSTD_compress_frameChunk() : diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index 3f6edb612..d25773950 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -12,6 +12,7 @@ #include "../common/mem.h" /* S64 */ #include "../common/zstd_deps.h" /* ZSTD_memset */ #include "../common/zstd_internal.h" /* ZSTD_STATIC_ASSERT */ +#include "hist.h" /* HIST_add */ #include "zstd_preSplit.h" @@ -77,10 +78,10 @@ typedef void (*RecordEvents_f)(Fingerprint* fp, const void* src, size_t srcSize) #define FP_RECORD(_rate) ZSTD_recordFingerprint_##_rate -#define ZSTD_GEN_RECORD_FINGERPRINT(_rate, _hSize) \ +#define ZSTD_GEN_RECORD_FINGERPRINT(_rate, _hSize) \ static void FP_RECORD(_rate)(Fingerprint* fp, const void* src, size_t srcSize) \ - { \ - recordFingerprint_generic(fp, src, srcSize, _rate, _hSize); \ + { \ + recordFingerprint_generic(fp, src, srcSize, _rate, _hSize); \ } ZSTD_GEN_RECORD_FINGERPRINT(1, 10) @@ -185,10 +186,52 @@ static size_t ZSTD_splitBlock_byChunks(const void* blockStart, size_t blockSize, (void)flushEvents; (void)removeEvents; } +/* ZSTD_splitBlock_fromBorders(): very fast strategy : + * compare fingerprint from beginning and end of the block, + * derive from their difference if it's preferable to split in the middle, + * repeat the process a second time, for finer grained decision. + * 3 times did not brought improvements, so I stopped at 2. + * Benefits are good enough for a cheap heuristic. + * More accurate splitting saves more, but speed impact is also more perceptible. + * For better accuracy, use more elaborate variant *_byChunks. + */ +static size_t ZSTD_splitBlock_fromBorders(const void* blockStart, size_t blockSize, + void* workspace, size_t wkspSize) +{ +#define SEGMENT_SIZE 512 + FPStats* const fpstats = (FPStats*)workspace; + Fingerprint* middleEvents = (Fingerprint*)(void*)((char*)workspace + 512 * sizeof(unsigned)); + assert(blockSize == (128 << 10)); + assert(workspace != NULL); + assert((size_t)workspace % ZSTD_ALIGNOF(FPStats) == 0); + ZSTD_STATIC_ASSERT(ZSTD_SLIPBLOCK_WORKSPACESIZE >= sizeof(FPStats)); + assert(wkspSize >= sizeof(FPStats)); (void)wkspSize; + + initStats(fpstats); + HIST_add(fpstats->pastEvents.events, blockStart, SEGMENT_SIZE); + HIST_add(fpstats->newEvents.events, (const char*)blockStart + blockSize - SEGMENT_SIZE, SEGMENT_SIZE); + fpstats->pastEvents.nbEvents = fpstats->newEvents.nbEvents = SEGMENT_SIZE; + if (!compareFingerprints(&fpstats->pastEvents, &fpstats->newEvents, 0, 8)) + return blockSize; + + HIST_add(middleEvents->events, (const char*)blockStart + blockSize/2 - SEGMENT_SIZE/2, SEGMENT_SIZE); + middleEvents->nbEvents = SEGMENT_SIZE; + { 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) + return 64 KB; + return (distFromBegin > distFromEnd) ? 32 KB : 96 KB; + } +} + size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, int level, void* workspace, size_t wkspSize) { - assert(0<=level && level<=3); - return ZSTD_splitBlock_byChunks(blockStart, blockSize, level, workspace, wkspSize); + assert(0<=level && level<=4); + if (level == 0) + return ZSTD_splitBlock_fromBorders(blockStart, blockSize, workspace, wkspSize); + /* level >= 1*/ + return ZSTD_splitBlock_byChunks(blockStart, blockSize, level-1, workspace, wkspSize); } From 5b4ce643f03a2cc2c6f4e10dca3332c058f165d5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 25 Oct 2024 16:25:02 -0700 Subject: [PATCH 441/937] update ZSTD_splitBlock() documentation --- lib/compress/zstd_preSplit.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h index 07d7d4ef5..d606a52b5 100644 --- a/lib/compress/zstd_preSplit.h +++ b/lib/compress/zstd_preSplit.h @@ -19,14 +19,16 @@ extern "C" { #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208 -/* @level must be a value between 0 and 3. - * higher levels spend more energy to find block boundaries - * @workspace must be aligned on 8-bytes boundaries +/* ZSTD_splitBlock(): + * @level must be a value between 0 and 4. + * higher levels spend more energy to detect block boundaries. + * @workspace must be aligned for size_t. * @wkspSize must be at least >= ZSTD_SLIPBLOCK_WORKSPACESIZE - * note2: - * for the time being, this function only accepts full 128 KB blocks, - * therefore @blockSizeMax must be == 128 KB. - * This could be extended to smaller sizes in the future. + * note: + * For the time being, this function only accepts full 128 KB blocks. + * Therefore, @blockSize must be == 128 KB. + * While this could be extended to smaller sizes in the future, + * it is not yet clear if this would be useful. TBD. */ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, int level, From 4e1a87976f5286b60748aece532e05f4515721c0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 25 Oct 2024 16:33:00 -0700 Subject: [PATCH 442/937] update regression results --- tests/regression/results.csv | 298 +++++++++++++++++------------------ 1 file changed, 149 insertions(+), 149 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 0b1a79b85..94d113578 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -1,9 +1,9 @@ Data, Config, Method, Total compressed size -silesia.tar, level -5, compress simple, 6860782 -silesia.tar, level -3, compress simple, 6507448 -silesia.tar, level -1, compress simple, 6175582 +silesia.tar, level -5, compress simple, 6858730 +silesia.tar, level -3, compress simple, 6502944 +silesia.tar, level -1, compress simple, 6175652 silesia.tar, level 0, compress simple, 4829268 -silesia.tar, level 1, compress simple, 5316794 +silesia.tar, level 1, compress simple, 5307443 silesia.tar, level 3, compress simple, 4829268 silesia.tar, level 4, compress simple, 4767074 silesia.tar, level 5, compress simple, 4662847 @@ -15,12 +15,12 @@ silesia.tar, level 16, compress silesia.tar, level 19, compress simple, 4257629 silesia.tar, uncompressed literals, compress simple, 4829268 silesia.tar, uncompressed literals optimal, compress simple, 4257629 -silesia.tar, huffman literals, compress simple, 6175582 -github.tar, level -5, compress simple, 52320 -github.tar, level -3, compress simple, 45823 -github.tar, level -1, compress simple, 42740 +silesia.tar, huffman literals, compress simple, 6175652 +github.tar, level -5, compress simple, 52173 +github.tar, level -3, compress simple, 45783 +github.tar, level -1, compress simple, 42606 github.tar, level 0, compress simple, 38884 -github.tar, level 1, compress simple, 39444 +github.tar, level 1, compress simple, 39200 github.tar, level 3, compress simple, 38884 github.tar, level 4, compress simple, 38880 github.tar, level 5, compress simple, 39651 @@ -32,12 +32,12 @@ github.tar, level 16, compress github.tar, level 19, compress simple, 32262 github.tar, uncompressed literals, compress simple, 38884 github.tar, uncompressed literals optimal, compress simple, 32262 -github.tar, huffman literals, compress simple, 42740 -silesia, level -5, compress cctx, 6857776 -silesia, level -3, compress cctx, 6504756 -silesia, level -1, compress cctx, 6174127 +github.tar, huffman literals, compress simple, 42606 +silesia, level -5, compress cctx, 6854688 +silesia, level -3, compress cctx, 6502839 +silesia, level -1, compress cctx, 6173625 silesia, level 0, compress cctx, 4832054 -silesia, level 1, compress cctx, 5306931 +silesia, level 1, compress cctx, 5304296 silesia, level 3, compress cctx, 4832054 silesia, level 4, compress cctx, 4768799 silesia, level 5, compress cctx, 4663718 @@ -56,7 +56,7 @@ silesia, small chain log, compress silesia, explicit params, compress cctx, 4789676 silesia, uncompressed literals, compress cctx, 4832054 silesia, uncompressed literals optimal, compress cctx, 4265851 -silesia, huffman literals, compress cctx, 6174127 +silesia, huffman literals, compress cctx, 6173625 silesia, multithreaded with advanced params, compress cctx, 4832054 github, level -5, compress cctx, 204407 github, level -5 with dict, compress cctx, 47581 @@ -97,11 +97,11 @@ github, uncompressed literals, compress github, uncompressed literals optimal, compress cctx, 132879 github, huffman literals, compress cctx, 175468 github, multithreaded with advanced params, compress cctx, 141069 -silesia, level -5, zstdcli, 6856073 -silesia, level -3, zstdcli, 6505580 -silesia, level -1, zstdcli, 6172649 +silesia, level -5, zstdcli, 6854509 +silesia, level -3, zstdcli, 6502336 +silesia, level -1, zstdcli, 6171366 silesia, level 0, zstdcli, 4833113 -silesia, level 1, zstdcli, 5306179 +silesia, level 1, zstdcli, 5302161 silesia, level 3, zstdcli, 4833113 silesia, level 4, zstdcli, 4770061 silesia, level 5, zstdcli, 4663332 @@ -120,13 +120,13 @@ silesia, small chain log, zstdcli, silesia, explicit params, zstdcli, 4790803 silesia, uncompressed literals, zstdcli, 5118235 silesia, uncompressed literals optimal, zstdcli, 4316761 -silesia, huffman literals, zstdcli, 5320793 +silesia, huffman literals, zstdcli, 5316827 silesia, multithreaded with advanced params, zstdcli, 5118235 -silesia.tar, level -5, zstdcli, 6860173 -silesia.tar, level -3, zstdcli, 6507196 -silesia.tar, level -1, zstdcli, 6177719 +silesia.tar, level -5, zstdcli, 6859945 +silesia.tar, level -3, zstdcli, 6504296 +silesia.tar, level -1, zstdcli, 6176520 silesia.tar, level 0, zstdcli, 4836004 -silesia.tar, level 1, zstdcli, 5313917 +silesia.tar, level 1, zstdcli, 5309074 silesia.tar, level 3, zstdcli, 4836004 silesia.tar, level 4, zstdcli, 4774061 silesia.tar, level 5, zstdcli, 4667310 @@ -146,7 +146,7 @@ silesia.tar, small chain log, zstdcli, silesia.tar, explicit params, zstdcli, 4808370 silesia.tar, uncompressed literals, zstdcli, 5116583 silesia.tar, uncompressed literals optimal, zstdcli, 4306520 -silesia.tar, huffman literals, zstdcli, 5326463 +silesia.tar, huffman literals, zstdcli, 5324019 silesia.tar, multithreaded with advanced params, zstdcli, 5116583 github, level -5, zstdcli, 206407 github, level -5 with dict, zstdcli, 47832 @@ -187,16 +187,16 @@ github, uncompressed literals, zstdcli, github, uncompressed literals optimal, zstdcli, 154667 github, huffman literals, zstdcli, 144365 github, multithreaded with advanced params, zstdcli, 167909 -github.tar, level -5, zstdcli, 52308 -github.tar, level -5 with dict, zstdcli, 51318 -github.tar, level -3, zstdcli, 45815 -github.tar, level -3 with dict, zstdcli, 44883 -github.tar, level -1, zstdcli, 42688 -github.tar, level -1 with dict, zstdcli, 41510 +github.tar, level -5, zstdcli, 52231 +github.tar, level -5 with dict, zstdcli, 51249 +github.tar, level -3, zstdcli, 45778 +github.tar, level -3 with dict, zstdcli, 44847 +github.tar, level -1, zstdcli, 42680 +github.tar, level -1 with dict, zstdcli, 41486 github.tar, level 0, zstdcli, 38888 github.tar, level 0 with dict, zstdcli, 37999 -github.tar, level 1, zstdcli, 39404 -github.tar, level 1 with dict, zstdcli, 38320 +github.tar, level 1, zstdcli, 39340 +github.tar, level 1 with dict, zstdcli, 38230 github.tar, level 3, zstdcli, 38888 github.tar, level 3 with dict, zstdcli, 37999 github.tar, level 4, zstdcli, 38884 @@ -226,13 +226,13 @@ github.tar, small chain log, zstdcli, github.tar, explicit params, zstdcli, 41385 github.tar, uncompressed literals, zstdcli, 41566 github.tar, uncompressed literals optimal, zstdcli, 35360 -github.tar, huffman literals, zstdcli, 39046 +github.tar, huffman literals, zstdcli, 38989 github.tar, multithreaded with advanced params, zstdcli, 41566 -silesia, level -5, advanced one pass, 6857776 -silesia, level -3, advanced one pass, 6504756 -silesia, level -1, advanced one pass, 6174127 +silesia, level -5, advanced one pass, 6854688 +silesia, level -3, advanced one pass, 6502839 +silesia, level -1, advanced one pass, 6173625 silesia, level 0, advanced one pass, 4832054 -silesia, level 1, advanced one pass, 5306931 +silesia, level 1, advanced one pass, 5304296 silesia, level 3, advanced one pass, 4832054 silesia, level 4, advanced one pass, 4768799 silesia, level 5 row 1, advanced one pass, 4663718 @@ -260,13 +260,13 @@ silesia, small chain log, advanced silesia, explicit params, advanced one pass, 4791219 silesia, uncompressed literals, advanced one pass, 5117526 silesia, uncompressed literals optimal, advanced one pass, 4316644 -silesia, huffman literals, advanced one pass, 5321686 +silesia, huffman literals, advanced one pass, 5319104 silesia, multithreaded with advanced params, advanced one pass, 5118187 -silesia.tar, level -5, advanced one pass, 6860782 -silesia.tar, level -3, advanced one pass, 6507448 -silesia.tar, level -1, advanced one pass, 6175582 +silesia.tar, level -5, advanced one pass, 6858730 +silesia.tar, level -3, advanced one pass, 6502944 +silesia.tar, level -1, advanced one pass, 6175652 silesia.tar, level 0, advanced one pass, 4829268 -silesia.tar, level 1, advanced one pass, 5316794 +silesia.tar, level 1, advanced one pass, 5307443 silesia.tar, level 3, advanced one pass, 4829268 silesia.tar, level 4, advanced one pass, 4767074 silesia.tar, level 5 row 1, advanced one pass, 4662847 @@ -294,7 +294,7 @@ silesia.tar, small chain log, advanced silesia.tar, explicit params, advanced one pass, 4790421 silesia.tar, uncompressed literals, advanced one pass, 5114702 silesia.tar, uncompressed literals optimal, advanced one pass, 4306289 -silesia.tar, huffman literals, advanced one pass, 5331382 +silesia.tar, huffman literals, advanced one pass, 5323421 silesia.tar, multithreaded with advanced params, advanced one pass, 5116579 github, level -5, advanced one pass, 204407 github, level -5 with dict, advanced one pass, 45832 @@ -421,24 +421,24 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced one pass, 152667 github, huffman literals, advanced one pass, 142365 github, multithreaded with advanced params, advanced one pass, 165909 -github.tar, level -5, advanced one pass, 52320 -github.tar, level -5 with dict, advanced one pass, 51321 -github.tar, level -3, advanced one pass, 45823 -github.tar, level -3 with dict, advanced one pass, 44882 -github.tar, level -1, advanced one pass, 42740 -github.tar, level -1 with dict, advanced one pass, 41506 +github.tar, level -5, advanced one pass, 52173 +github.tar, level -5 with dict, advanced one pass, 51161 +github.tar, level -3, advanced one pass, 45783 +github.tar, level -3 with dict, advanced one pass, 44768 +github.tar, level -1, advanced one pass, 42606 +github.tar, level -1 with dict, advanced one pass, 41397 github.tar, level 0, advanced one pass, 38884 github.tar, level 0 with dict, advanced one pass, 37995 github.tar, level 0 with dict dms, advanced one pass, 38114 github.tar, level 0 with dict dds, advanced one pass, 38114 github.tar, level 0 with dict copy, advanced one pass, 37995 github.tar, level 0 with dict load, advanced one pass, 37956 -github.tar, level 1, advanced one pass, 39444 -github.tar, level 1 with dict, advanced one pass, 38338 -github.tar, level 1 with dict dms, advanced one pass, 38641 -github.tar, level 1 with dict dds, advanced one pass, 38641 -github.tar, level 1 with dict copy, advanced one pass, 38338 -github.tar, level 1 with dict load, advanced one pass, 38592 +github.tar, level 1, advanced one pass, 39200 +github.tar, level 1 with dict, advanced one pass, 38189 +github.tar, level 1 with dict dms, advanced one pass, 38398 +github.tar, level 1 with dict dds, advanced one pass, 38398 +github.tar, level 1 with dict copy, advanced one pass, 38189 +github.tar, level 1 with dict load, advanced one pass, 38393 github.tar, level 3, advanced one pass, 38884 github.tar, level 3 with dict, advanced one pass, 37995 github.tar, level 3 with dict dms, advanced one pass, 38114 @@ -544,13 +544,13 @@ github.tar, small chain log, advanced github.tar, explicit params, advanced one pass, 41385 github.tar, uncompressed literals, advanced one pass, 41562 github.tar, uncompressed literals optimal, advanced one pass, 35356 -github.tar, huffman literals, advanced one pass, 39099 +github.tar, huffman literals, advanced one pass, 38921 github.tar, multithreaded with advanced params, advanced one pass, 41562 -silesia, level -5, advanced one pass small out, 6857776 -silesia, level -3, advanced one pass small out, 6504756 -silesia, level -1, advanced one pass small out, 6174127 +silesia, level -5, advanced one pass small out, 6854688 +silesia, level -3, advanced one pass small out, 6502839 +silesia, level -1, advanced one pass small out, 6173625 silesia, level 0, advanced one pass small out, 4832054 -silesia, level 1, advanced one pass small out, 5306931 +silesia, level 1, advanced one pass small out, 5304296 silesia, level 3, advanced one pass small out, 4832054 silesia, level 4, advanced one pass small out, 4768799 silesia, level 5 row 1, advanced one pass small out, 4663718 @@ -578,13 +578,13 @@ silesia, small chain log, advanced silesia, explicit params, advanced one pass small out, 4791219 silesia, uncompressed literals, advanced one pass small out, 5117526 silesia, uncompressed literals optimal, advanced one pass small out, 4316644 -silesia, huffman literals, advanced one pass small out, 5321686 +silesia, huffman literals, advanced one pass small out, 5319104 silesia, multithreaded with advanced params, advanced one pass small out, 5118187 -silesia.tar, level -5, advanced one pass small out, 6860782 -silesia.tar, level -3, advanced one pass small out, 6507448 -silesia.tar, level -1, advanced one pass small out, 6175582 +silesia.tar, level -5, advanced one pass small out, 6858730 +silesia.tar, level -3, advanced one pass small out, 6502944 +silesia.tar, level -1, advanced one pass small out, 6175652 silesia.tar, level 0, advanced one pass small out, 4829268 -silesia.tar, level 1, advanced one pass small out, 5316794 +silesia.tar, level 1, advanced one pass small out, 5307443 silesia.tar, level 3, advanced one pass small out, 4829268 silesia.tar, level 4, advanced one pass small out, 4767074 silesia.tar, level 5 row 1, advanced one pass small out, 4662847 @@ -612,7 +612,7 @@ silesia.tar, small chain log, advanced silesia.tar, explicit params, advanced one pass small out, 4790421 silesia.tar, uncompressed literals, advanced one pass small out, 5114702 silesia.tar, uncompressed literals optimal, advanced one pass small out, 4306289 -silesia.tar, huffman literals, advanced one pass small out, 5331382 +silesia.tar, huffman literals, advanced one pass small out, 5323421 silesia.tar, multithreaded with advanced params, advanced one pass small out, 5116579 github, level -5, advanced one pass small out, 204407 github, level -5 with dict, advanced one pass small out, 45832 @@ -739,24 +739,24 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced one pass small out, 152667 github, huffman literals, advanced one pass small out, 142365 github, multithreaded with advanced params, advanced one pass small out, 165909 -github.tar, level -5, advanced one pass small out, 52320 -github.tar, level -5 with dict, advanced one pass small out, 51321 -github.tar, level -3, advanced one pass small out, 45823 -github.tar, level -3 with dict, advanced one pass small out, 44882 -github.tar, level -1, advanced one pass small out, 42740 -github.tar, level -1 with dict, advanced one pass small out, 41506 +github.tar, level -5, advanced one pass small out, 52173 +github.tar, level -5 with dict, advanced one pass small out, 51161 +github.tar, level -3, advanced one pass small out, 45783 +github.tar, level -3 with dict, advanced one pass small out, 44768 +github.tar, level -1, advanced one pass small out, 42606 +github.tar, level -1 with dict, advanced one pass small out, 41397 github.tar, level 0, advanced one pass small out, 38884 github.tar, level 0 with dict, advanced one pass small out, 37995 github.tar, level 0 with dict dms, advanced one pass small out, 38114 github.tar, level 0 with dict dds, advanced one pass small out, 38114 github.tar, level 0 with dict copy, advanced one pass small out, 37995 github.tar, level 0 with dict load, advanced one pass small out, 37956 -github.tar, level 1, advanced one pass small out, 39444 -github.tar, level 1 with dict, advanced one pass small out, 38338 -github.tar, level 1 with dict dms, advanced one pass small out, 38641 -github.tar, level 1 with dict dds, advanced one pass small out, 38641 -github.tar, level 1 with dict copy, advanced one pass small out, 38338 -github.tar, level 1 with dict load, advanced one pass small out, 38592 +github.tar, level 1, advanced one pass small out, 39200 +github.tar, level 1 with dict, advanced one pass small out, 38189 +github.tar, level 1 with dict dms, advanced one pass small out, 38398 +github.tar, level 1 with dict dds, advanced one pass small out, 38398 +github.tar, level 1 with dict copy, advanced one pass small out, 38189 +github.tar, level 1 with dict load, advanced one pass small out, 38393 github.tar, level 3, advanced one pass small out, 38884 github.tar, level 3 with dict, advanced one pass small out, 37995 github.tar, level 3 with dict dms, advanced one pass small out, 38114 @@ -862,13 +862,13 @@ github.tar, small chain log, advanced github.tar, explicit params, advanced one pass small out, 41385 github.tar, uncompressed literals, advanced one pass small out, 41562 github.tar, uncompressed literals optimal, advanced one pass small out, 35356 -github.tar, huffman literals, advanced one pass small out, 39099 +github.tar, huffman literals, advanced one pass small out, 38921 github.tar, multithreaded with advanced params, advanced one pass small out, 41562 -silesia, level -5, advanced streaming, 6856699 -silesia, level -3, advanced streaming, 6505694 -silesia, level -1, advanced streaming, 6174139 +silesia, level -5, advanced streaming, 6853462 +silesia, level -3, advanced streaming, 6502349 +silesia, level -1, advanced streaming, 6172125 silesia, level 0, advanced streaming, 4835804 -silesia, level 1, advanced streaming, 5305682 +silesia, level 1, advanced streaming, 5301644 silesia, level 3, advanced streaming, 4835804 silesia, level 4, advanced streaming, 4773049 silesia, level 5 row 1, advanced streaming, 4664679 @@ -896,13 +896,13 @@ silesia, small chain log, advanced silesia, explicit params, advanced streaming, 4792505 silesia, uncompressed literals, advanced streaming, 5116404 silesia, uncompressed literals optimal, advanced streaming, 4316533 -silesia, huffman literals, advanced streaming, 5321812 +silesia, huffman literals, advanced streaming, 5317620 silesia, multithreaded with advanced params, advanced streaming, 5118187 -silesia.tar, level -5, advanced streaming, 6857458 -silesia.tar, level -3, advanced streaming, 6508562 -silesia.tar, level -1, advanced streaming, 6178057 +silesia.tar, level -5, advanced streaming, 6853184 +silesia.tar, level -3, advanced streaming, 6503455 +silesia.tar, level -1, advanced streaming, 6175761 silesia.tar, level 0, advanced streaming, 4846783 -silesia.tar, level 1, advanced streaming, 5311452 +silesia.tar, level 1, advanced streaming, 5306719 silesia.tar, level 3, advanced streaming, 4846783 silesia.tar, level 4, advanced streaming, 4785332 silesia.tar, level 5 row 1, advanced streaming, 4664523 @@ -930,7 +930,7 @@ silesia.tar, small chain log, advanced silesia.tar, explicit params, advanced streaming, 4791739 silesia.tar, uncompressed literals, advanced streaming, 5123274 silesia.tar, uncompressed literals optimal, advanced streaming, 4306968 -silesia.tar, huffman literals, advanced streaming, 5326278 +silesia.tar, huffman literals, advanced streaming, 5323245 silesia.tar, multithreaded with advanced params, advanced streaming, 5116579 github, level -5, advanced streaming, 204407 github, level -5 with dict, advanced streaming, 45832 @@ -1057,24 +1057,24 @@ github, uncompressed literals, advanced github, uncompressed literals optimal, advanced streaming, 152667 github, huffman literals, advanced streaming, 142365 github, multithreaded with advanced params, advanced streaming, 165909 -github.tar, level -5, advanced streaming, 52384 -github.tar, level -5 with dict, advanced streaming, 51420 -github.tar, level -3, advanced streaming, 45907 -github.tar, level -3 with dict, advanced streaming, 44973 -github.tar, level -1, advanced streaming, 42777 -github.tar, level -1 with dict, advanced streaming, 41603 +github.tar, level -5, advanced streaming, 52273 +github.tar, level -5 with dict, advanced streaming, 51297 +github.tar, level -3, advanced streaming, 45783 +github.tar, level -3 with dict, advanced streaming, 44853 +github.tar, level -1, advanced streaming, 42687 +github.tar, level -1 with dict, advanced streaming, 41486 github.tar, level 0, advanced streaming, 38884 github.tar, level 0 with dict, advanced streaming, 37995 github.tar, level 0 with dict dms, advanced streaming, 38114 github.tar, level 0 with dict dds, advanced streaming, 38114 github.tar, level 0 with dict copy, advanced streaming, 37995 github.tar, level 0 with dict load, advanced streaming, 37956 -github.tar, level 1, advanced streaming, 39550 -github.tar, level 1 with dict, advanced streaming, 38502 -github.tar, level 1 with dict dms, advanced streaming, 38770 -github.tar, level 1 with dict dds, advanced streaming, 38770 -github.tar, level 1 with dict copy, advanced streaming, 38502 -github.tar, level 1 with dict load, advanced streaming, 38716 +github.tar, level 1, advanced streaming, 39346 +github.tar, level 1 with dict, advanced streaming, 38251 +github.tar, level 1 with dict dms, advanced streaming, 38557 +github.tar, level 1 with dict dds, advanced streaming, 38557 +github.tar, level 1 with dict copy, advanced streaming, 38251 +github.tar, level 1 with dict load, advanced streaming, 38503 github.tar, level 3, advanced streaming, 38884 github.tar, level 3 with dict, advanced streaming, 37995 github.tar, level 3 with dict dms, advanced streaming, 38114 @@ -1180,13 +1180,13 @@ github.tar, small chain log, advanced github.tar, explicit params, advanced streaming, 41385 github.tar, uncompressed literals, advanced streaming, 41562 github.tar, uncompressed literals optimal, advanced streaming, 35356 -github.tar, huffman literals, advanced streaming, 39226 +github.tar, huffman literals, advanced streaming, 38998 github.tar, multithreaded with advanced params, advanced streaming, 41562 -silesia, level -5, old streaming, 6856699 -silesia, level -3, old streaming, 6505694 -silesia, level -1, old streaming, 6174139 +silesia, level -5, old streaming, 6853462 +silesia, level -3, old streaming, 6502349 +silesia, level -1, old streaming, 6172125 silesia, level 0, old streaming, 4835804 -silesia, level 1, old streaming, 5305682 +silesia, level 1, old streaming, 5301644 silesia, level 3, old streaming, 4835804 silesia, level 4, old streaming, 4773049 silesia, level 5, old streaming, 4664679 @@ -1199,12 +1199,12 @@ silesia, level 19, old stre silesia, no source size, old streaming, 4835768 silesia, uncompressed literals, old streaming, 4835804 silesia, uncompressed literals optimal, old streaming, 4265908 -silesia, huffman literals, old streaming, 6174139 -silesia.tar, level -5, old streaming, 6857458 -silesia.tar, level -3, old streaming, 6508562 -silesia.tar, level -1, old streaming, 6178057 +silesia, huffman literals, old streaming, 6172125 +silesia.tar, level -5, old streaming, 6853184 +silesia.tar, level -3, old streaming, 6503455 +silesia.tar, level -1, old streaming, 6175761 silesia.tar, level 0, old streaming, 4846783 -silesia.tar, level 1, old streaming, 5311452 +silesia.tar, level 1, old streaming, 5306719 silesia.tar, level 3, old streaming, 4846783 silesia.tar, level 4, old streaming, 4785332 silesia.tar, level 5, old streaming, 4664523 @@ -1217,7 +1217,7 @@ silesia.tar, level 19, old stre silesia.tar, no source size, old streaming, 4846779 silesia.tar, uncompressed literals, old streaming, 4846783 silesia.tar, uncompressed literals optimal, old streaming, 4258228 -silesia.tar, huffman literals, old streaming, 6178057 +silesia.tar, huffman literals, old streaming, 6175761 github, level -5, old streaming, 204407 github, level -5 with dict, old streaming, 45832 github, level -3, old streaming, 193253 @@ -1251,16 +1251,16 @@ github, no source size with dict, old stre github, uncompressed literals, old streaming, 136331 github, uncompressed literals optimal, old streaming, 132879 github, huffman literals, old streaming, 175468 -github.tar, level -5, old streaming, 52384 -github.tar, level -5 with dict, old streaming, 51420 -github.tar, level -3, old streaming, 45907 -github.tar, level -3 with dict, old streaming, 44973 -github.tar, level -1, old streaming, 42777 -github.tar, level -1 with dict, old streaming, 41603 +github.tar, level -5, old streaming, 52273 +github.tar, level -5 with dict, old streaming, 51297 +github.tar, level -3, old streaming, 45783 +github.tar, level -3 with dict, old streaming, 44853 +github.tar, level -1, old streaming, 42687 +github.tar, level -1 with dict, old streaming, 41486 github.tar, level 0, old streaming, 38884 github.tar, level 0 with dict, old streaming, 37995 -github.tar, level 1, old streaming, 39550 -github.tar, level 1 with dict, old streaming, 38502 +github.tar, level 1, old streaming, 39346 +github.tar, level 1 with dict, old streaming, 38251 github.tar, level 3, old streaming, 38884 github.tar, level 3 with dict, old streaming, 37995 github.tar, level 4, old streaming, 38880 @@ -1283,12 +1283,12 @@ github.tar, no source size, old stre github.tar, no source size with dict, old streaming, 38111 github.tar, uncompressed literals, old streaming, 38884 github.tar, uncompressed literals optimal, old streaming, 32262 -github.tar, huffman literals, old streaming, 42777 -silesia, level -5, old streaming advanced, 6856699 -silesia, level -3, old streaming advanced, 6505694 -silesia, level -1, old streaming advanced, 6174139 +github.tar, huffman literals, old streaming, 42687 +silesia, level -5, old streaming advanced, 6853462 +silesia, level -3, old streaming advanced, 6502349 +silesia, level -1, old streaming advanced, 6172125 silesia, level 0, old streaming advanced, 4835804 -silesia, level 1, old streaming advanced, 5305682 +silesia, level 1, old streaming advanced, 5301644 silesia, level 3, old streaming advanced, 4835804 silesia, level 4, old streaming advanced, 4773049 silesia, level 5, old streaming advanced, 4664679 @@ -1308,13 +1308,13 @@ silesia, small chain log, old stre silesia, explicit params, old streaming advanced, 4792505 silesia, uncompressed literals, old streaming advanced, 4835804 silesia, uncompressed literals optimal, old streaming advanced, 4265908 -silesia, huffman literals, old streaming advanced, 6174139 +silesia, huffman literals, old streaming advanced, 6172125 silesia, multithreaded with advanced params, old streaming advanced, 4835804 -silesia.tar, level -5, old streaming advanced, 6857458 -silesia.tar, level -3, old streaming advanced, 6508562 -silesia.tar, level -1, old streaming advanced, 6178057 +silesia.tar, level -5, old streaming advanced, 6853184 +silesia.tar, level -3, old streaming advanced, 6503455 +silesia.tar, level -1, old streaming advanced, 6175761 silesia.tar, level 0, old streaming advanced, 4846783 -silesia.tar, level 1, old streaming advanced, 5311452 +silesia.tar, level 1, old streaming advanced, 5306719 silesia.tar, level 3, old streaming advanced, 4846783 silesia.tar, level 4, old streaming advanced, 4785332 silesia.tar, level 5, old streaming advanced, 4664523 @@ -1334,7 +1334,7 @@ silesia.tar, small chain log, old stre silesia.tar, explicit params, old streaming advanced, 4791739 silesia.tar, uncompressed literals, old streaming advanced, 4846783 silesia.tar, uncompressed literals optimal, old streaming advanced, 4258228 -silesia.tar, huffman literals, old streaming advanced, 6178057 +silesia.tar, huffman literals, old streaming advanced, 6175761 silesia.tar, multithreaded with advanced params, old streaming advanced, 4846783 github, level -5, old streaming advanced, 213265 github, level -5 with dict, old streaming advanced, 46708 @@ -1377,16 +1377,16 @@ github, uncompressed literals, old stre github, uncompressed literals optimal, old streaming advanced, 132879 github, huffman literals, old streaming advanced, 181107 github, multithreaded with advanced params, old streaming advanced, 141101 -github.tar, level -5, old streaming advanced, 52384 -github.tar, level -5 with dict, old streaming advanced, 51359 -github.tar, level -3, old streaming advanced, 45907 -github.tar, level -3 with dict, old streaming advanced, 45211 -github.tar, level -1, old streaming advanced, 42777 -github.tar, level -1 with dict, old streaming advanced, 41865 +github.tar, level -5, old streaming advanced, 52273 +github.tar, level -5 with dict, old streaming advanced, 51249 +github.tar, level -3, old streaming advanced, 45783 +github.tar, level -3 with dict, old streaming advanced, 45093 +github.tar, level -1, old streaming advanced, 42687 +github.tar, level -1 with dict, old streaming advanced, 41762 github.tar, level 0, old streaming advanced, 38884 github.tar, level 0 with dict, old streaming advanced, 38013 -github.tar, level 1, old streaming advanced, 39550 -github.tar, level 1 with dict, old streaming advanced, 38714 +github.tar, level 1, old streaming advanced, 39346 +github.tar, level 1 with dict, old streaming advanced, 38507 github.tar, level 3, old streaming advanced, 38884 github.tar, level 3 with dict, old streaming advanced, 38013 github.tar, level 4, old streaming advanced, 38880 @@ -1416,7 +1416,7 @@ github.tar, small chain log, old stre github.tar, explicit params, old streaming advanced, 41385 github.tar, uncompressed literals, old streaming advanced, 38884 github.tar, uncompressed literals optimal, old streaming advanced, 32262 -github.tar, huffman literals, old streaming advanced, 42777 +github.tar, huffman literals, old streaming advanced, 42687 github.tar, multithreaded with advanced params, old streaming advanced, 38884 github, level -5 with dict, old streaming cdict, 45832 github, level -3 with dict, old streaming cdict, 44671 @@ -1433,11 +1433,11 @@ github, level 13 with dict, old stre github, level 16 with dict, old streaming cdict, 37902 github, level 19 with dict, old streaming cdict, 37916 github, no source size with dict, old streaming cdict, 40652 -github.tar, level -5 with dict, old streaming cdict, 51512 -github.tar, level -3 with dict, old streaming cdict, 45379 -github.tar, level -1 with dict, old streaming cdict, 42084 +github.tar, level -5 with dict, old streaming cdict, 51407 +github.tar, level -3 with dict, old streaming cdict, 45254 +github.tar, level -1 with dict, old streaming cdict, 41973 github.tar, level 0 with dict, old streaming cdict, 37956 -github.tar, level 1 with dict, old streaming cdict, 38716 +github.tar, level 1 with dict, old streaming cdict, 38503 github.tar, level 3 with dict, old streaming cdict, 37956 github.tar, level 4 with dict, old streaming cdict, 37927 github.tar, level 5 with dict, old streaming cdict, 39000 @@ -1463,11 +1463,11 @@ github, level 13 with dict, old stre github, level 16 with dict, old streaming advanced cdict, 40804 github, level 19 with dict, old streaming advanced cdict, 37916 github, no source size with dict, old streaming advanced cdict, 40608 -github.tar, level -5 with dict, old streaming advanced cdict, 51019 -github.tar, level -3 with dict, old streaming advanced cdict, 45149 -github.tar, level -1 with dict, old streaming advanced cdict, 41694 +github.tar, level -5 with dict, old streaming advanced cdict, 50907 +github.tar, level -3 with dict, old streaming advanced cdict, 45032 +github.tar, level -1 with dict, old streaming advanced cdict, 41589 github.tar, level 0 with dict, old streaming advanced cdict, 38013 -github.tar, level 1 with dict, old streaming advanced cdict, 38513 +github.tar, level 1 with dict, old streaming advanced cdict, 38294 github.tar, level 3 with dict, old streaming advanced cdict, 38013 github.tar, level 4 with dict, old streaming advanced cdict, 38063 github.tar, level 5 with dict, old streaming advanced cdict, 39018 From 01474bf73b357fe0c7bcf51f5cd41928462e2488 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 25 Oct 2024 15:51:03 -0700 Subject: [PATCH 443/937] add internal compression parameter preBlockSplitter_level not yet exposed to the interface. Also: renames `useBlockSplitter` to `postBlockSplitter` to better qualify the difference between the 2 settings. --- lib/compress/zstd_compress.c | 52 +++++++++++++++++---------- lib/compress/zstd_compress_internal.h | 20 ++++++++--- 2 files changed, 48 insertions(+), 24 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 5f8f5aba4..05edcd201 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -323,7 +323,7 @@ static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams( assert(cctxParams.ldmParams.hashLog >= cctxParams.ldmParams.bucketSizeLog); assert(cctxParams.ldmParams.hashRateLog < 32); } - cctxParams.useBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.useBlockSplitter, &cParams); + cctxParams.postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams.postBlockSplitter, &cParams); cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams); cctxParams.validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams.validateSequences); cctxParams.maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams.maxBlockSize); @@ -391,13 +391,13 @@ ZSTD_CCtxParams_init_internal(ZSTD_CCtx_params* cctxParams, */ cctxParams->compressionLevel = compressionLevel; cctxParams->useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams->useRowMatchFinder, ¶ms->cParams); - cctxParams->useBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->useBlockSplitter, ¶ms->cParams); + cctxParams->postBlockSplitter = ZSTD_resolveBlockSplitterMode(cctxParams->postBlockSplitter, ¶ms->cParams); cctxParams->ldmParams.enableLdm = ZSTD_resolveEnableLdm(cctxParams->ldmParams.enableLdm, ¶ms->cParams); cctxParams->validateSequences = ZSTD_resolveExternalSequenceValidation(cctxParams->validateSequences); cctxParams->maxBlockSize = ZSTD_resolveMaxBlockSize(cctxParams->maxBlockSize); cctxParams->searchForExternalRepcodes = ZSTD_resolveExternalRepcodeSearch(cctxParams->searchForExternalRepcodes, compressionLevel); DEBUGLOG(4, "ZSTD_CCtxParams_init_internal: useRowMatchFinder=%d, useBlockSplitter=%d ldm=%d", - cctxParams->useRowMatchFinder, cctxParams->useBlockSplitter, cctxParams->ldmParams.enableLdm); + cctxParams->useRowMatchFinder, cctxParams->postBlockSplitter, cctxParams->ldmParams.enableLdm); } size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params) @@ -977,8 +977,8 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_useBlockSplitter: BOUNDCHECK(ZSTD_c_useBlockSplitter, value); - CCtxParams->useBlockSplitter = (ZSTD_paramSwitch_e)value; - return CCtxParams->useBlockSplitter; + CCtxParams->postBlockSplitter = (ZSTD_paramSwitch_e)value; + return CCtxParams->postBlockSplitter; case ZSTD_c_useRowMatchFinder: BOUNDCHECK(ZSTD_c_useRowMatchFinder, value); @@ -1136,7 +1136,7 @@ size_t ZSTD_CCtxParams_getParameter( *value = (int)CCtxParams->validateSequences; break; case ZSTD_c_useBlockSplitter : - *value = (int)CCtxParams->useBlockSplitter; + *value = (int)CCtxParams->postBlockSplitter; break; case ZSTD_c_useRowMatchFinder : *value = (int)CCtxParams->useRowMatchFinder; @@ -2111,7 +2111,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, params = &zc->appliedParams; assert(params->useRowMatchFinder != ZSTD_ps_auto); - assert(params->useBlockSplitter != ZSTD_ps_auto); + assert(params->postBlockSplitter != ZSTD_ps_auto); assert(params->ldmParams.enableLdm != ZSTD_ps_auto); assert(params->maxBlockSize != 0); if (params->ldmParams.enableLdm == ZSTD_ps_enable) { @@ -2517,10 +2517,10 @@ static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx, /* Copy only compression parameters related to tables. */ params.cParams = srcCCtx->appliedParams.cParams; assert(srcCCtx->appliedParams.useRowMatchFinder != ZSTD_ps_auto); - assert(srcCCtx->appliedParams.useBlockSplitter != ZSTD_ps_auto); + assert(srcCCtx->appliedParams.postBlockSplitter != ZSTD_ps_auto); assert(srcCCtx->appliedParams.ldmParams.enableLdm != ZSTD_ps_auto); params.useRowMatchFinder = srcCCtx->appliedParams.useRowMatchFinder; - params.useBlockSplitter = srcCCtx->appliedParams.useBlockSplitter; + params.postBlockSplitter = srcCCtx->appliedParams.postBlockSplitter; params.ldmParams = srcCCtx->appliedParams.ldmParams; params.fParams = fParams; params.maxBlockSize = srcCCtx->appliedParams.maxBlockSize; @@ -2728,9 +2728,9 @@ static int ZSTD_useTargetCBlockSize(const ZSTD_CCtx_params* cctxParams) * Returns 1 if true, 0 otherwise. */ static int ZSTD_blockSplitterEnabled(ZSTD_CCtx_params* cctxParams) { - DEBUGLOG(5, "ZSTD_blockSplitterEnabled (useBlockSplitter=%d)", cctxParams->useBlockSplitter); - assert(cctxParams->useBlockSplitter != ZSTD_ps_auto); - return (cctxParams->useBlockSplitter == ZSTD_ps_enable); + DEBUGLOG(5, "ZSTD_blockSplitterEnabled (postBlockSplitter=%d)", cctxParams->postBlockSplitter); + assert(cctxParams->postBlockSplitter != ZSTD_ps_auto); + return (cctxParams->postBlockSplitter == ZSTD_ps_enable); } /* Type returned by ZSTD_buildSequencesStatistics containing finalized symbol encoding types @@ -4300,7 +4300,7 @@ ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc, U32 nbSeq; size_t cSize; DEBUGLOG(4, "ZSTD_compressBlock_splitBlock"); - assert(zc->appliedParams.useBlockSplitter == ZSTD_ps_enable); + assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable); { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize); FORWARD_IF_ERROR(bss, "ZSTD_buildSeqStore failed"); @@ -4491,7 +4491,7 @@ static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, #include "zstd_preSplit.h" -static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, ZSTD_strategy strat, S64 savings) +static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t srcSize, size_t blockSizeMax, int splitLevel, ZSTD_strategy strat, S64 savings) { /* split level based on compression strategy, from `fast` to `btultra2` */ static const int splitLevels[] = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4 }; @@ -4506,9 +4506,18 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src * Note: as a consequence, the first full block is not split. */ if (savings < 3) return 128 KB; - /* dynamic splitting has a cpu cost for analysis, - * select a variant among multiple gradual speed/accuracy tradeoffs */ - return ZSTD_splitBlock(src, blockSizeMax, splitLevels[strat], cctx->tmpWorkspace, cctx->tmpWkspSize); + /* apply @splitLevel, or use default value (which depends on @strat). + * note that splitting heuristic is still conditioned by @savings >= 3, + * so the first block will not reach this code path */ + if (splitLevel == 1) return 128 KB; + if (splitLevel == 0) { + assert(ZSTD_fast <= strat && strat <= ZSTD_btultra2); + splitLevel = splitLevels[strat]; + } else { + assert(2 <= splitLevel && splitLevel <= 6); + splitLevel -= 2; + } + return ZSTD_splitBlock(src, blockSizeMax, splitLevel, cctx->tmpWorkspace, cctx->tmpWkspSize); } /*! ZSTD_compress_frameChunk() : @@ -4539,7 +4548,12 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, while (remaining) { ZSTD_matchState_t* const ms = &cctx->blockState.matchState; - size_t const blockSize = ZSTD_optimalBlockSize(cctx, ip, remaining, blockSizeMax, cctx->appliedParams.cParams.strategy, savings); + size_t const blockSize = ZSTD_optimalBlockSize(cctx, + ip, remaining, + blockSizeMax, + cctx->appliedParams.preBlockSplitter_level, + cctx->appliedParams.cParams.strategy, + savings); U32 const lastBlock = lastFrameChunk & (blockSize == remaining); assert(blockSize <= remaining); @@ -6286,7 +6300,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, dictSize, mode); } - params.useBlockSplitter = ZSTD_resolveBlockSplitterMode(params.useBlockSplitter, ¶ms.cParams); + params.postBlockSplitter = ZSTD_resolveBlockSplitterMode(params.postBlockSplitter, ¶ms.cParams); params.ldmParams.enableLdm = ZSTD_resolveEnableLdm(params.ldmParams.enableLdm, ¶ms.cParams); params.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params.useRowMatchFinder, ¶ms.cParams); params.validateSequences = ZSTD_resolveExternalSequenceValidation(params.validateSequences); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index e76bbda71..2d3510adc 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -343,8 +343,21 @@ struct ZSTD_CCtx_params_s { ZSTD_sequenceFormat_e blockDelimiters; int validateSequences; - /* Block splitting */ - ZSTD_paramSwitch_e useBlockSplitter; + /* Block splitting + * @postBlockSplitter executes split analysis after sequences are produced, + * it's more accurate but consumes more resources. + * @preBlockSplitter_level splits before knowing sequences, + * it's more approximative but also cheaper. + * Valid @preBlockSplitter_level values range from 0 to 6 (included). + * 0 means auto, 1 means do not split, + * then levels are sorted in increasing cpu budget, from 2 (fastest) to 6 (slowest). + * Highest @preBlockSplitter_level combines well with @postBlockSplitter. + */ + ZSTD_paramSwitch_e postBlockSplitter; + int preBlockSplitter_level; + + /* Adjust the max block size*/ + size_t maxBlockSize; /* Param for deciding whether to use row-based matchfinder */ ZSTD_paramSwitch_e useRowMatchFinder; @@ -368,9 +381,6 @@ struct ZSTD_CCtx_params_s { void* extSeqProdState; ZSTD_sequenceProducer_F extSeqProdFunc; - /* Adjust the max block size*/ - size_t maxBlockSize; - /* Controls repcode search in external sequence parsing */ ZSTD_paramSwitch_e searchForExternalRepcodes; }; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */ From 226ae73311d1ffd0c3488d8bc6a59576d910d6d4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 25 Oct 2024 16:08:22 -0700 Subject: [PATCH 444/937] expose new parameter ZSTD_c_blockSplitter_level --- lib/compress/zstd_compress.c | 15 +++++++++++++++ lib/zstd.h | 23 +++++++++++++++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 05edcd201..fbc11349e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -603,6 +603,11 @@ ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param) bounds.upperBound = (int)ZSTD_ps_disable; return bounds; + case ZSTD_c_blockSplitter_level: + bounds.lowerBound = 0; + bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX; + return bounds; + case ZSTD_c_useRowMatchFinder: bounds.lowerBound = (int)ZSTD_ps_auto; bounds.upperBound = (int)ZSTD_ps_disable; @@ -669,6 +674,7 @@ static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param) case ZSTD_c_minMatch: case ZSTD_c_targetLength: case ZSTD_c_strategy: + case ZSTD_c_blockSplitter_level: return 1; case ZSTD_c_format: @@ -755,6 +761,7 @@ size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value) case ZSTD_c_blockDelimiters: case ZSTD_c_validateSequences: case ZSTD_c_useBlockSplitter: + case ZSTD_c_blockSplitter_level: case ZSTD_c_useRowMatchFinder: case ZSTD_c_deterministicRefPrefix: case ZSTD_c_prefetchCDictTables: @@ -980,6 +987,11 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, CCtxParams->postBlockSplitter = (ZSTD_paramSwitch_e)value; return CCtxParams->postBlockSplitter; + case ZSTD_c_blockSplitter_level: + BOUNDCHECK(ZSTD_c_blockSplitter_level, value); + CCtxParams->preBlockSplitter_level = value; + return (size_t)CCtxParams->preBlockSplitter_level; + case ZSTD_c_useRowMatchFinder: BOUNDCHECK(ZSTD_c_useRowMatchFinder, value); CCtxParams->useRowMatchFinder = (ZSTD_paramSwitch_e)value; @@ -1138,6 +1150,9 @@ size_t ZSTD_CCtxParams_getParameter( case ZSTD_c_useBlockSplitter : *value = (int)CCtxParams->postBlockSplitter; break; + case ZSTD_c_blockSplitter_level : + *value = CCtxParams->preBlockSplitter_level; + break; case ZSTD_c_useRowMatchFinder : *value = (int)CCtxParams->useRowMatchFinder; break; diff --git a/lib/zstd.h b/lib/zstd.h index 3a88c74d1..c1ad26a8d 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -496,6 +496,7 @@ typedef enum { * ZSTD_c_prefetchCDictTables * ZSTD_c_enableSeqProducerFallback * ZSTD_c_maxBlockSize + * ZSTD_c_blockSplitter_level * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. * note : never ever use experimentalParam? names directly; * also, the enums values themselves are unstable and can still change. @@ -518,7 +519,8 @@ typedef enum { ZSTD_c_experimentalParam16=1013, ZSTD_c_experimentalParam17=1014, ZSTD_c_experimentalParam18=1015, - ZSTD_c_experimentalParam19=1016 + ZSTD_c_experimentalParam19=1016, + ZSTD_c_experimentalParam20=1017 } ZSTD_cParameter; typedef struct { @@ -2236,7 +2238,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo * that overrides the default ZSTD_BLOCKSIZE_MAX. It cannot be used to set upper * bounds greater than ZSTD_BLOCKSIZE_MAX or bounds lower than 1KB (will make * compressBound() inaccurate). Only currently meant to be used for testing. - * */ #define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18 @@ -2264,6 +2265,24 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo */ #define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 +/* ZSTD_c_blockSplitter_level + * note: this parameter only influences the first splitter stage, + * which is active before producing the sequences. + * ZSTD_c_useBlockSplitter influence the next splitter stage, + * which is active after sequence production, + * and is more accurate but also slower. + * Both can be combined. + * Allowed values are between 0 and 6. + * 0 means "auto", which will select a value depending on current ZSTD_c_strategy. + * 1 means no splitting. + * Then, values from 2 to 6 are sorted in increasing cpu load order. + * + * Note that currently the first block is never split, + * to ensure expansion guarantees in presence of incompressible data. + */ +#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 +#define ZSTD_c_blockSplitter_level ZSTD_c_experimentalParam20 + /*! ZSTD_CCtx_getParameter() : * Get the requested compression parameter value, selected by enum ZSTD_cParameter, * and store it into int* value. From 37706a677c09a1051f8b02361928c475bd094e67 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 25 Oct 2024 20:29:15 -0700 Subject: [PATCH 445/937] added a test test both that the new parameter works as intended, and that the over-split protection works as intended --- lib/compress/zstd_compress.c | 7 ++-- lib/compress/zstd_preSplit.c | 1 + tests/fuzzer.c | 63 ++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index fbc11349e..ca9e5edff 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2114,7 +2114,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, { ZSTD_cwksp* const ws = &zc->workspace; DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u, useRowMatchFinder=%d useBlockSplitter=%d", - (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->useBlockSplitter); + (U32)pledgedSrcSize, params->cParams.windowLog, (int)params->useRowMatchFinder, (int)params->postBlockSplitter); assert(!ZSTD_isError(ZSTD_checkCParams(params->cParams))); zc->isFirstBlock = 1; @@ -4520,7 +4520,10 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src * require verified savings to allow pre-splitting. * Note: as a consequence, the first full block is not split. */ - if (savings < 3) return 128 KB; + if (savings < 3) { + DEBUGLOG(6, "don't attempt splitting: savings (%lli) too low", savings); + return 128 KB; + } /* apply @splitLevel, or use default value (which depends on @strat). * note that splitting heuristic is still conditioned by @savings >= 3, * so the first block will not reach this code path */ diff --git a/lib/compress/zstd_preSplit.c b/lib/compress/zstd_preSplit.c index d25773950..d820c20ac 100644 --- a/lib/compress/zstd_preSplit.c +++ b/lib/compress/zstd_preSplit.c @@ -229,6 +229,7 @@ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize, int level, void* workspace, size_t wkspSize) { + DEBUGLOG(6, "ZSTD_splitBlock (level=%i)", level); assert(0<=level && level<=4); if (level == 0) return ZSTD_splitBlock_fromBorders(blockStart, blockSize, workspace, wkspSize); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index f5a894354..e32c0130d 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -559,6 +559,67 @@ static void test_setCParams(unsigned tnb) DISPLAYLEVEL(3, "OK \n"); } +static void test_blockSplitter_incompressibleExpansionProtection(unsigned testNb, unsigned seed) +{ + DISPLAYLEVEL(3, "test%3i : Check block splitter doesn't oversplit incompressible data (seed %u): ", testNb, seed); + { ZSTD_CCtx* cctx = ZSTD_createCCtx(); + size_t const srcSize = 256 * 1024; /* needs to be at least 2 blocks */ + void* incompressible = malloc(srcSize); + size_t const dstCapacity = ZSTD_compressBound(srcSize); + void* cBuffer = malloc(dstCapacity); + size_t const chunkSize = 8 KB; + size_t const nbChunks = srcSize / chunkSize; + size_t chunkNb, cSizeNoSplit, cSizeWithSplit; + assert(cctx != NULL); + assert(incompressible != NULL); + assert(cBuffer != NULL); + + /* let's fill input with random noise (incompressible) */ + RDG_genBuffer(incompressible, srcSize, 0.0, 0.0, seed); + DISPLAYLEVEL(4, "(hash: %llx) ", XXH64(incompressible, srcSize, 0)); + + /* this pattern targets the fastest _byChunk variant's sampling (level 3). + * manually checked that, without the @savings protection, it would over-split. + */ + for (chunkNb=0; chunkNb Date: Mon, 28 Oct 2024 16:47:38 -0700 Subject: [PATCH 446/937] fixed minor conversion warning --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index ca9e5edff..ea7a45fa7 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4521,7 +4521,7 @@ static size_t ZSTD_optimalBlockSize(ZSTD_CCtx* cctx, const void* src, size_t src * Note: as a consequence, the first full block is not split. */ if (savings < 3) { - DEBUGLOG(6, "don't attempt splitting: savings (%lli) too low", savings); + DEBUGLOG(6, "don't attempt splitting: savings (%i) too low", (int)savings); return 128 KB; } /* apply @splitLevel, or use default value (which depends on @strat). From f593ccda04f89be6fc4f966b9b816d542941771f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 28 Oct 2024 16:57:01 -0700 Subject: [PATCH 447/937] removed trace left over --- tests/fuzzer.c | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index e32c0130d..c1bff7a5a 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -576,7 +576,6 @@ static void test_blockSplitter_incompressibleExpansionProtection(unsigned testNb /* let's fill input with random noise (incompressible) */ RDG_genBuffer(incompressible, srcSize, 0.0, 0.0, seed); - DISPLAYLEVEL(4, "(hash: %llx) ", XXH64(incompressible, srcSize, 0)); /* this pattern targets the fastest _byChunk variant's sampling (level 3). * manually checked that, without the @savings protection, it would over-split. From 4f93206d62f306040a8e35033312e16986d0aeab Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 29 Oct 2024 11:04:11 -0700 Subject: [PATCH 448/937] changed variable name to ZSTD_c_blockSplitterLevel suggested by @terrelln --- lib/compress/zstd_compress.c | 12 ++++++------ lib/zstd.h | 6 +++--- tests/fuzzer.c | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index ea7a45fa7..cf3e08dca 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -603,7 +603,7 @@ ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param) bounds.upperBound = (int)ZSTD_ps_disable; return bounds; - case ZSTD_c_blockSplitter_level: + case ZSTD_c_blockSplitterLevel: bounds.lowerBound = 0; bounds.upperBound = ZSTD_BLOCKSPLITTER_LEVEL_MAX; return bounds; @@ -674,7 +674,7 @@ static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param) case ZSTD_c_minMatch: case ZSTD_c_targetLength: case ZSTD_c_strategy: - case ZSTD_c_blockSplitter_level: + case ZSTD_c_blockSplitterLevel: return 1; case ZSTD_c_format: @@ -761,7 +761,7 @@ size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value) case ZSTD_c_blockDelimiters: case ZSTD_c_validateSequences: case ZSTD_c_useBlockSplitter: - case ZSTD_c_blockSplitter_level: + case ZSTD_c_blockSplitterLevel: case ZSTD_c_useRowMatchFinder: case ZSTD_c_deterministicRefPrefix: case ZSTD_c_prefetchCDictTables: @@ -987,8 +987,8 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, CCtxParams->postBlockSplitter = (ZSTD_paramSwitch_e)value; return CCtxParams->postBlockSplitter; - case ZSTD_c_blockSplitter_level: - BOUNDCHECK(ZSTD_c_blockSplitter_level, value); + case ZSTD_c_blockSplitterLevel: + BOUNDCHECK(ZSTD_c_blockSplitterLevel, value); CCtxParams->preBlockSplitter_level = value; return (size_t)CCtxParams->preBlockSplitter_level; @@ -1150,7 +1150,7 @@ size_t ZSTD_CCtxParams_getParameter( case ZSTD_c_useBlockSplitter : *value = (int)CCtxParams->postBlockSplitter; break; - case ZSTD_c_blockSplitter_level : + case ZSTD_c_blockSplitterLevel : *value = CCtxParams->preBlockSplitter_level; break; case ZSTD_c_useRowMatchFinder : diff --git a/lib/zstd.h b/lib/zstd.h index c1ad26a8d..cc5bb9879 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -496,7 +496,7 @@ typedef enum { * ZSTD_c_prefetchCDictTables * ZSTD_c_enableSeqProducerFallback * ZSTD_c_maxBlockSize - * ZSTD_c_blockSplitter_level + * ZSTD_c_blockSplitterLevel * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. * note : never ever use experimentalParam? names directly; * also, the enums values themselves are unstable and can still change. @@ -2265,7 +2265,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo */ #define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 -/* ZSTD_c_blockSplitter_level +/* ZSTD_c_blockSplitterLevel * note: this parameter only influences the first splitter stage, * which is active before producing the sequences. * ZSTD_c_useBlockSplitter influence the next splitter stage, @@ -2281,7 +2281,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo * to ensure expansion guarantees in presence of incompressible data. */ #define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 -#define ZSTD_c_blockSplitter_level ZSTD_c_experimentalParam20 +#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20 /*! ZSTD_CCtx_getParameter() : * Get the requested compression parameter value, selected by enum ZSTD_cParameter, diff --git a/tests/fuzzer.c b/tests/fuzzer.c index c1bff7a5a..08c2662fb 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -595,11 +595,11 @@ static void test_blockSplitter_incompressibleExpansionProtection(unsigned testNb } /* run first without splitting */ - ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockSplitter_level, 1 /* no split */); + ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockSplitterLevel, 1 /* no split */); cSizeNoSplit = ZSTD_compress2(cctx, cBuffer, dstCapacity, incompressible, srcSize); /* run with sample43 splitter, check it's still the same */ - ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockSplitter_level, 3 /* sample43, fastest _byChunk variant */); + ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockSplitterLevel, 3 /* sample43, fastest _byChunk variant */); cSizeWithSplit = ZSTD_compress2(cctx, cBuffer, dstCapacity, incompressible, srcSize); if (cSizeWithSplit != cSizeNoSplit) { From bbaba45589f233b91a310806d97ee7b4d9ee8320 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 31 Oct 2024 13:43:40 -0700 Subject: [PATCH 449/937] change experimental parameter name from ZSTD_c_useBlockSplitter to ZSTD_c_splitAfterSequences. --- lib/compress/zstd_compress.c | 12 ++++----- lib/zstd.h | 51 ++++++++++++++++++++---------------- tests/fuzz/zstd_helpers.c | 3 ++- tests/fuzzer.c | 14 +++++----- 4 files changed, 44 insertions(+), 36 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index cf3e08dca..3d78b7da3 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -598,7 +598,7 @@ ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param) bounds.upperBound = 1; return bounds; - case ZSTD_c_useBlockSplitter: + case ZSTD_c_splitAfterSequences: bounds.lowerBound = (int)ZSTD_ps_auto; bounds.upperBound = (int)ZSTD_ps_disable; return bounds; @@ -701,7 +701,7 @@ static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param) case ZSTD_c_stableOutBuffer: case ZSTD_c_blockDelimiters: case ZSTD_c_validateSequences: - case ZSTD_c_useBlockSplitter: + case ZSTD_c_splitAfterSequences: case ZSTD_c_useRowMatchFinder: case ZSTD_c_deterministicRefPrefix: case ZSTD_c_prefetchCDictTables: @@ -760,7 +760,7 @@ size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value) case ZSTD_c_stableOutBuffer: case ZSTD_c_blockDelimiters: case ZSTD_c_validateSequences: - case ZSTD_c_useBlockSplitter: + case ZSTD_c_splitAfterSequences: case ZSTD_c_blockSplitterLevel: case ZSTD_c_useRowMatchFinder: case ZSTD_c_deterministicRefPrefix: @@ -982,8 +982,8 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, CCtxParams->validateSequences = value; return (size_t)CCtxParams->validateSequences; - case ZSTD_c_useBlockSplitter: - BOUNDCHECK(ZSTD_c_useBlockSplitter, value); + case ZSTD_c_splitAfterSequences: + BOUNDCHECK(ZSTD_c_splitAfterSequences, value); CCtxParams->postBlockSplitter = (ZSTD_paramSwitch_e)value; return CCtxParams->postBlockSplitter; @@ -1147,7 +1147,7 @@ size_t ZSTD_CCtxParams_getParameter( case ZSTD_c_validateSequences : *value = (int)CCtxParams->validateSequences; break; - case ZSTD_c_useBlockSplitter : + case ZSTD_c_splitAfterSequences : *value = (int)CCtxParams->postBlockSplitter; break; case ZSTD_c_blockSplitterLevel : diff --git a/lib/zstd.h b/lib/zstd.h index cc5bb9879..ecf837bc9 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -491,12 +491,12 @@ typedef enum { * ZSTD_c_stableOutBuffer * ZSTD_c_blockDelimiters * ZSTD_c_validateSequences - * ZSTD_c_useBlockSplitter + * ZSTD_c_blockSplitterLevel + * ZSTD_c_splitAfterSequences * ZSTD_c_useRowMatchFinder * ZSTD_c_prefetchCDictTables * ZSTD_c_enableSeqProducerFallback * ZSTD_c_maxBlockSize - * ZSTD_c_blockSplitterLevel * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them. * note : never ever use experimentalParam? names directly; * also, the enums values themselves are unstable and can still change. @@ -2150,8 +2150,32 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo */ #define ZSTD_c_validateSequences ZSTD_c_experimentalParam12 -/* ZSTD_c_useBlockSplitter - * Controlled with ZSTD_paramSwitch_e enum. +/* ZSTD_c_blockSplitterLevel + * note: this parameter only influences the first splitter stage, + * which is active before producing the sequences. + * ZSTD_c_splitAfterSequences controls the next splitter stage, + * which is active after sequence production. + * Note that both can be combined. + * Allowed values are between 0 and ZSTD_BLOCKSPLITTER_LEVEL_MAX included. + * 0 means "auto", which will select a value depending on current ZSTD_c_strategy. + * 1 means no splitting. + * Then, values from 2 to 6 are sorted in increasing cpu load order. + * + * Note that currently the first block is never split, + * to ensure expansion guarantees in presence of incompressible data. + */ +#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 +#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20 + +/* ZSTD_c_splitAfterSequences + * This is a stronger splitter algorithm, + * based on actual sequences previously produced by the selected parser. + * It's also slower, and as a consequence, mostly used for high compression levels. + * While the post-splitter does overlap with the pre-splitter, + * both can nonetheless be combined, + * notably with ZSTD_c_blockSplitterLevel at ZSTD_BLOCKSPLITTER_LEVEL_MAX, + * resulting in higher compression ratio than just one of them. + * * Default is ZSTD_ps_auto. * Set to ZSTD_ps_disable to never use block splitter. * Set to ZSTD_ps_enable to always use block splitter. @@ -2159,7 +2183,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo * By default, in ZSTD_ps_auto, the library will decide at runtime whether to use * block splitting based on the compression parameters. */ -#define ZSTD_c_useBlockSplitter ZSTD_c_experimentalParam13 +#define ZSTD_c_splitAfterSequences ZSTD_c_experimentalParam13 /* ZSTD_c_useRowMatchFinder * Controlled with ZSTD_paramSwitch_e enum. @@ -2265,23 +2289,6 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo */ #define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 -/* ZSTD_c_blockSplitterLevel - * note: this parameter only influences the first splitter stage, - * which is active before producing the sequences. - * ZSTD_c_useBlockSplitter influence the next splitter stage, - * which is active after sequence production, - * and is more accurate but also slower. - * Both can be combined. - * Allowed values are between 0 and 6. - * 0 means "auto", which will select a value depending on current ZSTD_c_strategy. - * 1 means no splitting. - * Then, values from 2 to 6 are sorted in increasing cpu load order. - * - * Note that currently the first block is never split, - * to ensure expansion guarantees in presence of incompressible data. - */ -#define ZSTD_BLOCKSPLITTER_LEVEL_MAX 6 -#define ZSTD_c_blockSplitterLevel ZSTD_c_experimentalParam20 /*! ZSTD_CCtx_getParameter() : * Get the requested compression parameter value, selected by enum ZSTD_cParameter, diff --git a/tests/fuzz/zstd_helpers.c b/tests/fuzz/zstd_helpers.c index f4cb10823..c89e448d0 100644 --- a/tests/fuzz/zstd_helpers.c +++ b/tests/fuzz/zstd_helpers.c @@ -140,7 +140,8 @@ void FUZZ_setRandomParameters(ZSTD_CCtx *cctx, size_t srcSize, FUZZ_dataProducer setRand(cctx, ZSTD_c_forceMaxWindow, 0, 1, producer); setRand(cctx, ZSTD_c_literalCompressionMode, 0, 2, producer); setRand(cctx, ZSTD_c_forceAttachDict, 0, 2, producer); - setRand(cctx, ZSTD_c_useBlockSplitter, 0, 2, producer); + setRand(cctx, ZSTD_c_blockSplitterLevel, 0, ZSTD_BLOCKSPLITTER_LEVEL_MAX, producer); + setRand(cctx, ZSTD_c_splitAfterSequences, 0, 2, producer); setRand(cctx, ZSTD_c_deterministicRefPrefix, 0, 1, producer); setRand(cctx, ZSTD_c_prefetchCDictTables, 0, 2, producer); setRand(cctx, ZSTD_c_maxBlockSize, ZSTD_BLOCKSIZE_MAX_MIN, ZSTD_BLOCKSIZE_MAX, producer); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 08c2662fb..4a6ebd69c 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -1420,7 +1420,7 @@ static int basicUnitTests(U32 const seed, double compressibility) CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 19)); CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7)); - CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_useBlockSplitter, ZSTD_ps_enable)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_splitAfterSequences, ZSTD_ps_enable)); cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, data, srcSize); CHECK_Z(cSize); @@ -1737,8 +1737,8 @@ static int basicUnitTests(U32 const seed, double compressibility) { ZSTD_CCtx* const cctx = ZSTD_createCCtx(); int value; ZSTD_compressionParameters cparams = ZSTD_getCParams(1, 0, 0); - cparams.strategy = -1; - /* Set invalid cParams == no change. */ + cparams.strategy = (ZSTD_strategy)-1; /* set invalid value, on purpose */ + /* Set invalid cParams == error out, and no change. */ CHECK(ZSTD_isError(ZSTD_CCtx_setCParams(cctx, cparams))); CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_windowLog, &value)); @@ -1801,12 +1801,12 @@ static int basicUnitTests(U32 const seed, double compressibility) ZSTD_freeCCtx(cctx); } - DISPLAYLEVEL(3, "test%3d : ZSTD_CCtx_setCarams() : ", testNb++); + DISPLAYLEVEL(3, "test%3d : ZSTD_CCtx_setParams() : ", testNb++); { ZSTD_CCtx* const cctx = ZSTD_createCCtx(); int value; ZSTD_parameters params = ZSTD_getParams(1, 0, 0); - params.cParams.strategy = -1; - /* Set invalid params == no change. */ + params.cParams.strategy = (ZSTD_strategy)-1; /* set invalid value, on purpose */ + /* Set invalid params == error out, and no change. */ CHECK(ZSTD_isError(ZSTD_CCtx_setParams(cctx, params))); CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_windowLog, &value)); @@ -2252,7 +2252,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "test%3i : compress with block splitting : ", testNb++) { ZSTD_CCtx* cctx = ZSTD_createCCtx(); - CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_useBlockSplitter, ZSTD_ps_enable) ); + CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_splitAfterSequences, ZSTD_ps_enable) ); cSize = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize); CHECK_Z(cSize); ZSTD_freeCCtx(cctx); From d9553fd2180535a11dcb4e2f5a3197202befc2c0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 31 Oct 2024 14:04:11 -0700 Subject: [PATCH 450/937] elevated ZSTD_getErrorCode() to stable status answering #4183 --- doc/zstd_manual.html | 149 ++++++++++++++++++++++++------------------- lib/zstd.h | 44 ++++++++----- lib/zstd_errors.h | 8 --- 3 files changed, 109 insertions(+), 92 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 56bfbcd81..7a1cbbd3e 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -10,7 +10,7 @@
  1. Introduction
  2. Version
  3. -
  4. Simple API
  5. +
  6. Simple Core API
  7. Explicit context
  8. Advanced compression API (Requires v1.4.0+)
  9. Advanced decompression API (Requires v1.4.0+)
  10. @@ -74,7 +74,7 @@

    Return runtime library version, like "1.4.5". Requires v1.3.0+.


-

Simple API


+

Simple Core API


 
 
size_t ZSTD_compress( void* dst, size_t dstCapacity,
                 const void* src, size_t srcSize,
@@ -88,38 +88,42 @@
 
 
size_t ZSTD_decompress( void* dst, size_t dstCapacity,
                   const void* src, size_t compressedSize);
-

`compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. - `dstCapacity` is an upper bound of originalSize to regenerate. - If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data. - @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), - or an errorCode if it fails (which can be tested using ZSTD_isError()). +

`compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames. + Multiple compressed frames can be decompressed at once with this method. + The result will be the concatenation of all decompressed frames, back to back. + `dstCapacity` is an upper bound of originalSize to regenerate. + First frame's decompressed size can be extracted using ZSTD_getFrameContentSize(). + If maximum upper bound isn't known, prefer using streaming mode to decompress data. + @return : the number of bytes decompressed into `dst` (<= `dstCapacity`), + or an errorCode if it fails (which can be tested using ZSTD_isError()).


+

Decompression helper functions


#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
 #define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
 unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);
-

`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". - 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() +

`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". + 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()


ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize")
@@ -140,35 +144,21 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
         or an error code if input is invalid 
 


-

Helper functions

/* ZSTD_compressBound() :
- * maximum compressed size in worst case single-pass scenario.
- * When invoking `ZSTD_compress()` or any other one-pass compression function,
- * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
- * as it eliminates one potential failure scenario,
- * aka not enough room in dst buffer to write the compressed frame.
- * Note : ZSTD_compressBound() itself can fail, if @srcSize > ZSTD_MAX_INPUT_SIZE .
- *        In which case, ZSTD_compressBound() will return an error code
- *        which can be tested using ZSTD_isError().
- *
- * ZSTD_COMPRESSBOUND() :
- * same as ZSTD_compressBound(), but as a macro.
- * It can be used to produce constants, which can be useful for static allocation,
- * for example to size a static array on stack.
- * Will produce constant value 0 if srcSize too large.
- */
-#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
-#define ZSTD_COMPRESSBOUND(srcSize)   (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
-size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
+

Compression helper functions


+
size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
+

+

Error helper functions

#include "zstd_errors.h" /* list of errors */
 /* ZSTD_isError() :
  * Most ZSTD_* functions returning a size_t value can be tested for error,
  * using ZSTD_isError().
  * @return 1 if error, 0 otherwise
  */
-unsigned    ZSTD_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
-const char* ZSTD_getErrorName(size_t code);     /*!< provides readable string from an error code */
-int         ZSTD_minCLevel(void);               /*!< minimum negative compression level allowed, requires v1.4.0+ */
-int         ZSTD_maxCLevel(void);               /*!< maximum compression level available */
-int         ZSTD_defaultCLevel(void);           /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
+unsigned     ZSTD_isError(size_t code);        /*!< tells if a `size_t` function result is an error code */
+ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */
+const char*  ZSTD_getErrorName(size_t code);   /*!< provides readable string from an error code */
+int          ZSTD_minCLevel(void);             /*!< minimum negative compression level allowed, requires v1.4.0+ */
+int          ZSTD_maxCLevel(void);             /*!< maximum compression level available */
+int          ZSTD_defaultCLevel(void);         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
 

Explicit context


 
@@ -718,7 +708,7 @@ size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
 

Streaming decompression - HowTo

   A ZSTD_DStream object is required to track streaming operations.
   Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
-  ZSTD_DStream objects can be reused multiple times.
+  ZSTD_DStream objects can be re-employed multiple times.
 
   Use ZSTD_initDStream() to start a new decompression operation.
  @return : recommended first input size
@@ -728,16 +718,21 @@ size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
   The function will update both `pos` fields.
   If `input.pos < input.size`, some input has not been consumed.
   It's up to the caller to present again remaining data.
+
   The function tries to flush all data decoded immediately, respecting output buffer size.
   If `output.pos < output.size`, decoder has flushed everything it could.
-  But if `output.pos == output.size`, there might be some data left within internal buffers.,
+
+  However, when `output.pos == output.size`, it's more difficult to know.
+  If @return > 0, the frame is not complete, meaning
+  either there is still some data left to flush within internal buffers,
+  or there is more input to read to complete the frame (or both).
   In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.
   Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.
  @return : 0 when a frame is completely decoded and fully flushed,
         or an error code, which can be tested using ZSTD_isError(),
         or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :
                                 the return value is a suggested next input size (just a hint for better latency)
-                                that will never request more than the remaining frame size.
+                                that will never request more than the remaining content of the compressed frame.
  
 
@@ -763,9 +758,10 @@ size_t ZSTD_freeDStream(ZSTD_DStream* zds);
/* accept NULL pointer */ Function will update both input and output `pos` fields exposing current state via these fields: - `input.pos < input.size`, some input remaining and caller should provide remaining input on the next call. - - `output.pos < output.size`, decoder finished and flushed all remaining buffers. - - `output.pos == output.size`, potentially uncflushed data present in the internal buffers, - call ZSTD_decompressStream() again to flush remaining data to output. + - `output.pos < output.size`, decoder flushed internal output buffer. + - `output.pos == output.size`, unflushed data potentially present in the internal buffers, + check ZSTD_decompressStream() @return value, + if > 0, invoke it again to flush remaining data to output. Note : with no additional input, amount of data flushed <= ZSTD_BLOCKSIZE_MAX. @return : 0 when a frame is completely decoded and fully flushed, @@ -1311,19 +1307,37 @@ ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr,


-

Generate sequences using ZSTD_compress2(), given a source buffer. +

ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()")
+ZSTDLIB_STATIC_API size_t
+ZSTD_generateSequences(ZSTD_CCtx* zc,
+           ZSTD_Sequence* outSeqs, size_t outSeqsSize,
+           const void* src, size_t srcSize);
+

WARNING: This function is meant for debugging and informational purposes ONLY! + Its implementation is flawed, and it will be deleted in a future version. + It is not guaranteed to succeed, as there are several cases where it will give + up and fail. You should NOT use this function in production code. + + This function is deprecated, and will be removed in a future version. + + Generate sequences using ZSTD_compress2(), given a source buffer. + + @param zc The compression context to be used for ZSTD_compress2(). Set any + compression parameters you need on this context. + @param outSeqs The output sequences buffer of size @p outSeqsSize + @param outSeqsSize The size of the output sequences buffer. + ZSTD_sequenceBound(srcSize) is an upper bound on the number + of sequences that can be generated. + @param src The source buffer to generate sequences from of size @p srcSize. + @param srcSize The size of the source buffer. Each block will end with a dummy sequence with offset == 0, matchLength == 0, and litLength == length of last literals. litLength may be == 0, and if so, then the sequence of (of: 0 ml: 0 ll: 0) simply acts as a block delimiter. - @zc can be used to insert custom compression params. - This function invokes ZSTD_compress2(). - - The output of this function can be fed into ZSTD_compressSequences() with CCtx - setting of ZSTD_c_blockDelimiters as ZSTD_sf_explicitBlockDelimiters - @return : number of sequences generated + @returns The number of sequences generated, necessarily less than + ZSTD_sequenceBound(srcSize), or an error code that can be checked + with ZSTD_isError().


@@ -1512,13 +1526,14 @@ static #ifdef __GNUC__ __attribute__((__unused__)) #endif -ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL };
/**< this constant defers to stdlib's functions */

These prototypes make it possible to pass your own allocation/free functions. ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below. All allocation/free operations will be completed using these custom variants instead of regular ones.


+
ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL };  /**< this constant defers to stdlib's functions */
+

typedef struct POOL_ctx_s ZSTD_threadPool;
 ZSTDLIB_STATIC_API ZSTD_threadPool* ZSTD_createThreadPool(size_t numThreads);
 ZSTDLIB_STATIC_API void ZSTD_freeThreadPool (ZSTD_threadPool* pool);  /* accept NULL pointer */
diff --git a/lib/zstd.h b/lib/zstd.h
index ecf837bc9..22aca768c 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -15,7 +15,6 @@ extern "C" {
 #define ZSTD_H_235446
 
 /* ======   Dependencies   ======*/
-#include    /* INT_MAX */
 #include    /* size_t */
 
 
@@ -106,7 +105,7 @@ extern "C" {
 /*------   Version   ------*/
 #define ZSTD_VERSION_MAJOR    1
 #define ZSTD_VERSION_MINOR    5
-#define ZSTD_VERSION_RELEASE  6
+#define ZSTD_VERSION_RELEASE  7
 #define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
 
 /*! ZSTD_versionNumber() :
@@ -144,7 +143,7 @@ ZSTDLIB_API const char* ZSTD_versionString(void);
 
 
 /***************************************
-*  Simple API
+*  Simple Core API
 ***************************************/
 /*! ZSTD_compress() :
  *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
@@ -168,6 +167,9 @@ ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
 ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
                               const void* src, size_t compressedSize);
 
+
+/*======  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.
@@ -214,10 +216,11 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
 ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);
 
 
-/*======  Helper functions  ======*/
+/*======  Compression helper functions  ======*/
+
 /* ZSTD_compressBound() :
  * maximum compressed size in worst case single-pass scenario.
- * When invoking `ZSTD_compress()` or any other one-pass compression function,
+ * When invoking `ZSTD_compress()`, or any other one-pass compression function,
  * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
  * as it eliminates one potential failure scenario,
  * aka not enough room in dst buffer to write the compressed frame.
@@ -229,21 +232,26 @@ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize)
  * same as ZSTD_compressBound(), but as a macro.
  * It can be used to produce constants, which can be useful for static allocation,
  * for example to size a static array on stack.
- * Will produce constant value 0 if srcSize too large.
+ * Will produce constant value 0 if srcSize is too large.
  */
 #define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
 #define ZSTD_COMPRESSBOUND(srcSize)   (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
 ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
+
+
+/*======  Error helper functions  ======*/
+#include "zstd_errors.h" /* list of errors */
 /* ZSTD_isError() :
  * Most ZSTD_* functions returning a size_t value can be tested for error,
  * using ZSTD_isError().
  * @return 1 if error, 0 otherwise
  */
-ZSTDLIB_API unsigned    ZSTD_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
-ZSTDLIB_API const char* ZSTD_getErrorName(size_t code);     /*!< provides readable string from an error code */
-ZSTDLIB_API int         ZSTD_minCLevel(void);               /*!< minimum negative compression level allowed, requires v1.4.0+ */
-ZSTDLIB_API int         ZSTD_maxCLevel(void);               /*!< maximum compression level available */
-ZSTDLIB_API int         ZSTD_defaultCLevel(void);           /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
+ZSTDLIB_API unsigned     ZSTD_isError(size_t result);      /*!< tells if a `size_t` function result is an error code */
+ZSTDLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */
+ZSTDLIB_API const char*  ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */
+ZSTDLIB_API int          ZSTD_minCLevel(void);             /*!< minimum negative compression level allowed, requires v1.4.0+ */
+ZSTDLIB_API int          ZSTD_maxCLevel(void);             /*!< maximum compression level available */
+ZSTDLIB_API int          ZSTD_defaultCLevel(void);         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
 
 
 /***************************************
@@ -251,17 +259,17 @@ ZSTDLIB_API int         ZSTD_defaultCLevel(void);           /*!< default compres
 ***************************************/
 /*= Compression context
  *  When compressing many times,
- *  it is recommended to allocate a context just once,
+ *  it is recommended to allocate a compression context just once,
  *  and reuse it for each successive compression operation.
- *  This will make workload friendlier for system's memory.
+ *  This will make the workload easier for system's memory.
  *  Note : re-using context is just a speed / resource optimization.
  *         It doesn't change the compression ratio, which remains identical.
- *  Note 2 : In multi-threaded environments,
- *         use one different context per thread for parallel execution.
+ *  Note 2: For parallel execution in multi-threaded environments,
+ *         use one different context per thread .
  */
 typedef struct ZSTD_CCtx_s ZSTD_CCtx;
 ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
-ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* accept NULL pointer */
+ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* compatible with NULL pointer */
 
 /*! ZSTD_compressCCtx() :
  *  Same as ZSTD_compress(), using an explicit ZSTD_CCtx.
@@ -269,7 +277,7 @@ ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* accept NULL pointer *
  *  this function compresses at the requested compression level,
  *  __ignoring any other advanced parameter__ .
  *  If any advanced parameter was set using the advanced API,
- *  they will all be reset. Only `compressionLevel` remains.
+ *  they will all be reset. Only @compressionLevel remains.
  */
 ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
                                      void* dst, size_t dstCapacity,
@@ -1207,6 +1215,8 @@ ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
 
+#include    /* INT_MAX */
+
 /* This can be overridden externally to hide static symbols. */
 #ifndef ZSTDLIB_STATIC_API
 #  if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
diff --git a/lib/zstd_errors.h b/lib/zstd_errors.h
index dc75eeeba..20e488f15 100644
--- a/lib/zstd_errors.h
+++ b/lib/zstd_errors.h
@@ -15,10 +15,6 @@
 extern "C" {
 #endif
 
-/*===== dependency =====*/
-#include    /* size_t */
-
-
 /* =====   ZSTDERRORLIB_API : control library symbols visibility   ===== */
 #ifndef ZSTDERRORLIB_VISIBLE
    /* Backwards compatibility with old macro name */
@@ -100,10 +96,6 @@ typedef enum {
   ZSTD_error_maxCode = 120  /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
 } ZSTD_ErrorCode;
 
-/*! ZSTD_getErrorCode() :
-    convert a `size_t` function result into a `ZSTD_ErrorCode` enum type,
-    which can be used to compare with enum list published above */
-ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult);
 ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code);   /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */
 
 

From adbb536d00a1a67f2654040fd201760e2abfb20c Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 31 Oct 2024 14:38:36 -0700
Subject: [PATCH 451/937] fixed single file library test

copy "zstd_errors.h" alongside "zstd.h" to pass compilation test.
---
 build/single_file_libs/build_library_test.sh | 1 +
 1 file changed, 1 insertion(+)

diff --git a/build/single_file_libs/build_library_test.sh b/build/single_file_libs/build_library_test.sh
index f4ba109ab..b67cd99a0 100755
--- a/build/single_file_libs/build_library_test.sh
+++ b/build/single_file_libs/build_library_test.sh
@@ -70,6 +70,7 @@ echo "Single file library creation script: PASSED"
 
 # Copy the header to here (for the tests)
 cp "$ZSTD_SRC_ROOT/zstd.h" examples/zstd.h
+cp "$ZSTD_SRC_ROOT/zstd_errors.h" examples/zstd_errors.h
 
 # Compile the generated output
 cc -Wall -Wextra -Werror -Wshadow -pthread -I. -Os -g0 -o $OUT_FILE zstd.c examples/roundtrip.c

From 2e02cd330dee3fcf9a8609b90ed7b965e0a6f9a1 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Thu, 31 Oct 2024 15:06:48 -0700
Subject: [PATCH 452/937] inform manual users that it's automatically generated

suggested by @Eugeny1
---
 contrib/gen_html/gen_html.cpp |  1 +
 doc/zstd_manual.html          | 49 +++++++++++++++++++++++++----------
 lib/zstd.h                    |  2 +-
 3 files changed, 37 insertions(+), 15 deletions(-)

diff --git a/contrib/gen_html/gen_html.cpp b/contrib/gen_html/gen_html.cpp
index 1da5879ad..adf0f41b9 100644
--- a/contrib/gen_html/gen_html.cpp
+++ b/contrib/gen_html/gen_html.cpp
@@ -211,6 +211,7 @@ int main(int argc, char *argv[]) {
 
     ostream << "\n\n\n" << version << "\n\n" << endl;
     ostream << "

" << version << "

\n"; + ostream << "Note: the content of this file has been automatically generated by parsing \"zstd.h\" \n"; ostream << "
\n

Contents

\n
    \n"; for (size_t i=0; i -zstd 1.5.6 Manual +zstd 1.5.7 Manual -

    zstd 1.5.6 Manual

    +

    zstd 1.5.7 Manual

    +Note: the content of this file has been automatically generated by parsing "zstd.h"

    Contents

      @@ -145,17 +146,35 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);


Compression helper functions


-
size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
-

+
#define ZSTD_MAX_INPUT_SIZE ((sizeof(size_t)==8) ? 0xFF00FF00FF00FF00ULL : 0xFF00FF00U)
+#define ZSTD_COMPRESSBOUND(srcSize)   (((size_t)(srcSize) >= ZSTD_MAX_INPUT_SIZE) ? 0 : (srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
+size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
+

maximum compressed size in worst case single-pass scenario. + When invoking `ZSTD_compress()`, or any other one-pass compression function, + it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize) + as it eliminates one potential failure scenario, + aka not enough room in dst buffer to write the compressed frame. + Note : ZSTD_compressBound() itself can fail, if @srcSize > ZSTD_MAX_INPUT_SIZE . + In which case, ZSTD_compressBound() will return an error code + which can be tested using ZSTD_isError(). + + ZSTD_COMPRESSBOUND() : + same as ZSTD_compressBound(), but as a macro. + It can be used to produce constants, which can be useful for static allocation, + for example to size a static array on stack. + Will produce constant value 0 if srcSize is too large. + +


+

Error helper functions

#include "zstd_errors.h" /* list of errors */
 /* ZSTD_isError() :
  * Most ZSTD_* functions returning a size_t value can be tested for error,
  * using ZSTD_isError().
  * @return 1 if error, 0 otherwise
  */
-unsigned     ZSTD_isError(size_t code);        /*!< tells if a `size_t` function result is an error code */
+unsigned     ZSTD_isError(size_t result);      /*!< tells if a `size_t` function result is an error code */
 ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult); /* convert a result into an error code, which can be compared to error enum list */
-const char*  ZSTD_getErrorName(size_t code);   /*!< provides readable string from an error code */
+const char*  ZSTD_getErrorName(size_t result); /*!< provides readable string from a function result */
 int          ZSTD_minCLevel(void);             /*!< minimum negative compression level allowed, requires v1.4.0+ */
 int          ZSTD_maxCLevel(void);             /*!< maximum compression level available */
 int          ZSTD_defaultCLevel(void);         /*!< default compression level, specified by ZSTD_CLEVEL_DEFAULT, requires v1.5.0+ */
@@ -163,17 +182,17 @@ int          ZSTD_defaultCLevel(void);         /*!< default compression leve
 

Explicit context


 
 

Compression context

  When compressing many times,
-  it is recommended to allocate a context just once,
+  it is recommended to allocate a compression context just once,
   and reuse it for each successive compression operation.
-  This will make workload friendlier for system's memory.
+  This will make the workload easier for system's memory.
   Note : re-using context is just a speed / resource optimization.
          It doesn't change the compression ratio, which remains identical.
-  Note 2 : In multi-threaded environments,
-         use one different context per thread for parallel execution.
+  Note 2: For parallel execution in multi-threaded environments,
+         use one different context per thread .
  
 
typedef struct ZSTD_CCtx_s ZSTD_CCtx;
 ZSTD_CCtx* ZSTD_createCCtx(void);
-size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* accept NULL pointer */
+size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* compatible with NULL pointer */
 

size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
                          void* dst, size_t dstCapacity,
@@ -184,7 +203,7 @@ size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);  /* accept NULL pointer */
   this function compresses at the requested compression level,
   __ignoring any other advanced parameter__ .
   If any advanced parameter was set using the advanced API,
-  they will all be reset. Only `compressionLevel` remains.
+  they will all be reset. Only @compressionLevel remains.
  
 


@@ -384,7 +403,8 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx);
/* accept NULL pointer */ * ZSTD_c_stableOutBuffer * ZSTD_c_blockDelimiters * ZSTD_c_validateSequences - * ZSTD_c_useBlockSplitter + * ZSTD_c_blockSplitterLevel + * ZSTD_c_splitAfterSequences * ZSTD_c_useRowMatchFinder * ZSTD_c_prefetchCDictTables * ZSTD_c_enableSeqProducerFallback @@ -411,7 +431,8 @@ size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx); /* accept NULL pointer */ ZSTD_c_experimentalParam16=1013, ZSTD_c_experimentalParam17=1014, ZSTD_c_experimentalParam18=1015, - ZSTD_c_experimentalParam19=1016 + ZSTD_c_experimentalParam19=1016, + ZSTD_c_experimentalParam20=1017 } ZSTD_cParameter;

typedef struct {
diff --git a/lib/zstd.h b/lib/zstd.h
index 22aca768c..d2d6795e4 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -218,7 +218,7 @@ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize)
 
 /*======  Compression helper functions  ======*/
 
-/* ZSTD_compressBound() :
+/*! ZSTD_compressBound() :
  * maximum compressed size in worst case single-pass scenario.
  * When invoking `ZSTD_compress()`, or any other one-pass compression function,
  * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)

From b3035b36c631614e32707cce0ab04c72c79c49a7 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 5 Nov 2024 00:09:13 -0800
Subject: [PATCH 453/937] blind fix for QNX

following notification from @rainbowball.
fix #4186.

Note: there is currently no QNX compilation test in CI
so this is a "blind" fix,
and this target can be silently broken again in the future.
---
 programs/util.h | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/programs/util.h b/programs/util.h
index 571d39421..ec8139684 100644
--- a/programs/util.h
+++ b/programs/util.h
@@ -11,23 +11,18 @@
 #ifndef UTIL_H_MODULE
 #define UTIL_H_MODULE
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
 /*-****************************************
 *  Dependencies
 ******************************************/
 #include "platform.h"     /* PLATFORM_POSIX_VERSION, ZSTD_NANOSLEEP_SUPPORT, ZSTD_SETPRIORITY_SUPPORT */
 #include        /* size_t, ptrdiff_t */
+#include         /* FILE */
 #include     /* stat, utime */
 #include      /* stat, chmod */
 #include "../lib/common/mem.h"          /* U64 */
 
-
 /*-************************************************************
-* Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
+*  Fix fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
 ***************************************************************/
 #if defined(_MSC_VER) && (_MSC_VER >= 1400)
 #  define UTIL_fseek _fseeki64
@@ -39,7 +34,6 @@ extern "C" {
 #  define UTIL_fseek fseek
 #endif
 
-
 /*-*************************************************
 *  Sleep & priority functions: Windows - Posix - others
 ***************************************************/
@@ -88,6 +82,10 @@ extern "C" {
 #endif
 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*-****************************************
 *  Console log
 ******************************************/

From d0fe334c8552edb764b853854037697c6710fa64 Mon Sep 17 00:00:00 2001
From: Lukas Oberhuber 
Date: Fri, 8 Nov 2024 00:08:33 +0000
Subject: [PATCH 454/937] cmake: Fix #4038 MacOS target older OS and SDK
 versions

This fix ensures that when `MACOSX_DEPLOYMENT_TARGET` and `SDKROOT` are set, they are respected when building the libraries and executables.
---
 Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/Makefile b/Makefile
index 95d45afb4..e80505b7f 100644
--- a/Makefile
+++ b/Makefile
@@ -200,9 +200,9 @@ travis-install:
 .PHONY: clangbuild-darwin-fat
 clangbuild-darwin-fat: clean
 	clang -v
-	CXX=clang++ CC=clang CFLAGS="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch arm64" $(MAKE) zstd-release
+	CXX=clang++ CC=clang CFLAGS+="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch arm64" $(MAKE) zstd-release
 	mv programs/zstd programs/zstd_arm64
-	CXX=clang++ CC=clang CFLAGS="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch x86_64" $(MAKE) zstd-release
+	CXX=clang++ CC=clang CFLAGS+="-Werror -Wconversion -Wno-sign-conversion -Wdocumentation -arch x86_64" $(MAKE) zstd-release
 	mv programs/zstd programs/zstd_x64
 	lipo -create programs/zstd_x64 programs/zstd_arm64 -output programs/zstd
 

From 2d1bbc37ebf4cbf48a2f107a3816f3e137fb5d49 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 11 Nov 2024 05:27:06 +0000
Subject: [PATCH 455/937] Bump github/codeql-action from 3.26.2 to 3.27.1

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.26.2 to 3.27.1.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/429e1977040da7a23b6822b13c129cd1ba93dbb2...4f3212b61783c3c68e8309a0f18a699764811cda)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/scorecards.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index ccd7956a5..0ae40d859 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -59,6 +59,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@429e1977040da7a23b6822b13c129cd1ba93dbb2 # tag=v3.26.2
+        uses: github/codeql-action/upload-sarif@4f3212b61783c3c68e8309a0f18a699764811cda # tag=v3.27.1
         with:
           sarif_file: results.sarif

From a9d279c97c76f3d5018f96fd4f65b28cb501e3ad Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 18 Nov 2024 05:12:44 +0000
Subject: [PATCH 456/937] Bump msys2/setup-msys2 from 2.24.1 to 2.25.0

Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.24.1 to 2.25.0.
- [Release notes](https://github.com/msys2/setup-msys2/releases)
- [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md)
- [Commits](https://github.com/msys2/setup-msys2/compare/ddf331adaebd714795f1042345e6ca57bd66cea8...c52d1fa9c7492275e60fe763540fb601f5f232a1)

---
updated-dependencies:
- dependency-name: msys2/setup-msys2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/dev-short-tests.yml   | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index fa603e401..043f42356 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -263,7 +263,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
-    - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1
+    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
       with:
         msystem: MINGW64
         install: make
diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 99aa166c9..5e459aabf 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -499,7 +499,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
-    - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1
+    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
       with:
         msystem: ${{ matrix.msystem }}
         install: make diffutils
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index ff81b504a..0524d5f63 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -24,7 +24,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # tag=v2.24.1
+    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
       with:
         msystem: ${{ matrix.msystem }}
         install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc

From 194062a4e73fef16e29e9175426fe1a3b9b23a73 Mon Sep 17 00:00:00 2001
From: Dimitrios Apostolou 
Date: Wed, 20 Nov 2024 16:11:17 +0100
Subject: [PATCH 457/937] Fix printing of filesize if >4GB

---
 programs/zstdcli.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 8f94352fe..90e090b58 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -696,7 +696,7 @@ static void printDefaultCParams(const char* filename, const char* dictFileName,
     unsigned long long fileSize = UTIL_getFileSize(filename);
     const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
     const ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
-    if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%u bytes)\n", filename, (unsigned)fileSize);
+    if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%llu bytes)\n", filename, fileSize);
     else DISPLAY("%s (src size unknown)\n", filename);
     DISPLAY(" - windowLog     : %u\n", cParams.windowLog);
     DISPLAY(" - chainLog      : %u\n", cParams.chainLog);

From 10beb7cb53ba328722d82c271d7b450b97869c92 Mon Sep 17 00:00:00 2001
From: nhz2 
Date: Sun, 24 Nov 2024 19:05:15 -0500
Subject: [PATCH 458/937] Fix typo in ZSTD_compressBound docs

---
 lib/zstd.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/zstd.h b/lib/zstd.h
index d2d6795e4..a78b6db45 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -224,7 +224,7 @@ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize)
  * it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
  * as it eliminates one potential failure scenario,
  * aka not enough room in dst buffer to write the compressed frame.
- * Note : ZSTD_compressBound() itself can fail, if @srcSize > ZSTD_MAX_INPUT_SIZE .
+ * Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE .
  *        In which case, ZSTD_compressBound() will return an error code
  *        which can be tested using ZSTD_isError().
  *

From b683c0dbe278f71e371376847deebd44fdcf392f Mon Sep 17 00:00:00 2001
From: Robert Rose 
Date: Sun, 24 Nov 2024 23:36:53 +0100
Subject: [PATCH 459/937] prevent possible segfault when creating seek table

Add a check whether the seek table of a `ZSTD_seekable` is initialized
before creating a new seek table from it. Return `NULL`, if the check
fails.
---
 contrib/seekable_format/zstdseek_decompress.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/contrib/seekable_format/zstdseek_decompress.c b/contrib/seekable_format/zstdseek_decompress.c
index 4fefc5f2e..5ee6e0541 100644
--- a/contrib/seekable_format/zstdseek_decompress.c
+++ b/contrib/seekable_format/zstdseek_decompress.c
@@ -252,6 +252,8 @@ size_t ZSTD_seekable_free(ZSTD_seekable* zs)
 
 ZSTD_seekTable* ZSTD_seekTable_create_fromSeekable(const ZSTD_seekable* zs)
 {
+    assert(zs != NULL);
+    if (zs->seekTable.entries == NULL) return NULL;
     ZSTD_seekTable* const st = (ZSTD_seekTable*)malloc(sizeof(ZSTD_seekTable));
     if (st==NULL) return NULL;
 

From fcf88ae39b560f8605f8e7c56e243cb1a3a98e5c Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Tue, 26 Nov 2024 11:15:39 +0100
Subject: [PATCH 460/937] Fix new typos found by codespell

---
 doc/zstd_compression_format.md | 2 +-
 lib/compress/hist.h            | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md
index 78279ce71..a2bf20cbc 100644
--- a/doc/zstd_compression_format.md
+++ b/doc/zstd_compression_format.md
@@ -1120,7 +1120,7 @@ For the purpose of counting total allocated probability points, it counts as one
 
 Symbols probabilities are read one by one, in order.
 After each probability is decoded, the total nb of probability points is updated.
-This is used to dermine how many bits must be read to decode the probability of next symbol.
+This is used to determine how many bits must be read to decode the probability of next symbol.
 
 When a symbol has a __probability__ of `zero` (decoded from reading a Value `1`),
 it is followed by a 2-bits repeat flag.
diff --git a/lib/compress/hist.h b/lib/compress/hist.h
index e6e39d348..bea2a9ebf 100644
--- a/lib/compress/hist.h
+++ b/lib/compress/hist.h
@@ -75,7 +75,7 @@ unsigned HIST_count_simple(unsigned* count, unsigned* maxSymbolValuePtr,
                            const void* src, size_t srcSize);
 
 /*! HIST_add() :
- *  Lowest level: just add nb of occurences of characters from @src into @count.
+ *  Lowest level: just add nb of occurrences of characters from @src into @count.
  *  @count is not reset. @count array is presumed large enough (i.e. 1 KB).
  @  This function does not need any additional stack memory.
  */

From 5e0a83ec255a0f4bb6a3cf8c4abcae46bfc2c3c5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=83=91=E8=8B=8F=E6=B3=A2=20=28Super=20Zheng=29?=
 
Date: Wed, 7 Aug 2024 11:22:50 +0800
Subject: [PATCH 461/937] Disallow 32-bit mode in clang section

Fix register %rbx is only available in 64-bit mode
---
 lib/common/cpu.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/common/cpu.h b/lib/common/cpu.h
index d9cdf8feb..3f15d560f 100644
--- a/lib/common/cpu.h
+++ b/lib/common/cpu.h
@@ -35,7 +35,7 @@ MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) {
     U32 f7b = 0;
     U32 f7c = 0;
 #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
-#if !defined(__clang__) || __clang_major__ >= 16
+#if !defined(_M_X64) || !defined(__clang__) || __clang_major__ >= 16
     int reg[4];
     __cpuid((int*)reg, 0);
     {

From c254ea097b017cac8f9b33856370afb729048035 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 9 Dec 2024 05:38:13 +0000
Subject: [PATCH 462/937] Bump msys2/setup-msys2 from 2.25.0 to 2.26.0

Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.25.0 to 2.26.0.
- [Release notes](https://github.com/msys2/setup-msys2/releases)
- [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md)
- [Commits](https://github.com/msys2/setup-msys2/compare/c52d1fa9c7492275e60fe763540fb601f5f232a1...d44ca8e88d8b43d56cf5670f91747359d5537f97)

---
updated-dependencies:
- dependency-name: msys2/setup-msys2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dev-long-tests.yml    | 2 +-
 .github/workflows/dev-short-tests.yml   | 2 +-
 .github/workflows/windows-artifacts.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 043f42356..75c6f6653 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -263,7 +263,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
-    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
+    - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0
       with:
         msystem: MINGW64
         install: make
diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml
index 5e459aabf..7ed068d6e 100644
--- a/.github/workflows/dev-short-tests.yml
+++ b/.github/workflows/dev-short-tests.yml
@@ -499,7 +499,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
-    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
+    - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0
       with:
         msystem: ${{ matrix.msystem }}
         install: make diffutils
diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml
index 0524d5f63..35999476e 100644
--- a/.github/workflows/windows-artifacts.yml
+++ b/.github/workflows/windows-artifacts.yml
@@ -24,7 +24,7 @@ jobs:
         shell: msys2 {0}
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3
-    - uses: msys2/setup-msys2@c52d1fa9c7492275e60fe763540fb601f5f232a1 # tag=v2.25.0
+    - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0
       with:
         msystem: ${{ matrix.msystem }}
         install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc

From e190e7944e42309a60b31c9d025c877219e7f878 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Mon, 9 Dec 2024 10:53:38 -0800
Subject: [PATCH 463/937] Update cmake minimum requirement to 3.10

CMake warns on the current minimum requirement (3.5). Update to 3.10.
This means support is still available for the default on Ubuntu 18.04, which
exited LTS standard in April of 2023.
[draft]
---
 build/cmake/CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt
index 399b818fc..b43671cc2 100644
--- a/build/cmake/CMakeLists.txt
+++ b/build/cmake/CMakeLists.txt
@@ -7,7 +7,7 @@
 # in the COPYING file in the root directory of this source tree).
 # ################################################################
 
-cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
+cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
 
 # As of 2018-12-26 ZSTD has been validated to build with cmake version 3.13.2 new policies.
 # Set and use the newest cmake policies that are validated to work

From 4a4786bef0b5b4b4fb190de6816b4d9df503a5d8 Mon Sep 17 00:00:00 2001
From: Diego Nieto Cid 
Date: Tue, 10 Dec 2024 10:20:32 -0300
Subject: [PATCH 464/937] tests: fix non-regular file test on GNU/Hurd

Since commit b21b03ca6 [1] the behaviour of writes to /dev/zero has been
fixed and now the non-regular file removal test no longer needs to be
done on /dev/random (which no longer works as random is not writable now).

[1] https://git.savannah.gnu.org/cgit/hurd/hurd.git/commit/?id=b21b03ca624b89caeedfe58430cea4b40317d39f
---
 tests/playTests.sh | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/tests/playTests.sh b/tests/playTests.sh
index 026490051..692e93e89 100755
--- a/tests/playTests.sh
+++ b/tests/playTests.sh
@@ -109,10 +109,7 @@ isTerminal=${isTerminal:-$detectedTerminal}
 
 isWindows=false
 INTOVOID="/dev/null"
-case "$UNAME" in
-  GNU) DEVDEVICE="/dev/random" ;;
-  *) DEVDEVICE="/dev/zero" ;;
-esac
+DEVDEVICE="/dev/zero"
 case "$OS" in
   Windows*)
     isWindows=true

From 17beeb5d1a978cb7775d37ee5f2b184368262ef5 Mon Sep 17 00:00:00 2001
From: daniellerozenblit <48103643+daniellerozenblit@users.noreply.github.com>
Date: Thu, 12 Dec 2024 13:09:29 -0500
Subject: [PATCH 465/937] Change CLI to employ multithreading by default
 (#4211)

* Change CLI to employ multithreading by default

* Document changes to benchmarking, print number of threads for display level >= 4, and add lower bound of 1 for the default number of threads
---
 programs/fileio_common.h | 11 ++++----
 programs/zstd.1.md       |  5 +++-
 programs/zstdcli.c       | 56 +++++++++++++++++++++-------------------
 3 files changed, 39 insertions(+), 33 deletions(-)

diff --git a/programs/fileio_common.h b/programs/fileio_common.h
index 55491b8e3..7a014ee4b 100644
--- a/programs/fileio_common.h
+++ b/programs/fileio_common.h
@@ -28,11 +28,14 @@ extern "C" {
 #define GB *(1U<<30)
 #undef MAX
 #define MAX(a,b) ((a)>(b) ? (a) : (b))
+#undef MIN  /* in case it would be already defined */
+#define MIN(a,b)    ((a) < (b) ? (a) : (b))
 
 extern FIO_display_prefs_t g_display_prefs;
 
-#define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
-#define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
+#define DISPLAY_F(f, ...)    fprintf((f), __VA_ARGS__)
+#define DISPLAYOUT(...)      DISPLAY_F(stdout, __VA_ARGS__)
+#define DISPLAY(...)         DISPLAY_F(stderr, __VA_ARGS__)
 #define DISPLAYLEVEL(l, ...) { if (g_display_prefs.displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
 
 extern UTIL_time_t g_displayClock;
@@ -56,10 +59,6 @@ extern UTIL_time_t g_displayClock;
 #define DISPLAYUPDATE_PROGRESS(...) { if (SHOULD_DISPLAY_PROGRESS()) { DISPLAYUPDATE(1, __VA_ARGS__); }}
 #define DISPLAY_SUMMARY(...) { if (SHOULD_DISPLAY_SUMMARY()) { DISPLAYLEVEL(1, __VA_ARGS__); } }
 
-#undef MIN  /* in case it would be already defined */
-#define MIN(a,b)    ((a) < (b) ? (a) : (b))
-
-
 #define EXM_THROW(error, ...)                                             \
 {                                                                         \
     DISPLAYLEVEL(1, "zstd: ");                                            \
diff --git a/programs/zstd.1.md b/programs/zstd.1.md
index fabf8d6fc..b4e848640 100644
--- a/programs/zstd.1.md
+++ b/programs/zstd.1.md
@@ -343,7 +343,7 @@ If the value of `ZSTD_CLEVEL` is not a valid integer, it will be ignored with a
 
 `ZSTD_NBTHREADS` can be used to set the number of threads `zstd` will attempt to use during compression.
 If the value of `ZSTD_NBTHREADS` is not a valid unsigned integer, it will be ignored with a warning message.
-`ZSTD_NBTHREADS` has a default value of (`1`), and is capped at ZSTDMT_NBWORKERS_MAX==200.
+`ZSTD_NBTHREADS` has a default value of `max(1, min(4, nbCores/4))`, and is capped at ZSTDMT_NBWORKERS_MAX==200.
 `zstd` must be compiled with multithread support for this variable to have any effect.
 
 They can both be overridden by corresponding command line arguments:
@@ -664,9 +664,12 @@ BENCHMARK
 The `zstd` CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer's performance.
 `zstd -b [FILE(s)]` will benchmark `zstd` for both compression and decompression using default compression level.
 Note that results are very dependent on the content being compressed.
+
 It's possible to pass multiple files to the benchmark, and even a directory with `-r DIRECTORY`.
 When no `FILE` is provided, the benchmark will use a procedurally generated `lorem ipsum` text.
 
+Benchmarking will employ `max(1, min(4, nbCores/4))` worker threads by default in order to match the behavior of the normal CLI I/O.
+
 * `-b#`:
     benchmark file(s) using compression level #
 * `-e#`:
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 90e090b58..024552d52 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -8,22 +8,6 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
-
-/*-************************************
-*  Tuning parameters
-**************************************/
-#ifndef ZSTDCLI_CLEVEL_DEFAULT
-#  define ZSTDCLI_CLEVEL_DEFAULT 3
-#endif
-
-#ifndef ZSTDCLI_CLEVEL_MAX
-#  define ZSTDCLI_CLEVEL_MAX 19   /* without using --ultra */
-#endif
-
-#ifndef ZSTDCLI_NBTHREADS_DEFAULT
-#  define ZSTDCLI_NBTHREADS_DEFAULT 1
-#endif
-
 /*-************************************
 *  Dependencies
 **************************************/
@@ -46,6 +30,23 @@
 #endif
 #include "../lib/zstd.h"  /* ZSTD_VERSION_STRING, ZSTD_minCLevel, ZSTD_maxCLevel */
 #include "fileio_asyncio.h"
+#include "fileio_common.h"
+
+/*-************************************
+*  Tuning parameters
+**************************************/
+#ifndef ZSTDCLI_CLEVEL_DEFAULT
+#  define ZSTDCLI_CLEVEL_DEFAULT 3
+#endif
+
+#ifndef ZSTDCLI_CLEVEL_MAX
+#  define ZSTDCLI_CLEVEL_MAX 19   /* without using --ultra */
+#endif
+
+#ifndef ZSTDCLI_NBTHREADS_DEFAULT
+#define ZSTDCLI_NBTHREADS_DEFAULT MAX(1, MIN(4, UTIL_countLogicalCores() / 4))
+#endif
+
 
 
 /*-************************************
@@ -99,9 +100,7 @@ typedef enum { cover, fastCover, legacy } dictType;
 /*-************************************
 *  Display Macros
 **************************************/
-#define DISPLAY_F(f, ...)    fprintf((f), __VA_ARGS__)
-#define DISPLAYOUT(...)      DISPLAY_F(stdout, __VA_ARGS__)
-#define DISPLAY(...)         DISPLAY_F(stderr, __VA_ARGS__)
+#undef DISPLAYLEVEL
 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
 static int g_displayLevel = DISPLAY_LEVEL_DEFAULT;   /* 0 : no display,  1: errors,  2 : + result + interaction + warnings,  3 : + progression,  4 : + information */
 
@@ -760,7 +759,7 @@ static int init_cLevel(void) {
 }
 
 #ifdef ZSTD_MULTITHREAD
-static unsigned init_nbThreads(void) {
+static unsigned default_nbThreads(void) {
     const char* const env = getenv(ENV_NBTHREADS);
     if (env != NULL) {
         const char* ptr = env;
@@ -855,7 +854,7 @@ int main(int argCount, const char* argv[])
     ZSTD_paramSwitch_e mmapDict=ZSTD_ps_auto;
     ZSTD_paramSwitch_e useRowMatchFinder = ZSTD_ps_auto;
     FIO_compressionType_t cType = FIO_zstdCompression;
-    unsigned nbWorkers = 0;
+    int nbWorkers = -1; /* -1 means unset */
     double compressibility = -1.0;  /* lorem ipsum generator */
     unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
     size_t blockSize = 0;
@@ -896,7 +895,6 @@ int main(int argCount, const char* argv[])
 #endif
     ZSTD_paramSwitch_e literalCompressionMode = ZSTD_ps_auto;
 
-
     /* init */
     checkLibVersion();
     (void)recursive; (void)cLevelLast;    /* not used when ZSTD_NOBENCH set */
@@ -904,9 +902,6 @@ int main(int argCount, const char* argv[])
     assert(argCount >= 1);
     if ((filenames==NULL) || (file_of_names==NULL)) { DISPLAYLEVEL(1, "zstd: allocation error \n"); exit(1); }
     programName = lastNameFromPath(programName);
-#ifdef ZSTD_MULTITHREAD
-    nbWorkers = init_nbThreads();
-#endif
 
     /* preset behaviors */
     if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0;
@@ -1298,7 +1293,7 @@ int main(int argCount, const char* argv[])
     DISPLAYLEVEL(3, WELCOME_MESSAGE);
 
 #ifdef ZSTD_MULTITHREAD
-    if ((operation==zom_decompress) && (!singleThread) && (nbWorkers > 1)) {
+    if ((operation==zom_decompress) && (nbWorkers > 1)) {
         DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n");
     }
     if ((nbWorkers==0) && (!singleThread)) {
@@ -1311,6 +1306,15 @@ int main(int argCount, const char* argv[])
             DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
         }
     }
+    /* Resolve to default if nbWorkers is still unset */
+    if (nbWorkers == -1) {
+      if (operation == zom_decompress) {
+        nbWorkers = 1;
+      } else {
+        nbWorkers = default_nbThreads();
+      }
+    }
+    DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers);
 #else
     (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores;
 #endif

From 1198a582d3c931c7faba149cbf1b48910da3f256 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 12 Dec 2024 11:39:40 -0800
Subject: [PATCH 466/937] Update VERSION_LESS usage to VERSION_GREATER_THAN

---
 build/cmake/CMakeModules/AddZstdCompilationFlags.cmake | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake
index 6f55450c3..153c51bae 100644
--- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake
+++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake
@@ -1,11 +1,10 @@
 include(CheckCXXCompilerFlag)
 include(CheckCCompilerFlag)
-# VERSION_GREATER_EQUAL requires CMake 3.7 or later.
-# https://cmake.org/cmake/help/latest/command/if.html#version-greater-equal
-if (CMAKE_VERSION VERSION_LESS 3.18)
-    set(ZSTD_HAVE_CHECK_LINKER_FLAG false)
-else ()
+
+if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.18)
     set(ZSTD_HAVE_CHECK_LINKER_FLAG true)
+else ()
+    set(ZSTD_HAVE_CHECK_LINKER_FLAG false)
 endif ()
 if (ZSTD_HAVE_CHECK_LINKER_FLAG)
     include(CheckLinkerFlag)

From 7236e05b0a4f5e9c9435661fe7b2bfedeba29ec4 Mon Sep 17 00:00:00 2001
From: Elliot Gorokhovsky 
Date: Tue, 12 Mar 2024 08:26:01 -0700
Subject: [PATCH 467/937] Revert "Pin tsan and msan CI jobs to ubuntu-20.04
 (#3945)"

This reverts commit ee6acaf26bbf842837513087c91776b83d4d9560.
---
 .github/workflows/dev-long-tests.yml | 34 ++++++++++++++--------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml
index 75c6f6653..d5e476b4c 100644
--- a/.github/workflows/dev-long-tests.yml
+++ b/.github/workflows/dev-long-tests.yml
@@ -61,14 +61,14 @@ jobs:
       run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest
 
   tsan-zstreamtest:
-    runs-on: ubuntu-20.04
+    runs-on: ubuntu-latest
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer zstreamtest
       run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream
 
   ubsan-zstreamtest:
-    runs-on: ubuntu-20.04
+    runs-on: ubuntu-latest
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: undefined behavior sanitizer zstreamtest
@@ -76,7 +76,7 @@ jobs:
 
   # lasts ~15mn
   tsan-fuzztest:
-    runs-on: ubuntu-20.04
+    runs-on: ubuntu-latest
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: thread sanitizer fuzztest
@@ -95,7 +95,7 @@ jobs:
 
   # lasts ~23mn
   gcc-8-asan-ubsan-testzstd:
-    runs-on: ubuntu-20.04
+    runs-on: ubuntu-latest
     steps:
     - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1
     - name: gcc-8 + ASan + UBSan + Test Zstd
@@ -107,14 +107,14 @@ jobs:
         CC=gcc-8 make -j uasan-test-zstd 
Date: Sat, 14 Dec 2024 11:57:14 -0800
Subject: [PATCH 468/937] minor: more accurate parameter

just pass ldm_bucketLog, instead of the entire ldm* state
---
 lib/compress/zstd_ldm.c | 25 +++++++++++++------------
 1 file changed, 13 insertions(+), 12 deletions(-)

diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c
index 17c069fe1..e06431374 100644
--- a/lib/compress/zstd_ldm.c
+++ b/lib/compress/zstd_ldm.c
@@ -170,22 +170,22 @@ size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
 /** ZSTD_ldm_getBucket() :
  *  Returns a pointer to the start of the bucket associated with hash. */
 static ldmEntry_t* ZSTD_ldm_getBucket(
-        ldmState_t* ldmState, size_t hash, ldmParams_t const ldmParams)
+        const ldmState_t* ldmState, size_t hash, U32 const bucketSizeLog)
 {
-    return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
+    return ldmState->hashTable + (hash << bucketSizeLog);
 }
 
 /** ZSTD_ldm_insertEntry() :
  *  Insert the entry with corresponding hash into the hash table */
 static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
                                  size_t const hash, const ldmEntry_t entry,
-                                 ldmParams_t const ldmParams)
+                                 U32 const bucketSizeLog)
 {
     BYTE* const pOffset = ldmState->bucketOffsets + hash;
     unsigned const offset = *pOffset;
 
-    *(ZSTD_ldm_getBucket(ldmState, hash, ldmParams) + offset) = entry;
-    *pOffset = (BYTE)((offset + 1) & ((1u << ldmParams.bucketSizeLog) - 1));
+    *(ZSTD_ldm_getBucket(ldmState, hash, bucketSizeLog) + offset) = entry;
+    *pOffset = (BYTE)((offset + 1) & ((1u << bucketSizeLog) - 1));
 
 }
 
@@ -273,7 +273,8 @@ void ZSTD_ldm_fillHashTable(
             const BYTE* iend, ldmParams_t const* params)
 {
     U32 const minMatchLength = params->minMatchLength;
-    U32 const hBits = params->hashLog - params->bucketSizeLog;
+    U32 const bucketSizeLog = params->bucketSizeLog;
+    U32 const hBits = params->hashLog - bucketSizeLog;
     BYTE const* const base = ldmState->window.base;
     BYTE const* const istart = ip;
     ldmRollingHashState_t hashState;
@@ -288,7 +289,7 @@ void ZSTD_ldm_fillHashTable(
         unsigned n;
 
         numSplits = 0;
-        hashed = ZSTD_ldm_gear_feed(&hashState, ip, iend - ip, splits, &numSplits);
+        hashed = ZSTD_ldm_gear_feed(&hashState, ip, (size_t)(iend - ip), splits, &numSplits);
 
         for (n = 0; n < numSplits; n++) {
             if (ip + splits[n] >= istart + minMatchLength) {
@@ -299,7 +300,7 @@ void ZSTD_ldm_fillHashTable(
 
                 entry.offset = (U32)(split - base);
                 entry.checksum = (U32)(xxhash >> 32);
-                ZSTD_ldm_insertEntry(ldmState, hash, entry, *params);
+                ZSTD_ldm_insertEntry(ldmState, hash, entry, params->bucketSizeLog);
             }
         }
 
@@ -379,7 +380,7 @@ size_t ZSTD_ldm_generateSequences_internal(
             candidates[n].split = split;
             candidates[n].hash = hash;
             candidates[n].checksum = (U32)(xxhash >> 32);
-            candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, *params);
+            candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, params->bucketSizeLog);
             PREFETCH_L1(candidates[n].bucket);
         }
 
@@ -402,7 +403,7 @@ size_t ZSTD_ldm_generateSequences_internal(
              * the previous one, we merely register it in the hash table and
              * move on */
             if (split < anchor) {
-                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
+                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
                 continue;
             }
 
@@ -449,7 +450,7 @@ size_t ZSTD_ldm_generateSequences_internal(
             /* No match found -- insert an entry into the hash table
              * and process the next candidate match */
             if (bestEntry == NULL) {
-                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
+                ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
                 continue;
             }
 
@@ -470,7 +471,7 @@ size_t ZSTD_ldm_generateSequences_internal(
 
             /* Insert the current entry into the hash table --- it must be
              * done after the previous block to avoid clobbering bestEntry */
-            ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
+            ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
 
             anchor = split + forwardMatchLength;
 

From fc726da7747b159520de2edb0febab30342d2744 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Tue, 17 Dec 2024 17:55:07 -0800
Subject: [PATCH 469/937] Move #includes out of `extern "C"` blocks

Do some include shuffling for `**.h` files within lib, programs, tests, and zlibWrapper.
`lib/legacy` and `lib/deprecated` are untouched.
`#include`s within `extern "C"` blocks in .cpp files are untouched.

todo: shuffling for `xxhash.h`
---
 contrib/seekable_format/zstd_seekable.h |  6 +++---
 lib/common/bitstream.h                  |  8 ++++----
 lib/common/debug.h                      |  9 ++++-----
 lib/common/error_private.h              |  8 +++-----
 lib/common/fse.h                        | 16 +++++++--------
 lib/common/huf.h                        |  7 +++----
 lib/common/mem.h                        |  8 ++++----
 lib/common/pool.h                       |  8 ++++----
 lib/common/threading.h                  | 27 +++++++++++++++++++++----
 lib/common/zstd_trace.h                 |  4 ++--
 lib/compress/zstd_double_fast.h         |  6 +++---
 lib/compress/zstd_fast.h                |  6 +++---
 lib/compress/zstd_lazy.h                |  4 ++--
 lib/compress/zstd_ldm.h                 |  6 +++---
 lib/compress/zstd_opt.h                 |  4 ++--
 lib/compress/zstdmt_compress.h          | 11 +++++-----
 lib/zdict.h                             |  8 ++++----
 lib/zstd.h                              | 15 ++++++++------
 programs/benchfn.h                      |  8 ++++----
 programs/benchzstd.h                    |  8 ++++----
 programs/fileio_asyncio.h               |  8 ++++----
 programs/fileio_common.h                | 16 ++++++++++-----
 programs/platform.h                     | 21 +++++++++----------
 programs/timefn.h                       | 11 +++++-----
 programs/util.c                         |  9 ---------
 programs/util.h                         |  4 +++-
 zlibWrapper/zstd_zlibwrapper.h          | 10 ++++-----
 27 files changed, 135 insertions(+), 121 deletions(-)

diff --git a/contrib/seekable_format/zstd_seekable.h b/contrib/seekable_format/zstd_seekable.h
index a0e5e3573..b1f83d0e0 100644
--- a/contrib/seekable_format/zstd_seekable.h
+++ b/contrib/seekable_format/zstd_seekable.h
@@ -1,13 +1,13 @@
 #ifndef SEEKABLE_H
 #define SEEKABLE_H
 
+#include 
+#include "zstd.h"   /* ZSTDLIB_API */
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include 
-#include "zstd.h"   /* ZSTDLIB_API */
-
 
 #define ZSTD_seekTableFooterSize 9
 
diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h
index 676044989..bce91e801 100644
--- a/lib/common/bitstream.h
+++ b/lib/common/bitstream.h
@@ -14,9 +14,6 @@
 #ifndef BITSTREAM_H_MODULE
 #define BITSTREAM_H_MODULE
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*
 *  This API consists of small unitary functions, which must be inlined for best performance.
 *  Since link-time-optimization is not available for all compilers,
@@ -32,7 +29,6 @@ extern "C" {
 #include "error_private.h"  /* error codes and messages */
 #include "bits.h"           /* ZSTD_highbit32 */
 
-
 /*=========================================
 *  Target specific
 =========================================*/
@@ -44,6 +40,10 @@ extern "C" {
 #  endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #define STREAM_ACCUMULATOR_MIN_32  25
 #define STREAM_ACCUMULATOR_MIN_64  57
 #define STREAM_ACCUMULATOR_MIN    ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
diff --git a/lib/common/debug.h b/lib/common/debug.h
index a16b69e57..8ef37a908 100644
--- a/lib/common/debug.h
+++ b/lib/common/debug.h
@@ -32,10 +32,6 @@
 #ifndef DEBUG_H_12987983217
 #define DEBUG_H_12987983217
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 
 /* static assert is triggered at compile time, leaving no runtime artefact.
  * static assert only works with compile-time constants.
@@ -75,9 +71,12 @@ extern "C" {
 #  endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #if (DEBUGLEVEL>=2)
 #  define ZSTD_DEPS_NEED_IO
-#  include "zstd_deps.h"
 extern int g_debuglevel; /* the variable is only declared,
                             it actually lives in debug.c,
                             and is shared by the whole process.
diff --git a/lib/common/error_private.h b/lib/common/error_private.h
index 0156010c7..06233aaa8 100644
--- a/lib/common/error_private.h
+++ b/lib/common/error_private.h
@@ -13,11 +13,6 @@
 #ifndef ERROR_H_MODULE
 #define ERROR_H_MODULE
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
 /* ****************************************
 *  Dependencies
 ******************************************/
@@ -26,6 +21,9 @@ extern "C" {
 #include "debug.h"
 #include "zstd_deps.h"       /* size_t */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 
 /* ****************************************
 *  Compiler-specific
diff --git a/lib/common/fse.h b/lib/common/fse.h
index 2ae128e60..4c41b06ef 100644
--- a/lib/common/fse.h
+++ b/lib/common/fse.h
@@ -11,11 +11,6 @@
  * in the COPYING file in the root directory of this source tree).
  * You may select, at your option, one of the above-listed licenses.
 ****************************************************************** */
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef FSE_H
 #define FSE_H
 
@@ -25,6 +20,14 @@ extern "C" {
 ******************************************/
 #include "zstd_deps.h"    /* size_t, ptrdiff_t */
 
+#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
+#define FSE_H_FSE_STATIC_LINKING_ONLY
+#include "bitstream.h"
+#endif 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
 
 /*-*****************************************
 *  FSE_PUBLIC_API : control library symbols visibility
@@ -233,9 +236,6 @@ If there is an error, the function will return an error code, which can be teste
 #if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
 #define FSE_H_FSE_STATIC_LINKING_ONLY
 
-/* *** Dependency *** */
-#include "bitstream.h"
-
 
 /* *****************************************
 *  Static allocation
diff --git a/lib/common/huf.h b/lib/common/huf.h
index 99bf85d6f..bfcec4a81 100644
--- a/lib/common/huf.h
+++ b/lib/common/huf.h
@@ -12,10 +12,6 @@
  * You may select, at your option, one of the above-listed licenses.
 ****************************************************************** */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef HUF_H_298734234
 #define HUF_H_298734234
 
@@ -25,6 +21,9 @@ extern "C" {
 #define FSE_STATIC_LINKING_ONLY
 #include "fse.h"
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 
 /* ***   Tool functions *** */
 #define HUF_BLOCKSIZE_MAX (128 * 1024)   /**< maximum input size for a single block compressed with HUF_compress */
diff --git a/lib/common/mem.h b/lib/common/mem.h
index a02141c9d..1b0a946ad 100644
--- a/lib/common/mem.h
+++ b/lib/common/mem.h
@@ -11,10 +11,6 @@
 #ifndef MEM_H_MODULE
 #define MEM_H_MODULE
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-****************************************
 *  Dependencies
 ******************************************/
@@ -77,6 +73,10 @@ extern "C" {
 #endif
 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*-**************************************************************
 *  Memory I/O API
 *****************************************************************/
diff --git a/lib/common/pool.h b/lib/common/pool.h
index cca4de73a..d34082dc1 100644
--- a/lib/common/pool.h
+++ b/lib/common/pool.h
@@ -11,15 +11,15 @@
 #ifndef POOL_H
 #define POOL_H
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 
 #include "zstd_deps.h"
 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_customMem */
 #include "../zstd.h"
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 typedef struct POOL_ctx_s POOL_ctx;
 
 /*! POOL_create() :
diff --git a/lib/common/threading.h b/lib/common/threading.h
index fb5c1c878..25448548d 100644
--- a/lib/common/threading.h
+++ b/lib/common/threading.h
@@ -16,10 +16,6 @@
 
 #include "debug.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #if defined(ZSTD_MULTITHREAD) && defined(_WIN32)
 
 /**
@@ -60,6 +56,11 @@ extern "C" {
 #define ZSTD_pthread_cond_signal(a)     WakeConditionVariable((a))
 #define ZSTD_pthread_cond_broadcast(a)  WakeAllConditionVariable((a))
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* ZSTD_pthread_create() and ZSTD_pthread_join() */
 typedef HANDLE ZSTD_pthread_t;
 
@@ -73,10 +74,19 @@ int ZSTD_pthread_join(ZSTD_pthread_t thread);
  */
 
 
+#if defined (__cplusplus)
+}
+#endif
+
 #elif defined(ZSTD_MULTITHREAD)    /* posix assumed ; need a better detection method */
 /* ===   POSIX Systems   === */
 #  include 
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #if DEBUGLEVEL < 1
 
 #define ZSTD_pthread_mutex_t            pthread_mutex_t
@@ -123,9 +133,18 @@ int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond);
 
 #endif
 
+#if defined (__cplusplus)
+}
+#endif
+
 #else  /* ZSTD_MULTITHREAD not defined */
 /* No multithreading support */
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 typedef int ZSTD_pthread_mutex_t;
 #define ZSTD_pthread_mutex_init(a, b)   ((void)(a), (void)(b), 0)
 #define ZSTD_pthread_mutex_destroy(a)   ((void)(a))
diff --git a/lib/common/zstd_trace.h b/lib/common/zstd_trace.h
index 173d63fb1..b9187079c 100644
--- a/lib/common/zstd_trace.h
+++ b/lib/common/zstd_trace.h
@@ -11,12 +11,12 @@
 #ifndef ZSTD_TRACE_H
 #define ZSTD_TRACE_H
 
+#include 
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include 
-
 /* weak symbol support
  * For now, enable conservatively:
  * - Only GNUC
diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h
index ce6ed8c97..ae66f3142 100644
--- a/lib/compress/zstd_double_fast.h
+++ b/lib/compress/zstd_double_fast.h
@@ -11,13 +11,13 @@
 #ifndef ZSTD_DOUBLE_FAST_H
 #define ZSTD_DOUBLE_FAST_H
 
+#include "../common/mem.h"      /* U32 */
+#include "zstd_compress_internal.h"     /* ZSTD_CCtx, size_t */
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include "../common/mem.h"      /* U32 */
-#include "zstd_compress_internal.h"     /* ZSTD_CCtx, size_t */
-
 #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
 
 void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms,
diff --git a/lib/compress/zstd_fast.h b/lib/compress/zstd_fast.h
index 9e4236b47..f92cf35b9 100644
--- a/lib/compress/zstd_fast.h
+++ b/lib/compress/zstd_fast.h
@@ -11,13 +11,13 @@
 #ifndef ZSTD_FAST_H
 #define ZSTD_FAST_H
 
+#include "../common/mem.h"      /* U32 */
+#include "zstd_compress_internal.h"
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include "../common/mem.h"      /* U32 */
-#include "zstd_compress_internal.h"
-
 void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
                         void const* end, ZSTD_dictTableLoadMethod_e dtlm,
                         ZSTD_tableFillPurpose_e tfp);
diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h
index 3635813bd..bec17b124 100644
--- a/lib/compress/zstd_lazy.h
+++ b/lib/compress/zstd_lazy.h
@@ -11,12 +11,12 @@
 #ifndef ZSTD_LAZY_H
 #define ZSTD_LAZY_H
 
+#include "zstd_compress_internal.h"
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include "zstd_compress_internal.h"
-
 /**
  * Dedicated Dictionary Search Structure bucket log. In the
  * ZSTD_dedicatedDictSearch mode, the hashTable has
diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h
index f147021d2..847c2befb 100644
--- a/lib/compress/zstd_ldm.h
+++ b/lib/compress/zstd_ldm.h
@@ -11,13 +11,13 @@
 #ifndef ZSTD_LDM_H
 #define ZSTD_LDM_H
 
+#include "zstd_compress_internal.h"   /* ldmParams_t, U32 */
+#include "../zstd.h"   /* ZSTD_CCtx, size_t */
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include "zstd_compress_internal.h"   /* ldmParams_t, U32 */
-#include "../zstd.h"   /* ZSTD_CCtx, size_t */
-
 /*-*************************************
 *  Long distance matching
 ***************************************/
diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h
index d4e711315..7ce6fdae7 100644
--- a/lib/compress/zstd_opt.h
+++ b/lib/compress/zstd_opt.h
@@ -11,12 +11,12 @@
 #ifndef ZSTD_OPT_H
 #define ZSTD_OPT_H
 
+#include "zstd_compress_internal.h"
+
 #if defined (__cplusplus)
 extern "C" {
 #endif
 
-#include "zstd_compress_internal.h"
-
 #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
  || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
  || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
diff --git a/lib/compress/zstdmt_compress.h b/lib/compress/zstdmt_compress.h
index ed4dc0e99..9a58b5ad3 100644
--- a/lib/compress/zstdmt_compress.h
+++ b/lib/compress/zstdmt_compress.h
@@ -11,6 +11,11 @@
  #ifndef ZSTDMT_COMPRESS_H
  #define ZSTDMT_COMPRESS_H
 
+/* ===   Dependencies   === */
+#include "../common/zstd_deps.h"   /* size_t */
+#define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_parameters */
+#include "../zstd.h"            /* ZSTD_inBuffer, ZSTD_outBuffer, ZSTDLIB_API */
+
  #if defined (__cplusplus)
  extern "C" {
  #endif
@@ -25,12 +30,6 @@
  *        otherwise ZSTDMT_createCCtx*() will fail.
  */
 
-/* ===   Dependencies   === */
-#include "../common/zstd_deps.h"   /* size_t */
-#define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_parameters */
-#include "../zstd.h"            /* ZSTD_inBuffer, ZSTD_outBuffer, ZSTDLIB_API */
-
-
 /* ===   Constants   === */
 #ifndef ZSTDMT_NBWORKERS_MAX /* a different value can be selected at compile time */
 #  define ZSTDMT_NBWORKERS_MAX ((sizeof(void*)==4) /*32-bit*/ ? 64 : 256)
diff --git a/lib/zdict.h b/lib/zdict.h
index bcccf750e..340a9a24e 100644
--- a/lib/zdict.h
+++ b/lib/zdict.h
@@ -8,16 +8,16 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef ZSTD_ZDICT_H
 #define ZSTD_ZDICT_H
 
+
 /*======  Dependencies  ======*/
 #include   /* size_t */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 
 /* =====   ZDICTLIB_API : control library symbols visibility   ===== */
 #ifndef ZDICTLIB_VISIBLE
diff --git a/lib/zstd.h b/lib/zstd.h
index a78b6db45..7571f8069 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -7,16 +7,22 @@
  * in the COPYING file in the root directory of this source tree).
  * You may select, at your option, one of the above-listed licenses.
  */
-#if defined (__cplusplus)
-extern "C" {
-#endif
 
 #ifndef ZSTD_H_235446
 #define ZSTD_H_235446
 
+
 /* ======   Dependencies   ======*/
 #include    /* size_t */
 
+#include "zstd_errors.h" /* list of errors */
+#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
+#include    /* INT_MAX */
+#endif /* ZSTD_STATIC_LINKING_ONLY */
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
 
 /* =====   ZSTDLIB_API : control library symbols visibility   ===== */
 #ifndef ZSTDLIB_VISIBLE
@@ -240,7 +246,6 @@ ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed s
 
 
 /*======  Error helper functions  ======*/
-#include "zstd_errors.h" /* list of errors */
 /* ZSTD_isError() :
  * Most ZSTD_* functions returning a size_t value can be tested for error,
  * using ZSTD_isError().
@@ -1215,8 +1220,6 @@ ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
 
-#include    /* INT_MAX */
-
 /* This can be overridden externally to hide static symbols. */
 #ifndef ZSTDLIB_STATIC_API
 #  if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
diff --git a/programs/benchfn.h b/programs/benchfn.h
index 1bd93d135..3ba3a4f55 100644
--- a/programs/benchfn.h
+++ b/programs/benchfn.h
@@ -15,10 +15,6 @@
  * or detecting and returning an error
  */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef BENCH_FN_H_23876
 #define BENCH_FN_H_23876
 
@@ -26,6 +22,10 @@ extern "C" {
 #include    /* size_t */
 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* ====  Benchmark any function, iterated on a set of blocks  ==== */
 
 /* BMK_runTime_t: valid result return type */
diff --git a/programs/benchzstd.h b/programs/benchzstd.h
index 6388d4d58..7ea018b12 100644
--- a/programs/benchzstd.h
+++ b/programs/benchzstd.h
@@ -14,10 +14,6 @@
   * and display progress result and final summary
   */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef BENCH_ZSTD_H_3242387
 #define BENCH_ZSTD_H_3242387
 
@@ -27,6 +23,10 @@ extern "C" {
 #include "../lib/zstd.h"     /* ZSTD_compressionParameters */
 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* ===  Constants  === */
 
 #define MB_UNIT 1000000
diff --git a/programs/fileio_asyncio.h b/programs/fileio_asyncio.h
index feb25a3f9..1c30a73da 100644
--- a/programs/fileio_asyncio.h
+++ b/programs/fileio_asyncio.h
@@ -22,10 +22,6 @@
 #ifndef ZSTD_FILEIO_ASYNCIO_H
 #define ZSTD_FILEIO_ASYNCIO_H
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #include "../lib/common/mem.h"     /* U32, U64 */
 #include "fileio_types.h"
 #include "platform.h"
@@ -35,6 +31,10 @@ extern "C" {
 
 #define MAX_IO_JOBS          (10)
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 typedef struct {
     /* These struct fields should be set only on creation and not changed afterwards */
     POOL_ctx* threadPool;
diff --git a/programs/fileio_common.h b/programs/fileio_common.h
index 7a014ee4b..87f99cda9 100644
--- a/programs/fileio_common.h
+++ b/programs/fileio_common.h
@@ -11,15 +11,22 @@
 #ifndef ZSTD_FILEIO_COMMON_H
 #define ZSTD_FILEIO_COMMON_H
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #include "../lib/common/mem.h"     /* U32, U64 */
 #include "fileio_types.h"
 #include "platform.h"
 #include "timefn.h"     /* UTIL_getTime, UTIL_clockSpanMicro */
 
+#if !(defined(_MSC_VER) && _MSC_VER >= 1400) \
+    && !(!defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L)) \
+    && !(defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)) \
+    && (defined(_WIN32) && !defined(__DJGPP__))
+#   include 
+#endif
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*-*************************************
 *  Macros
 ***************************************/
@@ -89,7 +96,6 @@ extern UTIL_time_t g_displayClock;
 #   define LONG_SEEK fseeko64
 #   define LONG_TELL ftello64
 #elif defined(_WIN32) && !defined(__DJGPP__)
-#   include 
     static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
         LARGE_INTEGER off;
         DWORD method;
diff --git a/programs/platform.h b/programs/platform.h
index 4d2b9490e..05a26a564 100644
--- a/programs/platform.h
+++ b/programs/platform.h
@@ -11,12 +11,6 @@
 #ifndef PLATFORM_H_MODULE
 #define PLATFORM_H_MODULE
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
-
 /* **************************************
 *  Compiler Options
 ****************************************/
@@ -144,10 +138,20 @@ extern "C" {
 #  include       /* _isatty */
 #  include  /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
 #  include    /* FILE */
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 static __inline int IS_CONSOLE(FILE* stdStream) {
     DWORD dummy;
     return _isatty(_fileno(stdStream)) && GetConsoleMode((HANDLE)_get_osfhandle(_fileno(stdStream)), &dummy);
 }
+
+#if defined (__cplusplus)
+}
+#endif
+
 #else
 #  define IS_CONSOLE(stdStream) 0
 #endif
@@ -210,9 +214,4 @@ static __inline int IS_CONSOLE(FILE* stdStream) {
 #  endif
 #endif
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* PLATFORM_H_MODULE */
diff --git a/programs/timefn.h b/programs/timefn.h
index b814ff8d8..dc7463be3 100644
--- a/programs/timefn.h
+++ b/programs/timefn.h
@@ -11,12 +11,6 @@
 #ifndef TIME_FN_H_MODULE_287987
 #define TIME_FN_H_MODULE_287987
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
-
 /*-****************************************
 *  Types
 ******************************************/
@@ -32,6 +26,11 @@ extern "C" {
   typedef unsigned long long PTime;  /* does not support compilers without long long support */
 #endif
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* UTIL_time_t contains a nanosecond time counter.
  * The absolute value is not meaningful.
  * It's only valid to compute the difference between 2 measurements. */
diff --git a/programs/util.c b/programs/util.c
index 7f65f9373..065a35855 100644
--- a/programs/util.c
+++ b/programs/util.c
@@ -8,11 +8,6 @@
  * You may select, at your option, one of the above-listed licenses.
  */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
 /*-****************************************
 *  Dependencies
 ******************************************/
@@ -1646,7 +1641,3 @@ int UTIL_countLogicalCores(void)
 {
     return UTIL_countCores(1);
 }
-
-#if defined (__cplusplus)
-}
-#endif
diff --git a/programs/util.h b/programs/util.h
index ec8139684..5868f5eae 100644
--- a/programs/util.h
+++ b/programs/util.h
@@ -20,6 +20,9 @@
 #include     /* stat, utime */
 #include      /* stat, chmod */
 #include "../lib/common/mem.h"          /* U64 */
+#if not (defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__))
+#include 
+#endif
 
 /*-************************************************************
 *  Fix fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW
@@ -116,7 +119,6 @@ int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg, const
 #define STRDUP(s) _strdup(s)
 #else
 #define PATH_SEP '/'
-#include 
 #define STRDUP(s) strdup(s)
 #endif
 
diff --git a/zlibWrapper/zstd_zlibwrapper.h b/zlibWrapper/zstd_zlibwrapper.h
index 230bf8411..dae6787d3 100644
--- a/zlibWrapper/zstd_zlibwrapper.h
+++ b/zlibWrapper/zstd_zlibwrapper.h
@@ -11,11 +11,6 @@
 #ifndef ZSTD_ZLIBWRAPPER_H
 #define ZSTD_ZLIBWRAPPER_H
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
 #define ZLIB_CONST
 #define Z_PREFIX
 #define ZLIB_INTERNAL   /* disables gz*64 functions but fixes zlib 1.2.4 with Z_PREFIX */
@@ -29,6 +24,11 @@ extern "C" {
     #define _Z_OF OF
 #endif
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* returns a string with version of zstd library */
 const char * zstdVersion(void);
 

From 5222dd87cff5533a83938d0e54b724f675266bf6 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Tue, 17 Dec 2024 18:11:58 -0800
Subject: [PATCH 470/937] Oopsie with fse.h

---
 lib/common/fse.h | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)

diff --git a/lib/common/fse.h b/lib/common/fse.h
index 4c41b06ef..9f031f31f 100644
--- a/lib/common/fse.h
+++ b/lib/common/fse.h
@@ -20,11 +20,6 @@
 ******************************************/
 #include "zstd_deps.h"    /* size_t, ptrdiff_t */
 
-#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
-#define FSE_H_FSE_STATIC_LINKING_ONLY
-#include "bitstream.h"
-#endif 
-
 #if defined (__cplusplus)
 extern "C" {
 #endif
@@ -230,12 +225,16 @@ FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<
 If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
 */
 
+#if defined (__cplusplus)
+}
+#endif
+
 #endif  /* FSE_H */
 
 
 #if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
 #define FSE_H_FSE_STATIC_LINKING_ONLY
-
+#include "bitstream.h"
 
 /* *****************************************
 *  Static allocation
@@ -258,6 +257,10 @@ If there is an error, the function will return an error code, which can be teste
  *  FSE advanced API
  ***************************************** */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
 /**< same as FSE_optimalTableLog(), which used `minus==2` */
 
@@ -631,10 +634,8 @@ MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
 
 #define FSE_TABLESTEP(tableSize) (((tableSize)>>1) + ((tableSize)>>3) + 3)
 
-
-#endif /* FSE_STATIC_LINKING_ONLY */
-
-
 #if defined (__cplusplus)
 }
 #endif
+
+#endif /* FSE_STATIC_LINKING_ONLY */

From ded4c1ec18bf39db0ce6b4263ddf6daac6712e94 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Tue, 17 Dec 2024 18:18:02 -0800
Subject: [PATCH 471/937] Oopsie with util.h

---
 programs/util.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/programs/util.h b/programs/util.h
index 5868f5eae..93d6c807f 100644
--- a/programs/util.h
+++ b/programs/util.h
@@ -20,7 +20,7 @@
 #include     /* stat, utime */
 #include      /* stat, chmod */
 #include "../lib/common/mem.h"          /* U64 */
-#if not (defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__))
+#if !(defined(_MSC_VER) || defined(__MINGW32__) || defined (__MSVCRT__))
 #include 
 #endif
 

From fa5bfb603065e0f426c3ede2b5e239a13b69ea22 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Tue, 17 Dec 2024 18:34:04 -0800
Subject: [PATCH 472/937] Oopsie with zstd.h

---
 lib/zstd.h | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/lib/zstd.h b/lib/zstd.h
index 7571f8069..1ae47c2b6 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -1205,6 +1205,10 @@ ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
 ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
 ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 
+#if defined (__cplusplus)
+}
+#endif
+
 #endif  /* ZSTD_H_235446 */
 
 
@@ -1220,6 +1224,10 @@ ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 #if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
 #define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* This can be overridden externally to hide static symbols. */
 #ifndef ZSTDLIB_STATIC_API
 #  if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
@@ -3138,8 +3146,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_
 ZSTD_DEPRECATED("The block API is deprecated in favor of the normal compression API. See docs.")
 ZSTDLIB_STATIC_API size_t ZSTD_insertBlock    (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize);  /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */
 
-#endif   /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */
-
 #if defined (__cplusplus)
 }
 #endif
+
+#endif   /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */

From 58a7f4b869e02e02ab7e119f20fca9ea631dd83d Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Tue, 17 Dec 2024 18:37:33 -0800
Subject: [PATCH 473/937] Oopsie with threading.h

---
 lib/common/threading.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/lib/common/threading.h b/lib/common/threading.h
index 25448548d..85b6a3ac8 100644
--- a/lib/common/threading.h
+++ b/lib/common/threading.h
@@ -140,7 +140,6 @@ int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond);
 #else  /* ZSTD_MULTITHREAD not defined */
 /* No multithreading support */
 
-
 #if defined (__cplusplus)
 extern "C" {
 #endif
@@ -160,10 +159,11 @@ typedef int ZSTD_pthread_cond_t;
 
 /* do not use ZSTD_pthread_t */
 
-#endif /* ZSTD_MULTITHREAD */
-
 #if defined (__cplusplus)
 }
 #endif
 
+#endif /* ZSTD_MULTITHREAD */
+
+
 #endif /* THREADING_H_938743 */

From 63acf9a9955302c9595d6eccf3e8813256dfe069 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Wed, 18 Dec 2024 09:56:50 -0800
Subject: [PATCH 474/937] Oopsie with huf.h, debug.h

---
 lib/common/debug.h | 10 +---------
 lib/common/huf.h   |  4 ++--
 2 files changed, 3 insertions(+), 11 deletions(-)

diff --git a/lib/common/debug.h b/lib/common/debug.h
index 8ef37a908..4b60ddf7f 100644
--- a/lib/common/debug.h
+++ b/lib/common/debug.h
@@ -71,12 +71,9 @@
 #  endif
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #if (DEBUGLEVEL>=2)
 #  define ZSTD_DEPS_NEED_IO
+#  include "zstd_deps.h"
 extern int g_debuglevel; /* the variable is only declared,
                             it actually lives in debug.c,
                             and is shared by the whole process.
@@ -107,9 +104,4 @@ extern int g_debuglevel; /* the variable is only declared,
 #  define DEBUGLOG(l, ...) do { } while (0)    /* disabled */
 #endif
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* DEBUG_H_12987983217 */
diff --git a/lib/common/huf.h b/lib/common/huf.h
index bfcec4a81..962fe43fa 100644
--- a/lib/common/huf.h
+++ b/lib/common/huf.h
@@ -278,8 +278,8 @@ size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize
 size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);
 #endif
 
-#endif   /* HUF_H_298734234 */
-
 #if defined (__cplusplus)
 }
 #endif
+
+#endif   /* HUF_H_298734234 */

From f25b9f11ba1df6e2a5bfe7e73e43c24c7c0906db Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Wed, 18 Dec 2024 10:10:20 -0800
Subject: [PATCH 475/937] Oopsie with zdict.h

---
 lib/zdict.h | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/lib/zdict.h b/lib/zdict.h
index 340a9a24e..599b79301 100644
--- a/lib/zdict.h
+++ b/lib/zdict.h
@@ -271,11 +271,19 @@ ZDICTLIB_API size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictS
 ZDICTLIB_API unsigned ZDICT_isError(size_t errorCode);
 ZDICTLIB_API const char* ZDICT_getErrorName(size_t errorCode);
 
+#if defined (__cplusplus)
+}
+#endif
+
 #endif   /* ZSTD_ZDICT_H */
 
 #if defined(ZDICT_STATIC_LINKING_ONLY) && !defined(ZSTD_ZDICT_H_STATIC)
 #define ZSTD_ZDICT_H_STATIC
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* This can be overridden externally to hide static symbols. */
 #ifndef ZDICTLIB_STATIC_API
 #  if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
@@ -466,9 +474,8 @@ ZDICTLIB_STATIC_API
 size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples);
 
-
-#endif   /* ZSTD_ZDICT_H_STATIC */
-
 #if defined (__cplusplus)
 }
 #endif
+
+#endif   /* ZSTD_ZDICT_H_STATIC */

From 07ffcc6b65a0eb95afc63a73e595384aef9f3552 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Wed, 18 Dec 2024 12:35:10 -0800
Subject: [PATCH 476/937] Separate xxhash includes from extern C blocks

---
 lib/common/xxhash.h | 108 +++++++++++++++++++++++++++++++++++++-------
 1 file changed, 91 insertions(+), 17 deletions(-)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index e59e44267..477fd4792 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -227,10 +227,6 @@
  * xxHash prototypes and implementation
  */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ****************************
  *  INLINE mode
  ******************************/
@@ -537,6 +533,9 @@ extern "C" {
 /*! @brief Version number, encoded as two digits each */
 #define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @brief Obtains the xxHash version.
  *
@@ -547,6 +546,9 @@ extern "C" {
  */
 XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void);
 
+#if defined (__cplusplus)
+}
+#endif
 
 /* ****************************
 *  Common basic types
@@ -593,6 +595,10 @@ typedef uint32_t XXH32_hash_t;
 #   endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*!
  * @}
  *
@@ -821,6 +827,9 @@ XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canoni
 #endif
 /*! @endcond */
 
+#if defined (__cplusplus)
+} /* end of extern "C" */
+#endif
 
 /*!
  * @}
@@ -859,6 +868,9 @@ typedef uint64_t XXH64_hash_t;
 #  endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @}
  *
@@ -1562,6 +1574,11 @@ XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE con
 
 
 #endif  /* !XXH_NO_XXH3 */
+
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_LONG_LONG */
 
 /*!
@@ -1748,6 +1765,10 @@ struct XXH3_state_s {
     } while(0)
 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*!
  * @brief Calculates the 128-bit hash of @p data using XXH3.
  *
@@ -1963,8 +1984,13 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
                                      XXH64_hash_t seed64);
 #endif /* !XXH_NO_STREAM */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* !XXH_NO_XXH3 */
 #endif  /* XXH_NO_LONG_LONG */
+
 #if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)
 #  define XXH_IMPLEMENTATION
 #endif
@@ -2263,10 +2289,12 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
  * @{
  */
 
-
 /* *************************************
 *  Includes & Memory related functions
 ***************************************/
+#include    /* memcmp, memcpy */
+#include    /* ULLONG_MAX */
+
 #if defined(XXH_NO_STREAM)
 /* nothing */
 #elif defined(XXH_NO_STDLIB)
@@ -2280,9 +2308,17 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
  * without access to dynamic allocation.
  */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; }
 static void XXH_free(void* p) { (void)p; }
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #else
 
 /*
@@ -2291,6 +2327,9 @@ static void XXH_free(void* p) { (void)p; }
  */
 #include 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than malloc().
@@ -2303,10 +2342,15 @@ static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); }
  */
 static void XXH_free(void* p) { free(p); }
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_STDLIB */
 
-#include 
-
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than memcpy().
@@ -2316,8 +2360,9 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size)
     return memcpy(dest,src,size);
 }
 
-#include    /* ULLONG_MAX */
-
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
 
 /* *************************************
 *  Compiler Specific Options
@@ -2452,6 +2497,10 @@ typedef XXH32_hash_t xxh_u32;
 #  define U32  xxh_u32
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* ***   Memory access   *** */
 
 /*!
@@ -3608,6 +3657,10 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_can
     return XXH_readBE64(src);
 }
 
+#if defined (__cplusplus)
+}
+#endif
+
 #ifndef XXH_NO_XXH3
 
 /* *********************************************************************
@@ -3928,6 +3981,10 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #  pragma GCC optimize("-O2")
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #if XXH_VECTOR == XXH_NEON
 
 /*
@@ -4050,6 +4107,10 @@ XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
 # endif
 #endif  /* XXH_VECTOR == XXH_NEON */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 /*
  * VSX and Z Vector helpers.
  *
@@ -4111,6 +4172,9 @@ typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING;
 #  if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
 #    define XXH_vec_revb vec_revb
 #  else
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * A polyfill for POWER9's vec_revb().
  */
@@ -4120,9 +4184,15 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val)
                                   0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 };
     return vec_perm(val, val, vByteSwap);
 }
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
 #  endif
 # endif /* XXH_VSX_BE */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * Performs an unaligned vector load and byte swaps it on big endian.
  */
@@ -4167,6 +4237,11 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
     return result;
 }
 # endif /* XXH_vec_mulo, XXH_vec_mule */
+
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif /* XXH_VECTOR == XXH_VSX */
 
 #if XXH_VECTOR == XXH_SVE
@@ -4200,7 +4275,9 @@ do { \
 #  endif
 #endif  /* XXH_NO_PREFETCH */
 
-
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /* ==========================================
  * XXH3 default settings
  * ========================================== */
@@ -6877,8 +6954,6 @@ XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_digest (XXH_NOESCAPE const XXH3_state_
 #endif /* !XXH_NO_STREAM */
 /* 128-bit utility functions */
 
-#include    /* memcmp, memcpy */
-
 /* return : 1 is equal, 0 if different */
 /*! @ingroup XXH3_family */
 XXH_PUBLIC_API int XXH128_isEqual(XXH128_hash_t h1, XXH128_hash_t h2)
@@ -7007,14 +7082,13 @@ XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed)
 
 #endif  /* XXH_NO_LONG_LONG */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_XXH3 */
 
 /*!
  * @}
  */
 #endif  /* XXH_IMPLEMENTATION */
-
-
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif

From a7bb6d6c490a5b60b58666e73890c19921907e18 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Wed, 18 Dec 2024 12:41:53 -0800
Subject: [PATCH 477/937] Oopsie with xxhash.h [1/?]

---
 lib/common/xxhash.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 477fd4792..68ec6b29f 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -7080,12 +7080,12 @@ XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed)
 #  pragma GCC pop_options
 #endif
 
-#endif  /* XXH_NO_LONG_LONG */
 
 #if defined (__cplusplus)
 } /* extern "C" */
 #endif
 
+#endif  /* XXH_NO_LONG_LONG */
 #endif  /* XXH_NO_XXH3 */
 
 /*!

From d51e6072a847f91610637e44feef972fd41167ea Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 14:59:02 -0800
Subject: [PATCH 478/937] Test: remove extern C from some lib/common files

---
 lib/common/bitstream.h |  8 --------
 lib/common/fse.h       | 16 ----------------
 2 files changed, 24 deletions(-)

diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h
index bce91e801..bcfa09b89 100644
--- a/lib/common/bitstream.h
+++ b/lib/common/bitstream.h
@@ -40,10 +40,6 @@
 #  endif
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #define STREAM_ACCUMULATOR_MIN_32  25
 #define STREAM_ACCUMULATOR_MIN_64  57
 #define STREAM_ACCUMULATOR_MIN    ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
@@ -450,8 +446,4 @@ MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
     return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
 }
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* BITSTREAM_H_MODULE */
diff --git a/lib/common/fse.h b/lib/common/fse.h
index 9f031f31f..b1940d942 100644
--- a/lib/common/fse.h
+++ b/lib/common/fse.h
@@ -20,10 +20,6 @@
 ******************************************/
 #include "zstd_deps.h"    /* size_t, ptrdiff_t */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-*****************************************
 *  FSE_PUBLIC_API : control library symbols visibility
 ******************************************/
@@ -225,10 +221,6 @@ FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<
 If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
 */
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif  /* FSE_H */
 
 
@@ -257,10 +249,6 @@ If there is an error, the function will return an error code, which can be teste
  *  FSE advanced API
  ***************************************** */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
 /**< same as FSE_optimalTableLog(), which used `minus==2` */
 
@@ -634,8 +622,4 @@ MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
 
 #define FSE_TABLESTEP(tableSize) (((tableSize)>>1) + ((tableSize)>>3) + 3)
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* FSE_STATIC_LINKING_ONLY */

From d0d5ce4c00469d4f11970e649e55217a659b4690 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 16:00:11 -0800
Subject: [PATCH 479/937] Remove extern C blocks from lib/* internal APIs
 (except xxhash.h)

---
 lib/common/error_private.h            |  8 --------
 lib/common/huf.h                      |  8 --------
 lib/common/mem.h                      | 10 ----------
 lib/common/pool.h                     |  9 ---------
 lib/common/threading.h                | 27 ---------------------------
 lib/common/zstd_internal.h            |  8 --------
 lib/common/zstd_trace.h               |  8 --------
 lib/compress/zstd_compress_internal.h |  8 --------
 lib/compress/zstd_cwksp.h             |  8 --------
 lib/compress/zstd_double_fast.h       |  8 --------
 lib/compress/zstd_fast.h              |  8 --------
 lib/compress/zstd_lazy.h              |  9 ---------
 lib/compress/zstd_ldm.h               |  8 --------
 lib/compress/zstd_opt.h               |  8 --------
 lib/compress/zstd_preSplit.h          |  8 --------
 lib/compress/zstdmt_compress.h        | 10 ----------
 lib/dictBuilder/divsufsort.h          | 10 ----------
 17 files changed, 163 deletions(-)

diff --git a/lib/common/error_private.h b/lib/common/error_private.h
index 06233aaa8..9dcc85951 100644
--- a/lib/common/error_private.h
+++ b/lib/common/error_private.h
@@ -21,10 +21,6 @@
 #include "debug.h"
 #include "zstd_deps.h"       /* size_t */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ****************************************
 *  Compiler-specific
 ******************************************/
@@ -159,8 +155,4 @@ void _force_has_format_string(const char *format, ...) {
         }                                                                          \
     } while(0)
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ERROR_H_MODULE */
diff --git a/lib/common/huf.h b/lib/common/huf.h
index 962fe43fa..4b142c4f9 100644
--- a/lib/common/huf.h
+++ b/lib/common/huf.h
@@ -21,10 +21,6 @@
 #define FSE_STATIC_LINKING_ONLY
 #include "fse.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ***   Tool functions *** */
 #define HUF_BLOCKSIZE_MAX (128 * 1024)   /**< maximum input size for a single block compressed with HUF_compress */
 size_t HUF_compressBound(size_t size);   /**< maximum compressed size (worst case) */
@@ -278,8 +274,4 @@ size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize
 size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);
 #endif
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif   /* HUF_H_298734234 */
diff --git a/lib/common/mem.h b/lib/common/mem.h
index 1b0a946ad..ca756e237 100644
--- a/lib/common/mem.h
+++ b/lib/common/mem.h
@@ -72,11 +72,6 @@
   typedef   signed long long  S64;
 #endif
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-**************************************************************
 *  Memory I/O API
 *****************************************************************/
@@ -424,9 +419,4 @@ MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val)
 /* code only tested on 32 and 64 bits systems */
 MEM_STATIC void MEM_check(void) { DEBUG_STATIC_ASSERT((sizeof(size_t)==4) || (sizeof(size_t)==8)); }
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* MEM_H_MODULE */
diff --git a/lib/common/pool.h b/lib/common/pool.h
index d34082dc1..f39b7f1eb 100644
--- a/lib/common/pool.h
+++ b/lib/common/pool.h
@@ -16,10 +16,6 @@
 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_customMem */
 #include "../zstd.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 typedef struct POOL_ctx_s POOL_ctx;
 
 /*! POOL_create() :
@@ -82,9 +78,4 @@ void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque);
  */
 int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque);
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif
diff --git a/lib/common/threading.h b/lib/common/threading.h
index 85b6a3ac8..e123cdf14 100644
--- a/lib/common/threading.h
+++ b/lib/common/threading.h
@@ -56,11 +56,6 @@
 #define ZSTD_pthread_cond_signal(a)     WakeConditionVariable((a))
 #define ZSTD_pthread_cond_broadcast(a)  WakeAllConditionVariable((a))
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ZSTD_pthread_create() and ZSTD_pthread_join() */
 typedef HANDLE ZSTD_pthread_t;
 
@@ -73,20 +68,10 @@ int ZSTD_pthread_join(ZSTD_pthread_t thread);
  * add here more wrappers as required
  */
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #elif defined(ZSTD_MULTITHREAD)    /* posix assumed ; need a better detection method */
 /* ===   POSIX Systems   === */
 #  include 
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #if DEBUGLEVEL < 1
 
 #define ZSTD_pthread_mutex_t            pthread_mutex_t
@@ -133,17 +118,9 @@ int ZSTD_pthread_cond_destroy(ZSTD_pthread_cond_t* cond);
 
 #endif
 
-#if defined (__cplusplus)
-}
-#endif
-
 #else  /* ZSTD_MULTITHREAD not defined */
 /* No multithreading support */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 typedef int ZSTD_pthread_mutex_t;
 #define ZSTD_pthread_mutex_init(a, b)   ((void)(a), (void)(b), 0)
 #define ZSTD_pthread_mutex_destroy(a)   ((void)(a))
@@ -159,10 +136,6 @@ typedef int ZSTD_pthread_cond_t;
 
 /* do not use ZSTD_pthread_t */
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_MULTITHREAD */
 
 
diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h
index ecb9cfba8..e40d15a05 100644
--- a/lib/common/zstd_internal.h
+++ b/lib/common/zstd_internal.h
@@ -39,10 +39,6 @@
 #  define ZSTD_TRACE 0
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ---- static assert (debug) --- */
 #define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)
 #define ZSTD_isError ERR_isError   /* for inlining */
@@ -385,8 +381,4 @@ MEM_STATIC int ZSTD_cpuSupportsBmi2(void)
     return ZSTD_cpuid_bmi1(cpuid) && ZSTD_cpuid_bmi2(cpuid);
 }
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif   /* ZSTD_CCOMMON_H_MODULE */
diff --git a/lib/common/zstd_trace.h b/lib/common/zstd_trace.h
index b9187079c..198438a7c 100644
--- a/lib/common/zstd_trace.h
+++ b/lib/common/zstd_trace.h
@@ -13,10 +13,6 @@
 
 #include 
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* weak symbol support
  * For now, enable conservatively:
  * - Only GNUC
@@ -157,8 +153,4 @@ ZSTD_WEAK_ATTR void ZSTD_trace_decompress_end(
 
 #endif /* ZSTD_TRACE */
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_TRACE_H */
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 2d3510adc..bbca66cd3 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -26,10 +26,6 @@
 #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */
 #include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-*************************************
 *  Constants
 ***************************************/
@@ -1426,10 +1422,6 @@ MEM_STATIC int ZSTD_comparePackedTags(size_t packedTag1, size_t packedTag2) {
     return tag1 == tag2;
 }
 
-#if defined (__cplusplus)
-}
-#endif
-
 /* ===============================================================
  * Shared internal declarations
  * These prototypes may be called from sources not in lib/compress
diff --git a/lib/compress/zstd_cwksp.h b/lib/compress/zstd_cwksp.h
index aa4c3e49e..77518002d 100644
--- a/lib/compress/zstd_cwksp.h
+++ b/lib/compress/zstd_cwksp.h
@@ -19,10 +19,6 @@
 #include "../common/portability_macros.h"
 #include "../common/compiler.h" /* ZS2_isPower2 */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-*************************************
 *  Constants
 ***************************************/
@@ -766,8 +762,4 @@ MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
     }
 }
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_CWKSP_H */
diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h
index ae66f3142..a4d4d345e 100644
--- a/lib/compress/zstd_double_fast.h
+++ b/lib/compress/zstd_double_fast.h
@@ -14,10 +14,6 @@
 #include "../common/mem.h"      /* U32 */
 #include "zstd_compress_internal.h"     /* ZSTD_CCtx, size_t */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
 
 void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms,
@@ -43,8 +39,4 @@ size_t ZSTD_compressBlock_doubleFast_extDict(
 #define ZSTD_COMPRESSBLOCK_DOUBLEFAST_EXTDICT NULL
 #endif /* ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR */
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_DOUBLE_FAST_H */
diff --git a/lib/compress/zstd_fast.h b/lib/compress/zstd_fast.h
index f92cf35b9..8bbed8f97 100644
--- a/lib/compress/zstd_fast.h
+++ b/lib/compress/zstd_fast.h
@@ -14,10 +14,6 @@
 #include "../common/mem.h"      /* U32 */
 #include "zstd_compress_internal.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
                         void const* end, ZSTD_dictTableLoadMethod_e dtlm,
                         ZSTD_tableFillPurpose_e tfp);
@@ -31,8 +27,4 @@ size_t ZSTD_compressBlock_fast_extDict(
         ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize);
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_FAST_H */
diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h
index bec17b124..cd4e1c7fa 100644
--- a/lib/compress/zstd_lazy.h
+++ b/lib/compress/zstd_lazy.h
@@ -13,10 +13,6 @@
 
 #include "zstd_compress_internal.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /**
  * Dedicated Dictionary Search Structure bucket log. In the
  * ZSTD_dedicatedDictSearch mode, the hashTable has
@@ -194,9 +190,4 @@ size_t ZSTD_compressBlock_btlazy2_extDict(
 #define ZSTD_COMPRESSBLOCK_BTLAZY2_EXTDICT NULL
 #endif
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_LAZY_H */
diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h
index 847c2befb..592b95a98 100644
--- a/lib/compress/zstd_ldm.h
+++ b/lib/compress/zstd_ldm.h
@@ -14,10 +14,6 @@
 #include "zstd_compress_internal.h"   /* ldmParams_t, U32 */
 #include "../zstd.h"   /* ZSTD_CCtx, size_t */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-*************************************
 *  Long distance matching
 ***************************************/
@@ -110,8 +106,4 @@ size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize);
 void ZSTD_ldm_adjustParameters(ldmParams_t* params,
                                ZSTD_compressionParameters const* cParams);
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_FAST_H */
diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h
index 7ce6fdae7..cace81494 100644
--- a/lib/compress/zstd_opt.h
+++ b/lib/compress/zstd_opt.h
@@ -13,10 +13,6 @@
 
 #include "zstd_compress_internal.h"
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #if !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) \
  || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \
  || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR)
@@ -73,8 +69,4 @@ size_t ZSTD_compressBlock_btultra2(
 #define ZSTD_COMPRESSBLOCK_BTULTRA2 NULL
 #endif
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_OPT_H */
diff --git a/lib/compress/zstd_preSplit.h b/lib/compress/zstd_preSplit.h
index d606a52b5..b89a200dc 100644
--- a/lib/compress/zstd_preSplit.h
+++ b/lib/compress/zstd_preSplit.h
@@ -13,10 +13,6 @@
 
 #include   /* size_t */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #define ZSTD_SLIPBLOCK_WORKSPACESIZE 8208
 
 /* ZSTD_splitBlock():
@@ -34,8 +30,4 @@ size_t ZSTD_splitBlock(const void* blockStart, size_t blockSize,
                     int level,
                     void* workspace, size_t wkspSize);
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_PRESPLIT_H */
diff --git a/lib/compress/zstdmt_compress.h b/lib/compress/zstdmt_compress.h
index 9a58b5ad3..91b489b9c 100644
--- a/lib/compress/zstdmt_compress.h
+++ b/lib/compress/zstdmt_compress.h
@@ -16,11 +16,6 @@
 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_parameters */
 #include "../zstd.h"            /* ZSTD_inBuffer, ZSTD_outBuffer, ZSTDLIB_API */
 
- #if defined (__cplusplus)
- extern "C" {
- #endif
-
-
 /* Note : This is an internal API.
  *        These APIs used to be exposed with ZSTDLIB_API,
  *        because it used to be the only way to invoke MT compression.
@@ -104,9 +99,4 @@ void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_p
  */
 ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx);
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif   /* ZSTDMT_COMPRESS_H */
diff --git a/lib/dictBuilder/divsufsort.h b/lib/dictBuilder/divsufsort.h
index 5440994af..3ed2b287a 100644
--- a/lib/dictBuilder/divsufsort.h
+++ b/lib/dictBuilder/divsufsort.h
@@ -27,11 +27,6 @@
 #ifndef _DIVSUFSORT_H
 #define _DIVSUFSORT_H 1
 
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-
 /*- Prototypes -*/
 
 /**
@@ -59,9 +54,4 @@ divsufsort(const unsigned char *T, int *SA, int n, int openMP);
 int
 divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * num_indexes, int * indexes, int openMP);
 
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif /* __cplusplus */
-
 #endif /* _DIVSUFSORT_H */

From c727d5cd675dc04e07c0113d168ce93dc5624e54 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 16:20:23 -0800
Subject: [PATCH 480/937] Remove unnecessary extern C declarations from
 programs/ and contrib/

---
 contrib/pzstd/test/PzstdTest.cpp     |  2 --
 contrib/pzstd/test/RoundTripTest.cpp |  2 --
 programs/benchfn.h                   | 10 ----------
 programs/benchzstd.h                 |  9 ---------
 programs/datagen.h                   |  8 ++++++++
 programs/fileio.h                    | 10 ----------
 programs/fileio_asyncio.h            |  8 --------
 programs/fileio_common.h             |  7 -------
 programs/timefn.h                    | 10 ----------
 9 files changed, 8 insertions(+), 58 deletions(-)

diff --git a/contrib/pzstd/test/PzstdTest.cpp b/contrib/pzstd/test/PzstdTest.cpp
index 75453f5f6..3249f860a 100644
--- a/contrib/pzstd/test/PzstdTest.cpp
+++ b/contrib/pzstd/test/PzstdTest.cpp
@@ -7,9 +7,7 @@
  * in the COPYING file in the root directory of this source tree).
  */
 #include "Pzstd.h"
-extern "C" {
 #include "datagen.h"
-}
 #include "test/RoundTrip.h"
 #include "utils/ScopeGuard.h"
 
diff --git a/contrib/pzstd/test/RoundTripTest.cpp b/contrib/pzstd/test/RoundTripTest.cpp
index c37646d1c..27c5028e8 100644
--- a/contrib/pzstd/test/RoundTripTest.cpp
+++ b/contrib/pzstd/test/RoundTripTest.cpp
@@ -6,9 +6,7 @@
  * 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).
  */
-extern "C" {
 #include "datagen.h"
-}
 #include "Options.h"
 #include "test/RoundTrip.h"
 #include "utils/ScopeGuard.h"
diff --git a/programs/benchfn.h b/programs/benchfn.h
index 3ba3a4f55..3fc6e0d04 100644
--- a/programs/benchfn.h
+++ b/programs/benchfn.h
@@ -21,11 +21,6 @@
 /* ===  Dependencies  === */
 #include    /* size_t */
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ====  Benchmark any function, iterated on a set of blocks  ==== */
 
 /* BMK_runTime_t: valid result return type */
@@ -175,9 +170,4 @@ typedef union {
 } BMK_timedFnState_shell;
 BMK_timedFnState_t* BMK_initStatic_timedFnState(void* buffer, size_t size, unsigned total_ms, unsigned run_ms);
 
-
 #endif   /* BENCH_FN_H_23876 */
-
-#if defined (__cplusplus)
-}
-#endif
diff --git a/programs/benchzstd.h b/programs/benchzstd.h
index 7ea018b12..5125c20e8 100644
--- a/programs/benchzstd.h
+++ b/programs/benchzstd.h
@@ -22,11 +22,6 @@
 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_compressionParameters */
 #include "../lib/zstd.h"     /* ZSTD_compressionParameters */
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ===  Constants  === */
 
 #define MB_UNIT 1000000
@@ -194,7 +189,3 @@ BMK_benchOutcome_t BMK_benchMemAdvanced(const void* srcBuffer, size_t srcSize,
 
 
 #endif   /* BENCH_ZSTD_H_3242387 */
-
-#if defined (__cplusplus)
-}
-#endif
diff --git a/programs/datagen.h b/programs/datagen.h
index ca7270006..461fb716c 100644
--- a/programs/datagen.h
+++ b/programs/datagen.h
@@ -14,6 +14,10 @@
 
 #include    /* size_t */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 void RDG_genStdout(unsigned long long size, double matchProba, double litProba, unsigned seed);
 void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed);
 /*!RDG_genBuffer
@@ -27,4 +31,8 @@ void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba
    Same as RDG_genBuffer, but generates data into stdout
 */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif
diff --git a/programs/fileio.h b/programs/fileio.h
index 224d89525..6babf40e1 100644
--- a/programs/fileio.h
+++ b/programs/fileio.h
@@ -17,11 +17,6 @@
 #define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_compressionParameters */
 #include "../lib/zstd.h"           /* ZSTD_* */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
-
 /* *************************************
 *  Special i/o constants
 **************************************/
@@ -173,9 +168,4 @@ char const* FIO_zlibVersion(void);
 char const* FIO_lz4Version(void);
 char const* FIO_lzmaVersion(void);
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif  /* FILEIO_H_23981798732 */
diff --git a/programs/fileio_asyncio.h b/programs/fileio_asyncio.h
index 1c30a73da..d4980ef5b 100644
--- a/programs/fileio_asyncio.h
+++ b/programs/fileio_asyncio.h
@@ -31,10 +31,6 @@
 
 #define MAX_IO_JOBS          (10)
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 typedef struct {
     /* These struct fields should be set only on creation and not changed afterwards */
     POOL_ctx* threadPool;
@@ -196,8 +192,4 @@ FILE* AIO_ReadPool_getFile(const ReadPoolCtx_t *ctx);
  * Closes the current set file. Waits for all current enqueued tasks to complete and resets state. */
 int AIO_ReadPool_closeFile(ReadPoolCtx_t *ctx);
 
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* ZSTD_FILEIO_ASYNCIO_H */
diff --git a/programs/fileio_common.h b/programs/fileio_common.h
index 87f99cda9..e073dc101 100644
--- a/programs/fileio_common.h
+++ b/programs/fileio_common.h
@@ -23,10 +23,6 @@
 #   include 
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*-*************************************
 *  Macros
 ***************************************/
@@ -124,7 +120,4 @@ extern UTIL_time_t g_displayClock;
 #   define LONG_TELL ftell
 #endif
 
-#if defined (__cplusplus)
-}
-#endif
 #endif /* ZSTD_FILEIO_COMMON_H */
diff --git a/programs/timefn.h b/programs/timefn.h
index dc7463be3..80f72e228 100644
--- a/programs/timefn.h
+++ b/programs/timefn.h
@@ -26,11 +26,6 @@
   typedef unsigned long long PTime;  /* does not support compilers without long long support */
 #endif
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* UTIL_time_t contains a nanosecond time counter.
  * The absolute value is not meaningful.
  * It's only valid to compute the difference between 2 measurements. */
@@ -61,9 +56,4 @@ PTime UTIL_clockSpanMicro(UTIL_time_t clockStart);
 
 #define SEC_TO_MICRO ((PTime)1000000)  /* nb of microseconds in a second */
 
-
-#if defined (__cplusplus)
-}
-#endif
-
 #endif /* TIME_FN_H_MODULE_287987 */

From 10b9d81909f8631e3ac64bd45e3bdd04982e39d6 Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 16:54:32 -0800
Subject: [PATCH 481/937] Remove unnecessary extern C declarations from
 xxhash.h

---
 lib/common/xxhash.h | 90 ---------------------------------------------
 1 file changed, 90 deletions(-)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index 68ec6b29f..a849b75f9 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -533,9 +533,6 @@
 /*! @brief Version number, encoded as two digits each */
 #define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * @brief Obtains the xxHash version.
  *
@@ -546,10 +543,6 @@ extern "C" {
  */
 XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void);
 
-#if defined (__cplusplus)
-}
-#endif
-
 /* ****************************
 *  Common basic types
 ******************************/
@@ -595,10 +588,6 @@ typedef uint32_t XXH32_hash_t;
 #   endif
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*!
  * @}
  *
@@ -827,10 +816,6 @@ XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canoni
 #endif
 /*! @endcond */
 
-#if defined (__cplusplus)
-} /* end of extern "C" */
-#endif
-
 /*!
  * @}
  * @ingroup public
@@ -868,9 +853,6 @@ typedef uint64_t XXH64_hash_t;
 #  endif
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * @}
  *
@@ -1575,10 +1557,6 @@ XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE con
 
 #endif  /* !XXH_NO_XXH3 */
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #endif  /* XXH_NO_LONG_LONG */
 
 /*!
@@ -1764,11 +1742,6 @@ struct XXH3_state_s {
         tmp_xxh3_state_ptr->extSecret = NULL;                \
     } while(0)
 
-
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /*!
  * @brief Calculates the 128-bit hash of @p data using XXH3.
  *
@@ -1984,10 +1957,6 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
                                      XXH64_hash_t seed64);
 #endif /* !XXH_NO_STREAM */
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #endif  /* !XXH_NO_XXH3 */
 #endif  /* XXH_NO_LONG_LONG */
 
@@ -2308,17 +2277,9 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
  * without access to dynamic allocation.
  */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; }
 static void XXH_free(void* p) { (void)p; }
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #else
 
 /*
@@ -2327,9 +2288,6 @@ static void XXH_free(void* p) { (void)p; }
  */
 #include 
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than malloc().
@@ -2342,15 +2300,8 @@ static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); }
  */
 static void XXH_free(void* p) { free(p); }
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #endif  /* XXH_NO_STDLIB */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than memcpy().
@@ -2360,10 +2311,6 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size)
     return memcpy(dest,src,size);
 }
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 /* *************************************
 *  Compiler Specific Options
 ***************************************/
@@ -2497,10 +2444,6 @@ typedef XXH32_hash_t xxh_u32;
 #  define U32  xxh_u32
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 /* ***   Memory access   *** */
 
 /*!
@@ -3657,10 +3600,6 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_can
     return XXH_readBE64(src);
 }
 
-#if defined (__cplusplus)
-}
-#endif
-
 #ifndef XXH_NO_XXH3
 
 /* *********************************************************************
@@ -3981,10 +3920,6 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #  pragma GCC optimize("-O2")
 #endif
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
-
 #if XXH_VECTOR == XXH_NEON
 
 /*
@@ -4107,10 +4042,6 @@ XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
 # endif
 #endif  /* XXH_VECTOR == XXH_NEON */
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 /*
  * VSX and Z Vector helpers.
  *
@@ -4172,9 +4103,6 @@ typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING;
 #  if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
 #    define XXH_vec_revb vec_revb
 #  else
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * A polyfill for POWER9's vec_revb().
  */
@@ -4184,15 +4112,9 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val)
                                   0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 };
     return vec_perm(val, val, vByteSwap);
 }
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
 #  endif
 # endif /* XXH_VSX_BE */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /*!
  * Performs an unaligned vector load and byte swaps it on big endian.
  */
@@ -4238,10 +4160,6 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
 }
 # endif /* XXH_vec_mulo, XXH_vec_mule */
 
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #endif /* XXH_VECTOR == XXH_VSX */
 
 #if XXH_VECTOR == XXH_SVE
@@ -4275,9 +4193,6 @@ do { \
 #  endif
 #endif  /* XXH_NO_PREFETCH */
 
-#if defined (__cplusplus)
-extern "C" {
-#endif
 /* ==========================================
  * XXH3 default settings
  * ========================================== */
@@ -7080,11 +6995,6 @@ XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed)
 #  pragma GCC pop_options
 #endif
 
-
-#if defined (__cplusplus)
-} /* extern "C" */
-#endif
-
 #endif  /* XXH_NO_LONG_LONG */
 #endif  /* XXH_NO_XXH3 */
 

From c7af0428c6cceac32a192392d954dc8e6e1ba79a Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 17:48:00 -0800
Subject: [PATCH 482/937] Oopsie with fileio_common.h

---
 programs/fileio_common.h | 8 +-------
 1 file changed, 1 insertion(+), 7 deletions(-)

diff --git a/programs/fileio_common.h b/programs/fileio_common.h
index e073dc101..274a6d10c 100644
--- a/programs/fileio_common.h
+++ b/programs/fileio_common.h
@@ -16,13 +16,6 @@
 #include "platform.h"
 #include "timefn.h"     /* UTIL_getTime, UTIL_clockSpanMicro */
 
-#if !(defined(_MSC_VER) && _MSC_VER >= 1400) \
-    && !(!defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L)) \
-    && !(defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__)) \
-    && (defined(_WIN32) && !defined(__DJGPP__))
-#   include 
-#endif
-
 /*-*************************************
 *  Macros
 ***************************************/
@@ -92,6 +85,7 @@ extern UTIL_time_t g_displayClock;
 #   define LONG_SEEK fseeko64
 #   define LONG_TELL ftello64
 #elif defined(_WIN32) && !defined(__DJGPP__)
+#   include 
     static int LONG_SEEK(FILE* file, __int64 offset, int origin) {
         LARGE_INTEGER off;
         DWORD method;

From 8f49db5a022f5f77ad2c9a468b5929855bb6f36b Mon Sep 17 00:00:00 2001
From: Victor Zhang 
Date: Thu, 19 Dec 2024 17:54:41 -0800
Subject: [PATCH 483/937] Revert "Remove unnecessary extern C declarations from
 xxhash.h"

This reverts commit 10b9d81909f8631e3ac64bd45e3bdd04982e39d6.
---
 lib/common/xxhash.h | 90 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 90 insertions(+)

diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h
index a849b75f9..68ec6b29f 100644
--- a/lib/common/xxhash.h
+++ b/lib/common/xxhash.h
@@ -533,6 +533,9 @@
 /*! @brief Version number, encoded as two digits each */
 #define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @brief Obtains the xxHash version.
  *
@@ -543,6 +546,10 @@
  */
 XXH_PUBLIC_API XXH_CONSTF unsigned XXH_versionNumber (void);
 
+#if defined (__cplusplus)
+}
+#endif
+
 /* ****************************
 *  Common basic types
 ******************************/
@@ -588,6 +595,10 @@ typedef uint32_t XXH32_hash_t;
 #   endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*!
  * @}
  *
@@ -816,6 +827,10 @@ XXH_PUBLIC_API XXH_PUREF XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canoni
 #endif
 /*! @endcond */
 
+#if defined (__cplusplus)
+} /* end of extern "C" */
+#endif
+
 /*!
  * @}
  * @ingroup public
@@ -853,6 +868,9 @@ typedef uint64_t XXH64_hash_t;
 #  endif
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @}
  *
@@ -1557,6 +1575,10 @@ XXH_PUBLIC_API XXH_PUREF XXH128_hash_t XXH128_hashFromCanonical(XXH_NOESCAPE con
 
 #endif  /* !XXH_NO_XXH3 */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_LONG_LONG */
 
 /*!
@@ -1742,6 +1764,11 @@ struct XXH3_state_s {
         tmp_xxh3_state_ptr->extSecret = NULL;                \
     } while(0)
 
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /*!
  * @brief Calculates the 128-bit hash of @p data using XXH3.
  *
@@ -1957,6 +1984,10 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
                                      XXH64_hash_t seed64);
 #endif /* !XXH_NO_STREAM */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* !XXH_NO_XXH3 */
 #endif  /* XXH_NO_LONG_LONG */
 
@@ -2277,9 +2308,17 @@ XXH3_128bits_reset_withSecretandSeed(XXH_NOESCAPE XXH3_state_t* statePtr,
  * without access to dynamic allocation.
  */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 static XXH_CONSTF void* XXH_malloc(size_t s) { (void)s; return NULL; }
 static void XXH_free(void* p) { (void)p; }
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #else
 
 /*
@@ -2288,6 +2327,9 @@ static void XXH_free(void* p) { (void)p; }
  */
 #include 
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than malloc().
@@ -2300,8 +2342,15 @@ static XXH_MALLOCF void* XXH_malloc(size_t s) { return malloc(s); }
  */
 static void XXH_free(void* p) { free(p); }
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_STDLIB */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * @internal
  * @brief Modify this function to use a different routine than memcpy().
@@ -2311,6 +2360,10 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size)
     return memcpy(dest,src,size);
 }
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 /* *************************************
 *  Compiler Specific Options
 ***************************************/
@@ -2444,6 +2497,10 @@ typedef XXH32_hash_t xxh_u32;
 #  define U32  xxh_u32
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 /* ***   Memory access   *** */
 
 /*!
@@ -3600,6 +3657,10 @@ XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(XXH_NOESCAPE const XXH64_can
     return XXH_readBE64(src);
 }
 
+#if defined (__cplusplus)
+}
+#endif
+
 #ifndef XXH_NO_XXH3
 
 /* *********************************************************************
@@ -3920,6 +3981,10 @@ enum XXH_VECTOR_TYPE /* fake enum */ {
 #  pragma GCC optimize("-O2")
 #endif
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
 #if XXH_VECTOR == XXH_NEON
 
 /*
@@ -4042,6 +4107,10 @@ XXH_vmlal_high_u32(uint64x2_t acc, uint32x4_t lhs, uint32x4_t rhs)
 # endif
 #endif  /* XXH_VECTOR == XXH_NEON */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 /*
  * VSX and Z Vector helpers.
  *
@@ -4103,6 +4172,9 @@ typedef xxh_u64x2 xxh_aliasing_u64x2 XXH_ALIASING;
 #  if defined(__POWER9_VECTOR__) || (defined(__clang__) && defined(__s390x__))
 #    define XXH_vec_revb vec_revb
 #  else
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * A polyfill for POWER9's vec_revb().
  */
@@ -4112,9 +4184,15 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_revb(xxh_u64x2 val)
                                   0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08 };
     return vec_perm(val, val, vByteSwap);
 }
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
 #  endif
 # endif /* XXH_VSX_BE */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /*!
  * Performs an unaligned vector load and byte swaps it on big endian.
  */
@@ -4160,6 +4238,10 @@ XXH_FORCE_INLINE xxh_u64x2 XXH_vec_mule(xxh_u32x4 a, xxh_u32x4 b)
 }
 # endif /* XXH_vec_mulo, XXH_vec_mule */
 
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif /* XXH_VECTOR == XXH_VSX */
 
 #if XXH_VECTOR == XXH_SVE
@@ -4193,6 +4275,9 @@ do { \
 #  endif
 #endif  /* XXH_NO_PREFETCH */
 
+#if defined (__cplusplus)
+extern "C" {
+#endif
 /* ==========================================
  * XXH3 default settings
  * ========================================== */
@@ -6995,6 +7080,11 @@ XXH3_generateSecret_fromSeed(XXH_NOESCAPE void* secretBuffer, XXH64_hash_t seed)
 #  pragma GCC pop_options
 #endif
 
+
+#if defined (__cplusplus)
+} /* extern "C" */
+#endif
+
 #endif  /* XXH_NO_LONG_LONG */
 #endif  /* XXH_NO_XXH3 */
 

From d06e8778bc4b150507abe0a8b7eaed08f2d16a17 Mon Sep 17 00:00:00 2001
From: Bent 
Date: Thu, 19 Dec 2024 12:16:08 +0100
Subject: [PATCH 484/937] added UNAME_TARGET_SYSTEM build flag to configure
 shared lib flags

---
 lib/Makefile | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/lib/Makefile b/lib/Makefile
index 020d2ff5d..2fe436bc2 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -73,13 +73,15 @@ endif
 
 # macOS linker doesn't support -soname, and use different extension
 # see : https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryDesignGuidelines.html
-ifeq ($(UNAME), Darwin)
+UNAME_TARGET_SYSTEM ?= $(UNAME)
+
+ifeq ($(UNAME_TARGET_SYSTEM), Darwin)
   SHARED_EXT = dylib
   SHARED_EXT_MAJOR = $(LIBVER_MAJOR).$(SHARED_EXT)
   SHARED_EXT_VER = $(LIBVER).$(SHARED_EXT)
   SONAME_FLAGS = -install_name $(LIBDIR)/libzstd.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER)
 else
-  ifeq ($(UNAME), AIX)
+  ifeq ($(UNAME_TARGET_SYSTEM), AIX)
     SONAME_FLAGS =
   else
     SONAME_FLAGS = -Wl,-soname=libzstd.$(SHARED_EXT).$(LIBVER_MAJOR)
@@ -108,6 +110,9 @@ ifndef BUILD_DIR
 # determine BUILD_DIR from compilation flags
 
 libzstd.a:
+	@echo uname_target $(UNAME_TARGET)
+	@echo target_system $(TARGET_SYSTEM)
+	@echo uname $(uname)
 	$(SET_CACHE_DIRECTORY)
 
 else

From 5a7f5c745cfb7135f27002efc79fee1804d21d44 Mon Sep 17 00:00:00 2001
From: Bent 
Date: Thu, 19 Dec 2024 12:22:10 +0100
Subject: [PATCH 485/937] removed debug echos

---
 lib/Makefile | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/lib/Makefile b/lib/Makefile
index 2fe436bc2..a6a0eb09d 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -110,9 +110,6 @@ ifndef BUILD_DIR
 # determine BUILD_DIR from compilation flags
 
 libzstd.a:
-	@echo uname_target $(UNAME_TARGET)
-	@echo target_system $(TARGET_SYSTEM)
-	@echo uname $(uname)
 	$(SET_CACHE_DIRECTORY)
 
 else

From 125f05282b0566790551e6756bdbc0290addfcb2 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 9 Dec 2024 18:17:34 -0800
Subject: [PATCH 486/937] publish new symbol
 ZSTD_compressSequencesAndLiterals()

---
 lib/zstd.h         | 15 +++++++++++++++
 programs/zstdcli.c |  2 --
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/lib/zstd.h b/lib/zstd.h
index a78b6db45..cfacd58d0 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -1656,6 +1656,21 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
                         const void* src, size_t srcSize);
 
 
+/*! ZSTD_compressSequencesAndLiterals() :
+ * This is a variant of ZSTD_compressSequences() which,
+ * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize),
+ * aka all literals already extracted and grouped into a single continuous buffer.
+ * This can be useful if the process generating the sequences also happens to generate the buffer of literals,
+ * thus skipping an extraction + caching stage.
+ * To be valid, `litSize` must be equal to the sum of all @.litLength fields in @inSeqs.
+ * @return : final compressed size, or a ZSTD error code.
+ */
+ZSTDLIB_STATIC_API size_t
+ZSTD_compressSequencesAndLiterals( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
+                        const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
+                        const void* literals, size_t litSize);
+
+
 /*! ZSTD_writeSkippableFrame() :
  * Generates a zstd skippable frame containing data given by src, and writes it to dst buffer.
  *
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 024552d52..2a9a77624 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -635,8 +635,6 @@ static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressi
         return 0;
     }
 
-    DISPLAYLEVEL(4, "windowLog=%d, chainLog=%d, hashLog=%d, searchLog=%d \n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
-    DISPLAYLEVEL(4, "minMatch=%d, targetLength=%d, strategy=%d \n", params->minMatch, params->targetLength, params->strategy);
     if (stringPtr[0] != 0) return 0; /* check the end of string */
     return 1;
 }

From a00f45a03751a90f620425f30690d86d872dfef1 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Mon, 9 Dec 2024 21:39:34 -0800
Subject: [PATCH 487/937] created ZSTD_storeSeqOnly()

makes it possible to register a sequence without copying its literals.
---
 lib/compress/zstd_compress.c          |  9 ++--
 lib/compress/zstd_compress_internal.h | 76 ++++++++++++++++++---------
 2 files changed, 57 insertions(+), 28 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 3d78b7da3..9df219ded 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -6666,9 +6666,11 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx,
 }
 
 size_t
-ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos,
+ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx,
+                                         ZSTD_sequencePosition* seqPos,
                                    const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
-                                   const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch)
+                                   const void* src, size_t blockSize,
+                                         ZSTD_paramSwitch_e externalRepSearch)
 {
     U32 idx = seqPos->idx;
     U32 startPosInSequence = seqPos->posInSequence;
@@ -6855,7 +6857,7 @@ static size_t determine_blockSize(ZSTD_sequenceFormat_e mode,
     }
 }
 
-/* Compress, block-by-block, all of the sequences given.
+/* Compress all provided sequences, block-by-block.
  *
  * Returns the cumulative size of all compressed blocks (including their headers),
  * otherwise a ZSTD error.
@@ -6896,7 +6898,6 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
         FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size");
         assert(blockSize <= remaining);
         ZSTD_resetSeqStore(&cctx->seqStore);
-        DEBUGLOG(5, "Working on new block. Blocksize: %zu (total:%zu)", blockSize, (ip - (const BYTE*)src) + blockSize);
 
         additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize, cctx->appliedParams.searchForExternalRepcodes);
         FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 2d3510adc..d49023d88 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -671,6 +671,57 @@ ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE con
 #define OFFBASE_TO_OFFSET(o)  (assert(OFFBASE_IS_OFFSET(o)), (o) - ZSTD_REP_NUM)
 #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o))  /* returns ID 1,2,3 */
 
+/*! ZSTD_storeSeqOnly() :
+ *  Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.
+ *  Literals themselves are not copied, but @litPtr is updated.
+ *  @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
+ *  @matchLength : must be >= MINMATCH
+*/
+HINT_INLINE UNUSED_ATTR void
+ZSTD_storeSeqOnly(seqStore_t* seqStorePtr,
+              size_t litLength,
+              U32 offBase,
+              size_t matchLength)
+{
+#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
+    static const BYTE* g_start = NULL;
+    if (g_start==NULL) g_start = (const BYTE*)literals;  /* note : index only works for compression within a single segment */
+    {   U32 const pos = (U32)((const BYTE*)literals - g_start);
+        DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u",
+               pos, (U32)litLength, (U32)matchLength, (U32)offBase);
+    }
+#endif
+    assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
+    /* update seqStorePtr->lit, so that we know how many literals were or will be copied */
+    assert(seqStorePtr->maxNbLit <= 128 KB);
+    assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
+    seqStorePtr->lit += litLength;
+
+    /* literal Length */
+    if (litLength>0xFFFF) {
+        assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
+        seqStorePtr->longLengthType = ZSTD_llt_literalLength;
+        seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+    }
+    seqStorePtr->sequences[0].litLength = (U16)litLength;
+
+    /* match offset */
+    seqStorePtr->sequences[0].offBase = offBase;
+
+    /* match Length */
+    assert(matchLength >= MINMATCH);
+    {   size_t const mlBase = matchLength - MINMATCH;
+        if (mlBase>0xFFFF) {
+            assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
+            seqStorePtr->longLengthType = ZSTD_llt_matchLength;
+            seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+        }
+        seqStorePtr->sequences[0].mlBase = (U16)mlBase;
+    }
+
+    seqStorePtr->sequences++;
+}
+
 /*! ZSTD_storeSeq() :
  *  Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t.
  *  @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE().
@@ -710,31 +761,8 @@ ZSTD_storeSeq(seqStore_t* seqStorePtr,
     } else {
         ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w);
     }
-    seqStorePtr->lit += litLength;
 
-    /* literal Length */
-    if (litLength>0xFFFF) {
-        assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
-        seqStorePtr->longLengthType = ZSTD_llt_literalLength;
-        seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
-    }
-    seqStorePtr->sequences[0].litLength = (U16)litLength;
-
-    /* match offset */
-    seqStorePtr->sequences[0].offBase = offBase;
-
-    /* match Length */
-    assert(matchLength >= MINMATCH);
-    {   size_t const mlBase = matchLength - MINMATCH;
-        if (mlBase>0xFFFF) {
-            assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */
-            seqStorePtr->longLengthType = ZSTD_llt_matchLength;
-            seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
-        }
-        seqStorePtr->sequences[0].mlBase = (U16)mlBase;
-    }
-
-    seqStorePtr->sequences++;
+    ZSTD_storeSeqOnly(seqStorePtr, litLength, offBase, matchLength);
 }
 
 /* ZSTD_updateRep() :

From b4a40a845fffc07a0e95a8a59fdbb1b87934d256 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 10 Dec 2024 11:04:25 -0800
Subject: [PATCH 488/937] move Sequences definition to zstd_compress_internal.h

they should not be in common/zstd_internal.h,
since these definitions are not shared beyond lib/compress/.
---
 build/single_file_libs/examples/zstd_errors.h | 106 ++++++++++++++++++
 doc/zstd_manual.html                          |  16 ++-
 lib/common/zstd_internal.h                    |  60 ----------
 lib/compress/zstd_compress.c                  |   2 +-
 lib/compress/zstd_compress_internal.h         |  64 +++++++++++
 lib/compress/zstd_compress_sequences.h        |   1 +
 6 files changed, 187 insertions(+), 62 deletions(-)
 create mode 100644 build/single_file_libs/examples/zstd_errors.h

diff --git a/build/single_file_libs/examples/zstd_errors.h b/build/single_file_libs/examples/zstd_errors.h
new file mode 100644
index 000000000..20e488f15
--- /dev/null
+++ b/build/single_file_libs/examples/zstd_errors.h
@@ -0,0 +1,106 @@
+/*
+ * 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_ERRORS_H_398273423
+#define ZSTD_ERRORS_H_398273423
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/* =====   ZSTDERRORLIB_API : control library symbols visibility   ===== */
+#ifndef ZSTDERRORLIB_VISIBLE
+   /* Backwards compatibility with old macro name */
+#  ifdef ZSTDERRORLIB_VISIBILITY
+#    define ZSTDERRORLIB_VISIBLE ZSTDERRORLIB_VISIBILITY
+#  elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
+#    define ZSTDERRORLIB_VISIBLE __attribute__ ((visibility ("default")))
+#  else
+#    define ZSTDERRORLIB_VISIBLE
+#  endif
+#endif
+
+#ifndef ZSTDERRORLIB_HIDDEN
+#  if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)
+#    define ZSTDERRORLIB_HIDDEN __attribute__ ((visibility ("hidden")))
+#  else
+#    define ZSTDERRORLIB_HIDDEN
+#  endif
+#endif
+
+#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
+#  define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBLE
+#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
+#  define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+#  define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBLE
+#endif
+
+/*-*********************************************
+ *  Error codes list
+ *-*********************************************
+ *  Error codes _values_ are pinned down since v1.3.1 only.
+ *  Therefore, don't rely on values if you may link to any version < v1.3.1.
+ *
+ *  Only values < 100 are considered stable.
+ *
+ *  note 1 : this API shall be used with static linking only.
+ *           dynamic linking is not yet officially supported.
+ *  note 2 : Prefer relying on the enum than on its value whenever possible
+ *           This is the only supported way to use the error list < v1.3.1
+ *  note 3 : ZSTD_isError() is always correct, whatever the library version.
+ **********************************************/
+typedef enum {
+  ZSTD_error_no_error = 0,
+  ZSTD_error_GENERIC  = 1,
+  ZSTD_error_prefix_unknown                = 10,
+  ZSTD_error_version_unsupported           = 12,
+  ZSTD_error_frameParameter_unsupported    = 14,
+  ZSTD_error_frameParameter_windowTooLarge = 16,
+  ZSTD_error_corruption_detected = 20,
+  ZSTD_error_checksum_wrong      = 22,
+  ZSTD_error_literals_headerWrong = 24,
+  ZSTD_error_dictionary_corrupted      = 30,
+  ZSTD_error_dictionary_wrong          = 32,
+  ZSTD_error_dictionaryCreation_failed = 34,
+  ZSTD_error_parameter_unsupported   = 40,
+  ZSTD_error_parameter_combination_unsupported = 41,
+  ZSTD_error_parameter_outOfBound    = 42,
+  ZSTD_error_tableLog_tooLarge       = 44,
+  ZSTD_error_maxSymbolValue_tooLarge = 46,
+  ZSTD_error_maxSymbolValue_tooSmall = 48,
+  ZSTD_error_stabilityCondition_notRespected = 50,
+  ZSTD_error_stage_wrong       = 60,
+  ZSTD_error_init_missing      = 62,
+  ZSTD_error_memory_allocation = 64,
+  ZSTD_error_workSpace_tooSmall= 66,
+  ZSTD_error_dstSize_tooSmall = 70,
+  ZSTD_error_srcSize_wrong    = 72,
+  ZSTD_error_dstBuffer_null   = 74,
+  ZSTD_error_noForwardProgress_destFull = 80,
+  ZSTD_error_noForwardProgress_inputEmpty = 82,
+  /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
+  ZSTD_error_frameIndex_tooLarge = 100,
+  ZSTD_error_seekableIO          = 102,
+  ZSTD_error_dstBuffer_wrong     = 104,
+  ZSTD_error_srcBuffer_wrong     = 105,
+  ZSTD_error_sequenceProducer_failed = 106,
+  ZSTD_error_externalSequences_invalid = 107,
+  ZSTD_error_maxCode = 120  /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
+} ZSTD_ErrorCode;
+
+ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code);   /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_ERRORS_H_398273423 */
diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index 8118b7362..bcd1f05da 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -154,7 +154,7 @@ size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in w
  it's recommended to provide @dstCapacity >= ZSTD_compressBound(srcSize)
  as it eliminates one potential failure scenario,
  aka not enough room in dst buffer to write the compressed frame.
- Note : ZSTD_compressBound() itself can fail, if @srcSize > ZSTD_MAX_INPUT_SIZE .
+ Note : ZSTD_compressBound() itself can fail, if @srcSize >= ZSTD_MAX_INPUT_SIZE .
         In which case, ZSTD_compressBound() will return an error code
         which can be tested using ZSTD_isError().
 
@@ -1410,6 +1410,20 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
  
 


+
ZSTDLIB_STATIC_API size_t
+ZSTD_compressSequencesAndLiterals( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
+            const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
+            const void* literals, size_t litSize);
+

This is a variant of ZSTD_compressSequences() which, + instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), + aka all literals already extracted and grouped into a single continuous buffer. + This can be useful if the process generating the sequences also happens to generate the buffer of literals, + thus skipping an extraction + caching stage. + To be valid, `litSize` must be equal to the sum of all @.litLength fields in @inSeqs. + @return : final compressed size, or a ZSTD error code. + +


+
ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
                                 const void* src, size_t srcSize, unsigned magicVariant);
 

Generates a zstd skippable frame containing data given by src, and writes it to dst buffer. diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index ecb9cfba8..1122e2f39 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -278,62 +278,6 @@ typedef enum { /*-******************************************* * Private declarations *********************************************/ -typedef struct seqDef_s { - U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */ - U16 litLength; - U16 mlBase; /* mlBase == matchLength - MINMATCH */ -} seqDef; - -/* Controls whether seqStore has a single "long" litLength or matchLength. See seqStore_t. */ -typedef enum { - ZSTD_llt_none = 0, /* no longLengthType */ - ZSTD_llt_literalLength = 1, /* represents a long literal */ - ZSTD_llt_matchLength = 2 /* represents a long match */ -} ZSTD_longLengthType_e; - -typedef struct { - seqDef* sequencesStart; - seqDef* sequences; /* ptr to end of sequences */ - BYTE* litStart; - BYTE* lit; /* ptr to end of literals */ - BYTE* llCode; - BYTE* mlCode; - BYTE* ofCode; - size_t maxNbSeq; - size_t maxNbLit; - - /* longLengthPos and longLengthType to allow us to represent either a single litLength or matchLength - * in the seqStore that has a value larger than U16 (if it exists). To do so, we increment - * the existing value of the litLength or matchLength by 0x10000. - */ - ZSTD_longLengthType_e longLengthType; - U32 longLengthPos; /* Index of the sequence to apply long length modification to */ -} seqStore_t; - -typedef struct { - U32 litLength; - U32 matchLength; -} ZSTD_sequenceLength; - -/** - * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences - * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength. - */ -MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq) -{ - ZSTD_sequenceLength seqLen; - seqLen.litLength = seq->litLength; - seqLen.matchLength = seq->mlBase + MINMATCH; - if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) { - if (seqStore->longLengthType == ZSTD_llt_literalLength) { - seqLen.litLength += 0x10000; - } - if (seqStore->longLengthType == ZSTD_llt_matchLength) { - seqLen.matchLength += 0x10000; - } - } - return seqLen; -} /** * Contains the compressed frame size and an upper-bound for the decompressed frame size. @@ -347,10 +291,6 @@ typedef struct { unsigned long long decompressedBound; } ZSTD_frameSizeInfo; /* decompress & legacy */ -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) */ - - /* ZSTD_invalidateRepCodes() : * ensures next compression will not use repcodes from previous block. * Note : only works with regular variant; diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9df219ded..a86748dae 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6909,7 +6909,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, if (blockSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1+1) { cBlockSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock); FORWARD_IF_ERROR(cBlockSize, "Nocompress block failed"); - DEBUGLOG(5, "Block too small, writing out nocompress block: cSize: %zu", cBlockSize); + DEBUGLOG(5, "Block too small (%zu): data remains uncompressed: cSize=%zu", blockSize, cBlockSize); cSize += cBlockSize; ip += blockSize; op += cBlockSize; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index d49023d88..e9f058771 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -83,6 +83,70 @@ typedef struct { ZSTD_fseCTables_t fse; } ZSTD_entropyCTables_t; +/*********************************************** +* Sequences * +***********************************************/ +typedef struct seqDef_s { + U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */ + U16 litLength; + U16 mlBase; /* mlBase == matchLength - MINMATCH */ +} seqDef; + +/* Controls whether seqStore has a single "long" litLength or matchLength. See seqStore_t. */ +typedef enum { + ZSTD_llt_none = 0, /* no longLengthType */ + ZSTD_llt_literalLength = 1, /* represents a long literal */ + ZSTD_llt_matchLength = 2 /* represents a long match */ +} ZSTD_longLengthType_e; + +typedef struct { + seqDef* sequencesStart; + seqDef* sequences; /* ptr to end of sequences */ + BYTE* litStart; + BYTE* lit; /* ptr to end of literals */ + BYTE* llCode; + BYTE* mlCode; + BYTE* ofCode; + size_t maxNbSeq; + size_t maxNbLit; + + /* longLengthPos and longLengthType to allow us to represent either a single litLength or matchLength + * in the seqStore that has a value larger than U16 (if it exists). To do so, we increment + * the existing value of the litLength or matchLength by 0x10000. + */ + ZSTD_longLengthType_e longLengthType; + U32 longLengthPos; /* Index of the sequence to apply long length modification to */ +} seqStore_t; + +typedef struct { + U32 litLength; + U32 matchLength; +} ZSTD_sequenceLength; + +/** + * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences + * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength. + */ +MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq) +{ + ZSTD_sequenceLength seqLen; + seqLen.litLength = seq->litLength; + seqLen.matchLength = seq->mlBase + MINMATCH; + if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) { + if (seqStore->longLengthType == ZSTD_llt_literalLength) { + seqLen.litLength += 0x10000; + } + if (seqStore->longLengthType == ZSTD_llt_matchLength) { + seqLen.matchLength += 0x10000; + } + } + return seqLen; +} + +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) */ + + /*********************************************** * Entropy buffer statistics structs and funcs * ***********************************************/ diff --git a/lib/compress/zstd_compress_sequences.h b/lib/compress/zstd_compress_sequences.h index 4a3a05da9..fb393cca2 100644 --- a/lib/compress/zstd_compress_sequences.h +++ b/lib/compress/zstd_compress_sequences.h @@ -11,6 +11,7 @@ #ifndef ZSTD_COMPRESS_SEQUENCES_H #define ZSTD_COMPRESS_SEQUENCES_H +#include "zstd_compress_internal.h" /* seqDef */ #include "../common/fse.h" /* FSE_repeat, FSE_CTable */ #include "../common/zstd_internal.h" /* symbolEncodingType_e, ZSTD_strategy */ From 9671813375cec4576f874eab00ebe669e3cfbe36 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 11:06:58 -0800 Subject: [PATCH 489/937] codemod: seqDef -> SeqDef SeqDef is a type name, so it should start with a Capital letter. It's an internal symbol, no impact on public API. --- lib/compress/zstd_compress.c | 16 ++++++++-------- lib/compress/zstd_compress_internal.h | 10 +++++----- lib/compress/zstd_compress_sequences.c | 8 ++++---- lib/compress/zstd_compress_sequences.h | 4 ++-- lib/compress/zstd_compress_superblock.c | 18 +++++++++--------- lib/dictBuilder/zdict.c | 2 +- tests/decodecorpus.c | 4 ++-- 7 files changed, 31 insertions(+), 31 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index a86748dae..16544e985 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1722,7 +1722,7 @@ static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal( size_t const blockSize = MIN(ZSTD_resolveMaxBlockSize(maxBlockSize), windowSize); size_t const maxNbSeq = ZSTD_maxNbSeq(blockSize, cParams->minMatch, useSequenceProducer); size_t const tokenSpace = ZSTD_cwksp_alloc_size(WILDCOPY_OVERLENGTH + blockSize) - + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(seqDef)) + + ZSTD_cwksp_aligned64_alloc_size(maxNbSeq * sizeof(SeqDef)) + 3 * ZSTD_cwksp_alloc_size(maxNbSeq * sizeof(BYTE)); size_t const tmpWorkSpace = ZSTD_cwksp_alloc_size(TMP_WORKSPACE_SIZE); size_t const blockStateSpace = 2 * ZSTD_cwksp_alloc_size(sizeof(ZSTD_compressedBlockState_t)); @@ -2224,7 +2224,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, needsIndexReset, ZSTD_resetTarget_CCtx), ""); - zc->seqStore.sequencesStart = (seqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(seqDef)); + zc->seqStore.sequencesStart = (SeqDef*)ZSTD_cwksp_reserve_aligned64(ws, maxNbSeq * sizeof(SeqDef)); /* ldm hash table */ if (params->ldmParams.enableLdm == ZSTD_ps_enable) { @@ -2700,7 +2700,7 @@ static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* par int ZSTD_seqToCodes(const seqStore_t* seqStorePtr) { - const seqDef* const sequences = seqStorePtr->sequencesStart; + const SeqDef* const sequences = seqStorePtr->sequencesStart; BYTE* const llCodeTable = seqStorePtr->llCode; BYTE* const ofCodeTable = seqStorePtr->ofCode; BYTE* const mlCodeTable = seqStorePtr->mlCode; @@ -2907,7 +2907,7 @@ ZSTD_entropyCompressSeqStore_internal( FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable; FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable; FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable; - const seqDef* const sequences = seqStorePtr->sequencesStart; + const SeqDef* const sequences = seqStorePtr->sequencesStart; const size_t nbSeq = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart); const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; @@ -3385,7 +3385,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const seqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM]) { - const seqDef* inSeqs = seqStore->sequencesStart; + const SeqDef* inSeqs = seqStore->sequencesStart; const size_t nbInSequences = seqStore->sequences - inSeqs; const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart); @@ -3929,7 +3929,7 @@ static size_t ZSTD_countSeqStoreLiteralsBytes(const seqStore_t* const seqStore) size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart); size_t i; for (i = 0; i < nbSeqs; ++i) { - seqDef const seq = seqStore->sequencesStart[i]; + SeqDef const seq = seqStore->sequencesStart[i]; literalsBytes += seq.litLength; if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_literalLength) { literalsBytes += 0x10000; @@ -3944,7 +3944,7 @@ static size_t ZSTD_countSeqStoreMatchBytes(const seqStore_t* const seqStore) size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart); size_t i; for (i = 0; i < nbSeqs; ++i) { - seqDef seq = seqStore->sequencesStart[i]; + SeqDef seq = seqStore->sequencesStart[i]; matchBytes += seq.mlBase + MINMATCH; if (i == seqStore->longLengthPos && seqStore->longLengthType == ZSTD_llt_matchLength) { matchBytes += 0x10000; @@ -4030,7 +4030,7 @@ ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRe U32 idx = 0; U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq; for (; idx < nbSeq; ++idx) { - seqDef* const seq = seqStore->sequencesStart + idx; + SeqDef* const seq = seqStore->sequencesStart + idx; U32 const ll0 = (seq->litLength == 0) && (idx != longLitLenIdx); U32 const offBase = seq->offBase; assert(offBase > 0); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index e9f058771..fcd8622cf 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -86,11 +86,11 @@ typedef struct { /*********************************************** * Sequences * ***********************************************/ -typedef struct seqDef_s { +typedef struct SeqDef_s { U32 offBase; /* offBase == Offset + ZSTD_REP_NUM, or repcode 1,2,3 */ U16 litLength; U16 mlBase; /* mlBase == matchLength - MINMATCH */ -} seqDef; +} SeqDef; /* Controls whether seqStore has a single "long" litLength or matchLength. See seqStore_t. */ typedef enum { @@ -100,8 +100,8 @@ typedef enum { } ZSTD_longLengthType_e; typedef struct { - seqDef* sequencesStart; - seqDef* sequences; /* ptr to end of sequences */ + SeqDef* sequencesStart; + SeqDef* sequences; /* ptr to end of sequences */ BYTE* litStart; BYTE* lit; /* ptr to end of literals */ BYTE* llCode; @@ -127,7 +127,7 @@ typedef struct { * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength. */ -MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq) +MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, SeqDef const* seq) { ZSTD_sequenceLength seqLen; seqLen.litLength = seq->litLength; diff --git a/lib/compress/zstd_compress_sequences.c b/lib/compress/zstd_compress_sequences.c index 8872d4d35..7a9d595b1 100644 --- a/lib/compress/zstd_compress_sequences.c +++ b/lib/compress/zstd_compress_sequences.c @@ -293,7 +293,7 @@ ZSTD_encodeSequences_body( FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, - seqDef const* sequences, size_t nbSeq, int longOffsets) + SeqDef const* sequences, size_t nbSeq, int longOffsets) { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; @@ -387,7 +387,7 @@ ZSTD_encodeSequences_default( FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, - seqDef const* sequences, size_t nbSeq, int longOffsets) + SeqDef const* sequences, size_t nbSeq, int longOffsets) { return ZSTD_encodeSequences_body(dst, dstCapacity, CTable_MatchLength, mlCodeTable, @@ -405,7 +405,7 @@ ZSTD_encodeSequences_bmi2( FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, - seqDef const* sequences, size_t nbSeq, int longOffsets) + SeqDef const* sequences, size_t nbSeq, int longOffsets) { return ZSTD_encodeSequences_body(dst, dstCapacity, CTable_MatchLength, mlCodeTable, @@ -421,7 +421,7 @@ size_t ZSTD_encodeSequences( FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, - seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) + SeqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) { DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity); #if DYNAMIC_BMI2 diff --git a/lib/compress/zstd_compress_sequences.h b/lib/compress/zstd_compress_sequences.h index fb393cca2..b974d1cfc 100644 --- a/lib/compress/zstd_compress_sequences.h +++ b/lib/compress/zstd_compress_sequences.h @@ -11,7 +11,7 @@ #ifndef ZSTD_COMPRESS_SEQUENCES_H #define ZSTD_COMPRESS_SEQUENCES_H -#include "zstd_compress_internal.h" /* seqDef */ +#include "zstd_compress_internal.h" /* SeqDef */ #include "../common/fse.h" /* FSE_repeat, FSE_CTable */ #include "../common/zstd_internal.h" /* symbolEncodingType_e, ZSTD_strategy */ @@ -43,7 +43,7 @@ size_t ZSTD_encodeSequences( FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, - seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2); + SeqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2); size_t ZSTD_fseBitCost( FSE_CTable const* ctable, diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index 97321bc76..a8882c169 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -127,7 +127,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, static size_t ZSTD_seqDecompressedSize(seqStore_t const* seqStore, - const seqDef* sequences, size_t nbSeqs, + const SeqDef* sequences, size_t nbSeqs, size_t litSize, int lastSubBlock) { size_t matchLengthSum = 0; @@ -162,7 +162,7 @@ ZSTD_seqDecompressedSize(seqStore_t const* seqStore, static size_t ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables, const ZSTD_fseCTablesMetadata_t* fseMetadata, - const seqDef* sequences, size_t nbSeq, + const SeqDef* sequences, size_t nbSeq, const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode, const ZSTD_CCtx_params* cctxParams, void* dst, size_t dstCapacity, @@ -262,7 +262,7 @@ ZSTD_compressSubBlock_sequences(const ZSTD_fseCTables_t* fseTables, * Or 0 if it failed to compress. */ static size_t ZSTD_compressSubBlock(const ZSTD_entropyCTables_t* entropy, const ZSTD_entropyCTablesMetadata_t* entropyMetadata, - const seqDef* sequences, size_t nbSeq, + const SeqDef* sequences, size_t nbSeq, const BYTE* literals, size_t litSize, const BYTE* llCode, const BYTE* mlCode, const BYTE* ofCode, const ZSTD_CCtx_params* cctxParams, @@ -426,7 +426,7 @@ static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMe return 0; } -static size_t countLiterals(seqStore_t const* seqStore, const seqDef* sp, size_t seqCount) +static size_t countLiterals(seqStore_t const* seqStore, const SeqDef* sp, size_t seqCount) { size_t n, total = 0; assert(sp != NULL); @@ -439,7 +439,7 @@ static size_t countLiterals(seqStore_t const* seqStore, const seqDef* sp, size_t #define BYTESCALE 256 -static size_t sizeBlockSequences(const seqDef* sp, size_t nbSeqs, +static size_t sizeBlockSequences(const SeqDef* sp, size_t nbSeqs, size_t targetBudget, size_t avgLitCost, size_t avgSeqCost, int firstSubBlock) { @@ -486,9 +486,9 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr, const int bmi2, U32 lastBlock, void* workspace, size_t wkspSize) { - const seqDef* const sstart = seqStorePtr->sequencesStart; - const seqDef* const send = seqStorePtr->sequences; - const seqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */ + const SeqDef* const sstart = seqStorePtr->sequencesStart; + const SeqDef* const send = seqStorePtr->sequences; + const SeqDef* sp = sstart; /* tracks progresses within seqStorePtr->sequences */ size_t const nbSeqs = (size_t)(send - sstart); const BYTE* const lstart = seqStorePtr->litStart; const BYTE* const lend = seqStorePtr->lit; @@ -647,7 +647,7 @@ static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr, op += cSize; /* We have to regenerate the repcodes because we've skipped some sequences */ if (sp < send) { - const seqDef* seq; + const SeqDef* seq; repcodes_t rep; ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep)); for (seq = sstart; seq < sp; ++seq) { diff --git a/lib/dictBuilder/zdict.c b/lib/dictBuilder/zdict.c index 82e999e80..1164f03f5 100644 --- a/lib/dictBuilder/zdict.c +++ b/lib/dictBuilder/zdict.c @@ -608,7 +608,7 @@ static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params, } if (nbSeq >= 2) { /* rep offsets */ - const seqDef* const seq = seqStorePtr->sequencesStart; + const SeqDef* const seq = seqStorePtr->sequencesStart; U32 offset1 = seq[0].offBase - ZSTD_REP_NUM; U32 offset2 = seq[1].offBase - ZSTD_REP_NUM; if (offset1 >= MAXREPOFFSET) offset1 = 0; diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c index f25e5dc7c..dd425ac52 100644 --- a/tests/decodecorpus.c +++ b/tests/decodecorpus.c @@ -182,7 +182,7 @@ BYTE CONTENT_BUFFER[MAX_DECOMPRESSED_SIZE]; BYTE FRAME_BUFFER[MAX_DECOMPRESSED_SIZE * 2]; BYTE LITERAL_BUFFER[ZSTD_BLOCKSIZE_MAX]; -seqDef SEQUENCE_BUFFER[MAX_NB_SEQ]; +SeqDef SEQUENCE_BUFFER[MAX_NB_SEQ]; BYTE SEQUENCE_LITERAL_BUFFER[ZSTD_BLOCKSIZE_MAX]; /* storeSeq expects a place to copy literals to */ BYTE SEQUENCE_LLCODE[ZSTD_BLOCKSIZE_MAX]; BYTE SEQUENCE_MLCODE[ZSTD_BLOCKSIZE_MAX]; @@ -842,7 +842,7 @@ static size_t writeSequences(U32* seed, frame_t* frame, seqStore_t* seqStorePtr, FSE_CTable* CTable_OffsetBits = frame->stats.offcodeCTable; FSE_CTable* CTable_MatchLength = frame->stats.matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ - const seqDef* const sequences = seqStorePtr->sequencesStart; + const SeqDef* const sequences = seqStorePtr->sequencesStart; const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; From a2245721ca3e91261d7c948f7a71d195caf1f871 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 11:09:52 -0800 Subject: [PATCH 490/937] codemod: seqStore_t -> SeqStore_t same idea, SeqStore_t is a type name, it should start with a Capital letter. --- lib/compress/zstd_compress.c | 50 ++++++++++----------- lib/compress/zstd_compress_internal.h | 36 +++++++-------- lib/compress/zstd_compress_superblock.c | 6 +-- lib/compress/zstd_double_fast.c | 14 +++--- lib/compress/zstd_double_fast.h | 6 +-- lib/compress/zstd_fast.c | 14 +++--- lib/compress/zstd_fast.h | 6 +-- lib/compress/zstd_lazy.c | 58 ++++++++++++------------- lib/compress/zstd_lazy.h | 54 +++++++++++------------ lib/compress/zstd_ldm.c | 2 +- lib/compress/zstd_ldm.h | 2 +- lib/compress/zstd_opt.c | 22 +++++----- lib/compress/zstd_opt.h | 14 +++--- lib/dictBuilder/zdict.c | 2 +- lib/legacy/zstd_v01.c | 4 +- lib/legacy/zstd_v02.c | 2 +- lib/legacy/zstd_v03.c | 2 +- lib/legacy/zstd_v05.c | 2 +- lib/legacy/zstd_v06.c | 4 +- lib/legacy/zstd_v07.c | 4 +- tests/decodecorpus.c | 8 ++-- 21 files changed, 156 insertions(+), 156 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 16544e985..075f491d6 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -218,7 +218,7 @@ size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs) } /* private API call, for dictBuilder only */ -const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); } +const SeqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); } /* Returns true if the strategy supports using a row based matchfinder */ static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) { @@ -2698,7 +2698,7 @@ static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* par /* See doc/zstd_compression_format.md for detailed format description */ -int ZSTD_seqToCodes(const seqStore_t* seqStorePtr) +int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr) { const SeqDef* const sequences = seqStorePtr->sequencesStart; BYTE* const llCodeTable = seqStorePtr->llCode; @@ -2769,7 +2769,7 @@ typedef struct { */ static ZSTD_symbolEncodingTypeStats_t ZSTD_buildSequencesStatistics( - const seqStore_t* seqStorePtr, size_t nbSeq, + const SeqStore_t* seqStorePtr, size_t nbSeq, const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy, BYTE* dst, const BYTE* const dstEnd, ZSTD_strategy strategy, unsigned* countWorkspace, @@ -2894,7 +2894,7 @@ ZSTD_buildSequencesStatistics( #define SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO 20 MEM_STATIC size_t ZSTD_entropyCompressSeqStore_internal( - const seqStore_t* seqStorePtr, + const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, @@ -3014,7 +3014,7 @@ ZSTD_entropyCompressSeqStore_internal( MEM_STATIC size_t ZSTD_entropyCompressSeqStore( - const seqStore_t* seqStorePtr, + const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, @@ -3137,14 +3137,14 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS return selectedCompressor; } -static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr, +static void ZSTD_storeLastLiterals(SeqStore_t* seqStorePtr, const BYTE* anchor, size_t lastLLSize) { ZSTD_memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } -void ZSTD_resetSeqStore(seqStore_t* ssPtr) +void ZSTD_resetSeqStore(SeqStore_t* ssPtr) { ssPtr->lit = ssPtr->litStart; ssPtr->sequences = ssPtr->sequencesStart; @@ -3383,7 +3383,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) return ZSTDbss_compress; } -static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const seqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM]) +static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM]) { const SeqDef* inSeqs = seqStore->sequencesStart; const size_t nbInSequences = seqStore->sequences - inSeqs; @@ -3552,7 +3552,7 @@ static int ZSTD_isRLE(const BYTE* src, size_t length) { * This is just a heuristic based on the compressibility. * It may return both false positives and false negatives. */ -static int ZSTD_maybeRLE(seqStore_t const* seqStore) +static int ZSTD_maybeRLE(SeqStore_t const* seqStore) { size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart); size_t const nbLits = (size_t)(seqStore->lit - seqStore->litStart); @@ -3714,7 +3714,7 @@ ZSTD_buildDummySequencesStatistics(ZSTD_fseCTables_t* nextEntropy) * @return : size of fse tables or error code */ static size_t ZSTD_buildBlockEntropyStats_sequences( - const seqStore_t* seqStorePtr, + const SeqStore_t* seqStorePtr, const ZSTD_fseCTables_t* prevEntropy, ZSTD_fseCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, @@ -3753,7 +3753,7 @@ ZSTD_buildBlockEntropyStats_sequences( * Note : also employed in superblock */ size_t ZSTD_buildBlockEntropyStats( - const seqStore_t* seqStorePtr, + const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, @@ -3902,7 +3902,7 @@ ZSTD_estimateBlockSize(const BYTE* literals, size_t litSize, * @return: estimated compressed size of the seqStore, or a zstd error. */ static size_t -ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t* seqStore, ZSTD_CCtx* zc) +ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(SeqStore_t* seqStore, ZSTD_CCtx* zc) { ZSTD_entropyCTablesMetadata_t* const entropyMetadata = &zc->blockSplitCtx.entropyMetadata; DEBUGLOG(6, "ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize()"); @@ -3923,7 +3923,7 @@ ZSTD_buildEntropyStatisticsAndEstimateSubBlockSize(seqStore_t* seqStore, ZSTD_CC } /* Returns literals bytes represented in a seqStore */ -static size_t ZSTD_countSeqStoreLiteralsBytes(const seqStore_t* const seqStore) +static size_t ZSTD_countSeqStoreLiteralsBytes(const SeqStore_t* const seqStore) { size_t literalsBytes = 0; size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart); @@ -3938,7 +3938,7 @@ static size_t ZSTD_countSeqStoreLiteralsBytes(const seqStore_t* const seqStore) } /* Returns match bytes represented in a seqStore */ -static size_t ZSTD_countSeqStoreMatchBytes(const seqStore_t* const seqStore) +static size_t ZSTD_countSeqStoreMatchBytes(const SeqStore_t* const seqStore) { size_t matchBytes = 0; size_t const nbSeqs = (size_t)(seqStore->sequences - seqStore->sequencesStart); @@ -3955,8 +3955,8 @@ 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, - const seqStore_t* originalSeqStore, +static void ZSTD_deriveSeqStoreChunk(SeqStore_t* resultSeqStore, + const SeqStore_t* originalSeqStore, size_t startIdx, size_t endIdx) { *resultSeqStore = *originalSeqStore; @@ -4025,7 +4025,7 @@ ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, c */ static void ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRepcodes, - const seqStore_t* const seqStore, U32 const nbSeq) + const SeqStore_t* const seqStore, U32 const nbSeq) { U32 idx = 0; U32 const longLitLenIdx = seqStore->longLengthType == ZSTD_llt_literalLength ? seqStore->longLengthPos : nbSeq; @@ -4060,7 +4060,7 @@ ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRe */ static size_t ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, - const seqStore_t* const seqStore, + const SeqStore_t* const seqStore, repcodes_t* const dRep, repcodes_t* const cRep, void* dst, size_t dstCapacity, const void* src, size_t srcSize, @@ -4152,11 +4152,11 @@ typedef struct { */ static void ZSTD_deriveBlockSplitsHelper(seqStoreSplits* splits, size_t startIdx, size_t endIdx, - ZSTD_CCtx* zc, const seqStore_t* origSeqStore) + ZSTD_CCtx* zc, const SeqStore_t* origSeqStore) { - seqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk; - seqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore; - seqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore; + SeqStore_t* const fullSeqStoreChunk = &zc->blockSplitCtx.fullSeqStoreChunk; + SeqStore_t* const firstHalfSeqStore = &zc->blockSplitCtx.firstHalfSeqStore; + SeqStore_t* const secondHalfSeqStore = &zc->blockSplitCtx.secondHalfSeqStore; size_t estimatedOriginalSize; size_t estimatedFirstHalfSize; size_t estimatedSecondHalfSize; @@ -4226,8 +4226,8 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, size_t i = 0; size_t srcBytesTotal = 0; U32* const partitions = zc->blockSplitCtx.partitions; /* size == ZSTD_MAX_NB_BLOCK_SPLITS */ - seqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore; - seqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore; + SeqStore_t* const nextSeqStore = &zc->blockSplitCtx.nextSeqStore; + SeqStore_t* const currSeqStore = &zc->blockSplitCtx.currSeqStore; size_t const numSplits = ZSTD_deriveBlockSplits(zc, partitions, nbSeq); /* If a block is split and some partitions are emitted as RLE/uncompressed, then repcode history @@ -4248,7 +4248,7 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, repcodes_t cRep; ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t)); ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t)); - ZSTD_memset(nextSeqStore, 0, sizeof(seqStore_t)); + ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t)); DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)", (unsigned)dstCapacity, (unsigned)zc->blockState.matchState.window.dictLimit, diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index fcd8622cf..121885e6c 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -92,7 +92,7 @@ typedef struct SeqDef_s { U16 mlBase; /* mlBase == matchLength - MINMATCH */ } SeqDef; -/* Controls whether seqStore has a single "long" litLength or matchLength. See seqStore_t. */ +/* Controls whether seqStore has a single "long" litLength or matchLength. See SeqStore_t. */ typedef enum { ZSTD_llt_none = 0, /* no longLengthType */ ZSTD_llt_literalLength = 1, /* represents a long literal */ @@ -116,7 +116,7 @@ typedef struct { */ ZSTD_longLengthType_e longLengthType; U32 longLengthPos; /* Index of the sequence to apply long length modification to */ -} seqStore_t; +} SeqStore_t; typedef struct { U32 litLength; @@ -127,7 +127,7 @@ typedef struct { * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength. */ -MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, SeqDef const* seq) +MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore, SeqDef const* seq) { ZSTD_sequenceLength seqLen; seqLen.litLength = seq->litLength; @@ -143,8 +143,8 @@ MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore return seqLen; } -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) */ +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) */ /*********************************************** @@ -184,7 +184,7 @@ typedef struct { * Builds entropy for the block. * @return : 0 on success or error code */ size_t ZSTD_buildBlockEntropyStats( - const seqStore_t* seqStorePtr, + const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, @@ -469,11 +469,11 @@ typedef enum { */ #define ZSTD_MAX_NB_BLOCK_SPLITS 196 typedef struct { - seqStore_t fullSeqStoreChunk; - seqStore_t firstHalfSeqStore; - seqStore_t secondHalfSeqStore; - seqStore_t currSeqStore; - seqStore_t nextSeqStore; + SeqStore_t fullSeqStoreChunk; + SeqStore_t firstHalfSeqStore; + SeqStore_t secondHalfSeqStore; + SeqStore_t currSeqStore; + SeqStore_t nextSeqStore; U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS]; ZSTD_entropyCTablesMetadata_t entropyMetadata; @@ -502,7 +502,7 @@ struct ZSTD_CCtx_s { int isFirstBlock; int initialized; - seqStore_t seqStore; /* sequences storage ptrs */ + SeqStore_t seqStore; /* sequences storage ptrs */ ldmState_t ldmState; /* long distance matching state */ rawSeq* ldmSequences; /* Storage for the ldm output sequences */ size_t maxNbLdmSequences; @@ -586,7 +586,7 @@ typedef enum { } ZSTD_cParamMode_e; typedef size_t (*ZSTD_blockCompressor) ( - ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); @@ -736,13 +736,13 @@ ZSTD_safecopyLiterals(BYTE* op, BYTE const* ip, BYTE const* const iend, BYTE con #define OFFBASE_TO_REPCODE(o) (assert(OFFBASE_IS_REPCODE(o)), (o)) /* returns ID 1,2,3 */ /*! ZSTD_storeSeqOnly() : - * Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t. + * Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t. * Literals themselves are not copied, but @litPtr is updated. * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE(). * @matchLength : must be >= MINMATCH */ HINT_INLINE UNUSED_ATTR void -ZSTD_storeSeqOnly(seqStore_t* seqStorePtr, +ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr, size_t litLength, U32 offBase, size_t matchLength) @@ -787,13 +787,13 @@ ZSTD_storeSeqOnly(seqStore_t* seqStorePtr, } /*! ZSTD_storeSeq() : - * Store a sequence (litlen, litPtr, offBase and matchLength) into seqStore_t. + * Store a sequence (litlen, litPtr, offBase and matchLength) into SeqStore_t. * @offBase : Users should employ macros REPCODE_TO_OFFBASE() and OFFSET_TO_OFFBASE(). * @matchLength : must be >= MINMATCH * Allowed to over-read literals up to litLimit. */ HINT_INLINE UNUSED_ATTR void -ZSTD_storeSeq(seqStore_t* seqStorePtr, +ZSTD_storeSeq(SeqStore_t* seqStorePtr, size_t litLength, const BYTE* literals, const BYTE* litLimit, U32 offBase, size_t matchLength) @@ -1560,7 +1560,7 @@ size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs, const ZSTD_CDict* cdict, const ZSTD_CCtx_params* params, unsigned long long pledgedSrcSize); -void ZSTD_resetSeqStore(seqStore_t* ssPtr); +void ZSTD_resetSeqStore(SeqStore_t* ssPtr); /*! ZSTD_getCParamsFromCDict() : * as the name implies */ diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index a8882c169..d74f44548 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -126,7 +126,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, } static size_t -ZSTD_seqDecompressedSize(seqStore_t const* seqStore, +ZSTD_seqDecompressedSize(SeqStore_t const* seqStore, const SeqDef* sequences, size_t nbSeqs, size_t litSize, int lastSubBlock) { @@ -426,7 +426,7 @@ static int ZSTD_needSequenceEntropyTables(ZSTD_fseCTablesMetadata_t const* fseMe return 0; } -static size_t countLiterals(seqStore_t const* seqStore, const SeqDef* sp, size_t seqCount) +static size_t countLiterals(SeqStore_t const* seqStore, const SeqDef* sp, size_t seqCount) { size_t n, total = 0; assert(sp != NULL); @@ -476,7 +476,7 @@ static size_t sizeBlockSequences(const SeqDef* sp, size_t nbSeqs, * Sub-blocks are all compressed, except the last one when beneficial. * @return : compressed size of the super block (which features multiple ZSTD blocks) * or 0 if it failed to compress. */ -static size_t ZSTD_compressSubBlock_multi(const seqStore_t* seqStorePtr, +static size_t ZSTD_compressSubBlock_multi(const SeqStore_t* seqStorePtr, const ZSTD_compressedBlockState_t* prevCBlock, ZSTD_compressedBlockState_t* nextCBlock, const ZSTD_entropyCTablesMetadata_t* entropyMetadata, diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 50d698b37..1406c2d50 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -103,7 +103,7 @@ void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_noDict_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { ZSTD_compressionParameters const* cParams = &ms->cParams; @@ -326,7 +326,7 @@ _match_stored: FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { @@ -548,7 +548,7 @@ _match_stored: #define ZSTD_GEN_DFAST_FN(dictMode, mls) \ static size_t ZSTD_compressBlock_doubleFast_##dictMode##_##mls( \ - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ return ZSTD_compressBlock_doubleFast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mls); \ @@ -566,7 +566,7 @@ ZSTD_GEN_DFAST_FN(dictMatchState, 7) size_t ZSTD_compressBlock_doubleFast( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { const U32 mls = ms->cParams.minMatch; @@ -586,7 +586,7 @@ size_t ZSTD_compressBlock_doubleFast( size_t ZSTD_compressBlock_doubleFast_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { const U32 mls = ms->cParams.minMatch; @@ -608,7 +608,7 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_extDict_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { @@ -757,7 +757,7 @@ ZSTD_GEN_DFAST_FN(extDict, 6) ZSTD_GEN_DFAST_FN(extDict, 7) size_t ZSTD_compressBlock_doubleFast_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h index ce6ed8c97..1a746fab9 100644 --- a/lib/compress/zstd_double_fast.h +++ b/lib/compress/zstd_double_fast.h @@ -25,13 +25,13 @@ void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, ZSTD_tableFillPurpose_e tfp); size_t ZSTD_compressBlock_doubleFast( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_doubleFast_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_doubleFast_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_DOUBLEFAST ZSTD_compressBlock_doubleFast diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 5373e3640..3c8d5b527 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -190,7 +190,7 @@ ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 ma FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_noDict_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, int useCmov) { @@ -424,7 +424,7 @@ _match: /* Requires: ip0, match0, offcode */ #define ZSTD_GEN_FAST_FN(dictMode, mml, cmov) \ static size_t ZSTD_compressBlock_fast_##dictMode##_##mml##_##cmov( \ - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mml, cmov); \ @@ -441,7 +441,7 @@ ZSTD_GEN_FAST_FN(noDict, 6, 0) ZSTD_GEN_FAST_FN(noDict, 7, 0) size_t ZSTD_compressBlock_fast( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mml = ms->cParams.minMatch; @@ -481,7 +481,7 @@ size_t ZSTD_compressBlock_fast( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_dictMatchState_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, U32 const hasStep) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -684,7 +684,7 @@ ZSTD_GEN_FAST_FN(dictMatchState, 6, 0) ZSTD_GEN_FAST_FN(dictMatchState, 7, 0) size_t ZSTD_compressBlock_fast_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; @@ -707,7 +707,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_extDict_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, U32 const hasStep) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -965,7 +965,7 @@ ZSTD_GEN_FAST_FN(extDict, 6, 0) ZSTD_GEN_FAST_FN(extDict, 7, 0) size_t ZSTD_compressBlock_fast_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; diff --git a/lib/compress/zstd_fast.h b/lib/compress/zstd_fast.h index 9e4236b47..5a971cf32 100644 --- a/lib/compress/zstd_fast.h +++ b/lib/compress/zstd_fast.h @@ -22,13 +22,13 @@ void ZSTD_fillHashTable(ZSTD_matchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp); size_t ZSTD_compressBlock_fast( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_fast_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_fast_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #if defined (__cplusplus) diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index cfbadf458..9fe56c76b 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1514,7 +1514,7 @@ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth, @@ -1782,42 +1782,42 @@ _storeSequence: #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict); } size_t ZSTD_compressBlock_greedy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_greedy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict); } size_t ZSTD_compressBlock_greedy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch); @@ -1826,42 +1826,42 @@ size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_lazy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch); @@ -1870,42 +1870,42 @@ size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch); @@ -1914,14 +1914,14 @@ size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState); @@ -1935,7 +1935,7 @@ size_t ZSTD_compressBlock_btlazy2_dictMatchState( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_extDict_generic( - ZSTD_matchState_t* ms, seqStore_t* seqStore, + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth) @@ -2139,14 +2139,14 @@ _storeSequence: #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0); } size_t ZSTD_compressBlock_greedy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0); @@ -2155,7 +2155,7 @@ size_t ZSTD_compressBlock_greedy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2163,7 +2163,7 @@ size_t ZSTD_compressBlock_lazy_extDict( } size_t ZSTD_compressBlock_lazy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2173,7 +2173,7 @@ size_t ZSTD_compressBlock_lazy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2181,7 +2181,7 @@ size_t ZSTD_compressBlock_lazy2_extDict( } size_t ZSTD_compressBlock_lazy2_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2); @@ -2190,7 +2190,7 @@ size_t ZSTD_compressBlock_lazy2_extDict_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h index 3635813bd..21258145e 100644 --- a/lib/compress/zstd_lazy.h +++ b/lib/compress/zstd_lazy.h @@ -41,28 +41,28 @@ void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const redu #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_GREEDY ZSTD_compressBlock_greedy @@ -86,28 +86,28 @@ size_t ZSTD_compressBlock_greedy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_LAZY ZSTD_compressBlock_lazy @@ -131,28 +131,28 @@ size_t ZSTD_compressBlock_lazy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_extDict_row( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_LAZY2 ZSTD_compressBlock_lazy2 @@ -176,13 +176,13 @@ size_t ZSTD_compressBlock_lazy2_extDict_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btlazy2_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTLAZY2 ZSTD_compressBlock_btlazy2 diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index e06431374..e636a42c0 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -665,7 +665,7 @@ void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) { } size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize) { diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h index f147021d2..624caf937 100644 --- a/lib/compress/zstd_ldm.h +++ b/lib/compress/zstd_ldm.h @@ -65,7 +65,7 @@ size_t ZSTD_ldm_generateSequences( * NOTE: This function does not return any errors. */ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize); diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index e4a8ee81e..1045cdd2c 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1073,7 +1073,7 @@ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, - seqStore_t* seqStore, + SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const int optLevel, @@ -1440,7 +1440,7 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt0( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode); @@ -1449,7 +1449,7 @@ static size_t ZSTD_compressBlock_opt0( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); @@ -1458,7 +1458,7 @@ static size_t ZSTD_compressBlock_opt2( #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_compressBlock_btopt"); @@ -1478,7 +1478,7 @@ size_t ZSTD_compressBlock_btopt( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_initStats_ultra(ZSTD_matchState_t* ms, - seqStore_t* seqStore, + SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { @@ -1503,7 +1503,7 @@ void ZSTD_initStats_ultra(ZSTD_matchState_t* ms, } size_t ZSTD_compressBlock_btultra( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize); @@ -1511,7 +1511,7 @@ size_t ZSTD_compressBlock_btultra( } size_t ZSTD_compressBlock_btultra2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { U32 const curr = (U32)((const BYTE*)src - ms->window.base); @@ -1541,14 +1541,14 @@ size_t ZSTD_compressBlock_btultra2( #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_btopt_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict); @@ -1557,14 +1557,14 @@ size_t ZSTD_compressBlock_btopt_extDict( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_btultra_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict); diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index d4e711315..9e1cff91a 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -26,13 +26,13 @@ void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btopt_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btopt_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTOPT ZSTD_compressBlock_btopt @@ -46,20 +46,20 @@ size_t ZSTD_compressBlock_btopt_extDict( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btultra_dictMatchState( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btultra_extDict( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); /* note : no btultra2 variant for extDict nor dictMatchState, * because btultra2 is not meant to work with dictionaries * and is only specific for the first block (no prefix) */ size_t ZSTD_compressBlock_btultra2( - ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTULTRA ZSTD_compressBlock_btultra diff --git a/lib/dictBuilder/zdict.c b/lib/dictBuilder/zdict.c index 1164f03f5..d5e60a4da 100644 --- a/lib/dictBuilder/zdict.c +++ b/lib/dictBuilder/zdict.c @@ -580,7 +580,7 @@ static void ZDICT_countEStats(EStats_ress_t esr, const ZSTD_parameters* params, if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; } if (cSize) { /* if == 0; block is not compressible */ - const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc); + const SeqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc); /* literals stats */ { const BYTE* bytePtr; diff --git a/lib/legacy/zstd_v01.c b/lib/legacy/zstd_v01.c index 6cf51234a..ad3c9330e 100644 --- a/lib/legacy/zstd_v01.c +++ b/lib/legacy/zstd_v01.c @@ -1383,7 +1383,7 @@ typedef struct { BYTE* matchLength; BYTE* dumpsStart; BYTE* dumps; -} seqStore_t; +} SeqStore_t; typedef struct ZSTD_Cctx_s @@ -1391,7 +1391,7 @@ typedef struct ZSTD_Cctx_s const BYTE* base; U32 current; U32 nextUpdate; - seqStore_t seqStore; + SeqStore_t seqStore; #ifdef __AVX2__ __m256i hashTable[HASH_TABLESIZE>>3]; #else diff --git a/lib/legacy/zstd_v02.c b/lib/legacy/zstd_v02.c index 6d39b6e5b..d1e00385a 100644 --- a/lib/legacy/zstd_v02.c +++ b/lib/legacy/zstd_v02.c @@ -2722,7 +2722,7 @@ typedef struct { BYTE* matchLength; BYTE* dumpsStart; BYTE* dumps; -} seqStore_t; +} SeqStore_t; /* ************************************* diff --git a/lib/legacy/zstd_v03.c b/lib/legacy/zstd_v03.c index 47195f337..7d82db666 100644 --- a/lib/legacy/zstd_v03.c +++ b/lib/legacy/zstd_v03.c @@ -2362,7 +2362,7 @@ typedef struct { BYTE* matchLength; BYTE* dumpsStart; BYTE* dumps; -} seqStore_t; +} SeqStore_t; /* ************************************* diff --git a/lib/legacy/zstd_v05.c b/lib/legacy/zstd_v05.c index 44a877bf1..7a3af4214 100644 --- a/lib/legacy/zstd_v05.c +++ b/lib/legacy/zstd_v05.c @@ -491,7 +491,7 @@ typedef struct { U32 litLengthSum; U32 litSum; U32 offCodeSum; -} seqStore_t; +} SeqStore_t; diff --git a/lib/legacy/zstd_v06.c b/lib/legacy/zstd_v06.c index 3a8bd0c93..88a39e2a0 100644 --- a/lib/legacy/zstd_v06.c +++ b/lib/legacy/zstd_v06.c @@ -552,9 +552,9 @@ typedef struct { U32 cachedLitLength; const BYTE* cachedLiterals; ZSTDv06_stats_t stats; -} seqStore_t; +} SeqStore_t; -void ZSTDv06_seqToCodes(const seqStore_t* seqStorePtr, size_t const nbSeq); +void ZSTDv06_seqToCodes(const SeqStore_t* seqStorePtr, size_t const nbSeq); #endif /* ZSTDv06_CCOMMON_H_MODULE */ diff --git a/lib/legacy/zstd_v07.c b/lib/legacy/zstd_v07.c index 8778f079c..cdc56288c 100644 --- a/lib/legacy/zstd_v07.c +++ b/lib/legacy/zstd_v07.c @@ -2787,9 +2787,9 @@ typedef struct { U32 cachedLitLength; const BYTE* cachedLiterals; ZSTDv07_stats_t stats; -} seqStore_t; +} SeqStore_t; -void ZSTDv07_seqToCodes(const seqStore_t* seqStorePtr, size_t const nbSeq); +void ZSTDv07_seqToCodes(const SeqStore_t* seqStorePtr, size_t const nbSeq); /* custom memory allocation functions */ static const ZSTDv07_customMem defaultCustomMem = { ZSTDv07_defaultAllocFunction, ZSTDv07_defaultFreeFunction, NULL }; diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c index dd425ac52..bbe32ee72 100644 --- a/tests/decodecorpus.c +++ b/tests/decodecorpus.c @@ -657,7 +657,7 @@ static size_t writeLiteralsBlock(U32* seed, frame_t* frame, size_t contentSize) } } -static inline void initSeqStore(seqStore_t *seqStore) { +static inline void initSeqStore(SeqStore_t *seqStore) { seqStore->maxNbSeq = MAX_NB_SEQ; seqStore->maxNbLit = ZSTD_BLOCKSIZE_MAX; seqStore->sequencesStart = SEQUENCE_BUFFER; @@ -671,7 +671,7 @@ static inline void initSeqStore(seqStore_t *seqStore) { /* Randomly generate sequence commands */ static U32 -generateSequences(U32* seed, frame_t* frame, seqStore_t* seqStore, +generateSequences(U32* seed, frame_t* frame, SeqStore_t* seqStore, size_t contentSize, size_t literalsSize, dictInfo info) { /* The total length of all the matches */ @@ -832,7 +832,7 @@ static int isSymbolSubset(const BYTE* symbols, size_t len, const BYTE* set, BYTE return 1; } -static size_t writeSequences(U32* seed, frame_t* frame, seqStore_t* seqStorePtr, +static size_t writeSequences(U32* seed, frame_t* frame, SeqStore_t* seqStorePtr, size_t nbSeq) { /* This code is mostly copied from ZSTD_compressSequences in zstd_compress.c */ @@ -1028,7 +1028,7 @@ static size_t writeSequences(U32* seed, frame_t* frame, seqStore_t* seqStorePtr, static size_t writeSequencesBlock(U32* seed, frame_t* frame, size_t contentSize, size_t literalsSize, dictInfo info) { - seqStore_t seqStore; + SeqStore_t seqStore; size_t numSequences; From 8d4506bc9463607725e43131b71b2f09b7e1109d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 11:27:03 -0800 Subject: [PATCH 491/937] codemod: ZSTD_sequenceLength -> ZSTD_SequenceLength --- lib/compress/zstd_compress_internal.h | 8 ++++---- lib/compress/zstd_compress_superblock.c | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 121885e6c..92812192f 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -121,15 +121,15 @@ typedef struct { typedef struct { U32 litLength; U32 matchLength; -} ZSTD_sequenceLength; +} ZSTD_SequenceLength; /** - * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences + * Returns the ZSTD_SequenceLength for the given sequences. It handles the decoding of long sequences * indicated by longLengthPos and longLengthType, and adds MINMATCH back to matchLength. */ -MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore, SeqDef const* seq) +MEM_STATIC ZSTD_SequenceLength ZSTD_getSequenceLength(SeqStore_t const* seqStore, SeqDef const* seq) { - ZSTD_sequenceLength seqLen; + ZSTD_SequenceLength seqLen; seqLen.litLength = seq->litLength; seqLen.matchLength = seq->mlBase + MINMATCH; if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) { diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index d74f44548..f2806c9ab 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -134,7 +134,7 @@ ZSTD_seqDecompressedSize(SeqStore_t const* seqStore, size_t litLengthSum = 0; size_t n; for (n=0; n Date: Tue, 10 Dec 2024 11:34:12 -0800 Subject: [PATCH 492/937] codemod: symbolEncodingType_e -> SymbolEncodingType_e --- lib/common/zstd_internal.h | 2 +- lib/compress/zstd_compress.c | 14 +++++++------- lib/compress/zstd_compress_internal.h | 8 ++++---- lib/compress/zstd_compress_literals.c | 2 +- lib/compress/zstd_compress_sequences.c | 4 ++-- lib/compress/zstd_compress_sequences.h | 6 +++--- lib/compress/zstd_compress_superblock.c | 4 ++-- lib/decompress/zstd_decompress_block.c | 10 +++++----- tests/decodecorpus.c | 2 +- tests/fullbench.c | 2 +- 10 files changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index 1122e2f39..b67ca8633 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -95,7 +95,7 @@ typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e; #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */) /* for a non-null block */ #define MIN_LITERALS_FOR_4_STREAMS 6 -typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e; +typedef enum { set_basic, set_rle, set_compressed, set_repeat } SymbolEncodingType_e; #define LONGNBSEQ 0x7F00 diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 075f491d6..1715dad3f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2805,7 +2805,7 @@ ZSTD_buildSequencesStatistics( assert(!(stats.LLtype < set_compressed && nextEntropy->litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable( op, (size_t)(oend - op), - CTable_LitLength, LLFSELog, (symbolEncodingType_e)stats.LLtype, + CTable_LitLength, LLFSELog, (SymbolEncodingType_e)stats.LLtype, countWorkspace, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL, prevEntropy->litlengthCTable, @@ -2837,7 +2837,7 @@ ZSTD_buildSequencesStatistics( assert(!(stats.Offtype < set_compressed && nextEntropy->offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable( op, (size_t)(oend - op), - CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)stats.Offtype, + CTable_OffsetBits, OffFSELog, (SymbolEncodingType_e)stats.Offtype, countWorkspace, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff, prevEntropy->offcodeCTable, @@ -2867,7 +2867,7 @@ ZSTD_buildSequencesStatistics( assert(!(stats.MLtype < set_compressed && nextEntropy->matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable( op, (size_t)(oend - op), - CTable_MatchLength, MLFSELog, (symbolEncodingType_e)stats.MLtype, + CTable_MatchLength, MLFSELog, (SymbolEncodingType_e)stats.MLtype, countWorkspace, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML, prevEntropy->matchlengthCTable, @@ -3738,9 +3738,9 @@ ZSTD_buildBlockEntropyStats_sequences( entropyWorkspace, entropyWorkspaceSize) : ZSTD_buildDummySequencesStatistics(nextEntropy); FORWARD_IF_ERROR(stats.size, "ZSTD_buildSequencesStatistics failed!"); - fseMetadata->llType = (symbolEncodingType_e) stats.LLtype; - fseMetadata->ofType = (symbolEncodingType_e) stats.Offtype; - fseMetadata->mlType = (symbolEncodingType_e) stats.MLtype; + fseMetadata->llType = (SymbolEncodingType_e) stats.LLtype; + fseMetadata->ofType = (SymbolEncodingType_e) stats.Offtype; + fseMetadata->mlType = (SymbolEncodingType_e) stats.MLtype; fseMetadata->lastCountSize = stats.lastCountSize; return stats.size; } @@ -3811,7 +3811,7 @@ ZSTD_estimateBlockSize_literal(const BYTE* literals, size_t litSize, /* Returns the size estimate for the FSE-compressed symbols (of, ml, ll) of a block */ static size_t -ZSTD_estimateBlockSize_symbolType(symbolEncodingType_e type, +ZSTD_estimateBlockSize_symbolType(SymbolEncodingType_e type, const BYTE* codeTable, size_t nbSeq, unsigned maxCode, const FSE_CTable* fseCTable, const U8* additionalBits, diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 92812192f..3dcd52c95 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -156,7 +156,7 @@ int ZSTD_seqToCodes(const SeqStore_t* seqStorePtr); /* compress, dictBuilder, * hufDesSize refers to the size of huffman tree description in bytes. * This metadata is populated in ZSTD_buildBlockEntropyStats_literals() */ typedef struct { - symbolEncodingType_e hType; + SymbolEncodingType_e hType; BYTE hufDesBuffer[ZSTD_MAX_HUF_HEADER_SIZE]; size_t hufDesSize; } ZSTD_hufCTablesMetadata_t; @@ -167,9 +167,9 @@ typedef struct { * fseTablesSize refers to the size of fse tables in bytes. * This metadata is populated in ZSTD_buildBlockEntropyStats_sequences() */ typedef struct { - symbolEncodingType_e llType; - symbolEncodingType_e ofType; - symbolEncodingType_e mlType; + SymbolEncodingType_e llType; + SymbolEncodingType_e ofType; + SymbolEncodingType_e mlType; BYTE fseTablesBuffer[ZSTD_MAX_FSE_HEADERS_SIZE]; size_t fseTablesSize; size_t lastCountSize; /* This is to account for bug in 1.3.4. More detail in ZSTD_entropyCompressSeqStore_internal() */ diff --git a/lib/compress/zstd_compress_literals.c b/lib/compress/zstd_compress_literals.c index bfd4f11ab..06036de5d 100644 --- a/lib/compress/zstd_compress_literals.c +++ b/lib/compress/zstd_compress_literals.c @@ -140,7 +140,7 @@ size_t ZSTD_compressLiterals ( size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB); BYTE* const ostart = (BYTE*)dst; U32 singleStream = srcSize < 256; - symbolEncodingType_e hType = set_compressed; + SymbolEncodingType_e hType = set_compressed; size_t cLitSize; DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i, srcSize=%u, dstCapacity=%zu)", diff --git a/lib/compress/zstd_compress_sequences.c b/lib/compress/zstd_compress_sequences.c index 7a9d595b1..d4d28d819 100644 --- a/lib/compress/zstd_compress_sequences.c +++ b/lib/compress/zstd_compress_sequences.c @@ -153,7 +153,7 @@ size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog, return cost >> 8; } -symbolEncodingType_e +SymbolEncodingType_e ZSTD_selectEncodingType( FSE_repeat* repeatMode, unsigned const* count, unsigned const max, size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, @@ -241,7 +241,7 @@ typedef struct { size_t ZSTD_buildCTable(void* dst, size_t dstCapacity, - FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type, + FSE_CTable* nextCTable, U32 FSELog, SymbolEncodingType_e type, unsigned* count, U32 max, const BYTE* codeTable, size_t nbSeq, const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, diff --git a/lib/compress/zstd_compress_sequences.h b/lib/compress/zstd_compress_sequences.h index b974d1cfc..03247ea75 100644 --- a/lib/compress/zstd_compress_sequences.h +++ b/lib/compress/zstd_compress_sequences.h @@ -13,14 +13,14 @@ #include "zstd_compress_internal.h" /* SeqDef */ #include "../common/fse.h" /* FSE_repeat, FSE_CTable */ -#include "../common/zstd_internal.h" /* symbolEncodingType_e, ZSTD_strategy */ +#include "../common/zstd_internal.h" /* SymbolEncodingType_e, ZSTD_strategy */ typedef enum { ZSTD_defaultDisallowed = 0, ZSTD_defaultAllowed = 1 } ZSTD_defaultPolicy_e; -symbolEncodingType_e +SymbolEncodingType_e ZSTD_selectEncodingType( FSE_repeat* repeatMode, unsigned const* count, unsigned const max, size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, @@ -31,7 +31,7 @@ ZSTD_selectEncodingType( size_t ZSTD_buildCTable(void* dst, size_t dstCapacity, - FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type, + FSE_CTable* nextCTable, U32 FSELog, SymbolEncodingType_e type, unsigned* count, U32 max, const BYTE* codeTable, size_t nbSeq, const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax, diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index f2806c9ab..672af2d32 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -51,7 +51,7 @@ ZSTD_compressSubBlock_literal(const HUF_CElt* hufTable, BYTE* const oend = ostart + dstSize; BYTE* op = ostart + lhSize; U32 const singleStream = lhSize == 3; - symbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat; + SymbolEncodingType_e hType = writeEntropy ? hufMetadata->hType : set_repeat; size_t cLitSize = 0; DEBUGLOG(5, "ZSTD_compressSubBlock_literal (litSize=%zu, lhSize=%zu, writeEntropy=%d)", litSize, lhSize, writeEntropy); @@ -327,7 +327,7 @@ static size_t ZSTD_estimateSubBlockSize_literal(const BYTE* literals, size_t lit return 0; } -static size_t ZSTD_estimateSubBlockSize_symbolType(symbolEncodingType_e type, +static size_t ZSTD_estimateSubBlockSize_symbolType(SymbolEncodingType_e type, const BYTE* codeTable, unsigned maxCode, size_t nbSeq, const FSE_CTable* fseCTable, const U8* additionalBits, diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index f865692f5..ca5044376 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -139,7 +139,7 @@ static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx, RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, ""); { const BYTE* const istart = (const BYTE*) src; - symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3); + SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3); size_t const blockSizeMax = ZSTD_blockSizeMax(dctx); switch(litEncType) @@ -645,7 +645,7 @@ void ZSTD_buildFSETable(ZSTD_seqSymbol* dt, * @return : nb bytes read from src, * or an error code if it fails */ static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr, - symbolEncodingType_e type, unsigned max, U32 maxLog, + SymbolEncodingType_e type, unsigned max, U32 maxLog, const void* src, size_t srcSize, const U32* baseValue, const U8* nbAdditionalBits, const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable, @@ -728,9 +728,9 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, /* FSE table descriptors */ RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */ RETURN_ERROR_IF(*ip & 3, corruption_detected, ""); /* The last field, Reserved, must be all-zeroes. */ - { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6); - symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3); - symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3); + { SymbolEncodingType_e const LLtype = (SymbolEncodingType_e)(*ip >> 6); + SymbolEncodingType_e const OFtype = (SymbolEncodingType_e)((*ip >> 4) & 3); + SymbolEncodingType_e const MLtype = (SymbolEncodingType_e)((*ip >> 2) & 3); ip++; /* Build DTables */ diff --git a/tests/decodecorpus.c b/tests/decodecorpus.c index bbe32ee72..c53d83251 100644 --- a/tests/decodecorpus.c +++ b/tests/decodecorpus.c @@ -505,7 +505,7 @@ static size_t writeLiteralsBlockCompressed(U32* seed, frame_t* frame, size_t con size_t compressedSize = 0; size_t maxLitSize = MIN(contentSize-3, g_maxBlockSize); - symbolEncodingType_e hType; + SymbolEncodingType_e hType; if (contentSize < 64) { /* make sure we get reasonably-sized literals for compression */ diff --git a/tests/fullbench.c b/tests/fullbench.c index c8f0c0af1..250359e92 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -170,7 +170,7 @@ FORCE_NOINLINE size_t ZSTD_decodeLiteralsHeader(ZSTD_DCtx* dctx, void const* src RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, ""); { BYTE const* istart = (BYTE const*)src; - symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3); + SymbolEncodingType_e const litEncType = (SymbolEncodingType_e)(istart[0] & 3); if (litEncType == set_compressed) { RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3"); { From 0442e43acadd65b35b41f1fadae301a629d7e37e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 11:40:06 -0800 Subject: [PATCH 493/937] codemod: ZSTD_defaultPolicy_e -> ZSTD_DefaultPolicy_e --- lib/compress/zstd_compress.c | 2 +- lib/compress/zstd_compress_sequences.c | 2 +- lib/compress/zstd_compress_sequences.h | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 1715dad3f..24afefa85 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2826,7 +2826,7 @@ ZSTD_buildSequencesStatistics( size_t const mostFrequent = HIST_countFast_wksp( countWorkspace, &max, ofCodeTable, nbSeq, entropyWorkspace, entropyWkspSize); /* can't fail */ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */ - ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; + ZSTD_DefaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; DEBUGLOG(5, "Building OF table"); nextEntropy->offcode_repeatMode = prevEntropy->offcode_repeatMode; stats.Offtype = ZSTD_selectEncodingType(&nextEntropy->offcode_repeatMode, diff --git a/lib/compress/zstd_compress_sequences.c b/lib/compress/zstd_compress_sequences.c index d4d28d819..7beb9daa6 100644 --- a/lib/compress/zstd_compress_sequences.c +++ b/lib/compress/zstd_compress_sequences.c @@ -159,7 +159,7 @@ ZSTD_selectEncodingType( size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, FSE_CTable const* prevCTable, short const* defaultNorm, U32 defaultNormLog, - ZSTD_defaultPolicy_e const isDefaultAllowed, + ZSTD_DefaultPolicy_e const isDefaultAllowed, ZSTD_strategy const strategy) { ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0); diff --git a/lib/compress/zstd_compress_sequences.h b/lib/compress/zstd_compress_sequences.h index 03247ea75..4be8e91f2 100644 --- a/lib/compress/zstd_compress_sequences.h +++ b/lib/compress/zstd_compress_sequences.h @@ -18,7 +18,7 @@ typedef enum { ZSTD_defaultDisallowed = 0, ZSTD_defaultAllowed = 1 -} ZSTD_defaultPolicy_e; +} ZSTD_DefaultPolicy_e; SymbolEncodingType_e ZSTD_selectEncodingType( @@ -26,7 +26,7 @@ ZSTD_selectEncodingType( size_t const mostFrequent, size_t nbSeq, unsigned const FSELog, FSE_CTable const* prevCTable, short const* defaultNorm, U32 defaultNormLog, - ZSTD_defaultPolicy_e const isDefaultAllowed, + ZSTD_DefaultPolicy_e const isDefaultAllowed, ZSTD_strategy const strategy); size_t From e9f8a119b4fcd44038dbb0d072aa44968d81bd9b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 12:02:44 -0800 Subject: [PATCH 494/937] ZSTD_entropyCompressSeqStore_internal() can accept an externally defined literals buffer --- lib/compress/zstd_compress.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 24afefa85..873c1671f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2894,11 +2894,12 @@ ZSTD_buildSequencesStatistics( #define SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO 20 MEM_STATIC size_t ZSTD_entropyCompressSeqStore_internal( + void* dst, size_t dstCapacity, + const void* literals, size_t litSize, const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, - void* dst, size_t dstCapacity, void* entropyWorkspace, size_t entropyWkspSize, const int bmi2) { @@ -2926,12 +2927,9 @@ ZSTD_entropyCompressSeqStore_internal( assert(entropyWkspSize >= HUF_WORKSPACE_SIZE); /* Compress literals */ - { const BYTE* const literals = seqStorePtr->litStart; - size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart); - size_t const numLiterals = (size_t)(seqStorePtr->lit - seqStorePtr->litStart); + { size_t const numSequences = (size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart); /* Base suspicion of uncompressibility on ratio of literals to sequences */ - unsigned const suspectUncompressible = (numSequences == 0) || (numLiterals / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO); - size_t const litSize = (size_t)(seqStorePtr->lit - literals); + int const suspectUncompressible = (numSequences == 0) || (litSize / numSequences >= SUSPECT_UNCOMPRESSIBLE_LITERAL_RATIO); size_t const cSize = ZSTD_compressLiterals( op, dstCapacity, @@ -3012,7 +3010,7 @@ ZSTD_entropyCompressSeqStore_internal( return (size_t)(op - ostart); } -MEM_STATIC size_t +static size_t ZSTD_entropyCompressSeqStore( const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, @@ -3024,8 +3022,9 @@ ZSTD_entropyCompressSeqStore( int bmi2) { size_t const cSize = ZSTD_entropyCompressSeqStore_internal( - seqStorePtr, prevEntropy, nextEntropy, cctxParams, dst, dstCapacity, + seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart), + seqStorePtr, prevEntropy, nextEntropy, cctxParams, entropyWorkspace, entropyWkspSize, bmi2); if (cSize == 0) return 0; /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block. From 0165eeb441de43ffe11b95b9073c0a694b66e6a4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 13:33:48 -0800 Subject: [PATCH 495/937] created ZSTD_entropyCompressSeqStore_wExtLitBuffer() can receive externally defined buffer of literals --- lib/compress/zstd_compress.c | 71 ++++++++++++++++++++++++------------ 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 873c1671f..4f9f17447 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1039,7 +1039,7 @@ size_t ZSTD_CCtxParams_getParameter( switch(param) { case ZSTD_c_format : - *value = CCtxParams->format; + *value = (int)CCtxParams->format; break; case ZSTD_c_compressionLevel : *value = CCtxParams->compressionLevel; @@ -1054,16 +1054,16 @@ size_t ZSTD_CCtxParams_getParameter( *value = (int)CCtxParams->cParams.chainLog; break; case ZSTD_c_searchLog : - *value = CCtxParams->cParams.searchLog; + *value = (int)CCtxParams->cParams.searchLog; break; case ZSTD_c_minMatch : - *value = CCtxParams->cParams.minMatch; + *value = (int)CCtxParams->cParams.minMatch; break; case ZSTD_c_targetLength : - *value = CCtxParams->cParams.targetLength; + *value = (int)CCtxParams->cParams.targetLength; break; case ZSTD_c_strategy : - *value = (unsigned)CCtxParams->cParams.strategy; + *value = (int)CCtxParams->cParams.strategy; break; case ZSTD_c_contentSizeFlag : *value = CCtxParams->fParams.contentSizeFlag; @@ -1078,10 +1078,10 @@ size_t ZSTD_CCtxParams_getParameter( *value = CCtxParams->forceWindow; break; case ZSTD_c_forceAttachDict : - *value = CCtxParams->attachDictPref; + *value = (int)CCtxParams->attachDictPref; break; case ZSTD_c_literalCompressionMode : - *value = CCtxParams->literalCompressionMode; + *value = (int)CCtxParams->literalCompressionMode; break; case ZSTD_c_nbWorkers : #ifndef ZSTD_MULTITHREAD @@ -1115,19 +1115,19 @@ size_t ZSTD_CCtxParams_getParameter( *value = CCtxParams->enableDedicatedDictSearch; break; case ZSTD_c_enableLongDistanceMatching : - *value = CCtxParams->ldmParams.enableLdm; + *value = (int)CCtxParams->ldmParams.enableLdm; break; case ZSTD_c_ldmHashLog : - *value = CCtxParams->ldmParams.hashLog; + *value = (int)CCtxParams->ldmParams.hashLog; break; case ZSTD_c_ldmMinMatch : - *value = CCtxParams->ldmParams.minMatchLength; + *value = (int)CCtxParams->ldmParams.minMatchLength; break; case ZSTD_c_ldmBucketSizeLog : - *value = CCtxParams->ldmParams.bucketSizeLog; + *value = (int)CCtxParams->ldmParams.bucketSizeLog; break; case ZSTD_c_ldmHashRateLog : - *value = CCtxParams->ldmParams.hashRateLog; + *value = (int)CCtxParams->ldmParams.hashRateLog; break; case ZSTD_c_targetCBlockSize : *value = (int)CCtxParams->targetCBlockSize; @@ -1401,7 +1401,7 @@ size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams) BOUNDCHECK(ZSTD_c_searchLog, (int)cParams.searchLog); BOUNDCHECK(ZSTD_c_minMatch, (int)cParams.minMatch); BOUNDCHECK(ZSTD_c_targetLength,(int)cParams.targetLength); - BOUNDCHECK(ZSTD_c_strategy, cParams.strategy); + BOUNDCHECK(ZSTD_c_strategy, (int)cParams.strategy); return 0; } @@ -2558,7 +2558,7 @@ static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx, ? ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog) : 0; size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog; - int const h3log = srcCCtx->blockState.matchState.hashLog3; + U32 const h3log = srcCCtx->blockState.matchState.hashLog3; size_t const h3Size = h3log ? ((size_t)1 << h3log) : 0; ZSTD_memcpy(dstCCtx->blockState.matchState.hashTable, @@ -3011,19 +3011,20 @@ ZSTD_entropyCompressSeqStore_internal( } static size_t -ZSTD_entropyCompressSeqStore( +ZSTD_entropyCompressSeqStore_wExtLitBuffer( + void* dst, size_t dstCapacity, + const void* literals, size_t litSize, + size_t srcSize, const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, const ZSTD_CCtx_params* cctxParams, - void* dst, size_t dstCapacity, - size_t srcSize, void* entropyWorkspace, size_t entropyWkspSize, int bmi2) { size_t const cSize = ZSTD_entropyCompressSeqStore_internal( dst, dstCapacity, - seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart), + literals, litSize, seqStorePtr, prevEntropy, nextEntropy, cctxParams, entropyWorkspace, entropyWkspSize, bmi2); if (cSize == 0) return 0; @@ -3048,6 +3049,28 @@ ZSTD_entropyCompressSeqStore( return cSize; } +static size_t +ZSTD_entropyCompressSeqStore( + const SeqStore_t* seqStorePtr, + const ZSTD_entropyCTables_t* prevEntropy, + ZSTD_entropyCTables_t* nextEntropy, + const ZSTD_CCtx_params* cctxParams, + void* dst, size_t dstCapacity, + size_t srcSize, + void* entropyWorkspace, size_t entropyWkspSize, + int bmi2) +{ + return ZSTD_entropyCompressSeqStore_wExtLitBuffer( + dst, dstCapacity, + seqStorePtr->litStart, (size_t)(seqStorePtr->lit - seqStorePtr->litStart), + srcSize, + seqStorePtr, + prevEntropy, nextEntropy, + cctxParams, + entropyWorkspace, entropyWkspSize, + bmi2); +} + /* ZSTD_selectBlockCompressor() : * Not static, but internal use only (used by long distance matcher) * assumption : strat is a valid strategy */ @@ -3101,7 +3124,7 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS ZSTD_blockCompressor selectedCompressor; ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1); - assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat)); + assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat)); DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder); if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) { static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = { @@ -3385,7 +3408,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore_t* seqStore, const U32 prevRepcodes[ZSTD_REP_NUM]) { const SeqDef* inSeqs = seqStore->sequencesStart; - const size_t nbInSequences = seqStore->sequences - inSeqs; + const size_t nbInSequences = (size_t)(seqStore->sequences - inSeqs); const size_t nbInLiterals = (size_t)(seqStore->lit - seqStore->litStart); ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex; @@ -6931,10 +6954,10 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, if (!cctx->isFirstBlock && ZSTD_maybeRLE(&cctx->seqStore) && ZSTD_isRLE(ip, blockSize)) { - /* We don't want to emit our first block as a RLE even if it qualifies because - * doing so will cause the decoder (cli only) to throw a "should consume all input error." - * This is only an issue for zstd <= v1.4.3 - */ + /* We don't want to emit our first block as RLE even if it qualifies because + * doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error + * "should consume all input error." + */ compressedSeqsSize = 1; } From c97522f7fb797cde035ab26f0ba97addb718c174 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 13:58:11 -0800 Subject: [PATCH 496/937] codemod: ZSTD_sequenceFormat_e -> ZSTD_SequenceFormat_e since it's a type name. Note: in contrast with previous names, this one is on the Public API side. So there is a #define, so that existing programs using ZSTD_sequenceFormat_e still work. --- doc/zstd_manual.html | 2 +- lib/compress/zstd_compress.c | 16 +++++++++------- lib/compress/zstd_compress_internal.h | 2 +- lib/zstd.h | 3 ++- tests/fuzz/sequence_compression_api.c | 10 +++++----- tests/fuzzer.c | 2 +- 6 files changed, 19 insertions(+), 16 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index bcd1f05da..e6f8fc504 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1317,7 +1317,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr,

typedef enum {
   ZSTD_sf_noBlockDelimiters = 0,         /* Representation of ZSTD_Sequence has no block delimiters, sequences only */
   ZSTD_sf_explicitBlockDelimiters = 1    /* Representation of ZSTD_Sequence contains explicit block delimiters */
-} ZSTD_sequenceFormat_e;
+} ZSTD_SequenceFormat_e;
 

ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize);
 

`srcSize` : size of the input buffer diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 4f9f17447..5976a8e5c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -974,7 +974,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, case ZSTD_c_blockDelimiters: BOUNDCHECK(ZSTD_c_blockDelimiters, value); - CCtxParams->blockDelimiters = (ZSTD_sequenceFormat_e)value; + CCtxParams->blockDelimiters = (ZSTD_SequenceFormat_e)value; return CCtxParams->blockDelimiters; case ZSTD_c_validateSequences: @@ -6815,10 +6815,10 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, typedef size_t (*ZSTD_sequenceCopier) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); -static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_sequenceFormat_e mode) +static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode) { ZSTD_sequenceCopier sequenceCopier = NULL; - assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, mode)); + assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode)); if (mode == ZSTD_sf_explicitBlockDelimiters) { return ZSTD_copySequencesToSeqStoreExplicitBlockDelim; } else if (mode == ZSTD_sf_noBlockDelimiters) { @@ -6862,7 +6862,7 @@ static size_t blockSize_noDelimiter(size_t blockSize, size_t remaining) return lastBlock ? remaining : blockSize; } -static size_t determine_blockSize(ZSTD_sequenceFormat_e mode, +static size_t determine_blockSize(ZSTD_SequenceFormat_e mode, size_t blockSize, size_t remaining, const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos) { @@ -6941,11 +6941,13 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, } RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); - compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore, + compressedSeqsSize = ZSTD_entropyCompressSeqStore_wExtLitBuffer( + op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, + cctx->seqStore.litStart, (size_t)(cctx->seqStore.lit - cctx->seqStore.litStart), + blockSize, + &cctx->seqStore, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, &cctx->appliedParams, - op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, - blockSize, cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, cctx->bmi2); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 3dcd52c95..2d7e0230d 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -404,7 +404,7 @@ struct ZSTD_CCtx_params_s { ZSTD_bufferMode_e outBufferMode; /* Sequence compression API */ - ZSTD_sequenceFormat_e blockDelimiters; + ZSTD_SequenceFormat_e blockDelimiters; int validateSequences; /* Block splitting diff --git a/lib/zstd.h b/lib/zstd.h index cfacd58d0..94058a1b2 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1562,7 +1562,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin(const void* src, size_t srcSi typedef enum { ZSTD_sf_noBlockDelimiters = 0, /* Representation of ZSTD_Sequence has no block delimiters, sequences only */ ZSTD_sf_explicitBlockDelimiters = 1 /* Representation of ZSTD_Sequence contains explicit block delimiters */ -} ZSTD_sequenceFormat_e; +} ZSTD_SequenceFormat_e; +#define ZSTD_sequenceFormat_e ZSTD_SequenceFormat_e /* old name */ /*! ZSTD_sequenceBound() : * `srcSize` : size of the input buffer diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c index 3c60f42c6..5e5e1e604 100644 --- a/tests/fuzz/sequence_compression_api.c +++ b/tests/fuzz/sequence_compression_api.c @@ -76,7 +76,7 @@ static char* generatePseudoRandomString(char* str, size_t size, FUZZ_dataProduce static size_t decodeSequences(void* dst, size_t nbSequences, size_t literalsSize, const void* dict, size_t dictSize, - ZSTD_sequenceFormat_e mode) + ZSTD_SequenceFormat_e mode) { const uint8_t* litPtr = literalsBuffer; const uint8_t* const litBegin = literalsBuffer; @@ -141,7 +141,7 @@ static size_t decodeSequences(void* dst, size_t nbSequences, */ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, size_t literalsSizeLimit, size_t dictSize, - size_t windowLog, ZSTD_sequenceFormat_e mode) + size_t windowLog, ZSTD_SequenceFormat_e mode) { const uint32_t repCode = 0; /* not used by sequence ingestion api */ size_t windowSize = 1ULL << windowLog; @@ -232,7 +232,7 @@ static size_t roundTripTest(void* result, size_t resultCapacity, const void* src, size_t srcSize, const ZSTD_Sequence* seqs, size_t seqSize, unsigned hasDict, - ZSTD_sequenceFormat_e mode) + ZSTD_SequenceFormat_e mode) { size_t cSize; size_t dSize; @@ -276,7 +276,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* src, size_t size) unsigned hasDict; unsigned wLog; int cLevel; - ZSTD_sequenceFormat_e mode; + ZSTD_SequenceFormat_e mode; FUZZ_dataProducer_t* const producer = FUZZ_dataProducer_create(src, size); FUZZ_ASSERT(producer); @@ -293,7 +293,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* src, size_t size) /* Generate window log first so we don't generate offsets too large */ wLog = FUZZ_dataProducer_uint32Range(producer, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX); cLevel = FUZZ_dataProducer_int32Range(producer, -3, 22); - mode = (ZSTD_sequenceFormat_e)FUZZ_dataProducer_int32Range(producer, 0, 1); + mode = (ZSTD_SequenceFormat_e)FUZZ_dataProducer_int32Range(producer, 0, 1); ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters); ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 0); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 4a6ebd69c..2180d1edb 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -310,7 +310,7 @@ static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part) #endif static void FUZ_decodeSequences(BYTE* dst, ZSTD_Sequence* seqs, size_t seqsSize, - BYTE* src, size_t size, ZSTD_sequenceFormat_e format) + BYTE* src, size_t size, ZSTD_SequenceFormat_e format) { size_t i; size_t j; From 894ea312819e36084e0ce26922037ba8571cd65d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 14:00:09 -0800 Subject: [PATCH 497/937] codemod: ZSTD_sequenceCopier -> ZSTD_SequenceCopier_f --- lib/compress/zstd_compress.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 5976a8e5c..a8d317a8d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6812,12 +6812,12 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, return bytesAdjustment; } -typedef size_t (*ZSTD_sequenceCopier) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, +typedef size_t (*ZSTD_SequenceCopier_f) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); -static ZSTD_sequenceCopier ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode) +static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode) { - ZSTD_sequenceCopier sequenceCopier = NULL; + ZSTD_SequenceCopier_f sequenceCopier = NULL; assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode)); if (mode == ZSTD_sf_explicitBlockDelimiters) { return ZSTD_copySequencesToSeqStoreExplicitBlockDelim; @@ -6896,7 +6896,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, BYTE const* ip = (BYTE const*)src; BYTE* op = (BYTE*)dst; - ZSTD_sequenceCopier const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters); + ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters); DEBUGLOG(4, "ZSTD_compressSequences_internal srcSize: %zu, inSeqsSize: %zu", srcSize, inSeqsSize); /* Special case: empty frame */ From 1ac79ba1b63f9e060d767380bca369051f6969be Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 14:02:53 -0800 Subject: [PATCH 498/937] minor: simplify ZSTD_selectSequenceCopier --- lib/compress/zstd_compress.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index a8d317a8d..26af1581c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6817,15 +6817,12 @@ typedef size_t (*ZSTD_SequenceCopier_f) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode) { - ZSTD_SequenceCopier_f sequenceCopier = NULL; assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode)); if (mode == ZSTD_sf_explicitBlockDelimiters) { return ZSTD_copySequencesToSeqStoreExplicitBlockDelim; - } else if (mode == ZSTD_sf_noBlockDelimiters) { - return ZSTD_copySequencesToSeqStoreNoBlockDelim; } - assert(sequenceCopier != NULL); - return sequenceCopier; + assert(mode == ZSTD_sf_noBlockDelimiters); + return ZSTD_copySequencesToSeqStoreNoBlockDelim; } /* Discover the size of next block by searching for the delimiter. From 76dd3a98c48445f5f586d2deca5a3aedfefbd49d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 14:11:51 -0800 Subject: [PATCH 499/937] scope: ZSTD_copySequencesToSeqStore*() are private to ZSTD_compress.c no need to publish them outside of this unit. --- lib/compress/zstd_compress.c | 41 +++++++++++++++++++++------ lib/compress/zstd_compress_internal.h | 27 ------------------ 2 files changed, 32 insertions(+), 36 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 26af1581c..3d926a991 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1203,13 +1203,13 @@ size_t ZSTD_CCtx_setCParams(ZSTD_CCtx* cctx, ZSTD_compressionParameters cparams) DEBUGLOG(4, "ZSTD_CCtx_setCParams"); /* only update if all parameters are valid */ FORWARD_IF_ERROR(ZSTD_checkCParams(cparams), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, cparams.windowLog), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, cparams.chainLog), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, cparams.hashLog), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, cparams.searchLog), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, cparams.minMatch), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, cparams.targetLength), ""); - FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, cparams.strategy), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)cparams.windowLog), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, (int)cparams.chainLog), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, (int)cparams.hashLog), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, (int)cparams.searchLog), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, (int)cparams.minMatch), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, (int)cparams.targetLength), ""); + FORWARD_IF_ERROR(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, (int)cparams.strategy), ""); return 0; } @@ -3239,6 +3239,13 @@ static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seq return litLenSum + matchLenSum; } +static size_t +ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, + ZSTD_sequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, + const void* src, size_t blockSize, + ZSTD_paramSwitch_e externalRepSearch); + typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e; static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) @@ -6601,7 +6608,11 @@ static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 return offBase; } -size_t +/* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of + * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter. + * Note that the block delimiter must include the last literals of the block. + */ +static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, @@ -6687,7 +6698,19 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, return 0; } -size_t +/* Returns the number of bytes to move the current read position back by. + * Only non-zero if we ended up splitting a sequence. + * Otherwise, it may return a ZSTD error if something went wrong. + * + * This function will attempt to scan through blockSize bytes + * represented by the sequences in @inSeqs, + * storing any (partial) sequences. + * + * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to + * avoid splitting a match, or to avoid splitting a match such that it would produce a match + * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block. + */ +static size_t ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 2d7e0230d..737d1cc45 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1613,33 +1613,6 @@ U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat); */ void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize); -/* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of - * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter. - * Note that the block delimiter must include the last literals of the block. - */ -size_t -ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, - ZSTD_sequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); - -/* Returns the number of bytes to move the current read position back by. - * Only non-zero if we ended up splitting a sequence. - * Otherwise, it may return a ZSTD error if something went wrong. - * - * This function will attempt to scan through blockSize bytes - * represented by the sequences in @inSeqs, - * storing any (partial) sequences. - * - * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to - * avoid splitting a match, or to avoid splitting a match such that it would produce a match - * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block. - */ -size_t -ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); - /* Returns 1 if an external sequence producer is registered, otherwise returns 0. */ MEM_STATIC int ZSTD_hasExtSeqProd(const ZSTD_CCtx_params* params) { return params->extSeqProdFunc != NULL; From 03d95f9d135a9009b15567acf6f85b6e23534224 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 14:14:07 -0800 Subject: [PATCH 500/937] fix proper type for .forceNonContiguous --- lib/compress/zstd_compress_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 737d1cc45..21e69650f 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -301,7 +301,7 @@ struct ZSTD_matchState_t { U32* hashTable3; U32* chainTable; - U32 forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */ + int forceNonContiguous; /* Non-zero if we should force non-contiguous load for the next window update. */ int dedicatedDictSearch; /* Indicates whether this matchState is using the * dedicated dictionary search structure. From 5359d16d8d646b2010b9d5ac07fbf747d432fdfe Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 14:18:39 -0800 Subject: [PATCH 501/937] enable proper type --- lib/compress/zstd_compress.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 3d926a991..639b78cbb 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1661,7 +1661,7 @@ ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams( static size_t ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams, const ZSTD_paramSwitch_e useRowMatchFinder, - const U32 enableDedicatedDictSearch, + const int enableDedicatedDictSearch, const U32 forCCtx) { /* chain table size should be 0 for fast or row-hash strategies */ @@ -5052,7 +5052,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, { unsigned maxSymbolValue = 255; unsigned hasZeroWeights = 1; size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr, - dictEnd-dictPtr, &hasZeroWeights); + (size_t)(dictEnd-dictPtr), &hasZeroWeights); /* We only set the loaded table as valid if it contains all non-zero * weights. Otherwise, we set it to check */ @@ -5064,7 +5064,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, } { unsigned offcodeLog; - size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr); + size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, (size_t)(dictEnd-dictPtr)); RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, ""); RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, ""); /* fill all offset symbols to avoid garbage at end of table */ @@ -5093,7 +5093,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, { short litlengthNCount[MaxLL+1]; unsigned litlengthMaxValue = MaxLL, litlengthLog; - size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr); + 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, ""); RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp( @@ -5358,7 +5358,7 @@ static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity) } cctx->stage = ZSTDcs_created; /* return to "created but no init" status */ - return op-ostart; + return (size_t)(op-ostart); } void ZSTD_CCtx_trace(ZSTD_CCtx* cctx, size_t extraCSize) @@ -5586,7 +5586,7 @@ static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_compressionParameters cParams, ZSTD_paramSwitch_e useRowMatchFinder, - U32 enableDedicatedDictSearch, + int enableDedicatedDictSearch, ZSTD_customMem customMem) { if ((!customMem.customAlloc) ^ (!customMem.customFree)) return NULL; From 30671d77afeedbc70957ac8ce8e864d5219d97bb Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 15:01:43 -0800 Subject: [PATCH 502/937] codemod: ZSTD_sequencePosition -> ZSTD_SequencePosition --- lib/compress/zstd_compress.c | 54 ++++++++++++++++----------- lib/compress/zstd_compress_internal.h | 6 --- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 639b78cbb..9f649dd6e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3239,9 +3239,15 @@ static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seq return litLenSum + matchLenSum; } +typedef struct { + U32 idx; /* Index in array of ZSTD_Sequence */ + U32 posInSequence; /* Position within sequence at idx */ + size_t posInSrc; /* Number of bytes given by sequences provided so far */ +} ZSTD_SequencePosition; + static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, - ZSTD_sequencePosition* seqPos, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); @@ -3362,7 +3368,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) /* Return early if there is no error, since we don't need to worry about last literals */ if (!ZSTD_isError(nbPostProcessedSeqs)) { - ZSTD_sequencePosition seqPos = {0,0,0}; + ZSTD_SequencePosition seqPos = {0,0,0}; size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs); RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!"); FORWARD_IF_ERROR( @@ -5079,7 +5085,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, { short matchlengthNCount[MaxML+1]; unsigned matchlengthMaxValue = MaxML, matchlengthLog; - size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr); + 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, ""); RETURN_ERROR_IF(FSE_isError(FSE_buildCTable_wksp( @@ -6123,12 +6129,13 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, case zcss_load: if ( (flushMode == ZSTD_e_end) - && ( (size_t)(oend-op) >= ZSTD_compressBound(iend-ip) /* Enough output space */ + && ( (size_t)(oend-op) >= ZSTD_compressBound((size_t)(iend-ip)) /* Enough output space */ || zcs->appliedParams.outBufferMode == ZSTD_bm_stable) /* OR we are allowed to return dstSizeTooSmall */ && (zcs->inBuffPos == 0) ) { /* shortcut to compression pass directly into output buffer */ size_t const cSize = ZSTD_compressEnd_public(zcs, - op, oend-op, ip, iend-ip); + op, (size_t)(oend-op), + ip, (size_t)(iend-ip)); DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize); FORWARD_IF_ERROR(cSize, "ZSTD_compressEnd failed"); ip = iend; @@ -6142,7 +6149,7 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos; size_t const loaded = ZSTD_limitCopy( zcs->inBuff + zcs->inBuffPos, toLoad, - ip, iend-ip); + ip, (size_t)(iend-ip)); zcs->inBuffPos += loaded; if (ip) ip += loaded; if ( (flushMode == ZSTD_e_continue) @@ -6175,7 +6182,7 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, { int const inputBuffered = (zcs->appliedParams.inBufferMode == ZSTD_bm_buffered); void* cDst; size_t cSize; - size_t oSize = oend-op; + size_t oSize = (size_t)(oend-op); size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress : MIN((size_t)(iend - ip), zcs->blockSize); if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable) @@ -6258,8 +6265,8 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, } } - input->pos = ip - istart; - output->pos = op - ostart; + input->pos = (size_t)(ip - istart); + output->pos = (size_t)(op - ostart); if (zcs->frameEnded) return 0; return ZSTD_nextInputSizeHint(zcs); } @@ -6608,16 +6615,17 @@ static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 return offBase; } -/* Returns 0 on success, and a ZSTD_error otherwise. This function scans through an array of - * ZSTD_Sequence, storing the sequences it finds, until it reaches a block delimiter. +/* This function scans through an array of ZSTD_Sequence, + * storing the sequences it reads, until it reaches a block delimiter. * Note that the block delimiter must include the last literals of the block. + * @returns 0 on success, and a ZSTD_error otherwise. */ static size_t ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, - ZSTD_sequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, - ZSTD_paramSwitch_e externalRepSearch) + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, + const void* src, size_t blockSize, + ZSTD_paramSwitch_e externalRepSearch) { U32 idx = seqPos->idx; U32 const startIdx = idx; @@ -6652,8 +6660,10 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); if (cctx->appliedParams.validateSequences) { seqPos->posInSrc += litLength + matchLength; - FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc, - cctx->appliedParams.cParams.windowLog, dictSize, ZSTD_hasExtSeqProd(&cctx->appliedParams)), + FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, + seqPos->posInSrc, + cctx->appliedParams.cParams.windowLog, dictSize, + ZSTD_hasExtSeqProd(&cctx->appliedParams)), "Sequence validation failed"); } RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid, @@ -6712,7 +6722,7 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, */ static size_t ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, - ZSTD_sequencePosition* seqPos, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch) @@ -6835,7 +6845,7 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, return bytesAdjustment; } -typedef size_t (*ZSTD_SequenceCopier_f) (ZSTD_CCtx* cctx, ZSTD_sequencePosition* seqPos, +typedef size_t (*ZSTD_SequenceCopier_f) (ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode) @@ -6853,7 +6863,7 @@ static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mod * otherwise it's an input error. * The block size retrieved will be later compared to ensure it remains within bounds */ static size_t -blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos) +blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos) { int end = 0; size_t blockSize = 0; @@ -6884,7 +6894,7 @@ static size_t blockSize_noDelimiter(size_t blockSize, size_t remaining) static size_t determine_blockSize(ZSTD_SequenceFormat_e mode, size_t blockSize, size_t remaining, - const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_sequencePosition seqPos) + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos) { DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining); if (mode == ZSTD_sf_noBlockDelimiters) @@ -6912,7 +6922,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, { size_t cSize = 0; size_t remaining = srcSize; - ZSTD_sequencePosition seqPos = {0, 0, 0}; + ZSTD_SequencePosition seqPos = {0, 0, 0}; BYTE const* ip = (BYTE const*)src; BYTE* op = (BYTE*)dst; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 21e69650f..d3aa1e234 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -215,12 +215,6 @@ typedef struct { size_t capacity; /* The capacity starting from `seq` pointer */ } rawSeqStore_t; -typedef struct { - U32 idx; /* Index in array of ZSTD_Sequence */ - U32 posInSequence; /* Position within sequence at idx */ - size_t posInSrc; /* Number of bytes given by sequences provided so far */ -} ZSTD_sequencePosition; - UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0}; typedef struct { From fa468944f2a999a10f6a823fe7252da3e0fdc129 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 15:04:56 -0800 Subject: [PATCH 503/937] codemod: ZSTD_buildSeqStore_e -> ZSTD_BuildSeqStore_e --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9f649dd6e..e068b48bd 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3252,7 +3252,7 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch); -typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_buildSeqStore_e; +typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e; static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) { From 5df80acedb6b352e949ef24446cb489b15524ce0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 15:35:11 -0800 Subject: [PATCH 504/937] codemod: ZSTD_matchState_t -> ZSTD_MatchState_t --- lib/compress/zstd_compress.c | 52 ++++++------- lib/compress/zstd_compress_internal.h | 20 ++--- lib/compress/zstd_double_fast.c | 22 +++--- lib/compress/zstd_double_fast.h | 8 +- lib/compress/zstd_fast.c | 22 +++--- lib/compress/zstd_fast.h | 8 +- lib/compress/zstd_lazy.c | 106 +++++++++++++------------- lib/compress/zstd_lazy.h | 60 +++++++-------- lib/compress/zstd_ldm.c | 6 +- lib/compress/zstd_ldm.h | 2 +- lib/compress/zstd_opt.c | 42 +++++----- lib/compress/zstd_opt.h | 16 ++-- 12 files changed, 182 insertions(+), 182 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index e068b48bd..029928fb2 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -48,7 +48,7 @@ * in log format, aka 17 => 1 << 17 == 128Ki positions. * This structure is only used in zstd_opt. * Since allocation is centralized for all strategies, it has to be known here. - * The actual (selected) size of the hash table is then stored in ZSTD_matchState_t.hashLog3, + * The actual (selected) size of the hash table is then stored in ZSTD_MatchState_t.hashLog3, * so that zstd_opt.c doesn't need to know about this constant. */ #ifndef ZSTD_HASHLOG3_MAX @@ -82,7 +82,7 @@ struct ZSTD_CDict_s { ZSTD_dictContentType_e dictContentType; /* The dictContentType the CDict was created with */ U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */ ZSTD_cwksp workspace; - ZSTD_matchState_t matchState; + ZSTD_MatchState_t matchState; ZSTD_compressedBlockState_t cBlockState; ZSTD_customMem customMem; U32 dictID; @@ -1938,7 +1938,7 @@ void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs) * Invalidate all the matches in the match finder tables. * Requires nextSrc and base to be set (can be NULL). */ -static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms) +static void ZSTD_invalidateMatchState(ZSTD_MatchState_t* ms) { ZSTD_window_clear(&ms->window); @@ -1985,12 +1985,12 @@ static U64 ZSTD_bitmix(U64 val, U64 len) { } /* Mixes in the hashSalt and hashSaltEntropy to create a new hashSalt */ -static void ZSTD_advanceHashSalt(ZSTD_matchState_t* ms) { +static void ZSTD_advanceHashSalt(ZSTD_MatchState_t* ms) { ms->hashSalt = ZSTD_bitmix(ms->hashSalt, 8) ^ ZSTD_bitmix((U64) ms->hashSaltEntropy, 4); } static size_t -ZSTD_reset_matchState(ZSTD_matchState_t* ms, +ZSTD_reset_matchState(ZSTD_MatchState_t* ms, ZSTD_cwksp* ws, const ZSTD_compressionParameters* cParams, const ZSTD_paramSwitch_e useRowMatchFinder, @@ -2473,8 +2473,8 @@ static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx, ZSTD_cwksp_mark_tables_clean(&cctx->workspace); /* copy dictionary offsets */ - { ZSTD_matchState_t const* srcMatchState = &cdict->matchState; - ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState; + { ZSTD_MatchState_t const* srcMatchState = &cdict->matchState; + ZSTD_MatchState_t* dstMatchState = &cctx->blockState.matchState; dstMatchState->window = srcMatchState->window; dstMatchState->nextToUpdate = srcMatchState->nextToUpdate; dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd; @@ -2576,8 +2576,8 @@ static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx, /* copy dictionary offsets */ { - const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState; - ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState; + 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; @@ -2671,7 +2671,7 @@ static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const /*! ZSTD_reduceIndex() : * rescale all indexes to avoid future overflow (indexes are U32) */ -static void ZSTD_reduceIndex (ZSTD_matchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue) +static void ZSTD_reduceIndex (ZSTD_MatchState_t* ms, ZSTD_CCtx_params const* params, const U32 reducerValue) { { U32 const hSize = (U32)1 << params->cParams.hashLog; ZSTD_reduceTable(ms->hashTable, hSize, reducerValue); @@ -3246,17 +3246,17 @@ typedef struct { } ZSTD_SequencePosition; static size_t -ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, - ZSTD_paramSwitch_e externalRepSearch); +ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, + const void* src, size_t blockSize, + ZSTD_paramSwitch_e externalRepSearch); typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e; static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) { - ZSTD_matchState_t* const ms = &zc->blockState.matchState; + ZSTD_MatchState_t* const ms = &zc->blockState.matchState; DEBUGLOG(5, "ZSTD_buildSeqStore (srcSize=%zu)", srcSize); assert(srcSize <= ZSTD_BLOCKSIZE_MAX); /* Assert that we have correctly flushed the ctx params into the ms's copy */ @@ -3372,7 +3372,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) size_t const seqLenSum = ZSTD_fastSequenceLengthSum(zc->extSeqBuf, nbPostProcessedSeqs); RETURN_ERROR_IF(seqLenSum > srcSize, externalSequences_invalid, "External sequences imply too large a block!"); FORWARD_IF_ERROR( - ZSTD_copySequencesToSeqStoreExplicitBlockDelim( + ZSTD_transferSequences_wBlockDelim( zc, &seqPos, zc->extSeqBuf, nbPostProcessedSeqs, src, srcSize, @@ -4515,7 +4515,7 @@ static size_t ZSTD_compressBlock_targetCBlockSize(ZSTD_CCtx* zc, return cSize; } -static void ZSTD_overflowCorrectIfNeeded(ZSTD_matchState_t* ms, +static void ZSTD_overflowCorrectIfNeeded(ZSTD_MatchState_t* ms, ZSTD_cwksp* ws, ZSTD_CCtx_params const* params, void const* ip, @@ -4600,7 +4600,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, XXH64_update(&cctx->xxhState, src, srcSize); while (remaining) { - ZSTD_matchState_t* const ms = &cctx->blockState.matchState; + ZSTD_MatchState_t* const ms = &cctx->blockState.matchState; size_t const blockSize = ZSTD_optimalBlockSize(cctx, ip, remaining, blockSizeMax, @@ -4784,7 +4784,7 @@ static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx, const void* src, size_t srcSize, U32 frame, U32 lastFrameChunk) { - ZSTD_matchState_t* const ms = &cctx->blockState.matchState; + ZSTD_MatchState_t* const ms = &cctx->blockState.matchState; size_t fhSize = 0; DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u", @@ -4888,7 +4888,7 @@ size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const /*! ZSTD_loadDictionaryContent() : * @return : 0, or an error code */ -static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms, +static size_t ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, ldmState_t* ls, ZSTD_cwksp* ws, ZSTD_CCtx_params const* params, @@ -5146,7 +5146,7 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, * dictSize supposed >= 8 */ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs, - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, ZSTD_cwksp* ws, ZSTD_CCtx_params const* params, const void* dict, size_t dictSize, @@ -5179,7 +5179,7 @@ static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs, * @return : dictID, or an error code */ static size_t ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs, - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, ldmState_t* ls, ZSTD_cwksp* ws, const ZSTD_CCtx_params* params, @@ -6621,7 +6621,7 @@ static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 * @returns 0 on success, and a ZSTD_error otherwise. */ static size_t -ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, +ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, const void* src, size_t blockSize, @@ -6634,7 +6634,7 @@ ZSTD_copySequencesToSeqStoreExplicitBlockDelim(ZSTD_CCtx* cctx, repcodes_t updatedRepcodes; U32 dictSize; - DEBUGLOG(5, "ZSTD_copySequencesToSeqStoreExplicitBlockDelim (blockSize = %zu)", blockSize); + DEBUGLOG(5, "ZSTD_transferSequences_wBlockDelim (blockSize = %zu)", blockSize); if (cctx->cdict) { dictSize = (U32)cctx->cdict->dictContentSize; @@ -6852,7 +6852,7 @@ static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mod { assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode)); if (mode == ZSTD_sf_explicitBlockDelimiters) { - return ZSTD_copySequencesToSeqStoreExplicitBlockDelim; + return ZSTD_transferSequences_wBlockDelim; } assert(mode == ZSTD_sf_noBlockDelimiters); return ZSTD_copySequencesToSeqStoreNoBlockDelim; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index d3aa1e234..91066a4be 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -269,11 +269,11 @@ typedef struct { #define ZSTD_WINDOW_START_INDEX 2 -typedef struct ZSTD_matchState_t ZSTD_matchState_t; +typedef struct ZSTD_MatchState_t ZSTD_MatchState_t; #define ZSTD_ROW_HASH_CACHE_SIZE 8 /* Size of prefetching hash cache for row-based matchfinder */ -struct ZSTD_matchState_t { +struct ZSTD_MatchState_t { ZSTD_window_t window; /* State for window round buffer management */ U32 loadedDictEnd; /* index of end of dictionary, within context's referential. * When loadedDictEnd != 0, a dictionary is in use, and still valid. @@ -301,7 +301,7 @@ struct ZSTD_matchState_t { * dedicated dictionary search structure. */ optState_t opt; /* optimal parser state */ - const ZSTD_matchState_t* dictMatchState; + const ZSTD_MatchState_t* dictMatchState; ZSTD_compressionParameters cParams; const rawSeqStore_t* ldmSeqStore; @@ -321,7 +321,7 @@ struct ZSTD_matchState_t { typedef struct { ZSTD_compressedBlockState_t* prevCBlock; ZSTD_compressedBlockState_t* nextCBlock; - ZSTD_matchState_t matchState; + ZSTD_MatchState_t matchState; } ZSTD_blockState_t; typedef struct { @@ -580,7 +580,7 @@ typedef enum { } ZSTD_cParamMode_e; typedef size_t (*ZSTD_blockCompressor) ( - ZSTD_matchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); @@ -1081,7 +1081,7 @@ MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window) * Inspects the provided matchState and figures out what dictMode should be * passed to the compressor. */ -MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms) +MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms) { return ZSTD_window_hasExtDict(ms->window) ? ZSTD_extDict : @@ -1270,7 +1270,7 @@ ZSTD_window_enforceMaxDist(ZSTD_window_t* window, const void* blockEnd, U32 maxDist, U32* loadedDictEndPtr, - const ZSTD_matchState_t** dictMatchStatePtr) + const ZSTD_MatchState_t** dictMatchStatePtr) { U32 const blockEndIdx = (U32)((BYTE const*)blockEnd - window->base); U32 const loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0; @@ -1315,7 +1315,7 @@ ZSTD_checkDictValidity(const ZSTD_window_t* window, const void* blockEnd, U32 maxDist, U32* loadedDictEndPtr, - const ZSTD_matchState_t** dictMatchStatePtr) + const ZSTD_MatchState_t** dictMatchStatePtr) { assert(loadedDictEndPtr != NULL); assert(dictMatchStatePtr != NULL); @@ -1405,7 +1405,7 @@ U32 ZSTD_window_update(ZSTD_window_t* window, /** * Returns the lowest allowed match index. It may either be in the ext-dict or the prefix. */ -MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog) +MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog) { U32 const maxDistance = 1U << windowLog; U32 const lowestValid = ms->window.lowLimit; @@ -1422,7 +1422,7 @@ MEM_STATIC U32 ZSTD_getLowestMatchIndex(const ZSTD_matchState_t* ms, U32 curr, u /** * Returns the lowest allowed match index in the prefix. */ -MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_matchState_t* ms, U32 curr, unsigned windowLog) +MEM_STATIC U32 ZSTD_getLowestPrefixIndex(const ZSTD_MatchState_t* ms, U32 curr, unsigned windowLog) { U32 const maxDistance = 1U << windowLog; U32 const lowestValid = ms->window.dictLimit; diff --git a/lib/compress/zstd_double_fast.c b/lib/compress/zstd_double_fast.c index 1406c2d50..1a266e7d9 100644 --- a/lib/compress/zstd_double_fast.c +++ b/lib/compress/zstd_double_fast.c @@ -15,7 +15,7 @@ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms, +void ZSTD_fillDoubleHashTableForCDict(ZSTD_MatchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -53,7 +53,7 @@ void ZSTD_fillDoubleHashTableForCDict(ZSTD_matchState_t* ms, static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_fillDoubleHashTableForCCtx(ZSTD_matchState_t* ms, +void ZSTD_fillDoubleHashTableForCCtx(ZSTD_MatchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -87,7 +87,7 @@ void ZSTD_fillDoubleHashTableForCCtx(ZSTD_matchState_t* ms, } } } -void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, +void ZSTD_fillDoubleHashTable(ZSTD_MatchState_t* ms, const void* const end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp) @@ -103,7 +103,7 @@ void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_noDict_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { ZSTD_compressionParameters const* cParams = &ms->cParams; @@ -326,7 +326,7 @@ _match_stored: FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { @@ -347,7 +347,7 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState_generic( const BYTE* const ilimit = iend - HASH_READ_SIZE; U32 offset_1=rep[0], offset_2=rep[1]; - const ZSTD_matchState_t* const dms = ms->dictMatchState; + const ZSTD_MatchState_t* const dms = ms->dictMatchState; const ZSTD_compressionParameters* const dictCParams = &dms->cParams; const U32* const dictHashLong = dms->hashTable; const U32* const dictHashSmall = dms->chainTable; @@ -548,7 +548,7 @@ _match_stored: #define ZSTD_GEN_DFAST_FN(dictMode, mls) \ static size_t ZSTD_compressBlock_doubleFast_##dictMode##_##mls( \ - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ return ZSTD_compressBlock_doubleFast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mls); \ @@ -566,7 +566,7 @@ ZSTD_GEN_DFAST_FN(dictMatchState, 7) size_t ZSTD_compressBlock_doubleFast( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { const U32 mls = ms->cParams.minMatch; @@ -586,7 +586,7 @@ size_t ZSTD_compressBlock_doubleFast( size_t ZSTD_compressBlock_doubleFast_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { const U32 mls = ms->cParams.minMatch; @@ -608,7 +608,7 @@ size_t ZSTD_compressBlock_doubleFast_dictMatchState( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_doubleFast_extDict_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls /* template */) { @@ -757,7 +757,7 @@ ZSTD_GEN_DFAST_FN(extDict, 6) ZSTD_GEN_DFAST_FN(extDict, 7) size_t ZSTD_compressBlock_doubleFast_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; diff --git a/lib/compress/zstd_double_fast.h b/lib/compress/zstd_double_fast.h index 1a746fab9..c58697ad2 100644 --- a/lib/compress/zstd_double_fast.h +++ b/lib/compress/zstd_double_fast.h @@ -20,18 +20,18 @@ extern "C" { #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR -void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms, +void ZSTD_fillDoubleHashTable(ZSTD_MatchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp); size_t ZSTD_compressBlock_doubleFast( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_doubleFast_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_doubleFast_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_DOUBLEFAST ZSTD_compressBlock_doubleFast diff --git a/lib/compress/zstd_fast.c b/lib/compress/zstd_fast.c index 3c8d5b527..ee25bcbac 100644 --- a/lib/compress/zstd_fast.c +++ b/lib/compress/zstd_fast.c @@ -13,7 +13,7 @@ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms, +void ZSTD_fillHashTableForCDict(ZSTD_MatchState_t* ms, const void* const end, ZSTD_dictTableLoadMethod_e dtlm) { @@ -50,7 +50,7 @@ void ZSTD_fillHashTableForCDict(ZSTD_matchState_t* ms, static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_fillHashTableForCCtx(ZSTD_matchState_t* ms, +void ZSTD_fillHashTableForCCtx(ZSTD_MatchState_t* ms, const void* const end, ZSTD_dictTableLoadMethod_e dtlm) { @@ -84,7 +84,7 @@ void ZSTD_fillHashTableForCCtx(ZSTD_matchState_t* ms, } } } } } -void ZSTD_fillHashTable(ZSTD_matchState_t* ms, +void ZSTD_fillHashTable(ZSTD_MatchState_t* ms, const void* const end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp) @@ -190,7 +190,7 @@ ZSTD_match4Found_branch(const BYTE* currentPtr, const BYTE* matchAddress, U32 ma FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_noDict_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, int useCmov) { @@ -424,7 +424,7 @@ _match: /* Requires: ip0, match0, offcode */ #define ZSTD_GEN_FAST_FN(dictMode, mml, cmov) \ static size_t ZSTD_compressBlock_fast_##dictMode##_##mml##_##cmov( \ - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], \ void const* src, size_t srcSize) \ { \ return ZSTD_compressBlock_fast_##dictMode##_generic(ms, seqStore, rep, src, srcSize, mml, cmov); \ @@ -441,7 +441,7 @@ ZSTD_GEN_FAST_FN(noDict, 6, 0) ZSTD_GEN_FAST_FN(noDict, 7, 0) size_t ZSTD_compressBlock_fast( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mml = ms->cParams.minMatch; @@ -481,7 +481,7 @@ size_t ZSTD_compressBlock_fast( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_dictMatchState_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, U32 const hasStep) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -500,7 +500,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState_generic( const BYTE* const ilimit = iend - HASH_READ_SIZE; U32 offset_1=rep[0], offset_2=rep[1]; - const ZSTD_matchState_t* const dms = ms->dictMatchState; + const ZSTD_MatchState_t* const dms = ms->dictMatchState; const ZSTD_compressionParameters* const dictCParams = &dms->cParams ; const U32* const dictHashTable = dms->hashTable; const U32 dictStartIndex = dms->window.dictLimit; @@ -684,7 +684,7 @@ ZSTD_GEN_FAST_FN(dictMatchState, 6, 0) ZSTD_GEN_FAST_FN(dictMatchState, 7, 0) size_t ZSTD_compressBlock_fast_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; @@ -707,7 +707,7 @@ size_t ZSTD_compressBlock_fast_dictMatchState( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_fast_extDict_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize, U32 const mls, U32 const hasStep) { const ZSTD_compressionParameters* const cParams = &ms->cParams; @@ -965,7 +965,7 @@ ZSTD_GEN_FAST_FN(extDict, 6, 0) ZSTD_GEN_FAST_FN(extDict, 7, 0) size_t ZSTD_compressBlock_fast_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { U32 const mls = ms->cParams.minMatch; diff --git a/lib/compress/zstd_fast.h b/lib/compress/zstd_fast.h index 5a971cf32..f7fbf4f68 100644 --- a/lib/compress/zstd_fast.h +++ b/lib/compress/zstd_fast.h @@ -18,17 +18,17 @@ extern "C" { #include "../common/mem.h" /* U32 */ #include "zstd_compress_internal.h" -void ZSTD_fillHashTable(ZSTD_matchState_t* ms, +void ZSTD_fillHashTable(ZSTD_MatchState_t* ms, void const* end, ZSTD_dictTableLoadMethod_e dtlm, ZSTD_tableFillPurpose_e tfp); size_t ZSTD_compressBlock_fast( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_fast_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_fast_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #if defined (__cplusplus) diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 9fe56c76b..272ebe0ec 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -26,7 +26,7 @@ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_updateDUBT(ZSTD_matchState_t* ms, +void ZSTD_updateDUBT(ZSTD_MatchState_t* ms, const BYTE* ip, const BYTE* iend, U32 mls) { @@ -71,7 +71,7 @@ void ZSTD_updateDUBT(ZSTD_matchState_t* ms, * doesn't fail */ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_insertDUBT1(const ZSTD_matchState_t* ms, +void ZSTD_insertDUBT1(const ZSTD_MatchState_t* ms, U32 curr, const BYTE* inputEnd, U32 nbCompares, U32 btLow, const ZSTD_dictMode_e dictMode) @@ -162,7 +162,7 @@ void ZSTD_insertDUBT1(const ZSTD_matchState_t* ms, static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_DUBT_findBetterDictMatch ( - const ZSTD_matchState_t* ms, + const ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, size_t* offsetPtr, size_t bestLength, @@ -170,7 +170,7 @@ size_t ZSTD_DUBT_findBetterDictMatch ( U32 const mls, const ZSTD_dictMode_e dictMode) { - const ZSTD_matchState_t * const dms = ms->dictMatchState; + const ZSTD_MatchState_t * const dms = ms->dictMatchState; const ZSTD_compressionParameters* const dmsCParams = &dms->cParams; const U32 * const dictHashTable = dms->hashTable; U32 const hashLog = dmsCParams->hashLog; @@ -240,7 +240,7 @@ size_t ZSTD_DUBT_findBetterDictMatch ( static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -size_t ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms, +size_t ZSTD_DUBT_findBestMatch(ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, size_t* offBasePtr, U32 const mls, @@ -392,7 +392,7 @@ size_t ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms, /** ZSTD_BtFindBestMatch() : Tree updater, providing best match */ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -size_t ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms, +size_t ZSTD_BtFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offBasePtr, const U32 mls /* template */, @@ -408,7 +408,7 @@ size_t ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms, * Dedicated dict search ***********************************/ -void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const BYTE* const ip) +void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_MatchState_t* ms, const BYTE* const ip) { const BYTE* const base = ms->window.base; U32 const target = (U32)(ip - base); @@ -527,7 +527,7 @@ void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const B */ FORCE_INLINE_TEMPLATE size_t ZSTD_dedicatedDictSearch_lazy_search(size_t* offsetPtr, size_t ml, U32 nbAttempts, - const ZSTD_matchState_t* const dms, + const ZSTD_MatchState_t* const dms, const BYTE* const ip, const BYTE* const iLimit, const BYTE* const prefixStart, const U32 curr, const U32 dictLimit, const size_t ddsIdx) { @@ -630,7 +630,7 @@ size_t ZSTD_dedicatedDictSearch_lazy_search(size_t* offsetPtr, size_t ml, U32 nb FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertAndFindFirstIndex_internal( - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, const ZSTD_compressionParameters* const cParams, const BYTE* ip, U32 const mls, U32 const lazySkipping) { @@ -656,7 +656,7 @@ U32 ZSTD_insertAndFindFirstIndex_internal( return hashTable[ZSTD_hashPtr(ip, hashLog, mls)]; } -U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip) { +U32 ZSTD_insertAndFindFirstIndex(ZSTD_MatchState_t* ms, const BYTE* ip) { const ZSTD_compressionParameters* const cParams = &ms->cParams; return ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, ms->cParams.minMatch, /* lazySkipping*/ 0); } @@ -665,7 +665,7 @@ U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip) { FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_HcFindBestMatch( - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, const U32 mls, const ZSTD_dictMode_e dictMode) @@ -689,7 +689,7 @@ size_t ZSTD_HcFindBestMatch( U32 nbAttempts = 1U << cParams->searchLog; size_t ml=4-1; - const ZSTD_matchState_t* const dms = ms->dictMatchState; + const ZSTD_MatchState_t* const dms = ms->dictMatchState; const U32 ddsHashLog = dictMode == ZSTD_dedicatedDictSearch ? dms->cParams.hashLog - ZSTD_LAZY_DDSS_BUCKET_LOG : 0; const size_t ddsIdx = dictMode == ZSTD_dedicatedDictSearch @@ -834,7 +834,7 @@ FORCE_INLINE_TEMPLATE void ZSTD_row_prefetch(U32 const* hashTable, BYTE const* t */ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_row_fillHashCache(ZSTD_matchState_t* ms, const BYTE* base, +void ZSTD_row_fillHashCache(ZSTD_MatchState_t* ms, const BYTE* base, U32 const rowLog, U32 const mls, U32 idx, const BYTE* const iLimit) { @@ -882,7 +882,7 @@ U32 ZSTD_row_nextCachedHash(U32* cache, U32 const* hashTable, */ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms, +void ZSTD_row_update_internalImpl(ZSTD_MatchState_t* ms, U32 updateStartIdx, U32 const updateEndIdx, U32 const mls, U32 const rowLog, U32 const rowMask, U32 const useCache) @@ -913,7 +913,7 @@ void ZSTD_row_update_internalImpl(ZSTD_matchState_t* ms, */ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_row_update_internal(ZSTD_matchState_t* ms, const BYTE* ip, +void ZSTD_row_update_internal(ZSTD_MatchState_t* ms, const BYTE* ip, U32 const mls, U32 const rowLog, U32 const rowMask, U32 const useCache) { @@ -946,7 +946,7 @@ void ZSTD_row_update_internal(ZSTD_matchState_t* ms, const BYTE* ip, * External wrapper for ZSTD_row_update_internal(). Used for filling the hashtable during dictionary * processing. */ -void ZSTD_row_update(ZSTD_matchState_t* const ms, const BYTE* ip) { +void ZSTD_row_update(ZSTD_MatchState_t* const ms, const BYTE* ip) { const U32 rowLog = BOUNDED(4, ms->cParams.searchLog, 6); const U32 rowMask = (1u << rowLog) - 1; const U32 mls = MIN(ms->cParams.minMatch, 6 /* mls caps out at 6 */); @@ -1139,7 +1139,7 @@ ZSTD_row_getMatchMask(const BYTE* const tagRow, const BYTE tag, const U32 headGr FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_RowFindBestMatch( - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, const U32 mls, const ZSTD_dictMode_e dictMode, @@ -1171,7 +1171,7 @@ size_t ZSTD_RowFindBestMatch( U32 hash; /* DMS/DDS variables that may be referenced laster */ - const ZSTD_matchState_t* const dms = ms->dictMatchState; + const ZSTD_MatchState_t* const dms = ms->dictMatchState; /* Initialize the following variables to satisfy static analyzer */ size_t ddsIdx = 0; @@ -1340,7 +1340,7 @@ size_t ZSTD_RowFindBestMatch( * ZSTD_searchMax() dispatches to the correct implementation function. * * TODO: The start of the search function involves loading and calculating a - * bunch of constants from the ZSTD_matchState_t. These computations could be + * bunch of constants from the ZSTD_MatchState_t. These computations could be * done in an initialization function, and saved somewhere in the match state. * Then we could pass a pointer to the saved state instead of the match state, * and avoid duplicate computations. @@ -1364,7 +1364,7 @@ size_t ZSTD_RowFindBestMatch( #define GEN_ZSTD_BT_SEARCH_FN(dictMode, mls) \ ZSTD_SEARCH_FN_ATTRS size_t ZSTD_BT_SEARCH_FN(dictMode, mls)( \ - ZSTD_matchState_t* ms, \ + ZSTD_MatchState_t* ms, \ const BYTE* ip, const BYTE* const iLimit, \ size_t* offBasePtr) \ { \ @@ -1374,7 +1374,7 @@ size_t ZSTD_RowFindBestMatch( #define GEN_ZSTD_HC_SEARCH_FN(dictMode, mls) \ ZSTD_SEARCH_FN_ATTRS size_t ZSTD_HC_SEARCH_FN(dictMode, mls)( \ - ZSTD_matchState_t* ms, \ + ZSTD_MatchState_t* ms, \ const BYTE* ip, const BYTE* const iLimit, \ size_t* offsetPtr) \ { \ @@ -1384,7 +1384,7 @@ size_t ZSTD_RowFindBestMatch( #define GEN_ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog) \ ZSTD_SEARCH_FN_ATTRS size_t ZSTD_ROW_SEARCH_FN(dictMode, mls, rowLog)( \ - ZSTD_matchState_t* ms, \ + ZSTD_MatchState_t* ms, \ const BYTE* ip, const BYTE* const iLimit, \ size_t* offsetPtr) \ { \ @@ -1485,7 +1485,7 @@ typedef enum { search_hashChain=0, search_binaryTree=1, search_rowHash=2 } searc * If a match is found its offset is stored in @p offsetPtr. */ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax( - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, const BYTE* ip, const BYTE* iend, size_t* offsetPtr, @@ -1514,7 +1514,7 @@ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth, @@ -1537,7 +1537,7 @@ size_t ZSTD_compressBlock_lazy_generic( const int isDMS = dictMode == ZSTD_dictMatchState; const int isDDS = dictMode == ZSTD_dedicatedDictSearch; const int isDxS = isDMS || isDDS; - const ZSTD_matchState_t* const dms = ms->dictMatchState; + const ZSTD_MatchState_t* const dms = ms->dictMatchState; const U32 dictLowestIndex = isDxS ? dms->window.dictLimit : 0; const BYTE* const dictBase = isDxS ? dms->window.base : NULL; const BYTE* const dictLowest = isDxS ? dictBase + dictLowestIndex : NULL; @@ -1782,42 +1782,42 @@ _storeSequence: #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_noDict); } size_t ZSTD_compressBlock_greedy_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_greedy_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_noDict); } size_t ZSTD_compressBlock_greedy_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0, ZSTD_dedicatedDictSearch); @@ -1826,42 +1826,42 @@ size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 1, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_lazy_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 1, ZSTD_dedicatedDictSearch); @@ -1870,42 +1870,42 @@ size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 2, ZSTD_dedicatedDictSearch); } size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2, ZSTD_dedicatedDictSearch); @@ -1914,14 +1914,14 @@ size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_noDict); } size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, search_binaryTree, 2, ZSTD_dictMatchState); @@ -1935,7 +1935,7 @@ size_t ZSTD_compressBlock_btlazy2_dictMatchState( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_compressBlock_lazy_extDict_generic( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth) @@ -2139,14 +2139,14 @@ _storeSequence: #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_hashChain, 0); } size_t ZSTD_compressBlock_greedy_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 0); @@ -2155,7 +2155,7 @@ size_t ZSTD_compressBlock_greedy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2163,7 +2163,7 @@ size_t ZSTD_compressBlock_lazy_extDict( } size_t ZSTD_compressBlock_lazy_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2173,7 +2173,7 @@ size_t ZSTD_compressBlock_lazy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { @@ -2181,7 +2181,7 @@ size_t ZSTD_compressBlock_lazy2_extDict( } size_t ZSTD_compressBlock_lazy2_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, search_rowHash, 2); @@ -2190,7 +2190,7 @@ size_t ZSTD_compressBlock_lazy2_extDict_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize) { diff --git a/lib/compress/zstd_lazy.h b/lib/compress/zstd_lazy.h index 21258145e..6da51e4ec 100644 --- a/lib/compress/zstd_lazy.h +++ b/lib/compress/zstd_lazy.h @@ -31,38 +31,38 @@ extern "C" { || !defined(ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR) -U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip); -void ZSTD_row_update(ZSTD_matchState_t* const ms, const BYTE* ip); +U32 ZSTD_insertAndFindFirstIndex(ZSTD_MatchState_t* ms, const BYTE* ip); +void ZSTD_row_update(ZSTD_MatchState_t* const ms, const BYTE* ip); -void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_matchState_t* ms, const BYTE* const ip); +void ZSTD_dedicatedDictSearch_lazy_loadDictionary(ZSTD_MatchState_t* ms, const BYTE* const ip); void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const reducerValue); /*! used in ZSTD_reduceIndex(). preemptively increase value of ZSTD_DUBT_UNSORTED_MARK */ #endif #ifndef ZSTD_EXCLUDE_GREEDY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_greedy( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_greedy_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_GREEDY ZSTD_compressBlock_greedy @@ -86,28 +86,28 @@ size_t ZSTD_compressBlock_greedy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_LAZY ZSTD_compressBlock_lazy @@ -131,28 +131,28 @@ size_t ZSTD_compressBlock_lazy_extDict_row( #ifndef ZSTD_EXCLUDE_LAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_lazy2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dictMatchState_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_dedicatedDictSearch_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_lazy2_extDict_row( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_LAZY2 ZSTD_compressBlock_lazy2 @@ -176,13 +176,13 @@ size_t ZSTD_compressBlock_lazy2_extDict_row( #ifndef ZSTD_EXCLUDE_BTLAZY2_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btlazy2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btlazy2_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btlazy2_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTLAZY2 ZSTD_compressBlock_btlazy2 diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index e636a42c0..8812b72a2 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -234,7 +234,7 @@ static size_t ZSTD_ldm_countBackwardsMatch_2segments( * * The tables for the other strategies are filled within their * block compressors. */ -static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms, +static size_t ZSTD_ldm_fillFastTables(ZSTD_MatchState_t* ms, void const* end) { const BYTE* const iend = (const BYTE*)end; @@ -314,7 +314,7 @@ void ZSTD_ldm_fillHashTable( * Sets cctx->nextToUpdate to a position corresponding closer to anchor * if it is far way * (after a long match, only update tables a limited amount). */ -static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor) +static void ZSTD_ldm_limitTableUpdate(ZSTD_MatchState_t* ms, const BYTE* anchor) { U32 const curr = (U32)(anchor - ms->window.base); if (curr > ms->nextToUpdate + 1024) { @@ -665,7 +665,7 @@ void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) { } size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize) { diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h index 624caf937..9bdf90cda 100644 --- a/lib/compress/zstd_ldm.h +++ b/lib/compress/zstd_ldm.h @@ -65,7 +65,7 @@ size_t ZSTD_ldm_generateSequences( * NOTE: This function does not return any errors. */ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize); diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 1045cdd2c..1aee5017b 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -408,7 +408,7 @@ MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length) Assumption : always within prefix (i.e. not within extDict) */ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms, +U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_MatchState_t* ms, U32* nextToUpdate3, const BYTE* const ip) { @@ -440,7 +440,7 @@ U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms, static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertBt1( - const ZSTD_matchState_t* ms, + const ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, U32 const target, U32 const mls, const int extDict) @@ -560,7 +560,7 @@ U32 ZSTD_insertBt1( FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_updateTree_internal( - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, const U32 mls, const ZSTD_dictMode_e dictMode) { @@ -580,7 +580,7 @@ void ZSTD_updateTree_internal( ms->nextToUpdate = target; } -void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) { +void ZSTD_updateTree(ZSTD_MatchState_t* ms, const BYTE* ip, const BYTE* iend) { ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict); } @@ -589,7 +589,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_insertBtAndGetAllMatches ( ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */ - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, U32* nextToUpdate3, const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode, @@ -625,7 +625,7 @@ ZSTD_insertBtAndGetAllMatches ( U32 mnum = 0; U32 nbCompares = 1U << cParams->searchLog; - const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL; + const ZSTD_MatchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL; const ZSTD_compressionParameters* const dmsCParams = dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL; const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL; @@ -819,7 +819,7 @@ ZSTD_insertBtAndGetAllMatches ( typedef U32 (*ZSTD_getAllMatchesFn)( ZSTD_match_t*, - ZSTD_matchState_t*, + ZSTD_MatchState_t*, U32*, const BYTE*, const BYTE*, @@ -831,7 +831,7 @@ FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR U32 ZSTD_btGetAllMatches_internal( ZSTD_match_t* matches, - ZSTD_matchState_t* ms, + ZSTD_MatchState_t* ms, U32* nextToUpdate3, const BYTE* ip, const BYTE* const iHighLimit, @@ -854,7 +854,7 @@ U32 ZSTD_btGetAllMatches_internal( #define GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, mls) \ static U32 ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls)( \ ZSTD_match_t* matches, \ - ZSTD_matchState_t* ms, \ + ZSTD_MatchState_t* ms, \ U32* nextToUpdate3, \ const BYTE* ip, \ const BYTE* const iHighLimit, \ @@ -886,7 +886,7 @@ GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState) } static ZSTD_getAllMatchesFn -ZSTD_selectBtGetAllMatches(ZSTD_matchState_t const* ms, ZSTD_dictMode_e const dictMode) +ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_dictMode_e const dictMode) { ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = { ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict), @@ -1072,7 +1072,7 @@ listStats(const U32* table, int lastEltID) FORCE_INLINE_TEMPLATE ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t -ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms, +ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, @@ -1440,7 +1440,7 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt0( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode); @@ -1449,7 +1449,7 @@ static size_t ZSTD_compressBlock_opt0( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); @@ -1458,7 +1458,7 @@ static size_t ZSTD_compressBlock_opt2( #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_compressBlock_btopt"); @@ -1477,7 +1477,7 @@ size_t ZSTD_compressBlock_btopt( */ static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR -void ZSTD_initStats_ultra(ZSTD_matchState_t* ms, +void ZSTD_initStats_ultra(ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) @@ -1503,7 +1503,7 @@ void ZSTD_initStats_ultra(ZSTD_matchState_t* ms, } size_t ZSTD_compressBlock_btultra( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize); @@ -1511,7 +1511,7 @@ size_t ZSTD_compressBlock_btultra( } size_t ZSTD_compressBlock_btultra2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { U32 const curr = (U32)((const BYTE*)src - ms->window.base); @@ -1541,14 +1541,14 @@ size_t ZSTD_compressBlock_btultra2( #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_btopt_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict); @@ -1557,14 +1557,14 @@ size_t ZSTD_compressBlock_btopt_extDict( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState); } size_t ZSTD_compressBlock_btultra_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize) { return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict); diff --git a/lib/compress/zstd_opt.h b/lib/compress/zstd_opt.h index 9e1cff91a..247c9ee65 100644 --- a/lib/compress/zstd_opt.h +++ b/lib/compress/zstd_opt.h @@ -21,18 +21,18 @@ extern "C" { || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) /* used in ZSTD_loadDictionaryContent() */ -void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend); +void ZSTD_updateTree(ZSTD_MatchState_t* ms, const BYTE* ip, const BYTE* iend); #endif #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btopt( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btopt_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btopt_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTOPT ZSTD_compressBlock_btopt @@ -46,20 +46,20 @@ size_t ZSTD_compressBlock_btopt_extDict( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR size_t ZSTD_compressBlock_btultra( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btultra_dictMatchState( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); size_t ZSTD_compressBlock_btultra_extDict( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); /* note : no btultra2 variant for extDict nor dictMatchState, * because btultra2 is not meant to work with dictionaries * and is only specific for the first block (no prefix) */ size_t ZSTD_compressBlock_btultra2( - ZSTD_matchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], + ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); #define ZSTD_COMPRESSBLOCK_BTULTRA ZSTD_compressBlock_btultra From 41c667c0fdfa653f52809975bce8306b21099810 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:00:20 -0800 Subject: [PATCH 505/937] codemod: repcodes_t -> Repcodes_t --- lib/compress/zstd_compress.c | 66 +++++++++++++------------ lib/compress/zstd_compress_internal.h | 6 +-- lib/compress/zstd_compress_superblock.c | 2 +- lib/compress/zstd_opt.c | 16 +++--- 4 files changed, 46 insertions(+), 44 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 029928fb2..03806c234 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3427,7 +3427,7 @@ static size_t ZSTD_copyBlockSequences(SeqCollector* seqCollector, const SeqStore ZSTD_Sequence* outSeqs = seqCollector->seqIndex == 0 ? seqCollector->seqStart : seqCollector->seqStart + seqCollector->seqIndex; const size_t nbOutSequences = nbInSequences + 1; size_t nbOutLiterals = 0; - repcodes_t repcodes; + Repcodes_t repcodes; size_t i; /* Bounds check that we have enough space for every input sequence @@ -4059,7 +4059,7 @@ ZSTD_resolveRepcodeToRawOffset(const U32 rep[ZSTD_REP_NUM], const U32 offBase, c * 4+ : real_offset+3 */ static void -ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRepcodes, +ZSTD_seqStore_resolveOffCodes(Repcodes_t* const dRepcodes, Repcodes_t* const cRepcodes, const SeqStore_t* const seqStore, U32 const nbSeq) { U32 idx = 0; @@ -4096,7 +4096,7 @@ ZSTD_seqStore_resolveOffCodes(repcodes_t* const dRepcodes, repcodes_t* const cRe static size_t ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, const SeqStore_t* const seqStore, - repcodes_t* const dRep, repcodes_t* const cRep, + Repcodes_t* const dRep, Repcodes_t* const cRep, void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock, U32 isPartition) @@ -4108,7 +4108,7 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, size_t cSeqsSize; /* In case of an RLE or raw block, the simulated decompression repcode history must be reset */ - repcodes_t const dRepOriginal = *dRep; + Repcodes_t const dRepOriginal = *dRep; DEBUGLOG(5, "ZSTD_compressSeqStore_singleBlock"); if (isPartition) ZSTD_seqStore_resolveOffCodes(dRep, cRep, seqStore, (U32)(seqStore->sequences - seqStore->sequencesStart)); @@ -4279,10 +4279,10 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, * * See ZSTD_seqStore_resolveOffCodes() for more details. */ - repcodes_t dRep; - repcodes_t cRep; - ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t)); - ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(repcodes_t)); + Repcodes_t dRep; + Repcodes_t cRep; + ZSTD_memcpy(dRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t)); + ZSTD_memcpy(cRep.rep, zc->blockState.prevCBlock->rep, sizeof(Repcodes_t)); ZSTD_memset(nextSeqStore, 0, sizeof(SeqStore_t)); DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)", @@ -4338,7 +4338,7 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, /* cRep and dRep may have diverged during the compression. * If so, we use the dRep repcodes for the next block. */ - ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(repcodes_t)); + ZSTD_memcpy(zc->blockState.prevCBlock->rep, dRep.rep, sizeof(Repcodes_t)); return cSize; } @@ -6617,21 +6617,22 @@ static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32 /* This function scans through an array of ZSTD_Sequence, * storing the sequences it reads, until it reaches a block delimiter. - * Note that the block delimiter must include the last literals of the block. + * Note that the block delimiter includes the last literals of the block. + * @blockSize must be == sum(sequence_lengths). * @returns 0 on success, and a ZSTD_error otherwise. */ static size_t ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, - ZSTD_paramSwitch_e externalRepSearch) + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, + const void* src, size_t blockSize, + ZSTD_paramSwitch_e externalRepSearch) { U32 idx = seqPos->idx; U32 const startIdx = idx; BYTE const* ip = (BYTE const*)(src); const BYTE* const iend = ip + blockSize; - repcodes_t updatedRepcodes; + Repcodes_t updatedRepcodes; U32 dictSize; DEBUGLOG(5, "ZSTD_transferSequences_wBlockDelim (blockSize = %zu)", blockSize); @@ -6643,7 +6644,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, } else { dictSize = 0; } - ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(repcodes_t)); + ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t)); for (; idx < inSeqsSize && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) { U32 const litLength = inSeqs[idx].litLength; U32 const matchLength = inSeqs[idx].matchLength; @@ -6695,7 +6696,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, } } - ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t)); + ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); if (inSeqs[idx].litLength) { DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength); @@ -6708,24 +6709,25 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, return 0; } -/* Returns the number of bytes to move the current read position back by. - * Only non-zero if we ended up splitting a sequence. - * Otherwise, it may return a ZSTD error if something went wrong. - * - * This function will attempt to scan through blockSize bytes +/* + * This function attempts to scan through blockSize bytes * represented by the sequences in @inSeqs, * storing any (partial) sequences. * + * @returns the number of bytes to move the current read position back by. + * Only non-zero if we ended up splitting a sequence. + * Otherwise, it may return a ZSTD error if something went wrong. + * * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to * avoid splitting a match, or to avoid splitting a match such that it would produce a match * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block. */ static size_t -ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, - const void* src, size_t blockSize, - ZSTD_paramSwitch_e externalRepSearch) +ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t inSeqsSize, + const void* src, size_t blockSize, + ZSTD_paramSwitch_e externalRepSearch) { U32 idx = seqPos->idx; U32 startPosInSequence = seqPos->posInSequence; @@ -6733,7 +6735,7 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, size_t dictSize; BYTE const* ip = (BYTE const*)(src); BYTE const* iend = ip + blockSize; /* May be adjusted if we decide to process fewer than blockSize bytes */ - repcodes_t updatedRepcodes; + Repcodes_t updatedRepcodes; U32 bytesAdjustment = 0; U32 finalMatchSplit = 0; @@ -6747,9 +6749,9 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, } else { dictSize = 0; } - DEBUGLOG(5, "ZSTD_copySequencesToSeqStoreNoBlockDelim: idx: %u PIS: %u blockSize: %zu", idx, startPosInSequence, blockSize); + DEBUGLOG(5, "ZSTD_transferSequences_noDelim: idx: %u PIS: %u blockSize: %zu", idx, 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)); + 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; @@ -6830,7 +6832,7 @@ ZSTD_copySequencesToSeqStoreNoBlockDelim(ZSTD_CCtx* cctx, assert(idx == inSeqsSize || endPosInSequence <= inSeqs[idx].litLength + inSeqs[idx].matchLength); seqPos->idx = idx; seqPos->posInSequence = endPosInSequence; - ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(repcodes_t)); + ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); iend -= bytesAdjustment; if (ip != iend) { @@ -6855,7 +6857,7 @@ static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mod return ZSTD_transferSequences_wBlockDelim; } assert(mode == ZSTD_sf_noBlockDelimiters); - return ZSTD_copySequencesToSeqStoreNoBlockDelim; + return ZSTD_transferSequences_noDelim; } /* Discover the size of next block by searching for the delimiter. diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 91066a4be..2387d9c28 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -849,12 +849,12 @@ ZSTD_updateRep(U32 rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0) typedef struct repcodes_s { U32 rep[3]; -} repcodes_t; +} Repcodes_t; -MEM_STATIC repcodes_t +MEM_STATIC Repcodes_t ZSTD_newRep(U32 const rep[ZSTD_REP_NUM], U32 const offBase, U32 const ll0) { - repcodes_t newReps; + Repcodes_t newReps; ZSTD_memcpy(&newReps, rep, sizeof(newReps)); ZSTD_updateRep(newReps.rep, offBase, ll0); return newReps; diff --git a/lib/compress/zstd_compress_superblock.c b/lib/compress/zstd_compress_superblock.c index 672af2d32..6f57345be 100644 --- a/lib/compress/zstd_compress_superblock.c +++ b/lib/compress/zstd_compress_superblock.c @@ -648,7 +648,7 @@ static size_t ZSTD_compressSubBlock_multi(const SeqStore_t* seqStorePtr, /* We have to regenerate the repcodes because we've skipped some sequences */ if (sp < send) { const SeqDef* seq; - repcodes_t rep; + Repcodes_t rep; ZSTD_memcpy(&rep, prevCBlock->rep, sizeof(rep)); for (seq = sstart; seq < sp; ++seq) { ZSTD_updateRep(rep.rep, seq->offBase, ZSTD_getSequenceLength(seqStorePtr, seq).litLength == 0); diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 1aee5017b..8f3b4d100 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1227,13 +1227,13 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, && (with1literal < opt[cur+1].price) ) { /* update offset history - before it disappears */ U32 const prev = cur - prevMatch.mlen; - repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, prevMatch.off, opt[prev].litlen==0); + Repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, prevMatch.off, opt[prev].litlen==0); assert(cur >= prevMatch.mlen); DEBUGLOG(7, "==> match+1lit is cheaper (%.2f < %.2f) (hist:%u,%u,%u) !", ZSTD_fCost(with1literal), ZSTD_fCost(withMoreLiterals), newReps.rep[0], newReps.rep[1], newReps.rep[2] ); opt[cur+1] = prevMatch; /* mlen & offbase */ - ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(repcodes_t)); + ZSTD_memcpy(opt[cur+1].rep, &newReps, sizeof(Repcodes_t)); opt[cur+1].litlen = 1; opt[cur+1].price = with1literal; if (last_pos < cur+1) last_pos = cur+1; @@ -1248,13 +1248,13 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, /* Offset history is not updated during match comparison. * Do it here, now that the match is selected and confirmed. */ - ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t)); + ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(Repcodes_t)); assert(cur >= opt[cur].mlen); if (opt[cur].litlen == 0) { /* just finished a match => alter offset history */ U32 const prev = cur - opt[cur].mlen; - repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0); - ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t)); + Repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[prev].litlen==0); + ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(Repcodes_t)); } /* last match must start at a minimum distance of 8 from oend */ @@ -1353,10 +1353,10 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ /* Update offset history */ if (lastStretch.litlen == 0) { /* finishing on a match : update offset history */ - repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastStretch.off, opt[cur].litlen==0); - ZSTD_memcpy(rep, &reps, sizeof(repcodes_t)); + Repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastStretch.off, opt[cur].litlen==0); + ZSTD_memcpy(rep, &reps, sizeof(Repcodes_t)); } else { - ZSTD_memcpy(rep, lastStretch.rep, sizeof(repcodes_t)); + ZSTD_memcpy(rep, lastStretch.rep, sizeof(Repcodes_t)); assert(cur >= lastStretch.litlen); cur -= lastStretch.litlen; } From 25bef24c5cf47fe9841edb4b2b6708e206833d31 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:04:01 -0800 Subject: [PATCH 506/937] codemod: rawSeqStore_t -> RawSeqStore_t --- lib/compress/zstd_compress.c | 2 +- lib/compress/zstd_compress_internal.h | 8 ++++---- lib/compress/zstd_ldm.c | 12 ++++++------ lib/compress/zstd_ldm.h | 8 ++++---- lib/compress/zstd_opt.c | 4 ++-- lib/compress/zstdmt_compress.c | 16 ++++++++-------- 6 files changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 03806c234..7ad630735 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3317,7 +3317,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) src, srcSize); assert(zc->externSeqStore.pos <= zc->externSeqStore.size); } else if (zc->appliedParams.ldmParams.enableLdm == ZSTD_ps_enable) { - rawSeqStore_t ldmSeqStore = kNullRawSeqStore; + RawSeqStore_t ldmSeqStore = kNullRawSeqStore; /* External matchfinder + LDM is technically possible, just not implemented yet. * We need to revisit soon and implement it. */ diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 2387d9c28..9fb35de48 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -213,9 +213,9 @@ typedef struct { stopped. posInSequence <= seq[pos].litLength + seq[pos].matchLength */ size_t size; /* The number of sequences. <= capacity. */ size_t capacity; /* The capacity starting from `seq` pointer */ -} rawSeqStore_t; +} RawSeqStore_t; -UNUSED_ATTR static const rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0}; +UNUSED_ATTR static const RawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0, 0}; typedef struct { int price; /* price from beginning of segment to this position */ @@ -303,7 +303,7 @@ struct ZSTD_MatchState_t { optState_t opt; /* optimal parser state */ const ZSTD_MatchState_t* dictMatchState; ZSTD_compressionParameters cParams; - const rawSeqStore_t* ldmSeqStore; + const RawSeqStore_t* ldmSeqStore; /* Controls prefetching in some dictMatchState matchfinders. * This behavior is controlled from the cctx ms. @@ -500,7 +500,7 @@ struct ZSTD_CCtx_s { ldmState_t ldmState; /* long distance matching state */ rawSeq* ldmSequences; /* Storage for the ldm output sequences */ size_t maxNbLdmSequences; - rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */ + RawSeqStore_t externSeqStore; /* Mutable reference to external sequences */ ZSTD_blockState_t blockState; void* tmpWorkspace; /* used as substitute of stack space - must be aligned for S64 type */ size_t tmpWkspSize; diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 8812b72a2..30caeb1a8 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -326,7 +326,7 @@ static void ZSTD_ldm_limitTableUpdate(ZSTD_MatchState_t* ms, const BYTE* anchor) static ZSTD_ALLOW_POINTER_OVERFLOW_ATTR size_t ZSTD_ldm_generateSequences_internal( - ldmState_t* ldmState, rawSeqStore_t* rawSeqStore, + ldmState_t* ldmState, RawSeqStore_t* rawSeqStore, ldmParams_t const* params, void const* src, size_t srcSize) { /* LDM parameters */ @@ -510,7 +510,7 @@ static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size, } size_t ZSTD_ldm_generateSequences( - ldmState_t* ldmState, rawSeqStore_t* sequences, + ldmState_t* ldmState, RawSeqStore_t* sequences, ldmParams_t const* params, void const* src, size_t srcSize) { U32 const maxDist = 1U << params->windowLog; @@ -587,7 +587,7 @@ size_t ZSTD_ldm_generateSequences( } void -ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch) +ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch) { while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) { rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos; @@ -623,7 +623,7 @@ ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const min * Returns the current sequence to handle, or if the rest of the block should * be literals, it returns a sequence with offset == 0. */ -static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore, +static rawSeq maybeSplitSequence(RawSeqStore_t* rawSeqStore, U32 const remaining, U32 const minMatch) { rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos]; @@ -647,7 +647,7 @@ static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore, return sequence; } -void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) { +void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) { U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes); while (currPos && rawSeqStore->pos < rawSeqStore->size) { rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos]; @@ -664,7 +664,7 @@ void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) { } } -size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, +size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore, ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize) diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h index 9bdf90cda..e43ab4e78 100644 --- a/lib/compress/zstd_ldm.h +++ b/lib/compress/zstd_ldm.h @@ -43,7 +43,7 @@ void ZSTD_ldm_fillHashTable( * sequences. */ size_t ZSTD_ldm_generateSequences( - ldmState_t* ldms, rawSeqStore_t* sequences, + ldmState_t* ldms, RawSeqStore_t* sequences, ldmParams_t const* params, void const* src, size_t srcSize); /** @@ -64,7 +64,7 @@ size_t ZSTD_ldm_generateSequences( * two. We handle that case correctly, and update `rawSeqStore` appropriately. * NOTE: This function does not return any errors. */ -size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, +size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore, ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], ZSTD_paramSwitch_e useRowMatchFinder, void const* src, size_t srcSize); @@ -76,7 +76,7 @@ size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore, * Avoids emitting matches less than `minMatch` bytes. * Must be called for data that is not passed to ZSTD_ldm_blockCompress(). */ -void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, +void ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch); /* ZSTD_ldm_skipRawSeqStoreBytes(): @@ -84,7 +84,7 @@ void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, * Not to be used in conjunction with ZSTD_ldm_skipSequences(). * Must be called for data with is not passed to ZSTD_ldm_blockCompress(). */ -void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes); +void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes); /** ZSTD_ldm_getTableSize() : * Estimate the space needed for long distance matching tables or 0 if LDM is diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 8f3b4d100..0ab33d56e 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -905,7 +905,7 @@ ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_dictMode_e const di /* Struct containing info needed to make decision about ldm inclusion */ typedef struct { - rawSeqStore_t seqStore; /* External match candidates store for this block */ + RawSeqStore_t seqStore; /* External match candidates store for this block */ U32 startPosInBlock; /* Start position of the current match candidate */ U32 endPosInBlock; /* End position of the current match candidate */ U32 offset; /* Offset of the match candidate */ @@ -915,7 +915,7 @@ typedef struct { * Moves forward in @rawSeqStore by @nbBytes, * which will update the fields 'pos' and 'posInSequence'. */ -static void ZSTD_optLdm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) +static void ZSTD_optLdm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) { U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes); while (currPos && rawSeqStore->pos < rawSeqStore->size) { diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 86ccce318..e8fef5144 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -290,15 +290,15 @@ static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool) return ZSTDMT_sizeof_bufferPool(seqPool); } -static rawSeqStore_t bufferToSeq(buffer_t buffer) +static RawSeqStore_t bufferToSeq(buffer_t buffer) { - rawSeqStore_t seq = kNullRawSeqStore; + RawSeqStore_t seq = kNullRawSeqStore; seq.seq = (rawSeq*)buffer.start; seq.capacity = buffer.capacity / sizeof(rawSeq); return seq; } -static buffer_t seqToBuffer(rawSeqStore_t seq) +static buffer_t seqToBuffer(RawSeqStore_t seq) { buffer_t buffer; buffer.start = seq.seq; @@ -306,7 +306,7 @@ static buffer_t seqToBuffer(rawSeqStore_t seq) return buffer; } -static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool) +static RawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool) { if (seqPool->bufferSize == 0) { return kNullRawSeqStore; @@ -315,13 +315,13 @@ static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool) } #if ZSTD_RESIZE_SEQPOOL -static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq) +static RawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, RawSeqStore_t seq) { return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq))); } #endif -static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq) +static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, RawSeqStore_t seq) { ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq)); } @@ -578,7 +578,7 @@ static void ZSTDMT_serialState_free(serialState_t* serialState) } static void ZSTDMT_serialState_update(serialState_t* serialState, - ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore, + ZSTD_CCtx* jobCCtx, RawSeqStore_t seqStore, range_t src, unsigned jobID) { /* Wait for our turn */ @@ -685,7 +685,7 @@ static void ZSTDMT_compressionJob(void* jobDescription) ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription; ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */ ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool); - rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool); + RawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool); buffer_t dstBuff = job->dstBuff; size_t lastCBlockSize = 0; From 08edecb78c0b95db74aa9747cc06206d74027b0f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:08:44 -0800 Subject: [PATCH 507/937] codemod: ZSTD_blockCompressor -> ZSTD_BlockCompressor_f --- lib/compress/zstd_compress.c | 12 ++++++------ lib/compress/zstd_compress_internal.h | 4 ++-- lib/compress/zstd_ldm.c | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 7ad630735..0c094dabc 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3074,9 +3074,9 @@ ZSTD_entropyCompressSeqStore( /* ZSTD_selectBlockCompressor() : * Not static, but internal use only (used by long distance matcher) * assumption : strat is a valid strategy */ -ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode) +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode) { - static const ZSTD_blockCompressor blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { + static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { { ZSTD_compressBlock_fast /* default for 0 */, ZSTD_compressBlock_fast, ZSTD_COMPRESSBLOCK_DOUBLEFAST, @@ -3121,13 +3121,13 @@ ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramS NULL, NULL } }; - ZSTD_blockCompressor selectedCompressor; + ZSTD_BlockCompressor_f selectedCompressor; ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1); assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat)); DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder); if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) { - static const ZSTD_blockCompressor rowBasedBlockCompressors[4][3] = { + static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = { { ZSTD_COMPRESSBLOCK_GREEDY_ROW, ZSTD_COMPRESSBLOCK_LAZY_ROW, @@ -3391,7 +3391,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) } /* Fallback to software matchfinder */ - { ZSTD_blockCompressor const blockCompressor = + { ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor( zc->appliedParams.cParams.strategy, zc->appliedParams.useRowMatchFinder, @@ -3405,7 +3405,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize); } } } else { /* not long range mode and no external matchfinder */ - ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor( + ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor( zc->appliedParams.cParams.strategy, zc->appliedParams.useRowMatchFinder, dictMode); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 9fb35de48..8257607e0 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -579,10 +579,10 @@ typedef enum { */ } ZSTD_cParamMode_e; -typedef size_t (*ZSTD_blockCompressor) ( +typedef size_t (*ZSTD_BlockCompressor_f) ( ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); MEM_STATIC U32 ZSTD_LLcode(U32 litLength) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 30caeb1a8..2b84c3027 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -671,7 +671,7 @@ size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore, { const ZSTD_compressionParameters* const cParams = &ms->cParams; unsigned const minMatch = cParams->minMatch; - ZSTD_blockCompressor const blockCompressor = + ZSTD_BlockCompressor_f const blockCompressor = ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms)); /* Input bounds */ BYTE const* const istart = (BYTE const*)src; From e0f3aaee467bbcb7e1653756eb426a9b7adde5d8 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:17:41 -0800 Subject: [PATCH 508/937] doc: add mention of frame checksum incompatibility for new prototype ZSTD_compressSequencesAndLiterals() --- lib/zstd.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 94058a1b2..b3c82e174 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1660,10 +1660,11 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize, /*! ZSTD_compressSequencesAndLiterals() : * This is a variant of ZSTD_compressSequences() which, * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), - * aka all literals already extracted and grouped into a single continuous buffer. + * aka all literals already extracted and laid out into a single continuous buffer. * This can be useful if the process generating the sequences also happens to generate the buffer of literals, * thus skipping an extraction + caching stage. - * To be valid, `litSize` must be equal to the sum of all @.litLength fields in @inSeqs. + * To be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. + * Important: Employing this prototype is incompatible with frame checksum. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t From 2503b64345b22d3f1729c2c380bc98500c8024aa Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:21:47 -0800 Subject: [PATCH 509/937] fix minor artifact error in single_file_lib --- build/single_file_libs/.gitignore | 1 + build/single_file_libs/examples/zstd_errors.h | 106 ------------------ 2 files changed, 1 insertion(+), 106 deletions(-) delete mode 100644 build/single_file_libs/examples/zstd_errors.h diff --git a/build/single_file_libs/.gitignore b/build/single_file_libs/.gitignore index 8c1bc71ed..b769e1089 100644 --- a/build/single_file_libs/.gitignore +++ b/build/single_file_libs/.gitignore @@ -4,6 +4,7 @@ zstddeclib.c zstdenclib.c zstd.c zstd.h +zstd_errors.h # test artifacts temp* diff --git a/build/single_file_libs/examples/zstd_errors.h b/build/single_file_libs/examples/zstd_errors.h deleted file mode 100644 index 20e488f15..000000000 --- a/build/single_file_libs/examples/zstd_errors.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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_ERRORS_H_398273423 -#define ZSTD_ERRORS_H_398273423 - -#if defined (__cplusplus) -extern "C" { -#endif - -/* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */ -#ifndef ZSTDERRORLIB_VISIBLE - /* Backwards compatibility with old macro name */ -# ifdef ZSTDERRORLIB_VISIBILITY -# define ZSTDERRORLIB_VISIBLE ZSTDERRORLIB_VISIBILITY -# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) -# define ZSTDERRORLIB_VISIBLE __attribute__ ((visibility ("default"))) -# else -# define ZSTDERRORLIB_VISIBLE -# endif -#endif - -#ifndef ZSTDERRORLIB_HIDDEN -# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__) -# define ZSTDERRORLIB_HIDDEN __attribute__ ((visibility ("hidden"))) -# else -# define ZSTDERRORLIB_HIDDEN -# endif -#endif - -#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1) -# define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBLE -#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1) -# define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ -#else -# define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBLE -#endif - -/*-********************************************* - * Error codes list - *-********************************************* - * Error codes _values_ are pinned down since v1.3.1 only. - * Therefore, don't rely on values if you may link to any version < v1.3.1. - * - * Only values < 100 are considered stable. - * - * note 1 : this API shall be used with static linking only. - * dynamic linking is not yet officially supported. - * note 2 : Prefer relying on the enum than on its value whenever possible - * This is the only supported way to use the error list < v1.3.1 - * note 3 : ZSTD_isError() is always correct, whatever the library version. - **********************************************/ -typedef enum { - ZSTD_error_no_error = 0, - ZSTD_error_GENERIC = 1, - ZSTD_error_prefix_unknown = 10, - ZSTD_error_version_unsupported = 12, - ZSTD_error_frameParameter_unsupported = 14, - ZSTD_error_frameParameter_windowTooLarge = 16, - ZSTD_error_corruption_detected = 20, - ZSTD_error_checksum_wrong = 22, - ZSTD_error_literals_headerWrong = 24, - ZSTD_error_dictionary_corrupted = 30, - ZSTD_error_dictionary_wrong = 32, - ZSTD_error_dictionaryCreation_failed = 34, - ZSTD_error_parameter_unsupported = 40, - ZSTD_error_parameter_combination_unsupported = 41, - ZSTD_error_parameter_outOfBound = 42, - ZSTD_error_tableLog_tooLarge = 44, - ZSTD_error_maxSymbolValue_tooLarge = 46, - ZSTD_error_maxSymbolValue_tooSmall = 48, - ZSTD_error_stabilityCondition_notRespected = 50, - ZSTD_error_stage_wrong = 60, - ZSTD_error_init_missing = 62, - ZSTD_error_memory_allocation = 64, - ZSTD_error_workSpace_tooSmall= 66, - ZSTD_error_dstSize_tooSmall = 70, - ZSTD_error_srcSize_wrong = 72, - ZSTD_error_dstBuffer_null = 74, - ZSTD_error_noForwardProgress_destFull = 80, - ZSTD_error_noForwardProgress_inputEmpty = 82, - /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */ - ZSTD_error_frameIndex_tooLarge = 100, - ZSTD_error_seekableIO = 102, - ZSTD_error_dstBuffer_wrong = 104, - ZSTD_error_srcBuffer_wrong = 105, - ZSTD_error_sequenceProducer_failed = 106, - ZSTD_error_externalSequences_invalid = 107, - ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */ -} ZSTD_ErrorCode; - -ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */ - - -#if defined (__cplusplus) -} -#endif - -#endif /* ZSTD_ERRORS_H_398273423 */ From 13b9296d79094185565f42b55a19fa88b43aa19d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:38:51 -0800 Subject: [PATCH 510/937] minor simplification --- doc/zstd_manual.html | 27 +++++++++++++++------------ lib/compress/zstd_compress.c | 17 +++++++---------- lib/zstd.h | 22 ++++++++++++---------- 3 files changed, 34 insertions(+), 32 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index e6f8fc504..a780e97d9 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1376,13 +1376,14 @@ ZSTD_generateSequences(ZSTD_CCtx* zc,


ZSTDLIB_STATIC_API size_t
-ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
-            const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
-            const void* src, size_t srcSize);
+ZSTD_compressSequences(ZSTD_CCtx* cctx,
+           void* dst, size_t dstCapacity,
+     const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
+     const void* src, size_t srcSize);
 

Compress an array of ZSTD_Sequence, associated with @src buffer, into dst. @src contains the entire input (not just the literals). If @srcSize > sum(sequence.length), the remaining bytes are considered all literals - If a dictionary is included, then the cctx should reference the dict. (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.) + If a dictionary is included, then the cctx should reference the dict (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.). The entire source is compressed into a single frame. The compression behavior changes based on cctx params. In particular: @@ -1403,23 +1404,25 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize, - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md - Note: Repcodes are, as of now, always re-calculated within this function, so ZSTD_Sequence::rep is unused. - Note 2: Once we integrate ability to ingest repcodes, the explicit block delims mode must respect those repcodes exactly, - and cannot emit an RLE block that disagrees with the repcode history + Note: Repcodes are, as of now, always re-calculated within this function, ZSTD_Sequence.rep is effectively unused. + Dev Note: Once ability to ingest repcodes become available, the explicit block delims mode must respect those repcodes exactly, + and cannot emit an RLE block that disagrees with the repcode history. @return : final compressed size, or a ZSTD error code.


ZSTDLIB_STATIC_API size_t
-ZSTD_compressSequencesAndLiterals( ZSTD_CCtx* cctx, void* dst, size_t dstSize,
-            const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
-            const void* literals, size_t litSize);
+ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
+                      void* dst, size_t dstCapacity,
+                const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
+                const void* literals, size_t litSize);
 

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), - aka all literals already extracted and grouped into a single continuous buffer. + aka all literals already extracted and laid out into a single continuous buffer. This can be useful if the process generating the sequences also happens to generate the buffer of literals, thus skipping an extraction + caching stage. - To be valid, `litSize` must be equal to the sum of all @.litLength fields in @inSeqs. + To be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. + Important: Employing this prototype is incompatible with frame checksum. @return : final compressed size, or a ZSTD error code.


diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 0c094dabc..92f757b1b 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6887,20 +6887,17 @@ blockSize_explicitDelimiter(const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD return blockSize; } -/* More a "target" block size */ -static size_t blockSize_noDelimiter(size_t blockSize, size_t remaining) -{ - int const lastBlock = (remaining <= blockSize); - return lastBlock ? remaining : blockSize; -} - static size_t determine_blockSize(ZSTD_SequenceFormat_e mode, size_t blockSize, size_t remaining, - const ZSTD_Sequence* inSeqs, size_t inSeqsSize, ZSTD_SequencePosition seqPos) + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + ZSTD_SequencePosition seqPos) { DEBUGLOG(6, "determine_blockSize : remainingSize = %zu", remaining); - if (mode == ZSTD_sf_noBlockDelimiters) - return blockSize_noDelimiter(blockSize, remaining); + if (mode == ZSTD_sf_noBlockDelimiters) { + /* Note: more a "target" block size */ + return MIN(remaining, blockSize); + } + assert(mode == ZSTD_sf_explicitBlockDelimiters); { size_t const explicitBlockSize = blockSize_explicitDelimiter(inSeqs, inSeqsSize, seqPos); FORWARD_IF_ERROR(explicitBlockSize, "Error while determining block size with explicit delimiters"); if (explicitBlockSize > blockSize) diff --git a/lib/zstd.h b/lib/zstd.h index b3c82e174..08feed9a6 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1625,7 +1625,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, si * Compress an array of ZSTD_Sequence, associated with @src buffer, into dst. * @src contains the entire input (not just the literals). * If @srcSize > sum(sequence.length), the remaining bytes are considered all literals - * If a dictionary is included, then the cctx should reference the dict. (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.) + * If a dictionary is included, then the cctx should reference the dict (see: ZSTD_CCtx_refCDict(), ZSTD_CCtx_loadDictionary(), etc.). * The entire source is compressed into a single frame. * * The compression behavior changes based on cctx params. In particular: @@ -1646,15 +1646,16 @@ ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, si * - ZSTD_c_windowLog affects offset validation: this function will return an error at higher debug levels if a provided offset * is larger than what the spec allows for a given window log and dictionary (if present). See: doc/zstd_compression_format.md * - * Note: Repcodes are, as of now, always re-calculated within this function, so ZSTD_Sequence::rep is unused. - * Note 2: Once we integrate ability to ingest repcodes, the explicit block delims mode must respect those repcodes exactly, - * and cannot emit an RLE block that disagrees with the repcode history + * Note: Repcodes are, as of now, always re-calculated within this function, ZSTD_Sequence.rep is effectively unused. + * Dev Note: Once ability to ingest repcodes become available, the explicit block delims mode must respect those repcodes exactly, + * and cannot emit an RLE block that disagrees with the repcode history. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t -ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize, - const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* src, size_t srcSize); +ZSTD_compressSequences(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const void* src, size_t srcSize); /*! ZSTD_compressSequencesAndLiterals() : @@ -1668,9 +1669,10 @@ ZSTD_compressSequences( ZSTD_CCtx* cctx, void* dst, size_t dstSize, * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t -ZSTD_compressSequencesAndLiterals( ZSTD_CCtx* cctx, void* dst, size_t dstSize, - const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* literals, size_t litSize); +ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const void* literals, size_t litSize); /*! ZSTD_writeSkippableFrame() : From 56cfb7816a5a627b39c03405e967cf67691974c4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 10 Dec 2024 16:54:53 -0800 Subject: [PATCH 511/937] codemod: ZSTD_paramSwitch_e -> ZSTD_ParamSwitch_e --- contrib/largeNbDicts/largeNbDicts.c | 2 +- doc/zstd_manual.html | 2 +- lib/compress/zstd_compress.c | 73 +++++++++++++++------------ lib/compress/zstd_compress_internal.h | 16 +++--- lib/compress/zstd_ldm.c | 2 +- lib/compress/zstd_ldm.h | 2 +- lib/zstd.h | 15 +++--- programs/benchzstd.h | 2 +- programs/fileio.c | 4 +- programs/fileio.h | 4 +- programs/fileio_types.h | 4 +- programs/zstdcli.c | 6 +-- 12 files changed, 71 insertions(+), 61 deletions(-) diff --git a/contrib/largeNbDicts/largeNbDicts.c b/contrib/largeNbDicts/largeNbDicts.c index eeaaf7182..6502f1227 100644 --- a/contrib/largeNbDicts/largeNbDicts.c +++ b/contrib/largeNbDicts/largeNbDicts.c @@ -1025,7 +1025,7 @@ int main (int argc, const char** argv) unsigned nbBlocks = 0; /* determine nbBlocks automatically, from source and blockSize */ ZSTD_dictContentType_e dictContentType = ZSTD_dct_auto; ZSTD_dictAttachPref_e dictAttachPref = ZSTD_dictDefaultAttach; - ZSTD_paramSwitch_e prefetchCDictTables = ZSTD_ps_auto; + ZSTD_ParamSwitch_e prefetchCDictTables = ZSTD_ps_auto; metricAggregatePref_e metricAggregatePref = fastest; for (int argNb = 1; argNb < argc ; argNb++) { diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index a780e97d9..f3fb75264 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1196,7 +1196,7 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); ZSTD_ps_auto = 0,
/* Let the library automatically determine whether the feature shall be enabled */ ZSTD_ps_enable = 1, /* Force-enable the feature */ ZSTD_ps_disable = 2 /* Do not use the feature */ -} ZSTD_paramSwitch_e; +} ZSTD_ParamSwitch_e;

Frame header and size functions


 
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 92f757b1b..2290fd869 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -87,7 +87,7 @@ struct ZSTD_CDict_s {
     ZSTD_customMem customMem;
     U32 dictID;
     int compressionLevel; /* 0 indicates that advanced API was used to select CDict params */
-    ZSTD_paramSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
+    ZSTD_ParamSwitch_e useRowMatchFinder; /* Indicates whether the CDict was created with params that would use
                                            * row-based matchfinder. Unless the cdict is reloaded, we will use
                                            * the same greedy/lazy matchfinder at compression time.
                                            */
@@ -228,13 +228,13 @@ static int ZSTD_rowMatchFinderSupported(const ZSTD_strategy strategy) {
 /* Returns true if the strategy and useRowMatchFinder mode indicate that we will use the row based matchfinder
  * for this compression.
  */
-static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_paramSwitch_e mode) {
+static int ZSTD_rowMatchFinderUsed(const ZSTD_strategy strategy, const ZSTD_ParamSwitch_e mode) {
     assert(mode != ZSTD_ps_auto);
     return ZSTD_rowMatchFinderSupported(strategy) && (mode == ZSTD_ps_enable);
 }
 
 /* Returns row matchfinder usage given an initial mode and cParams */
-static ZSTD_paramSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_paramSwitch_e mode,
+static ZSTD_ParamSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_ParamSwitch_e mode,
                                                          const ZSTD_compressionParameters* const cParams) {
 #if defined(ZSTD_ARCH_X86_SSE2) || defined(ZSTD_ARCH_ARM_NEON)
     int const kHasSIMD128 = 1;
@@ -253,7 +253,7 @@ static ZSTD_paramSwitch_e ZSTD_resolveRowMatchFinderMode(ZSTD_paramSwitch_e mode
 }
 
 /* Returns block splitter usage (generally speaking, when using slower/stronger compression modes) */
-static ZSTD_paramSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_paramSwitch_e mode,
+static ZSTD_ParamSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_ParamSwitch_e mode,
                                                         const ZSTD_compressionParameters* const cParams) {
     if (mode != ZSTD_ps_auto) return mode;
     return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 17) ? ZSTD_ps_enable : ZSTD_ps_disable;
@@ -261,7 +261,7 @@ static ZSTD_paramSwitch_e ZSTD_resolveBlockSplitterMode(ZSTD_paramSwitch_e mode,
 
 /* Returns 1 if the arguments indicate that we should allocate a chainTable, 0 otherwise */
 static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
-                                   const ZSTD_paramSwitch_e useRowMatchFinder,
+                                   const ZSTD_ParamSwitch_e useRowMatchFinder,
                                    const U32 forDDSDict) {
     assert(useRowMatchFinder != ZSTD_ps_auto);
     /* We always should allocate a chaintable if we are allocating a matchstate for a DDS dictionary matchstate.
@@ -274,7 +274,7 @@ static int ZSTD_allocateChainTable(const ZSTD_strategy strategy,
  * enable long distance matching (wlog >= 27, strategy >= btopt).
  * Returns ZSTD_ps_disable otherwise.
  */
-static ZSTD_paramSwitch_e ZSTD_resolveEnableLdm(ZSTD_paramSwitch_e mode,
+static ZSTD_ParamSwitch_e ZSTD_resolveEnableLdm(ZSTD_ParamSwitch_e mode,
                                  const ZSTD_compressionParameters* const cParams) {
     if (mode != ZSTD_ps_auto) return mode;
     return (cParams->strategy >= ZSTD_btopt && cParams->windowLog >= 27) ? ZSTD_ps_enable : ZSTD_ps_disable;
@@ -293,7 +293,7 @@ static size_t ZSTD_resolveMaxBlockSize(size_t maxBlockSize) {
     }
 }
 
-static ZSTD_paramSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_paramSwitch_e value, int cLevel) {
+static ZSTD_ParamSwitch_e ZSTD_resolveExternalRepcodeSearch(ZSTD_ParamSwitch_e value, int cLevel) {
     if (value != ZSTD_ps_auto) return value;
     if (cLevel < 10) {
         return ZSTD_ps_disable;
@@ -865,7 +865,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
     }
 
     case ZSTD_c_literalCompressionMode : {
-        const ZSTD_paramSwitch_e lcm = (ZSTD_paramSwitch_e)value;
+        const ZSTD_ParamSwitch_e lcm = (ZSTD_ParamSwitch_e)value;
         BOUNDCHECK(ZSTD_c_literalCompressionMode, (int)lcm);
         CCtxParams->literalCompressionMode = lcm;
         return CCtxParams->literalCompressionMode;
@@ -921,7 +921,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
 
     case ZSTD_c_enableLongDistanceMatching :
         BOUNDCHECK(ZSTD_c_enableLongDistanceMatching, value);
-        CCtxParams->ldmParams.enableLdm = (ZSTD_paramSwitch_e)value;
+        CCtxParams->ldmParams.enableLdm = (ZSTD_ParamSwitch_e)value;
         return CCtxParams->ldmParams.enableLdm;
 
     case ZSTD_c_ldmHashLog :
@@ -984,7 +984,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
 
     case ZSTD_c_splitAfterSequences:
         BOUNDCHECK(ZSTD_c_splitAfterSequences, value);
-        CCtxParams->postBlockSplitter = (ZSTD_paramSwitch_e)value;
+        CCtxParams->postBlockSplitter = (ZSTD_ParamSwitch_e)value;
         return CCtxParams->postBlockSplitter;
 
     case ZSTD_c_blockSplitterLevel:
@@ -994,7 +994,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
 
     case ZSTD_c_useRowMatchFinder:
         BOUNDCHECK(ZSTD_c_useRowMatchFinder, value);
-        CCtxParams->useRowMatchFinder = (ZSTD_paramSwitch_e)value;
+        CCtxParams->useRowMatchFinder = (ZSTD_ParamSwitch_e)value;
         return CCtxParams->useRowMatchFinder;
 
     case ZSTD_c_deterministicRefPrefix:
@@ -1004,7 +1004,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
 
     case ZSTD_c_prefetchCDictTables:
         BOUNDCHECK(ZSTD_c_prefetchCDictTables, value);
-        CCtxParams->prefetchCDictTables = (ZSTD_paramSwitch_e)value;
+        CCtxParams->prefetchCDictTables = (ZSTD_ParamSwitch_e)value;
         return CCtxParams->prefetchCDictTables;
 
     case ZSTD_c_enableSeqProducerFallback:
@@ -1021,7 +1021,7 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams,
 
     case ZSTD_c_searchForExternalRepcodes:
         BOUNDCHECK(ZSTD_c_searchForExternalRepcodes, value);
-        CCtxParams->searchForExternalRepcodes = (ZSTD_paramSwitch_e)value;
+        CCtxParams->searchForExternalRepcodes = (ZSTD_ParamSwitch_e)value;
         return CCtxParams->searchForExternalRepcodes;
 
     default: RETURN_ERROR(parameter_unsupported, "unknown parameter");
@@ -1482,7 +1482,7 @@ ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
                             unsigned long long srcSize,
                             size_t dictSize,
                             ZSTD_cParamMode_e mode,
-                            ZSTD_paramSwitch_e useRowMatchFinder)
+                            ZSTD_ParamSwitch_e useRowMatchFinder)
 {
     const U64 minSrcSize = 513; /* (1<<9) + 1 */
     const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
@@ -1660,7 +1660,7 @@ ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
 
 static size_t
 ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
-                       const ZSTD_paramSwitch_e useRowMatchFinder,
+                       const ZSTD_ParamSwitch_e useRowMatchFinder,
                        const int enableDedicatedDictSearch,
                        const U32 forCCtx)
 {
@@ -1711,7 +1711,7 @@ static size_t ZSTD_estimateCCtxSize_usingCCtxParams_internal(
         const ZSTD_compressionParameters* cParams,
         const ldmParams_t* ldmParams,
         const int isStatic,
-        const ZSTD_paramSwitch_e useRowMatchFinder,
+        const ZSTD_ParamSwitch_e useRowMatchFinder,
         const size_t buffInSize,
         const size_t buffOutSize,
         const U64 pledgedSrcSize,
@@ -1763,7 +1763,7 @@ size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
 {
     ZSTD_compressionParameters const cParams =
                 ZSTD_getCParamsFromCCtxParams(params, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
-    ZSTD_paramSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder,
+    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.");
@@ -1828,7 +1828,7 @@ size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
         size_t const outBuffSize = (params->outBufferMode == ZSTD_bm_buffered)
                 ? ZSTD_compressBound(blockSize) + 1
                 : 0;
-        ZSTD_paramSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, ¶ms->cParams);
+        ZSTD_ParamSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(params->useRowMatchFinder, ¶ms->cParams);
 
         return ZSTD_estimateCCtxSize_usingCCtxParams_internal(
             &cParams, ¶ms->ldmParams, 1, useRowMatchFinder, inBuffSize, outBuffSize,
@@ -1993,7 +1993,7 @@ static size_t
 ZSTD_reset_matchState(ZSTD_MatchState_t* ms,
                       ZSTD_cwksp* ws,
                 const ZSTD_compressionParameters* cParams,
-                const ZSTD_paramSwitch_e useRowMatchFinder,
+                const ZSTD_ParamSwitch_e useRowMatchFinder,
                 const ZSTD_compResetPolicy_e crp,
                 const ZSTD_indexResetPolicy_e forceResetIndex,
                 const ZSTD_resetTarget_e forWho)
@@ -3074,7 +3074,7 @@ ZSTD_entropyCompressSeqStore(
 /* ZSTD_selectBlockCompressor() :
  * Not static, but internal use only (used by long distance matcher)
  * assumption : strat is a valid strategy */
-ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
+ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode)
 {
     static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = {
         { ZSTD_compressBlock_fast  /* default for 0 */,
@@ -3250,7 +3250,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
                                    ZSTD_SequencePosition* seqPos,
                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
                              const void* src, size_t blockSize,
-                                   ZSTD_paramSwitch_e externalRepSearch);
+                                   ZSTD_ParamSwitch_e externalRepSearch);
 
 typedef enum { ZSTDbss_compress, ZSTDbss_noCompress } ZSTD_BuildSeqStore_e;
 
@@ -5591,7 +5591,7 @@ static size_t ZSTD_initCDict_internal(
 static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize,
                                       ZSTD_dictLoadMethod_e dictLoadMethod,
                                       ZSTD_compressionParameters cParams,
-                                      ZSTD_paramSwitch_e useRowMatchFinder,
+                                      ZSTD_ParamSwitch_e useRowMatchFinder,
                                       int enableDedicatedDictSearch,
                                       ZSTD_customMem customMem)
 {
@@ -5746,7 +5746,7 @@ const ZSTD_CDict* ZSTD_initStaticCDict(
                                  ZSTD_dictContentType_e dictContentType,
                                  ZSTD_compressionParameters cParams)
 {
-    ZSTD_paramSwitch_e const useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(ZSTD_ps_auto, &cParams);
+    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))
@@ -6626,7 +6626,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
                                    ZSTD_SequencePosition* seqPos,
                              const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
                              const void* src, size_t blockSize,
-                                   ZSTD_paramSwitch_e externalRepSearch)
+                                   ZSTD_ParamSwitch_e externalRepSearch)
 {
     U32 idx = seqPos->idx;
     U32 const startIdx = idx;
@@ -6727,7 +6727,7 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
                                ZSTD_SequencePosition* seqPos,
                          const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
                          const void* src, size_t blockSize,
-                               ZSTD_paramSwitch_e externalRepSearch)
+                               ZSTD_ParamSwitch_e externalRepSearch)
 {
     U32 idx = seqPos->idx;
     U32 startPosInSequence = seqPos->posInSequence;
@@ -6847,9 +6847,18 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
     return bytesAdjustment;
 }
 
-typedef size_t (*ZSTD_SequenceCopier_f) (ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos,
-                                       const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
-                                       const void* src, size_t blockSize, ZSTD_paramSwitch_e externalRepSearch);
+/* @seqPos represents a position within @inSeqs,
+ * it is read and updated by this function,
+ * once the goal to produce a block of size @blockSize is reached.
+ * @return: nb of bytes missing to reach @blockSize goal.
+ * so (@blockSize - @return) represents the nb of bytes ingested from @src.
+ */
+typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,
+                                        ZSTD_SequencePosition* seqPos,
+                                  const ZSTD_Sequence* const inSeqs, size_t inSeqsSize,
+                                  const void* src, size_t blockSize,
+                                        ZSTD_ParamSwitch_e externalRepSearch);
+
 static ZSTD_SequenceCopier_f ZSTD_selectSequenceCopier(ZSTD_SequenceFormat_e mode)
 {
     assert(ZSTD_cParam_withinBounds(ZSTD_c_blockDelimiters, (int)mode));
@@ -6941,7 +6950,6 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
     while (remaining) {
         size_t compressedSeqsSize;
         size_t cBlockSize;
-        size_t additionalByteAdjustment;
         size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters,
                                         cctx->blockSize, remaining,
                                         inSeqs, inSeqsSize, seqPos);
@@ -6950,9 +6958,10 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
         assert(blockSize <= remaining);
         ZSTD_resetSeqStore(&cctx->seqStore);
 
-        additionalByteAdjustment = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize, cctx->appliedParams.searchForExternalRepcodes);
-        FORWARD_IF_ERROR(additionalByteAdjustment, "Bad sequence copy");
-        blockSize -= additionalByteAdjustment;
+        {   size_t adjust = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize, cctx->appliedParams.searchForExternalRepcodes);
+            FORWARD_IF_ERROR(adjust, "Bad sequence copy");
+            blockSize -= adjust;
+        }
 
         /* If blocks are too small, emit as a nocompress block */
         /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index 8257607e0..dd43d597c 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -247,7 +247,7 @@ typedef struct {
     U32  offCodeSumBasePrice;    /* to compare to log2(offreq)  */
     ZSTD_OptPrice_e priceType;   /* prices can be determined dynamically, or follow a pre-defined cost structure */
     const ZSTD_entropyCTables_t* symbolCosts;  /* pre-calculated dictionary statistics */
-    ZSTD_paramSwitch_e literalCompressionMode;
+    ZSTD_ParamSwitch_e literalCompressionMode;
 } optState_t;
 
 typedef struct {
@@ -348,7 +348,7 @@ typedef struct {
 } ldmState_t;
 
 typedef struct {
-    ZSTD_paramSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
+    ZSTD_ParamSwitch_e enableLdm; /* ZSTD_ps_enable to enable LDM. ZSTD_ps_auto by default */
     U32 hashLog;            /* Log size of hashTable */
     U32 bucketSizeLog;      /* Log bucket size for collision resolution, at most 8 */
     U32 minMatchLength;     /* Minimum match length */
@@ -379,7 +379,7 @@ struct ZSTD_CCtx_params_s {
                                 * There is no guarantee that hint is close to actual source size */
 
     ZSTD_dictAttachPref_e attachDictPref;
-    ZSTD_paramSwitch_e literalCompressionMode;
+    ZSTD_ParamSwitch_e literalCompressionMode;
 
     /* Multithreading: used to pass parameters to mtctx */
     int nbWorkers;
@@ -411,14 +411,14 @@ struct ZSTD_CCtx_params_s {
      * then levels are sorted in increasing cpu budget, from 2 (fastest) to 6 (slowest).
      * Highest @preBlockSplitter_level combines well with @postBlockSplitter.
      */
-    ZSTD_paramSwitch_e postBlockSplitter;
+    ZSTD_ParamSwitch_e postBlockSplitter;
     int preBlockSplitter_level;
 
     /* Adjust the max block size*/
     size_t maxBlockSize;
 
     /* Param for deciding whether to use row-based matchfinder */
-    ZSTD_paramSwitch_e useRowMatchFinder;
+    ZSTD_ParamSwitch_e useRowMatchFinder;
 
     /* Always load a dictionary in ext-dict mode (not prefix mode)? */
     int deterministicRefPrefix;
@@ -427,7 +427,7 @@ struct ZSTD_CCtx_params_s {
     ZSTD_customMem customMem;
 
     /* Controls prefetching in some dictMatchState matchfinders */
-    ZSTD_paramSwitch_e prefetchCDictTables;
+    ZSTD_ParamSwitch_e prefetchCDictTables;
 
     /* Controls whether zstd will fall back to an internal matchfinder
      * if the external matchfinder returns an error code. */
@@ -440,7 +440,7 @@ struct ZSTD_CCtx_params_s {
     ZSTD_sequenceProducer_F extSeqProdFunc;
 
     /* Controls repcode search in external sequence parsing */
-    ZSTD_paramSwitch_e searchForExternalRepcodes;
+    ZSTD_ParamSwitch_e searchForExternalRepcodes;
 };  /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
 
 #define COMPRESS_SEQUENCES_WORKSPACE_SIZE (sizeof(unsigned) * (MaxSeq + 2))
@@ -582,7 +582,7 @@ typedef enum {
 typedef size_t (*ZSTD_BlockCompressor_f) (
         ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
         void const* src, size_t srcSize);
-ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_paramSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
+ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode);
 
 
 MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c
index 2b84c3027..42b38c0d0 100644
--- a/lib/compress/zstd_ldm.c
+++ b/lib/compress/zstd_ldm.c
@@ -666,7 +666,7 @@ void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) {
 
 size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore,
     ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
-    ZSTD_paramSwitch_e useRowMatchFinder,
+    ZSTD_ParamSwitch_e useRowMatchFinder,
     void const* src, size_t srcSize)
 {
     const ZSTD_compressionParameters* const cParams = &ms->cParams;
diff --git a/lib/compress/zstd_ldm.h b/lib/compress/zstd_ldm.h
index e43ab4e78..8efa7c4f0 100644
--- a/lib/compress/zstd_ldm.h
+++ b/lib/compress/zstd_ldm.h
@@ -66,7 +66,7 @@ size_t ZSTD_ldm_generateSequences(
  */
 size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore,
             ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
-            ZSTD_paramSwitch_e useRowMatchFinder,
+            ZSTD_ParamSwitch_e useRowMatchFinder,
             void const* src, size_t srcSize);
 
 /**
diff --git a/lib/zstd.h b/lib/zstd.h
index 08feed9a6..978f8cebd 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -1433,14 +1433,15 @@ typedef enum {
 } ZSTD_literalCompressionMode_e;
 
 typedef enum {
-  /* Note: This enum controls features which are conditionally beneficial. Zstd typically will make a final
-   * decision on whether or not to enable the feature (ZSTD_ps_auto), but setting the switch to ZSTD_ps_enable
-   * or ZSTD_ps_disable allow for a force enable/disable the feature.
+  /* Note: This enum controls features which are conditionally beneficial.
+   * Zstd can take a decision on whether or not to enable the feature (ZSTD_ps_auto),
+   * but setting the switch to ZSTD_ps_enable or ZSTD_ps_disable force enable/disable the feature.
    */
   ZSTD_ps_auto = 0,         /* Let the library automatically determine whether the feature shall be enabled */
   ZSTD_ps_enable = 1,       /* Force-enable the feature */
   ZSTD_ps_disable = 2       /* Do not use the feature */
-} ZSTD_paramSwitch_e;
+} ZSTD_ParamSwitch_e;
+#define ZSTD_paramSwitch_e ZSTD_ParamSwitch_e  /* old name */
 
 /***************************************
 *  Frame header and size functions
@@ -2024,7 +2025,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo
  * See the comments on that enum for an explanation of the feature. */
 #define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4
 
-/* Controlled with ZSTD_paramSwitch_e enum.
+/* Controlled with ZSTD_ParamSwitch_e enum.
  * Default is ZSTD_ps_auto.
  * Set to ZSTD_ps_disable to never compress literals.
  * Set to ZSTD_ps_enable to always compress literals. (Note: uncompressed literals
@@ -2215,7 +2216,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo
 #define ZSTD_c_splitAfterSequences ZSTD_c_experimentalParam13
 
 /* ZSTD_c_useRowMatchFinder
- * Controlled with ZSTD_paramSwitch_e enum.
+ * Controlled with ZSTD_ParamSwitch_e enum.
  * Default is ZSTD_ps_auto.
  * Set to ZSTD_ps_disable to never use row-based matchfinder.
  * Set to ZSTD_ps_enable to force usage of row-based matchfinder.
@@ -2247,7 +2248,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo
 #define ZSTD_c_deterministicRefPrefix ZSTD_c_experimentalParam15
 
 /* ZSTD_c_prefetchCDictTables
- * Controlled with ZSTD_paramSwitch_e enum. Default is ZSTD_ps_auto.
+ * Controlled with ZSTD_ParamSwitch_e enum. Default is ZSTD_ps_auto.
  *
  * In some situations, zstd uses CDict tables in-place rather than copying them
  * into the working context. (See docs on ZSTD_dictAttachPref_e above for details).
diff --git a/programs/benchzstd.h b/programs/benchzstd.h
index 6388d4d58..6ff62d43e 100644
--- a/programs/benchzstd.h
+++ b/programs/benchzstd.h
@@ -109,7 +109,7 @@ typedef struct {
     int ldmHashLog;
     int ldmBucketSizeLog;
     int ldmHashRateLog;
-    ZSTD_paramSwitch_e literalCompressionMode;
+    ZSTD_ParamSwitch_e literalCompressionMode;
     int useRowMatchFinder;  /* use row-based matchfinder if possible */
 } BMK_advancedParams_t;
 
diff --git a/programs/fileio.c b/programs/fileio.c
index c6af36fbd..c2036b83c 100644
--- a/programs/fileio.c
+++ b/programs/fileio.c
@@ -423,7 +423,7 @@ void FIO_setTestMode(FIO_prefs_t* const prefs, int testMode) {
 
 void FIO_setLiteralCompressionMode(
         FIO_prefs_t* const prefs,
-        ZSTD_paramSwitch_e mode) {
+        ZSTD_ParamSwitch_e mode) {
     prefs->literalCompressionMode = mode;
 }
 
@@ -485,7 +485,7 @@ void FIO_setPassThroughFlag(FIO_prefs_t* const prefs, int value) {
     prefs->passThrough = (value != 0);
 }
 
-void FIO_setMMapDict(FIO_prefs_t* const prefs, ZSTD_paramSwitch_e value)
+void FIO_setMMapDict(FIO_prefs_t* const prefs, ZSTD_ParamSwitch_e value)
 {
     prefs->mmapDict = value;
 }
diff --git a/programs/fileio.h b/programs/fileio.h
index 224d89525..e8cb2e6ab 100644
--- a/programs/fileio.h
+++ b/programs/fileio.h
@@ -95,7 +95,7 @@ void FIO_setSrcSizeHint(FIO_prefs_t* const prefs, size_t srcSizeHint);
 void FIO_setTestMode(FIO_prefs_t* const prefs, int testMode);
 void FIO_setLiteralCompressionMode(
         FIO_prefs_t* const prefs,
-        ZSTD_paramSwitch_e mode);
+        ZSTD_ParamSwitch_e mode);
 
 void FIO_setProgressSetting(FIO_progressSetting_e progressSetting);
 void FIO_setNotificationLevel(int level);
@@ -106,7 +106,7 @@ void FIO_setContentSize(FIO_prefs_t* const prefs, int value);
 void FIO_displayCompressionParameters(const FIO_prefs_t* prefs);
 void FIO_setAsyncIOFlag(FIO_prefs_t* const prefs, int value);
 void FIO_setPassThroughFlag(FIO_prefs_t* const prefs, int value);
-void FIO_setMMapDict(FIO_prefs_t* const prefs, ZSTD_paramSwitch_e value);
+void FIO_setMMapDict(FIO_prefs_t* const prefs, ZSTD_ParamSwitch_e value);
 
 /* FIO_ctx_t functions */
 void FIO_setNbFilesTotal(FIO_ctx_t* const fCtx, int value);
diff --git a/programs/fileio_types.h b/programs/fileio_types.h
index 2994a6092..23bda4168 100644
--- a/programs/fileio_types.h
+++ b/programs/fileio_types.h
@@ -53,7 +53,7 @@ typedef struct FIO_prefs_s {
     size_t targetCBlockSize;
     int srcSizeHint;
     int testMode;
-    ZSTD_paramSwitch_e literalCompressionMode;
+    ZSTD_ParamSwitch_e literalCompressionMode;
 
     /* IO preferences */
     int removeSrcFile;
@@ -69,7 +69,7 @@ typedef struct FIO_prefs_s {
     int contentSize;
     int allowBlockDevices;
     int passThrough;
-    ZSTD_paramSwitch_e mmapDict;
+    ZSTD_ParamSwitch_e mmapDict;
 } FIO_prefs_t;
 
 typedef enum {FIO_mallocDict, FIO_mmapDict} FIO_dictBufferType_t;
diff --git a/programs/zstdcli.c b/programs/zstdcli.c
index 2a9a77624..9fa7e2275 100644
--- a/programs/zstdcli.c
+++ b/programs/zstdcli.c
@@ -849,8 +849,8 @@ int main(int argCount, const char* argv[])
         ultra=0,
         contentSize=1,
         removeSrcFile=0;
-    ZSTD_paramSwitch_e mmapDict=ZSTD_ps_auto;
-    ZSTD_paramSwitch_e useRowMatchFinder = ZSTD_ps_auto;
+    ZSTD_ParamSwitch_e mmapDict=ZSTD_ps_auto;
+    ZSTD_ParamSwitch_e useRowMatchFinder = ZSTD_ps_auto;
     FIO_compressionType_t cType = FIO_zstdCompression;
     int nbWorkers = -1; /* -1 means unset */
     double compressibility = -1.0;  /* lorem ipsum generator */
@@ -891,7 +891,7 @@ int main(int argCount, const char* argv[])
 #ifndef ZSTD_NOBENCH
     BMK_advancedParams_t benchParams = BMK_initAdvancedParams();
 #endif
-    ZSTD_paramSwitch_e literalCompressionMode = ZSTD_ps_auto;
+    ZSTD_ParamSwitch_e literalCompressionMode = ZSTD_ps_auto;
 
     /* init */
     checkLibVersion();

From 4ef9d7d585e8892dacd3f954848b91cd5e773ff7 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 10 Dec 2024 17:07:19 -0800
Subject: [PATCH 512/937] codemod: ZSTD_cParamMode_e -> ZSTD_CParamMode_e

---
 doc/zstd_manual.html                  |  6 ++--
 lib/compress/zstd_compress.c          | 40 ++++++++++++++++-----------
 lib/compress/zstd_compress_internal.h |  4 +--
 3 files changed, 29 insertions(+), 21 deletions(-)

diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index f3fb75264..4cf72cb91 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -1189,9 +1189,9 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 } ZSTD_literalCompressionMode_e;
 

typedef enum {
-  /* Note: This enum controls features which are conditionally beneficial. Zstd typically will make a final
-   * decision on whether or not to enable the feature (ZSTD_ps_auto), but setting the switch to ZSTD_ps_enable
-   * or ZSTD_ps_disable allow for a force enable/disable the feature.
+  /* Note: This enum controls features which are conditionally beneficial.
+   * Zstd can take a decision on whether or not to enable the feature (ZSTD_ps_auto),
+   * but setting the switch to ZSTD_ps_enable or ZSTD_ps_disable force enable/disable the feature.
    */
   ZSTD_ps_auto = 0,         /* Let the library automatically determine whether the feature shall be enabled */
   ZSTD_ps_enable = 1,       /* Force-enable the feature */
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 2290fd869..4fcf32cfa 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -1474,14 +1474,14 @@ static U32 ZSTD_dictAndWindowLog(U32 windowLog, U64 srcSize, U64 dictSize)
  *  optimize `cPar` for a specified input (`srcSize` and `dictSize`).
  *  mostly downsize to reduce memory consumption and initialization latency.
  * `srcSize` can be ZSTD_CONTENTSIZE_UNKNOWN when not known.
- * `mode` is the mode for parameter adjustment. See docs for `ZSTD_cParamMode_e`.
+ * `mode` is the mode for parameter adjustment. See docs for `ZSTD_CParamMode_e`.
  *  note : `srcSize==0` means 0!
  *  condition : cPar is presumed validated (can be checked using ZSTD_checkCParams()). */
 static ZSTD_compressionParameters
 ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
                             unsigned long long srcSize,
                             size_t dictSize,
-                            ZSTD_cParamMode_e mode,
+                            ZSTD_CParamMode_e mode,
                             ZSTD_ParamSwitch_e useRowMatchFinder)
 {
     const U64 minSrcSize = 513; /* (1<<9) + 1 */
@@ -1626,8 +1626,8 @@ ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
     return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize, ZSTD_cpm_unknown, ZSTD_ps_auto);
 }
 
-static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
-static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
+static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
+static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
 
 static void ZSTD_overrideCParams(
               ZSTD_compressionParameters* cParams,
@@ -1643,7 +1643,7 @@ static void ZSTD_overrideCParams(
 }
 
 ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
-        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
+        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
 {
     ZSTD_compressionParameters cParams;
     if (srcSizeHint == ZSTD_CONTENTSIZE_UNKNOWN && CCtxParams->srcSizeHint > 0) {
@@ -5941,7 +5941,7 @@ size_t ZSTD_CStreamOutSize(void)
     return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
 }
 
-static ZSTD_cParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
+static ZSTD_CParamMode_e ZSTD_getCParamMode(ZSTD_CDict const* cdict, ZSTD_CCtx_params const* params, U64 pledgedSrcSize)
 {
     if (cdict != NULL && ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize))
         return ZSTD_cpm_attachDict;
@@ -6326,6 +6326,11 @@ static size_t ZSTD_checkBufferStability(ZSTD_CCtx const* cctx,
     return 0;
 }
 
+/*
+ * If @endOp == ZSTD_e_end, @inSize becomes pledgedSrcSize.
+ * Otherwise, it's ignored.
+ * @return: 0 on success, or a ZSTD_error code otherwise.
+ */
 static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
                                              ZSTD_EndDirective endOp,
                                              size_t inSize)
@@ -6348,7 +6353,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx,
     {   size_t const dictSize = prefixDict.dict
                 ? prefixDict.dictSize
                 : (cctx->cdict ? cctx->cdict->dictContentSize : 0);
-        ZSTD_cParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, ¶ms, cctx->pledgedSrcSizePlusOne - 1);
+        ZSTD_CParamMode_e const mode = ZSTD_getCParamMode(cctx->cdict, ¶ms, cctx->pledgedSrcSizePlusOne - 1);
         params.cParams = ZSTD_getCParamsFromCCtxParams(
                 ¶ms, cctx->pledgedSrcSizePlusOne-1,
                 dictSize, mode);
@@ -7184,7 +7189,7 @@ static void ZSTD_dedicatedDictSearch_revertCParams(
     }
 }
 
-static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
+static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
 {
     switch (mode) {
     case ZSTD_cpm_unknown:
@@ -7208,8 +7213,8 @@ static U64 ZSTD_getCParamRowSize(U64 srcSizeHint, size_t dictSize, ZSTD_cParamMo
  * @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
  *  Note: srcSizeHint 0 means 0, use ZSTD_CONTENTSIZE_UNKNOWN for unknown.
  *        Use dictSize == 0 for unknown or unused.
- *  Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_cParamMode_e`. */
-static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode)
+ *  Note: `mode` controls how we treat the `dictSize`. See docs for `ZSTD_CParamMode_e`. */
+static ZSTD_compressionParameters ZSTD_getCParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
 {
     U64 const rSize = ZSTD_getCParamRowSize(srcSizeHint, dictSize, mode);
     U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB);
@@ -7247,7 +7252,9 @@ ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long l
  *  same idea as ZSTD_getCParams()
  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
  *  Fields of `ZSTD_frameParameters` are set to default values */
-static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode) {
+static ZSTD_parameters
+ZSTD_getParams_internal(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode)
+{
     ZSTD_parameters params;
     ZSTD_compressionParameters const cParams = ZSTD_getCParams_internal(compressionLevel, srcSizeHint, dictSize, mode);
     DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
@@ -7261,7 +7268,8 @@ static ZSTD_parameters ZSTD_getParams_internal(int compressionLevel, unsigned lo
  *  same idea as ZSTD_getCParams()
  * @return a `ZSTD_parameters` structure (instead of `ZSTD_compressionParameters`).
  *  Fields of `ZSTD_frameParameters` are set to default values */
-ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
+ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
+{
     if (srcSizeHint == 0) srcSizeHint = ZSTD_CONTENTSIZE_UNKNOWN;
     return ZSTD_getParams_internal(compressionLevel, srcSizeHint, dictSize, ZSTD_cpm_unknown);
 }
@@ -7269,8 +7277,8 @@ ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeH
 void ZSTD_registerSequenceProducer(
     ZSTD_CCtx* zc,
     void* extSeqProdState,
-    ZSTD_sequenceProducer_F extSeqProdFunc
-) {
+    ZSTD_sequenceProducer_F extSeqProdFunc)
+{
     assert(zc != NULL);
     ZSTD_CCtxParams_registerSequenceProducer(
         &zc->requestedParams, extSeqProdState, extSeqProdFunc
@@ -7280,8 +7288,8 @@ void ZSTD_registerSequenceProducer(
 void ZSTD_CCtxParams_registerSequenceProducer(
   ZSTD_CCtx_params* params,
   void* extSeqProdState,
-  ZSTD_sequenceProducer_F extSeqProdFunc
-) {
+  ZSTD_sequenceProducer_F extSeqProdFunc)
+{
     assert(params != NULL);
     if (extSeqProdFunc != NULL) {
         params->extSeqProdFunc = extSeqProdFunc;
diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h
index dd43d597c..90d462fd2 100644
--- a/lib/compress/zstd_compress_internal.h
+++ b/lib/compress/zstd_compress_internal.h
@@ -577,7 +577,7 @@ typedef enum {
                                  * behavior of taking both the source size and the dict size into account
                                  * when selecting and adjusting parameters.
                                  */
-} ZSTD_cParamMode_e;
+} ZSTD_CParamMode_e;
 
 typedef size_t (*ZSTD_BlockCompressor_f) (
         ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
@@ -1542,7 +1542,7 @@ void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs);
  * Note: srcSizeHint == 0 means 0!
  */
 ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
-        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_cParamMode_e mode);
+        const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize, ZSTD_CParamMode_e mode);
 
 /*! ZSTD_initCStream_internal() :
  *  Private use only. Init streaming operation.

From 047db4f1f8e9d340e24b752323af17df1f0bb782 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 10 Dec 2024 17:51:20 -0800
Subject: [PATCH 513/937] ZSTD_SequenceCopier_f no returns the nb of bytes
 consumed from input

which feels much more natural
---
 doc/zstd_manual.html         |  4 +--
 lib/compress/zstd_compress.c | 51 ++++++++++++++++++------------------
 lib/zstd.h                   |  4 +--
 3 files changed, 30 insertions(+), 29 deletions(-)

diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index 4cf72cb91..10546e938 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -1315,8 +1315,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr,
 


typedef enum {
-  ZSTD_sf_noBlockDelimiters = 0,         /* Representation of ZSTD_Sequence has no block delimiters, sequences only */
-  ZSTD_sf_explicitBlockDelimiters = 1    /* Representation of ZSTD_Sequence contains explicit block delimiters */
+  ZSTD_sf_noBlockDelimiters = 0,         /* ZSTD_Sequence[] has no block delimiters, just sequences */
+  ZSTD_sf_explicitBlockDelimiters = 1    /* ZSTD_Sequence[] contains explicit block delimiters */
 } ZSTD_SequenceFormat_e;
 

ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize);
diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 4fcf32cfa..28ab04703 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -6624,7 +6624,7 @@ static U32 ZSTD_finalizeOffBase(U32 rawOffset, const U32 rep[ZSTD_REP_NUM], U32
  * storing the sequences it reads, until it reaches a block delimiter.
  * Note that the block delimiter includes the last literals of the block.
  * @blockSize must be == sum(sequence_lengths).
- * @returns 0 on success, and a ZSTD_error otherwise.
+ * @returns @blockSize on success, and a ZSTD_error otherwise.
  */
 static size_t
 ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
@@ -6711,21 +6711,19 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx,
     }
     RETURN_ERROR_IF(ip != iend, externalSequences_invalid, "Blocksize doesn't agree with block delimiter!");
     seqPos->idx = idx+1;
-    return 0;
+    return blockSize;
 }
 
 /*
- * This function attempts to scan through blockSize bytes
+ * This function attempts to scan through @blockSize bytes in @src
  * represented by the sequences in @inSeqs,
  * storing any (partial) sequences.
  *
- * @returns the number of bytes to move the current read position back by.
- * Only non-zero if we ended up splitting a sequence.
- * Otherwise, it may return a ZSTD error if something went wrong.
+ * Occasionally, we may want to reduce the actual number of bytes consumed from @src
+ * to avoid splitting a match, notably if it would produce a match smaller than MINMATCH.
  *
- * Occasionally, we may want to change the actual number of bytes we consumed from inSeqs to
- * avoid splitting a match, or to avoid splitting a match such that it would produce a match
- * smaller than MINMATCH. In this case, we return the number of bytes that we didn't read from this block.
+ * @returns the number of bytes consumed from @src, necessarily <= @blockSize.
+ * Otherwise, it may return a ZSTD error if something went wrong.
  */
 static size_t
 ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
@@ -6738,8 +6736,9 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
     U32 startPosInSequence = seqPos->posInSequence;
     U32 endPosInSequence = seqPos->posInSequence + (U32)blockSize;
     size_t dictSize;
-    BYTE const* ip = (BYTE const*)(src);
-    BYTE const* iend = ip + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
+    const BYTE* const istart = (const BYTE*)(src);
+    const BYTE* ip = istart;
+    const BYTE* iend = istart + blockSize;  /* May be adjusted if we decide to process fewer than blockSize bytes */
     Repcodes_t updatedRepcodes;
     U32 bytesAdjustment = 0;
     U32 finalMatchSplit = 0;
@@ -6842,21 +6841,20 @@ ZSTD_transferSequences_noDelim(ZSTD_CCtx* cctx,
     iend -= bytesAdjustment;
     if (ip != iend) {
         /* Store any last literals */
-        U32 lastLLSize = (U32)(iend - ip);
+        U32 const lastLLSize = (U32)(iend - ip);
         assert(ip <= iend);
         DEBUGLOG(6, "Storing last literals of size: %u", lastLLSize);
         ZSTD_storeLastLiterals(&cctx->seqStore, ip, lastLLSize);
         seqPos->posInSrc += lastLLSize;
     }
 
-    return bytesAdjustment;
+    return (size_t)(iend-istart);
 }
 
 /* @seqPos represents a position within @inSeqs,
  * it is read and updated by this function,
  * once the goal to produce a block of size @blockSize is reached.
- * @return: nb of bytes missing to reach @blockSize goal.
- * so (@blockSize - @return) represents the nb of bytes ingested from @src.
+ * @return: nb of bytes consumed from @src, necessarily <= @blockSize.
  */
 typedef size_t (*ZSTD_SequenceCopier_f)(ZSTD_CCtx* cctx,
                                         ZSTD_SequencePosition* seqPos,
@@ -6963,10 +6961,11 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
         assert(blockSize <= remaining);
         ZSTD_resetSeqStore(&cctx->seqStore);
 
-        {   size_t adjust = sequenceCopier(cctx, &seqPos, inSeqs, inSeqsSize, ip, blockSize, cctx->appliedParams.searchForExternalRepcodes);
-            FORWARD_IF_ERROR(adjust, "Bad sequence copy");
-            blockSize -= adjust;
-        }
+        blockSize = sequenceCopier(cctx,
+                                   &seqPos, inSeqs, inSeqsSize,
+                                   ip, blockSize,
+                                   cctx->appliedParams.searchForExternalRepcodes);
+        FORWARD_IF_ERROR(blockSize, "Bad sequence copy");
 
         /* If blocks are too small, emit as a nocompress block */
         /* TODO: See 3090. We reduced MIN_CBLOCK_SIZE from 3 to 2 so to compensate we are adding
@@ -7054,13 +7053,13 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
 {
     BYTE* op = (BYTE*)dst;
     size_t cSize = 0;
-    size_t compressedBlocksSize = 0;
     size_t frameHeaderSize = 0;
 
     /* Transparent initialization stage, same as compressStream2() */
     DEBUGLOG(4, "ZSTD_compressSequences (dstCapacity=%zu)", dstCapacity);
     assert(cctx != NULL);
     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
+
     /* Begin writing output, starting with frame header */
     frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID);
     op += frameHeaderSize;
@@ -7069,14 +7068,16 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
     if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
         XXH64_update(&cctx->xxhState, src, srcSize);
     }
-    /* cSize includes block header size and compressed sequences size */
-    compressedBlocksSize = ZSTD_compressSequences_internal(cctx,
+
+    {   size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,
                                                            op, dstCapacity,
                                                            inSeqs, inSeqsSize,
                                                            src, srcSize);
-    FORWARD_IF_ERROR(compressedBlocksSize, "Compressing blocks failed!");
-    cSize += compressedBlocksSize;
-    dstCapacity -= compressedBlocksSize;
+        FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!");
+        cSize += cBlocksSize;
+        assert(cBlocksSize <= dstCapacity);
+        dstCapacity -= cBlocksSize;
+    }
 
     if (cctx->appliedParams.fParams.checksumFlag) {
         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
diff --git a/lib/zstd.h b/lib/zstd.h
index 978f8cebd..0318e6f9a 100644
--- a/lib/zstd.h
+++ b/lib/zstd.h
@@ -1561,8 +1561,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_decompressionMargin(const void* src, size_t srcSi
     ))
 
 typedef enum {
-  ZSTD_sf_noBlockDelimiters = 0,         /* Representation of ZSTD_Sequence has no block delimiters, sequences only */
-  ZSTD_sf_explicitBlockDelimiters = 1    /* Representation of ZSTD_Sequence contains explicit block delimiters */
+  ZSTD_sf_noBlockDelimiters = 0,         /* ZSTD_Sequence[] has no block delimiters, just sequences */
+  ZSTD_sf_explicitBlockDelimiters = 1    /* ZSTD_Sequence[] contains explicit block delimiters */
 } ZSTD_SequenceFormat_e;
 #define ZSTD_sequenceFormat_e ZSTD_SequenceFormat_e /* old name */
 

From bcb15091aa7edc7d945a002d2d947577d999d7ea Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Tue, 10 Dec 2024 18:24:18 -0800
Subject: [PATCH 514/937] minor: more accurate variable scope

---
 lib/compress/zstd_compress.c | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c
index 28ab04703..9675c75c0 100644
--- a/lib/compress/zstd_compress.c
+++ b/lib/compress/zstd_compress.c
@@ -6935,7 +6935,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
     size_t remaining = srcSize;
     ZSTD_SequencePosition seqPos = {0, 0, 0};
 
-    BYTE const* ip = (BYTE const*)src;
+    const BYTE* ip = (BYTE const*)src;
     BYTE* op = (BYTE*)dst;
     ZSTD_SequenceCopier_f const sequenceCopier = ZSTD_selectSequenceCopier(cctx->appliedParams.blockDelimiters);
 
@@ -6998,7 +6998,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx,
         if (!cctx->isFirstBlock &&
             ZSTD_maybeRLE(&cctx->seqStore) &&
             ZSTD_isRLE(ip, blockSize)) {
-            /* We don't want to emit our first block as RLE even if it qualifies because
+            /* Note: don't emit the first block as RLE even if it qualifies because
              * doing so will cause the decoder (cli <= v1.4.3 only) to throw an (invalid) error
              * "should consume all input error."
              */
@@ -7053,7 +7053,6 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
 {
     BYTE* op = (BYTE*)dst;
     size_t cSize = 0;
-    size_t frameHeaderSize = 0;
 
     /* Transparent initialization stage, same as compressStream2() */
     DEBUGLOG(4, "ZSTD_compressSequences (dstCapacity=%zu)", dstCapacity);
@@ -7061,14 +7060,18 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
     FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed");
 
     /* Begin writing output, starting with frame header */
-    frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, &cctx->appliedParams, srcSize, cctx->dictID);
-    op += frameHeaderSize;
-    dstCapacity -= frameHeaderSize;
-    cSize += frameHeaderSize;
+    {   size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity,
+                    &cctx->appliedParams, srcSize, cctx->dictID);
+        op += frameHeaderSize;
+        assert(frameHeaderSize <= dstCapacity);
+        dstCapacity -= frameHeaderSize;
+        cSize += frameHeaderSize;
+    }
     if (cctx->appliedParams.fParams.checksumFlag && srcSize) {
         XXH64_update(&cctx->xxhState, src, srcSize);
     }
 
+    /* Now generate compressed blocks */
     {   size_t const cBlocksSize = ZSTD_compressSequences_internal(cctx,
                                                            op, dstCapacity,
                                                            inSeqs, inSeqsSize,
@@ -7079,6 +7082,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx,
         dstCapacity -= cBlocksSize;
     }
 
+    /* Complete with frame checksum, if needed */
     if (cctx->appliedParams.fParams.checksumFlag) {
         U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
         RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "no room for checksum");

From 14a21e43b31042b8cd67d4a757920735a8d33d94 Mon Sep 17 00:00:00 2001
From: Yann Collet 
Date: Wed, 11 Dec 2024 14:31:09 -0800
Subject: [PATCH 515/937] produced ZSTD_compressSequencesAndLiterals() as a
 separate pipeline

only supports explicit delimiter mode, at least for the time being
---
 doc/zstd_manual.html         |  10 +-
 lib/compress/zstd_compress.c | 242 ++++++++++++++++++++++++++++++++++-
 lib/zstd.h                   |  10 +-
 3 files changed, 254 insertions(+), 8 deletions(-)

diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html
index 10546e938..eed24a7a1 100644
--- a/doc/zstd_manual.html
+++ b/doc/zstd_manual.html
@@ -1415,14 +1415,18 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx,
 ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
                       void* dst, size_t dstCapacity,
                 const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
-                const void* literals, size_t litSize);
+                const void* literals, size_t litSize, size_t srcSize);
 

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), aka all literals already extracted and laid out into a single continuous buffer. This can be useful if the process generating the sequences also happens to generate the buffer of literals, thus skipping an extraction + caching stage. - To be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. - Important: Employing this prototype is incompatible with frame checksum. + It's essentially a speed optimization when the right conditions are met, + but it also includes so following limitations: + - Only supports explicit delimiter mode + - Not compatible with frame checksum, which must disabled + - Can fail when unable to compress sufficiently + Also, to be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. @return : final compressed size, or a ZSTD error code.


diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9675c75c0..d7ee68060 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -14,6 +14,7 @@ #include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */ #include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */ #include "../common/mem.h" +#include "../common/error_private.h" #include "hist.h" /* HIST_countFast_wksp */ #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */ #include "../common/fse.h" @@ -4685,8 +4686,10 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity, - const ZSTD_CCtx_params* params, U64 pledgedSrcSize, U32 dictID) -{ BYTE* const op = (BYTE*)dst; + const ZSTD_CCtx_params* params, + U64 pledgedSrcSize, U32 dictID) +{ + BYTE* const op = (BYTE*)dst; U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */ U32 const dictIDSizeCode = params->fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */ U32 const checksumFlag = params->fParams.checksumFlag>0; @@ -7095,6 +7098,241 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, return cSize; } +/* + * seqPos must end on an explicit block delimiter + * @blockSize must be exactly correct. + */ +static size_t +ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + size_t blockSize, + ZSTD_ParamSwitch_e externalRepSearch) +{ + U32 idx = seqPos->idx; + U32 const startIdx = idx; + Repcodes_t updatedRepcodes; + U32 dictSize; + size_t startPosInSrc = seqPos->posInSrc; + + DEBUGLOG(5, "ZSTD_transferSequencesOnly_wBlockDelim (blockSize = %zu)", blockSize); + + if (cctx->cdict) { + dictSize = (U32)cctx->cdict->dictContentSize; + } else if (cctx->prefixDict.dict) { + dictSize = (U32)cctx->prefixDict.dictSize; + } else { + dictSize = 0; + } + ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t)); + for (; idx < nbSequences && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) { + U32 const litLength = inSeqs[idx].litLength; + U32 const matchLength = inSeqs[idx].matchLength; + U32 offBase; + + if (externalRepSearch == ZSTD_ps_disable) { + offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset); + } else { + U32 const ll0 = (litLength == 0); + offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0); + ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); + } + + DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); + seqPos->posInSrc += litLength + matchLength; + if (cctx->appliedParams.validateSequences) { + FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, + seqPos->posInSrc, + cctx->appliedParams.cParams.windowLog, dictSize, + ZSTD_hasExtSeqProd(&cctx->appliedParams)), + "Sequence validation failed"); + } + RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid, + "Not enough memory allocated. Try adjusting ZSTD_c_minMatch."); + ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); + } + + /* last sequence (only literals) */ + seqPos->posInSrc += inSeqs[idx].litLength; + + /* blockSize must be exactly correct (checked before calling this function) */ + assert((seqPos->posInSrc - startPosInSrc) == blockSize); (void)startPosInSrc; + + /* If we skipped repcode search while parsing, we need to update repcodes now */ + assert(externalRepSearch != ZSTD_ps_auto); + assert(idx >= startIdx); + if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) { + U32* const rep = updatedRepcodes.rep; + U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */ + + if (lastSeqIdx >= startIdx + 2) { + rep[2] = inSeqs[lastSeqIdx - 2].offset; + rep[1] = inSeqs[lastSeqIdx - 1].offset; + rep[0] = inSeqs[lastSeqIdx].offset; + } else if (lastSeqIdx == startIdx + 1) { + rep[2] = rep[0]; + rep[1] = inSeqs[lastSeqIdx - 1].offset; + rep[0] = inSeqs[lastSeqIdx].offset; + } else { + assert(lastSeqIdx == startIdx); + rep[2] = rep[1]; + rep[1] = rep[0]; + rep[0] = inSeqs[lastSeqIdx].offset; + } + } + + ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); + + seqPos->idx = idx+1; + return blockSize; +} + +static size_t +ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t nbSequences, + const void* literals, size_t litSize, size_t srcSize) +{ + size_t cSize = 0; + size_t remaining = srcSize; + ZSTD_SequencePosition seqPos = {0, 0, 0}; + BYTE* op = (BYTE*)dst; + + DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); + if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { + RETURN_ERROR(GENERIC, "This mode is only compatible with explicit delimiters"); + } + + /* Special case: empty frame */ + if (remaining == 0) { + U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1); + RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header"); + MEM_writeLE32(op, cBlockHeader24); + op += ZSTD_blockHeaderSize; + dstCapacity -= ZSTD_blockHeaderSize; + cSize += ZSTD_blockHeaderSize; + } + + while (remaining) { + size_t compressedSeqsSize; + size_t cBlockSize; + size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters, + cctx->blockSize, remaining, + inSeqs, nbSequences, seqPos); + U32 const lastBlock = (blockSize == remaining); + FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); + assert(blockSize <= remaining); + ZSTD_resetSeqStore(&cctx->seqStore); + + blockSize = ZSTD_transferSequencesOnly_wBlockDelim(cctx, + &seqPos, + inSeqs, nbSequences, + blockSize, + cctx->appliedParams.searchForExternalRepcodes); + FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); + + /* Note: when blockSize is very small, other variant send it uncompressed. + * Here, we still send the sequences, because we don't have the source to send it uncompressed. + * In theory, it would be possible to reproduce the source from the sequences, + * but that's pretty complex and memory intensive, which goes against the principles of this variant. */ + + RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); + compressedSeqsSize = ZSTD_entropyCompressSeqStore_wExtLitBuffer( + op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, + literals, litSize, + blockSize, + &cctx->seqStore, + &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, + &cctx->appliedParams, + cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, + cctx->bmi2); + FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); + DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); + + /* Note: difficult to check source for RLE block when only Literals are provided, + * but it could be considered from analyzing the sequence directly */ + + if (compressedSeqsSize == 0) { + /* Sending uncompressed blocks is difficult, because we don't have the source. + * In theory, we could use the sequences to regenerate the source, like a decompressor, + * but it's complex and likely overkill. + * Current outcome: generate an error code. + */ + RETURN_ERROR(dstSize_tooSmall, "Data is not compressible"); /* note: error code might be misleading */ + } else { + U32 cBlockHeader; + assert(compressedSeqsSize > 1); /* no RLE */ + /* Error checking and repcodes update */ + ZSTD_blockState_confirmRepcodesAndEntropyTables(&cctx->blockState); + if (cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid) + cctx->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check; + + /* Write block header into beginning of block*/ + cBlockHeader = lastBlock + (((U32)bt_compressed)<<1) + (U32)(compressedSeqsSize << 3); + MEM_writeLE24(op, cBlockHeader); + cBlockSize = ZSTD_blockHeaderSize + compressedSeqsSize; + DEBUGLOG(5, "Writing out compressed block, size: %zu", cBlockSize); + } + + cSize += cBlockSize; + + if (lastBlock) { + break; + } else { + op += cBlockSize; + remaining -= blockSize; + dstCapacity -= cBlockSize; + cctx->isFirstBlock = 0; + } + DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity); + } + + DEBUGLOG(4, "cSize final total: %zu", cSize); + return cSize; +} + +size_t +ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, + void* dst, size_t dstCapacity, + const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const void* literals, size_t litSize, size_t srcSize) +{ + BYTE* op = (BYTE*)dst; + size_t cSize = 0; + + /* Transparent initialization stage, same as compressStream2() */ + DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); + assert(cctx != NULL); + FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed"); + + if (cctx->appliedParams.fParams.checksumFlag) { + RETURN_ERROR(frameParameter_unsupported, "this mode is incompatible with frame checksum"); + } + + /* Begin writing output, starting with frame header */ + { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, + &cctx->appliedParams, srcSize, cctx->dictID); + op += frameHeaderSize; + assert(frameHeaderSize <= dstCapacity); + dstCapacity -= frameHeaderSize; + cSize += frameHeaderSize; + } + + /* Now generate compressed blocks */ + { size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx, + op, dstCapacity, + inSeqs, inSeqsSize, + literals, litSize, srcSize); + FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!"); + cSize += cBlocksSize; + assert(cBlocksSize <= dstCapacity); + dstCapacity -= cBlocksSize; + } + + DEBUGLOG(4, "Final compressed size: %zu", cSize); + return cSize; +} + /*====== Finalize ======*/ static ZSTD_inBuffer inBuffer_forEndFlush(const ZSTD_CStream* zcs) diff --git a/lib/zstd.h b/lib/zstd.h index 0318e6f9a..67cb4d987 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1665,15 +1665,19 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * aka all literals already extracted and laid out into a single continuous buffer. * This can be useful if the process generating the sequences also happens to generate the buffer of literals, * thus skipping an extraction + caching stage. - * To be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. - * Important: Employing this prototype is incompatible with frame checksum. + * It's essentially a speed optimization when the right conditions are met, + * but it also is restricted by the following limitations: + * - Only supports explicit delimiter mode + * - Not compatible with frame checksum, which must disabled + * - Can fail when unable to compress sufficiently + * Also, to be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* literals, size_t litSize); + const void* literals, size_t litSize, size_t srcSize); /*! ZSTD_writeSkippableFrame() : From 0b013b26884bb25149eedc6d78a5d8f5dc38739a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 11 Dec 2024 16:13:22 -0800 Subject: [PATCH 516/937] added unit tests to ZSTD_compressSequencesAndLiterals() seems to work as expected, correctly control that `litSize` and `srcSize` are exactly correct. --- doc/zstd_manual.html | 2 +- lib/compress/zstd_compress.c | 19 +++++-- lib/zstd.h | 7 ++- tests/fuzzer.c | 105 ++++++++++++++++++++++++++++++++++- 4 files changed, 122 insertions(+), 11 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index eed24a7a1..7cfeda22d 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1422,7 +1422,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, This can be useful if the process generating the sequences also happens to generate the buffer of literals, thus skipping an extraction + caching stage. It's essentially a speed optimization when the right conditions are met, - but it also includes so following limitations: + but it also is restricted by the following limitations: - Only supports explicit delimiter mode - Not compatible with frame checksum, which must disabled - Can fail when unable to compress sufficiently diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d7ee68060..bb92bd1ff 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7104,7 +7104,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, */ static size_t ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, + ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, ZSTD_ParamSwitch_e externalRepSearch) @@ -7114,6 +7114,7 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, Repcodes_t updatedRepcodes; U32 dictSize; size_t startPosInSrc = seqPos->posInSrc; + size_t litConsumed = 0; DEBUGLOG(5, "ZSTD_transferSequencesOnly_wBlockDelim (blockSize = %zu)", blockSize); @@ -7150,10 +7151,15 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid, "Not enough memory allocated. Try adjusting ZSTD_c_minMatch."); ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); + litConsumed += litLength; } /* last sequence (only literals) */ - seqPos->posInSrc += inSeqs[idx].litLength; + { size_t const lastLitLength = inSeqs[idx].litLength; + seqPos->posInSrc += lastLitLength; + cctx->seqStore.lit += lastLitLength; /* register proper length */ + litConsumed += lastLitLength; + } /* blockSize must be exactly correct (checked before calling this function) */ assert((seqPos->posInSrc - startPosInSrc) == blockSize); (void)startPosInSrc; @@ -7184,6 +7190,7 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); seqPos->idx = idx+1; + *litConsumedPtr = litConsumed; return blockSize; } @@ -7214,21 +7221,23 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, } while (remaining) { - size_t compressedSeqsSize; - size_t cBlockSize; + size_t compressedSeqsSize, cBlockSize, litConsumed; size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters, cctx->blockSize, remaining, inSeqs, nbSequences, seqPos); U32 const lastBlock = (blockSize == remaining); FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); + RETURN_ERROR_IF(!lastBlock, GENERIC, "Only supports single block"); assert(blockSize <= remaining); ZSTD_resetSeqStore(&cctx->seqStore); blockSize = ZSTD_transferSequencesOnly_wBlockDelim(cctx, - &seqPos, + &seqPos, &litConsumed, inSeqs, nbSequences, blockSize, cctx->appliedParams.searchForExternalRepcodes); + RETURN_ERROR_IF(blockSize != remaining, GENERIC, "Must consume the entire block"); + RETURN_ERROR_IF(litConsumed != litSize, GENERIC, "Must consume the exact amount of literals provided"); FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); /* Note: when blockSize is very small, other variant send it uncompressed. diff --git a/lib/zstd.h b/lib/zstd.h index 67cb4d987..3c0e836c9 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1666,17 +1666,18 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * This can be useful if the process generating the sequences also happens to generate the buffer of literals, * thus skipping an extraction + caching stage. * It's essentially a speed optimization when the right conditions are met, - * but it also is restricted by the following limitations: + * but it also features the following limitations: * - Only supports explicit delimiter mode + * - Supports 1 block only (max input 128 KB) * - Not compatible with frame checksum, which must disabled - * - Can fail when unable to compress sufficiently + * - Can fail (return an error) when input data cannot be compress sufficiently * Also, to be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, - const ZSTD_Sequence* inSeqs, size_t inSeqsSize, + const ZSTD_Sequence* inSeqs, size_t nbSequences, const void* literals, size_t litSize, size_t srcSize); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 2180d1edb..3063ec2d1 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -40,7 +40,6 @@ #include "datagen.h" /* RDG_genBuffer */ #define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */ #include "xxhash.h" /* XXH64 */ -#include "util.h" #include "timefn.h" /* SEC_TO_MICRO, UTIL_time_t, UTIL_TIME_INITIALIZER, UTIL_clockSpanMicro, UTIL_getTime */ /* must be included after util.h, due to ERROR macro redefinition issue on Visual Studio */ #include "zstd_internal.h" /* ZSTD_WORKSPACETOOLARGE_MAXDURATION, ZSTD_WORKSPACETOOLARGE_FACTOR, KB, MB */ @@ -339,6 +338,35 @@ static void FUZ_decodeSequences(BYTE* dst, ZSTD_Sequence* seqs, size_t seqsSize, } } +static size_t FUZ_getLitSize(const ZSTD_Sequence* seqs, size_t nbSeqs) +{ + size_t n, litSize = 0; + assert(seqs != NULL); + for (n=0; n Date: Thu, 12 Dec 2024 17:29:11 -0800 Subject: [PATCH 517/937] prepare fullbench for a refactor --- tests/Makefile | 3 +- tests/fullbench.c | 271 ++++++++++++++++++++++++++++++++-------------- 2 files changed, 190 insertions(+), 84 deletions(-) diff --git a/tests/Makefile b/tests/Makefile index 5c0607d10..74e05774c 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -148,6 +148,7 @@ fullbench32: CPPFLAGS += -m32 $(FULLBENCHS) : CPPFLAGS += $(MULTITHREAD_CPP) -Wno-deprecated-declarations $(FULLBENCHS) : LDFLAGS += $(MULTITHREAD_LD) $(FULLBENCHS) : DEBUGFLAGS = -DNDEBUG # turn off assert() for speed measurements +$(FULLBENCHS) : DEBUGLEVEL = 0 # turn off assert() for speed measurements $(FULLBENCHS) : $(ZSTD_FILES) $(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c fullbench.c $(LINK.c) $^ -o $@$(EXT) @@ -271,7 +272,7 @@ clean: #---------------------------------------------------------------------------------- # valgrind tests validated only for some posix platforms #---------------------------------------------------------------------------------- -UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') +UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS AIX CYGWIN_NT%,$(UNAME))) HOST_OS = POSIX diff --git a/tests/fullbench.c b/tests/fullbench.c index 250359e92..abc0a881d 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -18,7 +18,6 @@ #include /* fprintf, fopen, ftello64 */ #include -#include "timefn.h" /* UTIL_clockSpanNano, UTIL_getTime */ #include "mem.h" /* U32 */ #ifndef ZSTD_DLL_IMPORT #include "zstd_internal.h" /* ZSTD_decodeSeqHeaders, ZSTD_blockHeaderSize, ZSTD_getcBlockSize, blockType_e, KB, MB */ @@ -36,7 +35,6 @@ #include "benchfn.h" /* CustomBench */ #include "benchzstd.h" /* MB_UNIT */ - /*_************************************ * Constants **************************************/ @@ -64,6 +62,7 @@ static const size_t kSampleSizeDefault = 10000000; #define CONTROL(c) { if (!(c)) { abort(); } } /* like assert(), but cannot be disabled */ + /*_************************************ * Benchmark Parameters **************************************/ @@ -97,7 +96,6 @@ static size_t BMK_findMaxMem(U64 requiredMem) *********************************************************/ static ZSTD_CCtx* g_zcc = NULL; - static size_t local_ZSTD_compress(const void* src, size_t srcSize, void* dst, size_t dstSize, @@ -129,40 +127,73 @@ local_ZSTD_compress_freshCCtx(const void* src, size_t srcSize, } } -static size_t g_cSize = 0; +typedef struct { + size_t prepSize; + size_t fixedOrigSize; +} PrepResult; + +static PrepResult prepDecompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +{ + size_t cSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); + PrepResult r; + r.prepSize = cSize; + r.fixedOrigSize = srcSize; + return r; +} + static size_t local_ZSTD_decompress(const void* src, size_t srcSize, void* dst, size_t dstSize, - void* buff2) + void* unused) { - (void)src; (void)srcSize; - return ZSTD_decompress(dst, dstSize, buff2, g_cSize); + (void)unused; + return ZSTD_decompress(dst, dstSize, src, srcSize); } static ZSTD_DCtx* g_zdc = NULL; /* will be initialized within benchMem */ static size_t local_ZSTD_decompressDCtx(const void* src, size_t srcSize, void* dst, size_t dstSize, - void* buff2) + void* unused) { - (void)src; (void)srcSize; - return ZSTD_decompressDCtx(g_zdc, dst, dstSize, buff2, g_cSize); + (void)unused; + return ZSTD_decompressDCtx(g_zdc, dst, dstSize, src, srcSize); } #ifndef ZSTD_DLL_IMPORT +static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +{ + size_t frameHeaderSize; + size_t prepSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); + frameHeaderSize = ZSTD_frameHeaderSize(dst, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); + CONTROL(!ZSTD_isError(frameHeaderSize)); + /* check block is compressible, hence contains a literals section */ + { blockProperties_t bp; + ZSTD_getcBlockSize((char*)dst+frameHeaderSize, dstCapacity, &bp); /* Get 1st block type */ + if (bp.blockType != bt_compressed) { + const PrepResult r = {0,0}; + DISPLAY("no compressed literals\n"); + return r; + } } + { size_t const skippedSize = frameHeaderSize + ZSTD_blockHeaderSize; + prepSize -= skippedSize; + memmove(dst, (char*)dst+skippedSize, prepSize); + } + ZSTD_decompressBegin(g_zdc); + { PrepResult r; + r.prepSize = prepSize; + r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + return r; + } +} + extern size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, const void* src, size_t srcSize, void* dst, size_t dstCapacity); -static size_t local_ZSTD_decodeLiteralsBlock(const void* src, size_t srcSize, void* dst, size_t dstSize, void* buff2) +static size_t +local_ZSTD_decodeLiteralsBlock(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* unused) { - (void)src; (void)srcSize; (void)dst; (void)dstSize; - return ZSTD_decodeLiteralsBlock_wrapper(g_zdc, buff2, g_cSize, dst, dstSize); -} - -static size_t local_ZSTD_decodeSeqHeaders(const void* src, size_t srcSize, void* dst, size_t dstSize, void* buff2) -{ - int nbSeq; - (void)src; (void)srcSize; (void)dst; (void)dstSize; - return ZSTD_decodeSeqHeaders(g_zdc, &nbSeq, buff2, g_cSize); + (void)unused; + return ZSTD_decodeLiteralsBlock_wrapper(g_zdc, src, srcSize, dst, dstCapacity); } FORCE_NOINLINE size_t ZSTD_decodeLiteralsHeader(ZSTD_DCtx* dctx, void const* src, size_t srcSize) @@ -219,11 +250,55 @@ FORCE_NOINLINE size_t ZSTD_decodeLiteralsHeader(ZSTD_DCtx* dctx, void const* src return 0; } -static size_t local_ZSTD_decodeLiteralsHeader(const void* src, size_t srcSize, void* dst, size_t dstSize, void* buff2) +static size_t +local_ZSTD_decodeLiteralsHeader(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* unused) { - (void)dst, (void)dstSize, (void)src, (void)srcSize; - return ZSTD_decodeLiteralsHeader(g_zdc, buff2, g_cSize); + (void)dst; (void)dstCapacity; (void)unused; + return ZSTD_decodeLiteralsHeader(g_zdc, src, srcSize); } + +static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +{ + const BYTE* ip = dst; + const BYTE* iend; + { size_t const cSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); + CONTROL(cSize > ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); + } + /* Skip frame Header */ + { size_t const frameHeaderSize = ZSTD_frameHeaderSize(dst, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); + CONTROL(!ZSTD_isError(frameHeaderSize)); + ip += frameHeaderSize; + } + /* Find end of block */ + { blockProperties_t bp; + size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstCapacity, &bp); /* Get 1st block type */ + if (bp.blockType != bt_compressed) { + const PrepResult r = {0,0}; + DISPLAY("No compressed sequences\n"); + return r; + } + iend = ip + ZSTD_blockHeaderSize + cBlockSize; /* End of first block */ + } + ip += ZSTD_blockHeaderSize; /* skip block header */ + ZSTD_decompressBegin(g_zdc); + CONTROL(iend > ip); + ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dst, dstCapacity); /* skip literal segment */ + { PrepResult r; + r.prepSize = (size_t)(iend-ip); + r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + memmove(dst, ip, r.prepSize); /* copy rest of block (it starts by SeqHeader) */ + return r; + } +} + +static size_t +local_ZSTD_decodeSeqHeaders(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* unused) +{ + int nbSeq; + (void)unused; (void)dst; (void)dstCapacity; + return ZSTD_decodeSeqHeaders(g_zdc, &nbSeq, src, srcSize); +} + #endif static ZSTD_CStream* g_cstream= NULL; @@ -346,17 +421,17 @@ static ZSTD_DStream* g_dstream= NULL; static size_t local_ZSTD_decompressStream(const void* src, size_t srcSize, void* dst, size_t dstCapacity, - void* buff2) + void* unused) { ZSTD_outBuffer buffOut; ZSTD_inBuffer buffIn; - (void)src; (void)srcSize; + (void)unused; ZSTD_initDStream(g_dstream); buffOut.dst = dst; buffOut.size = dstCapacity; buffOut.pos = 0; - buffIn.src = buff2; - buffIn.size = g_cSize; + buffIn.src = src; + buffIn.size = srcSize; buffIn.pos = 0; ZSTD_decompressStream(g_dstream, &buffOut, &buffIn); return buffOut.pos; @@ -408,15 +483,15 @@ local_ZSTD_compressContinue_extDict(const void* src, size_t srcSize, static size_t local_ZSTD_decompressContinue(const void* src, size_t srcSize, void* dst, size_t dstCapacity, - void* buff2) + void* unused) { size_t regeneratedSize = 0; - const BYTE* ip = (const BYTE*)buff2; - const BYTE* const iend = ip + g_cSize; + const BYTE* ip = (const BYTE*)src; + const BYTE* const iend = ip + srcSize; BYTE* op = (BYTE*)dst; size_t remainingCapacity = dstCapacity; - (void)src; (void)srcSize; /* unused */ + (void)unused; ZSTD_decompressBegin(g_zdc); while (ip < iend) { size_t const iSize = ZSTD_nextSrcSizeToDecompress(g_zdc); @@ -431,17 +506,61 @@ static size_t local_ZSTD_decompressContinue(const void* src, size_t srcSize, } #endif +static PrepResult prepCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +{ + const PrepResult r = { srcSize, srcSize}; + (void)cLevel; + assert(dstCapacity >= srcSize); + memcpy(dst, src, srcSize); + return r; +} + +/* if PrepFunction_f returns 0, benchmarking is cancelled */ +typedef PrepResult (*PrepFunction_f)(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel); +typedef size_t (*BenchedFunction_f)(const void* src, size_t srcSize, void* dst, size_t dstSize, void* opaque); + +typedef struct { + const char* name; + PrepFunction_f preparation_f; + BenchedFunction_f benchedFunction; +} BenchScenario; + +static BenchScenario kScenarios[] = { + { "compress", NULL, local_ZSTD_compress }, + { "decompress", prepDecompress, local_ZSTD_decompress }, + { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx }, + { "decompressDCtx", prepDecompress, local_ZSTD_decompressDCtx }, +#ifndef ZSTD_DLL_IMPORT + { "compressContinue", NULL, local_ZSTD_compressContinue }, + { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict }, + { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue }, + { "decodeLiteralsHeader", NULL, local_ZSTD_decodeLiteralsHeader }, + { "decodeLiteralsBlock", NULL, local_ZSTD_decodeLiteralsBlock }, + { "decodeSeqHeaders", NULL, local_ZSTD_decodeSeqHeaders }, +#endif + { "compressStream", NULL, local_ZSTD_compressStream }, + { "decompressStream", prepDecompress, local_ZSTD_decompressStream }, + { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx }, + { "compress2", NULL, local_ZSTD_compress2 }, + { "compressStream2, end", NULL, local_ZSTD_compressStream2_end }, + { "compressStream2, end & short", NULL, local_ZSTD_compressStream2_end }, + { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue }, + { "compress_generic, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, + { "compress_generic, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, +}; +#define NB_SCENARIOS (sizeof(kScenarios) / sizeof(kScenarios[0])) /*_******************************************************* * Bench functions *********************************************************/ static int benchMem(unsigned benchNb, - const void* src, size_t srcSize, + const void* origSrc, size_t origSrcSize, int cLevel, ZSTD_compressionParameters cparams) { - size_t dstBuffSize = ZSTD_compressBound(srcSize); - BYTE* dstBuff; - void* dstBuff2; + size_t dstBuffCapacity = ZSTD_compressBound(origSrcSize); + void* dstBuff; + void* prepBuff; + size_t prepBuffCapacity=dstBuffCapacity, prepBuffSize; void* payload; const char* benchName; BMK_benchFn_t benchFunction; @@ -514,14 +633,14 @@ static int benchMem(unsigned benchNb, } /* Allocation */ - dstBuff = (BYTE*)malloc(dstBuffSize); - dstBuff2 = malloc(dstBuffSize); - if ((!dstBuff) || (!dstBuff2)) { + dstBuff = malloc(dstBuffCapacity); + prepBuff = malloc(prepBuffCapacity); + if ((!dstBuff) || (!prepBuff)) { DISPLAY("\nError: not enough memory!\n"); - free(dstBuff); free(dstBuff2); + free(dstBuff); free(prepBuff); return 12; } - payload = dstBuff2; + memcpy(prepBuff, origSrc, origSrcSize); prepBuffSize = origSrcSize; if (g_zcc==NULL) g_zcc = ZSTD_createCCtx(); if (g_zdc==NULL) g_zdc = ZSTD_createDCtx(); if (g_cstream==NULL) g_cstream = ZSTD_createCStream(); @@ -538,7 +657,7 @@ static int benchMem(unsigned benchNb, ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_searchLog, (int)cparams.searchLog); ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_minMatch, (int)cparams.minMatch); ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_targetLength, (int)cparams.targetLength); - ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_strategy, cparams.strategy); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_strategy, (int)cparams.strategy); ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_compressionLevel, cLevel); ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_windowLog, (int)cparams.windowLog); @@ -547,51 +666,42 @@ static int benchMem(unsigned benchNb, ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_searchLog, (int)cparams.searchLog); ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_minMatch, (int)cparams.minMatch); ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_targetLength, (int)cparams.targetLength); - ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_strategy, cparams.strategy); + ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_strategy, (int)cparams.strategy); + /* Preparation */ + payload = &cparams; switch(benchNb) { - case 1: - payload = &cparams; - break; case 2: - g_cSize = ZSTD_compress(dstBuff2, dstBuffSize, src, srcSize, cLevel); - break; - case 3: - payload = &cparams; + prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); break; case 4: - g_cSize = ZSTD_compress(dstBuff2, dstBuffSize, src, srcSize, cLevel); + prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); break; #ifndef ZSTD_DLL_IMPORT - case 11: - payload = &cparams; - break; - case 12: - payload = &cparams; - break; case 13 : - g_cSize = ZSTD_compress(dstBuff2, dstBuffSize, src, srcSize, cLevel); + prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); break; case 30: /* ZSTD_decodeLiteralsHeader */ /* fall-through */ - case 31: /* ZSTD_decodeLiteralsBlock : starts literals block in dstBuff2 */ + case 31: /* ZSTD_decodeLiteralsBlock : starts literals block in prepBuff */ { size_t frameHeaderSize; - g_cSize = ZSTD_compress(dstBuff, dstBuffSize, src, srcSize, cLevel); + prepBuffSize = ZSTD_compress(dstBuff, dstBuffCapacity, origSrc, origSrcSize, cLevel); frameHeaderSize = ZSTD_frameHeaderSize(dstBuff, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); CONTROL(!ZSTD_isError(frameHeaderSize)); /* check block is compressible, hence contains a literals section */ { blockProperties_t bp; - ZSTD_getcBlockSize(dstBuff+frameHeaderSize, dstBuffSize, &bp); /* Get 1st block type */ + ZSTD_getcBlockSize((char*)dstBuff+frameHeaderSize, dstBuffCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - DISPLAY("ZSTD_decodeLiteralsBlock : impossible to test on this sample (not compressible)\n"); + DISPLAY("no compressed literals\n"); goto _cleanOut; } } { size_t const skippedSize = frameHeaderSize + ZSTD_blockHeaderSize; - memcpy(dstBuff2, dstBuff+skippedSize, g_cSize-skippedSize); + prepBuffSize -= skippedSize; + memcpy(prepBuff, (char*)dstBuff+skippedSize, prepBuffSize); } - srcSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + origSrcSize = origSrcSize > 128 KB ? 128 KB : origSrcSize; /* speed relative to block */ ZSTD_decompressBegin(g_zdc); break; } @@ -599,7 +709,7 @@ static int benchMem(unsigned benchNb, { blockProperties_t bp; const BYTE* ip = dstBuff; const BYTE* iend; - { size_t const cSize = ZSTD_compress(dstBuff, dstBuffSize, src, srcSize, cLevel); + { size_t const cSize = ZSTD_compress(dstBuff, dstBuffCapacity, origSrc, origSrcSize, cLevel); CONTROL(cSize > ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); } /* Skip frame Header */ @@ -608,7 +718,7 @@ static int benchMem(unsigned benchNb, ip += frameHeaderSize; } /* Find end of block */ - { size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstBuffSize, &bp); /* Get 1st block type */ + { size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstBuffCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { DISPLAY("ZSTD_decodeSeqHeaders : impossible to test on this sample (not compressible)\n"); goto _cleanOut; @@ -618,29 +728,23 @@ static int benchMem(unsigned benchNb, ip += ZSTD_blockHeaderSize; /* skip block header */ ZSTD_decompressBegin(g_zdc); CONTROL(iend > ip); - ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dstBuff, dstBuffSize); /* skip literal segment */ - g_cSize = (size_t)(iend-ip); - memcpy(dstBuff2, ip, g_cSize); /* copy rest of block (it starts by SeqHeader) */ - srcSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dstBuff, dstBuffCapacity); /* skip literal segment */ + prepBuffSize = (size_t)(iend-ip); + memcpy(prepBuff, ip, prepBuffSize); /* copy rest of block (it starts by SeqHeader) */ + origSrcSize = origSrcSize > 128 KB ? 128 KB : origSrcSize; /* speed relative to block */ break; } #else case 31: goto _cleanOut; #endif - case 41 : - payload = &cparams; - break; case 42 : - g_cSize = ZSTD_compress(payload, dstBuffSize, src, srcSize, cLevel); - break; - case 43 : - payload = &cparams; + prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); break; case 52 : /* compressStream2, short dstCapacity */ - dstBuffSize--; + dstBuffCapacity--; break; /* test functions */ @@ -650,11 +754,12 @@ static int benchMem(unsigned benchNb, } /* warming up dstBuff */ - { size_t i; for (i=0; i Date: Thu, 12 Dec 2024 17:50:14 -0800 Subject: [PATCH 518/937] refactor fullbench to make it easier to add new scenarios --- tests/fullbench.c | 186 ++++++++-------------------------------------- 1 file changed, 32 insertions(+), 154 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index abc0a881d..7f2e67b38 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -130,6 +130,7 @@ local_ZSTD_compress_freshCCtx(const void* src, size_t srcSize, typedef struct { size_t prepSize; size_t fixedOrigSize; + size_t moddedDstCapacity; /* if ==0, no modification */ } PrepResult; static PrepResult prepDecompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) @@ -138,6 +139,7 @@ static PrepResult prepDecompress(void* dst, size_t dstCapacity, const void* src, PrepResult r; r.prepSize = cSize; r.fixedOrigSize = srcSize; + r.moddedDstCapacity = 0; return r; } @@ -170,7 +172,7 @@ static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, s { blockProperties_t bp; ZSTD_getcBlockSize((char*)dst+frameHeaderSize, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = {0,0}; + const PrepResult r = {0,0, 0}; DISPLAY("no compressed literals\n"); return r; } } @@ -182,6 +184,7 @@ static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, s { PrepResult r; r.prepSize = prepSize; r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + r.moddedDstCapacity = 0; return r; } } @@ -273,8 +276,8 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, { blockProperties_t bp; size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = {0,0}; - DISPLAY("No compressed sequences\n"); + const PrepResult r = {0,0, 0}; + DISPLAY("no compressed sequences\n"); return r; } iend = ip + ZSTD_blockHeaderSize + cBlockSize; /* End of first block */ @@ -286,6 +289,7 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, { PrepResult r; r.prepSize = (size_t)(iend-ip); r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + r.moddedDstCapacity = 0; memmove(dst, ip, r.prepSize); /* copy rest of block (it starts by SeqHeader) */ return r; } @@ -508,7 +512,16 @@ static size_t local_ZSTD_decompressContinue(const void* src, size_t srcSize, static PrepResult prepCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) { - const PrepResult r = { srcSize, srcSize}; + const PrepResult r = { srcSize, srcSize, 0}; + (void)cLevel; + assert(dstCapacity >= srcSize); + memcpy(dst, src, srcSize); + return r; +} + +static PrepResult prepShorterDstCapacity(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +{ + const PrepResult r = { srcSize, srcSize, dstCapacity-1}; (void)cLevel; assert(dstCapacity >= srcSize); memcpy(dst, src, srcSize); @@ -534,16 +547,16 @@ static BenchScenario kScenarios[] = { { "compressContinue", NULL, local_ZSTD_compressContinue }, { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict }, { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue }, - { "decodeLiteralsHeader", NULL, local_ZSTD_decodeLiteralsHeader }, - { "decodeLiteralsBlock", NULL, local_ZSTD_decodeLiteralsBlock }, - { "decodeSeqHeaders", NULL, local_ZSTD_decodeSeqHeaders }, + { "decodeLiteralsHeader", prepLiterals, local_ZSTD_decodeLiteralsHeader }, + { "decodeLiteralsBlock", prepLiterals, local_ZSTD_decodeLiteralsBlock }, + { "decodeSeqHeaders", prepSequences, local_ZSTD_decodeSeqHeaders }, #endif { "compressStream", NULL, local_ZSTD_compressStream }, { "decompressStream", prepDecompress, local_ZSTD_decompressStream }, { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx }, { "compress2", NULL, local_ZSTD_compress2 }, { "compressStream2, end", NULL, local_ZSTD_compressStream2_end }, - { "compressStream2, end & short", NULL, local_ZSTD_compressStream2_end }, + { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end }, { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue }, { "compress_generic, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, { "compress_generic, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, @@ -564,73 +577,15 @@ static int benchMem(unsigned benchNb, void* payload; const char* benchName; BMK_benchFn_t benchFunction; + PrepFunction_f prep_f; int errorcode = 0; - /* Selection */ - switch(benchNb) - { - case 1: - benchFunction = local_ZSTD_compress; benchName = "compress"; - break; - case 2: - benchFunction = local_ZSTD_decompress; benchName = "decompress"; - break; - case 3: - benchFunction = local_ZSTD_compress_freshCCtx; benchName = "compress_freshCCtx"; - break; - case 4: - benchFunction = local_ZSTD_decompressDCtx; benchName = "decompressDCtx"; - break; -#ifndef ZSTD_DLL_IMPORT - case 11: - benchFunction = local_ZSTD_compressContinue; benchName = "compressContinue"; - break; - case 12: - benchFunction = local_ZSTD_compressContinue_extDict; benchName = "compressContinue_extDict"; - break; - case 13: - benchFunction = local_ZSTD_decompressContinue; benchName = "decompressContinue"; - break; - case 30: - benchFunction = local_ZSTD_decodeLiteralsHeader; benchName = "decodeLiteralsHeader"; - break; - case 31: - benchFunction = local_ZSTD_decodeLiteralsBlock; benchName = "decodeLiteralsBlock"; - break; - case 32: - benchFunction = local_ZSTD_decodeSeqHeaders; benchName = "decodeSeqHeaders"; - break; -#endif - case 41: - benchFunction = local_ZSTD_compressStream; benchName = "compressStream"; - break; - case 42: - benchFunction = local_ZSTD_decompressStream; benchName = "decompressStream"; - break; - case 43: - benchFunction = local_ZSTD_compressStream_freshCCtx; benchName = "compressStream_freshCCtx"; - break; - case 50: - benchFunction = local_ZSTD_compress2; benchName = "compress2"; - break; - case 51: - benchFunction = local_ZSTD_compressStream2_end; benchName = "compressStream2, end"; - break; - case 52: - benchFunction = local_ZSTD_compressStream2_end; benchName = "compressStream2, end & short"; - break; - case 53: - benchFunction = local_ZSTD_compressStream2_continue; benchName = "compressStream2, continue"; - break; - case 61: - benchFunction = local_ZSTD_compress_generic_T2_continue; benchName = "compress_generic, -T2, continue"; - break; - case 62: - benchFunction = local_ZSTD_compress_generic_T2_end; benchName = "compress_generic, -T2, end"; - break; - default : - return 0; - } + if (benchNb >= NB_SCENARIOS) return 0; /* scenario doesn't exist */ + + benchName = kScenarios[benchNb].name; + benchFunction = kScenarios[benchNb].benchedFunction; + prep_f = kScenarios[benchNb].preparation_f; + if (prep_f == NULL) prep_f = prepCopy; /* default */ /* Allocation */ dstBuff = malloc(dstBuffCapacity); @@ -640,7 +595,6 @@ static int benchMem(unsigned benchNb, free(dstBuff); free(prepBuff); return 12; } - memcpy(prepBuff, origSrc, origSrcSize); prepBuffSize = origSrcSize; if (g_zcc==NULL) g_zcc = ZSTD_createCCtx(); if (g_zdc==NULL) g_zdc = ZSTD_createDCtx(); if (g_cstream==NULL) g_cstream = ZSTD_createCStream(); @@ -671,87 +625,11 @@ static int benchMem(unsigned benchNb, /* Preparation */ payload = &cparams; - switch(benchNb) - { - case 2: - prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); - break; - case 4: - prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); - break; -#ifndef ZSTD_DLL_IMPORT - case 13 : - prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); - break; - case 30: /* ZSTD_decodeLiteralsHeader */ - /* fall-through */ - case 31: /* ZSTD_decodeLiteralsBlock : starts literals block in prepBuff */ - { size_t frameHeaderSize; - prepBuffSize = ZSTD_compress(dstBuff, dstBuffCapacity, origSrc, origSrcSize, cLevel); - frameHeaderSize = ZSTD_frameHeaderSize(dstBuff, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); - CONTROL(!ZSTD_isError(frameHeaderSize)); - /* check block is compressible, hence contains a literals section */ - { blockProperties_t bp; - ZSTD_getcBlockSize((char*)dstBuff+frameHeaderSize, dstBuffCapacity, &bp); /* Get 1st block type */ - if (bp.blockType != bt_compressed) { - DISPLAY("no compressed literals\n"); - goto _cleanOut; - } } - { size_t const skippedSize = frameHeaderSize + ZSTD_blockHeaderSize; - prepBuffSize -= skippedSize; - memcpy(prepBuff, (char*)dstBuff+skippedSize, prepBuffSize); - } - origSrcSize = origSrcSize > 128 KB ? 128 KB : origSrcSize; /* speed relative to block */ - ZSTD_decompressBegin(g_zdc); - break; - } - case 32: /* ZSTD_decodeSeqHeaders */ - { blockProperties_t bp; - const BYTE* ip = dstBuff; - const BYTE* iend; - { size_t const cSize = ZSTD_compress(dstBuff, dstBuffCapacity, origSrc, origSrcSize, cLevel); - CONTROL(cSize > ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); - } - /* Skip frame Header */ - { size_t const frameHeaderSize = ZSTD_frameHeaderSize(dstBuff, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); - CONTROL(!ZSTD_isError(frameHeaderSize)); - ip += frameHeaderSize; - } - /* Find end of block */ - { size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstBuffCapacity, &bp); /* Get 1st block type */ - if (bp.blockType != bt_compressed) { - DISPLAY("ZSTD_decodeSeqHeaders : impossible to test on this sample (not compressible)\n"); - goto _cleanOut; - } - iend = ip + ZSTD_blockHeaderSize + cBlockSize; /* End of first block */ - } - ip += ZSTD_blockHeaderSize; /* skip block header */ - ZSTD_decompressBegin(g_zdc); - CONTROL(iend > ip); - ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dstBuff, dstBuffCapacity); /* skip literal segment */ - prepBuffSize = (size_t)(iend-ip); - memcpy(prepBuff, ip, prepBuffSize); /* copy rest of block (it starts by SeqHeader) */ - origSrcSize = origSrcSize > 128 KB ? 128 KB : origSrcSize; /* speed relative to block */ - break; - } -#else - case 31: - goto _cleanOut; -#endif - case 42 : - prepBuffSize = ZSTD_compress(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); - break; - - case 52 : - /* compressStream2, short dstCapacity */ - dstBuffCapacity--; - break; - - /* test functions */ - /* convention: test functions have ID > 100 */ - - default : ; + { PrepResult pr = prep_f(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); + prepBuffSize = pr.prepSize; + origSrcSize = pr.fixedOrigSize; } + if (prepBuffSize==0) goto _cleanOut; /* failed preparation */ /* warming up dstBuff */ { size_t i; for (i=0; i Date: Fri, 13 Dec 2024 00:14:24 -0800 Subject: [PATCH 519/937] minor: test reordering --- tests/fullbench.c | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 7f2e67b38..d64258977 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -132,14 +132,14 @@ typedef struct { size_t fixedOrigSize; size_t moddedDstCapacity; /* if ==0, no modification */ } PrepResult; +#define PREPRESULT_INIT { 0,0,0 } static PrepResult prepDecompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) { size_t cSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); - PrepResult r; + PrepResult r = PREPRESULT_INIT; r.prepSize = cSize; r.fixedOrigSize = srcSize; - r.moddedDstCapacity = 0; return r; } @@ -172,7 +172,7 @@ static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, s { blockProperties_t bp; ZSTD_getcBlockSize((char*)dst+frameHeaderSize, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = {0,0, 0}; + const PrepResult r = PREPRESULT_INIT; DISPLAY("no compressed literals\n"); return r; } } @@ -181,10 +181,9 @@ static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, s memmove(dst, (char*)dst+skippedSize, prepSize); } ZSTD_decompressBegin(g_zdc); - { PrepResult r; + { PrepResult r = PREPRESULT_INIT; r.prepSize = prepSize; r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ - r.moddedDstCapacity = 0; return r; } } @@ -276,7 +275,7 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, { blockProperties_t bp; size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = {0,0, 0}; + const PrepResult r = PREPRESULT_INIT; DISPLAY("no compressed sequences\n"); return r; } @@ -286,10 +285,9 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, ZSTD_decompressBegin(g_zdc); CONTROL(iend > ip); ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dst, dstCapacity); /* skip literal segment */ - { PrepResult r; + { PrepResult r = PREPRESULT_INIT; r.prepSize = (size_t)(iend-ip); r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ - r.moddedDstCapacity = 0; memmove(dst, ip, r.prepSize); /* copy rest of block (it starts by SeqHeader) */ return r; } @@ -543,23 +541,23 @@ static BenchScenario kScenarios[] = { { "decompress", prepDecompress, local_ZSTD_decompress }, { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx }, { "decompressDCtx", prepDecompress, local_ZSTD_decompressDCtx }, -#ifndef ZSTD_DLL_IMPORT { "compressContinue", NULL, local_ZSTD_compressContinue }, { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict }, { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue }, - { "decodeLiteralsHeader", prepLiterals, local_ZSTD_decodeLiteralsHeader }, - { "decodeLiteralsBlock", prepLiterals, local_ZSTD_decodeLiteralsBlock }, - { "decodeSeqHeaders", prepSequences, local_ZSTD_decodeSeqHeaders }, -#endif { "compressStream", NULL, local_ZSTD_compressStream }, - { "decompressStream", prepDecompress, local_ZSTD_decompressStream }, { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx }, + { "decompressStream", prepDecompress, local_ZSTD_decompressStream }, { "compress2", NULL, local_ZSTD_compress2 }, { "compressStream2, end", NULL, local_ZSTD_compressStream2_end }, { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end }, { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue }, - { "compress_generic, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, - { "compress_generic, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, + { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, + { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, +#ifndef ZSTD_DLL_IMPORT + { "decodeLiteralsHeader (1st block)", prepLiterals, local_ZSTD_decodeLiteralsHeader }, + { "decodeLiteralsBlock (1st block)", prepLiterals, local_ZSTD_decodeLiteralsBlock }, + { "decodeSeqHeaders (1st block)", prepSequences, local_ZSTD_decodeSeqHeaders }, +#endif }; #define NB_SCENARIOS (sizeof(kScenarios) / sizeof(kScenarios[0])) @@ -622,12 +620,12 @@ static int benchMem(unsigned benchNb, ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_targetLength, (int)cparams.targetLength); ZSTD_CCtx_setParameter(g_cstream, ZSTD_c_strategy, (int)cparams.strategy); - /* Preparation */ payload = &cparams; { PrepResult pr = prep_f(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); prepBuffSize = pr.prepSize; origSrcSize = pr.fixedOrigSize; + if (pr.moddedDstCapacity) dstBuffCapacity = pr.moddedDstCapacity; } if (prepBuffSize==0) goto _cleanOut; /* failed preparation */ @@ -669,7 +667,7 @@ static int benchMem(unsigned benchNb, { BMK_runTime_t const newResult = BMK_extract_runTime(bOutcome); if (newResult.nanoSecPerRun < bestResult.nanoSecPerRun ) bestResult.nanoSecPerRun = newResult.nanoSecPerRun; - DISPLAY("\r%2u#%-29.29s:%8.1f MB/s (%8u) ", + DISPLAY("\r%2u#%-31.31s:%8.1f MB/s (%8u) ", benchNb, benchName, (double)origSrcSize * TIMELOOP_NANOSEC / bestResult.nanoSecPerRun / MB_UNIT, (unsigned)newResult.sumOfReturn ); From 8b7e1b795d50b69f44b5306511116251f60d1dda Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 13 Dec 2024 09:56:41 -0800 Subject: [PATCH 520/937] minor variable renaming --- tests/fullbench.c | 77 +++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index d64258977..3cc53713b 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -519,10 +519,8 @@ static PrepResult prepCopy(void* dst, size_t dstCapacity, const void* src, size_ static PrepResult prepShorterDstCapacity(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) { - const PrepResult r = { srcSize, srcSize, dstCapacity-1}; - (void)cLevel; - assert(dstCapacity >= srcSize); - memcpy(dst, src, srcSize); + PrepResult r = prepCopy(dst, dstCapacity, src, srcSize, cLevel); + r.moddedDstCapacity = dstCapacity - 1; return r; } @@ -564,33 +562,33 @@ static BenchScenario kScenarios[] = { /*_******************************************************* * Bench functions *********************************************************/ -static int benchMem(unsigned benchNb, +static int benchMem(unsigned scenarioID, const void* origSrc, size_t origSrcSize, int cLevel, ZSTD_compressionParameters cparams) { - size_t dstBuffCapacity = ZSTD_compressBound(origSrcSize); - void* dstBuff; + size_t dstCapacity = ZSTD_compressBound(origSrcSize); + void* dst; void* prepBuff; - size_t prepBuffCapacity=dstBuffCapacity, prepBuffSize; + size_t prepBuffCapacity=dstCapacity, prepBuffSize; void* payload; const char* benchName; BMK_benchFn_t benchFunction; PrepFunction_f prep_f; int errorcode = 0; - if (benchNb >= NB_SCENARIOS) return 0; /* scenario doesn't exist */ + if (scenarioID >= NB_SCENARIOS) return 0; /* scenario doesn't exist */ - benchName = kScenarios[benchNb].name; - benchFunction = kScenarios[benchNb].benchedFunction; - prep_f = kScenarios[benchNb].preparation_f; + benchName = kScenarios[scenarioID].name; + benchFunction = kScenarios[scenarioID].benchedFunction; + prep_f = kScenarios[scenarioID].preparation_f; if (prep_f == NULL) prep_f = prepCopy; /* default */ /* Allocation */ - dstBuff = malloc(dstBuffCapacity); + dst = malloc(dstCapacity); prepBuff = malloc(prepBuffCapacity); - if ((!dstBuff) || (!prepBuff)) { + if ((!dst) || (!prepBuff)) { DISPLAY("\nError: not enough memory!\n"); - free(dstBuff); free(prepBuff); + free(dst); free(prepBuff); return 12; } if (g_zcc==NULL) g_zcc = ZSTD_createCCtx(); @@ -625,16 +623,16 @@ static int benchMem(unsigned benchNb, { PrepResult pr = prep_f(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); prepBuffSize = pr.prepSize; origSrcSize = pr.fixedOrigSize; - if (pr.moddedDstCapacity) dstBuffCapacity = pr.moddedDstCapacity; + if (pr.moddedDstCapacity) dstCapacity = pr.moddedDstCapacity; } if (prepBuffSize==0) goto _cleanOut; /* failed preparation */ /* warming up dstBuff */ - { size_t i; for (i=0; i Date: Fri, 13 Dec 2024 16:23:54 -0800 Subject: [PATCH 521/937] fullbench: preparation functions are now in charge of allocating buffers --- tests/fullbench.c | 119 +++++++++++++++++++++++++++------------------- 1 file changed, 70 insertions(+), 49 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 3cc53713b..7218bd6e6 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -128,18 +128,26 @@ local_ZSTD_compress_freshCCtx(const void* src, size_t srcSize, } typedef struct { + void* prepBuffer; size_t prepSize; - size_t fixedOrigSize; - size_t moddedDstCapacity; /* if ==0, no modification */ + void* dst; + size_t dstCapacity; + size_t fixedOrigSize; /* optional, 0 means "no modification" */ } PrepResult; -#define PREPRESULT_INIT { 0,0,0 } +#define PREPRESULT_INIT { NULL, 0, NULL, 0, 0 } -static PrepResult prepDecompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +static PrepResult prepDecompress(const void* src, size_t srcSize, int cLevel) { - size_t cSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); + size_t prepCapacity = ZSTD_compressBound(srcSize); + void* prepBuffer = malloc(prepCapacity); + size_t cSize = ZSTD_compress(prepBuffer, prepCapacity, src, srcSize, cLevel); + void* dst = malloc(srcSize); PrepResult r = PREPRESULT_INIT; + assert(dst != NULL); + r.prepBuffer = prepBuffer; r.prepSize = cSize; - r.fixedOrigSize = srcSize; + r.dst = dst; + r.dstCapacity = srcSize; return r; } @@ -162,30 +170,35 @@ static size_t local_ZSTD_decompressDCtx(const void* src, size_t srcSize, #ifndef ZSTD_DLL_IMPORT -static PrepResult prepLiterals(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +static PrepResult prepLiterals(const void* src, size_t srcSize, int cLevel) { - size_t frameHeaderSize; + PrepResult r = PREPRESULT_INIT; + size_t dstCapacity = srcSize; + void* dst = malloc(dstCapacity); + void* prepBuffer; size_t prepSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); - frameHeaderSize = ZSTD_frameHeaderSize(dst, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); + size_t frameHeaderSize = ZSTD_frameHeaderSize(dst, ZSTD_FRAMEHEADERSIZE_PREFIX(ZSTD_f_zstd1)); CONTROL(!ZSTD_isError(frameHeaderSize)); /* check block is compressible, hence contains a literals section */ { blockProperties_t bp; ZSTD_getcBlockSize((char*)dst+frameHeaderSize, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = PREPRESULT_INIT; DISPLAY("no compressed literals\n"); return r; } } { size_t const skippedSize = frameHeaderSize + ZSTD_blockHeaderSize; prepSize -= skippedSize; - memmove(dst, (char*)dst+skippedSize, prepSize); + prepBuffer = malloc(prepSize); + CONTROL(prepBuffer != NULL); + memmove(prepBuffer, (char*)dst+skippedSize, prepSize); } ZSTD_decompressBegin(g_zdc); - { PrepResult r = PREPRESULT_INIT; - r.prepSize = prepSize; - r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ - return r; - } + r.prepBuffer = prepBuffer; + r.prepSize = prepSize; + r.dst = dst; + r.dstCapacity = dstCapacity; + r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + return r; } extern size_t ZSTD_decodeLiteralsBlock_wrapper(ZSTD_DCtx* dctx, @@ -259,8 +272,11 @@ local_ZSTD_decodeLiteralsHeader(const void* src, size_t srcSize, void* dst, size return ZSTD_decodeLiteralsHeader(g_zdc, src, srcSize); } -static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +static PrepResult prepSequences(const void* src, size_t srcSize, int cLevel) { + PrepResult r = PREPRESULT_INIT; + size_t const dstCapacity = srcSize; + void* dst = malloc(dstCapacity); const BYTE* ip = dst; const BYTE* iend; { size_t const cSize = ZSTD_compress(dst, dstCapacity, src, srcSize, cLevel); @@ -275,7 +291,6 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, { blockProperties_t bp; size_t const cBlockSize = ZSTD_getcBlockSize(ip, dstCapacity, &bp); /* Get 1st block type */ if (bp.blockType != bt_compressed) { - const PrepResult r = PREPRESULT_INIT; DISPLAY("no compressed sequences\n"); return r; } @@ -285,12 +300,14 @@ static PrepResult prepSequences(void* dst, size_t dstCapacity, const void* src, ZSTD_decompressBegin(g_zdc); CONTROL(iend > ip); ip += ZSTD_decodeLiteralsBlock_wrapper(g_zdc, ip, (size_t)(iend-ip), dst, dstCapacity); /* skip literal segment */ - { PrepResult r = PREPRESULT_INIT; - r.prepSize = (size_t)(iend-ip); - r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ - memmove(dst, ip, r.prepSize); /* copy rest of block (it starts by SeqHeader) */ - return r; - } + r.prepSize = (size_t)(iend-ip); + r.prepBuffer = malloc(r.prepSize); + CONTROL(r.prepBuffer != NULL); + memmove(r.prepBuffer, ip, r.prepSize); /* copy rest of block (it starts by SeqHeader) */ + r.dst = dst; + r.dstCapacity = dstCapacity; + r.fixedOrigSize = srcSize > 128 KB ? 128 KB : srcSize; /* speed relative to block */ + return r; } static size_t @@ -508,24 +525,33 @@ static size_t local_ZSTD_decompressContinue(const void* src, size_t srcSize, } #endif -static PrepResult prepCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +static PrepResult prepCopy(const void* src, size_t srcSize, int cLevel) { - const PrepResult r = { srcSize, srcSize, 0}; - (void)cLevel; - assert(dstCapacity >= srcSize); - memcpy(dst, src, srcSize); + PrepResult r = PREPRESULT_INIT; + r.prepSize = srcSize; + r.prepBuffer = malloc(srcSize); + CONTROL(r.prepBuffer != NULL); + memcpy(r.prepBuffer, src, srcSize); + r.dstCapacity = ZSTD_compressBound(srcSize); + r.dst = malloc(r.dstCapacity); + CONTROL(r.dst != NULL); return r; } -static PrepResult prepShorterDstCapacity(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel) +static PrepResult prepShorterDstCapacity(const void* src, size_t srcSize, int cLevel) { - PrepResult r = prepCopy(dst, dstCapacity, src, srcSize, cLevel); - r.moddedDstCapacity = dstCapacity - 1; + PrepResult r = prepCopy(src, srcSize, cLevel); + assert(r.dstCapacity > 1); + r.dstCapacity -= 1; return r; } +/*_******************************************************* +* List of Scenarios +*********************************************************/ + /* if PrepFunction_f returns 0, benchmarking is cancelled */ -typedef PrepResult (*PrepFunction_f)(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int cLevel); +typedef PrepResult (*PrepFunction_f)(const void* src, size_t srcSize, int cLevel); typedef size_t (*BenchedFunction_f)(const void* src, size_t srcSize, void* dst, size_t dstSize, void* opaque); typedef struct { @@ -560,16 +586,16 @@ static BenchScenario kScenarios[] = { #define NB_SCENARIOS (sizeof(kScenarios) / sizeof(kScenarios[0])) /*_******************************************************* -* Bench functions +* Bench loop *********************************************************/ static int benchMem(unsigned scenarioID, const void* origSrc, size_t origSrcSize, int cLevel, ZSTD_compressionParameters cparams) { - size_t dstCapacity = ZSTD_compressBound(origSrcSize); - void* dst; - void* prepBuff; - size_t prepBuffCapacity=dstCapacity, prepBuffSize; + size_t dstCapacity = 0; + void* dst = NULL; + void* prepBuff = NULL; + size_t prepBuffSize = 0; void* payload; const char* benchName; BMK_benchFn_t benchFunction; @@ -583,14 +609,7 @@ static int benchMem(unsigned scenarioID, prep_f = kScenarios[scenarioID].preparation_f; if (prep_f == NULL) prep_f = prepCopy; /* default */ - /* Allocation */ - dst = malloc(dstCapacity); - prepBuff = malloc(prepBuffCapacity); - if ((!dst) || (!prepBuff)) { - DISPLAY("\nError: not enough memory!\n"); - free(dst); free(prepBuff); - return 12; - } + /* Initialization */ if (g_zcc==NULL) g_zcc = ZSTD_createCCtx(); if (g_zdc==NULL) g_zdc = ZSTD_createDCtx(); if (g_cstream==NULL) g_cstream = ZSTD_createCStream(); @@ -620,10 +639,12 @@ static int benchMem(unsigned scenarioID, /* Preparation */ payload = &cparams; - { PrepResult pr = prep_f(prepBuff, prepBuffCapacity, origSrc, origSrcSize, cLevel); + { PrepResult pr = prep_f(origSrc, origSrcSize, cLevel); + dst = pr.dst; + dstCapacity = pr.dstCapacity; + prepBuff = pr.prepBuffer; prepBuffSize = pr.prepSize; - origSrcSize = pr.fixedOrigSize; - if (pr.moddedDstCapacity) dstCapacity = pr.moddedDstCapacity; + if (pr.fixedOrigSize) origSrcSize = pr.fixedOrigSize; } if (prepBuffSize==0) goto _cleanOut; /* failed preparation */ From 8ab04097ed9736923405e4928f928e49654e2c9a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 13 Dec 2024 17:22:19 -0800 Subject: [PATCH 522/937] add the compressSequences() benchmark scenario --- lib/compress/zstd_compress.c | 2 +- lib/compress/zstd_compress_internal.h | 8 ----- lib/zstd.h | 6 ++-- tests/fullbench.c | 52 ++++++++++++++++++++++++--- 4 files changed, 52 insertions(+), 16 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index bb92bd1ff..5aad13531 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7058,7 +7058,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, size_t cSize = 0; /* Transparent initialization stage, same as compressStream2() */ - DEBUGLOG(4, "ZSTD_compressSequences (dstCapacity=%zu)", dstCapacity); + DEBUGLOG(4, "ZSTD_compressSequences (nbSeqs=%zu,dstCapacity=%zu)", inSeqsSize, dstCapacity); assert(cctx != NULL); FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed"); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 90d462fd2..294835946 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -741,14 +741,6 @@ ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr, U32 offBase, size_t matchLength) { -#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6) - static const BYTE* g_start = NULL; - if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */ - { U32 const pos = (U32)((const BYTE*)literals - g_start); - DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offBase%7u", - pos, (U32)litLength, (U32)matchLength, (U32)offBase); - } -#endif assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq); /* update seqStorePtr->lit, so that we know how many literals were or will be copied */ assert(seqStorePtr->maxNbLit <= 128 KB); diff --git a/lib/zstd.h b/lib/zstd.h index 3c0e836c9..435fe34d4 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1328,7 +1328,7 @@ typedef struct { * * Note: This field is optional. ZSTD_generateSequences() will calculate the value of * 'rep', but repeat offsets do not necessarily need to be calculated from an external - * sequence provider's perspective. For example, ZSTD_compressSequences() does not + * sequence provider perspective. For example, ZSTD_compressSequences() does not * use this 'rep' field at all (as of now). */ } ZSTD_Sequence; @@ -1588,7 +1588,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize); * @param zc The compression context to be used for ZSTD_compress2(). Set any * compression parameters you need on this context. * @param outSeqs The output sequences buffer of size @p outSeqsSize - * @param outSeqsSize The size of the output sequences buffer. + * @param outSeqsCapacity The size of the output sequences buffer. * ZSTD_sequenceBound(srcSize) is an upper bound on the number * of sequences that can be generated. * @param src The source buffer to generate sequences from of size @p srcSize. @@ -1606,7 +1606,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_sequenceBound(size_t srcSize); ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()") ZSTDLIB_STATIC_API size_t ZSTD_generateSequences(ZSTD_CCtx* zc, - ZSTD_Sequence* outSeqs, size_t outSeqsSize, + ZSTD_Sequence* outSeqs, size_t outSeqsCapacity, const void* src, size_t srcSize); /*! ZSTD_mergeBlockDelimiters() : diff --git a/tests/fullbench.c b/tests/fullbench.c index 7218bd6e6..ff512149a 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -12,6 +12,7 @@ /*_************************************ * Includes **************************************/ +#include #define ZSTD_DISABLE_DEPRECATE_WARNINGS /* No deprecation warnings, we still bench some deprecated functions */ #include "util.h" /* Compiler options, UTIL_GetFileSize */ #include /* malloc */ @@ -272,7 +273,7 @@ local_ZSTD_decodeLiteralsHeader(const void* src, size_t srcSize, void* dst, size return ZSTD_decodeLiteralsHeader(g_zdc, src, srcSize); } -static PrepResult prepSequences(const void* src, size_t srcSize, int cLevel) +static PrepResult prepSequences1stBlock(const void* src, size_t srcSize, int cLevel) { PrepResult r = PREPRESULT_INIT; size_t const dstCapacity = srcSize; @@ -456,7 +457,6 @@ local_ZSTD_decompressStream(const void* src, size_t srcSize, return buffOut.pos; } -#ifndef ZSTD_DLL_IMPORT static size_t local_ZSTD_compressContinue(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* payload) @@ -523,11 +523,54 @@ static size_t local_ZSTD_decompressContinue(const void* src, size_t srcSize, return regeneratedSize; } -#endif + +static PrepResult prepSequences(const void* src, size_t srcSize, int cLevel) +{ + PrepResult r = PREPRESULT_INIT; + size_t const dstCapacity = ZSTD_compressBound(srcSize); + void* const dst = malloc(dstCapacity); + size_t const prepCapacity = dstCapacity * 4; + void* prepBuffer = malloc(prepCapacity); + void* sequencesStart = (char*)prepBuffer + 2*sizeof(unsigned); + ZSTD_Sequence* const seqs = sequencesStart; + size_t const seqsCapacity = prepCapacity / sizeof(ZSTD_Sequence); + size_t nbSeqs; + ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_compressionLevel, cLevel); + nbSeqs = ZSTD_generateSequences(g_zcc, seqs, seqsCapacity, src, srcSize); + CONTROL(srcSize < UINT_MAX); + MEM_write32(prepBuffer, (U32)srcSize); + MEM_write32((char*)prepBuffer+4, (U32)nbSeqs); + memcpy(seqs + nbSeqs, src, srcSize); + r.prepBuffer = prepBuffer; + r.prepSize = 8 + sizeof(ZSTD_Sequence)*nbSeqs + srcSize; + r.dst = dst; + r.dstCapacity = dstCapacity; + return r; +} + +static size_t local_compressSequences(const void* input, size_t inputSize, + void* dst, size_t dstCapacity, + void* payload) +{ + const char* ip = input; + size_t srcSize = MEM_read32(ip); + size_t nbSeqs = MEM_read32(ip+=4); + const ZSTD_Sequence* seqs = (const ZSTD_Sequence*)(const void*)(ip+=4); + const void* src = (ip+=nbSeqs * sizeof(ZSTD_Sequence)); + ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters); + assert(8 + nbSeqs * sizeof(ZSTD_Sequence) + srcSize == inputSize); (void)inputSize; + (void)payload; + + return ZSTD_compressSequences(g_zcc, dst, dstCapacity, seqs, nbSeqs, src, srcSize); +} + static PrepResult prepCopy(const void* src, size_t srcSize, int cLevel) { PrepResult r = PREPRESULT_INIT; + (void)cLevel; r.prepSize = srcSize; r.prepBuffer = malloc(srcSize); CONTROL(r.prepBuffer != NULL); @@ -577,10 +620,11 @@ static BenchScenario kScenarios[] = { { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue }, { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, + { "compressSequences", prepSequences, local_compressSequences }, #ifndef ZSTD_DLL_IMPORT { "decodeLiteralsHeader (1st block)", prepLiterals, local_ZSTD_decodeLiteralsHeader }, { "decodeLiteralsBlock (1st block)", prepLiterals, local_ZSTD_decodeLiteralsBlock }, - { "decodeSeqHeaders (1st block)", prepSequences, local_ZSTD_decodeSeqHeaders }, + { "decodeSeqHeaders (1st block)", prepSequences1stBlock, local_ZSTD_decodeSeqHeaders }, #endif }; #define NB_SCENARIOS (sizeof(kScenarios) / sizeof(kScenarios[0])) From ac05ea89a5e87cf9e9756790f08b9d21b349fd9e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 14 Dec 2024 12:34:26 -0800 Subject: [PATCH 523/937] fullbench: switch default generator to lorem ipsum which creates more "realistic" scenarios than former compressible noise. The legacy data generator remains accessible, it is triggered when requesting an explicit compressibility factor (-P#). --- tests/Makefile | 4 ++-- tests/fullbench.c | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/Makefile b/tests/Makefile index 74e05774c..c10d66f53 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -150,12 +150,12 @@ $(FULLBENCHS) : LDFLAGS += $(MULTITHREAD_LD) $(FULLBENCHS) : DEBUGFLAGS = -DNDEBUG # turn off assert() for speed measurements $(FULLBENCHS) : DEBUGLEVEL = 0 # turn off assert() for speed measurements $(FULLBENCHS) : $(ZSTD_FILES) -$(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c fullbench.c +$(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c fullbench.c $(LINK.c) $^ -o $@$(EXT) CLEAN += fullbench-lib fullbench-lib : CPPFLAGS += -DXXH_NAMESPACE=ZSTD_ -fullbench-lib : $(PRGDIR)/datagen.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(LIB_SRCDIR)/libzstd.a fullbench.c +fullbench-lib : $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c $(LIB_SRCDIR)/libzstd.a fullbench.c $(LINK.c) $^ -o $@$(EXT) # note : broken : requires symbols unavailable from dynamic library diff --git a/tests/fullbench.c b/tests/fullbench.c index ff512149a..889761ef4 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -33,6 +33,7 @@ #include "zstd.h" /* ZSTD_versionString */ #include "util.h" /* time functions */ #include "datagen.h" +#include "lorem.h" #include "benchfn.h" /* CustomBench */ #include "benchzstd.h" /* MB_UNIT */ @@ -50,7 +51,7 @@ #define DEFAULT_CLEVEL 1 -#define COMPRESSIBILITY_DEFAULT 0.50 +#define COMPRESSIBILITY_DEFAULT (-1.0) static const size_t kSampleSizeDefault = 10000000; #define TIMELOOP_NANOSEC (1*1000000000ULL) /* 1 second */ @@ -754,6 +755,11 @@ _cleanOut: #define BENCH_ALL_SCENARIOS 999 +/* + * if @compressibility < 0.0, use Lorem Ipsum generator + * otherwise, @compressibility is expected to be between 0.0 and 1.0 + * if scenarioID == BENCH_ALL_SCENARIOS, all scenarios will be run on the sample +*/ static int benchSample(U32 scenarioID, size_t benchedSize, double compressibility, int cLevel, ZSTD_compressionParameters cparams) @@ -763,7 +769,12 @@ static int benchSample(U32 scenarioID, if (!origBuff) { DISPLAY("\nError: not enough memory!\n"); return 12; } /* Fill buffer */ - RDG_genBuffer(origBuff, benchedSize, compressibility, 0.0, 0); + if (compressibility < 0.0) { + LOREM_genBuffer(origBuff, benchedSize, 0); + } else { + RDG_genBuffer(origBuff, benchedSize, compressibility, 0.0, 0); + + } /* bench */ DISPLAY("\r%70s\r", ""); From f281497aef87a0e6459eef28f695c437a3dec42d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 14 Dec 2024 23:38:18 -0800 Subject: [PATCH 524/937] fullbench: new scenario: compressSequencesAndLiterals() --- lib/compress/zstd_compress.c | 2 +- tests/fullbench.c | 60 +++++++++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 5aad13531..166208589 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7227,7 +7227,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, inSeqs, nbSequences, seqPos); U32 const lastBlock = (blockSize == remaining); FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); - RETURN_ERROR_IF(!lastBlock, GENERIC, "Only supports single block"); + RETURN_ERROR_IF(!lastBlock, srcSize_wrong, "Only supports single block"); assert(blockSize <= remaining); ZSTD_resetSeqStore(&cctx->seqStore); diff --git a/tests/fullbench.c b/tests/fullbench.c index 889761ef4..919ae2742 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -567,6 +567,63 @@ static size_t local_compressSequences(const void* input, size_t inputSize, return ZSTD_compressSequences(g_zcc, dst, dstCapacity, seqs, nbSeqs, src, srcSize); } +static PrepResult prepSequencesAndLiterals(const void* src, size_t srcSize, int cLevel) +{ + PrepResult r = PREPRESULT_INIT; + size_t const dstCapacity = ZSTD_compressBound(srcSize); + void* const dst = malloc(dstCapacity); + size_t const prepCapacity = dstCapacity * 4; + void* prepBuffer = malloc(prepCapacity); + void* sequencesStart = (char*)prepBuffer + 3*sizeof(unsigned); + ZSTD_Sequence* const seqs = sequencesStart; + size_t const seqsCapacity = prepCapacity / sizeof(ZSTD_Sequence); + size_t nbSeqs; + ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_compressionLevel, cLevel); + nbSeqs = ZSTD_generateSequences(g_zcc, seqs, seqsCapacity, src, srcSize); + CONTROL(srcSize < UINT_MAX); + MEM_write32(prepBuffer, (U32)srcSize); + MEM_write32((char*)prepBuffer+4, (U32)nbSeqs); + /* copy literals */ + { char* const litStart = (char*)(seqs + nbSeqs); + size_t nbLiterals = 0; + const char* ip = src; + size_t n; + for (n=0; n Date: Sat, 14 Dec 2024 23:46:21 -0800 Subject: [PATCH 525/937] minor conversion warning fix --- lib/common/zstd_trace.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/zstd_trace.h b/lib/common/zstd_trace.h index 173d63fb1..3ae779fa6 100644 --- a/lib/common/zstd_trace.h +++ b/lib/common/zstd_trace.h @@ -65,7 +65,7 @@ typedef struct { /** * Non-zero if streaming (de)compression is used. */ - unsigned streaming; + int streaming; /** * The dictionary ID. */ From 1c8f5b0f11c9fbcd47135a658dca9b927a0b27b7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 15 Dec 2024 16:14:38 -0800 Subject: [PATCH 526/937] minor optimization for ZSTD_compressSequencesAndLiterals() does not need to track and update internal `litPtr`. note: does not measurably impact performance. --- lib/compress/zstd_compress_internal.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 294835946..10bd8ca70 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -742,13 +742,10 @@ ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr, size_t matchLength) { assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq); - /* update seqStorePtr->lit, so that we know how many literals were or will be copied */ - assert(seqStorePtr->maxNbLit <= 128 KB); - assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit); - seqStorePtr->lit += litLength; /* literal Length */ - if (litLength>0xFFFF) { + assert(litLength <= ZSTD_BLOCKSIZE_MAX); + if (UNLIKELY(litLength>0xFFFF)) { assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */ seqStorePtr->longLengthType = ZSTD_llt_literalLength; seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); @@ -759,9 +756,10 @@ ZSTD_storeSeqOnly(SeqStore_t* seqStorePtr, seqStorePtr->sequences[0].offBase = offBase; /* match Length */ + assert(matchLength <= ZSTD_BLOCKSIZE_MAX); assert(matchLength >= MINMATCH); { size_t const mlBase = matchLength - MINMATCH; - if (mlBase>0xFFFF) { + if (UNLIKELY(mlBase>0xFFFF)) { assert(seqStorePtr->longLengthType == ZSTD_llt_none); /* there can only be a single long length */ seqStorePtr->longLengthType = ZSTD_llt_matchLength; seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); @@ -811,6 +809,7 @@ ZSTD_storeSeq(SeqStore_t* seqStorePtr, } else { ZSTD_safecopyLiterals(seqStorePtr->lit, literals, litEnd, litLimit_w); } + seqStorePtr->lit += litLength; ZSTD_storeSeqOnly(seqStorePtr, litLength, offBase, matchLength); } From f17651446730b580f0a45c4a7917236da140db76 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 15 Dec 2024 23:07:31 -0800 Subject: [PATCH 527/937] minor doc update --- lib/zstd.h | 17 +++++++++-------- tests/fullbench.c | 3 +++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 435fe34d4..6218a5d0c 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1665,13 +1665,14 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * aka all literals already extracted and laid out into a single continuous buffer. * This can be useful if the process generating the sequences also happens to generate the buffer of literals, * thus skipping an extraction + caching stage. - * It's essentially a speed optimization when the right conditions are met, + * It's merely a speed optimization when the right conditions are met, * but it also features the following limitations: * - Only supports explicit delimiter mode * - Supports 1 block only (max input 128 KB) * - Not compatible with frame checksum, which must disabled * - Can fail (return an error) when input data cannot be compress sufficiently - * Also, to be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. + * - @litSize must be == sum of all @.litLength fields in @inSeqs. Discrepancy will generate an error. + * - the buffer @literals must be larger than @litSize by at least 8 bytes. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t @@ -2301,9 +2302,12 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo #define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18 /* ZSTD_c_searchForExternalRepcodes + * Note: for now, this param only has an effect if ZSTD_c_blockDelimiters is + * set to ZSTD_sf_explicitBlockDelimiters. That may change in the future. + * * This parameter affects how zstd parses external sequences, such as sequences - * provided through the compressSequences() API or from an external block-level - * sequence producer. + * provided through compressSequences() and variant API + * or from an external block-level sequence producer. * * If set to ZSTD_ps_enable, the library will check for repeated offsets in * external sequences, even if those repcodes are not explicitly indicated in @@ -2317,10 +2321,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo * compression ratio. * * The default value is ZSTD_ps_auto, for which the library will enable/disable - * based on compression level. - * - * Note: for now, this param only has an effect if ZSTD_c_blockDelimiters is - * set to ZSTD_sf_explicitBlockDelimiters. That may change in the future. + * based on compression level (currently: level<10 disables, level>=10 enables). */ #define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 diff --git a/tests/fullbench.c b/tests/fullbench.c index 919ae2742..09c426154 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -617,6 +617,9 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, const void* literals = (ip+=nbSeqs * sizeof(ZSTD_Sequence)); ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters); +# if 0 /* for tests */ + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_searchForExternalRepcodes, ZSTD_ps_enable); +#endif assert(8 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; (void)payload; From a288751de78e3dd69dfacfe74d3f35c534b57096 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 11:31:28 -0800 Subject: [PATCH 528/937] minor optimization: only track seqPos->posInSrc when validateSequences is enabled note: very minor saving, no performance impact --- lib/compress/zstd_compress.c | 37 +++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 166208589..144a4b69d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7112,20 +7112,24 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, U32 idx = seqPos->idx; U32 const startIdx = idx; Repcodes_t updatedRepcodes; - U32 dictSize; + U32 dictSize = 0; size_t startPosInSrc = seqPos->posInSrc; size_t litConsumed = 0; DEBUGLOG(5, "ZSTD_transferSequencesOnly_wBlockDelim (blockSize = %zu)", blockSize); - if (cctx->cdict) { - dictSize = (U32)cctx->cdict->dictContentSize; - } else if (cctx->prefixDict.dict) { - dictSize = (U32)cctx->prefixDict.dictSize; - } else { - dictSize = 0; + /* dictSize is useful to check offset within Sequence validation */ + if (cctx->appliedParams.validateSequences) { + if (cctx->cdict) { + dictSize = (U32)cctx->cdict->dictContentSize; + } else if (cctx->prefixDict.dict) { + dictSize = (U32)cctx->prefixDict.dictSize; + } } + ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t)); + + /* Convert Sequences from public format to internal format */ for (; idx < nbSequences && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) { U32 const litLength = inSeqs[idx].litLength; U32 const matchLength = inSeqs[idx].matchLength; @@ -7140,8 +7144,8 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, } DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); - seqPos->posInSrc += litLength + matchLength; if (cctx->appliedParams.validateSequences) { + seqPos->posInSrc += litLength + matchLength; FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc, cctx->appliedParams.cParams.windowLog, dictSize, @@ -7156,14 +7160,17 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, /* last sequence (only literals) */ { size_t const lastLitLength = inSeqs[idx].litLength; - seqPos->posInSrc += lastLitLength; - cctx->seqStore.lit += lastLitLength; /* register proper length */ litConsumed += lastLitLength; + if (cctx->appliedParams.validateSequences) { + seqPos->posInSrc += lastLitLength; + /* blockSize must be exactly correct (checked before calling this function) */ + RETURN_ERROR_IF((seqPos->posInSrc - startPosInSrc) != blockSize, externalSequences_invalid, "mismatch between Sequences and specified blockSize"); + } else { + /* blockSize presumed exactly correct (checked before calling this function) */ + seqPos->posInSrc += blockSize; + } } - /* blockSize must be exactly correct (checked before calling this function) */ - assert((seqPos->posInSrc - startPosInSrc) == blockSize); (void)startPosInSrc; - /* If we skipped repcode search while parsing, we need to update repcodes now */ assert(externalRepSearch != ZSTD_ps_auto); assert(idx >= startIdx); @@ -7236,8 +7243,8 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, inSeqs, nbSequences, blockSize, cctx->appliedParams.searchForExternalRepcodes); - RETURN_ERROR_IF(blockSize != remaining, GENERIC, "Must consume the entire block"); - RETURN_ERROR_IF(litConsumed != litSize, GENERIC, "Must consume the exact amount of literals provided"); + RETURN_ERROR_IF(blockSize != remaining, externalSequences_invalid, "Must consume the entire block"); + RETURN_ERROR_IF(litConsumed != litSize, externalSequences_invalid, "Must consume the exact amount of literals provided"); FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); /* Note: when blockSize is very small, other variant send it uncompressed. From 1f6d6815c3fc4b6d1f406e01849c49b15518ba54 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 11:39:25 -0800 Subject: [PATCH 529/937] optimization: instantiate specialized version without Sequence checking code results in +4% compression speed, thanks to removal of branches in the hot loop. --- lib/compress/zstd_compress.c | 52 ++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 144a4b69d..6ff27056f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7102,12 +7102,13 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * seqPos must end on an explicit block delimiter * @blockSize must be exactly correct. */ -static size_t -ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, +FORCE_INLINE_TEMPLATE size_t +ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, - ZSTD_ParamSwitch_e externalRepSearch) + ZSTD_ParamSwitch_e externalRepSearch, + int const checkSequences) { U32 idx = seqPos->idx; U32 const startIdx = idx; @@ -7119,7 +7120,7 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, DEBUGLOG(5, "ZSTD_transferSequencesOnly_wBlockDelim (blockSize = %zu)", blockSize); /* dictSize is useful to check offset within Sequence validation */ - if (cctx->appliedParams.validateSequences) { + if (checkSequences) { if (cctx->cdict) { dictSize = (U32)cctx->cdict->dictContentSize; } else if (cctx->prefixDict.dict) { @@ -7144,7 +7145,7 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, } DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); - if (cctx->appliedParams.validateSequences) { + if (checkSequences) { seqPos->posInSrc += litLength + matchLength; FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, seqPos->posInSrc, @@ -7161,7 +7162,7 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, /* last sequence (only literals) */ { size_t const lastLitLength = inSeqs[idx].litLength; litConsumed += lastLitLength; - if (cctx->appliedParams.validateSequences) { + if (checkSequences) { seqPos->posInSrc += lastLitLength; /* blockSize must be exactly correct (checked before calling this function) */ RETURN_ERROR_IF((seqPos->posInSrc - startPosInSrc) != blockSize, externalSequences_invalid, "mismatch between Sequences and specified blockSize"); @@ -7201,6 +7202,32 @@ ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, return blockSize; } +typedef size_t (*ZSTD_transferSequencesOnly_f) (ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + size_t blockSize, + ZSTD_ParamSwitch_e externalRepSearch); + +static size_t +ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + size_t blockSize, + ZSTD_ParamSwitch_e externalRepSearch) +{ + return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, externalRepSearch, 0); +} + +static size_t +ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + size_t blockSize, + ZSTD_ParamSwitch_e externalRepSearch) +{ + return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, externalRepSearch, 1); +} + static size_t ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, @@ -7211,6 +7238,9 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, size_t remaining = srcSize; ZSTD_SequencePosition seqPos = {0, 0, 0}; BYTE* op = (BYTE*)dst; + const ZSTD_transferSequencesOnly_f transfer = cctx->appliedParams.validateSequences ? + ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences + : ZSTD_transferSequencesOnly_wBlockDelim; DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { @@ -7238,11 +7268,11 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, assert(blockSize <= remaining); ZSTD_resetSeqStore(&cctx->seqStore); - blockSize = ZSTD_transferSequencesOnly_wBlockDelim(cctx, - &seqPos, &litConsumed, - inSeqs, nbSequences, - blockSize, - cctx->appliedParams.searchForExternalRepcodes); + blockSize = transfer(cctx, + &seqPos, &litConsumed, + inSeqs, nbSequences, + blockSize, + cctx->appliedParams.searchForExternalRepcodes); RETURN_ERROR_IF(blockSize != remaining, externalSequences_invalid, "Must consume the entire block"); RETURN_ERROR_IF(litConsumed != litSize, externalSequences_invalid, "Must consume the exact amount of literals provided"); FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); From d2d0fdac4288fed2d63b4d3e0e41f4b4768f8b60 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 12:54:52 -0800 Subject: [PATCH 530/937] updated documentation on validateSequence --- lib/compress/zstd_compress.c | 6 +++--- lib/zstd.h | 24 ++++++++++++------------ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 6ff27056f..dc084830e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6585,11 +6585,11 @@ size_t ZSTD_compress2(ZSTD_CCtx* cctx, } /* ZSTD_validateSequence() : - * @offCode : is presumed to follow format required by ZSTD_storeSeq() + * @offBase : must use the format required by ZSTD_storeSeq() * @returns a ZSTD error code if sequence is not valid */ static size_t -ZSTD_validateSequence(U32 offCode, U32 matchLength, U32 minMatch, +ZSTD_validateSequence(U32 offBase, U32 matchLength, U32 minMatch, size_t posInSrc, U32 windowLog, size_t dictSize, int useSequenceProducer) { U32 const windowSize = 1u << windowLog; @@ -6600,7 +6600,7 @@ ZSTD_validateSequence(U32 offCode, U32 matchLength, U32 minMatch, */ size_t const offsetBound = posInSrc > windowSize ? (size_t)windowSize : posInSrc + (size_t)dictSize; size_t const matchLenLowerBound = (minMatch == 3 || useSequenceProducer) ? 3 : 4; - RETURN_ERROR_IF(offCode > OFFSET_TO_OFFBASE(offsetBound), externalSequences_invalid, "Offset too large!"); + RETURN_ERROR_IF(offBase > OFFSET_TO_OFFBASE(offsetBound), externalSequences_invalid, "Offset too large!"); /* Validate maxNbSeq is large enough for the given matchLength and minMatch */ RETURN_ERROR_IF(matchLength < matchLenLowerBound, externalSequences_invalid, "Matchlength too small for the minMatch"); return 0; diff --git a/lib/zstd.h b/lib/zstd.h index 6218a5d0c..7f1d8c483 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1635,11 +1635,11 @@ ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, si * the block size derived from the cctx, and sequences may be split. This is the default setting. * * If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain - * block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. + * valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. * - * If ZSTD_c_validateSequences == 0, this function will blindly accept the sequences provided. Invalid sequences cause undefined - * behavior. If ZSTD_c_validateSequences == 1, then if sequence is invalid (see doc/zstd_compression_format.md for - * specifics regarding offset/matchlength requirements) then the function will bail out and return an error. + * If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined + * behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for + * specifics regarding offset/matchlength requirements) and then bail out and return an error. * * In addition to the two adjustable experimental params, there are other important cctx params. * - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN. @@ -1662,10 +1662,10 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, /*! ZSTD_compressSequencesAndLiterals() : * This is a variant of ZSTD_compressSequences() which, * instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), - * aka all literals already extracted and laid out into a single continuous buffer. + * aka all the literals, already extracted and laid out into a single continuous buffer. * This can be useful if the process generating the sequences also happens to generate the buffer of literals, * thus skipping an extraction + caching stage. - * It's merely a speed optimization when the right conditions are met, + * It's a speed optimization, useful when the right conditions are met, * but it also features the following limitations: * - Only supports explicit delimiter mode * - Supports 1 block only (max input 128 KB) @@ -2172,17 +2172,17 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo /* ZSTD_c_validateSequences * Default is 0 == disabled. Set to 1 to enable sequence validation. * - * For use with sequence compression API: ZSTD_compressSequences(). - * Designates whether or not we validate sequences provided to ZSTD_compressSequences() + * For use with sequence compression API: ZSTD_compressSequences*(). + * Designates whether or not provided sequences are validated within ZSTD_compressSequences*() * during function execution. * - * Without validation, providing a sequence that does not conform to the zstd spec will cause - * undefined behavior, and may produce a corrupted block. + * When Sequence validation is disabled (default), Sequences are compressed as-is, + * so they must correct, otherwise it would result in a corruption error. * - * With validation enabled, if sequence is invalid (see doc/zstd_compression_format.md for + * Sequence validation adds some protection, by ensuring that all values respect boundary conditions. + * If a Sequence is detected invalid (see doc/zstd_compression_format.md for * specifics regarding offset/matchlength requirements) then the function will bail out and * return an error. - * */ #define ZSTD_c_validateSequences ZSTD_c_experimentalParam12 From ca8bd83373310ade16a6d230c01b671d7725eaf1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 13:08:16 -0800 Subject: [PATCH 531/937] minor: cleaner function parameter repcodeResolution --- lib/compress/zstd_compress.c | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index dc084830e..6b3efb336 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7107,7 +7107,7 @@ ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, - ZSTD_ParamSwitch_e externalRepSearch, + int const repcodeResolution, int const checkSequences) { U32 idx = seqPos->idx; @@ -7136,7 +7136,7 @@ ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, U32 const matchLength = inSeqs[idx].matchLength; U32 offBase; - if (externalRepSearch == ZSTD_ps_disable) { + if (!repcodeResolution) { offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset); } else { U32 const ll0 = (litLength == 0); @@ -7173,9 +7173,8 @@ ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, } /* If we skipped repcode search while parsing, we need to update repcodes now */ - assert(externalRepSearch != ZSTD_ps_auto); assert(idx >= startIdx); - if (externalRepSearch == ZSTD_ps_disable && idx != startIdx) { + if (!repcodeResolution && idx != startIdx) { U32* const rep = updatedRepcodes.rep; U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */ @@ -7206,16 +7205,18 @@ typedef size_t (*ZSTD_transferSequencesOnly_f) (ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, - ZSTD_ParamSwitch_e externalRepSearch); + int const repcodeResolution); static size_t ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, - ZSTD_ParamSwitch_e externalRepSearch) + int const repcodeResolution) { - return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, externalRepSearch, 0); + return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, + seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, + repcodeResolution, 0); } static size_t @@ -7223,9 +7224,11 @@ ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, - ZSTD_ParamSwitch_e externalRepSearch) + int const repcodeResolution) { - return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, externalRepSearch, 1); + return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, + seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, + repcodeResolution, 1); } static size_t @@ -7238,6 +7241,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, size_t remaining = srcSize; ZSTD_SequencePosition seqPos = {0, 0, 0}; BYTE* op = (BYTE*)dst; + int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable); const ZSTD_transferSequencesOnly_f transfer = cctx->appliedParams.validateSequences ? ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences : ZSTD_transferSequencesOnly_wBlockDelim; @@ -7246,6 +7250,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { RETURN_ERROR(GENERIC, "This mode is only compatible with explicit delimiters"); } + assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto); /* Special case: empty frame */ if (remaining == 0) { @@ -7272,7 +7277,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, &seqPos, &litConsumed, inSeqs, nbSequences, blockSize, - cctx->appliedParams.searchForExternalRepcodes); + repcodeResolution); RETURN_ERROR_IF(blockSize != remaining, externalSequences_invalid, "Must consume the entire block"); RETURN_ERROR_IF(litConsumed != litSize, externalSequences_invalid, "Must consume the exact amount of literals provided"); FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); @@ -7299,9 +7304,9 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, * but it could be considered from analyzing the sequence directly */ if (compressedSeqsSize == 0) { - /* Sending uncompressed blocks is difficult, because we don't have the source. - * In theory, we could use the sequences to regenerate the source, like a decompressor, - * but it's complex and likely overkill. + /* Sending uncompressed blocks is difficult, because the source is not provided. + * In theory, one could use the sequences to regenerate the source, like a decompressor, + * but it's complex, and memory hungry, killing the purpose of this variant. * Current outcome: generate an error code. */ RETURN_ERROR(dstSize_tooSmall, "Data is not compressible"); /* note: error code might be misleading */ From 5164d44dabbbf2f3f1cd89bbf1244b7b73d69ef3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 13:21:08 -0800 Subject: [PATCH 532/937] change advanced parameter name: ZSTD_c_repcodeResolution and updated its documentation. Note: older name ZSTD_c_searchForExternalRepcodes remains supported via #define --- lib/compress/zstd_compress.c | 12 ++++++------ lib/zstd.h | 23 +++++++++++++++-------- tests/fullbench.c | 2 +- tests/fuzz/zstd_helpers.c | 2 +- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 6b3efb336..be6107cb8 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -634,7 +634,7 @@ ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param) bounds.upperBound = ZSTD_BLOCKSIZE_MAX; return bounds; - case ZSTD_c_searchForExternalRepcodes: + case ZSTD_c_repcodeResolution: bounds.lowerBound = (int)ZSTD_ps_auto; bounds.upperBound = (int)ZSTD_ps_disable; return bounds; @@ -708,7 +708,7 @@ static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param) case ZSTD_c_prefetchCDictTables: case ZSTD_c_enableSeqProducerFallback: case ZSTD_c_maxBlockSize: - case ZSTD_c_searchForExternalRepcodes: + case ZSTD_c_repcodeResolution: default: return 0; } @@ -768,7 +768,7 @@ size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value) case ZSTD_c_prefetchCDictTables: case ZSTD_c_enableSeqProducerFallback: case ZSTD_c_maxBlockSize: - case ZSTD_c_searchForExternalRepcodes: + case ZSTD_c_repcodeResolution: break; default: RETURN_ERROR(parameter_unsupported, "unknown parameter"); @@ -1020,8 +1020,8 @@ size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* CCtxParams, CCtxParams->maxBlockSize = (size_t)value; return CCtxParams->maxBlockSize; - case ZSTD_c_searchForExternalRepcodes: - BOUNDCHECK(ZSTD_c_searchForExternalRepcodes, value); + case ZSTD_c_repcodeResolution: + BOUNDCHECK(ZSTD_c_repcodeResolution, value); CCtxParams->searchForExternalRepcodes = (ZSTD_ParamSwitch_e)value; return CCtxParams->searchForExternalRepcodes; @@ -1169,7 +1169,7 @@ size_t ZSTD_CCtxParams_getParameter( case ZSTD_c_maxBlockSize: *value = (int)CCtxParams->maxBlockSize; break; - case ZSTD_c_searchForExternalRepcodes: + case ZSTD_c_repcodeResolution: *value = (int)CCtxParams->searchForExternalRepcodes; break; default: RETURN_ERROR(parameter_unsupported, "unknown parameter"); diff --git a/lib/zstd.h b/lib/zstd.h index 7f1d8c483..ffcb059cf 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1637,6 +1637,12 @@ ZSTDLIB_STATIC_API size_t ZSTD_mergeBlockDelimiters(ZSTD_Sequence* sequences, si * If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain * valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. * + * When ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, it's possible to decide generating repcodes + * using the advanced parameter ZSTD_c_repcodeResolution. Repcodes will improve compression ratio, though the benefit + * can vary greatly depending on Sequences. On the other hand, repcode resolution is an expensive operation. + * By default, it's disabled at low (<10) compression levels, and enabled above the threshold (>=10). + * ZSTD_c_repcodeResolution makes it possible to directly manage this processing in either direction. + * * If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined * behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for * specifics regarding offset/matchlength requirements) and then bail out and return an error. @@ -2301,18 +2307,18 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo */ #define ZSTD_c_maxBlockSize ZSTD_c_experimentalParam18 -/* ZSTD_c_searchForExternalRepcodes - * Note: for now, this param only has an effect if ZSTD_c_blockDelimiters is - * set to ZSTD_sf_explicitBlockDelimiters. That may change in the future. +/* ZSTD_c_repcodeResolution + * This parameter only has an effect if ZSTD_c_blockDelimiters is + * set to ZSTD_sf_explicitBlockDelimiters (may change in the future). * - * This parameter affects how zstd parses external sequences, such as sequences - * provided through compressSequences() and variant API + * This parameter affects how zstd parses external sequences, + * provided via the ZSTD_compressSequences*() API * or from an external block-level sequence producer. * - * If set to ZSTD_ps_enable, the library will check for repeated offsets in + * If set to ZSTD_ps_enable, the library will check for repeated offsets within * external sequences, even if those repcodes are not explicitly indicated in * the "rep" field. Note that this is the only way to exploit repcode matches - * while using compressSequences() or an external sequence producer, since zstd + * while using compressSequences*() or an external sequence producer, since zstd * currently ignores the "rep" field of external sequences. * * If set to ZSTD_ps_disable, the library will not exploit repeated offsets in @@ -2323,7 +2329,8 @@ ZSTDLIB_STATIC_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const vo * The default value is ZSTD_ps_auto, for which the library will enable/disable * based on compression level (currently: level<10 disables, level>=10 enables). */ -#define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 +#define ZSTD_c_repcodeResolution ZSTD_c_experimentalParam19 +#define ZSTD_c_searchForExternalRepcodes ZSTD_c_experimentalParam19 /* older name */ /*! ZSTD_CCtx_getParameter() : diff --git a/tests/fullbench.c b/tests/fullbench.c index 09c426154..320b0ed73 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -618,7 +618,7 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters); # if 0 /* for tests */ - ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_searchForExternalRepcodes, ZSTD_ps_enable); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_repcodeResolution, ZSTD_ps_enable); #endif assert(8 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; (void)payload; diff --git a/tests/fuzz/zstd_helpers.c b/tests/fuzz/zstd_helpers.c index c89e448d0..f3b2e6fba 100644 --- a/tests/fuzz/zstd_helpers.c +++ b/tests/fuzz/zstd_helpers.c @@ -146,7 +146,7 @@ void FUZZ_setRandomParameters(ZSTD_CCtx *cctx, size_t srcSize, FUZZ_dataProducer setRand(cctx, ZSTD_c_prefetchCDictTables, 0, 2, producer); setRand(cctx, ZSTD_c_maxBlockSize, ZSTD_BLOCKSIZE_MAX_MIN, ZSTD_BLOCKSIZE_MAX, producer); setRand(cctx, ZSTD_c_validateSequences, 0, 1, producer); - setRand(cctx, ZSTD_c_searchForExternalRepcodes, 0, 2, producer); + setRand(cctx, ZSTD_c_repcodeResolution, 0, 2, producer); if (FUZZ_dataProducer_uint32Range(producer, 0, 1) == 0) { setRand(cctx, ZSTD_c_srcSizeHint, ZSTD_SRCSIZEHINT_MIN, 2 * srcSize, producer); } From 31b5ef25393c3abf4bb9e290cf32b06d97c78b93 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 18:05:40 -0800 Subject: [PATCH 533/937] ZSTD_compressSequencesAndLiterals() now supports multi-blocks frames. --- lib/compress/zstd_compress.c | 40 ++++++++++++++++++------------------ lib/zstd.h | 5 ++--- tests/fuzzer.c | 2 +- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index be6107cb8..71e40bdc1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7104,7 +7104,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, */ FORCE_INLINE_TEMPLATE size_t ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution, @@ -7197,37 +7197,36 @@ ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); seqPos->idx = idx+1; - *litConsumedPtr = litConsumed; - return blockSize; + return litConsumed; } typedef size_t (*ZSTD_transferSequencesOnly_f) (ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution); static size_t ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, - seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, + seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 0); } static size_t ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, size_t* litConsumedPtr, + ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, - seqPos, litConsumedPtr, inSeqs, nbSequences, blockSize, + seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 1); } @@ -7269,28 +7268,26 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, inSeqs, nbSequences, seqPos); U32 const lastBlock = (blockSize == remaining); FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); - RETURN_ERROR_IF(!lastBlock, srcSize_wrong, "Only supports single block"); assert(blockSize <= remaining); ZSTD_resetSeqStore(&cctx->seqStore); - blockSize = transfer(cctx, - &seqPos, &litConsumed, + litConsumed = transfer(cctx, + &seqPos, inSeqs, nbSequences, blockSize, repcodeResolution); - RETURN_ERROR_IF(blockSize != remaining, externalSequences_invalid, "Must consume the entire block"); - RETURN_ERROR_IF(litConsumed != litSize, externalSequences_invalid, "Must consume the exact amount of literals provided"); - FORWARD_IF_ERROR(blockSize, "Bad sequence copy"); + FORWARD_IF_ERROR(litConsumed, "Bad sequence conversion"); + RETURN_ERROR_IF(litConsumed > litSize, externalSequences_invalid, "discrepancy between literals buffer and Sequences"); /* Note: when blockSize is very small, other variant send it uncompressed. - * Here, we still send the sequences, because we don't have the source to send it uncompressed. - * In theory, it would be possible to reproduce the source from the sequences, - * but that's pretty complex and memory intensive, which goes against the principles of this variant. */ + * Here, we still send the sequences, because we don't have the original source to send it uncompressed. + * One could imagine it possible to reproduce the source from the sequences, + * but that's complex and costly memory intensive, which goes against the objectives of this variant. */ RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); compressedSeqsSize = ZSTD_entropyCompressSeqStore_wExtLitBuffer( op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, - literals, litSize, + literals, litConsumed, blockSize, &cctx->seqStore, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, @@ -7299,17 +7296,19 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, cctx->bmi2); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); + litSize -= litConsumed; + literals = (const char*)literals + litConsumed; /* Note: difficult to check source for RLE block when only Literals are provided, * but it could be considered from analyzing the sequence directly */ if (compressedSeqsSize == 0) { - /* Sending uncompressed blocks is difficult, because the source is not provided. + /* Sending uncompressed blocks is out of reach, because the source is not provided. * In theory, one could use the sequences to regenerate the source, like a decompressor, * but it's complex, and memory hungry, killing the purpose of this variant. * Current outcome: generate an error code. */ - RETURN_ERROR(dstSize_tooSmall, "Data is not compressible"); /* note: error code might be misleading */ + RETURN_ERROR(dstSize_tooSmall, "Data is not compressible"); /* note: error code could be clearer */ } else { U32 cBlockHeader; assert(compressedSeqsSize > 1); /* no RLE */ @@ -7338,6 +7337,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity); } + RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed"); DEBUGLOG(4, "cSize final total: %zu", cSize); return cSize; } diff --git a/lib/zstd.h b/lib/zstd.h index ffcb059cf..68e78b3ca 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1674,10 +1674,9 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * It's a speed optimization, useful when the right conditions are met, * but it also features the following limitations: * - Only supports explicit delimiter mode - * - Supports 1 block only (max input 128 KB) * - Not compatible with frame checksum, which must disabled - * - Can fail (return an error) when input data cannot be compress sufficiently - * - @litSize must be == sum of all @.litLength fields in @inSeqs. Discrepancy will generate an error. + * - If any block is incompressible, will fail and return an error + * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. * - the buffer @literals must be larger than @litSize by at least 8 bytes. * @return : final compressed size, or a ZSTD error code. */ diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 3063ec2d1..4901376ff 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3880,7 +3880,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "test%3i : ZSTD_compressSequencesAndLiterals : ", testNb++); { - const size_t srcSize = 100 KB; + const size_t srcSize = 500 KB; const BYTE* const src = (BYTE*)CNBuffer; BYTE* const dst = (BYTE*)compressedBuffer; const size_t dstCapacity = ZSTD_compressBound(srcSize); From f0d0d952348b4bdc2e3111d73d6703f1b6151f0d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 18:08:14 -0800 Subject: [PATCH 534/937] added tests check that ZSTD_compressAndLiterals() also controls that the `srcSize` field is exact. --- tests/fuzzer.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 4901376ff..b20031708 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3922,6 +3922,20 @@ static int basicUnitTests(U32 const seed, double compressibility) goto _output_error; } + /* too short srcSize: must fail */ + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize, srcSize-1); + if (!ZSTD_isError(compressedSize)) { + DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too short\n"); + goto _output_error; + } + + /* too large srcSize: must fail */ + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize, srcSize+1); + if (!ZSTD_isError(compressedSize)) { + DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too short\n"); + goto _output_error; + } + /* correct amount of literals: should compress successfully */ compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize); if (ZSTD_isError(compressedSize)) { From 6f8c1046d04a7a5439320edbd4775da5b5781726 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 21:05:24 -0800 Subject: [PATCH 535/937] update Visual Studio solutions --- build/VS2010/fullbench-dll/fullbench-dll.vcxproj | 1 + build/VS2010/fullbench/fullbench.vcxproj | 1 + 2 files changed, 2 insertions(+) diff --git a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj b/build/VS2010/fullbench-dll/fullbench-dll.vcxproj index befdc0445..3e88d087a 100644 --- a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj +++ b/build/VS2010/fullbench-dll/fullbench-dll.vcxproj @@ -169,6 +169,7 @@ + diff --git a/build/VS2010/fullbench/fullbench.vcxproj b/build/VS2010/fullbench/fullbench.vcxproj index f60cfe726..c78a72ecc 100644 --- a/build/VS2010/fullbench/fullbench.vcxproj +++ b/build/VS2010/fullbench/fullbench.vcxproj @@ -184,6 +184,7 @@ + From 47edd0acf4ec6a6c2c9b4fc05fbd3de2d2252c59 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 21:23:30 -0800 Subject: [PATCH 536/937] removed fullbench-dll project from visual solutions --- .../fullbench-dll/fullbench-dll.vcxproj | 190 ------------------ build/VS2010/zstd.sln | 5 - 2 files changed, 195 deletions(-) delete mode 100644 build/VS2010/fullbench-dll/fullbench-dll.vcxproj diff --git a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj b/build/VS2010/fullbench-dll/fullbench-dll.vcxproj deleted file mode 100644 index 3e88d087a..000000000 --- a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj +++ /dev/null @@ -1,190 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {00000000-1CC8-4FD7-9281-6B8DBB9D3DF8} - Win32Proj - fullbench-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - MultiByte - - - Application - true - MultiByte - - - Application - false - true - MultiByte - - - Application - false - true - MultiByte - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\common;$(UniversalCRT_IncludePath); - false - - - true - $(IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\common;$(UniversalCRT_IncludePath); - false - - - false - $(IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\common;$(UniversalCRT_IncludePath); - false - - - false - $(IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\common;$(UniversalCRT_IncludePath); - false - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;ZSTD_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - libzstd.lib;%(AdditionalDependencies) - false - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;ZSTD_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - libzstd.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;_DEBUG;_CONSOLE;ZSTD_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - libzstd.lib;%(AdditionalDependencies) - false - - - - - Level4 - - - MaxSpeed - true - true - WIN32;_DEBUG;_CONSOLE;ZSTD_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - libzstd.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - {00000000-94d5-4bf9-8a50-7bd9929a0850} - - - - - - diff --git a/build/VS2010/zstd.sln b/build/VS2010/zstd.sln index 12032db44..528aae8aa 100644 --- a/build/VS2010/zstd.sln +++ b/build/VS2010/zstd.sln @@ -7,11 +7,6 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcx EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{61ABD629-1CC8-4FD7-9281-6B8DBB9D3DF8}" EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{00000000-1CC8-4FD7-9281-6B8DBB9D3DF8}" - ProjectSection(ProjectDependencies) = postProject - {00000000-94D5-4BF9-8A50-7BD9929A0850} = {00000000-94D5-4BF9-8A50-7BD9929A0850} - EndProjectSection -EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{037E781E-81A6-494B-B1B3-438AB1200523}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libzstd", "libzstd\libzstd.vcxproj", "{8BFD8150-94D5-4BF9-8A50-7BD9929A0850}" From f617e86b71f71267b5ffc31aafb46c7ba83ee9e7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 21:29:20 -0800 Subject: [PATCH 537/937] fixed incorrect assert --- tests/Makefile | 2 +- tests/fullbench.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Makefile b/tests/Makefile index c10d66f53..f24d5cb7b 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -148,7 +148,7 @@ fullbench32: CPPFLAGS += -m32 $(FULLBENCHS) : CPPFLAGS += $(MULTITHREAD_CPP) -Wno-deprecated-declarations $(FULLBENCHS) : LDFLAGS += $(MULTITHREAD_LD) $(FULLBENCHS) : DEBUGFLAGS = -DNDEBUG # turn off assert() for speed measurements -$(FULLBENCHS) : DEBUGLEVEL = 0 # turn off assert() for speed measurements +$(FULLBENCHS) : DEBUGLEVEL ?= 0 # turn off assert() for speed measurements $(FULLBENCHS) : $(ZSTD_FILES) $(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c fullbench.c $(LINK.c) $^ -o $@$(EXT) diff --git a/tests/fullbench.c b/tests/fullbench.c index 320b0ed73..0776d4221 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -620,7 +620,7 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, # if 0 /* for tests */ ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_repcodeResolution, ZSTD_ps_enable); #endif - assert(8 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; + assert(12 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; (void)payload; return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, srcSize); From 61ac8311e0983d21b95d5ef8ac98477b348a806e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 16 Dec 2024 21:48:10 -0800 Subject: [PATCH 538/937] attempt to silence Visual Studio warning about fopen() --- tests/fullbench.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 0776d4221..e89a2b326 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -12,8 +12,9 @@ /*_************************************ * Includes **************************************/ -#include +#define _CRT_SECURE_NO_WARNINGS /* disable Visual warning that it doesn't like fopen() */ #define ZSTD_DISABLE_DEPRECATE_WARNINGS /* No deprecation warnings, we still bench some deprecated functions */ +#include #include "util.h" /* Compiler options, UTIL_GetFileSize */ #include /* malloc */ #include /* fprintf, fopen, ftello64 */ From d48e330ae10a4042b85122213b0add998d6598f6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 17 Dec 2024 14:24:29 -0800 Subject: [PATCH 539/937] change name to ZSTD_convertSequences*() --- lib/compress/zstd_compress.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 71e40bdc1..3c5cb209c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7103,7 +7103,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * @blockSize must be exactly correct. */ FORCE_INLINE_TEMPLATE size_t -ZSTD_transferSequencesOnly_wBlockDelim_internal(ZSTD_CCtx* cctx, +ZSTD_convertSequences_wBlockDelim_internal(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, @@ -7207,25 +7207,25 @@ typedef size_t (*ZSTD_transferSequencesOnly_f) (ZSTD_CCtx* cctx, int const repcodeResolution); static size_t -ZSTD_transferSequencesOnly_wBlockDelim(ZSTD_CCtx* cctx, +ZSTD_convertSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { - return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, + return ZSTD_convertSequences_wBlockDelim_internal(cctx, seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 0); } static size_t -ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, +ZSTD_convertSequences_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { - return ZSTD_transferSequencesOnly_wBlockDelim_internal(cctx, + return ZSTD_convertSequences_wBlockDelim_internal(cctx, seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 1); } @@ -7242,8 +7242,8 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, BYTE* op = (BYTE*)dst; int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable); const ZSTD_transferSequencesOnly_f transfer = cctx->appliedParams.validateSequences ? - ZSTD_transferSequencesOnly_wBlockDelim_andCheckSequences - : ZSTD_transferSequencesOnly_wBlockDelim; + ZSTD_convertSequences_wBlockDelim_andCheckSequences + : ZSTD_convertSequences_wBlockDelim; DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { From 95ad9e47ffa930d2facb5d2dd2de511bf8171e5d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 17 Dec 2024 17:25:57 -0800 Subject: [PATCH 540/937] added benchmark for ZSTD_convertBlockSequences_wBlockDelim() --- lib/compress/zstd_compress.c | 35 ++++++++-------- lib/compress/zstd_compress_internal.h | 16 +++++++ tests/fullbench.c | 60 +++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 17 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 3c5cb209c..c4f699eb0 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3240,12 +3240,6 @@ static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seq return litLenSum + matchLenSum; } -typedef struct { - U32 idx; /* Index in array of ZSTD_Sequence */ - U32 posInSequence; /* Position within sequence at idx */ - size_t posInSrc; /* Number of bytes given by sequences provided so far */ -} ZSTD_SequencePosition; - static size_t ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, @@ -7103,7 +7097,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * @blockSize must be exactly correct. */ FORCE_INLINE_TEMPLATE size_t -ZSTD_convertSequences_wBlockDelim_internal(ZSTD_CCtx* cctx, +ZSTD_convertBlockSequences_wBlockDelim_internal(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, @@ -7200,32 +7194,39 @@ ZSTD_convertSequences_wBlockDelim_internal(ZSTD_CCtx* cctx, return litConsumed; } -typedef size_t (*ZSTD_transferSequencesOnly_f) (ZSTD_CCtx* cctx, +/* for tests only */ +void CCTX_resetSeqStore(ZSTD_CCtx* cctx) +{ + cctx->seqStore.sequences = cctx->seqStore.sequencesStart; + cctx->seqStore.lit = cctx->seqStore.litStart; +} + +typedef size_t (*ZSTD_convertBlockSequences_f) (ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution); -static size_t -ZSTD_convertSequences_wBlockDelim(ZSTD_CCtx* cctx, +size_t +ZSTD_convertBlockSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { - return ZSTD_convertSequences_wBlockDelim_internal(cctx, + return ZSTD_convertBlockSequences_wBlockDelim_internal(cctx, seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 0); } static size_t -ZSTD_convertSequences_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, +ZSTD_convertBlockSequences_wBlockDelim_andCheckSequences(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, size_t blockSize, int const repcodeResolution) { - return ZSTD_convertSequences_wBlockDelim_internal(cctx, + return ZSTD_convertBlockSequences_wBlockDelim_internal(cctx, seqPos, inSeqs, nbSequences, blockSize, repcodeResolution, 1); } @@ -7241,9 +7242,9 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, ZSTD_SequencePosition seqPos = {0, 0, 0}; BYTE* op = (BYTE*)dst; int const repcodeResolution = (cctx->appliedParams.searchForExternalRepcodes == ZSTD_ps_enable); - const ZSTD_transferSequencesOnly_f transfer = cctx->appliedParams.validateSequences ? - ZSTD_convertSequences_wBlockDelim_andCheckSequences - : ZSTD_convertSequences_wBlockDelim; + const ZSTD_convertBlockSequences_f convertBlockSequences = cctx->appliedParams.validateSequences ? + ZSTD_convertBlockSequences_wBlockDelim_andCheckSequences + : ZSTD_convertBlockSequences_wBlockDelim; DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { @@ -7271,7 +7272,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, assert(blockSize <= remaining); ZSTD_resetSeqStore(&cctx->seqStore); - litConsumed = transfer(cctx, + litConsumed = convertBlockSequences(cctx, &seqPos, inSeqs, nbSequences, blockSize, diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 10bd8ca70..bbcf4a7d5 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1522,6 +1522,22 @@ size_t ZSTD_loadCEntropy(ZSTD_compressedBlockState_t* bs, void* workspace, 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 */ + size_t posInSrc; /* Number of bytes given by sequences provided so far */ +} ZSTD_SequencePosition; + +size_t +ZSTD_convertBlockSequences_wBlockDelim(ZSTD_CCtx* cctx, + ZSTD_SequencePosition* seqPos, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + size_t blockSize, + int const repcodeResolution); + +/* for tests only */ +void CCTX_resetSeqStore(ZSTD_CCtx* cctx); + /* ============================================================== * Private declarations * These prototypes shall only be called from within lib/compress diff --git a/tests/fullbench.c b/tests/fullbench.c index e89a2b326..c42c923c1 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -21,6 +21,7 @@ #include #include "mem.h" /* U32 */ +#include "compress/zstd_compress_internal.h" #ifndef ZSTD_DLL_IMPORT #include "zstd_internal.h" /* ZSTD_decodeSeqHeaders, ZSTD_blockHeaderSize, ZSTD_getcBlockSize, blockType_e, KB, MB */ #include "decompress/zstd_decompress_internal.h" /* ZSTD_DCtx struct */ @@ -627,6 +628,64 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, srcSize); } +static PrepResult prepConvertSequences(const void* src, size_t srcSize, int cLevel) +{ + PrepResult r = PREPRESULT_INIT; + size_t const prepCapacity = srcSize * 4; + void* prepBuffer = malloc(prepCapacity); + void* sequencesStart = (char*)prepBuffer + 2*sizeof(unsigned); + ZSTD_Sequence* const seqs = sequencesStart; + size_t const seqsCapacity = prepCapacity / sizeof(ZSTD_Sequence); + size_t totalNbSeqs, nbSeqs, blockSize=0; + ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_compressionLevel, cLevel); + totalNbSeqs = ZSTD_generateSequences(g_zcc, seqs, seqsCapacity, src, srcSize); + CONTROL(!ZSTD_isError(totalNbSeqs)); + /* find nb sequences in first block */ + { size_t n; + for (n=0; n Date: Tue, 17 Dec 2024 21:33:26 -0800 Subject: [PATCH 541/937] improved speed of the Sequences converter --- doc/zstd_manual.html | 36 +++-- lib/compress/zstd_compress.c | 209 ++++++++++---------------- lib/compress/zstd_compress_internal.h | 10 +- lib/zstd.h | 3 +- tests/Makefile | 6 +- tests/fullbench.c | 11 +- tests/fuzzer.c | 20 +-- 7 files changed, 116 insertions(+), 179 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 7cfeda22d..2c4c4b0e8 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1084,7 +1084,7 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); * * Note: This field is optional. ZSTD_generateSequences() will calculate the value of * 'rep', but repeat offsets do not necessarily need to be calculated from an external - * sequence provider's perspective. For example, ZSTD_compressSequences() does not + * sequence provider perspective. For example, ZSTD_compressSequences() does not * use this 'rep' field at all (as of now). */ } ZSTD_Sequence; @@ -1331,7 +1331,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr,
ZSTD_DEPRECATED("For debugging only, will be replaced by ZSTD_extractSequences()")
 ZSTDLIB_STATIC_API size_t
 ZSTD_generateSequences(ZSTD_CCtx* zc,
-           ZSTD_Sequence* outSeqs, size_t outSeqsSize,
+           ZSTD_Sequence* outSeqs, size_t outSeqsCapacity,
            const void* src, size_t srcSize);
 

WARNING: This function is meant for debugging and informational purposes ONLY! Its implementation is flawed, and it will be deleted in a future version. @@ -1345,7 +1345,7 @@ ZSTD_generateSequences(ZSTD_CCtx* zc, @param zc The compression context to be used for ZSTD_compress2(). Set any compression parameters you need on this context. @param outSeqs The output sequences buffer of size @p outSeqsSize - @param outSeqsSize The size of the output sequences buffer. + @param outSeqsCapacity The size of the output sequences buffer. ZSTD_sequenceBound(srcSize) is an upper bound on the number of sequences that can be generated. @param src The source buffer to generate sequences from of size @p srcSize. @@ -1392,11 +1392,17 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, the block size derived from the cctx, and sequences may be split. This is the default setting. If ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, the array of ZSTD_Sequence is expected to contain - block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. + valid block delimiters (defined in ZSTD_Sequence). Behavior is undefined if no block delimiters are provided. - If ZSTD_c_validateSequences == 0, this function will blindly accept the sequences provided. Invalid sequences cause undefined - behavior. If ZSTD_c_validateSequences == 1, then if sequence is invalid (see doc/zstd_compression_format.md for - specifics regarding offset/matchlength requirements) then the function will bail out and return an error. + When ZSTD_c_blockDelimiters == ZSTD_sf_explicitBlockDelimiters, it's possible to decide generating repcodes + using the advanced parameter ZSTD_c_repcodeResolution. Repcodes will improve compression ratio, though the benefit + can vary greatly depending on Sequences. On the other hand, repcode resolution is an expensive operation. + By default, it's disabled at low (<10) compression levels, and enabled above the threshold (>=10). + ZSTD_c_repcodeResolution makes it possible to directly manage this processing in either direction. + + If ZSTD_c_validateSequences == 0, this function blindly accepts the Sequences provided. Invalid Sequences cause undefined + behavior. If ZSTD_c_validateSequences == 1, then the function will detect invalid Sequences (see doc/zstd_compression_format.md for + specifics regarding offset/matchlength requirements) and then bail out and return an error. In addition to the two adjustable experimental params, there are other important cctx params. - ZSTD_c_minMatch MUST be set as less than or equal to the smallest match generated by the match finder. It has a minimum value of ZSTD_MINMATCH_MIN. @@ -1414,19 +1420,21 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx,

ZSTDLIB_STATIC_API size_t
 ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,
                       void* dst, size_t dstCapacity,
-                const ZSTD_Sequence* inSeqs, size_t inSeqsSize,
-                const void* literals, size_t litSize, size_t srcSize);
+                const ZSTD_Sequence* inSeqs, size_t nbSequences,
+                const void* literals, size_t litSize);
 

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), - aka all literals already extracted and laid out into a single continuous buffer. + aka all the literals, already extracted and laid out into a single continuous buffer. This can be useful if the process generating the sequences also happens to generate the buffer of literals, thus skipping an extraction + caching stage. - It's essentially a speed optimization when the right conditions are met, - but it also is restricted by the following limitations: + It's a speed optimization, useful when the right conditions are met, + but it also features the following limitations: - Only supports explicit delimiter mode - Not compatible with frame checksum, which must disabled - - Can fail when unable to compress sufficiently - Also, to be valid, @litSize must be equal to the sum of all @.litLength fields in @inSeqs. + - Does not write the content size in frame header + - If any block is incompressible, will fail and return an error + - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. + - the buffer @literals must be larger than @litSize by at least 8 bytes. @return : final compressed size, or a ZSTD error code.


diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c4f699eb0..70a9731bf 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -2207,7 +2207,7 @@ static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc, zc->appliedParams.fParams.contentSizeFlag = 0; DEBUGLOG(4, "pledged content size : %u ; flag : %u", (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag); - zc->blockSize = blockSize; + zc->blockSizeMax = blockSize; XXH64_reset(&zc->xxhState, 0); zc->stage = ZSTDcs_init; @@ -4293,8 +4293,8 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, lastBlock, 0 /* isPartition */); FORWARD_IF_ERROR(cSizeSingleBlock, "Compressing single block from splitBlock_internal() failed!"); DEBUGLOG(5, "ZSTD_compressBlock_splitBlock_internal: No splits"); - assert(zc->blockSize <= ZSTD_BLOCKSIZE_MAX); - assert(cSizeSingleBlock <= zc->blockSize + ZSTD_blockHeaderSize); + assert(zc->blockSizeMax <= ZSTD_BLOCKSIZE_MAX); + assert(cSizeSingleBlock <= zc->blockSizeMax + ZSTD_blockHeaderSize); return cSizeSingleBlock; } @@ -4328,7 +4328,7 @@ ZSTD_compressBlock_splitBlock_internal(ZSTD_CCtx* zc, dstCapacity -= cSizeChunk; cSize += cSizeChunk; *currSeqStore = *nextSeqStore; - assert(cSizeChunk <= zc->blockSize + ZSTD_blockHeaderSize); + assert(cSizeChunk <= zc->blockSizeMax + ZSTD_blockHeaderSize); } /* cRep and dRep may have diverged during the compression. * If so, we use the dRep repcodes for the next block. @@ -4580,7 +4580,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, const void* src, size_t srcSize, U32 lastFrameChunk) { - size_t blockSizeMax = cctx->blockSize; + size_t blockSizeMax = cctx->blockSizeMax; size_t remaining = srcSize; const BYTE* ip = (const BYTE*)src; BYTE* const ostart = (BYTE*)dst; @@ -4816,7 +4816,7 @@ static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx, src, (BYTE const*)src + srcSize); } - DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize); + DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSizeMax); { size_t const cSize = frame ? ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) : ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize, 0 /* frame */); @@ -6070,11 +6070,11 @@ size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel) static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx) { if (cctx->appliedParams.inBufferMode == ZSTD_bm_stable) { - return cctx->blockSize - cctx->stableIn_notConsumed; + return cctx->blockSizeMax - cctx->stableIn_notConsumed; } assert(cctx->appliedParams.inBufferMode == ZSTD_bm_buffered); { size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos; - if (hintInSize==0) hintInSize = cctx->blockSize; + if (hintInSize==0) hintInSize = cctx->blockSizeMax; return hintInSize; } } @@ -6162,7 +6162,7 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, } else { assert(zcs->appliedParams.inBufferMode == ZSTD_bm_stable); if ( (flushMode == ZSTD_e_continue) - && ( (size_t)(iend - ip) < zcs->blockSize) ) { + && ( (size_t)(iend - ip) < zcs->blockSizeMax) ) { /* can't compress a full block : stop here */ zcs->stableIn_notConsumed = (size_t)(iend - ip); ip = iend; /* pretend to have consumed input */ @@ -6181,7 +6181,7 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, size_t cSize; size_t oSize = (size_t)(oend-op); size_t const iSize = inputBuffered ? zcs->inBuffPos - zcs->inToCompress - : MIN((size_t)(iend - ip), zcs->blockSize); + : MIN((size_t)(iend - ip), zcs->blockSizeMax); if (oSize >= ZSTD_compressBound(iSize) || zcs->appliedParams.outBufferMode == ZSTD_bm_stable) cDst = op; /* compress into output buffer, to skip flush stage */ else @@ -6196,9 +6196,9 @@ static size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs, FORWARD_IF_ERROR(cSize, "%s", lastBlock ? "ZSTD_compressEnd failed" : "ZSTD_compressContinue failed"); zcs->frameEnded = lastBlock; /* prepare next block */ - zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize; + zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSizeMax; if (zcs->inBuffTarget > zcs->inBuffSize) - zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize; + zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSizeMax; DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u", (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize); if (!lastBlock) @@ -6413,7 +6413,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, /* for small input: avoid automatic flush on reaching end of block, since * it would require to add a 3-bytes null block to end frame */ - cctx->inBuffTarget = cctx->blockSize + (cctx->blockSize == pledgedSrcSize); + cctx->inBuffTarget = cctx->blockSizeMax + (cctx->blockSizeMax == pledgedSrcSize); } else { cctx->inBuffTarget = 0; } @@ -6951,7 +6951,7 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, size_t compressedSeqsSize; size_t cBlockSize; size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters, - cctx->blockSize, remaining, + cctx->blockSizeMax, remaining, inSeqs, inSeqsSize, seqPos); U32 const lastBlock = (blockSize == remaining); FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); @@ -7093,167 +7093,112 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, } /* - * seqPos must end on an explicit block delimiter - * @blockSize must be exactly correct. + * Note: Sequence validation functionality has been disabled (removed). + * This is helpful to find back simplicity, leading to performance. + * It may be re-inserted later. */ -FORCE_INLINE_TEMPLATE size_t -ZSTD_convertBlockSequences_wBlockDelim_internal(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, +size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, - size_t blockSize, - int const repcodeResolution, - int const checkSequences) + int const repcodeResolution) { - U32 idx = seqPos->idx; - U32 const startIdx = idx; Repcodes_t updatedRepcodes; - U32 dictSize = 0; - size_t startPosInSrc = seqPos->posInSrc; size_t litConsumed = 0; + size_t seqNb = 0; - DEBUGLOG(5, "ZSTD_transferSequencesOnly_wBlockDelim (blockSize = %zu)", blockSize); + DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences); - /* dictSize is useful to check offset within Sequence validation */ - if (checkSequences) { - if (cctx->cdict) { - dictSize = (U32)cctx->cdict->dictContentSize; - } else if (cctx->prefixDict.dict) { - dictSize = (U32)cctx->prefixDict.dictSize; - } - } + RETURN_ERROR_IF(nbSequences >= cctx->seqStore.maxNbSeq, externalSequences_invalid, + "Not enough memory allocated. Try adjusting ZSTD_c_minMatch."); ZSTD_memcpy(updatedRepcodes.rep, cctx->blockState.prevCBlock->rep, sizeof(Repcodes_t)); + /* check end condition */ + assert(nbSequences >= 1); + assert(inSeqs[nbSequences-1].matchLength == 0); + assert(inSeqs[nbSequences-1].offset == 0); + /* Convert Sequences from public format to internal format */ - for (; idx < nbSequences && (inSeqs[idx].matchLength != 0 || inSeqs[idx].offset != 0); ++idx) { - U32 const litLength = inSeqs[idx].litLength; - U32 const matchLength = inSeqs[idx].matchLength; + for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) { + U32 const litLength = inSeqs[seqNb].litLength; + U32 const matchLength = inSeqs[seqNb].matchLength; U32 offBase; if (!repcodeResolution) { - offBase = OFFSET_TO_OFFBASE(inSeqs[idx].offset); + offBase = OFFSET_TO_OFFBASE(inSeqs[seqNb].offset); } else { U32 const ll0 = (litLength == 0); - offBase = ZSTD_finalizeOffBase(inSeqs[idx].offset, updatedRepcodes.rep, ll0); + offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0); ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); } DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); - if (checkSequences) { - seqPos->posInSrc += litLength + matchLength; - FORWARD_IF_ERROR(ZSTD_validateSequence(offBase, matchLength, cctx->appliedParams.cParams.minMatch, - seqPos->posInSrc, - cctx->appliedParams.cParams.windowLog, dictSize, - ZSTD_hasExtSeqProd(&cctx->appliedParams)), - "Sequence validation failed"); - } - RETURN_ERROR_IF(idx - seqPos->idx >= cctx->seqStore.maxNbSeq, externalSequences_invalid, - "Not enough memory allocated. Try adjusting ZSTD_c_minMatch."); ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); litConsumed += litLength; } /* last sequence (only literals) */ - { size_t const lastLitLength = inSeqs[idx].litLength; - litConsumed += lastLitLength; - if (checkSequences) { - seqPos->posInSrc += lastLitLength; - /* blockSize must be exactly correct (checked before calling this function) */ - RETURN_ERROR_IF((seqPos->posInSrc - startPosInSrc) != blockSize, externalSequences_invalid, "mismatch between Sequences and specified blockSize"); - } else { - /* blockSize presumed exactly correct (checked before calling this function) */ - seqPos->posInSrc += blockSize; - } - } + litConsumed += inSeqs[nbSequences-1].litLength; /* If we skipped repcode search while parsing, we need to update repcodes now */ - assert(idx >= startIdx); - if (!repcodeResolution && idx != startIdx) { + if (!repcodeResolution && nbSequences > 1) { U32* const rep = updatedRepcodes.rep; - U32 lastSeqIdx = idx - 1; /* index of last non-block-delimiter sequence */ - if (lastSeqIdx >= startIdx + 2) { + if (nbSequences >= 4) { + U32 lastSeqIdx = (U32)nbSequences - 2; /* index of last full sequence */ rep[2] = inSeqs[lastSeqIdx - 2].offset; rep[1] = inSeqs[lastSeqIdx - 1].offset; rep[0] = inSeqs[lastSeqIdx].offset; - } else if (lastSeqIdx == startIdx + 1) { + } else if (nbSequences == 3) { rep[2] = rep[0]; - rep[1] = inSeqs[lastSeqIdx - 1].offset; - rep[0] = inSeqs[lastSeqIdx].offset; + rep[1] = inSeqs[0].offset; + rep[0] = inSeqs[1].offset; } else { - assert(lastSeqIdx == startIdx); + assert(nbSequences == 2); rep[2] = rep[1]; rep[1] = rep[0]; - rep[0] = inSeqs[lastSeqIdx].offset; + rep[0] = inSeqs[0].offset; } } ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); - seqPos->idx = idx+1; return litConsumed; } -/* for tests only */ -void CCTX_resetSeqStore(ZSTD_CCtx* cctx) -{ - cctx->seqStore.sequences = cctx->seqStore.sequencesStart; - cctx->seqStore.lit = cctx->seqStore.litStart; -} - typedef size_t (*ZSTD_convertBlockSequences_f) (ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, const ZSTD_Sequence* const inSeqs, size_t nbSequences, - size_t blockSize, int const repcodeResolution); -size_t -ZSTD_convertBlockSequences_wBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, - const ZSTD_Sequence* const inSeqs, size_t nbSequences, - size_t blockSize, - int const repcodeResolution) +static size_t getNbSequencesFor1Block(const ZSTD_Sequence* seqs, size_t nbSeqs) { - return ZSTD_convertBlockSequences_wBlockDelim_internal(cctx, - seqPos, inSeqs, nbSequences, blockSize, - repcodeResolution, 0); + size_t n; + assert(seqs); + for (n=0; nappliedParams.searchForExternalRepcodes == ZSTD_ps_enable); - const ZSTD_convertBlockSequences_f convertBlockSequences = cctx->appliedParams.validateSequences ? - ZSTD_convertBlockSequences_wBlockDelim_andCheckSequences - : ZSTD_convertBlockSequences_wBlockDelim; - - DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); - if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { - RETURN_ERROR(GENERIC, "This mode is only compatible with explicit delimiters"); - } assert(cctx->appliedParams.searchForExternalRepcodes != ZSTD_ps_auto); + DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals_internal: nbSeqs=%zu, litSize=%zu", nbSequences, litSize); + RETURN_ERROR_IF(nbSequences == 0, externalSequences_invalid, "Requires at least 1 end-of-block"); + /* Special case: empty frame */ - if (remaining == 0) { + if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) { U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1); RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header"); MEM_writeLE32(op, cBlockHeader24); @@ -7262,23 +7207,21 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, cSize += ZSTD_blockHeaderSize; } - while (remaining) { + while (nbSequences) { size_t compressedSeqsSize, cBlockSize, litConsumed; - size_t blockSize = determine_blockSize(cctx->appliedParams.blockDelimiters, - cctx->blockSize, remaining, - inSeqs, nbSequences, seqPos); - U32 const lastBlock = (blockSize == remaining); - FORWARD_IF_ERROR(blockSize, "Error while trying to determine block size"); - assert(blockSize <= remaining); + size_t nbBlockSeqs = getNbSequencesFor1Block(inSeqs, nbSequences); + U32 const lastBlock = (nbBlockSeqs == nbSequences); + FORWARD_IF_ERROR(nbBlockSeqs, "Error while trying to determine nb of sequences for a block"); + assert(nbBlockSeqs <= nbSequences); ZSTD_resetSeqStore(&cctx->seqStore); - litConsumed = convertBlockSequences(cctx, - &seqPos, - inSeqs, nbSequences, - blockSize, + litConsumed = ZSTD_convertBlockSequences(cctx, + inSeqs, nbBlockSeqs, repcodeResolution); FORWARD_IF_ERROR(litConsumed, "Bad sequence conversion"); RETURN_ERROR_IF(litConsumed > litSize, externalSequences_invalid, "discrepancy between literals buffer and Sequences"); + inSeqs += nbBlockSeqs; + nbSequences -= nbBlockSeqs; /* Note: when blockSize is very small, other variant send it uncompressed. * Here, we still send the sequences, because we don't have the original source to send it uncompressed. @@ -7286,16 +7229,18 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, * but that's complex and costly memory intensive, which goes against the objectives of this variant. */ RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); - compressedSeqsSize = ZSTD_entropyCompressSeqStore_wExtLitBuffer( + + compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal( op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, literals, litConsumed, - blockSize, &cctx->seqStore, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, &cctx->appliedParams, cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, cctx->bmi2); 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; DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); litSize -= litConsumed; literals = (const char*)literals + litConsumed; @@ -7331,7 +7276,6 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, break; } else { op += cBlockSize; - remaining -= blockSize; dstCapacity -= cBlockSize; cctx->isFirstBlock = 0; } @@ -7347,7 +7291,7 @@ size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* literals, size_t litSize, size_t srcSize) + const void* literals, size_t litSize) { BYTE* op = (BYTE*)dst; size_t cSize = 0; @@ -7355,15 +7299,18 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Transparent initialization stage, same as compressStream2() */ DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); assert(cctx != NULL); - FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed"); + FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_continue, ZSTD_CONTENTSIZE_UNKNOWN), "CCtx initialization failed"); + if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { + RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters"); + } if (cctx->appliedParams.fParams.checksumFlag) { - RETURN_ERROR(frameParameter_unsupported, "this mode is incompatible with frame checksum"); + RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum"); } /* Begin writing output, starting with frame header */ { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, - &cctx->appliedParams, srcSize, cctx->dictID); + &cctx->appliedParams, ZSTD_CONTENTSIZE_UNKNOWN, cctx->dictID); op += frameHeaderSize; assert(frameHeaderSize <= dstCapacity); dstCapacity -= frameHeaderSize; @@ -7374,7 +7321,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, { size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx, op, dstCapacity, inSeqs, inSeqsSize, - literals, litSize, srcSize); + literals, litSize); FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!"); cSize += cBlocksSize; assert(cBlocksSize <= dstCapacity); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index bbcf4a7d5..2d4ecc89f 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -484,7 +484,7 @@ struct ZSTD_CCtx_s { size_t dictContentSize; ZSTD_cwksp workspace; /* manages buffer for dynamic allocations */ - size_t blockSize; + size_t blockSizeMax; unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */ unsigned long long consumedSrcSize; unsigned long long producedCSize; @@ -1528,15 +1528,11 @@ typedef struct { size_t posInSrc; /* Number of bytes given by sequences provided so far */ } ZSTD_SequencePosition; -size_t -ZSTD_convertBlockSequences_wBlockDelim(ZSTD_CCtx* cctx, - ZSTD_SequencePosition* seqPos, +/* for benchmark */ +size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, - size_t blockSize, int const repcodeResolution); -/* for tests only */ -void CCTX_resetSeqStore(ZSTD_CCtx* cctx); /* ============================================================== * Private declarations diff --git a/lib/zstd.h b/lib/zstd.h index 68e78b3ca..3fb02619c 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1675,6 +1675,7 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * but it also features the following limitations: * - Only supports explicit delimiter mode * - Not compatible with frame checksum, which must disabled + * - Does not write the content size in frame header * - If any block is incompressible, will fail and return an error * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. * - the buffer @literals must be larger than @litSize by at least 8 bytes. @@ -1684,7 +1685,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize, size_t srcSize); + const void* literals, size_t litSize); /*! ZSTD_writeSkippableFrame() : diff --git a/tests/Makefile b/tests/Makefile index f24d5cb7b..982181de8 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -26,6 +26,9 @@ export ZSTD_LEGACY_SUPPORT DEBUGLEVEL ?= 2 export DEBUGLEVEL # transmit value to sub-makefiles +.PHONY: default +default: fullbench + LIBZSTD_MK_DIR := ../lib include $(LIBZSTD_MK_DIR)/libzstd.mk @@ -78,9 +81,6 @@ FUZZERTEST ?= -T200s ZSTDRTTEST = --test-large-data DECODECORPUS_TESTTIME ?= -T30 -.PHONY: default -default: fullbench - .PHONY: all all: fullbench fuzzer zstreamtest paramgrill datagen decodecorpus roundTripCrash poolTests diff --git a/tests/fullbench.c b/tests/fullbench.c index c42c923c1..3f5044c71 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -623,9 +623,9 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_repcodeResolution, ZSTD_ps_enable); #endif assert(12 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; - (void)payload; + (void)payload; (void)srcSize; - return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, srcSize); + return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals); } static PrepResult prepConvertSequences(const void* src, size_t srcSize, int cLevel) @@ -669,22 +669,21 @@ local_convertSequences(const void* input, size_t inputSize, void* dst, size_t dstCapacity, void* payload) { - ZSTD_SequencePosition seqPos = { 0, 0 , 0 }; const char* ip = input; size_t const blockSize = MEM_read32(ip); size_t const nbSeqs = MEM_read32(ip+=4); const ZSTD_Sequence* seqs = (const ZSTD_Sequence*)(const void*)(ip+=4); ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); - CCTX_resetSeqStore(g_zcc); + ZSTD_resetSeqStore(&g_zcc->seqStore); ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters); # if 0 /* for tests */ ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_repcodeResolution, ZSTD_ps_enable); #endif assert(8 + nbSeqs * sizeof(ZSTD_Sequence) == inputSize); (void)inputSize; (void)dst; (void)dstCapacity; - (void)payload; + (void)payload; (void)blockSize; - return ZSTD_convertBlockSequences_wBlockDelim(g_zcc, &seqPos, seqs, nbSeqs, blockSize, 0); + return ZSTD_convertBlockSequences(g_zcc, seqs, nbSeqs, 0); } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index b20031708..09572e909 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3909,35 +3909,21 @@ static int basicUnitTests(U32 const seed, double compressibility) FUZ_transferLiterals(litBuffer, decompressSize, CNBuffer, srcSize, seqs, nbSeqs); /* not enough literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: not enough literals provided\n"); goto _output_error; } /* too many literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: too many literals provided\n"); goto _output_error; } - /* too short srcSize: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize, srcSize-1); - if (!ZSTD_isError(compressedSize)) { - DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too short\n"); - goto _output_error; - } - - /* too large srcSize: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize, srcSize+1); - if (!ZSTD_isError(compressedSize)) { - DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too short\n"); - goto _output_error; - } - /* correct amount of literals: should compress successfully */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize); if (ZSTD_isError(compressedSize)) { DISPLAY("Error in ZSTD_compressSequencesAndLiterals()\n"); goto _output_error; From b7b4e8634786024499dd42d479a2be3a2edae92c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 17 Dec 2024 22:08:43 -0800 Subject: [PATCH 542/937] fixed minor conversion warning --- lib/compress/zstd_compress.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 70a9731bf..867e7fbf1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7299,7 +7299,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Transparent initialization stage, same as compressStream2() */ DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); assert(cctx != NULL); - FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_continue, ZSTD_CONTENTSIZE_UNKNOWN), "CCtx initialization failed"); + FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_continue, 0), "CCtx initialization failed"); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters"); @@ -7350,7 +7350,6 @@ size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output) return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush); } - size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output) { ZSTD_inBuffer input = inBuffer_forEndFlush(zcs); From ad023b392fc5081f53ebc30f68d6e8dfda256104 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 17 Dec 2024 22:27:09 -0800 Subject: [PATCH 543/937] fixed minor error in one benchmark scenario --- tests/fullbench.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 3f5044c71..9505110ec 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -659,7 +659,7 @@ static PrepResult prepConvertSequences(const void* src, size_t srcSize, int cLev MEM_write32((char*)prepBuffer+4, (U32)nbSeqs); memcpy(seqs + nbSeqs, src, srcSize); r.prepBuffer = prepBuffer; - r.prepSize = 8 + sizeof(ZSTD_Sequence)*nbSeqs + srcSize; + r.prepSize = 8 + sizeof(ZSTD_Sequence) * nbSeqs; r.fixedOrigSize = blockSize; return r; } From 0a54f6f288bab194e1c4edcd03cedc8d084c2d6f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 07:26:38 -0800 Subject: [PATCH 544/937] ZSTD_compressSequencesAndLiterals requires srcSize as parameter this makes it possible to adjust windowSize to its tightest. --- doc/zstd_manual.html | 2 +- lib/compress/zstd_compress.c | 6 +++--- lib/zstd.h | 3 +-- tests/fullbench.c | 8 ++++---- tests/fuzzer.c | 6 +++--- 5 files changed, 12 insertions(+), 13 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 2c4c4b0e8..a50dd3c5d 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1421,7 +1421,7 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize); + const void* literals, size_t litSize, size_t srcSize);

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), aka all the literals, already extracted and laid out into a single continuous buffer. diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 867e7fbf1..655adf34b 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7291,7 +7291,7 @@ size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* literals, size_t litSize) + const void* literals, size_t litSize, size_t srcSize) { BYTE* op = (BYTE*)dst; size_t cSize = 0; @@ -7299,7 +7299,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Transparent initialization stage, same as compressStream2() */ DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); assert(cctx != NULL); - FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_continue, 0), "CCtx initialization failed"); + FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed"); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters"); @@ -7310,7 +7310,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Begin writing output, starting with frame header */ { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, - &cctx->appliedParams, ZSTD_CONTENTSIZE_UNKNOWN, cctx->dictID); + &cctx->appliedParams, srcSize, cctx->dictID); op += frameHeaderSize; assert(frameHeaderSize <= dstCapacity); dstCapacity -= frameHeaderSize; diff --git a/lib/zstd.h b/lib/zstd.h index 3fb02619c..68e78b3ca 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1675,7 +1675,6 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * but it also features the following limitations: * - Only supports explicit delimiter mode * - Not compatible with frame checksum, which must disabled - * - Does not write the content size in frame header * - If any block is incompressible, will fail and return an error * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. * - the buffer @literals must be larger than @litSize by at least 8 bytes. @@ -1685,7 +1684,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize); + const void* literals, size_t litSize, size_t srcSize); /*! ZSTD_writeSkippableFrame() : diff --git a/tests/fullbench.c b/tests/fullbench.c index 9505110ec..8601af769 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -608,8 +608,8 @@ static PrepResult prepSequencesAndLiterals(const void* src, size_t srcSize, int static size_t local_compressSequencesAndLiterals(const void* input, size_t inputSize, - void* dst, size_t dstCapacity, - void* payload) + void* dst, size_t dstCapacity, + void* payload) { const char* ip = input; size_t srcSize = MEM_read32(ip); @@ -623,9 +623,9 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_repcodeResolution, ZSTD_ps_enable); #endif assert(12 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; - (void)payload; (void)srcSize; + (void)payload; - return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals); + return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, srcSize); } static PrepResult prepConvertSequences(const void* src, size_t srcSize, int cLevel) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 09572e909..4901376ff 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3909,21 +3909,21 @@ static int basicUnitTests(U32 const seed, double compressibility) FUZ_transferLiterals(litBuffer, decompressSize, CNBuffer, srcSize, seqs, nbSeqs); /* not enough literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1, srcSize); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: not enough literals provided\n"); goto _output_error; } /* too many literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1, srcSize); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: too many literals provided\n"); goto _output_error; } /* correct amount of literals: should compress successfully */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize); if (ZSTD_isError(compressedSize)) { DISPLAY("Error in ZSTD_compressSequencesAndLiterals()\n"); goto _output_error; From a80f55f47d7d4076c19a000459b88e28e8c95eee Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 07:38:14 -0800 Subject: [PATCH 545/937] added a test for ZSTD_compressSequencesAndLiterals checks that srcSize is present in the frame header and bounds the window size. --- tests/fuzzer.c | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 4901376ff..7907dbfad 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3880,7 +3880,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "test%3i : ZSTD_compressSequencesAndLiterals : ", testNb++); { - const size_t srcSize = 500 KB; + const size_t srcSize = 497000; const BYTE* const src = (BYTE*)CNBuffer; BYTE* const dst = (BYTE*)compressedBuffer; const size_t dstCapacity = ZSTD_compressBound(srcSize); @@ -3929,6 +3929,21 @@ static int basicUnitTests(U32 const seed, double compressibility) goto _output_error; } } + { ZSTD_frameHeader zfh; + size_t const zfhStatus = ZSTD_getFrameHeader(&zfh, dst, compressedSize); + if (zfhStatus != 0) { + DISPLAY("Error reading frame header\n"); + goto _output_error; + } + if (zfh.frameContentSize != srcSize) { + DISPLAY("Error: ZSTD_compressSequencesAndLiterals() did not report srcSize in the frame header\n"); + goto _output_error; + } + if (zfh.windowSize > srcSize) { + DISPLAY("Error: ZSTD_compressSequencesAndLiterals() did not resized window size to smaller contentSize\n"); + goto _output_error; + } + } { size_t const dSize = ZSTD_decompress(decompressBuffer, decompressSize, dst, compressedSize); if (ZSTD_isError(dSize)) { DISPLAY("Error during decompression of frame produced by ZSTD_compressSequencesAndLiterals()\n"); From b339efff2bc9d11ce091bca62328c1884a38b5f3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 09:45:28 -0800 Subject: [PATCH 546/937] add dedicated error code for special case ZSTD_compressSequencesAndLiterals() cannot produce an uncompressed block --- doc/zstd_manual.html | 1 - lib/common/error_private.c | 1 + lib/compress/zstd_compress.c | 2 +- lib/zstd_errors.h | 1 + 4 files changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index a50dd3c5d..30908e0aa 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1431,7 +1431,6 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, but it also features the following limitations: - Only supports explicit delimiter mode - Not compatible with frame checksum, which must disabled - - Does not write the content size in frame header - If any block is incompressible, will fail and return an error - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - the buffer @literals must be larger than @litSize by at least 8 bytes. diff --git a/lib/common/error_private.c b/lib/common/error_private.c index 075fc5ef4..7e7f24f67 100644 --- a/lib/common/error_private.c +++ b/lib/common/error_private.c @@ -40,6 +40,7 @@ const char* ERR_getErrorString(ERR_enum code) case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory : unsupported"; case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max Symbol Value : too large"; case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small"; + case PREFIX(cannotProduce_uncompressedBlock): return "This mode cannot generate an uncompressed block"; case PREFIX(stabilityCondition_notRespected): return "pledged buffer stability condition is not respected"; case PREFIX(dictionary_corrupted): return "Dictionary is corrupted"; case PREFIX(dictionary_wrong): return "Dictionary mismatch"; diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 655adf34b..d5adeb68e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7254,7 +7254,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, * but it's complex, and memory hungry, killing the purpose of this variant. * Current outcome: generate an error code. */ - RETURN_ERROR(dstSize_tooSmall, "Data is not compressible"); /* note: error code could be clearer */ + RETURN_ERROR(cannotProduce_uncompressedBlock, "ZSTD_compressSequencesAndLiterals cannot generate an uncompressed block"); } else { U32 cBlockHeader; assert(compressedSeqsSize > 1); /* no RLE */ diff --git a/lib/zstd_errors.h b/lib/zstd_errors.h index 20e488f15..8ebc95cbb 100644 --- a/lib/zstd_errors.h +++ b/lib/zstd_errors.h @@ -76,6 +76,7 @@ typedef enum { ZSTD_error_tableLog_tooLarge = 44, ZSTD_error_maxSymbolValue_tooLarge = 46, ZSTD_error_maxSymbolValue_tooSmall = 48, + ZSTD_error_cannotProduce_uncompressedBlock = 49, ZSTD_error_stabilityCondition_notRespected = 50, ZSTD_error_stage_wrong = 60, ZSTD_error_init_missing = 62, From ab0f1798e8ec85dc03d39412513c84a5ef5539ff Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 14:41:33 -0800 Subject: [PATCH 547/937] ensure that srcSize is controlled --- lib/compress/zstd_compress.c | 89 +++++++++++++++++++++--------------- tests/fullbench.c | 3 +- tests/fuzzer.c | 14 ++++++ 3 files changed, 68 insertions(+), 38 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d5adeb68e..5ef7337cc 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7093,16 +7093,16 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, } /* + * @return: 0 on success, or an error code. * Note: Sequence validation functionality has been disabled (removed). - * This is helpful to find back simplicity, leading to performance. + * This is helpful to generate a lean main pipeline, improving performance. * It may be re-inserted later. */ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, - int const repcodeResolution) + int repcodeResolution) { Repcodes_t updatedRepcodes; - size_t litConsumed = 0; size_t seqNb = 0; DEBUGLOG(5, "ZSTD_convertBlockSequences (nbSequences = %zu)", nbSequences); @@ -7133,12 +7133,8 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); - litConsumed += litLength; } - /* last sequence (only literals) */ - litConsumed += inSeqs[nbSequences-1].litLength; - /* If we skipped repcode search while parsing, we need to update repcodes now */ if (!repcodeResolution && nbSequences > 1) { U32* const rep = updatedRepcodes.rep; @@ -7162,24 +7158,40 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); - return litConsumed; + return 0; } -typedef size_t (*ZSTD_convertBlockSequences_f) (ZSTD_CCtx* cctx, - const ZSTD_Sequence* const inSeqs, size_t nbSequences, - int const repcodeResolution); +typedef struct { + size_t nbSequences; + size_t blockSize; + size_t litSize; +} BlockSummary; -static size_t getNbSequencesFor1Block(const ZSTD_Sequence* seqs, size_t nbSeqs) +static BlockSummary get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { + size_t blockSize = 0; + size_t litSize = 0; size_t n; assert(seqs); for (n=0; nappliedParams.searchForExternalRepcodes == ZSTD_ps_enable); @@ -7208,31 +7221,32 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, } while (nbSequences) { - size_t compressedSeqsSize, cBlockSize, litConsumed; - size_t nbBlockSeqs = getNbSequencesFor1Block(inSeqs, nbSequences); - U32 const lastBlock = (nbBlockSeqs == nbSequences); - FORWARD_IF_ERROR(nbBlockSeqs, "Error while trying to determine nb of sequences for a block"); - assert(nbBlockSeqs <= nbSequences); + size_t compressedSeqsSize, cBlockSize, conversionStatus; + BlockSummary const block = get1BlockSummary(inSeqs, nbSequences); + U32 const lastBlock = (block.nbSequences == nbSequences); + 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"); ZSTD_resetSeqStore(&cctx->seqStore); - litConsumed = ZSTD_convertBlockSequences(cctx, - inSeqs, nbBlockSeqs, + conversionStatus = ZSTD_convertBlockSequences(cctx, + inSeqs, block.nbSequences, repcodeResolution); - FORWARD_IF_ERROR(litConsumed, "Bad sequence conversion"); - RETURN_ERROR_IF(litConsumed > litSize, externalSequences_invalid, "discrepancy between literals buffer and Sequences"); - inSeqs += nbBlockSeqs; - nbSequences -= nbBlockSeqs; + FORWARD_IF_ERROR(conversionStatus, "Bad sequence conversion"); + inSeqs += block.nbSequences; + nbSequences -= block.nbSequences; + remaining -= block.blockSize; /* Note: when blockSize is very small, other variant send it uncompressed. * Here, we still send the sequences, because we don't have the original source to send it uncompressed. - * One could imagine it possible to reproduce the source from the sequences, - * but that's complex and costly memory intensive, which goes against the objectives of this variant. */ + * One could imagine in theory reproducing the source from the sequences, + * but that's complex and costly memory intensive, and goes against the objectives of this variant. */ RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); compressedSeqsSize = ZSTD_entropyCompressSeqStore_internal( op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, - literals, litConsumed, + literals, block.litSize, &cctx->seqStore, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, &cctx->appliedParams, @@ -7242,8 +7256,8 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, /* note: the spec forbids for any compressed block to be larger than maximum block size */ if (compressedSeqsSize > cctx->blockSizeMax) compressedSeqsSize = 0; DEBUGLOG(5, "Compressed sequences size: %zu", compressedSeqsSize); - litSize -= litConsumed; - literals = (const char*)literals + litConsumed; + litSize -= block.litSize; + literals = (const char*)literals + block.litSize; /* Note: difficult to check source for RLE block when only Literals are provided, * but it could be considered from analyzing the sequence directly */ @@ -7271,18 +7285,19 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, } cSize += cBlockSize; + op += cBlockSize; + dstCapacity -= cBlockSize; + cctx->isFirstBlock = 0; + DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity); if (lastBlock) { + assert(nbSequences == 0); break; - } else { - op += cBlockSize; - dstCapacity -= cBlockSize; - cctx->isFirstBlock = 0; } - DEBUGLOG(5, "cSize running total: %zu (remaining dstCapacity=%zu)", cSize, dstCapacity); } RETURN_ERROR_IF(litSize != 0, externalSequences_invalid, "literals must be entirely and exactly consumed"); + RETURN_ERROR_IF(remaining != 0, externalSequences_invalid, "Sequences must represent a total of exactly srcSize=%zu", srcSize); DEBUGLOG(4, "cSize final total: %zu", cSize); return cSize; } @@ -7321,7 +7336,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, { size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx, op, dstCapacity, inSeqs, inSeqsSize, - literals, litSize); + literals, litSize, srcSize); FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!"); cSize += cBlocksSize; assert(cBlocksSize <= dstCapacity); diff --git a/tests/fullbench.c b/tests/fullbench.c index 8601af769..4ac686a4d 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -683,7 +683,8 @@ local_convertSequences(const void* input, size_t inputSize, (void)dst; (void)dstCapacity; (void)payload; (void)blockSize; - return ZSTD_convertBlockSequences(g_zcc, seqs, nbSeqs, 0); + (void)ZSTD_convertBlockSequences(g_zcc, seqs, nbSeqs, 0); + return nbSeqs; } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 7907dbfad..335fbd5c4 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3922,6 +3922,20 @@ static int basicUnitTests(U32 const seed, double compressibility) goto _output_error; } + /* srcSize too large: must fail */ + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize+1); + if (!ZSTD_isError(compressedSize)) { + DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too large\n"); + goto _output_error; + } + + /* srcSize too small: must fail */ + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize-1); + if (!ZSTD_isError(compressedSize)) { + DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too small\n"); + goto _output_error; + } + /* correct amount of literals: should compress successfully */ compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize); if (ZSTD_isError(compressedSize)) { From 52a9bc6fca23bf0f9d51be0fe97a525db85aa12b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 15:00:12 -0800 Subject: [PATCH 548/937] fixed minor error in preparation of one fullbench scenario --- tests/fullbench.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 4ac686a4d..05d6bf027 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -594,7 +594,7 @@ static PrepResult prepSequencesAndLiterals(const void* src, size_t srcSize, int for (n=0; n Date: Thu, 19 Dec 2024 15:39:57 -0800 Subject: [PATCH 549/937] add a check, to return an error if Sequence validation is enabled since ZSTD_compressSequencesAndLiterals() doesn't support it. --- doc/zstd_manual.html | 3 ++- lib/compress/zstd_compress.c | 3 +++ lib/zstd.h | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 30908e0aa..dd6f9d7ab 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1430,7 +1430,8 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, It's a speed optimization, useful when the right conditions are met, but it also features the following limitations: - Only supports explicit delimiter mode - - Not compatible with frame checksum, which must disabled + - Currently does not support Sequences validation (so input Sequences are trusted) + - Not compatible with frame checksum, which must be disabled - If any block is incompressible, will fail and return an error - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - the buffer @literals must be larger than @litSize by at least 8 bytes. diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 5ef7337cc..b5831650f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7319,6 +7319,9 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters"); } + if (cctx->appliedParams.validateSequences) { + RETURN_ERROR(parameter_unsupported, "This mode is not compatible with Sequence validation"); + } if (cctx->appliedParams.fParams.checksumFlag) { RETURN_ERROR(frameParameter_unsupported, "this mode is not compatible with frame checksum"); } diff --git a/lib/zstd.h b/lib/zstd.h index 68e78b3ca..feb1ae17a 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1674,7 +1674,8 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * It's a speed optimization, useful when the right conditions are met, * but it also features the following limitations: * - Only supports explicit delimiter mode - * - Not compatible with frame checksum, which must disabled + * - Currently does not support Sequences validation (so input Sequences are trusted) + * - Not compatible with frame checksum, which must be disabled * - If any block is incompressible, will fail and return an error * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. * - the buffer @literals must be larger than @litSize by at least 8 bytes. From b7a9e69d8dc8b61be9d341a4e7a56350fb1e545e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 15:55:11 -0800 Subject: [PATCH 550/937] added parameter litCapacity to ZSTD_compressSequencesAndLiterals() to enforce the litCapacity >= litSize+8 condition. --- doc/zstd_manual.html | 6 ++++-- lib/compress/zstd_compress.c | 12 ++++++++---- lib/zstd.h | 6 ++++-- tests/fullbench.c | 4 ++-- tests/fuzzer.c | 10 +++++----- 5 files changed, 23 insertions(+), 15 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index dd6f9d7ab..ecb2b622c 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1421,7 +1421,8 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize, size_t srcSize); + const void* literals, size_t litSize, size_t litCapacity, + size_t decompressedSize);

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), aka all the literals, already extracted and laid out into a single continuous buffer. @@ -1434,7 +1435,8 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, - Not compatible with frame checksum, which must be disabled - If any block is incompressible, will fail and return an error - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - - the buffer @literals must be larger than @litSize by at least 8 bytes. + - the buffer @literals must have a size @litCapacity which is larger than @litSize by at least 8 bytes. + - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. @return : final compressed size, or a ZSTD error code.


diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index b5831650f..b5e88325d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7306,7 +7306,8 @@ size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t inSeqsSize, - const void* literals, size_t litSize, size_t srcSize) + const void* literals, size_t litSize, size_t litCapacity, + size_t decompressedSize) { BYTE* op = (BYTE*)dst; size_t cSize = 0; @@ -7314,7 +7315,10 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Transparent initialization stage, same as compressStream2() */ DEBUGLOG(4, "ZSTD_compressSequencesAndLiterals (dstCapacity=%zu)", dstCapacity); assert(cctx != NULL); - FORWARD_IF_ERROR(ZSTD_CCtx_init_compressStream2(cctx, ZSTD_e_end, srcSize), "CCtx initialization failed"); + if (litCapacity < litSize) { + 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"); if (cctx->appliedParams.blockDelimiters == ZSTD_sf_noBlockDelimiters) { RETURN_ERROR(frameParameter_unsupported, "This mode is only compatible with explicit delimiters"); @@ -7328,7 +7332,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, /* Begin writing output, starting with frame header */ { size_t const frameHeaderSize = ZSTD_writeFrameHeader(op, dstCapacity, - &cctx->appliedParams, srcSize, cctx->dictID); + &cctx->appliedParams, decompressedSize, cctx->dictID); op += frameHeaderSize; assert(frameHeaderSize <= dstCapacity); dstCapacity -= frameHeaderSize; @@ -7339,7 +7343,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, { size_t const cBlocksSize = ZSTD_compressSequencesAndLiterals_internal(cctx, op, dstCapacity, inSeqs, inSeqsSize, - literals, litSize, srcSize); + literals, litSize, decompressedSize); FORWARD_IF_ERROR(cBlocksSize, "Compressing blocks failed!"); cSize += cBlocksSize; assert(cBlocksSize <= dstCapacity); diff --git a/lib/zstd.h b/lib/zstd.h index feb1ae17a..36668b85b 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1678,14 +1678,16 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * - Not compatible with frame checksum, which must be disabled * - If any block is incompressible, will fail and return an error * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - * - the buffer @literals must be larger than @litSize by at least 8 bytes. + * - the buffer @literals must have a size @litCapacity which is larger than @litSize by at least 8 bytes. + * - @decompressedSize must be correct, and correspond to the sum of all Sequences. Any discrepancy will generate an error. * @return : final compressed size, or a ZSTD error code. */ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize, size_t srcSize); + const void* literals, size_t litSize, size_t litCapacity, + size_t decompressedSize); /*! ZSTD_writeSkippableFrame() : diff --git a/tests/fullbench.c b/tests/fullbench.c index 05d6bf027..5683eca25 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -612,7 +612,7 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, void* payload) { const char* ip = input; - size_t srcSize = MEM_read32(ip); + size_t decompressedSize = MEM_read32(ip); size_t nbSeqs = MEM_read32(ip+=4); size_t nbLiterals = MEM_read32(ip+=4); const ZSTD_Sequence* seqs = (const ZSTD_Sequence*)(const void*)(ip+=4); @@ -625,7 +625,7 @@ local_compressSequencesAndLiterals(const void* input, size_t inputSize, assert(12 + nbSeqs * sizeof(ZSTD_Sequence) + nbLiterals == inputSize); (void)inputSize; (void)payload; - return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, srcSize); + return ZSTD_compressSequencesAndLiterals(g_zcc, dst, dstCapacity, seqs, nbSeqs, literals, nbLiterals, nbLiterals + 8, decompressedSize); } static PrepResult prepConvertSequences(const void* src, size_t srcSize, int cLevel) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 335fbd5c4..6d165aea4 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -3909,35 +3909,35 @@ static int basicUnitTests(U32 const seed, double compressibility) FUZ_transferLiterals(litBuffer, decompressSize, CNBuffer, srcSize, seqs, nbSeqs); /* not enough literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize-1, decompressSize, srcSize); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: not enough literals provided\n"); goto _output_error; } /* too many literals: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, src, litSize+1, decompressSize, srcSize); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: too many literals provided\n"); goto _output_error; } /* srcSize too large: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize+1); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, decompressSize, srcSize+1); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too large\n"); goto _output_error; } /* srcSize too small: must fail */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize-1); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, decompressSize, srcSize-1); if (!ZSTD_isError(compressedSize)) { DISPLAY("ZSTD_compressSequencesAndLiterals() should have failed: srcSize is too small\n"); goto _output_error; } /* correct amount of literals: should compress successfully */ - compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, srcSize); + compressedSize = ZSTD_compressSequencesAndLiterals(cctx, dst, dstCapacity, seqs, nbSeqs, litBuffer, litSize, decompressSize, srcSize); if (ZSTD_isError(compressedSize)) { DISPLAY("Error in ZSTD_compressSequencesAndLiterals()\n"); goto _output_error; From 522adc34eb83c9145dfe1be36412eefa642413e1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 19 Dec 2024 16:11:46 -0800 Subject: [PATCH 551/937] minor: use MEM_writeLE24() so that an empty frame needs only 3 bytes of dstCapacity. --- lib/compress/zstd_compress.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index b5e88325d..fcd8035fa 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7213,8 +7213,8 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, /* Special case: empty frame */ if ((nbSequences == 1) && (inSeqs[0].litLength == 0)) { U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1); - RETURN_ERROR_IF(dstCapacity<4, dstSize_tooSmall, "No room for empty frame block header"); - MEM_writeLE32(op, cBlockHeader24); + RETURN_ERROR_IF(dstCapacity<3, dstSize_tooSmall, "No room for empty frame block header"); + MEM_writeLE24(op, cBlockHeader24); op += ZSTD_blockHeaderSize; dstCapacity -= ZSTD_blockHeaderSize; cSize += ZSTD_blockHeaderSize; From 47cbfc87a9c7ecb5a9058ad8e55ba19dcaf6a861 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 20 Dec 2024 09:03:26 -0800 Subject: [PATCH 552/937] restore invocation of ZSTD_entropyCompressSeqStore() in the ZSTD_compressSequences() pipeline --- lib/compress/zstd_compress.c | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index fcd8035fa..3af69c1ae 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3015,7 +3015,7 @@ static size_t ZSTD_entropyCompressSeqStore_wExtLitBuffer( void* dst, size_t dstCapacity, const void* literals, size_t litSize, - size_t srcSize, + size_t blockSize, const SeqStore_t* seqStorePtr, const ZSTD_entropyCTables_t* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, @@ -3032,14 +3032,14 @@ ZSTD_entropyCompressSeqStore_wExtLitBuffer( /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block. * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block. */ - if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity)) { + if ((cSize == ERROR(dstSize_tooSmall)) & (blockSize <= dstCapacity)) { DEBUGLOG(4, "not enough dstCapacity (%zu) for ZSTD_entropyCompressSeqStore_internal()=> do not compress block", dstCapacity); return 0; /* block not compressed */ } FORWARD_IF_ERROR(cSize, "ZSTD_entropyCompressSeqStore_internal failed"); /* Check compressibility */ - { size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy); + { size_t const maxCSize = blockSize - ZSTD_minGain(blockSize, cctxParams->cParams.strategy); if (cSize >= maxCSize) return 0; /* block not compressed */ } DEBUGLOG(5, "ZSTD_entropyCompressSeqStore() cSize: %zu", cSize); @@ -6980,13 +6980,11 @@ ZSTD_compressSequences_internal(ZSTD_CCtx* cctx, } RETURN_ERROR_IF(dstCapacity < ZSTD_blockHeaderSize, dstSize_tooSmall, "not enough dstCapacity to write a new compressed block"); - compressedSeqsSize = ZSTD_entropyCompressSeqStore_wExtLitBuffer( - op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, - cctx->seqStore.litStart, (size_t)(cctx->seqStore.lit - cctx->seqStore.litStart), - blockSize, - &cctx->seqStore, + compressedSeqsSize = ZSTD_entropyCompressSeqStore(&cctx->seqStore, &cctx->blockState.prevCBlock->entropy, &cctx->blockState.nextCBlock->entropy, &cctx->appliedParams, + op + ZSTD_blockHeaderSize /* Leave space for block header */, dstCapacity - ZSTD_blockHeaderSize, + blockSize, cctx->tmpWorkspace, cctx->tmpWkspSize /* statically allocated in resetCCtx */, cctx->bmi2); FORWARD_IF_ERROR(compressedSeqsSize, "Compressing sequences of block failed"); From f0937b83d9a32cb2b59f99bbc4db717ae6e83c9b Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 20 Dec 2024 09:40:32 -0800 Subject: [PATCH 553/937] [cmake] Fix -z noexecstack portability Summary: Issue reported by @ryandesign and @MarcusCalhoun-Lopez. CMake doesn't support spaces in flags. This caused older versions of gcc to ignore the unknown flag "-z noexecstack" on MacOS since it was interpreted as a single flag, not two separate flags. Then, during compilation it was treated as "-z" "noexecstack", which was correctly forwarded to the linker. But the MacOS linker does not support `-z noexecstack` so compilation failed. The fix is to use `-Wl,-z,noexecstack`. This is never misinterpreted by a compiler. However, not all compilers support this syntax to forward flags to the linker. To fix this issue, we check if all the relevant `noexecstack` flags have been successfully set, and if they haven't we disable assembly. See also PR#4056 and PR#4061. I decided to go a different route because this is simpler. It might not successfully set these flags on some compilers, but in that case it also disables assembly, so they aren't required. Test Plan: ``` mkdir build-cmake cmake ../build/cmake/CMakeLists.txt make -j ``` See that the linker flag is successfully detected & that assembly is enabled. Run the same commands on MacOS which doesn't support `-Wl,-z,noexecstack` and see that everything compiles and that `LD_FLAG_WL_Z_NOEXECSTACK` and `ZSTD_HAS_NOEXECSTACK` are both false. --- .../CMakeModules/AddZstdCompilationFlags.cmake | 18 +++++++++++++++++- build/cmake/lib/CMakeLists.txt | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake index 153c51bae..5f381c656 100644 --- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake +++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake @@ -50,6 +50,10 @@ function(EnableCompilerFlag _flag _C _CXX _LD) endfunction() macro(ADD_ZSTD_COMPILATION_FLAGS) + # We set ZSTD_HAS_NOEXECSTACK if we are certain we've set all the required + # compiler flags to mark the stack as non-executable. + set(ZSTD_HAS_NOEXECSTACK false) + if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang" OR MINGW) #Not only UNIX but also WIN32 for MinGW # It's possible to select the exact standard used for compilation. # It's not necessary, but can be employed for specific purposes. @@ -75,10 +79,22 @@ macro(ADD_ZSTD_COMPILATION_FLAGS) endif () # Add noexecstack flags # LDFLAGS - EnableCompilerFlag("-z noexecstack" false false true) + EnableCompilerFlag("-Wl,-z,noexecstack" false false true) # CFLAGS & CXXFLAGS EnableCompilerFlag("-Qunused-arguments" true true false) EnableCompilerFlag("-Wa,--noexecstack" true true false) + # NOTE: Using 3 nested ifs because the variables are sometimes + # empty if the condition is false, and sometimes equal to false. + # This implicitly converts them to truthy values. There may be + # a better way to do this, but this reliably works. + if (${LD_FLAG_WL_Z_NOEXECSTACK}) + if (${C_FLAG_WA_NOEXECSTACK}) + if (${CXX_FLAG_WA_NOEXECSTACK}) + # We've succeeded in marking the stack as non-executable + set(ZSTD_HAS_NOEXECSTACK true) + endif() + endif() + endif() elseif (MSVC) # Add specific compilation flags for Windows Visual set(ACTIVATE_MULTITHREADED_COMPILATION "ON" CACHE BOOL "activate multi-threaded compilation (/MP flag)") diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 43b14d175..d07b1f5ff 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -39,7 +39,7 @@ file(GLOB DecompressSources ${LIBRARY_DIR}/decompress/*.c) if (MSVC) add_compile_options(-DZSTD_DISABLE_ASM) else () - if(CMAKE_SYSTEM_PROCESSOR MATCHES "amd64.*|AMD64.*|x86_64.*|X86_64.*") + if(CMAKE_SYSTEM_PROCESSOR MATCHES "amd64.*|AMD64.*|x86_64.*|X86_64.*" AND ${ZSTD_HAS_NOEXECSTACK}) set(DecompressSources ${DecompressSources} ${LIBRARY_DIR}/decompress/huf_decompress_amd64.S) else() add_compile_options(-DZSTD_DISABLE_ASM) From f8725e80cc6089ec21903e292a58a21d322e302b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 23 Dec 2024 18:42:51 -0800 Subject: [PATCH 554/937] added fuzzer test for compressSequencesAndLiterals() piggy-backing onto existing compressSequences() fuzzer test --- tests/fuzz/Makefile | 8 +-- tests/fuzz/sequence_compression_api.c | 83 ++++++++++++++++++++++++--- 2 files changed, 78 insertions(+), 13 deletions(-) diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index 1333675d0..a64d2d252 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -28,6 +28,9 @@ LIBZSTD_MK_DIR = ../../lib DEBUGLEVEL ?= 2 ZSTD_LEGACY_SUPPORT ?= 1 +.PHONY: default +default: all + include $(LIBZSTD_MK_DIR)/libzstd.mk PRGDIR = ../../programs @@ -101,10 +104,6 @@ FUZZ_RT_OBJ9 := $(FUZZ_RT_OBJ8:.c=.o) FUZZ_RT_OBJ10 := $(THIRD_PARTY_SEQ_PROD_OBJ) $(FUZZ_RT_OBJ9) FUZZ_ROUND_TRIP_OBJ := $(FUZZ_RT_OBJ10:.S=.o) -.PHONY: default all clean cleanall - -default: all - FUZZ_TARGETS := \ simple_round_trip \ stream_round_trip \ @@ -128,6 +127,7 @@ FUZZ_TARGETS := \ decompress_cross_format \ generate_sequences +.PHONY: all clean cleanall all: libregression.a $(FUZZ_TARGETS) rt_lib_common_%.o: $(LIB_SRCDIR)/common/%.c diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c index 5e5e1e604..32710afb9 100644 --- a/tests/fuzz/sequence_compression_api.c +++ b/tests/fuzz/sequence_compression_api.c @@ -155,7 +155,7 @@ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, if (mode == ZSTD_sf_explicitBlockDelimiters) { /* ensure that no sequence can be larger than one block */ literalsSizeLimit = MIN(literalsSizeLimit, blockSizeMax/2); - matchLengthMax = MIN(matchLengthMax, blockSizeMax/2); + matchLengthMax = MIN(matchLengthMax, (uint32_t)blockSizeMax/2); } while ( nbSeqGenerated < ZSTD_FUZZ_MAX_NBSEQ - 3 /* extra room for explicit delimiters */ @@ -171,7 +171,7 @@ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, if (bytesGenerated > ZSTD_FUZZ_GENERATED_SRC_MAXSIZE) { break; } - offsetBound = (bytesGenerated > windowSize) ? windowSize : bytesGenerated + (uint32_t)dictSize; + offsetBound = (bytesGenerated > windowSize) ? (uint32_t)windowSize : bytesGenerated + (uint32_t)dictSize; offset = FUZZ_dataProducer_uint32Range(producer, 1, offsetBound); if (dictSize > 0 && bytesGenerated <= windowSize) { /* Prevent match length from being such that it would be associated with an offset too large @@ -180,7 +180,7 @@ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, */ const size_t bytesToReachWindowSize = windowSize - bytesGenerated; if (bytesToReachWindowSize < ZSTD_MINMATCH_MIN) { - const uint32_t newOffsetBound = offsetBound > windowSize ? windowSize : offsetBound; + const uint32_t newOffsetBound = offsetBound > windowSize ? (uint32_t)windowSize : offsetBound; offset = FUZZ_dataProducer_uint32Range(producer, 1, newOffsetBound); } else { matchBound = MIN(matchLengthMax, (uint32_t)bytesToReachWindowSize); @@ -201,14 +201,14 @@ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, if (blockSize + seqSize > blockSizeMax) { /* reaching limit : must end block now */ const ZSTD_Sequence endBlock = {0, 0, 0, 0}; generatedSequences[nbSeqGenerated++] = endBlock; - blockSize = seqSize; + blockSize = (uint32_t)seqSize; } if (split) { const ZSTD_Sequence endBlock = {0, lastLits, 0, 0}; generatedSequences[nbSeqGenerated++] = endBlock; assert(lastLits <= seq.litLength); seq.litLength -= lastLits; - blockSize = seqSize - lastLits; + blockSize = (uint32_t)(seqSize - lastLits); } else { blockSize += seqSize; } @@ -227,10 +227,67 @@ static size_t generateRandomSequences(FUZZ_dataProducer_t* producer, return nbSeqGenerated; } +static size_t +transferLiterals(void* dst, size_t dstCapacity, const ZSTD_Sequence* seqs, size_t nbSeqs, const void* src, size_t srcSize) +{ + size_t n; + char* op = dst; + char* const oend = op + dstCapacity; + const char* ip = src; + const char* const iend = ip + srcSize; + for (n=0; n= 8); + return (size_t)(op - (char*)dst); +} + +static size_t roundTripTest_compressSequencesAndLiterals( + void* result, size_t resultCapacity, + void* compressed, size_t compressedCapacity, + const void* src, size_t srcSize, + const ZSTD_Sequence* seqs, size_t nbSeqs, + ZSTD_SequenceFormat_e mode) +{ + size_t const litCapacity = srcSize + 8; + void* literals = malloc(litCapacity); + size_t cSize, litSize; + + assert(literals); + litSize = transferLiterals(literals, litCapacity, seqs, nbSeqs, src, srcSize); + + cSize = ZSTD_compressSequencesAndLiterals(cctx, + compressed, compressedCapacity, + seqs, nbSeqs, + literals, litSize, litCapacity, srcSize); + if ( (ZSTD_getErrorCode(cSize) == ZSTD_error_dstSize_tooSmall) + && (mode == ZSTD_sf_explicitBlockDelimiters) ) { + /* Valid scenario : in explicit delimiter mode, + * it might be possible for the compressed size to outgrow dstCapacity. + * In which case, it's still a valid fuzzer scenario, + * but no roundtrip shall be possible */ + return 0; + } + /* round-trip */ + FUZZ_ZASSERT(cSize); + { size_t const dSize = ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize); + FUZZ_ZASSERT(dSize); + FUZZ_ASSERT_MSG(dSize == srcSize, "Incorrect regenerated size"); + FUZZ_ASSERT_MSG(!FUZZ_memcmp(src, result, srcSize), "Corruption!"); + return dSize; + } +} + static size_t roundTripTest(void* result, size_t resultCapacity, void* compressed, size_t compressedCapacity, const void* src, size_t srcSize, - const ZSTD_Sequence* seqs, size_t seqSize, + const ZSTD_Sequence* seqs, size_t nbSeqs, unsigned hasDict, ZSTD_SequenceFormat_e mode) { @@ -242,8 +299,16 @@ static size_t roundTripTest(void* result, size_t resultCapacity, FUZZ_ZASSERT(ZSTD_DCtx_refDDict(dctx, ddict)); } + { int blockMode; + /* compressSequencesAndLiterals() only supports explicitBlockDelimiters */ + FUZZ_ZASSERT(ZSTD_CCtx_getParameter(cctx, ZSTD_c_blockDelimiters, &blockMode)); + if (blockMode == ZSTD_sf_explicitBlockDelimiters) { + FUZZ_ZASSERT(roundTripTest_compressSequencesAndLiterals(result, resultCapacity, compressed, compressedCapacity, src, srcSize, seqs, nbSeqs, mode)); + } + } + cSize = ZSTD_compressSequences(cctx, compressed, compressedCapacity, - seqs, seqSize, + seqs, nbSeqs, src, srcSize); if ( (ZSTD_getErrorCode(cSize) == ZSTD_error_dstSize_tooSmall) && (mode == ZSTD_sf_explicitBlockDelimiters) ) { @@ -298,10 +363,10 @@ int LLVMFuzzerTestOneInput(const uint8_t* src, size_t size) ZSTD_CCtx_reset(cctx, ZSTD_reset_session_and_parameters); ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 0); ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, cLevel); - ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, wLog); + ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, (int)wLog); ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, ZSTD_MINMATCH_MIN); ZSTD_CCtx_setParameter(cctx, ZSTD_c_validateSequences, 1); - ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockDelimiters, mode); + ZSTD_CCtx_setParameter(cctx, ZSTD_c_blockDelimiters, (int)mode); ZSTD_CCtx_setParameter(cctx, ZSTD_c_forceAttachDict, ZSTD_dictForceAttach); if (!literalsBuffer) { From 7b294caf461a15d74e64389bde16d5c33fc3d0c8 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 23 Dec 2024 19:43:17 -0800 Subject: [PATCH 555/937] add one valid test case ZSTD_compressSequencesAndLiterals() may return a specific error code when data to compress is non-compressible. --- tests/fuzz/sequence_compression_api.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c index 32710afb9..21b6ac84e 100644 --- a/tests/fuzz/sequence_compression_api.c +++ b/tests/fuzz/sequence_compression_api.c @@ -16,6 +16,7 @@ */ #define ZSTD_STATIC_LINKING_ONLY +#include "zstd_errors.h" #include #include @@ -275,7 +276,12 @@ static size_t roundTripTest_compressSequencesAndLiterals( return 0; } /* round-trip */ - FUZZ_ZASSERT(cSize); + if (ZSTD_isError(cSize)) { + ZSTD_ErrorCode err = ZSTD_getErrorCode(cSize); + /* this specific error might happen as a result of data being uncompressible */ + if (err != ZSTD_error_cannotProduce_uncompressedBlock) + FUZZ_ZASSERT(cSize); + } { size_t const dSize = ZSTD_decompressDCtx(dctx, result, resultCapacity, compressed, cSize); FUZZ_ZASSERT(dSize); FUZZ_ASSERT_MSG(dSize == srcSize, "Incorrect regenerated size"); From 72ce56b527d1710dd2fa193ca0c22933da382f44 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 23 Dec 2024 21:15:50 -0800 Subject: [PATCH 556/937] fixed another invalid scenario compressSequencesAndLiterals() doesn't support sequence validation --- .github/workflows/dev-long-tests.yml | 2 +- tests/fuzz/Makefile | 5 +++-- tests/fuzz/dictionary_loader.c | 6 ++--- tests/fuzz/sequence_compression_api.c | 32 +++++++++++++-------------- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index d5e476b4c..0adfed914 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -188,7 +188,7 @@ jobs: - name: ASan + UBSan + Regression Test run: make -j uasanregressiontest - clang-ubsan-regression: + clang-asan-ubsan-regression: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 diff --git a/tests/fuzz/Makefile b/tests/fuzz/Makefile index a64d2d252..13e29bb7a 100644 --- a/tests/fuzz/Makefile +++ b/tests/fuzz/Makefile @@ -263,9 +263,10 @@ corpora: $(patsubst %,corpora/%,$(FUZZ_TARGETS)) .PHONY: seedcorpora seedcorpora: $(patsubst %,corpora/%_seed_corpus.zip,$(FUZZ_TARGETS)) +REGRESSION_TARGET ?= all regressiontest: corpora - CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" $(PYTHON) ./fuzz.py build all --debug=$(DEBUGLEVEL) - $(PYTHON) ./fuzz.py regression all + CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" $(PYTHON) ./fuzz.py build $(REGRESSION_TARGET) --debug=$(DEBUGLEVEL) + $(PYTHON) ./fuzz.py regression $(REGRESSION_TARGET) clean: @$(RM) *.a *.o $(FUZZ_TARGETS) diff --git a/tests/fuzz/dictionary_loader.c b/tests/fuzz/dictionary_loader.c index 7b7c00428..ec9de4b0b 100644 --- a/tests/fuzz/dictionary_loader.c +++ b/tests/fuzz/dictionary_loader.c @@ -77,9 +77,9 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) FUZZ_dataProducer_uint32Range(producer, 0, 2); size = FUZZ_dataProducer_remainingBytes(producer); - DEBUGLOG(2, "Dict load method %d", dlm); - DEBUGLOG(2, "Dict content type %d", dct); - DEBUGLOG(2, "Dict size %u", (unsigned)size); + DEBUGLOG(4, "Dict load method %d", dlm); + DEBUGLOG(4, "Dict content type %d", dct); + DEBUGLOG(4, "Dict size %u", (unsigned)size); void* const rBuf = FUZZ_malloc(size); size_t const cBufSize = ZSTD_compressBound(size); diff --git a/tests/fuzz/sequence_compression_api.c b/tests/fuzz/sequence_compression_api.c index 21b6ac84e..9295d248c 100644 --- a/tests/fuzz/sequence_compression_api.c +++ b/tests/fuzz/sequence_compression_api.c @@ -239,8 +239,8 @@ transferLiterals(void* dst, size_t dstCapacity, const ZSTD_Sequence* seqs, size_ for (n=0; n Date: Sun, 29 Dec 2024 02:35:53 -0800 Subject: [PATCH 557/937] clarify doc on Frame-level methods when invoked on a skippable frame following discussion at #4226 --- lib/zstd.h | 39 +++++++++++++++++++++++---------------- tests/fuzzer.c | 18 ++++++++++++------ 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 36668b85b..acbcd0f99 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -178,6 +178,7 @@ ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, * - 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. @@ -197,22 +198,26 @@ ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity, #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2) ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); -/*! ZSTD_getDecompressedSize() : - * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). +/*! ZSTD_getDecompressedSize() (obsolete): + * This function is now obsolete, in favor of ZSTD_getFrameContentSize(). * Both functions work the same way, but ZSTD_getDecompressedSize() blends * "empty", "unknown" and "error" results to the same return value (0), * while ZSTD_getFrameContentSize() gives them separate return values. * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */ ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize") -ZSTDLIB_API -unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); +ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); /*! ZSTD_findFrameCompressedSize() : Requires v1.4.0+ * `src` should point to the start of a ZSTD frame or skippable frame. * `srcSize` must be >= first frame size * @return : the compressed size of the first frame starting at `src`, * suitable to pass as `srcSize` to `ZSTD_decompress` or similar, - * or an error code if input is invalid */ + * or an error code if input is invalid + * Note 1: this method is called _find*() because it's not enough to read the header, + * it may have to scan through the frame's content, to reach its end. + * Note 2: this method also works with Skippable Frames. In which case, + * it returns the size of the complete skippable frame, + * which is always equal to its content size + 8 bytes for headers. */ ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize); @@ -1507,7 +1512,7 @@ typedef struct { /*! ZSTD_getFrameHeader() : * decode Frame Header, or requires larger `srcSize`. * @return : 0, `zfhPtr` is correctly filled, - * >0, `srcSize` is too small, value is wanted `srcSize` amount, + * >0, `srcSize` is too small, @return value is the wanted `srcSize` amount, * 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); /**< doesn't consume input */ /*! ZSTD_getFrameHeader_advanced() : @@ -1695,8 +1700,8 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, * * Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number, * ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. - * As such, the parameter magicVariant controls the exact skippable frame magic number variant used, so - * the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. + * As such, the parameter magicVariant controls the exact skippable frame magic number variant used, + * so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. * * Returns an error if destination buffer is not large enough, if the source size is not representable * with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid). @@ -1704,26 +1709,28 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, * @return : number of bytes written or a ZSTD error. */ ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity, - const void* src, size_t srcSize, unsigned magicVariant); + const void* src, size_t srcSize, + unsigned magicVariant); /*! ZSTD_readSkippableFrame() : - * Retrieves a zstd skippable frame containing data given by src, and writes it to dst buffer. + * Retrieves the content of a zstd skippable frame starting at @src, and writes it to @dst buffer. * - * The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, - * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested - * in the magicVariant. + * The parameter @magicVariant will receive the magicVariant that was supplied when the frame was written, + * i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. + * This can be NULL if the caller is not interested in the magicVariant. * * Returns an error if destination buffer is not large enough, or if the frame is not skippable. * * @return : number of bytes written or a ZSTD error. */ -ZSTDLIB_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, unsigned* magicVariant, - const void* src, size_t srcSize); +ZSTDLIB_STATIC_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, + unsigned* magicVariant, + const void* src, size_t srcSize); /*! ZSTD_isSkippableFrame() : * Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame. */ -ZSTDLIB_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); +ZSTDLIB_STATIC_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size); diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 6d165aea4..706dd9b95 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -4110,12 +4110,18 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "OK \n"); - /* findFrameCompressedSize on skippable frames */ - DISPLAYLEVEL(3, "test%3i : frame compressed size of skippable frame : ", testNb++); - { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde"; - size_t const frameSrcSize = 13; - if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; } - DISPLAYLEVEL(3, "OK \n"); + /* frame operations on skippable frames */ + { const char skippableFrame[] = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde"; + size_t const skippableFrameSize = sizeof(skippableFrame) - 1 /* remove final /0 */; + + DISPLAYLEVEL(3, "test%3i : ZSTD_findFrameCompressedSize on skippable frame : ", testNb++); + if (ZSTD_findFrameCompressedSize(skippableFrame, skippableFrameSize) != skippableFrameSize) goto _output_error; + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize on skippable frame : ", testNb++); + if (ZSTD_getFrameContentSize(skippableFrame, skippableFrameSize) != 0) goto _output_error; + DISPLAYLEVEL(3, "OK \n"); + } /* error string tests */ DISPLAYLEVEL(3, "test%3i : testing ZSTD error code strings : ", testNb++); From a2ff6ea7846c598812be580026dfc63fd7229db3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 29 Dec 2024 12:26:04 -0800 Subject: [PATCH 558/937] improve ZSTD_getFrameHeader on skippable frames now reports: - the header size - the magic variant (within @dictID field) --- lib/common/zstd_trace.h | 2 +- lib/decompress/zstd_decompress.c | 6 ++++-- lib/zstd.h | 12 ++++++------ tests/fuzzer.c | 21 +++++++++++++++++---- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/lib/common/zstd_trace.h b/lib/common/zstd_trace.h index 3ae779fa6..d33edf35d 100644 --- a/lib/common/zstd_trace.h +++ b/lib/common/zstd_trace.h @@ -74,7 +74,7 @@ typedef struct { * Is the dictionary cold? * Only set on decompression. */ - unsigned dictionaryIsCold; + int dictionaryIsCold; /** * The dictionary size or zero if no dictionary. */ diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 6aac5dd3f..b2eb39c51 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -484,8 +484,10 @@ size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, s if (srcSize < ZSTD_SKIPPABLEHEADERSIZE) return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */ ZSTD_memset(zfhPtr, 0, sizeof(*zfhPtr)); - zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); zfhPtr->frameType = ZSTD_skippableFrame; + zfhPtr->dictID = MEM_readLE32(src) - ZSTD_MAGIC_SKIPPABLE_START; + zfhPtr->headerSize = ZSTD_SKIPPABLEHEADERSIZE; + zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE); return 0; } RETURN_ERROR(prefix_unknown, ""); @@ -917,7 +919,7 @@ static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity, return regenSize; } -static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 compressedSize, unsigned streaming) +static void ZSTD_DCtx_trace_end(ZSTD_DCtx const* dctx, U64 uncompressedSize, U64 compressedSize, int streaming) { #if ZSTD_TRACE if (dctx->traceCtx && ZSTD_trace_decompress_end != NULL) { diff --git a/lib/zstd.h b/lib/zstd.h index acbcd0f99..bbddacee7 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1491,7 +1491,7 @@ ZSTDLIB_STATIC_API unsigned long long ZSTD_findDecompressedSize(const void* src, ZSTDLIB_STATIC_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize); /*! ZSTD_frameHeaderSize() : - * srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX. + * srcSize must be large enough, aka >= ZSTD_FRAMEHEADERSIZE_PREFIX. * @return : size of the Frame Header, * or an error code (if srcSize is too small) */ ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize); @@ -1503,18 +1503,18 @@ typedef struct { unsigned blockSizeMax; ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ unsigned headerSize; - unsigned dictID; + unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ unsigned checksumFlag; unsigned _reserved1; unsigned _reserved2; } ZSTD_frameHeader; /*! ZSTD_getFrameHeader() : - * decode Frame Header, or requires larger `srcSize`. - * @return : 0, `zfhPtr` is correctly filled, - * >0, `srcSize` is too small, @return value is the wanted `srcSize` amount, + * 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); /**< doesn't consume input */ +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) */ diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 706dd9b95..4ef0db2d0 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -4111,15 +4111,28 @@ static int basicUnitTests(U32 const seed, double compressibility) /* frame operations on skippable frames */ - { const char skippableFrame[] = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde"; - size_t const skippableFrameSize = sizeof(skippableFrame) - 1 /* remove final /0 */; + { const char skippableFrame[] = "\x52\x2a\x4d\x18\x05\x0\x0\0abcde"; + size_t const skippableFrameSize = sizeof(skippableFrame) - 1 /* remove the terminating /0 */; DISPLAYLEVEL(3, "test%3i : ZSTD_findFrameCompressedSize on skippable frame : ", testNb++); - if (ZSTD_findFrameCompressedSize(skippableFrame, skippableFrameSize) != skippableFrameSize) goto _output_error; + CHECK(ZSTD_findFrameCompressedSize(skippableFrame, skippableFrameSize) == skippableFrameSize); DISPLAYLEVEL(3, "OK \n"); DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize on skippable frame : ", testNb++); - if (ZSTD_getFrameContentSize(skippableFrame, skippableFrameSize) != 0) goto _output_error; + CHECK(ZSTD_getFrameContentSize(skippableFrame, skippableFrameSize) == 0); + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameHeader on skippable frame : ", testNb++); + { ZSTD_frameHeader zfh; + size_t const s = ZSTD_getFrameHeader(&zfh, skippableFrame, skippableFrameSize); + CHECK_Z(s); + CHECK(s == 0); /* success */ + CHECK(zfh.frameType == ZSTD_skippableFrame); + CHECK(zfh.headerSize == ZSTD_SKIPPABLEHEADERSIZE); + CHECK(zfh.dictID == 2); /* magic variant */ + assert(skippableFrameSize >= ZSTD_SKIPPABLEHEADERSIZE); + CHECK(zfh.frameContentSize == skippableFrameSize - ZSTD_SKIPPABLEHEADERSIZE); + } DISPLAYLEVEL(3, "OK \n"); } From 04a2a0219ca424595949d725fda5da5cf764b419 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 29 Dec 2024 14:25:33 -0800 Subject: [PATCH 559/937] update type names naming convention: Type names should start with a Capital letter (after the prefix) --- contrib/linux-kernel/linux_zstd.h | 2 +- doc/zstd_manual.html | 10 +++++----- lib/decompress/zstd_decompress.c | 14 +++++++------- lib/decompress/zstd_decompress_internal.h | 2 +- lib/zstd.h | 14 ++++++++------ programs/fileio.c | 4 ++-- tests/fuzz/simple_round_trip.c | 2 +- tests/fuzz/zstd_frame_info.c | 2 +- tests/fuzzer.c | 18 +++++++++--------- tests/zstreamtest.c | 4 ++-- 10 files changed, 37 insertions(+), 35 deletions(-) diff --git a/contrib/linux-kernel/linux_zstd.h b/contrib/linux-kernel/linux_zstd.h index a7ce080dc..2daf5d25a 100644 --- a/contrib/linux-kernel/linux_zstd.h +++ b/contrib/linux-kernel/linux_zstd.h @@ -465,7 +465,7 @@ void zstd_register_sequence_producer( * * See zstd_lib.h. */ -typedef ZSTD_frameHeader zstd_frame_header; +typedef ZSTD_FrameHeader zstd_frame_header; /** * zstd_get_frame_header() - extracts parameters from a zstd or skippable frame diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index ecb2b622c..485d5eafb 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -1244,13 +1244,13 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); or an error code (if srcSize is too small)


-
typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e;
+
typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_FrameType_e;
 

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 */
+    ZSTD_FrameType_e frameType;          /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */
     unsigned headerSize;
     unsigned dictID;
     unsigned checksumFlag;
@@ -1258,11 +1258,11 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
     unsigned _reserved2;
 } ZSTD_frameHeader;
 

-
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
+
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
 /*! ZSTD_getFrameHeader_advanced() :
  *  same as ZSTD_getFrameHeader(),
  *  with added capability to select a format (like ZSTD_f_zstd1_magicless) */
-ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
+ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
 

decode Frame Header, or requires larger `srcSize`. @return : 0, `zfhPtr` is correctly filled, >0, `srcSize` is too small, value is wanted `srcSize` amount, @@ -2124,7 +2124,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const Z >0 : `srcSize` is too small, please provide at least result bytes on next attempt. errorCode, which can be tested using ZSTD_isError(). - It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, + It fills a ZSTD_FrameHeader structure with important information to correctly decode the frame, such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. As a consequence, check that values remain within valid application range. diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index b2eb39c51..402d75349 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -444,7 +444,7 @@ size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize) * @return : 0, `zfhPtr` is correctly filled, * >0, `srcSize` is too small, value is wanted `srcSize` amount, ** or an error code, which can be tested using ZSTD_isError() */ -size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) +size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format) { const BYTE* ip = (const BYTE*)src; size_t const minInputSize = ZSTD_startingInputLength(format); @@ -556,7 +556,7 @@ size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, s * @return : 0, `zfhPtr` is correctly filled, * >0, `srcSize` is too small, value is wanted `srcSize` amount, * or an error code, which can be tested using ZSTD_isError() */ -size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize) +size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize) { return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1); } @@ -574,7 +574,7 @@ unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize) return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret; } #endif - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0) return ZSTD_CONTENTSIZE_ERROR; if (zfh.frameType == ZSTD_skippableFrame) { @@ -752,7 +752,7 @@ static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize const BYTE* const ipstart = ip; size_t remainingSize = srcSize; size_t nbBlocks = 0; - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; /* Extract Frame Header */ { size_t const ret = ZSTD_getFrameHeader_advanced(&zfh, src, srcSize, format); @@ -845,7 +845,7 @@ size_t ZSTD_decompressionMargin(void const* src, size_t srcSize) ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize, ZSTD_f_zstd1); size_t const compressedSize = frameSizeInfo.compressedSize; unsigned long long const decompressedBound = frameSizeInfo.decompressedBound; - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; FORWARD_IF_ERROR(ZSTD_getFrameHeader(&zfh, src, srcSize), ""); if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR) @@ -1643,7 +1643,7 @@ unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize) * ZSTD_getFrameHeader(), which will provide a more precise error code. */ unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize) { - ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0, 0, 0 }; + ZSTD_FrameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0, 0, 0 }; size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize); if (ZSTD_isError(hError)) return 0; return zfp.dictID; @@ -2001,7 +2001,7 @@ size_t ZSTD_estimateDStreamSize(size_t windowSize) size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize) { U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */ - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize); if (ZSTD_isError(err)) return err; RETURN_ERROR_IF(err>0, srcSize_wrong, ""); diff --git a/lib/decompress/zstd_decompress_internal.h b/lib/decompress/zstd_decompress_internal.h index 83a7a0115..7d1f1053b 100644 --- a/lib/decompress/zstd_decompress_internal.h +++ b/lib/decompress/zstd_decompress_internal.h @@ -136,7 +136,7 @@ struct ZSTD_DCtx_s const void* virtualStart; /* virtual start of previous segment if it was just before current one */ const void* dictEnd; /* end of previous segment */ size_t expected; - ZSTD_frameHeader fParams; + ZSTD_FrameHeader fParams; U64 processedCSize; U64 decodedSize; blockType_e bType; /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */ diff --git a/lib/zstd.h b/lib/zstd.h index bbddacee7..08b3b357a 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1496,29 +1496,31 @@ 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; +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 */ + 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; +} 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); +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) */ -ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format); +ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format); /*! ZSTD_decompressionMargin() : * Zstd supports in-place decompression, where the input and output buffers overlap. @@ -3047,7 +3049,7 @@ size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_ >0 : `srcSize` is too small, please provide at least result bytes on next attempt. errorCode, which can be tested using ZSTD_isError(). - It fills a ZSTD_frameHeader structure with important information to correctly decode the frame, + It fills a ZSTD_FrameHeader structure with important information to correctly decode the frame, such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`). Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information. As a consequence, check that values remain within valid application range. diff --git a/programs/fileio.c b/programs/fileio.c index c2036b83c..1b8aa8a99 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -2401,7 +2401,7 @@ FIO_zstdErrorHelp(const FIO_prefs_t* const prefs, size_t err, const char* srcFileName) { - ZSTD_frameHeader header; + ZSTD_FrameHeader header; /* Help message only for one specific error */ if (ZSTD_getErrorCode(err) != ZSTD_error_frameParameter_windowTooLarge) @@ -3201,7 +3201,7 @@ FIO_analyzeFrames(fileInfo_t* info, FILE* const srcFile) { U32 const magicNumber = MEM_readLE32(headerBuffer); /* Zstandard frame */ if (magicNumber == ZSTD_MAGICNUMBER) { - ZSTD_frameHeader header; + ZSTD_FrameHeader header; U64 const frameContentSize = ZSTD_getFrameContentSize(headerBuffer, numBytesRead); if ( frameContentSize == ZSTD_CONTENTSIZE_ERROR || frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN ) { diff --git a/tests/fuzz/simple_round_trip.c b/tests/fuzz/simple_round_trip.c index 660092e61..ab50aadb4 100644 --- a/tests/fuzz/simple_round_trip.c +++ b/tests/fuzz/simple_round_trip.c @@ -34,7 +34,7 @@ static size_t getDecompressionMargin(void const* compressed, size_t cSize, size_ /* The macro should be correct in this case, but it may be smaller * because of e.g. block splitting, so take the smaller of the two. */ - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; size_t marginM; FUZZ_ZASSERT(ZSTD_getFrameHeader(&zfh, compressed, cSize)); if (maxBlockSize == 0) { diff --git a/tests/fuzz/zstd_frame_info.c b/tests/fuzz/zstd_frame_info.c index 95dbdd49a..4d17bba74 100644 --- a/tests/fuzz/zstd_frame_info.c +++ b/tests/fuzz/zstd_frame_info.c @@ -21,7 +21,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *src, size_t size) { - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; if (size == 0) { src = NULL; } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 4ef0db2d0..b457c2171 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -955,7 +955,7 @@ static int basicUnitTests(U32 const seed, double compressibility) ZSTD_freeCCtx(cctx); } { /* ensure frame content size is missing */ - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; size_t const ret = ZSTD_getFrameHeader(&zfh, compressedBuffer, compressedBufferSize); if (ret != 0 || zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error; } @@ -2512,7 +2512,7 @@ static int basicUnitTests(U32 const seed, double compressibility) CHECK_VAR(cSize, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize), (const char*)CNBuffer + dictSize, testSize) ); - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error; if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error; } } @@ -3585,7 +3585,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "test%3i : decompress of magic-less frame : ", testNb++); ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters); CHECK_Z( ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless) ); - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; size_t const zfhrt = ZSTD_getFrameHeader_advanced(&zfh, compressedBuffer, cSize, ZSTD_f_zstd1_magicless); if (zfhrt != 0) goto _output_error; } @@ -3943,7 +3943,7 @@ static int basicUnitTests(U32 const seed, double compressibility) goto _output_error; } } - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; size_t const zfhStatus = ZSTD_getFrameHeader(&zfh, dst, compressedSize); if (zfhStatus != 0) { DISPLAY("Error reading frame header\n"); @@ -4123,7 +4123,7 @@ static int basicUnitTests(U32 const seed, double compressibility) DISPLAYLEVEL(3, "OK \n"); DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameHeader on skippable frame : ", testNb++); - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; size_t const s = ZSTD_getFrameHeader(&zfh, skippableFrame, skippableFrameSize); CHECK_Z(s); CHECK(s == 0); /* success */ @@ -4153,8 +4153,8 @@ static int basicUnitTests(U32 const seed, double compressibility) ZSTD_CCtx* const cctx = ZSTD_createCCtx(); ZSTD_CDict* const lgCDict = ZSTD_createCDict(CNBuffer, size, 1); ZSTD_CDict* const smCDict = ZSTD_createCDict(CNBuffer, 1 KB, 1); - ZSTD_frameHeader lgHeader; - ZSTD_frameHeader smHeader; + ZSTD_FrameHeader lgHeader; + ZSTD_FrameHeader smHeader; CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, lgCDict)); CHECK_Z(ZSTD_getFrameHeader(&lgHeader, compressedBuffer, compressedBufferSize)); @@ -4773,7 +4773,7 @@ static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, U32 const } } /* frame header decompression test */ - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) ); CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect"); } @@ -4915,7 +4915,7 @@ static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, U32 const /* streaming decompression test */ DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb); /* ensure memory requirement is good enough (should always be true) */ - { ZSTD_frameHeader zfh; + { ZSTD_FrameHeader zfh; CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_FRAMEHEADERSIZE_MAX), "ZSTD_getFrameHeader(): error retrieving frame information"); { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize); diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 8df86d985..b8290fefc 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -436,7 +436,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) /* context size functions */ DISPLAYLEVEL(3, "test%3i : estimate DStream size : ", testNb++); - { ZSTD_frameHeader fhi; + { ZSTD_FrameHeader fhi; const void* cStart = (char*)compressedBuffer + (skippableFrameSize + 8); size_t const gfhError = ZSTD_getFrameHeader(&fhi, cStart, cSize); if (gfhError!=0) goto _output_error; @@ -1530,7 +1530,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : decompress large frame created from multiple threads + dictionary : ", testNb++); { ZSTD_DStream* const dstream = ZSTD_createDCtx(); - ZSTD_frameHeader zfh; + ZSTD_FrameHeader zfh; ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize); DISPLAYLEVEL(5, "frame windowsize = %u : ", (unsigned)zfh.windowSize); outBuff.dst = decodedBuffer; From 54c3d998a04a4002697a3a44293074cb01df54a5 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Thu, 2 Jan 2025 14:02:10 -0800 Subject: [PATCH 560/937] Support for libc variants without fseeko/ftello Some older Android libc implementations don't support `fseeko` or `ftello`. This commit adds a new compile-time macro `LIBC_NO_FSEEKO` as well as a usage in CMake for old Android APIs. --- build/cmake/CMakeLists.txt | 12 ++++++++++++ contrib/seekable_format/zstdseek_decompress.c | 5 ++++- programs/fileio_common.h | 6 +++++- programs/util.h | 5 ++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index b43671cc2..e03eadb66 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -82,8 +82,19 @@ else () add_definitions(-DZSTD_LEGACY_SUPPORT=0) endif () +get_cmake_property(_variableNames VARIABLES) +list (SORT _variableNames) +foreach (_variableName ${_variableNames}) + message("${_variableName}=${${_variableName}}") +endforeach() + if (ANDROID) set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT OFF) + # Old versions of bionic libc don't have fseeko/ftello + if ((NOT ${ANDROID_PLATFORM_LEVEL}) OR ${ANDROID_PLATFORM_LEVEL} VERSION_LESS 24) + message("Hi Android SDK") + add_compile_definitions(LIBC_NO_FSEEKO) + endif () else() set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT ON) endif() @@ -153,6 +164,7 @@ if (ZSTD_BUILD_PROGRAMS) elseif(NOT ZSTD_BUILD_SHARED AND ZSTD_PROGRAMS_LINK_SHARED) message(SEND_ERROR "You need to build shared library to build zstd CLI") endif () + message("Building program") add_subdirectory(programs) endif () diff --git a/contrib/seekable_format/zstdseek_decompress.c b/contrib/seekable_format/zstdseek_decompress.c index 5ee6e0541..7f4979875 100644 --- a/contrib/seekable_format/zstdseek_decompress.c +++ b/contrib/seekable_format/zstdseek_decompress.c @@ -77,7 +77,10 @@ /* ************************************************************ * Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW ***************************************************************/ -#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(LIBC_NO_FSEEKO) +/* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ +#define LONG_SEEK fseek +#elif defined(_MSC_VER) && _MSC_VER >= 1400 # define LONG_SEEK _fseeki64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ # define LONG_SEEK fseeko diff --git a/programs/fileio_common.h b/programs/fileio_common.h index 7a014ee4b..f1eb8160b 100644 --- a/programs/fileio_common.h +++ b/programs/fileio_common.h @@ -79,7 +79,11 @@ extern UTIL_time_t g_displayClock; /* Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW */ -#if defined(_MSC_VER) && _MSC_VER >= 1400 +#if defined(LIBC_NO_FSEEKO) +/* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ +#define LONG_SEEK fseek +#define LONG_TELL ftell +#elif defined(_MSC_VER) && _MSC_VER >= 1400 # define LONG_SEEK _fseeki64 # define LONG_TELL _ftelli64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ diff --git a/programs/util.h b/programs/util.h index ec8139684..e66d95c08 100644 --- a/programs/util.h +++ b/programs/util.h @@ -24,7 +24,10 @@ /*-************************************************************ * Fix fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW ***************************************************************/ -#if defined(_MSC_VER) && (_MSC_VER >= 1400) +#if defined(LIBC_NO_FSEEKO) +/* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ +#define UTIL_fseek fseek +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) # define UTIL_fseek _fseeki64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ # define UTIL_fseek fseeko From 757e29e170565ac48ff7d893a4cc421e0450dd72 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Thu, 2 Jan 2025 14:17:24 -0800 Subject: [PATCH 561/937] Oops --- build/cmake/CMakeLists.txt | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index e03eadb66..b9003c867 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -82,17 +82,11 @@ else () add_definitions(-DZSTD_LEGACY_SUPPORT=0) endif () -get_cmake_property(_variableNames VARIABLES) -list (SORT _variableNames) -foreach (_variableName ${_variableNames}) - message("${_variableName}=${${_variableName}}") -endforeach() - if (ANDROID) set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT OFF) # Old versions of bionic libc don't have fseeko/ftello if ((NOT ${ANDROID_PLATFORM_LEVEL}) OR ${ANDROID_PLATFORM_LEVEL} VERSION_LESS 24) - message("Hi Android SDK") + message(STATUS "Setting compile definitions for old Android API") add_compile_definitions(LIBC_NO_FSEEKO) endif () else() @@ -164,7 +158,6 @@ if (ZSTD_BUILD_PROGRAMS) elseif(NOT ZSTD_BUILD_SHARED AND ZSTD_PROGRAMS_LINK_SHARED) message(SEND_ERROR "You need to build shared library to build zstd CLI") endif () - message("Building program") add_subdirectory(programs) endif () From 6b046f58410fe66ea300c31ffc92dbfb4c956bb1 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Thu, 2 Jan 2025 15:05:58 -0800 Subject: [PATCH 562/937] PR feedback --- contrib/seekable_format/zstdseek_decompress.c | 2 +- programs/fileio_common.h | 4 ++-- programs/util.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/seekable_format/zstdseek_decompress.c b/contrib/seekable_format/zstdseek_decompress.c index 7f4979875..ab9088a10 100644 --- a/contrib/seekable_format/zstdseek_decompress.c +++ b/contrib/seekable_format/zstdseek_decompress.c @@ -79,7 +79,7 @@ ***************************************************************/ #if defined(LIBC_NO_FSEEKO) /* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ -#define LONG_SEEK fseek +# define LONG_SEEK fseek #elif defined(_MSC_VER) && _MSC_VER >= 1400 # define LONG_SEEK _fseeki64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ diff --git a/programs/fileio_common.h b/programs/fileio_common.h index f1eb8160b..044001506 100644 --- a/programs/fileio_common.h +++ b/programs/fileio_common.h @@ -81,8 +81,8 @@ extern UTIL_time_t g_displayClock; /* Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW */ #if defined(LIBC_NO_FSEEKO) /* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ -#define LONG_SEEK fseek -#define LONG_TELL ftell +# define LONG_SEEK fseek +# define LONG_TELL ftell #elif defined(_MSC_VER) && _MSC_VER >= 1400 # define LONG_SEEK _fseeki64 # define LONG_TELL _ftelli64 diff --git a/programs/util.h b/programs/util.h index e66d95c08..3a83a50ae 100644 --- a/programs/util.h +++ b/programs/util.h @@ -26,7 +26,7 @@ ***************************************************************/ #if defined(LIBC_NO_FSEEKO) /* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ -#define UTIL_fseek fseek +# define UTIL_fseek fseek #elif defined(_MSC_VER) && (_MSC_VER >= 1400) # define UTIL_fseek _fseeki64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ From dfb236b2aa58d3460945f5112e8d5388d7c4a666 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Thu, 2 Jan 2025 15:10:40 -0800 Subject: [PATCH 563/937] chore: indentation alignment --- programs/fileio_common.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/programs/fileio_common.h b/programs/fileio_common.h index 044001506..696626fe4 100644 --- a/programs/fileio_common.h +++ b/programs/fileio_common.h @@ -81,14 +81,14 @@ extern UTIL_time_t g_displayClock; /* Avoid fseek()'s 2GiB barrier with MSVC, macOS, *BSD, MinGW */ #if defined(LIBC_NO_FSEEKO) /* Some older libc implementations don't include these functions (e.g. Bionic < 24) */ -# define LONG_SEEK fseek -# define LONG_TELL ftell +# define LONG_SEEK fseek +# define LONG_TELL ftell #elif defined(_MSC_VER) && _MSC_VER >= 1400 # define LONG_SEEK _fseeki64 # define LONG_TELL _ftelli64 #elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ -# define LONG_SEEK fseeko -# define LONG_TELL ftello +# define LONG_SEEK fseeko +# define LONG_TELL ftello #elif defined(__MINGW32__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) && defined(__MSVCRT__) # define LONG_SEEK fseeko64 # define LONG_TELL ftello64 From 1548bfc3497f45399daab58bcec4ab06a0878af1 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Fri, 20 Dec 2024 17:32:28 -0500 Subject: [PATCH 564/937] [opt] Fix too short of match getting generated The optimal parser with LDM enabled using minMatch > 3 could generate a match length of 3 when minMatch >= 4. This is not allowed. 1. Fix the bug 2. Add validation logic to `ZSTD_buildSeqStore()` in debug mode for all block compressors that checks we never generate too short a match. This way we don't rely on the `generate_sequences` fuzzer to find this issue. Credit to OSS-Fuzz --- lib/compress/zstd_compress.c | 22 ++++++++++++++++++++++ lib/compress/zstd_opt.c | 18 +++++++++++------- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 3af69c1ae..52c54b4da 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3240,6 +3240,27 @@ static size_t ZSTD_fastSequenceLengthSum(ZSTD_Sequence const* seqBuf, size_t seq return litLenSum + matchLenSum; } +/** + * Function to validate sequences produced by a block compressor. + */ +static void ZSTD_validateSeqStore(const SeqStore_t* seqStore, const ZSTD_compressionParameters* cParams) +{ +#if DEBUGLEVEL >= 1 + const SeqDef* seq = seqStore->sequencesStart; + const SeqDef* const seqEnd = seqStore->sequences; + size_t const matchLenLowerBound = cParams->minMatch == 3 ? 3 : 4; + for (; seq < seqEnd; ++seq) { + const ZSTD_SequenceLength seqLength = ZSTD_getSequenceLength(seqStore, seq); + assert(seqLength.matchLength >= matchLenLowerBound); + (void)seqLength; + (void)matchLenLowerBound; + } +#else + (void)seqStore; + (void)cParams; +#endif +} + static size_t ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_SequencePosition* seqPos, @@ -3410,6 +3431,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize; ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize); } } + ZSTD_validateSeqStore(&zc->seqStore, &zc->appliedParams.cParams); return ZSTDbss_compress; } diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 0ab33d56e..3d7171b75 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -972,7 +972,7 @@ ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock return; } - /* Matches may be < MINMATCH by this process. In that case, we will reject them + /* Matches may be < minMatch by this process. In that case, we will reject them when we are deciding whether or not to add the ldm */ optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining; optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining; @@ -994,7 +994,8 @@ ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock * into 'matches'. Maintains the correct ordering of 'matches'. */ static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches, - const ZSTD_optLdm_t* optLdm, U32 currPosInBlock) + const ZSTD_optLdm_t* optLdm, U32 currPosInBlock, + U32 minMatch) { U32 const posDiff = currPosInBlock - optLdm->startPosInBlock; /* Note: ZSTD_match_t actually contains offBase and matchLength (before subtracting MINMATCH) */ @@ -1003,7 +1004,7 @@ static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches, /* Ensure that current block position is not outside of the match */ if (currPosInBlock < optLdm->startPosInBlock || currPosInBlock >= optLdm->endPosInBlock - || candidateMatchLength < MINMATCH) { + || candidateMatchLength < minMatch) { return; } @@ -1023,7 +1024,8 @@ static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches, static void ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm, ZSTD_match_t* matches, U32* nbMatches, - U32 currPosInBlock, U32 remainingBytes) + U32 currPosInBlock, U32 remainingBytes, + U32 minMatch) { if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) { return; @@ -1040,7 +1042,7 @@ ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm, } ZSTD_opt_getNextMatchAndUpdateSeqStore(optLdm, currPosInBlock, remainingBytes); } - ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock); + ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock, minMatch); } @@ -1122,7 +1124,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, U32 const ll0 = !litlen; U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch); ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches, - (U32)(ip-istart), (U32)(iend-ip)); + (U32)(ip-istart), (U32)(iend-ip), + minMatch); if (!nbMatches) { DEBUGLOG(8, "no match found at cPos %u", (unsigned)(ip-istart)); ip++; @@ -1276,7 +1279,8 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, U32 matchNb; ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches, - (U32)(inr-istart), (U32)(iend-inr)); + (U32)(inr-istart), (U32)(iend-inr), + minMatch); if (!nbMatches) { DEBUGLOG(7, "rPos:%u : no match found", cur); From d88651e6041995243c8cd6884bbc44c279ab80d2 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Fri, 3 Jan 2025 09:35:18 -0800 Subject: [PATCH 565/937] Do not vary row matchfinder selection based on availability of SSE2/Neon Move towards a stronger guarantee of reproducibility by removing this small difference for machines without SSE2/Neon. The SIMD behavior is now the default for all platforms. --- lib/compress/zstd_compress.c | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 52c54b4da..04b6bb9f1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -237,19 +237,10 @@ 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) { -#if defined(ZSTD_ARCH_X86_SSE2) || defined(ZSTD_ARCH_ARM_NEON) - int const kHasSIMD128 = 1; -#else - int const kHasSIMD128 = 0; -#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 (kHasSIMD128) { - if (cParams->windowLog > 14) mode = ZSTD_ps_enable; - } else { - if (cParams->windowLog > 17) mode = ZSTD_ps_enable; - } + if (cParams->windowLog > 14) mode = ZSTD_ps_enable; return mode; } From 0fd521048d9304e2e06020bebcfb0b481261b2fc Mon Sep 17 00:00:00 2001 From: Po-Chuan Hsieh Date: Sun, 5 Jan 2025 22:26:08 +0800 Subject: [PATCH 566/937] Update MANDIR for FreeBSD share/man became a valid path for manpage since Jan 2020. And we converted the whole ports tree to share/man around last March. --- programs/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/Makefile b/programs/Makefile index 4d32e0fa8..f4af5e981 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -388,7 +388,7 @@ datarootdir ?= $(PREFIX)/share mandir ?= $(datarootdir)/man man1dir ?= $(mandir)/man1 -ifneq (,$(filter OpenBSD FreeBSD NetBSD DragonFly SunOS,$(UNAME))) +ifneq (,$(filter OpenBSD NetBSD DragonFly SunOS,$(UNAME))) MANDIR ?= $(PREFIX)/man MAN1DIR ?= $(MANDIR)/man1 else From 42d704ad5e286fe8ad8b8aca0af4c78543abd3f1 Mon Sep 17 00:00:00 2001 From: MessyHack Date: Fri, 10 Jan 2025 22:38:56 -0800 Subject: [PATCH 567/937] should check defined(_M_X64) not defined(_M_X86) when building with MSVC. _M_X86 is only defined under MSVC 32Bit _M_X64 is only defined under MSVC 64Bit --- lib/common/bitstream.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index bcfa09b89..a1dac889d 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -309,7 +309,7 @@ FORCE_INLINE_TEMPLATE size_t BIT_getMiddleBits(BitContainerType bitContainer, U3 * such cpus old (pre-Haswell, 2013) and their performance is not of that * importance. */ -#if defined(__x86_64__) || defined(_M_X86) +#if defined(__x86_64__) || defined(_M_X64) return (bitContainer >> (start & regMask)) & ((((U64)1) << nbBits) - 1); #else return (bitContainer >> (start & regMask)) & BIT_mask[nbBits]; From 56500044c4c517dc405c04e6933130684743cb89 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 12 Jan 2025 01:32:40 -0800 Subject: [PATCH 568/937] bench: nb threads specified with -v --- programs/zstdcli.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 9fa7e2275..7d00a94b2 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1312,7 +1312,8 @@ int main(int argCount, const char* argv[]) nbWorkers = default_nbThreads(); } } - DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); + if (operation != zom_bench) + DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); #else (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores; #endif @@ -1397,13 +1398,19 @@ int main(int argCount, const char* argv[]) if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel(); if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel(); if (cLevelLast < cLevel) cLevelLast = cLevel; - if (cLevelLast > cLevel) - DISPLAYLEVEL(3, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast); + DISPLAYLEVEL(3, "Benchmarking "); + if (filenames->tableSize > 1) + DISPLAYLEVEL(3, "%u files ", (unsigned)filenames->tableSize); + if (cLevelLast > cLevel) { + DISPLAYLEVEL(3, "from level %d to %d ", cLevel, cLevelLast); + } else { + DISPLAYLEVEL(3, "at level %d ", cLevel); + } + DISPLAYLEVEL(3, "using %i threads \n", nbWorkers); if (filenames->tableSize > 0) { if(separateFiles) { unsigned i; for(i = 0; i < filenames->tableSize; i++) { - DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]); operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, cLevel, cLevelLast, &compressionParams, g_displayLevel, &benchParams); } } else { From f5dbdac81879e34a4dfffb77dd7769c536a9b702 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 12 Jan 2025 23:08:26 -0800 Subject: [PATCH 569/937] fixed macro name typo --- programs/platform.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/platform.h b/programs/platform.h index 05a26a564..e2cc1c3e6 100644 --- a/programs/platform.h +++ b/programs/platform.h @@ -32,7 +32,7 @@ #if defined __ia64 || defined _M_IA64 /* Intel Itanium */ \ || defined __powerpc64__ || defined __ppc64__ || defined __PPC64__ /* POWER 64-bit */ \ || (defined __sparc && (defined __sparcv9 || defined __sparc_v9__ || defined __arch64__)) || defined __sparc64__ /* SPARC 64-bit */ \ - || defined __x86_64__s || defined _M_X64 /* x86 64-bit */ \ + || defined __x86_64__ || defined _M_X64 /* x86 64-bit */ \ || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__ /* ARM 64-bit */ \ || (defined __mips && (__mips == 64 || __mips == 4 || __mips == 3)) /* MIPS 64-bit */ \ || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \ From e490be895cda9d1d6f707eaa86f8a72995960053 Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Mon, 13 Jan 2025 16:39:34 -0500 Subject: [PATCH 570/937] fix out-of-bounds array index access --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 04b6bb9f1..ef1817f52 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6713,7 +6713,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); - if (inSeqs[idx].litLength) { + if (idx < inSeqsSize && inSeqs[idx].litLength) { DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength); ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength); ip += inSeqs[idx].litLength; From 80af41e08a630946a75a5cda9e4cdf192247f20a Mon Sep 17 00:00:00 2001 From: Sean Bartell Date: Thu, 20 Jun 2024 15:52:43 -0500 Subject: [PATCH 571/937] [contrib/pzstd] Prevent hangs when there are errors When two threads are using a WorkQueue and the reader thread exits due to an error, it must call WorkQueue::finish() to wake up the writer thread. Otherwise, if the queue is full and the writer thread is waiting for a free slot, it could hang forever. This can happen in pratice when decompressing a large, corrupted file that does not contain pzstd skippable frames. --- contrib/pzstd/Pzstd.cpp | 12 ++++++++++-- contrib/pzstd/utils/WorkQueue.h | 7 ++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/contrib/pzstd/Pzstd.cpp b/contrib/pzstd/Pzstd.cpp index 67b941991..048a006b3 100644 --- a/contrib/pzstd/Pzstd.cpp +++ b/contrib/pzstd/Pzstd.cpp @@ -269,7 +269,10 @@ static void compress( std::shared_ptr out, size_t maxInputSize) { auto& errorHolder = state.errorHolder; - auto guard = makeScopeGuard([&] { out->finish(); }); + auto guard = makeScopeGuard([&] { + in->finish(); + out->finish(); + }); // Initialize the CCtx auto ctx = state.cStreamPool->get(); if (!errorHolder.check(ctx != nullptr, "Failed to allocate ZSTD_CStream")) { @@ -431,7 +434,10 @@ static void decompress( std::shared_ptr in, std::shared_ptr out) { auto& errorHolder = state.errorHolder; - auto guard = makeScopeGuard([&] { out->finish(); }); + auto guard = makeScopeGuard([&] { + in->finish(); + out->finish(); + }); // Initialize the DCtx auto ctx = state.dStreamPool->get(); if (!errorHolder.check(ctx != nullptr, "Failed to allocate ZSTD_DStream")) { @@ -578,6 +584,7 @@ std::uint64_t writeFile( FILE* outputFd, bool decompress) { auto& errorHolder = state.errorHolder; + auto outsFinishGuard = makeScopeGuard([&outs] { outs.finish(); }); auto lineClearGuard = makeScopeGuard([&state] { state.log.clear(kLogInfo); }); @@ -585,6 +592,7 @@ std::uint64_t writeFile( std::shared_ptr out; // Grab the output queue for each decompression job (in order). while (outs.pop(out)) { + auto outFinishGuard = makeScopeGuard([&out] { out->finish(); }); if (errorHolder.hasError()) { continue; } diff --git a/contrib/pzstd/utils/WorkQueue.h b/contrib/pzstd/utils/WorkQueue.h index d7947b814..07842e598 100644 --- a/contrib/pzstd/utils/WorkQueue.h +++ b/contrib/pzstd/utils/WorkQueue.h @@ -115,13 +115,14 @@ class WorkQueue { } /** - * Promise that `push()` won't be called again, so once the queue is empty - * there will never any more work. + * Promise that either the reader side or the writer side is done. + * If the writer is done, `push()` won't be called again, so once the queue + * is empty there will never be any more work. If the reader is done, `pop()` + * won't be called again, so further items pushed will just be ignored. */ void finish() { { std::lock_guard lock(mutex_); - assert(!done_); done_ = true; } readerCv_.notify_all(); From afff3d2cce1ad2e81b16459de5b572131949c44f Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Mon, 13 Jan 2025 20:52:06 -0500 Subject: [PATCH 572/937] return error if block delimiter is not found --- lib/compress/zstd_compress.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index ef1817f52..e033a04cc 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -6687,6 +6687,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_storeSeq(&cctx->seqStore, litLength, ip, iend, offBase, matchLength); ip += matchLength + litLength; } + RETURN_ERROR_IF(idx == inSeqsSize, externalSequences_invalid, "Block delimiter not found."); /* If we skipped repcode search while parsing, we need to update repcodes now */ assert(externalRepSearch != ZSTD_ps_auto); @@ -6713,7 +6714,7 @@ ZSTD_transferSequences_wBlockDelim(ZSTD_CCtx* cctx, ZSTD_memcpy(cctx->blockState.nextCBlock->rep, updatedRepcodes.rep, sizeof(Repcodes_t)); - if (idx < inSeqsSize && inSeqs[idx].litLength) { + if (inSeqs[idx].litLength) { DEBUGLOG(6, "Storing last literals of size: %u", inSeqs[idx].litLength); ZSTD_storeLastLiterals(&cctx->seqStore, ip, inSeqs[idx].litLength); ip += inSeqs[idx].litLength; From 7d63a1c7c3ceb5befd0839e8c50b91c3289019ce Mon Sep 17 00:00:00 2001 From: lalakii Date: Wed, 15 Jan 2025 02:16:42 +0800 Subject: [PATCH 573/937] add prerelease option --- build/VS_scripts/build.VSPreview.cmd | 7 +++++++ build/VS_scripts/build.generic.cmd | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 build/VS_scripts/build.VSPreview.cmd diff --git a/build/VS_scripts/build.VSPreview.cmd b/build/VS_scripts/build.VSPreview.cmd new file mode 100644 index 000000000..c594bb12c --- /dev/null +++ b/build/VS_scripts/build.VSPreview.cmd @@ -0,0 +1,7 @@ +@echo off + +rem build 32-bit +call "%~p0%build.generic.cmd" preview Win32 Release v143 + +rem build 64-bit +call "%~p0%build.generic.cmd" preview x64 Release v143 \ No newline at end of file diff --git a/build/VS_scripts/build.generic.cmd b/build/VS_scripts/build.generic.cmd index 6597d79ca..0912d2347 100644 --- a/build/VS_scripts/build.generic.cmd +++ b/build/VS_scripts/build.generic.cmd @@ -19,10 +19,10 @@ GOTO build :display_help echo Syntax: build.generic.cmd msbuild_version msbuild_platform msbuild_configuration msbuild_toolset -echo msbuild_version: VS installed version (latest, VS2012, VS2013, VS2015, VS2017, VS2019, ...) +echo msbuild_version: VS installed version (latest, VS2012, VS2013, VS2015, VS2017, VS2019, VS2022, ...) echo msbuild_platform: Platform (x64 or Win32) echo msbuild_configuration: VS configuration (Release or Debug) -echo msbuild_toolset: Platform Toolset (v100, v110, v120, v140, v141, v142, ...) +echo msbuild_toolset: Platform Toolset (v100, v110, v120, v140, v141, v142, v143, ...) EXIT /B 1 @@ -39,6 +39,7 @@ IF %msbuild_version% == VS2019 SET vswhere_params=-version [16,17) -products * IF %msbuild_version% == VS2022 SET vswhere_params=-version [17,18) -products * REM Add the next Visual Studio version here. IF %msbuild_version% == latest SET vswhere_params=-latest -products * +IF %msbuild_version% == preview SET vswhere_params=-prerelease -products * IF NOT DEFINED vswhere_params GOTO skip_vswhere SET vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" From 908a95889b2bbcdb30e945ac12e0b6b2e025fa4d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 14:49:45 -0800 Subject: [PATCH 574/937] fix clang-pgo test --- .github/workflows/dev-short-tests.yml | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7ed068d6e..752dda324 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -615,18 +615,6 @@ jobs: run: | make clangbuild - clang-pgo: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: Build PGO Zstd with Clang - env: - CC: clang-14 - LLVM_PROFDATA: llvm-profdata-14 - run: | - make -C programs zstd-pgo - ./programs/zstd -b - gcc-pgo: runs-on: ubuntu-latest steps: @@ -638,6 +626,19 @@ jobs: make -C programs zstd-pgo ./programs/zstd -b + clang-pgo: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Build PGO Zstd with Clang + env: + CC: clang + run: | + sudo apt install -y llvm + llvm-profdata --version + make -C programs zstd-pgo + ./programs/zstd -b + intel-cet-compatibility: runs-on: ubuntu-latest steps: From 0e819c9f933a6b1193cfa26453ba967eb198af13 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 15:15:27 -0800 Subject: [PATCH 575/937] fix meson-linux build test missing the liblzma package --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 752dda324..2867e4f3e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -220,7 +220,7 @@ jobs: - name: Install packages run: | sudo apt-get update - sudo apt-get -y install build-essential python3-pip ninja-build liblz4-dev + sudo apt-get -y install build-essential python3-pip ninja-build liblz4-dev liblzma-dev pip install --pre meson - name: Build with Meson run: | From 196e76efe16623c4a1aa5d636298b59f392671b5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 15:24:27 -0800 Subject: [PATCH 576/937] fix make-external-compressors "only-lzma" test missing the liblzma-dev package --- .github/workflows/dev-short-tests.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 2867e4f3e..7e58b40e6 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -199,7 +199,9 @@ jobs: steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: Build with ${{matrix.name}} - run: ${{matrix.flags}} make zstd + run: | + sudo apt install liblzma-dev + ${{matrix.flags}} make zstd implicit-fall-through: From 80ff61de1de352fb14d4bee6de7f7dd1e254da38 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 15:28:23 -0800 Subject: [PATCH 577/937] fixed cmake-build-and-test-check missing the liblzma library --- .github/workflows/dev-short-tests.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7e58b40e6..0dfd48529 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -89,6 +89,7 @@ jobs: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: cmake build and test run: | + sudo apt install liblzma-dev FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1 cpp-gnu90-c99-compatibility: From 642157cc450c5e2b1c5703ba0a164514ce29061a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 15:39:20 -0800 Subject: [PATCH 578/937] short-test-1: separate tests, giving each a name to better observe where the problem might be --- .github/workflows/commit.yml | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index ca5a85b8f..4fff0f5d7 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -45,16 +45,24 @@ jobs: run: | sudo apt-get update sudo apt-get install gcc-powerpc-linux-gnu gcc-arm-linux-gnueabi gcc-aarch64-linux-gnu libc6-dev-ppc64-powerpc-cross libcurl4-gnutls-dev lib64gcc-11-dev-powerpc-cross - - name: Test - run: |- - make gnu90build; make clean - make gnu99build; make clean - make ppc64build V=1; make clean - make ppcbuild V=1; make clean - make armbuild V=1; make clean - make aarch64build V=1; make clean - make -C tests test-legacy test-longmatch; make clean - make -C lib libzstd-nomt; make clean + - name: gnu90 build + run: make gnu90build && make clean + - name: gnu99 build + run: make gnu99build && make clean + - name: ppc64 build + run: make ppc64build V=1 && make clean + - name: ppc build + run: make ppcbuild V=1 && make clean + - name: arm build + run: make armbuild V=1 && make clean + - name: aarch64 build + run: make aarch64build V=1 && make clean + - name: test-legacy + run: make -C tests test-legacy V=1 && make clean + - name: test-longmatch + run: make -C tests test-longmatch V=1 && make clean + - name: libzstd-nomt build + run: make -C lib libzstd-nomt V=1 && make clean regression-test: runs-on: ubuntu-latest From d4ae5c3752c0f4a918cadcfb9489c91e59bb1f47 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 15:52:27 -0800 Subject: [PATCH 579/937] update installed lib64gcc version --- .github/workflows/commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 4fff0f5d7..2aa8a6d86 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -44,7 +44,7 @@ jobs: - name: Install Dependencies run: | sudo apt-get update - sudo apt-get install gcc-powerpc-linux-gnu gcc-arm-linux-gnueabi gcc-aarch64-linux-gnu libc6-dev-ppc64-powerpc-cross libcurl4-gnutls-dev lib64gcc-11-dev-powerpc-cross + sudo apt-get install gcc-powerpc-linux-gnu gcc-arm-linux-gnueabi gcc-aarch64-linux-gnu libc6-dev-ppc64-powerpc-cross libcurl4-gnutls-dev lib64gcc-13-dev-powerpc-cross - name: gnu90 build run: make gnu90build && make clean - name: gnu99 build From 43626f1ce0ae4f7f3a9f6d5b7b04f54566d49b52 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 16:05:42 -0800 Subject: [PATCH 580/937] zlib-wrapper: separate test components to better understand what is failing --- .github/workflows/dev-short-tests.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 0dfd48529..25919922d 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -141,12 +141,14 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: zlib wrapper test + - name: install valgrind run: | sudo apt-get -qqq update make valgrindinstall - make -C zlibWrapper test - make -C zlibWrapper test-valgrind + - name: zlib wrapper test + run: make -C zlibWrapper test + - name: zlib wrapper test under valgrind + run: make -C zlibWrapper test-valgrind lz4-threadpool-libs: runs-on: ubuntu-latest From 0b96e6d42a9b22eb472a050fcd2cc4be3ffb8e2b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 15 Jan 2025 16:31:00 -0800 Subject: [PATCH 581/937] fixed zlib test new versions of the library generate a different error code --- zlibWrapper/examples/example.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zlibWrapper/examples/example.c b/zlibWrapper/examples/example.c index 99fbf5b19..eaae69747 100644 --- a/zlibWrapper/examples/example.c +++ b/zlibWrapper/examples/example.c @@ -340,7 +340,7 @@ void test_large_deflate(Byte *compr, uLong comprLen, Byte *uncompr, /* =========================================================================== * Test inflate() with large buffers - */ + */ void test_large_inflate(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { int err; @@ -442,8 +442,8 @@ void test_sync(Byte *compr, uLong comprLen, Byte *uncompr, uLong uncomprLen) { CHECK_ERR(err, "inflateSync"); err = inflate(&d_stream, Z_FINISH); - if (err != Z_DATA_ERROR) { - fprintf(stderr, "inflate should report DATA_ERROR\n"); + if (err != Z_STREAM_END) { + fprintf(stderr, "inflate reported %i != %i (Z_STREAM_END)\n", err, Z_STREAM_END); /* Because of incorrect adler32 */ exit(1); } From 886720442f712b6e94c13075edaec1f224c1ae1a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 29 Dec 2024 02:13:57 -0800 Subject: [PATCH 582/937] initial implementation (incomplete) needs to take care of long lengths > 65535 --- lib/compress/zstd_compress.c | 264 ++++++++++++++++++++++++++++++++--- tests/Makefile | 2 +- 2 files changed, 249 insertions(+), 17 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 04b6bb9f1..d91fae619 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -15,7 +15,9 @@ #include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */ #include "../common/mem.h" #include "../common/error_private.h" +#include "compiler.h" #include "hist.h" /* HIST_countFast_wksp */ +#include "zstd_internal.h" #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */ #include "../common/fse.h" #include "../common/huf.h" @@ -7103,15 +7105,226 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, return cSize; } + +#if defined(__AVX2__) + +#include /* AVX2 intrinsics */ + /* + * Convert 2 sequences per iteration, using AVX2 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]). + * + * At the end, instead of extracting two __m128i, + * we use _mm256_permute4x64_epi64(..., 0xE8) to move lane2 into lane1, + * then store the lower 16 bytes in one go. + */ +void convertSequences_noRepcodes( + SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) +{ + /* + * addition: + * For each 128-bit half: (offset+2, litLength+0, matchLength-3, rep+0) + */ + const __m256i addition = _mm256_setr_epi32( + ZSTD_REP_NUM, 0, -MINMATCH, 0, /* for sequence i */ + ZSTD_REP_NUM, 0, -MINMATCH, 0 /* for sequence i+1 */ + ); + + /* + * shuffle mask for byte-level rearrangement in each 128-bit half: + * + * Input layout (after addition) per 128-bit half: + * [ offset+2 (4 bytes) | litLength (4 bytes) | matchLength (4 bytes) | rep (4 bytes) ] + * We only need: + * offBase (4 bytes) = offset+2 + * litLength (2 bytes) = low 2 bytes of litLength + * mlBase (2 bytes) = low 2 bytes of (matchLength) + * => Bytes [0..3, 4..5, 8..9], zero the rest. + */ + const __m256i mask = _mm256_setr_epi8( + /* For the lower 128 bits => sequence i */ + 0, 1, 2, 3, /* offset+2 */ + 4, 5, /* litLength (16 bits) */ + 8, 9, /* matchLength (16 bits) */ + (char)0x80, (char)0x80, (char)0x80, (char)0x80, + (char)0x80, (char)0x80, (char)0x80, (char)0x80, + + /* For the upper 128 bits => sequence i+1 */ + 16,17,18,19, /* offset+2 */ + 20,21, /* litLength */ + 24,25, /* matchLength */ + (char)0x80, (char)0x80, (char)0x80, (char)0x80, + (char)0x80, (char)0x80, (char)0x80, (char)0x80 + ); + + /* + * Next, we'll use _mm256_permute4x64_epi64(vshf, 0xE8). + * Explanation of 0xE8 = 11101000b => [lane0, lane2, lane2, lane3]. + * So the lower 128 bits become [lane0, lane2] => combining seq0 and seq1. + */ +#define PERM_LANE_0X_E8 0xE8 /* [0,2,2,3] in lane indices */ + + size_t i = 0; + /* Process 2 sequences per loop iteration */ + for (; i + 1 < nbSequences; i += 2) { + /* 1) Load 2 ZSTD_Sequence (32 bytes) */ + __m256i vin = _mm256_loadu_si256((__m256i const*)&inSeqs[i]); + + /* 2) Add {2, 0, -3, 0} in each 128-bit half */ + __m256i vadd = _mm256_add_epi32(vin, addition); + + /* 3) Shuffle bytes so each half gives us the 8 bytes we need */ + __m256i vshf = _mm256_shuffle_epi8(vadd, mask); + /* + * Now: + * Lane0 = seq0's 8 bytes + * Lane1 = 0 + * Lane2 = seq1's 8 bytes + * Lane3 = 0 + */ + + /* 4) Permute 64-bit lanes => move Lane2 down into Lane1. */ + __m256i vperm = _mm256_permute4x64_epi64(vshf, PERM_LANE_0X_E8); + /* + * Now the lower 16 bytes (Lane0+Lane1) = [seq0, seq1]. + * The upper 16 bytes are [Lane2, Lane3] = [seq1, 0], but we won't use them. + */ + + /* 5) Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */ + _mm_storeu_si128((__m128i *)&dstSeqs[i], _mm256_castsi256_si128(vperm)); + /* + * This writes out 16 bytes total: + * - offset 0..7 => seq0 (offBase, litLength, mlBase) + * - offset 8..15 => seq1 (offBase, litLength, mlBase) + */ + } + + /* Handle leftover if nbSequences is odd */ + if (i < nbSequences) { + /* Fallback: process last sequence */ + assert(i == nbSequences - 1); + dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset); + /* note: doesn't work if one length is > 65535 */ + dstSeqs[i].litLength = (U16)inSeqs[i].litLength; + dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH); + } +} + +#elif defined(__SSSE3__) + +#include /* SSSE3 intrinsics: _mm_shuffle_epi8 */ +#include /* SSE2 intrinsics: _mm_add_epi32, etc. */ + +/* + * Convert sequences with SSE. + * - offset -> offBase = offset + 2 + * - litLength (32-bit) -> (U16) litLength + * - matchLength (32-bit) -> (U16)(matchLength - 3) + * - rep is discarded. + * + * We shuffle so that only the first 8 bytes in the final 128-bit + * register are used. We still store 16 bytes (low 8 are good, high 8 are "don't care"). + */ +static void convertSequences_noRepcodes(SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) +{ + /* + addition = { offset+2, litLength+0, matchLength-3, rep+0 } + setr means the first argument is placed in the lowest 32 bits, + second in next-lower 32 bits, etc. + */ + const __m128i addition = _mm_setr_epi32(2, 0, -3, 0); + + /* + Shuffle mask: we reorder bytes after the addition. + + Input layout in 128-bit register (after addition): + Bytes: [ 0..3 | 4..7 | 8..11 | 12..15 ] + Fields: offset+2 litLength matchLength rep + + We want in output: + Bytes: [ 0..3 | 4..5 | 6..7 | 8..15 ignore ] + Fields: offset+2 (U16)litLength (U16)(matchLength) + + _mm_shuffle_epi8 picks bytes from the source. A byte of 0x80 means “zero out”. + So we want: + out[0] = in[0], out[1] = in[1], out[2] = in[2], out[3] = in[3], // offset+2 (4 bytes) + out[4] = in[4], out[5] = in[5], // (U16) litLength + out[6] = in[8], out[7] = in[9], // (U16) matchLength + out[8..15] = 0x80 => won't matter if we only care about first 8 bytes + */ + const __m128i mask = _mm_setr_epi8( + 0, 1, 2, 3, /* offset (4 bytes) */ + 4, 5, /* litLength (2 bytes) */ + 8, 9, /* matchLength (2 bytes) */ + (char)0x80, (char)0x80, (char)0x80, (char)0x80, + (char)0x80, (char)0x80, (char)0x80, (char)0x80 + ); + size_t i; + + for (i = 0; i + 1 < nbSequences; i += 2) { + /*-------------------------*/ + /* Process inSeqs[i] */ + /*-------------------------*/ + __m128i vin0 = _mm_loadu_si128((const __m128i *)(const void*)&inSeqs[i]); + __m128i vadd0 = _mm_add_epi32(vin0, addition); + __m128i vshf0 = _mm_shuffle_epi8(vadd0, mask); + _mm_storel_epi64((__m128i *)(void*)&dstSeqs[i], vshf0); + + /*-------------------------*/ + /* Process inSeqs[i + 1] */ + /*-------------------------*/ + __m128i vin1 = _mm_loadu_si128((__m128i const *)(const void*)&inSeqs[i + 1]); + __m128i vadd1 = _mm_add_epi32(vin1, addition); + __m128i vshf1 = _mm_shuffle_epi8(vadd1, mask); + _mm_storel_epi64((__m128i *)(void*)&dstSeqs[i + 1], vshf1); + } + + /* Handle leftover if nbSequences is odd */ + if (i < nbSequences) { + /* Fallback: process last sequence */ + assert(i == nbSequences - 1); + dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset); + /* note: doesn't work if one length is > 65535 */ + dstSeqs[i].litLength = (U16)inSeqs[i].litLength; + dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH); + } + +} + +#else /* no SSE */ + +FORCE_INLINE_TEMPLATE void convertSequences_noRepcodes(SeqDef* dstSeqs, + const ZSTD_Sequence* const inSeqs, size_t nbSequences) +{ + size_t n; + for (n=0; n 65535 */ + dstSeqs[n].litLength = (U16)inSeqs[n].litLength; + dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); + } +} + +#endif + +/* + * Precondition: Sequences must end on an explicit Block Delimiter * @return: 0 on success, or an error code. * Note: Sequence validation functionality has been disabled (removed). * This is helpful to generate a lean main pipeline, improving performance. * It may be re-inserted later. */ -size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, - const ZSTD_Sequence* const inSeqs, size_t nbSequences, - int repcodeResolution) +static size_t ZSTD_convertBlockSequences_internal(ZSTD_CCtx* cctx, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + int repcodeResolution) { Repcodes_t updatedRepcodes; size_t seqNb = 0; @@ -7129,21 +7342,26 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, assert(inSeqs[nbSequences-1].offset == 0); /* Convert Sequences from public format to internal format */ - for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) { - U32 const litLength = inSeqs[seqNb].litLength; - U32 const matchLength = inSeqs[seqNb].matchLength; - U32 offBase; + if (!repcodeResolution) { + convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences); + cctx->seqStore.sequences += nbSequences; + } else { + for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) { + U32 const litLength = inSeqs[seqNb].litLength; + U32 const matchLength = inSeqs[seqNb].matchLength; + U32 offBase; - if (!repcodeResolution) { - offBase = OFFSET_TO_OFFBASE(inSeqs[seqNb].offset); - } else { - U32 const ll0 = (litLength == 0); - offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0); - ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); + if (!repcodeResolution) { + offBase = OFFSET_TO_OFFBASE(inSeqs[seqNb].offset); + } else { + U32 const ll0 = (litLength == 0); + offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0); + ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); + } + + DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); + ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); } - - DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); - ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); } /* If we skipped repcode search while parsing, we need to update repcodes now */ @@ -7172,6 +7390,20 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, return 0; } +static size_t ZSTD_convertBlockSequences_noRepcode(ZSTD_CCtx* cctx, + const ZSTD_Sequence* const inSeqs, size_t nbSequences) +{ + return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); +} + +size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, + const ZSTD_Sequence* const inSeqs, size_t nbSequences, + int repcodeResolution) +{ + (void)repcodeResolution; + return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); +} + typedef struct { size_t nbSequences; size_t blockSize; diff --git a/tests/Makefile b/tests/Makefile index 982181de8..abb0b2b1d 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -148,7 +148,7 @@ fullbench32: CPPFLAGS += -m32 $(FULLBENCHS) : CPPFLAGS += $(MULTITHREAD_CPP) -Wno-deprecated-declarations $(FULLBENCHS) : LDFLAGS += $(MULTITHREAD_LD) $(FULLBENCHS) : DEBUGFLAGS = -DNDEBUG # turn off assert() for speed measurements -$(FULLBENCHS) : DEBUGLEVEL ?= 0 # turn off assert() for speed measurements +$(FULLBENCHS) : DEBUGLEVEL = 0 # turn off assert() for speed measurements $(FULLBENCHS) : $(ZSTD_FILES) $(FULLBENCHS) : $(PRGDIR)/datagen.c $(PRGDIR)/lorem.c $(PRGDIR)/util.c $(PRGDIR)/timefn.c $(PRGDIR)/benchfn.c fullbench.c $(LINK.c) $^ -o $@$(EXT) From d1f0e5fb9738073150e7e5c25b03444b5a6a5389 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 15:51:38 -0800 Subject: [PATCH 583/937] fullbench can run a verification function compressSequencesAndLiterals: fixed long lengths in scalar mode --- lib/compress/zstd_compress.c | 29 +++++++++++-- tests/fullbench.c | 80 +++++++++++++++++++++++++----------- 2 files changed, 80 insertions(+), 29 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d91fae619..c8dc86ccf 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7205,7 +7205,7 @@ void convertSequences_noRepcodes( */ } - /* Handle leftover if nbSequences is odd */ + /* Handle leftover if @nbSequences is odd */ if (i < nbSequences) { /* Fallback: process last sequence */ assert(i == nbSequences - 1); @@ -7301,16 +7301,23 @@ static void convertSequences_noRepcodes(SeqDef* dstSeqs, #else /* no SSE */ -FORCE_INLINE_TEMPLATE void convertSequences_noRepcodes(SeqDef* dstSeqs, +static size_t +convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* const inSeqs, size_t nbSequences) { + size_t longLen = 0; size_t n; for (n=0; n 65535 */ dstSeqs[n].litLength = (U16)inSeqs[n].litLength; dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); + if (UNLIKELY(inSeqs[n].litLength > 65535)) { + assert(longLen == 0); + longLen = n + nbSequences + 1; + } } + return longLen; } #endif @@ -7343,8 +7350,22 @@ static size_t ZSTD_convertBlockSequences_internal(ZSTD_CCtx* cctx, /* Convert Sequences from public format to internal format */ if (!repcodeResolution) { - convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences); - cctx->seqStore.sequences += nbSequences; + size_t const longl = convertSequences_noRepcodes(cctx->seqStore.sequencesStart, inSeqs, nbSequences-1); + cctx->seqStore.sequences = cctx->seqStore.sequencesStart + nbSequences-1; + if (longl) { + DEBUGLOG(5, "long length"); + assert(cctx->seqStore.longLengthType == ZSTD_llt_none); + if (longl <= nbSequences-1) { + DEBUGLOG(5, "long match length detected at pos %zu", longl-1); + cctx->seqStore.longLengthType = ZSTD_llt_matchLength; + cctx->seqStore.longLengthPos = (U32)(longl-1); + } else { + DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences); + assert(longl <= 2* (nbSequences-1)); + cctx->seqStore.longLengthType = ZSTD_llt_literalLength; + cctx->seqStore.longLengthPos = (U32)(longl-nbSequences); + } + } } else { for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) { U32 const litLength = inSeqs[seqNb].litLength; diff --git a/tests/fullbench.c b/tests/fullbench.c index 5683eca25..739e55ef2 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -687,6 +687,23 @@ local_convertSequences(const void* input, size_t inputSize, return nbSeqs; } +static size_t +check_compressedSequences(const void* compressed, size_t cSize, const void* orig, size_t origSize) +{ + size_t decSize; + int diff; + void* decompressed = malloc(origSize); + if (decompressed == NULL) return 2; + + decSize = ZSTD_decompress(decompressed, origSize, compressed, cSize); + if (decSize != origSize) { free(decompressed); DISPLAY("ZSTD_decompress failed (%zu) ", decSize); return 1; } + + diff = memcmp(decompressed, orig, origSize); + if (diff) { free(decompressed); return 1; } + + free(decompressed); + return 0; +} static PrepResult prepCopy(const void* src, size_t srcSize, int cLevel) { @@ -714,40 +731,43 @@ static PrepResult prepShorterDstCapacity(const void* src, size_t srcSize, int cL * List of Scenarios *********************************************************/ -/* if PrepFunction_f returns 0, benchmarking is cancelled */ +/* if PrepFunction_f returns PrepResult.prepBuffSize == 0, benchmarking is cancelled */ typedef PrepResult (*PrepFunction_f)(const void* src, size_t srcSize, int cLevel); typedef size_t (*BenchedFunction_f)(const void* src, size_t srcSize, void* dst, size_t dstSize, void* opaque); +/* must return 0, otherwise verification is considered failed */ +typedef size_t (*VerifFunction_f)(const void* processed, size_t procSize, const void* input, size_t inputSize); typedef struct { const char* name; PrepFunction_f preparation_f; - BenchedFunction_f benchedFunction; + BenchedFunction_f benched_f; + VerifFunction_f verif_f; /* optional */ } BenchScenario; static BenchScenario kScenarios[] = { - { "compress", NULL, local_ZSTD_compress }, - { "decompress", prepDecompress, local_ZSTD_decompress }, - { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx }, - { "decompressDCtx", prepDecompress, local_ZSTD_decompressDCtx }, - { "compressContinue", NULL, local_ZSTD_compressContinue }, - { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict }, - { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue }, - { "compressStream", NULL, local_ZSTD_compressStream }, - { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx }, - { "decompressStream", prepDecompress, local_ZSTD_decompressStream }, - { "compress2", NULL, local_ZSTD_compress2 }, - { "compressStream2, end", NULL, local_ZSTD_compressStream2_end }, - { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end }, - { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue }, - { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue }, - { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end }, - { "compressSequences", prepSequences, local_compressSequences }, - { "compressSequencesAndLiterals", prepSequencesAndLiterals, local_compressSequencesAndLiterals }, - { "convertSequences (1st block)", prepConvertSequences, local_convertSequences }, + { "compress", NULL, local_ZSTD_compress, NULL }, + { "decompress", prepDecompress, local_ZSTD_decompress, NULL }, + { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx, NULL }, + { "decompressDCtx", prepDecompress, local_ZSTD_decompressDCtx, NULL }, + { "compressContinue", NULL, local_ZSTD_compressContinue, NULL }, + { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict, NULL }, + { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue, NULL }, + { "compressStream", NULL, local_ZSTD_compressStream, NULL }, + { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx, NULL }, + { "decompressStream", prepDecompress, local_ZSTD_decompressStream, NULL }, + { "compress2", NULL, local_ZSTD_compress2, NULL }, + { "compressStream2, end", NULL, local_ZSTD_compressStream2_end, NULL }, + { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end, NULL }, + { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue, NULL }, + { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue, NULL }, + { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end, NULL }, + { "compressSequences", prepSequences, local_compressSequences, check_compressedSequences }, + { "compressSequencesAndLiterals", prepSequencesAndLiterals, local_compressSequencesAndLiterals, check_compressedSequences }, + { "convertSequences (1st block)", prepConvertSequences, local_convertSequences, NULL }, #ifndef ZSTD_DLL_IMPORT - { "decodeLiteralsHeader (1st block)", prepLiterals, local_ZSTD_decodeLiteralsHeader }, - { "decodeLiteralsBlock (1st block)", prepLiterals, local_ZSTD_decodeLiteralsBlock }, - { "decodeSeqHeaders (1st block)", prepSequences1stBlock, local_ZSTD_decodeSeqHeaders }, + { "decodeLiteralsHeader (1st block)", prepLiterals, local_ZSTD_decodeLiteralsHeader, NULL }, + { "decodeLiteralsBlock (1st block)", prepLiterals, local_ZSTD_decodeLiteralsBlock, NULL }, + { "decodeSeqHeaders (1st block)", prepSequences1stBlock, local_ZSTD_decodeSeqHeaders, NULL }, #endif }; #define NB_SCENARIOS (sizeof(kScenarios) / sizeof(kScenarios[0])) @@ -767,13 +787,15 @@ static int benchMem(unsigned scenarioID, const char* benchName; BMK_benchFn_t benchFunction; PrepFunction_f prep_f; + VerifFunction_f verif_f; int errorcode = 0; if (scenarioID >= NB_SCENARIOS) return 0; /* scenario doesn't exist */ benchName = kScenarios[scenarioID].name; - benchFunction = kScenarios[scenarioID].benchedFunction; + benchFunction = kScenarios[scenarioID].benched_f; prep_f = kScenarios[scenarioID].preparation_f; + verif_f = kScenarios[scenarioID].verif_f; if (prep_f == NULL) prep_f = prepCopy; /* default */ /* Initialization */ @@ -857,6 +879,14 @@ static int benchMem(unsigned scenarioID, scenarioID, benchName, (double)origSrcSize * TIMELOOP_NANOSEC / bestResult.nanoSecPerRun / MB_UNIT, (unsigned)newResult.sumOfReturn ); + + if (verif_f) { + size_t const vRes = verif_f(dst, newResult.sumOfReturn, origSrc, origSrcSize); + if (vRes) { + DISPLAY(" validation failed ! (%zu)\n", vRes); + break; + } + } } if ( BMK_isCompleted_TimedFn(tfs) ) break; From 8d621645891a8ec8a114fe09e94f967f2049352b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 16:42:36 -0800 Subject: [PATCH 584/937] control long length within AVX2 implementation --- lib/compress/zstd_compress.c | 150 ++++++++++++++--------------------- 1 file changed, 60 insertions(+), 90 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c8dc86ccf..a52980313 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7121,8 +7121,12 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * At the end, instead of extracting two __m128i, * we use _mm256_permute4x64_epi64(..., 0xE8) to move lane2 into lane1, * then store the lower 16 bytes in one go. + * + * @returns 0 on succes, with no long length detected + * @returns > 0 if there is one long length (> 65535), + * indicating the position, and type. */ -void convertSequences_noRepcodes( +size_t convertSequences_noRepcodes( SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) @@ -7136,6 +7140,9 @@ void convertSequences_noRepcodes( ZSTD_REP_NUM, 0, -MINMATCH, 0 /* for sequence i+1 */ ); + /* limit: check if there is a long length */ + const __m256i limit = _mm256_set1_epi32(65535); + /* * shuffle mask for byte-level rearrangement in each 128-bit half: * @@ -7170,16 +7177,20 @@ void convertSequences_noRepcodes( */ #define PERM_LANE_0X_E8 0xE8 /* [0,2,2,3] in lane indices */ - size_t i = 0; + size_t longLen = 0, i = 0; /* Process 2 sequences per loop iteration */ for (; i + 1 < nbSequences; i += 2) { - /* 1) Load 2 ZSTD_Sequence (32 bytes) */ + /* Load 2 ZSTD_Sequence (32 bytes) */ __m256i vin = _mm256_loadu_si256((__m256i const*)&inSeqs[i]); - /* 2) Add {2, 0, -3, 0} in each 128-bit half */ + /* Add {2, 0, -3, 0} in each 128-bit half */ __m256i vadd = _mm256_add_epi32(vin, addition); - /* 3) Shuffle bytes so each half gives us the 8 bytes we need */ + /* Check for long length */ + __m256i cmp = _mm256_cmpgt_epi32(vadd, limit); // 0xFFFFFFFF for element > 65535 + int cmp_res = _mm256_movemask_epi8(cmp); + + /* Shuffle bytes so each half gives us the 8 bytes we need */ __m256i vshf = _mm256_shuffle_epi8(vadd, mask); /* * Now: @@ -7189,20 +7200,44 @@ void convertSequences_noRepcodes( * Lane3 = 0 */ - /* 4) Permute 64-bit lanes => move Lane2 down into Lane1. */ + /* Permute 64-bit lanes => move Lane2 down into Lane1. */ __m256i vperm = _mm256_permute4x64_epi64(vshf, PERM_LANE_0X_E8); /* * Now the lower 16 bytes (Lane0+Lane1) = [seq0, seq1]. * The upper 16 bytes are [Lane2, Lane3] = [seq1, 0], but we won't use them. */ - /* 5) Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */ + /* Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */ _mm_storeu_si128((__m128i *)&dstSeqs[i], _mm256_castsi256_si128(vperm)); /* * This writes out 16 bytes total: * - offset 0..7 => seq0 (offBase, litLength, mlBase) * - offset 8..15 => seq1 (offBase, litLength, mlBase) */ + + /* check (unlikely) long lengths > 65535 + * indices for lengths correspond to bits [4..7], [8..11], [20..23], [24..27] + * => combined mask = 0x0FF00FF0 + */ + if (UNLIKELY((cmp_res & 0x0FF00FF0) != 0)) { + /* long length detected: let's figure out which one*/ + if (inSeqs[i].matchLength > 65535+MINMATCH) { + assert(longLen == 0); + longLen = i + 1; + } + if (inSeqs[i].litLength > 65535) { + assert(longLen == 0); + longLen = i + nbSequences + 1; + } + if (inSeqs[i+1].matchLength > 65535+MINMATCH) { + assert(longLen == 0); + longLen = i + 1 + 1; + } + if (inSeqs[i+1].litLength > 65535) { + assert(longLen == 0); + longLen = i + 1 + nbSequences + 1; + } + } } /* Handle leftover if @nbSequences is odd */ @@ -7213,93 +7248,24 @@ void convertSequences_noRepcodes( /* note: doesn't work if one length is > 65535 */ dstSeqs[i].litLength = (U16)inSeqs[i].litLength; dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH); + if (UNLIKELY(inSeqs[i].matchLength > 65535+MINMATCH)) { + assert(longLen == 0); + longLen = i + 1; + } + if (UNLIKELY(inSeqs[i].litLength > 65535)) { + assert(longLen == 0); + longLen = i + nbSequences + 1; + } } + + return longLen; } -#elif defined(__SSSE3__) +/* 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 platforms (before AVX2) */ -#include /* SSSE3 intrinsics: _mm_shuffle_epi8 */ -#include /* SSE2 intrinsics: _mm_add_epi32, etc. */ - -/* - * Convert sequences with SSE. - * - offset -> offBase = offset + 2 - * - litLength (32-bit) -> (U16) litLength - * - matchLength (32-bit) -> (U16)(matchLength - 3) - * - rep is discarded. - * - * We shuffle so that only the first 8 bytes in the final 128-bit - * register are used. We still store 16 bytes (low 8 are good, high 8 are "don't care"). - */ -static void convertSequences_noRepcodes(SeqDef* dstSeqs, - const ZSTD_Sequence* inSeqs, - size_t nbSequences) -{ - /* - addition = { offset+2, litLength+0, matchLength-3, rep+0 } - setr means the first argument is placed in the lowest 32 bits, - second in next-lower 32 bits, etc. - */ - const __m128i addition = _mm_setr_epi32(2, 0, -3, 0); - - /* - Shuffle mask: we reorder bytes after the addition. - - Input layout in 128-bit register (after addition): - Bytes: [ 0..3 | 4..7 | 8..11 | 12..15 ] - Fields: offset+2 litLength matchLength rep - - We want in output: - Bytes: [ 0..3 | 4..5 | 6..7 | 8..15 ignore ] - Fields: offset+2 (U16)litLength (U16)(matchLength) - - _mm_shuffle_epi8 picks bytes from the source. A byte of 0x80 means “zero out”. - So we want: - out[0] = in[0], out[1] = in[1], out[2] = in[2], out[3] = in[3], // offset+2 (4 bytes) - out[4] = in[4], out[5] = in[5], // (U16) litLength - out[6] = in[8], out[7] = in[9], // (U16) matchLength - out[8..15] = 0x80 => won't matter if we only care about first 8 bytes - */ - const __m128i mask = _mm_setr_epi8( - 0, 1, 2, 3, /* offset (4 bytes) */ - 4, 5, /* litLength (2 bytes) */ - 8, 9, /* matchLength (2 bytes) */ - (char)0x80, (char)0x80, (char)0x80, (char)0x80, - (char)0x80, (char)0x80, (char)0x80, (char)0x80 - ); - size_t i; - - for (i = 0; i + 1 < nbSequences; i += 2) { - /*-------------------------*/ - /* Process inSeqs[i] */ - /*-------------------------*/ - __m128i vin0 = _mm_loadu_si128((const __m128i *)(const void*)&inSeqs[i]); - __m128i vadd0 = _mm_add_epi32(vin0, addition); - __m128i vshf0 = _mm_shuffle_epi8(vadd0, mask); - _mm_storel_epi64((__m128i *)(void*)&dstSeqs[i], vshf0); - - /*-------------------------*/ - /* Process inSeqs[i + 1] */ - /*-------------------------*/ - __m128i vin1 = _mm_loadu_si128((__m128i const *)(const void*)&inSeqs[i + 1]); - __m128i vadd1 = _mm_add_epi32(vin1, addition); - __m128i vshf1 = _mm_shuffle_epi8(vadd1, mask); - _mm_storel_epi64((__m128i *)(void*)&dstSeqs[i + 1], vshf1); - } - - /* Handle leftover if nbSequences is odd */ - if (i < nbSequences) { - /* Fallback: process last sequence */ - assert(i == nbSequences - 1); - dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset); - /* note: doesn't work if one length is > 65535 */ - dstSeqs[i].litLength = (U16)inSeqs[i].litLength; - dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH); - } - -} - -#else /* no SSE */ +#else /* no AVX2 */ static size_t convertSequences_noRepcodes(SeqDef* dstSeqs, @@ -7312,6 +7278,10 @@ convertSequences_noRepcodes(SeqDef* dstSeqs, /* note: doesn't work if one length is > 65535 */ dstSeqs[n].litLength = (U16)inSeqs[n].litLength; dstSeqs[n].mlBase = (U16)(inSeqs[n].matchLength - MINMATCH); + 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; From bfc58f5ba24a3c27edfbc61288e09d2837235456 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 17:04:12 -0800 Subject: [PATCH 585/937] generalize validation function --- tests/fullbench.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 739e55ef2..3cc5c2341 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -745,22 +745,22 @@ typedef struct { } BenchScenario; static BenchScenario kScenarios[] = { - { "compress", NULL, local_ZSTD_compress, NULL }, + { "compress", NULL, local_ZSTD_compress, check_compressedSequences }, { "decompress", prepDecompress, local_ZSTD_decompress, NULL }, - { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx, NULL }, + { "compress_freshCCtx", NULL, local_ZSTD_compress_freshCCtx, check_compressedSequences }, { "decompressDCtx", prepDecompress, local_ZSTD_decompressDCtx, NULL }, - { "compressContinue", NULL, local_ZSTD_compressContinue, NULL }, + { "compressContinue", NULL, local_ZSTD_compressContinue, check_compressedSequences }, { "compressContinue_extDict", NULL, local_ZSTD_compressContinue_extDict, NULL }, { "decompressContinue", prepDecompress, local_ZSTD_decompressContinue, NULL }, - { "compressStream", NULL, local_ZSTD_compressStream, NULL }, - { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx, NULL }, + { "compressStream", NULL, local_ZSTD_compressStream, check_compressedSequences }, + { "compressStream_freshCCtx", NULL, local_ZSTD_compressStream_freshCCtx, check_compressedSequences }, { "decompressStream", prepDecompress, local_ZSTD_decompressStream, NULL }, - { "compress2", NULL, local_ZSTD_compress2, NULL }, - { "compressStream2, end", NULL, local_ZSTD_compressStream2_end, NULL }, - { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end, NULL }, - { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue, NULL }, - { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue, NULL }, - { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end, NULL }, + { "compress2", NULL, local_ZSTD_compress2, check_compressedSequences }, + { "compressStream2, end", NULL, local_ZSTD_compressStream2_end, check_compressedSequences }, + { "compressStream2, end & short", prepShorterDstCapacity, local_ZSTD_compressStream2_end, check_compressedSequences }, + { "compressStream2, continue", NULL, local_ZSTD_compressStream2_continue, check_compressedSequences }, + { "compressStream2, -T2, continue", NULL, local_ZSTD_compress_generic_T2_continue, check_compressedSequences }, + { "compressStream2, -T2, end", NULL, local_ZSTD_compress_generic_T2_end, check_compressedSequences }, { "compressSequences", prepSequences, local_compressSequences, check_compressedSequences }, { "compressSequencesAndLiterals", prepSequencesAndLiterals, local_compressSequencesAndLiterals, check_compressedSequences }, { "convertSequences (1st block)", prepConvertSequences, local_convertSequences, NULL }, From 8eb2587432d70359f26ff98fd12db7e8c9be7515 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 19:29:06 -0800 Subject: [PATCH 586/937] added benchmark for get1BlockSummary() --- lib/compress/zstd_compress.c | 10 ++-------- lib/compress/zstd_compress_internal.h | 7 +++++++ tests/fullbench.c | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index a52980313..d5e3d1c78 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7395,13 +7395,7 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); } -typedef struct { - size_t nbSequences; - size_t blockSize; - size_t litSize; -} BlockSummary; - -static BlockSummary get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) +BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { size_t blockSize = 0; size_t litSize = 0; @@ -7456,7 +7450,7 @@ ZSTD_compressSequencesAndLiterals_internal(ZSTD_CCtx* cctx, while (nbSequences) { size_t compressedSeqsSize, cBlockSize, conversionStatus; - BlockSummary const block = get1BlockSummary(inSeqs, nbSequences); + BlockSummary const block = ZSTD_get1BlockSummary(inSeqs, nbSequences); U32 const lastBlock = (block.nbSequences == nbSequences); FORWARD_IF_ERROR(block.nbSequences, "Error while trying to determine nb of sequences for a block"); assert(block.nbSequences <= nbSequences); diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index 2be67a124..ca5e2a4c5 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1525,6 +1525,13 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, int const repcodeResolution); +typedef struct { + size_t nbSequences; + size_t blockSize; + size_t litSize; +} BlockSummary; + +BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs); /* ============================================================== * Private declarations diff --git a/tests/fullbench.c b/tests/fullbench.c index 3cc5c2341..7d77bd176 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -705,6 +705,26 @@ check_compressedSequences(const void* compressed, size_t cSize, const void* orig return 0; } +static size_t +local_get1BlockSummary(const void* input, size_t inputSize, + void* dst, size_t dstCapacity, + void* payload) +{ + const char* ip = input; + size_t const blockSize = MEM_read32(ip); + size_t const nbSeqs = MEM_read32(ip+=4); + const ZSTD_Sequence* seqs = (const ZSTD_Sequence*)(const void*)(ip+=4); + ZSTD_CCtx_reset(g_zcc, ZSTD_reset_session_and_parameters); + ZSTD_resetSeqStore(&g_zcc->seqStore); + ZSTD_CCtx_setParameter(g_zcc, ZSTD_c_blockDelimiters, ZSTD_sf_explicitBlockDelimiters); + assert(8 + nbSeqs * sizeof(ZSTD_Sequence) == inputSize); (void)inputSize; + (void)dst; (void)dstCapacity; + (void)payload; (void)blockSize; + + (void)ZSTD_get1BlockSummary(seqs, nbSeqs); + return nbSeqs; +} + static PrepResult prepCopy(const void* src, size_t srcSize, int cLevel) { PrepResult r = PREPRESULT_INIT; @@ -764,6 +784,7 @@ static BenchScenario kScenarios[] = { { "compressSequences", prepSequences, local_compressSequences, check_compressedSequences }, { "compressSequencesAndLiterals", prepSequencesAndLiterals, local_compressSequencesAndLiterals, check_compressedSequences }, { "convertSequences (1st block)", prepConvertSequences, local_convertSequences, NULL }, + { "get1BlockSummary (1st block)", prepConvertSequences, local_get1BlockSummary, NULL }, #ifndef ZSTD_DLL_IMPORT { "decodeLiteralsHeader (1st block)", prepLiterals, local_ZSTD_decodeLiteralsHeader, NULL }, { "decodeLiteralsBlock (1st block)", prepLiterals, local_ZSTD_decodeLiteralsBlock, NULL }, From b6a4d5a8ba29bc873c95098103f57f987cfacd23 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 19:34:06 -0800 Subject: [PATCH 587/937] minor +10% speed improvement for scalar ZSTD_get1BlockSummary() --- lib/compress/zstd_compress.c | 61 ++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d5e3d1c78..11933fb3c 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7395,14 +7395,68 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); } +#if 0 && defined(__AVX2__) + +/* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ +#if defined(__GNUC__) +# define ALIGNED32 __attribute__((aligned(32))) +#else +# define ALIGNED32 +#endif + BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { - size_t blockSize = 0; + size_t i; + __m256i sumVec; /* accumulates match+lit in 32-bit lanes */ + __m256i mask; /* shuffling control */ + ALIGNED32 int tmp[8]; /* temporary buffer for reduction */ + uint64_t sum; + int k; + + sumVec = _mm256_setzero_si256(); + mask = _mm256_setr_epi32( + 1,5, /* match(0), match(1) */ + 2,6, /* lit(0), lit(1) */ + 1,5, /* match(0), match(1) */ + 2,6 /* lit(0), lit(1) */ + ); + + /* Process 2 structs (32 bytes) at a time */ + for (i = 0; i + 2 <= count; i += 2) { + /* Load two consecutive MyStructs (8×4 = 32 bytes) */ + __m256i data = _mm256_loadu_si256((const __m256i*)&arr[i]); + /* Shuffle out lanes 1,2,5,6 => match(0), match(1), lit(0), lit(1), repeated */ + __m256i selected = _mm256_permutevar8x32_epi32(data, mask); + /* Accumulate in sumVec */ + sumVec = _mm256_add_epi32(sumVec, selected); + } + + /* Horizontal reduction of sumVec */ + _mm256_store_si256((__m256i*)tmp, sumVec); + sum = 0; + for (k = 0; k < 8; k++) { + sum += (uint64_t)tmp[k]; /* each lane is match+lit from pairs, repeated twice */ + } + + /* Handle the leftover (if count is odd) */ + for (; i < count; i++) { + sum += arr[i].matchLength; + sum += arr[i].litLength; + } + + return sum; +} + +#else + +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 Date: Tue, 7 Jan 2025 23:32:05 -0800 Subject: [PATCH 588/937] AVX2 version of ZSTD_get1BlockSummary() --- lib/compress/zstd_compress.c | 69 ++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 30 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 11933fb3c..445c5613a 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7395,56 +7395,65 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); } -#if 0 && defined(__AVX2__) +#if defined(__AVX2__) /* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ #if defined(__GNUC__) # define ALIGNED32 __attribute__((aligned(32))) +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ +# define ALIGNED32 alignas(32) #else + /* this compiler will require its own alignment instruction */ # define ALIGNED32 #endif BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { size_t i; - __m256i sumVec; /* accumulates match+lit in 32-bit lanes */ - __m256i mask; /* shuffling control */ - ALIGNED32 int tmp[8]; /* temporary buffer for reduction */ - uint64_t sum; - int k; - - sumVec = _mm256_setzero_si256(); - mask = _mm256_setr_epi32( - 1,5, /* match(0), match(1) */ - 2,6, /* lit(0), lit(1) */ - 1,5, /* match(0), match(1) */ - 2,6 /* lit(0), lit(1) */ - ); + __m256i const zeroVec = _mm256_setzero_si256(); + __m256i sumVec = zeroVec; /* accumulates match+lit in 32-bit lanes */ + __m256i shuffle32; /* shuffling control */ + ALIGNED32 U32 tmp[8]; /* temporary buffer for reduction */ + size_t mSum = 0, lSum = 0; /* Process 2 structs (32 bytes) at a time */ - for (i = 0; i + 2 <= count; i += 2) { - /* Load two consecutive MyStructs (8×4 = 32 bytes) */ - __m256i data = _mm256_loadu_si256((const __m256i*)&arr[i]); - /* Shuffle out lanes 1,2,5,6 => match(0), match(1), lit(0), lit(1), repeated */ - __m256i selected = _mm256_permutevar8x32_epi32(data, mask); + for (i = 0; i + 2 <= nbSeqs; i += 2) { + /* Load two consecutive ZSTD_Sequence (8×4 = 32 bytes) */ + __m256i data = _mm256_loadu_si256((const __m256i*)&seqs[i]); + /* check end of block signal */ + __m256i cmp = _mm256_cmpeq_epi32(data, zeroVec); + int cmp_res = _mm256_movemask_epi8(cmp); + /* indices for match lengths correspond to bits [8..11], [24..27] + * => combined mask = 0x0F000F00 */ + if (cmp_res & 0x0F000F00) break; /* Accumulate in sumVec */ - sumVec = _mm256_add_epi32(sumVec, selected); + sumVec = _mm256_add_epi32(sumVec, data); } - /* Horizontal reduction of sumVec */ + /* Horizontal reduction */ _mm256_store_si256((__m256i*)tmp, sumVec); - sum = 0; - for (k = 0; k < 8; k++) { - sum += (uint64_t)tmp[k]; /* each lane is match+lit from pairs, repeated twice */ + lSum = tmp[1] + tmp[5]; + mSum = tmp[2] + tmp[6]; + + /* Handle the leftover */ + for (; i < nbSeqs; i++) { + lSum += seqs[i].litLength; + mSum += seqs[i].matchLength; + if (seqs[i].matchLength == 0) break; /* end of block */ } - /* Handle the leftover (if count is odd) */ - for (; i < count; i++) { - sum += arr[i].matchLength; - sum += arr[i].litLength; + if (i==nbSeqs) { + /* reaching end of sequences: end of block signal was not present */ + BlockSummary bs; + bs.nbSequences = ERROR(externalSequences_invalid); + return bs; + } + { BlockSummary bs; + bs.nbSequences = i+1; + bs.blockSize = lSum + mSum; + bs.litSize = lSum; + return bs; } - - return sum; } #else From cd53924eff684146b67e890d7b48158c37eca32c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 23:34:19 -0800 Subject: [PATCH 589/937] removed erroneous #includes that were automatically added by the editor without notification --- lib/compress/zstd_compress.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 445c5613a..beff0aae6 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -15,9 +15,7 @@ #include "../common/zstd_deps.h" /* INT_MAX, ZSTD_memset, ZSTD_memcpy */ #include "../common/mem.h" #include "../common/error_private.h" -#include "compiler.h" #include "hist.h" /* HIST_countFast_wksp */ -#include "zstd_internal.h" #define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */ #include "../common/fse.h" #include "../common/huf.h" From db3d48823a75a12a5ad9221e5a39191ff0044d3a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 23:40:49 -0800 Subject: [PATCH 590/937] no need for specialized variant the branch is not in the hot loop --- lib/compress/zstd_compress.c | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index beff0aae6..8e49169b1 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7297,7 +7297,7 @@ convertSequences_noRepcodes(SeqDef* dstSeqs, * This is helpful to generate a lean main pipeline, improving performance. * It may be re-inserted later. */ -static size_t ZSTD_convertBlockSequences_internal(ZSTD_CCtx* cctx, +size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, const ZSTD_Sequence* const inSeqs, size_t nbSequences, int repcodeResolution) { @@ -7379,20 +7379,6 @@ static size_t ZSTD_convertBlockSequences_internal(ZSTD_CCtx* cctx, return 0; } -static size_t ZSTD_convertBlockSequences_noRepcode(ZSTD_CCtx* cctx, - const ZSTD_Sequence* const inSeqs, size_t nbSequences) -{ - return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); -} - -size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, - const ZSTD_Sequence* const inSeqs, size_t nbSequences, - int repcodeResolution) -{ - (void)repcodeResolution; - return ZSTD_convertBlockSequences_internal(cctx, inSeqs, nbSequences, 0); -} - #if defined(__AVX2__) /* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ From 4aaf9cefe9bdda1fafb5f6a5ba13294d2b478bd7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 23:45:15 -0800 Subject: [PATCH 591/937] fix minor conversion warning --- lib/compress/zstd_compress.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 8e49169b1..19fb584fb 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7157,15 +7157,15 @@ size_t convertSequences_noRepcodes( 0, 1, 2, 3, /* offset+2 */ 4, 5, /* litLength (16 bits) */ 8, 9, /* matchLength (16 bits) */ - (char)0x80, (char)0x80, (char)0x80, (char)0x80, - (char)0x80, (char)0x80, (char)0x80, (char)0x80, + (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, + (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, /* For the upper 128 bits => sequence i+1 */ 16,17,18,19, /* offset+2 */ 20,21, /* litLength */ 24,25, /* matchLength */ - (char)0x80, (char)0x80, (char)0x80, (char)0x80, - (char)0x80, (char)0x80, (char)0x80, (char)0x80 + (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, + (BYTE)0x80, (BYTE)0x80, (BYTE)0x80, (BYTE)0x80 ); /* From 57a45541927180724712b651ed1fb3e125105f30 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 7 Jan 2025 23:59:01 -0800 Subject: [PATCH 592/937] removed unused variable --- lib/compress/zstd_compress.c | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 19fb584fb..e5b0cd80e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7396,7 +7396,6 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) size_t i; __m256i const zeroVec = _mm256_setzero_si256(); __m256i sumVec = zeroVec; /* accumulates match+lit in 32-bit lanes */ - __m256i shuffle32; /* shuffling control */ ALIGNED32 U32 tmp[8]; /* temporary buffer for reduction */ size_t mSum = 0, lSum = 0; From aa2cdf964f93d96113c09028ad7354ca2debc849 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 8 Jan 2025 10:51:57 -0800 Subject: [PATCH 593/937] added compilation-time checks to ensure AVX2 code is valid since it depends on a specific definition of ZSTD_Sequence structure. --- lib/compress/zstd_compress.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index e5b0cd80e..f6cde3d09 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7176,6 +7176,17 @@ size_t convertSequences_noRepcodes( #define PERM_LANE_0X_E8 0xE8 /* [0,2,2,3] in lane indices */ size_t longLen = 0, i = 0; + + /* AVX 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); + /* Process 2 sequences per loop iteration */ for (; i + 1 < nbSequences; i += 2) { /* Load 2 ZSTD_Sequence (32 bytes) */ @@ -7398,6 +7409,7 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) __m256i sumVec = zeroVec; /* accumulates match+lit in 32-bit lanes */ ALIGNED32 U32 tmp[8]; /* temporary buffer for reduction */ size_t mSum = 0, lSum = 0; + ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16); /* Process 2 structs (32 bytes) at a time */ for (i = 0; i + 2 <= nbSeqs; i += 2) { @@ -7408,6 +7420,7 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) int cmp_res = _mm256_movemask_epi8(cmp); /* indices for match lengths correspond to bits [8..11], [24..27] * => combined mask = 0x0F000F00 */ + ZSTD_STATIC_ASSERT(offsetof(ZSTD_Sequence, matchLength) == 8); if (cmp_res & 0x0F000F00) break; /* Accumulate in sumVec */ sumVec = _mm256_add_epi32(sumVec, data); From e3181cfd325db59dbdeadcaf91b8187f49c5546c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 8 Jan 2025 14:25:03 -0800 Subject: [PATCH 594/937] minor code doc update --- lib/compress/zstd_compress.c | 16 ++++++++-------- lib/zstd.h | 5 +++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index f6cde3d09..bdf0e8287 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7196,8 +7196,8 @@ size_t convertSequences_noRepcodes( __m256i vadd = _mm256_add_epi32(vin, addition); /* Check for long length */ - __m256i cmp = _mm256_cmpgt_epi32(vadd, limit); // 0xFFFFFFFF for element > 65535 - int cmp_res = _mm256_movemask_epi8(cmp); + __m256i ll_cmp = _mm256_cmpgt_epi32(vadd, limit); /* 0xFFFFFFFF for element > 65535 */ + int ll_res = _mm256_movemask_epi8(ll_cmp); /* Shuffle bytes so each half gives us the 8 bytes we need */ __m256i vshf = _mm256_shuffle_epi8(vadd, mask); @@ -7228,7 +7228,7 @@ size_t convertSequences_noRepcodes( * indices for lengths correspond to bits [4..7], [8..11], [20..23], [24..27] * => combined mask = 0x0FF00FF0 */ - if (UNLIKELY((cmp_res & 0x0FF00FF0) != 0)) { + if (UNLIKELY((ll_res & 0x0FF00FF0) != 0)) { /* long length detected: let's figure out which one*/ if (inSeqs[i].matchLength > 65535+MINMATCH) { assert(longLen == 0); @@ -7251,12 +7251,12 @@ size_t convertSequences_noRepcodes( /* Handle leftover if @nbSequences is odd */ if (i < nbSequences) { - /* Fallback: process last sequence */ + /* process last sequence */ assert(i == nbSequences - 1); dstSeqs[i].offBase = OFFSET_TO_OFFBASE(inSeqs[i].offset); - /* note: doesn't work if one length is > 65535 */ dstSeqs[i].litLength = (U16)inSeqs[i].litLength; dstSeqs[i].mlBase = (U16)(inSeqs[i].matchLength - MINMATCH); + /* check (unlikely) long lengths > 65535 */ if (UNLIKELY(inSeqs[i].matchLength > 65535+MINMATCH)) { assert(longLen == 0); longLen = i + 1; @@ -7271,8 +7271,8 @@ size_t convertSequences_noRepcodes( } /* 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 platforms (before AVX2) */ + * 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 */ @@ -7284,9 +7284,9 @@ convertSequences_noRepcodes(SeqDef* dstSeqs, size_t n; for (n=0; n 65535 */ 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; diff --git a/lib/zstd.h b/lib/zstd.h index 907a377d1..b8c0644a7 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1696,7 +1696,8 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, * - Not compatible with frame checksum, which must be disabled * - If any block is incompressible, will fail and return an error * - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - * - the buffer @literals must have a size @litCapacity which is larger than @litSize by at least 8 bytes. + * - @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. * @return : final compressed size, or a ZSTD error code. */ @@ -1704,7 +1705,7 @@ ZSTDLIB_STATIC_API size_t ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize, size_t litCapacity, + const void* literals, size_t litSize, size_t litBufCapacity, size_t decompressedSize); From 6f8e6f3c97c8e95527a29c4667edca6b793f798f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 14 Jan 2025 14:44:02 -0800 Subject: [PATCH 595/937] create new compilation macro ZSTD_ARCH_X86_AVX2 --- lib/common/compiler.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index b6cbcee03..f636b7f25 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -224,6 +224,9 @@ /* compile time determination of SIMD support */ #if !defined(ZSTD_NO_INTRINSICS) +# if defined(__AVX2__) +# define ZSTD_ARCH_X86_AVX2 +# endif # if defined(__SSE2__) || defined(_M_AMD64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) # define ZSTD_ARCH_X86_SSE2 # endif @@ -231,6 +234,9 @@ # define ZSTD_ARCH_ARM_NEON # endif # +# if defined(ZSTD_ARCH_X86_AVX2) +# include +# endif # if defined(ZSTD_ARCH_X86_SSE2) # include # elif defined(ZSTD_ARCH_ARM_NEON) From debe3d20d9ea0aaa45fbb692302347d0ece9f2c0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 14 Jan 2025 14:54:02 -0800 Subject: [PATCH 596/937] removed unused branch --- lib/compress/zstd_compress.c | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index bdf0e8287..55622cbd5 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7349,18 +7349,12 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, for (seqNb = 0; seqNb < nbSequences - 1 ; seqNb++) { U32 const litLength = inSeqs[seqNb].litLength; U32 const matchLength = inSeqs[seqNb].matchLength; - U32 offBase; - - if (!repcodeResolution) { - offBase = OFFSET_TO_OFFBASE(inSeqs[seqNb].offset); - } else { - U32 const ll0 = (litLength == 0); - offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0); - ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); - } + U32 const ll0 = (litLength == 0); + U32 const offBase = ZSTD_finalizeOffBase(inSeqs[seqNb].offset, updatedRepcodes.rep, ll0); DEBUGLOG(6, "Storing sequence: (of: %u, ml: %u, ll: %u)", offBase, matchLength, litLength); ZSTD_storeSeqOnly(&cctx->seqStore, litLength, offBase, matchLength); + ZSTD_updateRep(updatedRepcodes.rep, offBase, ll0); } } From 2f3ee8b5309958a2bc1fc7477e703fd8195a31ea Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 14 Jan 2025 14:56:10 -0800 Subject: [PATCH 597/937] changed code compilation test to employ ZSTD_ARCH_X86_AVX2 --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 55622cbd5..8e5f369bb 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7384,7 +7384,7 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, return 0; } -#if defined(__AVX2__) +#if defined(ZSTD_ARCH_X86_AVX2) /* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ #if defined(__GNUC__) From 8bff69af869fca1cc44172c2ae5d5f995322509b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 14 Jan 2025 15:54:10 -0800 Subject: [PATCH 598/937] Alignment instruction ZSTD_ALIGNED() in common/compiler.h --- lib/common/compiler.h | 15 ++++++++++++++- lib/compress/zstd_compress.c | 12 +----------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index f636b7f25..2a8002288 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -281,7 +281,7 @@ #endif /*-************************************************************** -* Alignment check +* Alignment *****************************************************************/ /* @return 1 if @u is a 2^n value, 0 otherwise @@ -315,6 +315,19 @@ MEM_STATIC int ZSTD_isPower2(size_t u) { # endif #endif /* ZSTD_ALIGNOF */ +#ifndef ZSTD_ALIGNED +/* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ +# if defined(__GNUC__) +# define ZSTD_ALIGNED(a) __attribute__((aligned(a))) +# elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ +# define ZSTD_ALIGNED(a) alignas(a) +# else + /* this compiler will require its own alignment instruction */ +# define ZSTD_ALIGNED(...) +# endif +#endif /* ZSTD_ALIGNED */ + + /*-************************************************************** * Sanitizer *****************************************************************/ diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 8e5f369bb..eba2d07dc 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7386,22 +7386,12 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, #if defined(ZSTD_ARCH_X86_AVX2) -/* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ -#if defined(__GNUC__) -# define ALIGNED32 __attribute__((aligned(32))) -#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ -# define ALIGNED32 alignas(32) -#else - /* this compiler will require its own alignment instruction */ -# define ALIGNED32 -#endif - BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { size_t i; __m256i const zeroVec = _mm256_setzero_si256(); __m256i sumVec = zeroVec; /* accumulates match+lit in 32-bit lanes */ - ALIGNED32 U32 tmp[8]; /* temporary buffer for reduction */ + ZSTD_ALIGNED(32) U32 tmp[8]; /* temporary buffer for reduction */ size_t mSum = 0, lSum = 0; ZSTD_STATIC_ASSERT(sizeof(ZSTD_Sequence) == 16); From 87f0a4fbe0a1ffcaab4618f2aa76545e225acf07 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 14 Jan 2025 15:57:05 -0800 Subject: [PATCH 599/937] restore full equation do not solve the equation, even though some members cancel each other, this is done for clarity, we'll let the compiler do the resolution at compile time. --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index eba2d07dc..e26e78a8f 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7342,7 +7342,7 @@ size_t ZSTD_convertBlockSequences(ZSTD_CCtx* cctx, DEBUGLOG(5, "long literals length detected at pos %zu", longl-nbSequences); assert(longl <= 2* (nbSequences-1)); cctx->seqStore.longLengthType = ZSTD_llt_literalLength; - cctx->seqStore.longLengthPos = (U32)(longl-nbSequences); + cctx->seqStore.longLengthPos = (U32)(longl-(nbSequences-1)-1); } } } else { From 78275149ead3bfc068d58a67480653740da5a86b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 17 Jan 2025 19:30:55 -0800 Subject: [PATCH 600/937] Added a final success message at end of tests so that a human reading the test log can determine everything was fine without consulting the shell error code. Also: made `make check` slightly shorter by moving one longer test to `make test` --- .github/workflows/dev-short-tests.yml | 6 +++--- CONTRIBUTING.md | 2 +- Makefile | 8 ++------ tests/Makefile | 13 ++++++++----- tests/playTests.sh | 3 ++- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 25919922d..18c66f4f6 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -144,11 +144,11 @@ jobs: - name: install valgrind run: | sudo apt-get -qqq update - make valgrindinstall + make valgrindinstall V=1 - name: zlib wrapper test - run: make -C zlibWrapper test + run: make -C zlibWrapper test V=1 - name: zlib wrapper test under valgrind - run: make -C zlibWrapper test-valgrind + run: make -C zlibWrapper test-valgrind V=1 lz4-threadpool-libs: runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 47f5bb8f0..57be94bf5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,7 +60,7 @@ Our contribution process works in three main stages: * Note: run local tests to ensure that your changes didn't break existing functionality * Quick check ``` - make shortest + make check ``` * Longer check ``` diff --git a/Makefile b/Makefile index e80505b7f..03ee6fe89 100644 --- a/Makefile +++ b/Makefile @@ -85,14 +85,10 @@ test: $(MAKE) -C $(TESTDIR) $@ ZSTD=../../programs/zstd $(MAKE) -C doc/educational_decoder $@ -## shortest: same as `make check` -.PHONY: shortest -shortest: - $(Q)$(MAKE) -C $(TESTDIR) $@ - ## check: run basic tests for `zstd` cli .PHONY: check -check: shortest +check: + $(Q)$(MAKE) -C $(TESTDIR) $@ .PHONY: automated_benchmarking automated_benchmarking: diff --git a/tests/Makefile b/tests/Makefile index abb0b2b1d..406c7f20b 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -312,12 +312,12 @@ endif list: @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs -.PHONY: shortest -shortest: ZSTDRTTEST= # remove long tests -shortest: test-zstd - .PHONY: check -check: shortest +check: ZSTDRTTEST= # remove long tests +check: test-zstd + @echo "\n******************************" + @echo "All tests completed successfully" + @echo "******************************" .PHONY: fuzztest fuzztest: test-fuzzer test-zstream test-decodecorpus @@ -327,6 +327,9 @@ test: test-zstd test-cli-tests test-fullbench test-fuzzer test-zstream test-inva ifeq ($(QEMU_SYS),) test: test-pool endif + @echo "\n******************************" + @echo "All tests completed successfully" + @echo "******************************" .PHONY: test32 test32: test-zstd32 test-fullbench32 test-fuzzer32 test-zstream32 diff --git a/tests/playTests.sh b/tests/playTests.sh index 692e93e89..5435ff5b3 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1554,7 +1554,6 @@ then roundTripTest -g4M "1 -T0 --auto-threads=physical" roundTripTest -g4M "1 -T0 --auto-threads=logical" roundTripTest -g8M "3 -T2" - roundTripTest -g8M "19 --long" roundTripTest -g8000K "2 --threads=2" fileRoundTripTest -g4M "19 -T2 -B1M" @@ -1850,6 +1849,8 @@ roundTripTest -g18000017 -P88 17 roundTripTest -g18000018 -P94 18 roundTripTest -g18000019 -P96 19 +roundTripTest -g8M "19 --long" + roundTripTest -g5000000000 -P99 "1 --zstd=wlog=25" roundTripTest -g3700000000 -P0 "1 --zstd=strategy=6,wlog=25" # ensure btlazy2 can survive an overflow rescale From 46e17b805b1bb2982583208da3b9184e377c2dd5 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sat, 18 Jan 2025 05:01:43 +0200 Subject: [PATCH 601/937] [asm] Enable x86_64 asm for windows builds --- lib/common/portability_macros.h | 8 +++----- lib/decompress/huf_decompress_amd64.S | 13 ++++++++++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index b1d9765fb..1ca28af6a 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -93,7 +93,7 @@ * Only enable assembly for GNU C compatible compilers, * because other platforms may not support GAS assembly syntax. * - * Only enable assembly for Linux / MacOS, other platforms may + * Only enable assembly for Linux / MacOS / Win32, other platforms may * work, but they haven't been tested. This could likely be * extended to BSD systems. * @@ -101,10 +101,8 @@ * 100% of code to be instrumented to work. */ #if defined(__GNUC__) -# if defined(__linux__) || defined(__linux) || defined(__APPLE__) -# if ZSTD_MEMORY_SANITIZER -# define ZSTD_ASM_SUPPORTED 0 -# elif ZSTD_DATAFLOW_SANITIZER +# if defined(__linux__) || defined(__linux) || defined(__APPLE__) || defined(_WIN32) +# if ZSTD_MEMORY_SANITIZER || ZSTD_DATAFLOW_SANITIZER # define ZSTD_ASM_SUPPORTED 0 # else # define ZSTD_ASM_SUPPORTED 1 diff --git a/lib/decompress/huf_decompress_amd64.S b/lib/decompress/huf_decompress_amd64.S index 78da291ee..656aada95 100644 --- a/lib/decompress/huf_decompress_amd64.S +++ b/lib/decompress/huf_decompress_amd64.S @@ -42,13 +42,11 @@ /* Calling convention: * - * %rdi contains the first argument: HUF_DecompressAsmArgs*. + * %rdi (or %rcx on Windows) contains the first argument: HUF_DecompressAsmArgs*. * %rbp isn't maintained (no frame pointer). * %rsp contains the stack pointer that grows down. * No red-zone is assumed, only addresses >= %rsp are used. * All register contents are preserved. - * - * TODO: Support Windows calling convention. */ ZSTD_HIDE_ASM_FUNCTION(HUF_decompress4X1_usingDTable_internal_fast_asm_loop) @@ -137,7 +135,11 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: push %r15 /* Read HUF_DecompressAsmArgs* args from %rax */ +#if defined(_WIN32) + movq %rcx, %rax +#else movq %rdi, %rax +#endif movq 0(%rax), %ip0 movq 8(%rax), %ip1 movq 16(%rax), %ip2 @@ -391,7 +393,12 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: push %r14 push %r15 + /* Read HUF_DecompressAsmArgs* args from %rax */ +#if defined(_WIN32) + movq %rcx, %rax +#else movq %rdi, %rax +#endif movq 0(%rax), %ip0 movq 8(%rax), %ip1 movq 16(%rax), %ip2 From ee17f4c6d295e82733673f824e7dba81a33e245b Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sat, 18 Jan 2025 21:32:30 +0200 Subject: [PATCH 602/937] Use _bzhi_u32 for 32-bit builds when building with STATIC_BMI2 `_bzhi_u64` is available only for 64-bit builds, while `BIT_getLowerBits` expects `nbBits` to be less than `BIT_MASK_SIZE` (`BIT_MASK_SIZE` is 32) --- lib/common/bitstream.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index a1dac889d..c9c645416 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -162,7 +162,11 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) - return _bzhi_u64(bitContainer, nbBits); +#if defined(__x86_64__) || defined(_M_X64) + return _bzhi_u64(bitContainer, nbBits); +#else + return _bzhi_u32(bitContainer, nbBits); +#endif #else assert(nbBits < BIT_MASK_SIZE); return bitContainer & BIT_mask[nbBits]; From 4f3311f245fedb99d65baca98cd33f6ec41a6589 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 12:22:52 -0800 Subject: [PATCH 603/937] CI: replaced shortest target by check --- .cirrus.yml | 4 ++-- .github/workflows/commit.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index e3617a960..9461de412 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,9 +1,9 @@ task: - name: FreeBSD (shortest) + name: FreeBSD (make check) freebsd_instance: matrix: image_family: freebsd-14-1 install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all - gmake shortest + gmake check diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 2aa8a6d86..659072861 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -30,7 +30,7 @@ jobs: make c99build; make clean make c11build; make clean make -j regressiontest; make clean - make shortest; make clean + make check; make clean make cxxtest; make clean short-tests-1: From e8de8085f4a75fe46021b82851b72b07bb824c2b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 13:08:04 -0800 Subject: [PATCH 604/937] minor: assert that state is not null replaces #4016 --- lib/decompress/zstd_decompress.c | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/decompress/zstd_decompress.c b/lib/decompress/zstd_decompress.c index 402d75349..9eb98327e 100644 --- a/lib/decompress/zstd_decompress.c +++ b/lib/decompress/zstd_decompress.c @@ -2096,6 +2096,7 @@ size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inB U32 someMoreWork = 1; DEBUGLOG(5, "ZSTD_decompressStream"); + assert(zds != NULL); RETURN_ERROR_IF( input->pos > input->size, srcSize_wrong, From 936927a427704ca21dfd07c666c4123737c8fb03 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sat, 18 Jan 2025 23:27:19 +0200 Subject: [PATCH 605/937] handle 32bit size_t when building for x64 --- lib/common/bitstream.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index c9c645416..c0db11d40 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -162,11 +162,11 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) -#if defined(__x86_64__) || defined(_M_X64) - return _bzhi_u64(bitContainer, nbBits); -#else +# if defined(__x86_64__) || defined(_M_X64) + return sizeof(size_t) == sizeof(U64) ? _bzhi_u64(bitContainer, nbBits) : _bzhi_u32((U32)bitContainer, nbBits); +# else return _bzhi_u32(bitContainer, nbBits); -#endif +# endif #else assert(nbBits < BIT_MASK_SIZE); return bitContainer & BIT_mask[nbBits]; From 26e5fb36149b9d155a3640ca0800199fc13711e8 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sat, 18 Jan 2025 23:37:50 +0200 Subject: [PATCH 606/937] handle 32bit size_t when building for x64 --- lib/common/bitstream.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index c0db11d40..d976c5478 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -162,9 +162,10 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) -# if defined(__x86_64__) || defined(_M_X64) - return sizeof(size_t) == sizeof(U64) ? _bzhi_u64(bitContainer, nbBits) : _bzhi_u32((U32)bitContainer, nbBits); +# if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) + return _bzhi_u64(bitContainer, nbBits); # else + DEBUG_STATIC_ASSERT(sizeof(size_t) == sizeof(U32)); return _bzhi_u32(bitContainer, nbBits); # endif #else From 462484d5dcbab964474bf4704df4d188e5c31818 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sun, 19 Jan 2025 02:34:23 +0200 Subject: [PATCH 607/937] change to BitContainerType --- lib/common/bitstream.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index d976c5478..582f9dd72 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -159,7 +159,7 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, return 0; } -FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits) +FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) # if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) From d60c4d75e9d29d76cc202f7a8341ab0bda1d6402 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sun, 19 Jan 2025 02:36:00 +0200 Subject: [PATCH 608/937] remove unrelated changes --- lib/common/portability_macros.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index 1ca28af6a..6016aefa5 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -102,7 +102,9 @@ */ #if defined(__GNUC__) # if defined(__linux__) || defined(__linux) || defined(__APPLE__) || defined(_WIN32) -# if ZSTD_MEMORY_SANITIZER || ZSTD_DATAFLOW_SANITIZER +# if ZSTD_MEMORY_SANITIZER +# define ZSTD_ASM_SUPPORTED 0 +# elif ZSTD_DATAFLOW_SANITIZER # define ZSTD_ASM_SUPPORTED 0 # else # define ZSTD_ASM_SUPPORTED 1 From fcd684b9b45917dbb90e8122faf782e4028fdb42 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Sun, 19 Jan 2025 02:37:35 +0200 Subject: [PATCH 609/937] update sizeof check --- lib/common/bitstream.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 582f9dd72..bc7118b37 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -165,7 +165,7 @@ FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(BitContainerType bitContainer, U32 # if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) return _bzhi_u64(bitContainer, nbBits); # else - DEBUG_STATIC_ASSERT(sizeof(size_t) == sizeof(U32)); + DEBUG_STATIC_ASSERT(sizeof(bitContainer) == sizeof(U32)); return _bzhi_u32(bitContainer, nbBits); # endif #else From 9efb09749b85acfbc2299fb6dec6146b942c6b2e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 20:19:55 -0800 Subject: [PATCH 610/937] added a CI test for x86 32-bit + avx2 combination which is expected to be quite rare, but nonetheless possible. This test is initially expected to fail, before integration of #4248 fix --- .github/workflows/dev-short-tests.yml | 13 ++++++++++++- lib/common/bitstream.h | 2 +- lib/common/compiler.h | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 18c66f4f6..fa28283f7 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -164,7 +164,7 @@ jobs: make clean bash tests/libzstd_builds.sh - gcc-make-tests-32bit: + gcc-make-all-32bit: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 @@ -174,6 +174,17 @@ jobs: make libc6install CFLAGS="-Werror -m32" make -j all32 + gcc-make-all-32bit-avx2: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Make all, 32bit mode + run: | + sudo apt-get -qqq update + make libc6install + CFLAGS="-Werror -m32 -mavx2" make -j all32 + + gcc-8-make: runs-on: ubuntu-latest steps: diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index bc7118b37..88f448aa6 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -238,7 +238,7 @@ MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC) BIT_addBitsFast(bitC, 1, 1); /* endMark */ BIT_flushBits(bitC); if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */ - return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0); + return (size_t)(bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0); } diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 2a8002288..84ce62349 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -210,7 +210,7 @@ /*Like DYNAMIC_BMI2 but for compile time determination of BMI2 support*/ #ifndef STATIC_BMI2 # if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) -# ifdef __AVX2__ //MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 +# ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ # define STATIC_BMI2 1 # endif # elif defined(__BMI2__) && defined(__x86_64__) && defined(__GNUC__) From 35edbc20dc31fcc64f7dfe0c256d5005879b1b59 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 20:38:48 -0800 Subject: [PATCH 611/937] added avx2 (x64) compilation test --- .github/workflows/dev-short-tests.yml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index fa28283f7..6bd311f09 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -164,6 +164,16 @@ jobs: make clean bash tests/libzstd_builds.sh + gcc-make-all-avx2: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Make all, with AVX2 + run: | + sudo apt-get -qqq update + make libc6install + CFLAGS="-Werror -mavx2" make -j all + gcc-make-all-32bit: runs-on: ubuntu-latest steps: @@ -178,7 +188,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: Make all, 32bit mode + - name: Make all, 32bit + AVX2 mode run: | sudo apt-get -qqq update make libc6install From f0b5f65bca6587f6d9b642e3a95d58ae36b7cdea Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 20:43:30 -0800 Subject: [PATCH 612/937] fixed minor static function declaration issue in AVX2 mode only --- lib/compress/zstd_compress.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 5d5ada0ae..abc75fb2d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7125,7 +7125,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, * @returns > 0 if there is one long length (> 65535), * indicating the position, and type. */ -size_t convertSequences_noRepcodes( +static size_t convertSequences_noRepcodes( SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) @@ -7277,9 +7277,10 @@ size_t convertSequences_noRepcodes( #else /* no AVX2 */ -static size_t -convertSequences_noRepcodes(SeqDef* dstSeqs, - const ZSTD_Sequence* const inSeqs, size_t nbSequences) +static size_t convertSequences_noRepcodes( + SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) { size_t longLen = 0; size_t n; From 050109589800be49d3840927b9e821d24622e1ea Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 22:40:18 -0800 Subject: [PATCH 613/937] added -DSTATIC_BMI2=1 for the -mavx2 test --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 6bd311f09..71afc0991 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -192,7 +192,7 @@ jobs: run: | sudo apt-get -qqq update make libc6install - CFLAGS="-Werror -m32 -mavx2" make -j all32 + CPPFLAGS="-DSTATIC_BMI2=1" CFLAGS="-Werror -m32 -mavx2" make -j all32 gcc-8-make: From 27d794063162096e3a4be7d2d3f80ce117a5592d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 22:48:49 -0800 Subject: [PATCH 614/937] minor: cosmetic, indentation --- lib/common/compiler.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 84ce62349..7927c4fb6 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -207,7 +207,7 @@ # pragma warning(disable : 4324) /* disable: C4324: padded structure */ #endif -/*Like DYNAMIC_BMI2 but for compile time determination of BMI2 support*/ +/* Like DYNAMIC_BMI2 but for compile time determination of BMI2 support */ #ifndef STATIC_BMI2 # if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) # ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ @@ -219,7 +219,7 @@ #endif #ifndef STATIC_BMI2 - #define STATIC_BMI2 0 +# define STATIC_BMI2 0 #endif /* compile time determination of SIMD support */ From d2d74616c0bfaf9d76186398a23fffafbb591c52 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 18 Jan 2025 22:58:03 -0800 Subject: [PATCH 615/937] also add `-mbmi2` to the compilation test --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 71afc0991..a84510686 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -192,7 +192,7 @@ jobs: run: | sudo apt-get -qqq update make libc6install - CPPFLAGS="-DSTATIC_BMI2=1" CFLAGS="-Werror -m32 -mavx2" make -j all32 + CPPFLAGS="-DSTATIC_BMI2=1" CFLAGS="-Werror -m32 -mavx2 -mbmi2" make -j all32 gcc-8-make: From a556559841db607ede4e4e0a85773e5b214e66f1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 19 Jan 2025 00:08:57 -0800 Subject: [PATCH 616/937] no longer limit automated BMI2 detection to x64 this was previously no triggered in x86 32-bit mode, due to a limitation in `bitstream.h`, that was fixed in #4248. Now, `bmi2` will be automatically detected and triggered at compilation time, if the corresponding instruction set is enabled, even in 32-bit mode. Also: updated library documentation, to feature STATIC_BMI2 build variable --- lib/README.md | 7 +++++++ lib/common/compiler.h | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/README.md b/lib/README.md index 0f6c64745..b37f5fc4f 100644 --- a/lib/README.md +++ b/lib/README.md @@ -149,6 +149,13 @@ The file structure is designed to make this selection manually achievable for an will expose the deprecated `ZSTDMT` API exposed by `zstdmt_compress.h` in the shared library, which is now hidden by default. +- The build macro `STATIC_BMI2` can be set to 1 to force usage of `bmi2` instructions. + It is generally not necessary to set this build macro, + because `STATIC_BMI2` will be automatically set to 1 + on detecting the presence of the corresponding instruction set in the compilation target. + It's nonetheless available as an optional manual toggle for better control, + and can also be used to forcefully disable `bmi2` instructions by setting it to 0. + - The build macro `DYNAMIC_BMI2` can be set to 1 or 0 in order to generate binaries which can detect at runtime the presence of BMI2 instructions, and use them only if present. These instructions contribute to better performance, notably on the decoder side. diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 7927c4fb6..6fd2d08e7 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -209,11 +209,11 @@ /* Like DYNAMIC_BMI2 but for compile time determination of BMI2 support */ #ifndef STATIC_BMI2 -# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) +# if defined(_MSC_VER) # ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ # define STATIC_BMI2 1 # endif -# elif defined(__BMI2__) && defined(__x86_64__) && defined(__GNUC__) +# elif defined(__BMI2__) # define STATIC_BMI2 1 # endif #endif From 4bbf4a285d92e4cb5b37e0fd1d4af96c12c2c249 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 19 Jan 2025 07:39:17 -0800 Subject: [PATCH 617/937] enable DYNAMIC_BMI2 by default on x86 (32-bit mode) so far was only enabled for x64 (64-bit mode) --- lib/common/portability_macros.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index 6016aefa5..b52394382 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -78,15 +78,15 @@ * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default. */ #ifndef DYNAMIC_BMI2 - #if ((defined(__clang__) && __has_attribute(__target__)) \ +# if ((defined(__clang__) && __has_attribute(__target__)) \ || (defined(__GNUC__) \ && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))) \ - && (defined(__x86_64__) || defined(_M_X64)) \ + && (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)) \ && !defined(__BMI2__) - # define DYNAMIC_BMI2 1 - #else - # define DYNAMIC_BMI2 0 - #endif +# define DYNAMIC_BMI2 1 +# else +# define DYNAMIC_BMI2 0 +# endif #endif /** From 82346b92bb5f02dea90907135f74cd77f0c9cb33 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 19 Jan 2025 09:32:01 -0800 Subject: [PATCH 618/937] minor: generalize BitContainerType technically equivalent to `size_t`, but it's the proper type for underlying register representation. This makes it possible to control register type, and therefore size, independently from `size_t`, which can be useful on systems where `size_t` is 32-bit, while the architecture supports 64-bit registers. --- lib/common/bitstream.h | 34 +++++++++++++++++----------------- lib/common/fse.h | 4 ++-- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 88f448aa6..2c4245678 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -48,12 +48,13 @@ /*-****************************************** * bitStream encoding API (write forward) ********************************************/ +typedef size_t BitContainerType; /* bitStream can mix input from multiple sources. * A critical property of these streams is that they encode and decode in **reverse** direction. * So the first bit sequence you add will be the last to be read, like a LIFO stack. */ typedef struct { - size_t bitContainer; + BitContainerType bitContainer; unsigned bitPos; char* startPtr; char* ptr; @@ -61,7 +62,7 @@ typedef struct { } BIT_CStream_t; MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity); -MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits); +MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits); MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC); MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); @@ -70,7 +71,7 @@ MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); * `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code. * * bits are first added to a local register. -* Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems. +* Local register is BitContainerType, 64-bits on 64-bits systems, or 32-bits on 32-bits systems. * Writing data into memory is an explicit operation, performed by the flushBits function. * Hence keep track how many bits are potentially stored into local register to avoid register overflow. * After a flushBits, a maximum of 7 bits might still be stored into local register. @@ -86,7 +87,6 @@ MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC); /*-******************************************** * bitStream decoding API (read backward) **********************************************/ -typedef size_t BitContainerType; typedef struct { BitContainerType bitContainer; unsigned bitsConsumed; @@ -102,7 +102,7 @@ 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 size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); +MEM_STATIC BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); @@ -121,7 +121,7 @@ MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); /*-**************************************** * unsafe API ******************************************/ -MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits); +MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, BitContainerType value, unsigned nbBits); /* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */ MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC); @@ -159,7 +159,7 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, return 0; } -FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits) +FORCE_INLINE_TEMPLATE BitContainerType BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits) { #if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) # if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) @@ -178,7 +178,7 @@ FORCE_INLINE_TEMPLATE size_t BIT_getLowerBits(BitContainerType bitContainer, U32 * can add up to 31 bits into `bitC`. * Note : does not check for register overflow ! */ MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, - size_t value, unsigned nbBits) + BitContainerType value, unsigned nbBits) { DEBUG_STATIC_ASSERT(BIT_MASK_SIZE == 32); assert(nbBits < BIT_MASK_SIZE); @@ -191,7 +191,7 @@ MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, * works only if `value` is _clean_, * meaning all high bits above nbBits are 0 */ MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, - size_t value, unsigned nbBits) + BitContainerType value, unsigned nbBits) { assert((value>>nbBits) == 0); assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8); @@ -299,12 +299,12 @@ MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, si return srcSize; } -FORCE_INLINE_TEMPLATE size_t BIT_getUpperBits(BitContainerType bitContainer, U32 const start) +FORCE_INLINE_TEMPLATE BitContainerType BIT_getUpperBits(BitContainerType bitContainer, U32 const start) { return bitContainer >> start; } -FORCE_INLINE_TEMPLATE size_t BIT_getMiddleBits(BitContainerType bitContainer, U32 const start, U32 const nbBits) +FORCE_INLINE_TEMPLATE BitContainerType BIT_getMiddleBits(BitContainerType bitContainer, U32 const start, U32 const nbBits) { U32 const regMask = sizeof(bitContainer)*8 - 1; /* if start > regMask, bitstream is corrupted, and result is undefined */ @@ -327,7 +327,7 @@ FORCE_INLINE_TEMPLATE size_t BIT_getMiddleBits(BitContainerType bitContainer, U3 * On 32-bits, maxNbBits==24. * On 64-bits, maxNbBits==56. * @return : value extracted */ -FORCE_INLINE_TEMPLATE size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) +FORCE_INLINE_TEMPLATE BitContainerType BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits) { /* arbitrate between double-shift and shift+mask */ #if 1 @@ -343,7 +343,7 @@ FORCE_INLINE_TEMPLATE size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits /*! BIT_lookBitsFast() : * unsafe version; only works if nbBits >= 1 */ -MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits) +MEM_STATIC BitContainerType BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits) { U32 const regMask = sizeof(bitD->bitContainer)*8 - 1; assert(nbBits >= 1); @@ -359,18 +359,18 @@ FORCE_INLINE_TEMPLATE void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) * Read (consume) next n bits from local register and update. * Pay attention to not read more than nbBits contained into local register. * @return : extracted value. */ -FORCE_INLINE_TEMPLATE size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) +FORCE_INLINE_TEMPLATE BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits) { - size_t const value = BIT_lookBits(bitD, nbBits); + BitContainerType const value = BIT_lookBits(bitD, nbBits); BIT_skipBits(bitD, nbBits); return value; } /*! BIT_readBitsFast() : * unsafe version; only works if nbBits >= 1 */ -MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) +MEM_STATIC BitContainerType BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits) { - size_t const value = BIT_lookBitsFast(bitD, nbBits); + BitContainerType const value = BIT_lookBitsFast(bitD, nbBits); assert(nbBits >= 1); BIT_skipBits(bitD, nbBits); return value; diff --git a/lib/common/fse.h b/lib/common/fse.h index b1940d942..b6c2a3e9c 100644 --- a/lib/common/fse.h +++ b/lib/common/fse.h @@ -456,13 +456,13 @@ MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, un FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol]; const U16* const stateTable = (const U16*)(statePtr->stateTable); U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16); - BIT_addBits(bitC, (size_t)statePtr->value, nbBitsOut); + BIT_addBits(bitC, (BitContainerType)statePtr->value, nbBitsOut); statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState]; } MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr) { - BIT_addBits(bitC, (size_t)statePtr->value, statePtr->stateLog); + BIT_addBits(bitC, (BitContainerType)statePtr->value, statePtr->stateLog); BIT_flushBits(bitC); } From e39ed414350313e8170d96c8fc82b3d0c2e67a6a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 05:46:57 +0000 Subject: [PATCH 619/937] Bump cygwin/cygwin-install-action from 4 to 5 Bumps [cygwin/cygwin-install-action](https://github.com/cygwin/cygwin-install-action) from 4 to 5. - [Release notes](https://github.com/cygwin/cygwin-install-action/releases) - [Commits](https://github.com/cygwin/cygwin-install-action/compare/006ad0b0946ca6d0a3ea2d4437677fa767392401...f61179d72284ceddc397ed07ddb444d82bf9e559) --- updated-dependencies: - dependency-name: cygwin/cygwin-install-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index a84510686..2fccb4d9e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -582,7 +582,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: cygwin/cygwin-install-action@006ad0b0946ca6d0a3ea2d4437677fa767392401 # tag=master + - uses: cygwin/cygwin-install-action@f61179d72284ceddc397ed07ddb444d82bf9e559 # tag=master with: platform: x86_64 packages: >- From 5b9c5d4929cea7b3a134f44887bfffeefd448500 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 05:47:03 +0000 Subject: [PATCH 620/937] Bump github/codeql-action from 3.27.1 to 3.28.1 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.27.1 to 3.28.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/4f3212b61783c3c68e8309a0f18a699764811cda...b6a472f63d85b9c78a3ac5e89422239fc15e9b3c) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 0ae40d859..c489ddc91 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@4f3212b61783c3c68e8309a0f18a699764811cda # tag=v3.27.1 + uses: github/codeql-action/upload-sarif@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # tag=v3.28.1 with: sarif_file: results.sarif From 056492e31b80fa746c187a5078e96163437c8739 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 19 Jan 2025 23:14:59 -0800 Subject: [PATCH 621/937] Update dev-short-tests.yml specify cygwin action version --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 2fccb4d9e..dfe1bf584 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -582,7 +582,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: cygwin/cygwin-install-action@f61179d72284ceddc397ed07ddb444d82bf9e559 # tag=master + - uses: cygwin/cygwin-install-action@f61179d72284ceddc397ed07ddb444d82bf9e559 # tag=v5 with: platform: x86_64 packages: >- From 6c1d1cc600f0cc5dab40e16200f4d23eeaeb0c9f Mon Sep 17 00:00:00 2001 From: Pavel P Date: Tue, 21 Jan 2025 02:27:09 +0200 Subject: [PATCH 622/937] Use _M_X64 only without mixing with _M_AMD64 --- lib/common/compiler.h | 2 +- lib/common/mem.h | 2 +- lib/common/xxhash.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 6fd2d08e7..0dad74c7d 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -227,7 +227,7 @@ # if defined(__AVX2__) # define ZSTD_ARCH_X86_AVX2 # endif -# if defined(__SSE2__) || defined(_M_AMD64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) +# if defined(__SSE2__) || defined(_M_X64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) # define ZSTD_ARCH_X86_SSE2 # endif # if defined(__ARM_NEON) || defined(_M_ARM64) diff --git a/lib/common/mem.h b/lib/common/mem.h index ca756e237..e66a2eaeb 100644 --- a/lib/common/mem.h +++ b/lib/common/mem.h @@ -147,7 +147,7 @@ MEM_STATIC unsigned MEM_isLittleEndian(void) return 1; #elif defined(__clang__) && __BIG_ENDIAN__ return 0; -#elif defined(_MSC_VER) && (_M_AMD64 || _M_IX86) +#elif defined(_MSC_VER) && (_M_X64 || _M_IX86) return 1; #elif defined(__DMC__) && defined(_M_IX86) return 1; diff --git a/lib/common/xxhash.h b/lib/common/xxhash.h index 68ec6b29f..b6af402fd 100644 --- a/lib/common/xxhash.h +++ b/lib/common/xxhash.h @@ -3892,7 +3892,7 @@ enum XXH_VECTOR_TYPE /* fake enum */ { # define XXH_VECTOR XXH_AVX512 # elif defined(__AVX2__) # define XXH_VECTOR XXH_AVX2 -# elif defined(__SSE2__) || defined(_M_AMD64) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2)) +# elif defined(__SSE2__) || defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP == 2)) # define XXH_VECTOR XXH_SSE2 # elif (defined(__PPC64__) && defined(__POWER8_VECTOR__)) \ || (defined(__s390x__) && defined(__VEC__)) \ From a0872a837294ae9b18967e9e80342587f3089fb0 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Tue, 21 Jan 2025 02:33:25 +0200 Subject: [PATCH 623/937] Implement ZSTD_ALIGNED for ms compiler --- lib/common/compiler.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 6fd2d08e7..b12de3edc 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -321,6 +321,8 @@ MEM_STATIC int ZSTD_isPower2(size_t u) { # define ZSTD_ALIGNED(a) __attribute__((aligned(a))) # elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ # define ZSTD_ALIGNED(a) alignas(a) +#elif defined(_MSC_VER) +# define ZSTD_ALIGNED(n) __declspec(align(n)) # else /* this compiler will require its own alignment instruction */ # define ZSTD_ALIGNED(...) From 897cec38760d1bb41e690225ba07b91c568e7cc8 Mon Sep 17 00:00:00 2001 From: Treata11 Date: Tue, 21 Jan 2025 20:58:27 +0330 Subject: [PATCH 624/937] Build: Add support for Apple frameworks Signed-off-by: Treata11 --- build/cmake/CMakeLists.txt | 11 +++++++-- build/cmake/lib/CMakeLists.txt | 45 +++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index b9003c867..f507181dc 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -7,7 +7,7 @@ # in the COPYING file in the root directory of this source tree). # ################################################################ -cmake_minimum_required(VERSION 3.10 FATAL_ERROR) +cmake_minimum_required(VERSION 3.14 FATAL_ERROR) # As of 2018-12-26 ZSTD has been validated to build with cmake version 3.13.2 new policies. # Set and use the newest cmake policies that are validated to work @@ -30,8 +30,11 @@ set(LIBRARY_DIR ${ZSTD_SOURCE_DIR}/lib) include(GetZstdLibraryVersion) GetZstdLibraryVersion(${LIBRARY_DIR}/zstd.h zstd_VERSION_MAJOR zstd_VERSION_MINOR zstd_VERSION_PATCH) +set(ZSTD_SHORT_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}") +set(ZSTD_FULL_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}") + project(zstd - VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}" + VERSION "${ZSTD_FULL_VERSION}" LANGUAGES C # Main library is in C ASM # And ASM CXX # Testing contributed code also utilizes CXX @@ -82,6 +85,10 @@ else () add_definitions(-DZSTD_LEGACY_SUPPORT=0) endif () +if (APPLE) + option(ZSTD_FRAMEWORK "Build as Apple Frameworks" OFF) +endif () + if (ANDROID) set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT OFF) # Old versions of bionic libc don't have fseeko/ftello diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index d07b1f5ff..c02822296 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -205,8 +205,28 @@ if (ZSTD_BUILD_SHARED) libzstd_shared PROPERTIES OUTPUT_NAME zstd - VERSION ${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH} + VERSION ${ZSTD_FULL_VERSION} SOVERSION ${zstd_VERSION_MAJOR}) + + if (ZSTD_FRAMEWORK) + set_target_properties( + libzstd_shared + PROPERTIES + FRAMEWORK TRUE + FRAMEWORK_VERSION "${ZSTD_FULL_VERSION}" + PRODUCT_BUNDLE_IDENTIFIER "github.com/facebook/zstd" + XCODE_ATTRIBUTE_INSTALL_PATH "@rpath" + PUBLIC_HEADER "${PublicHeaders}" + OUTPUT_NAME "zstd" + XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "" + XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO" + XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO" + MACOSX_FRAMEWORK_IDENTIFIER "github.com/facebook/zstd" + MACOSX_FRAMEWORK_BUNDLE_VERSION "${ZSTD_FULL_VERSION}" + MACOSX_FRAMEWORK_SHORT_VERSION_STRING "${ZSTD_SHORT_VERSION}" + MACOSX_RPATH TRUE + RESOURCE ${PublicHeaders}) + endif () endif () if (ZSTD_BUILD_STATIC) @@ -215,6 +235,26 @@ if (ZSTD_BUILD_STATIC) PROPERTIES POSITION_INDEPENDENT_CODE On OUTPUT_NAME ${STATIC_LIBRARY_BASE_NAME}) + + if (ZSTD_FRAMEWORK) + set_target_properties( + libzstd_static + PROPERTIES + FRAMEWORK TRUE + FRAMEWORK_VERSION "${ZSTD_FULL_VERSION}" + PRODUCT_BUNDLE_IDENTIFIER "github.com/facebook/zstd/${STATIC_LIBRARY_BASE_NAME}" + XCODE_ATTRIBUTE_INSTALL_PATH "@rpath" + PUBLIC_HEADER "${PublicHeaders}" + OUTPUT_NAME "${STATIC_LIBRARY_BASE_NAME}" + XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "" + XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO" + XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO" + MACOSX_FRAMEWORK_IDENTIFIER "github.com/facebook/zstd/${STATIC_LIBRARY_BASE_NAME}" + MACOSX_FRAMEWORK_BUNDLE_VERSION "${ZSTD_FULL_VERSION}" + MACOSX_FRAMEWORK_SHORT_VERSION_STRING "${ZSTD_SHORT_VERSION}" + MACOSX_RPATH TRUE + RESOURCE ${PublicHeaders}) + endif () endif () # pkg-config @@ -239,6 +279,9 @@ install(TARGETS ${library_targets} LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}" + FRAMEWORK DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT runtime OPTIONAL + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) # uninstall target From 03d5ad6fed5882a300289e5fa8a238f2fec29300 Mon Sep 17 00:00:00 2001 From: Treata11 Date: Tue, 21 Jan 2025 21:06:54 +0330 Subject: [PATCH 625/937] Ignore generated framework artifacts Signed-off-by: Treata11 --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 34e18b443..4b50bb186 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ *.so *.so.* *.dylib +*.framework +*.xcframework # Executables /zstd From becef672bb7c22af0fd723a4f8e4d279cf2a780a Mon Sep 17 00:00:00 2001 From: Treata11 Date: Wed, 22 Jan 2025 22:53:41 +0330 Subject: [PATCH 626/937] Build: Revert min version to 3.10 --- build/cmake/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index f507181dc..347d41c0f 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -7,7 +7,7 @@ # in the COPYING file in the root directory of this source tree). # ################################################################ -cmake_minimum_required(VERSION 3.14 FATAL_ERROR) +cmake_minimum_required(VERSION 3.10 FATAL_ERROR) # As of 2018-12-26 ZSTD has been validated to build with cmake version 3.13.2 new policies. # Set and use the newest cmake policies that are validated to work From 45c0e72c0a481be824cc12fe6032ac685205d187 Mon Sep 17 00:00:00 2001 From: Treata11 Date: Wed, 22 Jan 2025 22:54:03 +0330 Subject: [PATCH 627/937] Instructions for Apple Framework builds --- build/cmake/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/build/cmake/README.md b/build/cmake/README.md index 4c9d3a08b..6baa5974b 100644 --- a/build/cmake/README.md +++ b/build/cmake/README.md @@ -41,6 +41,16 @@ cmake -DZSTD_BUILD_TESTS=ON -DZSTD_LEGACY_SUPPORT=OFF .. make ``` +**Apple Frameworks** +It's generally recommended to have CMake with versions higher than 3.14 for [iOS-derived platforms](https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html#id27). +```sh +cmake -S. -B build-cmake -DZSTD_FRAMEWORK=ON -DCMAKE_SYSTEM_NAME=iOS +``` +Or you can utilize [iOS-CMake](https://github.com/leetal/ios-cmake) toolchain for CMake versions lower than 3.14 +```sh +cmake -B build -G Xcode -DCMAKE_TOOLCHAIN_FILE= -DPLATFORM=OS64 -DZSTD_FRAMEWORK=ON +``` + ### how to use it with CMake FetchContent For all options available, you can see it on From 12046261382422494d7423cd39df553f236270ee Mon Sep 17 00:00:00 2001 From: Pavel P Date: Thu, 23 Jan 2025 23:58:50 +0200 Subject: [PATCH 628/937] Check `DYNAMIC_BMI2` instead of `DYNAMIC_BMI2 != 0` `#if DYNAMIC_BMI2` is consistent with the rest of the code. + use spaces instead of tabs --- lib/decompress/zstd_decompress_internal.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/decompress/zstd_decompress_internal.h b/lib/decompress/zstd_decompress_internal.h index 7d1f1053b..e4bffdbc6 100644 --- a/lib/decompress/zstd_decompress_internal.h +++ b/lib/decompress/zstd_decompress_internal.h @@ -154,7 +154,7 @@ struct ZSTD_DCtx_s size_t rleSize; size_t staticSize; int isFrameDecompression; -#if DYNAMIC_BMI2 != 0 +#if DYNAMIC_BMI2 int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */ #endif @@ -211,11 +211,11 @@ struct ZSTD_DCtx_s }; /* typedef'd to ZSTD_DCtx within "zstd.h" */ MEM_STATIC int ZSTD_DCtx_get_bmi2(const struct ZSTD_DCtx_s *dctx) { -#if DYNAMIC_BMI2 != 0 - return dctx->bmi2; +#if DYNAMIC_BMI2 + return dctx->bmi2; #else (void)dctx; - return 0; + return 0; #endif } From 59afb28c977ab743b4430e8c284c41d209ac49eb Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 02:13:20 +0200 Subject: [PATCH 629/937] Remove unused ZSTD_decompressSequences_t typedef --- lib/decompress/zstd_decompress_block.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index ca5044376..862785a49 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1935,12 +1935,6 @@ ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx, #endif /* DYNAMIC_BMI2 */ -typedef size_t (*ZSTD_decompressSequences_t)( - ZSTD_DCtx* dctx, - void* dst, size_t maxDstSize, - const void* seqStart, size_t seqSize, int nbSeq, - const ZSTD_longOffset_e isLongOffset); - #ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG static size_t ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, From 1b15e888fc1a2f5f84583b0df014c6032eb3a162 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 00:05:03 +0200 Subject: [PATCH 630/937] Move STATIC_BMI2 block as-is to portability_macros.h --- lib/common/compiler.h | 15 --------------- lib/common/portability_macros.h | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index c942b984c..5ad212383 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -207,21 +207,6 @@ # pragma warning(disable : 4324) /* disable: C4324: padded structure */ #endif -/* Like DYNAMIC_BMI2 but for compile time determination of BMI2 support */ -#ifndef STATIC_BMI2 -# if defined(_MSC_VER) -# ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ -# define STATIC_BMI2 1 -# endif -# elif defined(__BMI2__) -# define STATIC_BMI2 1 -# endif -#endif - -#ifndef STATIC_BMI2 -# define STATIC_BMI2 0 -#endif - /* compile time determination of SIMD support */ #if !defined(ZSTD_NO_INTRINSICS) # if defined(__AVX2__) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index b52394382..b4da8a744 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -74,6 +74,21 @@ # define ZSTD_HIDE_ASM_FUNCTION(func) #endif +/* Like DYNAMIC_BMI2 but for compile time determination of BMI2 support */ +#ifndef STATIC_BMI2 +# if defined(_MSC_VER) +# ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ +# define STATIC_BMI2 1 +# endif +# elif defined(__BMI2__) +# define STATIC_BMI2 1 +# endif +#endif + +#ifndef STATIC_BMI2 +# define STATIC_BMI2 0 +#endif + /* Enable runtime BMI2 dispatch based on the CPU. * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default. */ From d486ccc9e90a9d2e0095f9a81cbf29f72bac4f37 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 00:06:13 +0200 Subject: [PATCH 631/937] Update comment for STATIC_BMI2 macro --- lib/common/portability_macros.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index b4da8a744..70964ba01 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -74,7 +74,7 @@ # define ZSTD_HIDE_ASM_FUNCTION(func) #endif -/* Like DYNAMIC_BMI2 but for compile time determination of BMI2 support */ +/* Compile time determination of BMI2 support */ #ifndef STATIC_BMI2 # if defined(_MSC_VER) # ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ From 0a183620a3c21bce4ca3b10a12aba7d7f84c12b2 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 00:09:44 +0200 Subject: [PATCH 632/937] Reorder __BMI2__ check + if `__BMI2__` defined, then set STATIC_BMI2 for all compilers + use `defined(_MSC_VER) && defined(__AVX2__)` as fallback for ms compiler --- lib/common/portability_macros.h | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index 70964ba01..860734141 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -76,12 +76,10 @@ /* Compile time determination of BMI2 support */ #ifndef STATIC_BMI2 -# if defined(_MSC_VER) -# ifdef __AVX2__ /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ -# define STATIC_BMI2 1 -# endif -# elif defined(__BMI2__) +# if defined(__BMI2__) # define STATIC_BMI2 1 +# elif defined(_MSC_VER) && defined(__AVX2__) +# define STATIC_BMI2 1 /* MSVC does not have a BMI2 specific flag, but every CPU that supports AVX2 also supports BMI2 */ # endif #endif From f7e8fc339b1ce64bbbfe3dc149b8cc0a13644844 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 01:25:07 +0200 Subject: [PATCH 633/937] Check `STATIC_BMI2` instead of `STATIC_BMI2 == 1` --- lib/common/bits.h | 8 ++++---- lib/common/bitstream.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/common/bits.h b/lib/common/bits.h index 992cc6925..8e09535a4 100644 --- a/lib/common/bits.h +++ b/lib/common/bits.h @@ -29,7 +29,7 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros32(U32 val) { assert(val != 0); # if defined(_MSC_VER) -# if STATIC_BMI2 == 1 +# if STATIC_BMI2 return (unsigned)_tzcnt_u32(val); # else if (val != 0) { @@ -70,7 +70,7 @@ MEM_STATIC unsigned ZSTD_countLeadingZeros32(U32 val) { assert(val != 0); # if defined(_MSC_VER) -# if STATIC_BMI2 == 1 +# if STATIC_BMI2 return (unsigned)_lzcnt_u32(val); # else if (val != 0) { @@ -95,7 +95,7 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros64(U64 val) { assert(val != 0); # if defined(_MSC_VER) && defined(_WIN64) -# if STATIC_BMI2 == 1 +# if STATIC_BMI2 return (unsigned)_tzcnt_u64(val); # else if (val != 0) { @@ -128,7 +128,7 @@ MEM_STATIC unsigned ZSTD_countLeadingZeros64(U64 val) { assert(val != 0); # if defined(_MSC_VER) && defined(_WIN64) -# if STATIC_BMI2 == 1 +# if STATIC_BMI2 return (unsigned)_lzcnt_u64(val); # else if (val != 0) { diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 2c4245678..3b7ad483d 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -161,7 +161,7 @@ MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, FORCE_INLINE_TEMPLATE BitContainerType BIT_getLowerBits(BitContainerType bitContainer, U32 const nbBits) { -#if defined(STATIC_BMI2) && STATIC_BMI2 == 1 && !defined(ZSTD_NO_INTRINSICS) +#if STATIC_BMI2 && !defined(ZSTD_NO_INTRINSICS) # if (defined(__x86_64__) || defined(_M_X64)) && !defined(__ILP32__) return _bzhi_u64(bitContainer, nbBits); # else From 0cda0100ea4b9d87eeaaf68e7d192fbbff4f2ab2 Mon Sep 17 00:00:00 2001 From: Pavel P Date: Fri, 24 Jan 2025 01:26:13 +0200 Subject: [PATCH 634/937] fix formatting --- lib/common/bits.h | 187 +++++++++++++++++++++++----------------------- 1 file changed, 92 insertions(+), 95 deletions(-) diff --git a/lib/common/bits.h b/lib/common/bits.h index 8e09535a4..f452f0889 100644 --- a/lib/common/bits.h +++ b/lib/common/bits.h @@ -28,29 +28,29 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros32_fallback(U32 val) MEM_STATIC unsigned ZSTD_countTrailingZeros32(U32 val) { assert(val != 0); -# if defined(_MSC_VER) -# if STATIC_BMI2 - return (unsigned)_tzcnt_u32(val); -# else - if (val != 0) { - unsigned long r; - _BitScanForward(&r, val); - return (unsigned)r; - } else { - /* Should not reach this code path */ - __assume(0); - } -# endif -# elif defined(__GNUC__) && (__GNUC__ >= 4) - return (unsigned)__builtin_ctz(val); -# elif defined(__ICCARM__) - return (unsigned)__builtin_ctz(val); -# else - return ZSTD_countTrailingZeros32_fallback(val); -# endif +#if defined(_MSC_VER) +# if STATIC_BMI2 + return (unsigned)_tzcnt_u32(val); +# else + if (val != 0) { + unsigned long r; + _BitScanForward(&r, val); + return (unsigned)r; + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)__builtin_ctz(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_ctz(val); +#else + return ZSTD_countTrailingZeros32_fallback(val); +#endif } -MEM_STATIC unsigned ZSTD_countLeadingZeros32_fallback(U32 val) { +MEM_STATIC unsigned ZSTD_countLeadingZeros32_fallback(U32 val) +{ assert(val != 0); { static const U32 DeBruijnClz[32] = {0, 9, 1, 10, 13, 21, 2, 29, @@ -69,92 +69,89 @@ MEM_STATIC unsigned ZSTD_countLeadingZeros32_fallback(U32 val) { MEM_STATIC unsigned ZSTD_countLeadingZeros32(U32 val) { assert(val != 0); -# if defined(_MSC_VER) -# if STATIC_BMI2 - return (unsigned)_lzcnt_u32(val); -# else - if (val != 0) { - unsigned long r; - _BitScanReverse(&r, val); - return (unsigned)(31 - r); - } else { - /* Should not reach this code path */ - __assume(0); - } -# endif -# elif defined(__GNUC__) && (__GNUC__ >= 4) - return (unsigned)__builtin_clz(val); -# elif defined(__ICCARM__) - return (unsigned)__builtin_clz(val); -# else - return ZSTD_countLeadingZeros32_fallback(val); -# endif +#if defined(_MSC_VER) +# if STATIC_BMI2 + return (unsigned)_lzcnt_u32(val); +# else + if (val != 0) { + unsigned long r; + _BitScanReverse(&r, val); + return (unsigned)(31 - r); + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)__builtin_clz(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_clz(val); +#else + return ZSTD_countLeadingZeros32_fallback(val); +#endif } MEM_STATIC unsigned ZSTD_countTrailingZeros64(U64 val) { assert(val != 0); -# if defined(_MSC_VER) && defined(_WIN64) -# if STATIC_BMI2 - return (unsigned)_tzcnt_u64(val); -# else - if (val != 0) { - unsigned long r; - _BitScanForward64(&r, val); - return (unsigned)r; - } else { - /* Should not reach this code path */ - __assume(0); - } -# endif -# elif defined(__GNUC__) && (__GNUC__ >= 4) && defined(__LP64__) - return (unsigned)__builtin_ctzll(val); -# elif defined(__ICCARM__) - return (unsigned)__builtin_ctzll(val); -# else - { - U32 mostSignificantWord = (U32)(val >> 32); - U32 leastSignificantWord = (U32)val; - if (leastSignificantWord == 0) { - return 32 + ZSTD_countTrailingZeros32(mostSignificantWord); - } else { - return ZSTD_countTrailingZeros32(leastSignificantWord); - } +#if defined(_MSC_VER) && defined(_WIN64) +# if STATIC_BMI2 + return (unsigned)_tzcnt_u64(val); +# else + if (val != 0) { + unsigned long r; + _BitScanForward64(&r, val); + return (unsigned)r; + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) && defined(__LP64__) + return (unsigned)__builtin_ctzll(val); +#elif defined(__ICCARM__) + return (unsigned)__builtin_ctzll(val); +#else + { + U32 mostSignificantWord = (U32)(val >> 32); + U32 leastSignificantWord = (U32)val; + if (leastSignificantWord == 0) { + return 32 + ZSTD_countTrailingZeros32(mostSignificantWord); + } else { + return ZSTD_countTrailingZeros32(leastSignificantWord); } -# endif + } +#endif } MEM_STATIC unsigned ZSTD_countLeadingZeros64(U64 val) { assert(val != 0); -# if defined(_MSC_VER) && defined(_WIN64) -# if STATIC_BMI2 - return (unsigned)_lzcnt_u64(val); -# else - if (val != 0) { - unsigned long r; - _BitScanReverse64(&r, val); - return (unsigned)(63 - r); - } else { - /* Should not reach this code path */ - __assume(0); - } -# endif -# elif defined(__GNUC__) && (__GNUC__ >= 4) - return (unsigned)(__builtin_clzll(val)); -# elif defined(__ICCARM__) - return (unsigned)(__builtin_clzll(val)); -# else - { - U32 mostSignificantWord = (U32)(val >> 32); - U32 leastSignificantWord = (U32)val; - if (mostSignificantWord == 0) { - return 32 + ZSTD_countLeadingZeros32(leastSignificantWord); - } else { - return ZSTD_countLeadingZeros32(mostSignificantWord); - } +#if defined(_MSC_VER) && defined(_WIN64) +# if STATIC_BMI2 + return (unsigned)_lzcnt_u64(val); +# else + if (val != 0) { + unsigned long r; + _BitScanReverse64(&r, val); + return (unsigned)(63 - r); + } else { + __assume(0); /* Should not reach this code path */ + } +# endif +#elif defined(__GNUC__) && (__GNUC__ >= 4) + return (unsigned)(__builtin_clzll(val)); +#elif defined(__ICCARM__) + return (unsigned)(__builtin_clzll(val)); +#else + { + U32 mostSignificantWord = (U32)(val >> 32); + U32 leastSignificantWord = (U32)val; + if (mostSignificantWord == 0) { + return 32 + ZSTD_countLeadingZeros32(leastSignificantWord); + } else { + return ZSTD_countLeadingZeros32(mostSignificantWord); } -# endif + } +#endif } MEM_STATIC unsigned ZSTD_NbCommonBytes(size_t val) From 6cd4204ee30c9d3a1ae00ca4082bf4b5c7e3dd7d Mon Sep 17 00:00:00 2001 From: luau-project Date: Sun, 26 Jan 2025 16:50:39 -0300 Subject: [PATCH 635/937] CI: build with CMake on source directory with spaces to reproduce #4268 --- .github/workflows/dev-short-tests.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index dfe1bf584..8648d777e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -92,6 +92,31 @@ jobs: sudo apt install liblzma-dev FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1 + cmake-source-directory-with-spaces: + runs-on: ${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-latest + generator: "Unix Makefiles" + - os: windows-latest + generator: "NMake Makefiles" + - os: macos-latest + generator: "Unix Makefiles" + env: + SRC_DIR: "source directory with spaces" + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + with: + path: "${{ env.SRC_DIR }}" + - uses: ilammy/msvc-dev-cmd@v1 + if: ${{ matrix.generator == 'NMake Makefiles' }} + - name: cmake build on a source directory with spaces + run: | + cmake -S "${{ env.SRC_DIR }}/build/cmake" -B build -DBUILD_TESTING=ON -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release --install-prefix "${{ runner.temp }}/install" + cmake --build build --config Release + cmake --install build --config Release + cpp-gnu90-c99-compatibility: runs-on: ubuntu-latest steps: From 92be4be8102eecedaa0d2a7c65b2d1088e01622a Mon Sep 17 00:00:00 2001 From: Giovanni Cabiddu Date: Tue, 21 Jan 2025 18:52:46 +0000 Subject: [PATCH 636/937] [linux] Expose ZSTD_compressSequencesAndLiterals() in the kernel Make the function ZSTD_compressSequencesAndLiterals() available in kernel space. This will be used by Intel QAT driver. Additionally, (1) expose the function ZSTD_CCtx_setParameter(), which is required to set parameters before calling ZSTD_compressSequencesAndLiterals(), (2) update the build process to include `compress/zstd_preSplit.o` and (3) replace `asm/unaligned.h` with `linux/unaligned.h`. Signed-off-by: Giovanni Cabiddu --- contrib/linux-kernel/linux.mk | 1 + contrib/linux-kernel/linux_zstd.h | 46 ++++++++++++++++++- contrib/linux-kernel/mem.h | 2 +- .../test/include/{asm => linux}/unaligned.h | 0 .../linux-kernel/test/include/linux/xxhash.h | 2 +- contrib/linux-kernel/zstd_compress_module.c | 17 +++++++ 6 files changed, 64 insertions(+), 4 deletions(-) rename contrib/linux-kernel/test/include/{asm => linux}/unaligned.h (100%) diff --git a/contrib/linux-kernel/linux.mk b/contrib/linux-kernel/linux.mk index 464c410b2..be218b5e0 100644 --- a/contrib/linux-kernel/linux.mk +++ b/contrib/linux-kernel/linux.mk @@ -26,6 +26,7 @@ zstd_compress-y := \ compress/zstd_lazy.o \ compress/zstd_ldm.o \ compress/zstd_opt.o \ + compress/zstd_preSplit.o \ zstd_decompress-y := \ zstd_decompress_module.o \ diff --git a/contrib/linux-kernel/linux_zstd.h b/contrib/linux-kernel/linux_zstd.h index 2daf5d25a..dda8a2d7d 100644 --- a/contrib/linux-kernel/linux_zstd.h +++ b/contrib/linux-kernel/linux_zstd.h @@ -136,9 +136,20 @@ typedef ZSTD_parameters zstd_parameters; zstd_parameters zstd_get_params(int level, unsigned long long estimated_src_size); -/* ====== Single-pass Compression ====== */ - typedef ZSTD_CCtx zstd_cctx; +typedef ZSTD_cParameter zstd_cparameter; + +/** + * zstd_cctx_set_param() - sets a compression parameter + * @cctx: The context. Must have been initialized with zstd_init_cctx(). + * @param: The parameter to set. + * @value: The value to set the parameter to. + * + * Return: Zero or an error, which can be checked using zstd_is_error(). + */ +size_t zstd_cctx_set_param(zstd_cctx *cctx, zstd_cparameter param, int value); + +/* ====== Single-pass Compression ====== */ /** * zstd_cctx_workspace_bound() - max memory needed to initialize a zstd_cctx @@ -480,4 +491,35 @@ typedef ZSTD_FrameHeader zstd_frame_header; size_t zstd_get_frame_header(zstd_frame_header *params, const void *src, size_t src_size); +/** + * struct zstd_sequence - a sequence of literals or a match + * + * @offset: The offset of the match + * @litLength: The literal length of the sequence + * @matchLength: The match length of the sequence + * @rep: Represents which repeat offset is used + */ +typedef ZSTD_Sequence zstd_sequence; + +/** + * zstd_compress_sequences_and_literals() - compress an array of zstd_sequence and literals + * + * @cctx: The zstd compression context. + * @dst: The buffer to compress the data into. + * @dst_capacity: The size of the destination buffer. + * @in_seqs: The array of zstd_sequence to compress. + * @in_seqs_size: The number of sequences in in_seqs. + * @literals: The literals associated to the sequences to be compressed. + * @lit_size: The size of the literals in the literals buffer. + * @lit_capacity: The size of the literals buffer. + * @decompressed_size: The size of the input data + * + * Return: The compressed size or an error, which can be checked using + * zstd_is_error(). + */ +size_t zstd_compress_sequences_and_literals(zstd_cctx *cctx, void* dst, size_t dst_capacity, + const zstd_sequence *in_seqs, size_t in_seqs_size, + const void* literals, size_t lit_size, size_t lit_capacity, + size_t decompressed_size); + #endif /* LINUX_ZSTD_H */ diff --git a/contrib/linux-kernel/mem.h b/contrib/linux-kernel/mem.h index 2e91e7780..d9bd752fe 100644 --- a/contrib/linux-kernel/mem.h +++ b/contrib/linux-kernel/mem.h @@ -15,7 +15,7 @@ /*-**************************************** * Dependencies ******************************************/ -#include /* get_unaligned, put_unaligned* */ +#include /* get_unaligned, put_unaligned* */ #include /* inline */ #include /* swab32, swab64 */ #include /* size_t, ptrdiff_t */ diff --git a/contrib/linux-kernel/test/include/asm/unaligned.h b/contrib/linux-kernel/test/include/linux/unaligned.h similarity index 100% rename from contrib/linux-kernel/test/include/asm/unaligned.h rename to contrib/linux-kernel/test/include/linux/unaligned.h diff --git a/contrib/linux-kernel/test/include/linux/xxhash.h b/contrib/linux-kernel/test/include/linux/xxhash.h index d41cbd933..f993eb9ee 100644 --- a/contrib/linux-kernel/test/include/linux/xxhash.h +++ b/contrib/linux-kernel/test/include/linux/xxhash.h @@ -296,7 +296,7 @@ XXH_API void xxh64_copy_state(struct xxh64_state *dst, const struct xxh64_state * - xxHash source repository: https://github.com/Cyan4973/xxHash */ -#include +#include #include #include #include diff --git a/contrib/linux-kernel/zstd_compress_module.c b/contrib/linux-kernel/zstd_compress_module.c index 039db55f9..804efe6d5 100644 --- a/contrib/linux-kernel/zstd_compress_module.c +++ b/contrib/linux-kernel/zstd_compress_module.c @@ -80,6 +80,12 @@ zstd_parameters zstd_get_params(int level, } EXPORT_SYMBOL(zstd_get_params); +size_t zstd_cctx_set_param(zstd_cctx *cctx, ZSTD_cParameter param, int value) +{ + return ZSTD_CCtx_setParameter(cctx, param, value); +} +EXPORT_SYMBOL(zstd_cctx_set_param); + size_t zstd_cctx_workspace_bound(const zstd_compression_parameters *cparams) { return ZSTD_estimateCCtxSize_usingCParams(*cparams); @@ -216,5 +222,16 @@ void zstd_register_sequence_producer( } EXPORT_SYMBOL(zstd_register_sequence_producer); +size_t zstd_compress_sequences_and_literals(zstd_cctx *cctx, void* dst, size_t dst_capacity, + const zstd_sequence *in_seqs, size_t in_seqs_size, + const void* literals, size_t lit_size, size_t lit_capacity, + size_t decompressed_size) +{ + return ZSTD_compressSequencesAndLiterals(cctx, dst, dst_capacity, in_seqs, + in_seqs_size, literals, lit_size, + lit_capacity, decompressed_size); +} +EXPORT_SYMBOL(zstd_compress_sequences_and_literals); + MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("Zstd Compressor"); From be1bf2469e44952efb318f80b781e82e8e9e5183 Mon Sep 17 00:00:00 2001 From: luau-project Date: Mon, 27 Jan 2025 15:18:55 -0300 Subject: [PATCH 637/937] fix: quote include directory for resource compiler --- build/cmake/lib/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index c02822296..2dcd249c6 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -118,7 +118,7 @@ endmacro () # Define directories containing the library's public headers set(PUBLIC_INCLUDE_DIRS ${LIBRARY_DIR}) -set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} /I ${LIBRARY_DIR}") +set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} /I \"${LIBRARY_DIR}\"") # Split project to static and shared libraries build set(library_targets) if (ZSTD_BUILD_SHARED) From de7c8b984236654a567b7b743913849fa6806e8e Mon Sep 17 00:00:00 2001 From: Albert Astals Cid Date: Tue, 28 Jan 2025 00:22:35 +0100 Subject: [PATCH 638/937] cmake: Remove duplicated line --- build/cmake/lib/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 2dcd249c6..4e902a1fb 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -280,7 +280,6 @@ install(TARGETS ${library_targets} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}" FRAMEWORK DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT runtime OPTIONAL - INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) From 8df6155495548d5db02b494fd8be23fad8c6cdfc Mon Sep 17 00:00:00 2001 From: luau-project Date: Thu, 30 Jan 2025 06:08:21 -0300 Subject: [PATCH 639/937] CI: enable Intel LLVM C compiler (icx) check --- .github/workflows/dev-short-tests.yml | 41 +++++++++++++-------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 8648d777e..ec9eff57e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -709,26 +709,23 @@ jobs: run: | sde-external-9.33.0-2024-01-07-lin/sde -cet -cet-raise 0 -cet-endbr-exe -cet-stderr -cet-abort -- ./zstd -b3 + icx: + # install instructions: https://www.intel.com/content/www/us/en/docs/oneapi/installation-guide-linux/2025-0/apt-005.html + name: icx-check + runs-on: ubuntu-latest + steps: + - name: install icx + run: | + # download the key to system keyring + wget -O- https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS.PUB \ + | gpg --dearmor | sudo tee /usr/share/keyrings/oneapi-archive-keyring.gpg > /dev/null -# Failing tests, for reference - -# icc tests are currently failing on Github Actions, likely to issues during installation stage -# -# icc: -# name: icc-check -# runs-on: ubuntu-latest -# steps: -# - name: install icc -# run: | -# export DEBIAN_FRONTEND=noninteractive -# sudo apt-get -qqq update -# sudo apt-get install -y wget build-essential pkg-config cmake ca-certificates gnupg -# sudo wget https://apt.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB -# sudo apt-key add GPG-PUB-KEY-INTEL-SW-PRODUCTS-2023.PUB -# sudo add-apt-repository "deb https://apt.repos.intel.com/oneapi all main" -# sudo apt-get update -# sudo apt-get install -y intel-basekit intel-hpckit -# - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 -# - name: make check -# run: | -# make CC=/opt/intel/oneapi/compiler/latest/linux/bin/intel64/icc check + # add signed entry to apt sources and configure the APT client to use Intel repository: + echo "deb [signed-by=/usr/share/keyrings/oneapi-archive-keyring.gpg] https://apt.repos.intel.com/oneapi all main" | sudo tee /etc/apt/sources.list.d/oneAPI.list + sudo apt-get update + sudo apt-get install -y intel-basekit intel-hpckit + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: make check + run: | + source /opt/intel/oneapi/setvars.sh + make CC=icx check \ No newline at end of file From 60f84f73fed4cb94c166e1dadf3f96ec71a7792c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 30 Jan 2025 21:30:48 -0800 Subject: [PATCH 640/937] bench: better result alignment when displaying ratios > x100 --- programs/benchzstd.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index 5ea7bb72e..f9274a517 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -633,7 +633,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( } { - int const ratioAccuracy = (ratio < 10.) ? 3 : 2; + int const ratioDigits = 1 + (ratio < 100.) + (ratio < 10.); assert(cSize < UINT_MAX); OUTPUTLEVEL( 2, @@ -642,7 +642,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( displayName, (unsigned)srcSize, (unsigned)cSize, - ratioAccuracy, + ratioDigits, ratio, benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT); @@ -669,7 +669,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( } { - int const ratioAccuracy = (ratio < 10.) ? 3 : 2; + int const ratioDigits = 1 + (ratio < 100.) + (ratio < 10.); OUTPUTLEVEL( 2, "%2s-%-17.17s :%10u ->%10u (x%5.*f), %6.*f MB/s, %6.1f MB/s\r", @@ -677,7 +677,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( displayName, (unsigned)srcSize, (unsigned)cSize, - ratioAccuracy, + ratioDigits, ratio, benchResult.cSpeed < (10 * MB_UNIT) ? 2 : 1, (double)benchResult.cSpeed / MB_UNIT, From 7b856e3028518109eb34019e215802cda7cbafc1 Mon Sep 17 00:00:00 2001 From: Victor Zhang Date: Tue, 4 Feb 2025 15:20:39 -0800 Subject: [PATCH 641/937] Add noexecstack flag for gcc/clang C and CPP in Meson The `-Wl,-z,noexecstack` and `-Wa,--noexecstack` flags are already set for CMake, but not for Meson. This brings the flags to the Meson build as well. Note that this maintains the discrepancy in behavior between CMake and Meson when it comes to enabling ASM: on CMake, the ZSTD_HAS_NOEXECSTACK variable is set and these flags added for GCC/Clang and MinGW. Then later, the ZSTD_HAS_NOEXECSTACK variable is checked (along with some other conditions) to enable or disable ASM. However on Meson, this logic is restricted to simply checking for GCC/Clang. This patch maintains this behavior; noexecstack is dependent on GCC/Clang only. --- build/meson/meson.build | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/build/meson/meson.build b/build/meson/meson.build index 7ddca2e79..5c35478d5 100644 --- a/build/meson/meson.build +++ b/build/meson/meson.build @@ -116,10 +116,16 @@ if [compiler_gcc, compiler_clang].contains(cc_id) if cc_id == compiler_clang common_warning_flags += ['-Wconversion', '-Wno-sign-conversion', '-Wdocumentation'] endif - cc_compile_flags = cc.get_supported_arguments(common_warning_flags + ['-Wstrict-prototypes']) - cxx_compile_flags = cxx.get_supported_arguments(common_warning_flags) + noexecstack_flags = ['-Wa,--noexecstack' ] + noexecstack_link_flags = ['-Wl,-z,noexecstack'] + cc_compile_flags = cc.get_supported_arguments(common_warning_flags + noexecstack_flags + ['-Wstrict-prototypes']) + cxx_compile_flags = cxx.get_supported_arguments(common_warning_flags + noexecstack_flags) add_project_arguments(cc_compile_flags, language : 'c') add_project_arguments(cxx_compile_flags, language : 'cpp') + cc_link_flags = cc.get_supported_link_arguments(noexecstack_link_flags) + cxx_link_flags = cxx.get_supported_link_arguments(noexecstack_link_flags) + add_project_link_arguments(cc_link_flags, language: 'c') + add_project_link_arguments(cxx_link_flags, language: 'cpp') elif cc_id == compiler_msvc msvc_compile_flags = [ '/D_UNICODE', '/DUNICODE' ] if use_multi_thread From 6e1d02f1f04f9c255108f84cc788b709e7871c2e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 12:06:14 -0800 Subject: [PATCH 642/937] adding a Visual + ClangCL + AVX2 compilation test --- .github/workflows/dev-short-tests.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 8648d777e..26c175994 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -362,6 +362,8 @@ jobs: - generator: "MinGW Makefiles" - generator: "Visual Studio 17 2022" flags: "-T ClangCL" + - generator: "Visual Studio 17 2022" + flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" runs-on: windows-2022 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 From bcf404c0ab73cb6cc822a1412b78ba7965f9d74d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 13:25:14 -0800 Subject: [PATCH 643/937] changed C11 keyword to _Alignas so that it doesn't depend on #include --- lib/common/compiler.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 5ad212383..66792463b 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -305,7 +305,7 @@ MEM_STATIC int ZSTD_isPower2(size_t u) { # if defined(__GNUC__) # define ZSTD_ALIGNED(a) __attribute__((aligned(a))) # elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ -# define ZSTD_ALIGNED(a) alignas(a) +# define ZSTD_ALIGNED(a) _Alignas(a) #elif defined(_MSC_VER) # define ZSTD_ALIGNED(n) __declspec(align(n)) # else From 54e9d46db44c4832d031100800f54a397358f896 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 13:48:24 -0800 Subject: [PATCH 644/937] added __clang__ to compiler-specific alignment attribute when clang is used within msvc, `__GNUC__` isn't defined, so testing `__clang__` explicitly is required. --- lib/common/compiler.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 66792463b..1f7da50e6 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -302,7 +302,7 @@ MEM_STATIC int ZSTD_isPower2(size_t u) { #ifndef ZSTD_ALIGNED /* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */ -# if defined(__GNUC__) +# if defined(__GNUC__) || defined(__clang__) # define ZSTD_ALIGNED(a) __attribute__((aligned(a))) # elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */ # define ZSTD_ALIGNED(a) _Alignas(a) From 5883ee6cc2303259f6a5ca824d9b9786c223df54 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 15:38:39 -0800 Subject: [PATCH 645/937] make visual studio tests error out on warnings --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 26c175994..2b35354d2 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -375,7 +375,7 @@ jobs: cd build\cmake mkdir build cd build - cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 .. + cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 .. cmake.exe --build . ctest.exe -V -C Debug From 32dff04d320c2dc667380076dff5d575fcf73207 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 15:46:44 -0800 Subject: [PATCH 646/937] fix one minor alignment warning seems like a prototype interface error: input parameter should have been `const void*`, since the documentation is explicit that input doesn't have to be aligned, but `const __m256i*` makes the compiler enforce it. --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index abc75fb2d..356397605 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7191,7 +7191,7 @@ static size_t convertSequences_noRepcodes( /* Process 2 sequences per loop iteration */ for (; i + 1 < nbSequences; i += 2) { /* Load 2 ZSTD_Sequence (32 bytes) */ - __m256i vin = _mm256_loadu_si256((__m256i const*)&inSeqs[i]); + __m256i vin = _mm256_loadu_si256((const __m256i*)(const void*)&inSeqs[i]); /* Add {2, 0, -3, 0} in each 128-bit half */ __m256i vadd = _mm256_add_epi32(vin, addition); From c39424ea87288aec400305c3bc3cf1ec6ef7d803 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 16:11:54 -0800 Subject: [PATCH 647/937] fix minor alignment warning this is a prototype definition error: `_mm_storeu_si128()` should accept a `void*` pointer, since it explicitly states that it accepts unaligned addresses yet requiring a `__m128i*` tells otherwise, and requires the compiler the enforce this alignment. --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 356397605..f9600ff71 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7218,7 +7218,7 @@ static size_t convertSequences_noRepcodes( */ /* Store only the lower 16 bytes => 2 SeqDef (8 bytes each) */ - _mm_storeu_si128((__m128i *)&dstSeqs[i], _mm256_castsi256_si128(vperm)); + _mm_storeu_si128((__m128i *)(void*)&dstSeqs[i], _mm256_castsi256_si128(vperm)); /* * This writes out 16 bytes total: * - offset 0..7 => seq0 (offBase, litLength, mlBase) From e117d79e22ae98be24d1867b0f2b8730e952c835 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 16:13:58 -0800 Subject: [PATCH 648/937] fix minor alignment warning --- lib/compress/zstd_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index f9600ff71..b755c6bc2 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7400,7 +7400,7 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) /* Process 2 structs (32 bytes) at a time */ for (i = 0; i + 2 <= nbSeqs; i += 2) { /* Load two consecutive ZSTD_Sequence (8×4 = 32 bytes) */ - __m256i data = _mm256_loadu_si256((const __m256i*)&seqs[i]); + __m256i data = _mm256_loadu_si256((const __m256i*)(const void*)&seqs[i]); /* check end of block signal */ __m256i cmp = _mm256_cmpeq_epi32(data, zeroVec); int cmp_res = _mm256_movemask_epi8(cmp); From f9c1850aa2df6024e930b257067401108fa268ef Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 16:28:52 -0800 Subject: [PATCH 649/937] fix minor printf argument limitation on older mingw which do not support `%zu` fields --- tests/fullbench.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/fullbench.c b/tests/fullbench.c index 7d77bd176..12a27f48c 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -696,7 +696,7 @@ check_compressedSequences(const void* compressed, size_t cSize, const void* orig if (decompressed == NULL) return 2; decSize = ZSTD_decompress(decompressed, origSize, compressed, cSize); - if (decSize != origSize) { free(decompressed); DISPLAY("ZSTD_decompress failed (%zu) ", decSize); return 1; } + if (decSize != origSize) { free(decompressed); DISPLAY("ZSTD_decompress failed (%u) ", (unsigned)decSize); return 1; } diff = memcmp(decompressed, orig, origSize); if (diff) { free(decompressed); return 1; } @@ -904,7 +904,7 @@ static int benchMem(unsigned scenarioID, if (verif_f) { size_t const vRes = verif_f(dst, newResult.sumOfReturn, origSrc, origSrcSize); if (vRes) { - DISPLAY(" validation failed ! (%zu)\n", vRes); + DISPLAY(" validation failed ! (%u)\n", (unsigned)vRes); break; } } From 590c22454e24c0247f60a5fd939a1c4f1d49e896 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 16:36:54 -0800 Subject: [PATCH 650/937] fix more %zu warnings --- tests/fuzzer.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/fuzzer.c b/tests/fuzzer.c index b457c2171..b74460bb5 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -1918,7 +1918,7 @@ static int basicUnitTests(U32 const seed, double compressibility) params.fParams.contentSizeFlag = 0; params.cParams.windowLog = ZSTD_WINDOWLOG_MAX; for (cnb = 0; cnb < nbCompressions; ++cnb) { - DISPLAYLEVEL(6, "run %zu / %zu \n", cnb, nbCompressions); + DISPLAYLEVEL(6, "run %u / %u \n", (unsigned)cnb, (unsigned)nbCompressions); CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* reuse same parameters */ CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) ); } @@ -1936,8 +1936,8 @@ static int basicUnitTests(U32 const seed, double compressibility) assert(smallCCtx != NULL); CHECK_Z(ZSTD_compressCCtx(smallCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1)); { size_t const smallCCtxSize = ZSTD_sizeof_CCtx(smallCCtx); - DISPLAYLEVEL(5, "(large) %zuKB > 32*%zuKB (small) : ", - largeCCtxSize>>10, smallCCtxSize>>10); + DISPLAYLEVEL(5, "(large) %uKB > 32*%uKB (small) : ", + (unsigned)(largeCCtxSize>>10), (unsigned)(smallCCtxSize>>10)); assert(largeCCtxSize > 32* smallCCtxSize); /* note : "too large" definition is handled within zstd_compress.c . * make this test case extreme, so that it doesn't depend on a possibly fluctuating definition */ } @@ -3480,7 +3480,7 @@ static int basicUnitTests(U32 const seed, double compressibility) { size_t const compressionResult = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, srcSize); - DISPLAYLEVEL(5, "simple=%zu vs %zu=advanced : ", cSize_1pass, compressionResult); + DISPLAYLEVEL(5, "simple=%u vs %u=advanced : ", (unsigned)cSize_1pass, (unsigned)compressionResult); if (ZSTD_isError(compressionResult)) goto _output_error; if (compressionResult != cSize_1pass) goto _output_error; } } @@ -4361,8 +4361,8 @@ static int basicUnitTests(U32 const seed, double compressibility) for (; level < ZSTD_maxCLevel(); ++level) { size_t const currSize = ZSTD_estimateCCtxSize(level); if (prevSize > currSize) { - DISPLAYLEVEL(3, "Error! previous cctx size: %zu at level: %d is larger than current cctx size: %zu at level: %d", - prevSize, level-1, currSize, level); + DISPLAYLEVEL(3, "Error! previous cctx size: %u at level: %d is larger than current cctx size: %u at level: %d", + (unsigned)prevSize, level-1, (unsigned)currSize, level); goto _output_error; } prevSize = currSize; @@ -4386,8 +4386,8 @@ static int basicUnitTests(U32 const seed, double compressibility) if (cctxSizeUsingLevel < cctxSizeUsingCParams || ZSTD_isError(cctxSizeUsingCParams) || ZSTD_isError(cctxSizeUsingLevel)) { - DISPLAYLEVEL(3, "error! l: %d dict: %zu srcSize: %zu cctx size cpar: %zu, cctx size level: %zu\n", - level, dictSize, srcSize, cctxSizeUsingCParams, cctxSizeUsingLevel); + DISPLAYLEVEL(3, "error! l: %d dict: %u srcSize: %u cctx size cpar: %u, cctx size level: %u\n", + level, (unsigned)dictSize, (unsigned)srcSize, (unsigned)cctxSizeUsingCParams, (unsigned)cctxSizeUsingLevel); goto _output_error; } } } } } DISPLAYLEVEL(3, "OK \n"); From e87d15938c888011cdcc7aa6d45a85ea055a5da8 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 16:48:19 -0800 Subject: [PATCH 651/937] more %zu warnings fixes --- tests/zstreamtest.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index b8290fefc..b50984f3f 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -537,7 +537,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) outBuff.size = compressedBufferSize; outBuff.pos = 0; { size_t const r = ZSTD_endStream(zc, &outBuff); - CHECK(r != 0, "Error or some data not flushed (ret=%zu)", r); + CHECK(r != 0, "Error or some data not flushed (ret=%i)", ZSTD_getErrorCode(r)); } inBuff.src = outBuff.dst; inBuff.size = outBuff.pos; @@ -567,7 +567,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) outBuff.size = compressedBufferSize; outBuff.pos = 0; { size_t const r = ZSTD_endStream(zc, &outBuff); - CHECK(r != 0, "Error or some data not flushed (ret=%zu)", r); + CHECK(r != 0, "Error or some data not flushed (ret=%i)", ZSTD_getErrorCode(r)); } inBuff.src = outBuff.dst; inBuff.size = outBuff.pos; @@ -595,7 +595,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) CHECK_Z( ZSTD_compressStream(zc, &outBuff, &inBuff) ); CHECK(inBuff.pos != inBuff.size, "Entire input should be consumed"); { size_t const r = ZSTD_endStream(zc, &outBuff); - CHECK(r != 0, "Error or some data not flushed (ret=%zu)", r); + CHECK(r != 0, "Error or some data not flushed (ret=%i)", ZSTD_getErrorCode(r)); } { unsigned long long origSize = ZSTD_findDecompressedSize(outBuff.dst, outBuff.pos); CHECK(origSize == ZSTD_CONTENTSIZE_UNKNOWN, "Unknown!"); @@ -777,7 +777,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) CHECK(streamingSize < singlePassSize + (1 << 18) + 3 * ZSTD_BLOCKSIZE_MAX, "Streaming doesn't use the right amount of memory"); CHECK(streamingSize != streaming2KSize + 3 * (ZSTD_BLOCKSIZE_MAX - 2048), "ZSTD_d_blockSizeMax didn't save the right amount of memory"); - DISPLAYLEVEL(3, "| %zu | %zu | %zu | ", singlePassSize, streaming2KSize, streamingSize); + DISPLAYLEVEL(3, "| %u | %u | %u | ", (unsigned)singlePassSize, (unsigned)streaming2KSize, (unsigned)streamingSize); ZSTD_freeDCtx(dctx); } @@ -999,7 +999,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) void* const verifBuf = (char*)outBuf.dst + outBuf.pos; const size_t decSize = ZSTD_decompress(verifBuf, inputSize, outBuf.dst, outBuf.pos); CHECK_Z(decSize); - CHECK(decSize != inputSize, "regenerated %zu bytes, instead of %zu", decSize, inputSize); + CHECK(decSize != inputSize, "regenerated %u bytes, instead of %u", (unsigned)decSize, (unsigned)inputSize); CHECK(memcmp(realSrcStart, verifBuf, inputSize) != 0, "regenerated data different from original"); } } DISPLAYLEVEL(3, "OK \n"); @@ -1029,14 +1029,14 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) void* const verifBuf = (char*)outBuf.dst + outBuf.pos; const size_t decSize = ZSTD_decompress(verifBuf, inputSize, outBuf.dst, outBuf.pos); CHECK_Z(decSize); - CHECK(decSize != inputSize, "regenerated %zu bytes, instead of %zu", decSize, inputSize); + CHECK(decSize != inputSize, "regenerated %u bytes, instead of %u", (unsigned)decSize, (unsigned)inputSize); CHECK(memcmp(realSrcStart, verifBuf, inputSize) != 0, "regenerated data different from original"); } } DISPLAYLEVEL(3, "OK \n"); DISPLAYLEVEL(3, "test%3i : ZSTD_compressStream2() with ZSTD_c_stableInBuffer: context size : ", testNb++); { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx); - DISPLAYLEVEL(4, "cctxSize1=%zu; cctxSize=%zu; cctxSize2=%zu : ", cctxSize1, cctxSize, cctxSize2); + DISPLAYLEVEL(4, "cctxSize1=%u; cctxSize=%u; cctxSize2=%u : ", (unsigned)cctxSize1, (unsigned)cctxSize, (unsigned)cctxSize2); CHECK(!(cctxSize1 < cctxSize), "Must be bigger than single-pass"); CHECK(!(cctxSize < cctxSize2), "Must be smaller than streaming"); cctxSize1 = cctxSize; @@ -1071,7 +1071,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : ZSTD_compressStream2() with ZSTD_c_stableOutBuffer: context size : ", testNb++); { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx); - DISPLAYLEVEL(4, "cctxSize1=%zu; cctxSize=%zu; cctxSize2=%zu : ", cctxSize1, cctxSize, cctxSize2); + DISPLAYLEVEL(4, "cctxSize1=%u; cctxSize=%u; cctxSize2=%u : ", (unsigned)cctxSize1, (unsigned)cctxSize, (unsigned)cctxSize2); CHECK(!(cctxSize1 < cctxSize), "Must be bigger than single-pass and stableInBuffer"); CHECK(!(cctxSize < cctxSize2), "Must be smaller than streaming"); } @@ -2983,7 +2983,7 @@ static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest, const U32 windowLogMax = bigTests ? 24 : 20; const U32 searchLogMax = bigTests ? 15 : 13; if (dictSize) - DISPLAYLEVEL(5, "t%u: with dictionary of size : %zu \n", testNb, dictSize); + DISPLAYLEVEL(5, "t%u: with dictionary of size : %u \n", testNb, (unsigned)dictSize); /* mess with compression parameters */ cParams.windowLog += (FUZ_rand(&lseed) & 3) - 1; @@ -3178,7 +3178,7 @@ static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest, } cSize = outBuff.pos; compressedCrcs[iter] = XXH64(cBuffer, cSize, 0); - DISPLAYLEVEL(5, "Frame completed : %zu bytes \n", cSize); + DISPLAYLEVEL(5, "Frame completed : %u bytes \n", (unsigned)cSize); } CHECK(!(compressedCrcs[0] == compressedCrcs[1]), "Compression is not deterministic!"); } @@ -3194,7 +3194,7 @@ static int fuzzerTests_newAPI(U32 seed, int nbTests, int startTest, CHECK_Z( ZSTD_resetDStream(zd) ); } else { if (dictSize) - DISPLAYLEVEL(5, "using dictionary of size %zu \n", dictSize); + DISPLAYLEVEL(5, "using dictionary of size %u \n", (unsigned)dictSize); CHECK_Z( ZSTD_initDStream_usingDict(zd, dict, dictSize) ); } if (FUZ_rand(&lseed) & 1) { From 294925292304b3c5b5e975f9036a684881dba469 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 17:01:19 -0800 Subject: [PATCH 652/937] fix minor conversion warnings --- tests/zstreamtest.c | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index b50984f3f..760d9f26c 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -1505,7 +1505,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) DISPLAYLEVEL(3, "test%3i : compress %u bytes with multiple threads + dictionary : ", testNb++, (unsigned)srcSize); CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_compressionLevel, 3) ); CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_nbWorkers, nbWorkers) ); - CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_jobSize, jobSize) ); + CHECK_Z( ZSTD_CCtx_setParameter(zc, ZSTD_c_jobSize, (int)jobSize) ); assert(start > offset); assert(start + segLength < COMPRESSIBLE_NOISE_LENGTH); memcpy(dst, srcToCopy, segLength); /* create a long repetition at long distance for job 2 */ @@ -1654,7 +1654,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) int windowLog; int const kMaxWindowLog = bigTests ? 29 : 26; size_t const kNbSequences = 10000; - size_t const kMaxSrcSize = (1u << kMaxWindowLog) + 10 * kNbSequences; + size_t const kMaxSrcSize = ((size_t)1 << kMaxWindowLog) + 10 * kNbSequences; char* src = calloc(kMaxSrcSize, 1); ZSTD_Sequence* sequences = malloc(sizeof(ZSTD_Sequence) * kNbSequences); for (windowLog = ZSTD_WINDOWLOG_MIN; windowLog <= kMaxWindowLog; ++windowLog) { @@ -1902,7 +1902,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) CHECK_Z(ZSTD_compressStream2(zc, &out, &in, ZSTD_e_flush)); CHECK(in.pos != in.size, "input not fully consumed"); - remainingInput -= kSmallBlockSize; + remainingInput -= (int)kSmallBlockSize; } /* Write several very long offset matches into the dictionary */ for (offset = 1024; offset >= 0; offset -= 128) { @@ -2582,13 +2582,13 @@ static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, double co static const U32 maxSampleLog = 19; size_t const srcBufferSize = (size_t)1< Date: Thu, 30 Jan 2025 15:58:20 -0800 Subject: [PATCH 653/937] fix speed of --patch-from at high compression mode --- lib/compress/zstd_compress.c | 69 ++++++++++++++++++---------------- lib/compress/zstdmt_compress.c | 4 +- 2 files changed, 38 insertions(+), 35 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index b755c6bc2..bd7667d4a 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -3117,7 +3117,7 @@ ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_Para ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1); assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, (int)strat)); - DEBUGLOG(4, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder); + DEBUGLOG(5, "Selected block compressor: dictMode=%d strat=%d rowMatchfinder=%d", (int)dictMode, (int)strat, (int)useRowMatchFinder); if (ZSTD_rowMatchFinderUsed(strat, useRowMatchFinder)) { static const ZSTD_BlockCompressor_f rowBasedBlockCompressors[4][3] = { { @@ -3141,7 +3141,7 @@ ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_Para ZSTD_COMPRESSBLOCK_LAZY2_DEDICATEDDICTSEARCH_ROW } }; - DEBUGLOG(4, "Selecting a row-based matchfinder"); + DEBUGLOG(5, "Selecting a row-based matchfinder"); assert(useRowMatchFinder != ZSTD_ps_auto); selectedCompressor = rowBasedBlockCompressors[(int)dictMode][(int)strat - (int)ZSTD_greedy]; } else { @@ -3619,7 +3619,7 @@ writeBlockHeader(void* op, size_t cSize, size_t blockSize, U32 lastBlock) lastBlock + (((U32)bt_rle)<<1) + (U32)(blockSize << 3) : lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3); MEM_writeLE24(op, cBlockHeader); - DEBUGLOG(3, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock); + DEBUGLOG(5, "writeBlockHeader: cSize: %zu blockSize: %zu lastBlock: %u", cSize, blockSize, lastBlock); } /** ZSTD_buildBlockEntropyStats_literals() : @@ -4151,18 +4151,18 @@ ZSTD_compressSeqStore_singleBlock(ZSTD_CCtx* zc, if (cSeqsSize == 0) { cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, srcSize, lastBlock); FORWARD_IF_ERROR(cSize, "Nocompress block failed"); - DEBUGLOG(4, "Writing out nocompress block, size: %zu", cSize); + DEBUGLOG(5, "Writing out nocompress block, size: %zu", cSize); *dRep = dRepOriginal; /* reset simulated decompression repcode history */ } else if (cSeqsSize == 1) { cSize = ZSTD_rleCompressBlock(op, dstCapacity, *ip, srcSize, lastBlock); FORWARD_IF_ERROR(cSize, "RLE compress block failed"); - DEBUGLOG(4, "Writing out RLE block, size: %zu", cSize); + DEBUGLOG(5, "Writing out RLE block, size: %zu", cSize); *dRep = dRepOriginal; /* reset simulated decompression repcode history */ } else { ZSTD_blockState_confirmRepcodesAndEntropyTables(&zc->blockState); writeBlockHeader(op, cSeqsSize, srcSize, lastBlock); cSize = ZSTD_blockHeaderSize + cSeqsSize; - DEBUGLOG(4, "Writing out compressed block, size: %zu", cSize); + DEBUGLOG(5, "Writing out compressed block, size: %zu", cSize); } if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid) @@ -4357,7 +4357,7 @@ ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc, { U32 nbSeq; size_t cSize; - DEBUGLOG(4, "ZSTD_compressBlock_splitBlock"); + DEBUGLOG(5, "ZSTD_compressBlock_splitBlock"); assert(zc->appliedParams.postBlockSplitter == ZSTD_ps_enable); { const size_t bss = ZSTD_buildSeqStore(zc, src, srcSize); @@ -4368,7 +4368,7 @@ ZSTD_compressBlock_splitBlock(ZSTD_CCtx* zc, RETURN_ERROR_IF(zc->seqCollector.collectSequences, sequenceProducer_failed, "Uncompressible block"); cSize = ZSTD_noCompressBlock(dst, dstCapacity, src, srcSize, lastBlock); FORWARD_IF_ERROR(cSize, "ZSTD_noCompressBlock failed"); - DEBUGLOG(4, "ZSTD_compressBlock_splitBlock: Nocompress block"); + DEBUGLOG(5, "ZSTD_compressBlock_splitBlock: Nocompress block"); return cSize; } nbSeq = (U32)(zc->seqStore.sequences - zc->seqStore.sequencesStart); @@ -4603,7 +4603,7 @@ static size_t ZSTD_compress_frameChunk(ZSTD_CCtx* cctx, assert(cctx->appliedParams.cParams.windowLog <= ZSTD_WINDOWLOG_MAX); - DEBUGLOG(4, "ZSTD_compress_frameChunk (blockSizeMax=%u)", (unsigned)blockSizeMax); + DEBUGLOG(5, "ZSTD_compress_frameChunk (srcSize=%u, blockSizeMax=%u)", (unsigned)srcSize, (unsigned)blockSizeMax); if (cctx->appliedParams.fParams.checksumFlag && srcSize) XXH64_update(&cctx->xxhState, src, srcSize); @@ -4898,13 +4898,14 @@ size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const /*! ZSTD_loadDictionaryContent() : * @return : 0, or an error code */ -static size_t ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, - ldmState_t* ls, - ZSTD_cwksp* ws, - ZSTD_CCtx_params const* params, - const void* src, size_t srcSize, - ZSTD_dictTableLoadMethod_e dtlm, - ZSTD_tableFillPurpose_e tfp) +static size_t +ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, + ldmState_t* ls, + ZSTD_cwksp* ws, + ZSTD_CCtx_params const* params, + const void* src, size_t srcSize, + ZSTD_dictTableLoadMethod_e dtlm, + ZSTD_tableFillPurpose_e tfp) { const BYTE* ip = (const BYTE*) src; const BYTE* const iend = ip + srcSize; @@ -4948,17 +4949,18 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, } ZSTD_window_update(&ms->window, src, srcSize, /* forceNonContiguous */ 0); - DEBUGLOG(4, "ZSTD_loadDictionaryContent(): useRowMatchFinder=%d", (int)params->useRowMatchFinder); + DEBUGLOG(4, "ZSTD_loadDictionaryContent: useRowMatchFinder=%d", (int)params->useRowMatchFinder); if (loadLdmDict) { /* Load the entire dict into LDM matchfinders. */ + DEBUGLOG(4, "ZSTD_loadDictionaryContent: Trigger loadLdmDict"); ZSTD_window_update(&ls->window, src, srcSize, /* forceNonContiguous */ 0); ls->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ls->window.base); ZSTD_ldm_fillHashTable(ls, ip, iend, ¶ms->ldmParams); + DEBUGLOG(4, "ZSTD_loadDictionaryContent: ZSTD_ldm_fillHashTable completes"); } /* If the dict is larger than we can reasonably index in our tables, only load the suffix. */ - if (params->cParams.strategy < ZSTD_btultra) { - U32 maxDictSize = 8U << MIN(MAX(params->cParams.hashLog, params->cParams.chainLog), 28); + { U32 maxDictSize = 2U << MIN(MAX(params->cParams.hashLog, params->cParams.chainLog), 30); if (srcSize > maxDictSize) { ip = iend - maxDictSize; src = ip; @@ -5022,6 +5024,7 @@ static size_t ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, || !defined(ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR) \ || !defined(ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR) assert(srcSize >= HASH_READ_SIZE); + DEBUGLOG(4, "Fill %u bytes into the Binary Tree", (unsigned)srcSize); ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend); #else assert(0); /* shouldn't be called: cparams should've been adjusted. */ @@ -5598,14 +5601,16 @@ static size_t ZSTD_initCDict_internal( return 0; } -static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize, - ZSTD_dictLoadMethod_e dictLoadMethod, - ZSTD_compressionParameters cParams, - ZSTD_ParamSwitch_e useRowMatchFinder, - int enableDedicatedDictSearch, - ZSTD_customMem customMem) +static ZSTD_CDict* +ZSTD_createCDict_advanced_internal(size_t dictSize, + ZSTD_dictLoadMethod_e dictLoadMethod, + ZSTD_compressionParameters cParams, + ZSTD_ParamSwitch_e useRowMatchFinder, + int enableDedicatedDictSearch, + ZSTD_customMem customMem) { 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)) + @@ -5642,6 +5647,7 @@ ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize, { ZSTD_CCtx_params cctxParams; ZSTD_memset(&cctxParams, 0, sizeof(cctxParams)); + DEBUGLOG(3, "ZSTD_createCDict_advanced, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType); ZSTD_CCtxParams_init(&cctxParams, 0); cctxParams.cParams = cParams; cctxParams.customMem = customMem; @@ -5662,7 +5668,7 @@ ZSTD_CDict* ZSTD_createCDict_advanced2( ZSTD_compressionParameters cParams; ZSTD_CDict* cdict; - DEBUGLOG(3, "ZSTD_createCDict_advanced2, mode %u", (unsigned)dictContentType); + DEBUGLOG(3, "ZSTD_createCDict_advanced2, dictSize=%u, mode=%u", (unsigned)dictSize, (unsigned)dictContentType); if (!customMem.customAlloc ^ !customMem.customFree) return NULL; if (cctxParams.enableDedicatedDictSearch) { @@ -5681,7 +5687,7 @@ ZSTD_CDict* ZSTD_createCDict_advanced2( &cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, dictSize, ZSTD_cpm_createCDict); } - DEBUGLOG(3, "ZSTD_createCDict_advanced2: DDS: %u", cctxParams.enableDedicatedDictSearch); + DEBUGLOG(3, "ZSTD_createCDict_advanced2: DedicatedDictSearch=%u", cctxParams.enableDedicatedDictSearch); cctxParams.cParams = cParams; cctxParams.useRowMatchFinder = ZSTD_resolveRowMatchFinderMode(cctxParams.useRowMatchFinder, &cParams); @@ -5767,6 +5773,7 @@ const ZSTD_CDict* ZSTD_initStaticCDict( ZSTD_CDict* cdict; ZSTD_CCtx_params params; + DEBUGLOG(4, "ZSTD_initStaticCDict (dictSize==%u)", (unsigned)dictSize); if ((size_t)workspace & 7) return NULL; /* 8-aligned */ { @@ -5777,8 +5784,6 @@ const ZSTD_CDict* ZSTD_initStaticCDict( ZSTD_cwksp_move(&cdict->workspace, &ws); } - DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u", - (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize)); if (workspaceSize < neededSize) return NULL; ZSTD_CCtxParams_init(¶ms, 0); @@ -6357,7 +6362,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, */ params.compressionLevel = cctx->cdict->compressionLevel; } - DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage"); + DEBUGLOG(4, "ZSTD_CCtx_init_compressStream2 : transparent init stage"); if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = inSize + 1; /* auto-determine pledgedSrcSize */ { size_t const dictSize = prefixDict.dict @@ -6388,9 +6393,9 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */ } if (params.nbWorkers > 0) { -#if ZSTD_TRACE +# if ZSTD_TRACE cctx->traceCtx = (ZSTD_trace_compress_begin != NULL) ? ZSTD_trace_compress_begin(cctx) : 0; -#endif +# endif /* mt context creation */ if (cctx->mtctx == NULL) { DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u", diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index e8fef5144..86ca05315 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1245,13 +1245,11 @@ size_t ZSTDMT_initCStream_internal( /* init */ if (params.nbWorkers != mtctx->params.nbWorkers) - FORWARD_IF_ERROR( ZSTDMT_resize(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; - DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers); - if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */ ZSTDMT_waitForAllJobsCompleted(mtctx); ZSTDMT_releaseAllJobResources(mtctx); From 34ba14437aeeb5e678ae7f1dbdfa6333beb2723b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 30 Jan 2025 18:05:58 -0800 Subject: [PATCH 654/937] minor boundary change improves compression ratio at low levels --- Makefile | 6 +++--- lib/compress/zstd_compress.c | 2 +- tests/regression/results.csv | 18 +++++++++--------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index 03ee6fe89..e8e6bcffe 100644 --- a/Makefile +++ b/Makefile @@ -296,9 +296,9 @@ msanregressiontest: update_regressionResults : REGRESS_RESULTS_DIR := /tmp/regress_results_dir/ update_regressionResults: - $(MAKE) -C programs zstd - $(MAKE) -C tests/regression test - $(RM) -rf $(REGRESS_RESULTS_DIR) + $(MAKE) -j -C programs zstd + $(MAKE) -j -C tests/regression test + $(RM) -r $(REGRESS_RESULTS_DIR) $(MKDIR) $(REGRESS_RESULTS_DIR) ./tests/regression/test \ --cache tests/regression/cache \ diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index bd7667d4a..d394617bc 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4960,7 +4960,7 @@ ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, } /* If the dict is larger than we can reasonably index in our tables, only load the suffix. */ - { U32 maxDictSize = 2U << MIN(MAX(params->cParams.hashLog, params->cParams.chainLog), 30); + { U32 maxDictSize = 1U << MIN(MAX(params->cParams.hashLog + 3, params->cParams.chainLog + 1), 31); if (srcSize > maxDictSize) { ip = iend - maxDictSize; src = ip; diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 94d113578..505f4755b 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -395,19 +395,19 @@ github, level 13 with dict, advanced github, level 13 with dict dms, advanced one pass, 39900 github, level 13 with dict dds, advanced one pass, 39900 github, level 13 with dict copy, advanced one pass, 39948 -github, level 13 with dict load, advanced one pass, 42624 +github, level 13 with dict load, advanced one pass, 42643 github, level 16, advanced one pass, 133209 github, level 16 with dict, advanced one pass, 37902 github, level 16 with dict dms, advanced one pass, 37902 github, level 16 with dict dds, advanced one pass, 37902 github, level 16 with dict copy, advanced one pass, 37892 -github, level 16 with dict load, advanced one pass, 42402 +github, level 16 with dict load, advanced one pass, 42434 github, level 19, advanced one pass, 132879 github, level 19 with dict, advanced one pass, 37916 github, level 19 with dict dms, advanced one pass, 37916 github, level 19 with dict dds, advanced one pass, 37916 github, level 19 with dict copy, advanced one pass, 37906 -github, level 19 with dict load, advanced one pass, 39770 +github, level 19 with dict load, advanced one pass, 40405 github, no source size, advanced one pass, 136331 github, no source size with dict, advanced one pass, 41118 github, long distance mode, advanced one pass, 136331 @@ -713,19 +713,19 @@ github, level 13 with dict, advanced github, level 13 with dict dms, advanced one pass small out, 39900 github, level 13 with dict dds, advanced one pass small out, 39900 github, level 13 with dict copy, advanced one pass small out, 39948 -github, level 13 with dict load, advanced one pass small out, 42624 +github, level 13 with dict load, advanced one pass small out, 42643 github, level 16, advanced one pass small out, 133209 github, level 16 with dict, advanced one pass small out, 37902 github, level 16 with dict dms, advanced one pass small out, 37902 github, level 16 with dict dds, advanced one pass small out, 37902 github, level 16 with dict copy, advanced one pass small out, 37892 -github, level 16 with dict load, advanced one pass small out, 42402 +github, level 16 with dict load, advanced one pass small out, 42434 github, level 19, advanced one pass small out, 132879 github, level 19 with dict, advanced one pass small out, 37916 github, level 19 with dict dms, advanced one pass small out, 37916 github, level 19 with dict dds, advanced one pass small out, 37916 github, level 19 with dict copy, advanced one pass small out, 37906 -github, level 19 with dict load, advanced one pass small out, 39770 +github, level 19 with dict load, advanced one pass small out, 40405 github, no source size, advanced one pass small out, 136331 github, no source size with dict, advanced one pass small out, 41118 github, long distance mode, advanced one pass small out, 136331 @@ -1031,19 +1031,19 @@ github, level 13 with dict, advanced github, level 13 with dict dms, advanced streaming, 39900 github, level 13 with dict dds, advanced streaming, 39900 github, level 13 with dict copy, advanced streaming, 39948 -github, level 13 with dict load, advanced streaming, 42624 +github, level 13 with dict load, advanced streaming, 42643 github, level 16, advanced streaming, 133209 github, level 16 with dict, advanced streaming, 37902 github, level 16 with dict dms, advanced streaming, 37902 github, level 16 with dict dds, advanced streaming, 37902 github, level 16 with dict copy, advanced streaming, 37892 -github, level 16 with dict load, advanced streaming, 42402 +github, level 16 with dict load, advanced streaming, 42434 github, level 19, advanced streaming, 132879 github, level 19 with dict, advanced streaming, 37916 github, level 19 with dict dms, advanced streaming, 37916 github, level 19 with dict dds, advanced streaming, 37916 github, level 19 with dict copy, advanced streaming, 37906 -github, level 19 with dict load, advanced streaming, 39770 +github, level 19 with dict load, advanced streaming, 40405 github, no source size, advanced streaming, 136331 github, no source size with dict, advanced streaming, 41118 github, long distance mode, advanced streaming, 136331 From e637fc64c5f918e316146fb1d78c1cb587b1134c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 31 Jan 2025 15:00:36 -0800 Subject: [PATCH 655/937] update type naming convention --- lib/compress/zstdmt_compress.c | 102 ++++++++++++++++----------------- 1 file changed, 51 insertions(+), 51 deletions(-) diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 86ca05315..fe98dab1c 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -90,9 +90,9 @@ static unsigned long long GetCurrentClockTimeMicroseconds(void) typedef struct buffer_s { void* start; size_t capacity; -} buffer_t; +} Buffer; -static const buffer_t g_nullBuffer = { NULL, 0 }; +static const Buffer g_nullBuffer = { NULL, 0 }; typedef struct ZSTDMT_bufferPool_s { ZSTD_pthread_mutex_t poolMutex; @@ -100,7 +100,7 @@ typedef struct ZSTDMT_bufferPool_s { unsigned totalBuffers; unsigned nbBuffers; ZSTD_customMem cMem; - buffer_t* buffers; + Buffer* buffers; } ZSTDMT_bufferPool; static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool) @@ -128,7 +128,7 @@ static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_cu ZSTD_customFree(bufPool, cMem); return NULL; } - bufPool->buffers = (buffer_t*)ZSTD_customCalloc(maxNbBuffers * sizeof(buffer_t), cMem); + bufPool->buffers = (Buffer*)ZSTD_customCalloc(maxNbBuffers * sizeof(Buffer), cMem); if (bufPool->buffers==NULL) { ZSTDMT_freeBufferPool(bufPool); return NULL; @@ -144,7 +144,7 @@ static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_cu static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool) { size_t const poolSize = sizeof(*bufPool); - size_t const arraySize = bufPool->totalBuffers * sizeof(buffer_t); + size_t const arraySize = bufPool->totalBuffers * sizeof(Buffer); unsigned u; size_t totalBufferSize = 0; ZSTD_pthread_mutex_lock(&bufPool->poolMutex); @@ -189,13 +189,13 @@ static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, * assumption : bufPool must be valid * @return : a buffer, with start pointer and size * note: allocation may fail, in this case, start==NULL and size==0 */ -static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool) +static Buffer ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool) { size_t const bSize = bufPool->bufferSize; DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize); ZSTD_pthread_mutex_lock(&bufPool->poolMutex); if (bufPool->nbBuffers) { /* try to use an existing buffer */ - buffer_t const buf = bufPool->buffers[--(bufPool->nbBuffers)]; + Buffer const buf = bufPool->buffers[--(bufPool->nbBuffers)]; size_t const availBufferSize = buf.capacity; bufPool->buffers[bufPool->nbBuffers] = g_nullBuffer; if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) { @@ -212,7 +212,7 @@ static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool) ZSTD_pthread_mutex_unlock(&bufPool->poolMutex); /* create new buffer */ DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer"); - { buffer_t buffer; + { Buffer buffer; void* const start = ZSTD_customMalloc(bSize, bufPool->cMem); buffer.start = start; /* note : start can be NULL if malloc fails ! */ buffer.capacity = (start==NULL) ? 0 : bSize; @@ -231,12 +231,12 @@ static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool) * @return : a buffer that is at least the buffer pool buffer size. * If a reallocation happens, the data in the input buffer is copied. */ -static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer) +static Buffer ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, Buffer buffer) { size_t const bSize = bufPool->bufferSize; if (buffer.capacity < bSize) { void* const start = ZSTD_customMalloc(bSize, bufPool->cMem); - buffer_t newBuffer; + Buffer newBuffer; newBuffer.start = start; newBuffer.capacity = start == NULL ? 0 : bSize; if (start != NULL) { @@ -252,7 +252,7 @@ static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer) #endif /* store buffer for later re-use, up to pool capacity */ -static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf) +static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, Buffer buf) { DEBUGLOG(5, "ZSTDMT_releaseBuffer"); if (buf.start == NULL) return; /* compatible with release on NULL */ @@ -290,7 +290,7 @@ static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool) return ZSTDMT_sizeof_bufferPool(seqPool); } -static RawSeqStore_t bufferToSeq(buffer_t buffer) +static RawSeqStore_t bufferToSeq(Buffer buffer) { RawSeqStore_t seq = kNullRawSeqStore; seq.seq = (rawSeq*)buffer.start; @@ -298,9 +298,9 @@ static RawSeqStore_t bufferToSeq(buffer_t buffer) return seq; } -static buffer_t seqToBuffer(RawSeqStore_t seq) +static Buffer seqToBuffer(RawSeqStore_t seq) { - buffer_t buffer; + Buffer buffer; buffer.start = seq.seq; buffer.capacity = seq.capacity * sizeof(rawSeq); return buffer; @@ -466,7 +466,7 @@ static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx) typedef struct { void const* start; size_t size; -} range_t; +} Range; typedef struct { /* All variables in the struct are protected by mutex. */ @@ -482,10 +482,10 @@ typedef struct { ZSTD_pthread_mutex_t ldmWindowMutex; ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is updated */ ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */ -} serialState_t; +} SerialState; static int -ZSTDMT_serialState_reset(serialState_t* serialState, +ZSTDMT_serialState_reset(SerialState* serialState, ZSTDMT_seqPool* seqPool, ZSTD_CCtx_params params, size_t jobSize, @@ -555,7 +555,7 @@ ZSTDMT_serialState_reset(serialState_t* serialState, return 0; } -static int ZSTDMT_serialState_init(serialState_t* serialState) +static int ZSTDMT_serialState_init(SerialState* serialState) { int initError = 0; ZSTD_memset(serialState, 0, sizeof(*serialState)); @@ -566,7 +566,7 @@ static int ZSTDMT_serialState_init(serialState_t* serialState) return initError; } -static void ZSTDMT_serialState_free(serialState_t* serialState) +static void ZSTDMT_serialState_free(SerialState* serialState) { ZSTD_customMem cMem = serialState->params.customMem; ZSTD_pthread_mutex_destroy(&serialState->mutex); @@ -577,9 +577,9 @@ static void ZSTDMT_serialState_free(serialState_t* serialState) ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem); } -static void ZSTDMT_serialState_update(serialState_t* serialState, +static void ZSTDMT_serialState_update(SerialState* serialState, ZSTD_CCtx* jobCCtx, RawSeqStore_t seqStore, - range_t src, unsigned jobID) + Range src, unsigned jobID) { /* Wait for our turn */ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex); @@ -623,7 +623,7 @@ static void ZSTDMT_serialState_update(serialState_t* serialState, } } -static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState, +static void ZSTDMT_serialState_ensureFinished(SerialState* serialState, unsigned jobID, size_t cSize) { ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex); @@ -647,7 +647,7 @@ static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState, /* ===== Worker thread ===== */ /* ------------------------------------------ */ -static const range_t kNullRange = { NULL, 0 }; +static const Range kNullRange = { NULL, 0 }; typedef struct { size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */ @@ -657,10 +657,10 @@ typedef struct { ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */ ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */ ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */ - serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */ - buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */ - range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */ - range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */ + SerialState* serial; /* Thread-safe - used by mtctx and (all) workers */ + Buffer dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */ + Range prefix; /* set by mtctx, then read by worker & mtctx => no barrier */ + Range src; /* set by mtctx, then read by worker & mtctx => no barrier */ unsigned jobID; /* set by mtctx, then read by worker => no barrier */ unsigned firstJob; /* set by mtctx, then read by worker => no barrier */ unsigned lastJob; /* set by mtctx, then read by worker => no barrier */ @@ -686,7 +686,7 @@ static void ZSTDMT_compressionJob(void* jobDescription) ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */ ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool); RawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool); - buffer_t dstBuff = job->dstBuff; + Buffer dstBuff = job->dstBuff; size_t lastCBlockSize = 0; /* resources */ @@ -809,10 +809,10 @@ _endJob: /* ------------------------------------------ */ typedef struct { - range_t prefix; /* read-only non-owned prefix buffer */ - buffer_t buffer; + Range prefix; /* read-only non-owned prefix buffer */ + Buffer buffer; size_t filled; -} inBuff_t; +} InBuff_t; typedef struct { BYTE* buffer; /* The round input buffer. All jobs get references @@ -826,9 +826,9 @@ typedef struct { * the inBuff is sent to the worker thread. * pos <= capacity. */ -} roundBuff_t; +} RoundBuff_t; -static const roundBuff_t kNullRoundBuff = {NULL, 0, 0}; +static const RoundBuff_t kNullRoundBuff = {NULL, 0, 0}; #define RSYNC_LENGTH 32 /* Don't create chunks smaller than the zstd block size. @@ -845,7 +845,7 @@ typedef struct { U64 hash; U64 hitMask; U64 primePower; -} rsyncState_t; +} RSyncState_t; struct ZSTDMT_CCtx_s { POOL_ctx* factory; @@ -857,10 +857,10 @@ struct ZSTDMT_CCtx_s { size_t targetSectionSize; size_t targetPrefixSize; int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */ - inBuff_t inBuff; - roundBuff_t roundBuff; - serialState_t serial; - rsyncState_t rsync; + InBuff_t inBuff; + RoundBuff_t roundBuff; + SerialState serial; + RSyncState_t rsync; unsigned jobIDMask; unsigned doneJobID; unsigned nextJobID; @@ -1538,7 +1538,7 @@ static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, u * If the data of the first job is broken up into two segments, we cover both * sections. */ -static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) +static Range ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) { unsigned const firstJobID = mtctx->doneJobID; unsigned const lastJobID = mtctx->nextJobID; @@ -1553,7 +1553,7 @@ static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex); if (consumed < mtctx->jobs[wJobID].src.size) { - range_t range = mtctx->jobs[wJobID].prefix; + Range range = mtctx->jobs[wJobID].prefix; if (range.size == 0) { /* Empty prefix */ range = mtctx->jobs[wJobID].src; @@ -1569,7 +1569,7 @@ static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) /** * Returns non-zero iff buffer and range overlap. */ -static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range) +static int ZSTDMT_isOverlapped(Buffer buffer, Range range) { BYTE const* const bufferStart = (BYTE const*)buffer.start; BYTE const* const rangeStart = (BYTE const*)range.start; @@ -1589,10 +1589,10 @@ static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range) } } -static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window) +static int ZSTDMT_doesOverlapWindow(Buffer buffer, ZSTD_window_t window) { - range_t extDict; - range_t prefix; + Range extDict; + Range prefix; DEBUGLOG(5, "ZSTDMT_doesOverlapWindow"); extDict.start = window.dictBase + window.lowLimit; @@ -1611,7 +1611,7 @@ static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window) || ZSTDMT_isOverlapped(buffer, prefix); } -static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer) +static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, Buffer buffer) { if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) { ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex; @@ -1636,10 +1636,10 @@ static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer) */ static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx) { - range_t const inUse = ZSTDMT_getInputDataInUse(mtctx); + Range const inUse = ZSTDMT_getInputDataInUse(mtctx); size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos; size_t const target = mtctx->targetSectionSize; - buffer_t buffer; + Buffer buffer; DEBUGLOG(5, "ZSTDMT_tryGetInputRange"); assert(mtctx->inBuff.buffer.start == NULL); @@ -1691,7 +1691,7 @@ static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx) typedef struct { size_t toLoad; /* The number of bytes to load from the input. */ int flush; /* Boolean declaring if we must flush because we found a synchronization point. */ -} syncPoint_t; +} SyncPoint; /** * Searches through the input for a synchronization point. If one is found, we @@ -1699,14 +1699,14 @@ typedef struct { * Otherwise, we will load as many bytes as possible and instruct the caller * to continue as normal. */ -static syncPoint_t +static SyncPoint findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input) { BYTE const* const istart = (BYTE const*)input.src + input.pos; U64 const primePower = mtctx->rsync.primePower; U64 const hitMask = mtctx->rsync.hitMask; - syncPoint_t syncPoint; + SyncPoint syncPoint; U64 hash; BYTE const* prev; size_t pos; @@ -1838,7 +1838,7 @@ size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx, DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start); } if (mtctx->inBuff.buffer.start != NULL) { - syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input); + SyncPoint const syncPoint = findSynchronizationPoint(mtctx, *input); if (syncPoint.flush && endOp == ZSTD_e_continue) { endOp = ZSTD_e_flush; } From 85a44b233accb544d89c85b804182e3f34e8d4b1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 31 Jan 2025 15:53:25 -0800 Subject: [PATCH 656/937] always free .cdictLocal --- lib/compress/zstdmt_compress.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index fe98dab1c..dbaffe536 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1258,15 +1258,14 @@ size_t ZSTDMT_initCStream_internal( mtctx->params = params; mtctx->frameContentSize = pledgedSrcSize; + ZSTD_freeCDict(mtctx->cdictLocal); if (dict) { - ZSTD_freeCDict(mtctx->cdictLocal); mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */ params.cParams, mtctx->cMem); mtctx->cdict = mtctx->cdictLocal; if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); } else { - ZSTD_freeCDict(mtctx->cdictLocal); mtctx->cdictLocal = NULL; mtctx->cdict = cdict; } @@ -1401,7 +1400,7 @@ static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZS mtctx->roundBuff.pos += srcSize; mtctx->inBuff.buffer = g_nullBuffer; mtctx->inBuff.filled = 0; - /* Set the prefix */ + /* Set the prefix for next job */ if (!endFrame) { size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize); mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize; From 220abe6da857142305ab7337b346c826856bcfd1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 31 Jan 2025 18:19:45 -0800 Subject: [PATCH 657/937] reduced memory usage by avoiding to duplicate in memory a dictionary that was passed by reference. --- lib/compress/zstd_compress.c | 12 +++++++----- lib/compress/zstd_compress_internal.h | 27 ++++++++++++++------------- lib/compress/zstd_lazy.c | 16 ++++++++-------- lib/compress/zstd_opt.c | 14 +++++++------- lib/compress/zstdmt_compress.c | 4 ++-- lib/compress/zstdmt_compress.h | 2 +- 6 files changed, 39 insertions(+), 36 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d394617bc..d7585c884 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1354,10 +1354,12 @@ size_t ZSTD_CCtx_refPrefix_advanced( RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong, "Can't ref a prefix when ctx not in init stage."); ZSTD_clearAllDicts(cctx); - if (prefix != NULL && prefixSize > 0) { + if (prefixSize > 0) { + RETURN_ERROR_IF(prefix == NULL, dictionary_wrong, "Invalid prefix pointer"); cctx->prefixDict.dict = prefix; cctx->prefixDict.dictSize = prefixSize; cctx->prefixDict.dictContentType = dictContentType; + cctx->prefixDict.loadMethod = ZSTD_dlm_byRef; } return 0; } @@ -3066,7 +3068,7 @@ ZSTD_entropyCompressSeqStore( /* ZSTD_selectBlockCompressor() : * Not static, but internal use only (used by long distance matcher) * assumption : strat is a valid strategy */ -ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode) +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_DictMode_e dictMode) { static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { { ZSTD_compressBlock_fast /* default for 0 */, @@ -3298,7 +3300,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) } /* select and store sequences */ - { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms); + { ZSTD_DictMode_e const dictMode = ZSTD_matchState_dictMode(ms); size_t lastLLSize; { int i; for (i = 0; i < ZSTD_REP_NUM; ++i) @@ -6351,7 +6353,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, size_t inSize) { ZSTD_CCtx_params params = cctx->requestedParams; - ZSTD_prefixDict const prefixDict = cctx->prefixDict; + ZSTD_PrefixDict const prefixDict = cctx->prefixDict; FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */ ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */ assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */ @@ -6407,7 +6409,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers); FORWARD_IF_ERROR( ZSTDMT_initCStream_internal( cctx->mtctx, - prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, + prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, prefixDict.loadMethod, cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , ""); cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0; cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index ca5e2a4c5..f71c47e88 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -12,8 +12,8 @@ * that shall **only** be used by modules within lib/compress. */ -#ifndef ZSTD_COMPRESS_H -#define ZSTD_COMPRESS_H +#ifndef ZSTD_COMPRESS_INTERNAL_H +#define ZSTD_COMPRESS_INTERNAL_H /*-************************************* * Dependencies @@ -21,10 +21,10 @@ #include "../common/zstd_internal.h" #include "zstd_cwksp.h" #ifdef ZSTD_MULTITHREAD -# include "zstdmt_compress.h" +# include "zstdmt_compress.h" /* ZSTDMT_CCtx */ #endif #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */ -#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */ +#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */ /*-************************************* * Constants @@ -46,11 +46,12 @@ typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e; typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage; -typedef struct ZSTD_prefixDict_s { +typedef struct { const void* dict; size_t dictSize; ZSTD_dictContentType_e dictContentType; -} ZSTD_prefixDict; + ZSTD_dictLoadMethod_e loadMethod; +} ZSTD_PrefixDict; typedef struct { void* dictBuffer; @@ -467,7 +468,7 @@ typedef struct { U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS]; ZSTD_entropyCTablesMetadata_t entropyMetadata; -} ZSTD_blockSplitCtx; +} ZSTD_BlockSplitCtx; struct ZSTD_CCtx_s { ZSTD_compressionStage_e stage; @@ -525,7 +526,7 @@ struct ZSTD_CCtx_s { /* Dictionary */ ZSTD_localDict localDict; const ZSTD_CDict* cdict; - ZSTD_prefixDict prefixDict; /* single-usage dictionary */ + ZSTD_PrefixDict prefixDict; /* single-usage dictionary */ /* Multi-threading */ #ifdef ZSTD_MULTITHREAD @@ -538,7 +539,7 @@ struct ZSTD_CCtx_s { #endif /* Workspace for block splitter */ - ZSTD_blockSplitCtx blockSplitCtx; + ZSTD_BlockSplitCtx blockSplitCtx; /* Buffer for output from external sequence producer */ ZSTD_Sequence* extSeqBuf; @@ -553,7 +554,7 @@ typedef enum { ZSTD_extDict = 1, ZSTD_dictMatchState = 2, ZSTD_dedicatedDictSearch = 3 -} ZSTD_dictMode_e; +} ZSTD_DictMode_e; typedef enum { ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict. @@ -578,7 +579,7 @@ typedef enum { typedef size_t (*ZSTD_BlockCompressor_f) ( ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_DictMode_e dictMode); MEM_STATIC U32 ZSTD_LLcode(U32 litLength) @@ -1068,7 +1069,7 @@ MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window) * Inspects the provided matchState and figures out what dictMode should be * passed to the compressor. */ -MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms) +MEM_STATIC ZSTD_DictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms) { return ZSTD_window_hasExtDict(ms->window) ? ZSTD_extDict : @@ -1633,4 +1634,4 @@ size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx, size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); -#endif /* ZSTD_COMPRESS_H */ +#endif /* ZSTD_COMPRESS_INTERNAL_H */ diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 272ebe0ec..1d5b37c20 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -74,7 +74,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_insertDUBT1(const ZSTD_MatchState_t* ms, U32 curr, const BYTE* inputEnd, U32 nbCompares, U32 btLow, - const ZSTD_dictMode_e dictMode) + const ZSTD_DictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const bt = ms->chainTable; @@ -168,7 +168,7 @@ size_t ZSTD_DUBT_findBetterDictMatch ( size_t bestLength, U32 nbCompares, U32 const mls, - const ZSTD_dictMode_e dictMode) + const ZSTD_DictMode_e dictMode) { const ZSTD_MatchState_t * const dms = ms->dictMatchState; const ZSTD_compressionParameters* const dmsCParams = &dms->cParams; @@ -244,7 +244,7 @@ size_t ZSTD_DUBT_findBestMatch(ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, size_t* offBasePtr, U32 const mls, - const ZSTD_dictMode_e dictMode) + const ZSTD_DictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const hashTable = ms->hashTable; @@ -396,7 +396,7 @@ size_t ZSTD_BtFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offBasePtr, const U32 mls /* template */, - const ZSTD_dictMode_e dictMode) + const ZSTD_DictMode_e dictMode) { DEBUGLOG(7, "ZSTD_BtFindBestMatch"); if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */ @@ -668,7 +668,7 @@ size_t ZSTD_HcFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, - const U32 mls, const ZSTD_dictMode_e dictMode) + const U32 mls, const ZSTD_DictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const chainTable = ms->chainTable; @@ -1142,7 +1142,7 @@ size_t ZSTD_RowFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, - const U32 mls, const ZSTD_dictMode_e dictMode, + const U32 mls, const ZSTD_DictMode_e dictMode, const U32 rowLog) { U32* const hashTable = ms->hashTable; @@ -1492,7 +1492,7 @@ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax( U32 const mls, U32 const rowLog, searchMethod_e const searchMethod, - ZSTD_dictMode_e const dictMode) + ZSTD_DictMode_e const dictMode) { if (dictMode == ZSTD_noDict) { ZSTD_SWITCH_SEARCH_METHOD(noDict) @@ -1518,7 +1518,7 @@ size_t ZSTD_compressBlock_lazy_generic( U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth, - ZSTD_dictMode_e const dictMode) + ZSTD_DictMode_e const dictMode) { const BYTE* const istart = (const BYTE*)src; const BYTE* ip = istart; diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 3d7171b75..09de5a9d9 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -562,7 +562,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_updateTree_internal( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, - const U32 mls, const ZSTD_dictMode_e dictMode) + const U32 mls, const ZSTD_DictMode_e dictMode) { const BYTE* const base = ms->window.base; U32 const target = (U32)(ip - base); @@ -592,7 +592,7 @@ ZSTD_insertBtAndGetAllMatches ( ZSTD_MatchState_t* ms, U32* nextToUpdate3, const BYTE* const ip, const BYTE* const iLimit, - const ZSTD_dictMode_e dictMode, + const ZSTD_DictMode_e dictMode, const U32 rep[ZSTD_REP_NUM], const U32 ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */ const U32 lengthToBeat, @@ -838,7 +838,7 @@ U32 ZSTD_btGetAllMatches_internal( const U32 rep[ZSTD_REP_NUM], U32 const ll0, U32 const lengthToBeat, - const ZSTD_dictMode_e dictMode, + const ZSTD_DictMode_e dictMode, const U32 mls) { assert(BOUNDED(3, ms->cParams.minMatch, 6) == mls); @@ -886,7 +886,7 @@ GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState) } static ZSTD_getAllMatchesFn -ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_dictMode_e const dictMode) +ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_DictMode_e const dictMode) { ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = { ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict), @@ -1079,7 +1079,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const int optLevel, - const ZSTD_dictMode_e dictMode) + const ZSTD_DictMode_e dictMode) { optState_t* const optStatePtr = &ms->opt; const BYTE* const istart = (const BYTE*)src; @@ -1445,7 +1445,7 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt0( ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) + const void* src, size_t srcSize, const ZSTD_DictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode); } @@ -1454,7 +1454,7 @@ static size_t ZSTD_compressBlock_opt0( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt2( ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) + const void* src, size_t srcSize, const ZSTD_DictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); } diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index dbaffe536..4de637513 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1232,7 +1232,7 @@ static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params) size_t ZSTDMT_initCStream_internal( ZSTDMT_CCtx* mtctx, - const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, + const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictLoadMethod_e dictLoadMethod, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize) { @@ -1261,7 +1261,7 @@ size_t ZSTDMT_initCStream_internal( ZSTD_freeCDict(mtctx->cdictLocal); if (dict) { mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, - ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */ + dictLoadMethod, dictContentType, /* note : a loadPrefix becomes an internal CDict */ params.cParams, mtctx->cMem); mtctx->cdict = mtctx->cdictLocal; if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); diff --git a/lib/compress/zstdmt_compress.h b/lib/compress/zstdmt_compress.h index 91b489b9c..2158d614f 100644 --- a/lib/compress/zstdmt_compress.h +++ b/lib/compress/zstdmt_compress.h @@ -64,7 +64,7 @@ size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx); * even if they are not needed for the current compression. * @return : 0, or an error code */ size_t ZSTDMT_initCStream_internal(ZSTDMT_CCtx* mtctx, - const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, + const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictLoadMethod_e dictLoadMethod, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize); From 7406d2b6eb91851db6a1cef10121de2a4c5a794a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 31 Jan 2025 20:57:21 -0800 Subject: [PATCH 658/937] skips the need to create a temporary cdict for --patch-from thus saving a bit of memory and a little bit of cpu time --- lib/compress/zstdmt_compress.c | 81 ++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 33 deletions(-) diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 4de637513..210ff63fa 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -650,25 +650,25 @@ static void ZSTDMT_serialState_ensureFinished(SerialState* serialState, 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 */ - 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 */ - ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */ - ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */ + 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 */ + 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 */ + ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */ + ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */ SerialState* serial; /* Thread-safe - used by mtctx and (all) workers */ Buffer dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */ Range prefix; /* set by mtctx, then read by worker & mtctx => no barrier */ Range src; /* set by mtctx, then read by worker & mtctx => no barrier */ - unsigned jobID; /* set by mtctx, then read by worker => no barrier */ - unsigned firstJob; /* set by mtctx, then read by worker => no barrier */ - unsigned lastJob; /* set by mtctx, then read by worker => no barrier */ - ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */ - const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */ - unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */ - size_t dstFlushed; /* used only by mtctx */ - unsigned frameChecksumNeeded; /* used only by mtctx */ + unsigned jobID; /* set by mtctx, then read by worker => no barrier */ + unsigned firstJob; /* set by mtctx, then read by worker => no barrier */ + unsigned lastJob; /* set by mtctx, then read by worker => no barrier */ + ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */ + const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */ + unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */ + size_t dstFlushed; /* used only by mtctx */ + unsigned frameChecksumNeeded; /* used only by mtctx */ } ZSTDMT_jobDescription; #define JOB_ERROR(e) \ @@ -714,7 +714,7 @@ static void ZSTDMT_compressionJob(void* jobDescription) size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize); assert(job->firstJob); /* only allowed for first job */ if (ZSTD_isError(initError)) JOB_ERROR(initError); - } else { /* srcStart points at reloaded section */ + } else { U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size; { size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob); if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError); @@ -741,7 +741,7 @@ static void ZSTDMT_compressionJob(void* jobDescription) ZSTD_invalidateRepCodes(cctx); } - /* compress */ + /* compress the entire job by smaller chunks, for better granularity */ { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX; int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize); const BYTE* ip = (const BYTE*) job->src.start; @@ -1258,18 +1258,6 @@ size_t ZSTDMT_initCStream_internal( mtctx->params = params; mtctx->frameContentSize = pledgedSrcSize; - ZSTD_freeCDict(mtctx->cdictLocal); - if (dict) { - mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, - dictLoadMethod, dictContentType, /* note : a loadPrefix becomes an internal CDict */ - params.cParams, mtctx->cMem); - mtctx->cdict = mtctx->cdictLocal; - if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); - } else { - mtctx->cdictLocal = NULL; - mtctx->cdict = cdict; - } - mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(¶ms); DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10)); mtctx->targetSectionSize = params.jobSize; @@ -1331,9 +1319,31 @@ size_t ZSTDMT_initCStream_internal( mtctx->allJobsCompleted = 0; mtctx->consumed = 0; mtctx->produced = 0; + + /* update dictionary */ + ZSTD_freeCDict(mtctx->cdictLocal); + mtctx->cdictLocal = NULL; + if (dict) { + if (dictContentType == ZSTD_dct_rawContent) { + mtctx->inBuff.prefix.start = (const BYTE*)dict; + mtctx->inBuff.prefix.size = dictSize; + } else { + /* note : a loadPrefix becomes an internal CDict */ + mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, + dictLoadMethod, dictContentType, + params.cParams, mtctx->cMem); + mtctx->cdict = mtctx->cdictLocal; + if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); + } + } else { + mtctx->cdict = cdict; + } + if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize, dict, dictSize, dictContentType)) return ERROR(memory_allocation); + + return 0; } @@ -1543,6 +1553,11 @@ static Range ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx) unsigned const lastJobID = mtctx->nextJobID; unsigned jobID; + /* no need to check during first round */ + size_t roundBuffCapacity = mtctx->roundBuff.capacity; + size_t nbJobs1stRoundMin = roundBuffCapacity / mtctx->targetSectionSize; + if (lastJobID < nbJobs1stRoundMin) return kNullRange; + for (jobID = firstJobID; jobID < lastJobID; ++jobID) { unsigned const wJobID = jobID & mtctx->jobIDMask; size_t consumed; @@ -1637,14 +1652,14 @@ static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx) { Range const inUse = ZSTDMT_getInputDataInUse(mtctx); size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos; - size_t const target = mtctx->targetSectionSize; + size_t const spaceNeeded = mtctx->targetSectionSize; Buffer buffer; DEBUGLOG(5, "ZSTDMT_tryGetInputRange"); assert(mtctx->inBuff.buffer.start == NULL); - assert(mtctx->roundBuff.capacity >= target); + assert(mtctx->roundBuff.capacity >= spaceNeeded); - if (spaceLeft < target) { + if (spaceLeft < spaceNeeded) { /* ZSTD_invalidateRepCodes() doesn't work for extDict variants. * Simply copy the prefix to the beginning in that case. */ @@ -1663,7 +1678,7 @@ static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx) mtctx->roundBuff.pos = prefixSize; } buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos; - buffer.capacity = target; + buffer.capacity = spaceNeeded; if (ZSTDMT_isOverlapped(buffer, inUse)) { DEBUGLOG(5, "Waiting for buffer..."); From f11bd19c7f7899840585a260688e969eb705a008 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 1 Feb 2025 00:55:52 -0800 Subject: [PATCH 659/937] ensure cdict is properly reset to NULL --- .github/workflows/dev-long-tests.yml | 4 ++-- lib/compress/zstdmt_compress.c | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 0adfed914..899a57b75 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -67,11 +67,11 @@ jobs: - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream - ubsan-zstreamtest: + uasan-zstreamtest: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: undefined behavior sanitizer zstreamtest + - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream # lasts ~15mn diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 210ff63fa..1840ad855 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1323,6 +1323,7 @@ size_t ZSTDMT_initCStream_internal( /* update dictionary */ ZSTD_freeCDict(mtctx->cdictLocal); mtctx->cdictLocal = NULL; + mtctx->cdict = NULL; if (dict) { if (dictContentType == ZSTD_dct_rawContent) { mtctx->inBuff.prefix.start = (const BYTE*)dict; From c7cd7dc04bede050475da32fa019c2d0712ed6cf Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 1 Feb 2025 00:41:36 -0800 Subject: [PATCH 660/937] better MT fluidity --patch-from no longer blocked on first job dictionary loading --- lib/compress/zstd_compress.c | 4 ++-- lib/compress/zstdmt_compress.c | 40 ++++++++++++++++++++++++---------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d7585c884..c560c902a 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -4900,7 +4900,7 @@ size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const /*! ZSTD_loadDictionaryContent() : * @return : 0, or an error code */ -static size_t +static size_t ZSTD_loadDictionaryContent(ZSTD_MatchState_t* ms, ldmState_t* ls, ZSTD_cwksp* ws, @@ -5603,7 +5603,7 @@ static size_t ZSTD_initCDict_internal( return 0; } -static ZSTD_CDict* +static ZSTD_CDict* ZSTD_createCDict_advanced_internal(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_compressionParameters cParams, diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 1840ad855..8725b9071 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -577,9 +577,10 @@ static void ZSTDMT_serialState_free(SerialState* serialState) ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem); } -static void ZSTDMT_serialState_update(SerialState* serialState, - ZSTD_CCtx* jobCCtx, RawSeqStore_t seqStore, - Range src, unsigned jobID) +static void +ZSTDMT_serialState_genSequences(SerialState* serialState, + RawSeqStore_t* seqStore, + Range src, unsigned jobID) { /* Wait for our turn */ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex); @@ -592,12 +593,13 @@ static void ZSTDMT_serialState_update(SerialState* serialState, /* It is now our turn, do any processing necessary */ if (serialState->params.ldmParams.enableLdm == ZSTD_ps_enable) { size_t error; - assert(seqStore.seq != NULL && seqStore.pos == 0 && - seqStore.size == 0 && seqStore.capacity > 0); + DEBUGLOG(6, "ZSTDMT_serialState_genSequences: LDM update"); + assert(seqStore->seq != NULL && seqStore->pos == 0 && + seqStore->size == 0 && seqStore->capacity > 0); assert(src.size <= serialState->params.jobSize); ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0); error = ZSTD_ldm_generateSequences( - &serialState->ldmState, &seqStore, + &serialState->ldmState, seqStore, &serialState->params.ldmParams, src.start, src.size); /* We provide a large enough buffer to never fail. */ assert(!ZSTD_isError(error)); (void)error; @@ -616,10 +618,18 @@ static void ZSTDMT_serialState_update(SerialState* serialState, serialState->nextJobID++; ZSTD_pthread_cond_broadcast(&serialState->cond); ZSTD_pthread_mutex_unlock(&serialState->mutex); +} - if (seqStore.size > 0) { - ZSTD_referenceExternalSequences(jobCCtx, seqStore.seq, seqStore.size); - assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable); +static void +ZSTDMT_serialState_applySequences(const SerialState* serialState, /* just for an assert() check */ + ZSTD_CCtx* jobCCtx, + const RawSeqStore_t* seqStore) +{ + if (seqStore->size > 0) { + DEBUGLOG(5, "ZSTDMT_serialState_applySequences: uploading %u external sequences", (unsigned)seqStore->size); + assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable); (void)serialState; + assert(jobCCtx); + ZSTD_referenceExternalSequences(jobCCtx, seqStore->seq, seqStore->size); } } @@ -689,6 +699,7 @@ static void ZSTDMT_compressionJob(void* jobDescription) Buffer dstBuff = job->dstBuff; size_t lastCBlockSize = 0; + DEBUGLOG(5, "ZSTDMT_compressionJob: job %u", job->jobID); /* resources */ if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation)); if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */ @@ -710,6 +721,10 @@ static void ZSTDMT_compressionJob(void* jobDescription) /* init */ + + /* Perform serial step as early as possible */ + ZSTDMT_serialState_genSequences(job->serial, &rawSeqStore, job->src, job->jobID); + if (job->cdict) { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize); assert(job->firstJob); /* only allowed for first job */ @@ -723,16 +738,17 @@ static void ZSTDMT_compressionJob(void* jobDescription) size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0); if (ZSTD_isError(err)) JOB_ERROR(err); } + DEBUGLOG(6, "ZSTDMT_compressionJob: job %u: loading prefix of size %zu", job->jobID, job->prefix.size); { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, - job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */ + job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, ZSTD_dtlm_fast, NULL, /*cdict*/ &jobParams, pledgedSrcSize); if (ZSTD_isError(initError)) JOB_ERROR(initError); } } - /* Perform serial step as early as possible, but after CCtx initialization */ - ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID); + /* External Sequences can only be applied after CCtx initialization */ + ZSTDMT_serialState_applySequences(job->serial, cctx, &rawSeqStore); if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */ size_t const hSize = ZSTD_compressContinue_public(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0); From 23e5f80390db9a3a65485933d255e163d2dab519 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 5 Feb 2025 18:47:26 -0800 Subject: [PATCH 661/937] Revert "pass dictionary loading method as parameter" This reverts commit 821fc567f93a415e9fbe856271ccd452ee7acf07. --- lib/compress/zstd_compress.c | 12 +++++------- lib/compress/zstd_compress_internal.h | 27 +++++++++++++-------------- lib/compress/zstd_lazy.c | 16 ++++++++-------- lib/compress/zstd_opt.c | 14 +++++++------- lib/compress/zstdmt_compress.c | 16 ++++++++++++++-- lib/compress/zstdmt_compress.h | 2 +- 6 files changed, 48 insertions(+), 39 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c560c902a..d928b1d3e 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1354,12 +1354,10 @@ size_t ZSTD_CCtx_refPrefix_advanced( RETURN_ERROR_IF(cctx->streamStage != zcss_init, stage_wrong, "Can't ref a prefix when ctx not in init stage."); ZSTD_clearAllDicts(cctx); - if (prefixSize > 0) { - RETURN_ERROR_IF(prefix == NULL, dictionary_wrong, "Invalid prefix pointer"); + if (prefix != NULL && prefixSize > 0) { cctx->prefixDict.dict = prefix; cctx->prefixDict.dictSize = prefixSize; cctx->prefixDict.dictContentType = dictContentType; - cctx->prefixDict.loadMethod = ZSTD_dlm_byRef; } return 0; } @@ -3068,7 +3066,7 @@ ZSTD_entropyCompressSeqStore( /* ZSTD_selectBlockCompressor() : * Not static, but internal use only (used by long distance matcher) * assumption : strat is a valid strategy */ -ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_DictMode_e dictMode) +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e useRowMatchFinder, ZSTD_dictMode_e dictMode) { static const ZSTD_BlockCompressor_f blockCompressor[4][ZSTD_STRATEGY_MAX+1] = { { ZSTD_compressBlock_fast /* default for 0 */, @@ -3300,7 +3298,7 @@ static size_t ZSTD_buildSeqStore(ZSTD_CCtx* zc, const void* src, size_t srcSize) } /* select and store sequences */ - { ZSTD_DictMode_e const dictMode = ZSTD_matchState_dictMode(ms); + { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms); size_t lastLLSize; { int i; for (i = 0; i < ZSTD_REP_NUM; ++i) @@ -6353,7 +6351,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, size_t inSize) { ZSTD_CCtx_params params = cctx->requestedParams; - ZSTD_PrefixDict const prefixDict = cctx->prefixDict; + ZSTD_prefixDict const prefixDict = cctx->prefixDict; FORWARD_IF_ERROR( ZSTD_initLocalDict(cctx) , ""); /* Init the local dict if present. */ ZSTD_memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */ assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */ @@ -6409,7 +6407,7 @@ static size_t ZSTD_CCtx_init_compressStream2(ZSTD_CCtx* cctx, DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers); FORWARD_IF_ERROR( ZSTDMT_initCStream_internal( cctx->mtctx, - prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, prefixDict.loadMethod, + prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType, cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) , ""); cctx->dictID = cctx->cdict ? cctx->cdict->dictID : 0; cctx->dictContentSize = cctx->cdict ? cctx->cdict->dictContentSize : prefixDict.dictSize; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index f71c47e88..ca5e2a4c5 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -12,8 +12,8 @@ * that shall **only** be used by modules within lib/compress. */ -#ifndef ZSTD_COMPRESS_INTERNAL_H -#define ZSTD_COMPRESS_INTERNAL_H +#ifndef ZSTD_COMPRESS_H +#define ZSTD_COMPRESS_H /*-************************************* * Dependencies @@ -21,10 +21,10 @@ #include "../common/zstd_internal.h" #include "zstd_cwksp.h" #ifdef ZSTD_MULTITHREAD -# include "zstdmt_compress.h" /* ZSTDMT_CCtx */ +# include "zstdmt_compress.h" #endif #include "../common/bits.h" /* ZSTD_highbit32, ZSTD_NbCommonBytes */ -#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */ +#include "zstd_preSplit.h" /* ZSTD_SLIPBLOCK_WORKSPACESIZE */ /*-************************************* * Constants @@ -46,12 +46,11 @@ typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e; typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage; -typedef struct { +typedef struct ZSTD_prefixDict_s { const void* dict; size_t dictSize; ZSTD_dictContentType_e dictContentType; - ZSTD_dictLoadMethod_e loadMethod; -} ZSTD_PrefixDict; +} ZSTD_prefixDict; typedef struct { void* dictBuffer; @@ -468,7 +467,7 @@ typedef struct { U32 partitions[ZSTD_MAX_NB_BLOCK_SPLITS]; ZSTD_entropyCTablesMetadata_t entropyMetadata; -} ZSTD_BlockSplitCtx; +} ZSTD_blockSplitCtx; struct ZSTD_CCtx_s { ZSTD_compressionStage_e stage; @@ -526,7 +525,7 @@ struct ZSTD_CCtx_s { /* Dictionary */ ZSTD_localDict localDict; const ZSTD_CDict* cdict; - ZSTD_PrefixDict prefixDict; /* single-usage dictionary */ + ZSTD_prefixDict prefixDict; /* single-usage dictionary */ /* Multi-threading */ #ifdef ZSTD_MULTITHREAD @@ -539,7 +538,7 @@ struct ZSTD_CCtx_s { #endif /* Workspace for block splitter */ - ZSTD_BlockSplitCtx blockSplitCtx; + ZSTD_blockSplitCtx blockSplitCtx; /* Buffer for output from external sequence producer */ ZSTD_Sequence* extSeqBuf; @@ -554,7 +553,7 @@ typedef enum { ZSTD_extDict = 1, ZSTD_dictMatchState = 2, ZSTD_dedicatedDictSearch = 3 -} ZSTD_DictMode_e; +} ZSTD_dictMode_e; typedef enum { ZSTD_cpm_noAttachDict = 0, /* Compression with ZSTD_noDict or ZSTD_extDict. @@ -579,7 +578,7 @@ typedef enum { typedef size_t (*ZSTD_BlockCompressor_f) ( ZSTD_MatchState_t* bs, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], void const* src, size_t srcSize); -ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_DictMode_e dictMode); +ZSTD_BlockCompressor_f ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_ParamSwitch_e rowMatchfinderMode, ZSTD_dictMode_e dictMode); MEM_STATIC U32 ZSTD_LLcode(U32 litLength) @@ -1069,7 +1068,7 @@ MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window) * Inspects the provided matchState and figures out what dictMode should be * passed to the compressor. */ -MEM_STATIC ZSTD_DictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms) +MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_MatchState_t *ms) { return ZSTD_window_hasExtDict(ms->window) ? ZSTD_extDict : @@ -1634,4 +1633,4 @@ size_t ZSTD_compressEnd_public(ZSTD_CCtx* cctx, size_t ZSTD_compressBlock_deprecated(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize); -#endif /* ZSTD_COMPRESS_INTERNAL_H */ +#endif /* ZSTD_COMPRESS_H */ diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 1d5b37c20..272ebe0ec 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -74,7 +74,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_insertDUBT1(const ZSTD_MatchState_t* ms, U32 curr, const BYTE* inputEnd, U32 nbCompares, U32 btLow, - const ZSTD_DictMode_e dictMode) + const ZSTD_dictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const bt = ms->chainTable; @@ -168,7 +168,7 @@ size_t ZSTD_DUBT_findBetterDictMatch ( size_t bestLength, U32 nbCompares, U32 const mls, - const ZSTD_DictMode_e dictMode) + const ZSTD_dictMode_e dictMode) { const ZSTD_MatchState_t * const dms = ms->dictMatchState; const ZSTD_compressionParameters* const dmsCParams = &dms->cParams; @@ -244,7 +244,7 @@ size_t ZSTD_DUBT_findBestMatch(ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, size_t* offBasePtr, U32 const mls, - const ZSTD_DictMode_e dictMode) + const ZSTD_dictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const hashTable = ms->hashTable; @@ -396,7 +396,7 @@ size_t ZSTD_BtFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offBasePtr, const U32 mls /* template */, - const ZSTD_DictMode_e dictMode) + const ZSTD_dictMode_e dictMode) { DEBUGLOG(7, "ZSTD_BtFindBestMatch"); if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */ @@ -668,7 +668,7 @@ size_t ZSTD_HcFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, - const U32 mls, const ZSTD_DictMode_e dictMode) + const U32 mls, const ZSTD_dictMode_e dictMode) { const ZSTD_compressionParameters* const cParams = &ms->cParams; U32* const chainTable = ms->chainTable; @@ -1142,7 +1142,7 @@ size_t ZSTD_RowFindBestMatch( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iLimit, size_t* offsetPtr, - const U32 mls, const ZSTD_DictMode_e dictMode, + const U32 mls, const ZSTD_dictMode_e dictMode, const U32 rowLog) { U32* const hashTable = ms->hashTable; @@ -1492,7 +1492,7 @@ FORCE_INLINE_TEMPLATE size_t ZSTD_searchMax( U32 const mls, U32 const rowLog, searchMethod_e const searchMethod, - ZSTD_DictMode_e const dictMode) + ZSTD_dictMode_e const dictMode) { if (dictMode == ZSTD_noDict) { ZSTD_SWITCH_SEARCH_METHOD(noDict) @@ -1518,7 +1518,7 @@ size_t ZSTD_compressBlock_lazy_generic( U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const searchMethod_e searchMethod, const U32 depth, - ZSTD_DictMode_e const dictMode) + ZSTD_dictMode_e const dictMode) { const BYTE* const istart = (const BYTE*)src; const BYTE* ip = istart; diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 09de5a9d9..3d7171b75 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -562,7 +562,7 @@ ZSTD_ALLOW_POINTER_OVERFLOW_ATTR void ZSTD_updateTree_internal( ZSTD_MatchState_t* ms, const BYTE* const ip, const BYTE* const iend, - const U32 mls, const ZSTD_DictMode_e dictMode) + const U32 mls, const ZSTD_dictMode_e dictMode) { const BYTE* const base = ms->window.base; U32 const target = (U32)(ip - base); @@ -592,7 +592,7 @@ ZSTD_insertBtAndGetAllMatches ( ZSTD_MatchState_t* ms, U32* nextToUpdate3, const BYTE* const ip, const BYTE* const iLimit, - const ZSTD_DictMode_e dictMode, + const ZSTD_dictMode_e dictMode, const U32 rep[ZSTD_REP_NUM], const U32 ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */ const U32 lengthToBeat, @@ -838,7 +838,7 @@ U32 ZSTD_btGetAllMatches_internal( const U32 rep[ZSTD_REP_NUM], U32 const ll0, U32 const lengthToBeat, - const ZSTD_DictMode_e dictMode, + const ZSTD_dictMode_e dictMode, const U32 mls) { assert(BOUNDED(3, ms->cParams.minMatch, 6) == mls); @@ -886,7 +886,7 @@ GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState) } static ZSTD_getAllMatchesFn -ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_DictMode_e const dictMode) +ZSTD_selectBtGetAllMatches(ZSTD_MatchState_t const* ms, ZSTD_dictMode_e const dictMode) { ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = { ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict), @@ -1079,7 +1079,7 @@ ZSTD_compressBlock_opt_generic(ZSTD_MatchState_t* ms, U32 rep[ZSTD_REP_NUM], const void* src, size_t srcSize, const int optLevel, - const ZSTD_DictMode_e dictMode) + const ZSTD_dictMode_e dictMode) { optState_t* const optStatePtr = &ms->opt; const BYTE* const istart = (const BYTE*)src; @@ -1445,7 +1445,7 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ #ifndef ZSTD_EXCLUDE_BTOPT_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt0( ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - const void* src, size_t srcSize, const ZSTD_DictMode_e dictMode) + const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode); } @@ -1454,7 +1454,7 @@ static size_t ZSTD_compressBlock_opt0( #ifndef ZSTD_EXCLUDE_BTULTRA_BLOCK_COMPRESSOR static size_t ZSTD_compressBlock_opt2( ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM], - const void* src, size_t srcSize, const ZSTD_DictMode_e dictMode) + const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode) { return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode); } diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 8725b9071..0f1fe6d74 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1248,7 +1248,7 @@ static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params) size_t ZSTDMT_initCStream_internal( ZSTDMT_CCtx* mtctx, - const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictLoadMethod_e dictLoadMethod, + const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize) { @@ -1274,6 +1274,18 @@ size_t ZSTDMT_initCStream_internal( mtctx->params = params; mtctx->frameContentSize = pledgedSrcSize; + ZSTD_freeCDict(mtctx->cdictLocal); + if (dict) { + mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, + ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */ + params.cParams, mtctx->cMem); + mtctx->cdict = mtctx->cdictLocal; + if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); + } else { + mtctx->cdictLocal = NULL; + mtctx->cdict = cdict; + } + mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(¶ms); DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10)); mtctx->targetSectionSize = params.jobSize; @@ -1347,7 +1359,7 @@ size_t ZSTDMT_initCStream_internal( } else { /* note : a loadPrefix becomes an internal CDict */ mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, - dictLoadMethod, dictContentType, + ZSTD_dlm_byRef, dictContentType, params.cParams, mtctx->cMem); mtctx->cdict = mtctx->cdictLocal; if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation); diff --git a/lib/compress/zstdmt_compress.h b/lib/compress/zstdmt_compress.h index 2158d614f..91b489b9c 100644 --- a/lib/compress/zstdmt_compress.h +++ b/lib/compress/zstdmt_compress.h @@ -64,7 +64,7 @@ size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx); * even if they are not needed for the current compression. * @return : 0, or an error code */ size_t ZSTDMT_initCStream_internal(ZSTDMT_CCtx* mtctx, - const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, ZSTD_dictLoadMethod_e dictLoadMethod, + const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType, const ZSTD_CDict* cdict, ZSTD_CCtx_params params, unsigned long long pledgedSrcSize); From aebffd66ec43a721b9d07e67e18f353bf2082430 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 8 Feb 2025 22:47:05 -0800 Subject: [PATCH 662/937] --ultra automatically triggered with --long and --patch-from the purpose of --ultra is to make the user explicitly opt-in to generate very large window size (> 8 MB). The agreement to generate very large window size is already implicit when selecting --long or --patch-from. Consequently, `--ultra ` is automatically enabled when `--long` or `--patch-from` is set. --- programs/zstdcli.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 7d00a94b2..8569896c0 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1082,10 +1082,11 @@ int main(int argCount, const char* argv[]) #ifndef ZSTD_NOTRACE if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; } #endif - if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); continue; } + if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); ultra = 1; continue; } if (longCommandWArg(&argument, "--long")) { unsigned ldmWindowLog = 0; ldmFlag = 1; + ultra = 1; /* Parse optional window log */ if (*argument == '=') { ++argument; From 630b47a158cc22002045494c7e0dc0f0672c2fca Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 11:38:44 -0800 Subject: [PATCH 663/937] added a new --max command set parameters to maximum compression (even more than -22) --- programs/zstdcli.c | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 7d00a94b2..0bb384b20 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -639,6 +639,22 @@ static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressi return 1; } +static void setMaxCompression(ZSTD_compressionParameters* params) +{ + params->windowLog = ZSTD_WINDOWLOG_MAX; + params->chainLog = ZSTD_CHAINLOG_MAX; + params->hashLog = ZSTD_HASHLOG_MAX; + params->searchLog = ZSTD_SEARCHLOG_MAX; + params->minMatch = ZSTD_MINMATCH_MIN; + params->targetLength = ZSTD_TARGETLENGTH_MAX; + params->strategy = ZSTD_STRATEGY_MAX; + g_overlapLog = ZSTD_OVERLAPLOG_MAX; + g_ldmHashLog = ZSTD_LDM_HASHLOG_MAX; + g_ldmHashRateLog = 0; /* automatically derived */ + g_ldmMinMatch = 32; /* heuristic */ + g_ldmBucketSizeLog = ZSTD_LDM_BUCKETSIZELOG_MAX; +} + static void printVersion(void) { if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) { @@ -957,6 +973,7 @@ int main(int argCount, const char* argv[]) if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; } if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; } if (!strcmp(argument, "--ultra")) { ultra=1; continue; } + if (!strcmp(argument, "--max")) { ultra=1; ldmFlag = 1; setMaxCompression(&compressionParams); continue; } if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; } if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; } if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; } From 8ae1330708b42c7f5751e94e02970e7ccb5d9731 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 11:51:25 -0800 Subject: [PATCH 664/937] add man entry for --max --- programs/zstd.1.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index b4e848640..184db049f 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -161,6 +161,9 @@ the last one takes effect. Note: If `windowLog` is set to larger than 27, `--long=windowLog` or `--memory=windowSize` needs to be passed to the decompressor. +* `--max`: + set advanced parameters to maximum compression. + warning: this setting uses a lot of resources and is very slow. * `-D DICT`: use `DICT` as Dictionary to compress or decompress FILE(s) * `--patch-from FILE`: From 41b719375778ca92978f406b44bdea06cffbf108 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 12:26:36 -0800 Subject: [PATCH 665/937] added --max to test suite --- tests/cli-tests/compression/levels.sh | 4 +++- tests/cli-tests/compression/levels.sh.stderr.exact | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/cli-tests/compression/levels.sh b/tests/cli-tests/compression/levels.sh index cc2700a30..db3baba6d 100755 --- a/tests/cli-tests/compression/levels.sh +++ b/tests/cli-tests/compression/levels.sh @@ -10,9 +10,11 @@ zstd --fast=10 file -o file-f10.zst -q zstd --fast=1 file -o file-f1.zst -q zstd -1 file -o file-1.zst -q zstd -19 file -o file-19.zst -q +zstd --max file -o file-max.zst -q -zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst +zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst file-max.zst +cmp_size -le file-max.zst file-19.zst cmp_size -lt file-19.zst file-1.zst cmp_size -lt file-1.zst file-f1.zst cmp_size -lt file-f1.zst file-f10.zst diff --git a/tests/cli-tests/compression/levels.sh.stderr.exact b/tests/cli-tests/compression/levels.sh.stderr.exact index c8fb79c68..ddec06467 100644 --- a/tests/cli-tests/compression/levels.sh.stderr.exact +++ b/tests/cli-tests/compression/levels.sh.stderr.exact @@ -6,10 +6,12 @@ zstd --fast=10 file -o file-f10.zst -q zstd --fast=1 file -o file-f1.zst -q zstd -1 file -o file-1.zst -q zstd -19 file -o file-19.zst -q +zstd --max file -o file-max.zst -q -zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst -4 files decompressed : 262148 bytes total +zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst file-max.zst +5 files decompressed : 327685 bytes total +cmp_size -le file-max.zst file-19.zst cmp_size -lt file-19.zst file-1.zst cmp_size -lt file-1.zst file-f1.zst cmp_size -lt file-f1.zst file-f10.zst From 39d1d82fa80bfbec6d894ccf8bf18137cedad5d6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 17:24:12 -0800 Subject: [PATCH 666/937] adjusted mml heuristic --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 0bb384b20..b69d6bf99 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -651,7 +651,7 @@ static void setMaxCompression(ZSTD_compressionParameters* params) g_overlapLog = ZSTD_OVERLAPLOG_MAX; g_ldmHashLog = ZSTD_LDM_HASHLOG_MAX; g_ldmHashRateLog = 0; /* automatically derived */ - g_ldmMinMatch = 32; /* heuristic */ + g_ldmMinMatch = 16; /* heuristic */ g_ldmBucketSizeLog = ZSTD_LDM_BUCKETSIZELOG_MAX; } From f86024ccd2b2fc4608be336594e073096405ac13 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 17:25:35 -0800 Subject: [PATCH 667/937] reinforce man page warning 32-bit is unsuitable for --max --- programs/zstd.1.md | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 184db049f..f56110100 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -164,6 +164,7 @@ the last one takes effect. * `--max`: set advanced parameters to maximum compression. warning: this setting uses a lot of resources and is very slow. + note that the amount of resource required is typically too large for 32-bit. * `-D DICT`: use `DICT` as Dictionary to compress or decompress FILE(s) * `--patch-from FILE`: From 7a2fce5a1fabcd28cc8c8ea5ef039dab32b24f0b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Feb 2025 05:36:44 +0000 Subject: [PATCH 668/937] Bump github/codeql-action from 3.28.1 to 3.28.9 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.1 to 3.28.9. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/b6a472f63d85b9c78a3ac5e89422239fc15e9b3c...9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index c489ddc91..e532b03bf 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # tag=v3.28.1 + uses: github/codeql-action/upload-sarif@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # tag=v3.28.9 with: sarif_file: results.sarif From 1603cbe83ef7140f0cd0412bea50e5bfc9dd6d1c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 23:02:14 -0800 Subject: [PATCH 669/937] update test for 32-bit mode --max doesn't work in 32-bit mode, due to address space limitation --- tests/cli-tests/compression/levels.sh | 10 +++++++++- tests/cli-tests/compression/levels.sh.stderr.exact | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tests/cli-tests/compression/levels.sh b/tests/cli-tests/compression/levels.sh index db3baba6d..8da3b4e74 100755 --- a/tests/cli-tests/compression/levels.sh +++ b/tests/cli-tests/compression/levels.sh @@ -5,12 +5,20 @@ set -v datagen > file +# Retrieve the program's version information +version_info=$(zstd -V) + # Compress with various levels and ensure that their sizes are ordered zstd --fast=10 file -o file-f10.zst -q zstd --fast=1 file -o file-f1.zst -q zstd -1 file -o file-1.zst -q zstd -19 file -o file-19.zst -q -zstd --max file -o file-max.zst -q +if echo "$version_info" | grep -q '32-bit'; then + # skip --max test: not enough address space + cp file-19.zst file-max.zst +else + zstd --max file -o file-max.zst -q +fi zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst file-max.zst diff --git a/tests/cli-tests/compression/levels.sh.stderr.exact b/tests/cli-tests/compression/levels.sh.stderr.exact index ddec06467..dff9784dd 100644 --- a/tests/cli-tests/compression/levels.sh.stderr.exact +++ b/tests/cli-tests/compression/levels.sh.stderr.exact @@ -1,12 +1,20 @@ datagen > file +# Retrieve the program's version information +version_info=$(zstd -V) + # Compress with various levels and ensure that their sizes are ordered zstd --fast=10 file -o file-f10.zst -q zstd --fast=1 file -o file-f1.zst -q zstd -1 file -o file-1.zst -q zstd -19 file -o file-19.zst -q -zstd --max file -o file-max.zst -q +if echo "$version_info" | grep -q '32-bit'; then + # skip --max test: not enough address space + cp file-19.zst file-max.zst +else + zstd --max file -o file-max.zst -q +fi zstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst file-max.zst 5 files decompressed : 327685 bytes total From 468e1453a55d119c914843bff73af809cbe4ba79 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 23:14:16 -0800 Subject: [PATCH 670/937] disable --max in 32-bit mode --- programs/zstd.1.md | 4 ++-- programs/zstdcli.c | 31 ++++++++++++++++++++----------- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index f56110100..29b7a5bb7 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -163,8 +163,8 @@ the last one takes effect. `--memory=windowSize` needs to be passed to the decompressor. * `--max`: set advanced parameters to maximum compression. - warning: this setting uses a lot of resources and is very slow. - note that the amount of resource required is typically too large for 32-bit. + warning: this setting is very slow and uses a lot of resources. + It's inappropriate for 32-bit mode and therefore disabled in this mode. * `-D DICT`: use `DICT` as Dictionary to compress or decompress FILE(s) * `--patch-from FILE`: diff --git a/programs/zstdcli.c b/programs/zstdcli.c index b69d6bf99..feab4f944 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -810,22 +810,22 @@ static unsigned default_nbThreads(void) { CLEAN_RETURN(1); \ } } } -#define NEXT_UINT32(val32) { \ - const char* __nb; \ - NEXT_FIELD(__nb); \ +#define NEXT_UINT32(val32) { \ + const char* __nb; \ + NEXT_FIELD(__nb); \ val32 = readU32FromChar(&__nb); \ - if(*__nb != 0) { \ + if(*__nb != 0) { \ errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ - } \ + } \ } -#define NEXT_TSIZE(valTsize) { \ - const char* __nb; \ - NEXT_FIELD(__nb); \ +#define NEXT_TSIZE(valTsize) { \ + const char* __nb; \ + NEXT_FIELD(__nb); \ valTsize = readSizeTFromChar(&__nb); \ - if(*__nb != 0) { \ + if(*__nb != 0) { \ errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ - } \ + } \ } typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode; @@ -973,7 +973,6 @@ int main(int argCount, const char* argv[]) if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; } if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; } if (!strcmp(argument, "--ultra")) { ultra=1; continue; } - if (!strcmp(argument, "--max")) { ultra=1; ldmFlag = 1; setMaxCompression(&compressionParams); continue; } if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; } if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; } if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; } @@ -1024,6 +1023,16 @@ int main(int argCount, const char* argv[]) if (!strcmp(argument, "--fake-stderr-is-console")) { UTIL_fakeStderrIsConsole(); continue; } if (!strcmp(argument, "--trace-file-stat")) { UTIL_traceFileStat(); continue; } + if (!strcmp(argument, "--max")) { + if (sizeof(void*)==4) { + DISPLAYLEVEL(2, "--max is incompatible with 32-bit mode \n"); + badUsage(programName, originalArgument); + CLEAN_RETURN(1); + } + ultra=1; ldmFlag = 1; setMaxCompression(&compressionParams); + continue; + } + /* long commands with arguments */ #ifndef ZSTD_NODICT if (longCommandWArg(&argument, "--train-cover")) { From 613901b6d3ea198ac051f63e16c6ea9cd088a6e4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 23:41:32 -0800 Subject: [PATCH 671/937] modifies command echoing for macos / linux compatibility --- tests/cli-tests/compression/levels.sh | 3 +++ tests/cli-tests/compression/levels.sh.stderr.exact | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/cli-tests/compression/levels.sh b/tests/cli-tests/compression/levels.sh index 8da3b4e74..b8230f2a3 100755 --- a/tests/cli-tests/compression/levels.sh +++ b/tests/cli-tests/compression/levels.sh @@ -6,7 +6,10 @@ set -v datagen > file # Retrieve the program's version information +# Note: command echoing differs between macos and linux, so it's disabled below +set +v version_info=$(zstd -V) +set -v # Compress with various levels and ensure that their sizes are ordered zstd --fast=10 file -o file-f10.zst -q diff --git a/tests/cli-tests/compression/levels.sh.stderr.exact b/tests/cli-tests/compression/levels.sh.stderr.exact index dff9784dd..fd7c076d2 100644 --- a/tests/cli-tests/compression/levels.sh.stderr.exact +++ b/tests/cli-tests/compression/levels.sh.stderr.exact @@ -2,7 +2,8 @@ datagen > file # Retrieve the program's version information -version_info=$(zstd -V) +# Note: command echoing differs between macos and linux, so it's disabled below +set +v # Compress with various levels and ensure that their sizes are ordered zstd --fast=10 file -o file-f10.zst -q From 4609a40b89b94cc61cc6a6a833725d6f89bf9de6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 15:58:42 -0800 Subject: [PATCH 672/937] dynamically adjust hratelog and ldmml based on strategy --- lib/compress/zstd_ldm.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 42b38c0d0..6f866ea16 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -139,15 +139,19 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX); DEBUGLOG(4, "ZSTD_ldm_adjustParameters"); if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG; - if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH; + if (params->hashRateLog == 0) { + assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); + /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ + params->hashRateLog = 9 - ((cParams->strategy+1)/2); + } if (params->hashLog == 0) { - params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG); + params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog); assert(params->hashLog <= ZSTD_HASHLOG_MAX); } - if (params->hashRateLog == 0) { - params->hashRateLog = params->windowLog < params->hashLog - ? 0 - : params->windowLog - params->hashLog; + if (params->minMatchLength == 0) { + params->minMatchLength = (params->hashRateLog < 6) ? + LDM_MIN_MATCH_LENGTH : + LDM_MIN_MATCH_LENGTH * 2; } params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog); } From f26cc54f37c614d3351b6873f0ee6e3fff00f6f6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 16:59:34 -0800 Subject: [PATCH 673/937] dynamic bucket sizes --- lib/compress/zstd_ldm.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 6f866ea16..39f23c565 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -16,7 +16,7 @@ #include "zstd_double_fast.h" /* ZSTD_fillDoubleHashTable() */ #include "zstd_ldm_geartab.h" -#define LDM_BUCKET_SIZE_LOG 3 +#define LDM_BUCKET_SIZE_LOG 4 #define LDM_MIN_MATCH_LENGTH 64 #define LDM_HASH_RLOG 7 @@ -138,7 +138,6 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, params->windowLog = cParams->windowLog; ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX); DEBUGLOG(4, "ZSTD_ldm_adjustParameters"); - if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG; if (params->hashRateLog == 0) { assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ @@ -152,6 +151,15 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, params->minMatchLength = (params->hashRateLog < 6) ? LDM_MIN_MATCH_LENGTH : LDM_MIN_MATCH_LENGTH * 2; + if (cParams->strategy >= ZSTD_btultra2) + params->minMatchLength /= 2; + } + if (params->bucketSizeLog==0) { + params->bucketSizeLog = LDM_BUCKET_SIZE_LOG; + if (cParams->strategy > ZSTD_lazy) { + params->bucketSizeLog += (U32)cParams->strategy - (U32)ZSTD_lazy; + } + params->bucketSizeLog = MIN(params->bucketSizeLog, ZSTD_LDM_BUCKETSIZELOG_MAX); } params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog); } From bf218c142aade4aa842205e93bc8260dcbfb372d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 17:15:24 -0800 Subject: [PATCH 674/937] updated LDM documentation --- programs/fileio.c | 11 ++++++----- programs/zstd.1.md | 27 ++++++++++++++------------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 1b8aa8a99..0ecca40d2 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -1100,11 +1100,12 @@ static void FIO_adjustParamsForPatchFromMode(FIO_prefs_t* const prefs, FIO_setLdmFlag(prefs, 1); } if (cParams.strategy >= ZSTD_btopt) { - DISPLAYLEVEL(3, "[Optimal parser notes] Consider the following to improve patch size at the cost of speed:\n"); - DISPLAYLEVEL(3, "- Use --single-thread mode in the zstd cli\n"); - DISPLAYLEVEL(3, "- Set a larger targetLength (e.g. --zstd=targetLength=4096)\n"); - DISPLAYLEVEL(3, "- Set a larger chainLog (e.g. --zstd=chainLog=%u)\n", ZSTD_CHAINLOG_MAX); - DISPLAYLEVEL(3, "Also consider playing around with searchLog and hashLog\n"); + DISPLAYLEVEL(4, "[Optimal parser notes] Consider the following to improve patch size at the cost of speed:\n"); + DISPLAYLEVEL(4, "- Set a larger targetLength (e.g. --zstd=targetLength=4096)\n"); + DISPLAYLEVEL(4, "- Set a larger chainLog (e.g. --zstd=chainLog=%u)\n", ZSTD_CHAINLOG_MAX); + DISPLAYLEVEL(4, "- Set a larger LDM hashLog (e.g. --zstd=ldmHashLog=%u)\n", ZSTD_LDM_HASHLOG_MAX); + DISPLAYLEVEL(4, "- Set a smaller LDM rateLog (e.g. --zstd=ldmHashRateLog=%u)\n", ZSTD_LDM_HASHRATELOG_MIN); + DISPLAYLEVEL(4, "Also consider playing around with searchLog and hashLog\n"); } } diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 29b7a5bb7..be2179e5d 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -455,6 +455,17 @@ The list of available _options_: Value 0 is special and means "default": _ovlog_ is automatically determined by `zstd`. In which case, _ovlog_ will range from 6 to 9, depending on selected _strat_. +- `ldmHashRateLog`=_lhrlog_, `lhrlog`=_lhrlog_: + Specify the frequency of inserting entries into the long distance matching + hash table. + + This option is ignored unless long distance matching is enabled. + + Larger values will improve compression speed. Deviating far from the + default value will likely result in a decrease in compression ratio. + + The default value varies between 4 and 8, depending on `strategy`. + - `ldmHashLog`=_lhlog_, `lhlog`=_lhlog_: Specify the maximum size for a hash table used for long distance matching. @@ -463,7 +474,7 @@ The list of available _options_: Bigger hash tables usually improve compression ratio at the expense of more memory during compression and a decrease in compression speed. - The minimum _lhlog_ is 6 and the maximum is 30 (default: 20). + The minimum _lhlog_ is 6 and the maximum is 30 (default: `windowLog - ldmHashRateLog`). - `ldmMinMatch`=_lmml_, `lmml`=_lmml_: Specify the minimum searched length of a match for long distance matching. @@ -472,7 +483,7 @@ The list of available _options_: Larger/very small values usually decrease compression ratio. - The minimum _lmml_ is 4 and the maximum is 4096 (default: 64). + The minimum _lmml_ is 4 and the maximum is 4096 (default: 32 to 128, depending on `strategy`). - `ldmBucketSizeLog`=_lblog_, `lblog`=_lblog_: Specify the size of each bucket for the hash table used for long distance @@ -483,18 +494,8 @@ The list of available _options_: Larger bucket sizes improve collision resolution but decrease compression speed. - The minimum _lblog_ is 1 and the maximum is 8 (default: 3). + The minimum _lblog_ is 1 and the maximum is 8 (default: 4 to 8, depending on `strategy`). -- `ldmHashRateLog`=_lhrlog_, `lhrlog`=_lhrlog_: - Specify the frequency of inserting entries into the long distance matching - hash table. - - This option is ignored unless long distance matching is enabled. - - Larger values will improve compression speed. Deviating far from the - default value will likely result in a decrease in compression ratio. - - The default value is `wlog - lhlog`. ### Example The following parameters sets advanced compression options to something From 7c5b6002c9c40936fbfd13bd6e7737b059f16d4a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 17:40:54 -0800 Subject: [PATCH 675/937] update results from the --long mode --- tests/regression/results.csv | 48 ++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 505f4755b..467073ebf 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -111,9 +111,9 @@ silesia, level 9, zstdcli, silesia, level 13, zstdcli, 4488438 silesia, level 16, zstdcli, 4358150 silesia, level 19, zstdcli, 4265929 -silesia, long distance mode, zstdcli, 4824875 +silesia, long distance mode, zstdcli, 4828930 silesia, multithreaded, zstdcli, 4833113 -silesia, multithreaded long distance mode, zstdcli, 4824875 +silesia, multithreaded long distance mode, zstdcli, 4828930 silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6527214 silesia, small chain log, zstdcli, 4911647 @@ -137,9 +137,9 @@ silesia.tar, level 13, zstdcli, silesia.tar, level 16, zstdcli, 4357018 silesia.tar, level 19, zstdcli, 4259593 silesia.tar, no source size, zstdcli, 4836000 -silesia.tar, long distance mode, zstdcli, 4828171 +silesia.tar, long distance mode, zstdcli, 4833141 silesia.tar, multithreaded, zstdcli, 4836004 -silesia.tar, multithreaded long distance mode, zstdcli, 4828171 +silesia.tar, multithreaded long distance mode, zstdcli, 4833141 silesia.tar, small window log, zstdcli, 7100110 silesia.tar, small hash log, zstdcli, 6530127 silesia.tar, small chain log, zstdcli, 4915865 @@ -217,9 +217,9 @@ github.tar, level 19, zstdcli, github.tar, level 19 with dict, zstdcli, 32705 github.tar, no source size, zstdcli, 38885 github.tar, no source size with dict, zstdcli, 38115 -github.tar, long distance mode, zstdcli, 40227 +github.tar, long distance mode, zstdcli, 38801 github.tar, multithreaded, zstdcli, 38888 -github.tar, multithreaded long distance mode, zstdcli, 40227 +github.tar, multithreaded long distance mode, zstdcli, 38801 github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 @@ -251,9 +251,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass, 4356799 silesia, level 19, advanced one pass, 4265851 silesia, no source size, advanced one pass, 4832054 -silesia, long distance mode, advanced one pass, 4823833 +silesia, long distance mode, advanced one pass, 4827748 silesia, multithreaded, advanced one pass, 4833065 -silesia, multithreaded long distance mode, advanced one pass, 4824827 +silesia, multithreaded long distance mode, advanced one pass, 4828882 silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6525510 silesia, small chain log, advanced one pass, 4912248 @@ -285,9 +285,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass, 4355572 silesia.tar, level 19, advanced one pass, 4257629 silesia.tar, no source size, advanced one pass, 4829268 -silesia.tar, long distance mode, advanced one pass, 4816169 +silesia.tar, long distance mode, advanced one pass, 4821065 silesia.tar, multithreaded, advanced one pass, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass, 4828167 +silesia.tar, multithreaded long distance mode, advanced one pass, 4833137 silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6530222 silesia.tar, small chain log, advanced one pass, 4915689 @@ -535,9 +535,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass, 32428 github.tar, no source size, advanced one pass, 38884 github.tar, no source size with dict, advanced one pass, 37995 -github.tar, long distance mode, advanced one pass, 40242 +github.tar, long distance mode, advanced one pass, 38797 github.tar, multithreaded, advanced one pass, 38884 -github.tar, multithreaded long distance mode, advanced one pass, 40223 +github.tar, multithreaded long distance mode, advanced one pass, 38797 github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 @@ -569,9 +569,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass small out, 4356799 silesia, level 19, advanced one pass small out, 4265851 silesia, no source size, advanced one pass small out, 4832054 -silesia, long distance mode, advanced one pass small out, 4823833 +silesia, long distance mode, advanced one pass small out, 4827748 silesia, multithreaded, advanced one pass small out, 4833065 -silesia, multithreaded long distance mode, advanced one pass small out, 4824827 +silesia, multithreaded long distance mode, advanced one pass small out, 4828882 silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6525510 silesia, small chain log, advanced one pass small out, 4912248 @@ -603,9 +603,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass small out, 4355572 silesia.tar, level 19, advanced one pass small out, 4257629 silesia.tar, no source size, advanced one pass small out, 4829268 -silesia.tar, long distance mode, advanced one pass small out, 4816169 +silesia.tar, long distance mode, advanced one pass small out, 4821065 silesia.tar, multithreaded, advanced one pass small out, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4828167 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4833137 silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6530222 silesia.tar, small chain log, advanced one pass small out, 4915689 @@ -853,9 +853,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass small out, 32428 github.tar, no source size, advanced one pass small out, 38884 github.tar, no source size with dict, advanced one pass small out, 37995 -github.tar, long distance mode, advanced one pass small out, 40242 +github.tar, long distance mode, advanced one pass small out, 38797 github.tar, multithreaded, advanced one pass small out, 38884 -github.tar, multithreaded long distance mode, advanced one pass small out, 40223 +github.tar, multithreaded long distance mode, advanced one pass small out, 38797 github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 @@ -887,9 +887,9 @@ silesia, level 13, advanced silesia, level 16, advanced streaming, 4358094 silesia, level 19, advanced streaming, 4265908 silesia, no source size, advanced streaming, 4835768 -silesia, long distance mode, advanced streaming, 4827592 +silesia, long distance mode, advanced streaming, 4831544 silesia, multithreaded, advanced streaming, 4833065 -silesia, multithreaded long distance mode, advanced streaming, 4824827 +silesia, multithreaded long distance mode, advanced streaming, 4828882 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6525259 silesia, small chain log, advanced streaming, 4911577 @@ -921,9 +921,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced streaming, 4358029 silesia.tar, level 19, advanced streaming, 4258228 silesia.tar, no source size, advanced streaming, 4846779 -silesia.tar, long distance mode, advanced streaming, 4826177 +silesia.tar, long distance mode, advanced streaming, 4831119 silesia.tar, multithreaded, advanced streaming, 4836000 -silesia.tar, multithreaded long distance mode, advanced streaming, 4828167 +silesia.tar, multithreaded long distance mode, advanced streaming, 4833137 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529503 silesia.tar, small chain log, advanced streaming, 4915956 @@ -1171,9 +1171,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced streaming, 32428 github.tar, no source size, advanced streaming, 38881 github.tar, no source size with dict, advanced streaming, 38111 -github.tar, long distance mode, advanced streaming, 40242 +github.tar, long distance mode, advanced streaming, 38797 github.tar, multithreaded, advanced streaming, 38884 -github.tar, multithreaded long distance mode, advanced streaming, 40223 +github.tar, multithreaded long distance mode, advanced streaming, 38797 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 From 72406b71c30efbfe865611a79f50117254820c40 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 18:57:44 -0800 Subject: [PATCH 676/937] update hrlog rule to favor compression ratio a bit more at low levels --- lib/compress/zstd_ldm.c | 2 +- programs/zstd.1.md | 2 +- tests/regression/results.csv | 48 ++++++++++++++++++------------------ 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 39f23c565..e85e904da 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -141,7 +141,7 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, if (params->hashRateLog == 0) { assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ - params->hashRateLog = 9 - ((cParams->strategy+1)/2); + params->hashRateLog = 7 - (cParams->strategy/3); } if (params->hashLog == 0) { params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog); diff --git a/programs/zstd.1.md b/programs/zstd.1.md index be2179e5d..1459abb9f 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -464,7 +464,7 @@ The list of available _options_: Larger values will improve compression speed. Deviating far from the default value will likely result in a decrease in compression ratio. - The default value varies between 4 and 8, depending on `strategy`. + The default value varies between 4 and 7, depending on `strategy`. - `ldmHashLog`=_lhlog_, `lhlog`=_lhlog_: Specify the maximum size for a hash table used for long distance matching. diff --git a/tests/regression/results.csv b/tests/regression/results.csv index 467073ebf..cc7500d96 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -111,9 +111,9 @@ silesia, level 9, zstdcli, silesia, level 13, zstdcli, 4488438 silesia, level 16, zstdcli, 4358150 silesia, level 19, zstdcli, 4265929 -silesia, long distance mode, zstdcli, 4828930 +silesia, long distance mode, zstdcli, 4827199 silesia, multithreaded, zstdcli, 4833113 -silesia, multithreaded long distance mode, zstdcli, 4828930 +silesia, multithreaded long distance mode, zstdcli, 4827199 silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6527214 silesia, small chain log, zstdcli, 4911647 @@ -137,9 +137,9 @@ silesia.tar, level 13, zstdcli, silesia.tar, level 16, zstdcli, 4357018 silesia.tar, level 19, zstdcli, 4259593 silesia.tar, no source size, zstdcli, 4836000 -silesia.tar, long distance mode, zstdcli, 4833141 +silesia.tar, long distance mode, zstdcli, 4831415 silesia.tar, multithreaded, zstdcli, 4836004 -silesia.tar, multithreaded long distance mode, zstdcli, 4833141 +silesia.tar, multithreaded long distance mode, zstdcli, 4831415 silesia.tar, small window log, zstdcli, 7100110 silesia.tar, small hash log, zstdcli, 6530127 silesia.tar, small chain log, zstdcli, 4915865 @@ -217,9 +217,9 @@ github.tar, level 19, zstdcli, github.tar, level 19 with dict, zstdcli, 32705 github.tar, no source size, zstdcli, 38885 github.tar, no source size with dict, zstdcli, 38115 -github.tar, long distance mode, zstdcli, 38801 +github.tar, long distance mode, zstdcli, 38775 github.tar, multithreaded, zstdcli, 38888 -github.tar, multithreaded long distance mode, zstdcli, 38801 +github.tar, multithreaded long distance mode, zstdcli, 38775 github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 @@ -251,9 +251,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass, 4356799 silesia, level 19, advanced one pass, 4265851 silesia, no source size, advanced one pass, 4832054 -silesia, long distance mode, advanced one pass, 4827748 +silesia, long distance mode, advanced one pass, 4826152 silesia, multithreaded, advanced one pass, 4833065 -silesia, multithreaded long distance mode, advanced one pass, 4828882 +silesia, multithreaded long distance mode, advanced one pass, 4827151 silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6525510 silesia, small chain log, advanced one pass, 4912248 @@ -285,9 +285,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass, 4355572 silesia.tar, level 19, advanced one pass, 4257629 silesia.tar, no source size, advanced one pass, 4829268 -silesia.tar, long distance mode, advanced one pass, 4821065 +silesia.tar, long distance mode, advanced one pass, 4819329 silesia.tar, multithreaded, advanced one pass, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass, 4833137 +silesia.tar, multithreaded long distance mode, advanced one pass, 4831411 silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6530222 silesia.tar, small chain log, advanced one pass, 4915689 @@ -535,9 +535,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass, 32428 github.tar, no source size, advanced one pass, 38884 github.tar, no source size with dict, advanced one pass, 37995 -github.tar, long distance mode, advanced one pass, 38797 +github.tar, long distance mode, advanced one pass, 38771 github.tar, multithreaded, advanced one pass, 38884 -github.tar, multithreaded long distance mode, advanced one pass, 38797 +github.tar, multithreaded long distance mode, advanced one pass, 38771 github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 @@ -569,9 +569,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass small out, 4356799 silesia, level 19, advanced one pass small out, 4265851 silesia, no source size, advanced one pass small out, 4832054 -silesia, long distance mode, advanced one pass small out, 4827748 +silesia, long distance mode, advanced one pass small out, 4826152 silesia, multithreaded, advanced one pass small out, 4833065 -silesia, multithreaded long distance mode, advanced one pass small out, 4828882 +silesia, multithreaded long distance mode, advanced one pass small out, 4827151 silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6525510 silesia, small chain log, advanced one pass small out, 4912248 @@ -603,9 +603,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass small out, 4355572 silesia.tar, level 19, advanced one pass small out, 4257629 silesia.tar, no source size, advanced one pass small out, 4829268 -silesia.tar, long distance mode, advanced one pass small out, 4821065 +silesia.tar, long distance mode, advanced one pass small out, 4819329 silesia.tar, multithreaded, advanced one pass small out, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4833137 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4831411 silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6530222 silesia.tar, small chain log, advanced one pass small out, 4915689 @@ -853,9 +853,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass small out, 32428 github.tar, no source size, advanced one pass small out, 38884 github.tar, no source size with dict, advanced one pass small out, 37995 -github.tar, long distance mode, advanced one pass small out, 38797 +github.tar, long distance mode, advanced one pass small out, 38771 github.tar, multithreaded, advanced one pass small out, 38884 -github.tar, multithreaded long distance mode, advanced one pass small out, 38797 +github.tar, multithreaded long distance mode, advanced one pass small out, 38771 github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 @@ -887,9 +887,9 @@ silesia, level 13, advanced silesia, level 16, advanced streaming, 4358094 silesia, level 19, advanced streaming, 4265908 silesia, no source size, advanced streaming, 4835768 -silesia, long distance mode, advanced streaming, 4831544 +silesia, long distance mode, advanced streaming, 4829919 silesia, multithreaded, advanced streaming, 4833065 -silesia, multithreaded long distance mode, advanced streaming, 4828882 +silesia, multithreaded long distance mode, advanced streaming, 4827151 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6525259 silesia, small chain log, advanced streaming, 4911577 @@ -921,9 +921,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced streaming, 4358029 silesia.tar, level 19, advanced streaming, 4258228 silesia.tar, no source size, advanced streaming, 4846779 -silesia.tar, long distance mode, advanced streaming, 4831119 +silesia.tar, long distance mode, advanced streaming, 4829404 silesia.tar, multithreaded, advanced streaming, 4836000 -silesia.tar, multithreaded long distance mode, advanced streaming, 4833137 +silesia.tar, multithreaded long distance mode, advanced streaming, 4831411 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529503 silesia.tar, small chain log, advanced streaming, 4915956 @@ -1171,9 +1171,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced streaming, 32428 github.tar, no source size, advanced streaming, 38881 github.tar, no source size with dict, advanced streaming, 38111 -github.tar, long distance mode, advanced streaming, 38797 +github.tar, long distance mode, advanced streaming, 38771 github.tar, multithreaded, advanced streaming, 38884 -github.tar, multithreaded long distance mode, advanced streaming, 38797 +github.tar, multithreaded long distance mode, advanced streaming, 38771 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 From d5e4698267b970545c349b3ed30a9168bcd165c3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 7 Feb 2025 22:47:57 -0800 Subject: [PATCH 677/937] fix boundary condition --- lib/compress/zstd_ldm.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index e85e904da..aa5743c5c 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -144,8 +144,7 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, params->hashRateLog = 7 - (cParams->strategy/3); } if (params->hashLog == 0) { - params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog); - assert(params->hashLog <= ZSTD_HASHLOG_MAX); + params->hashLog = MIN(MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog), ZSTD_HASHLOG_MAX); } if (params->minMatchLength == 0) { params->minMatchLength = (params->hashRateLog < 6) ? From 09d7e34ed8c138e913d8c11724f2d5fb5a1436bd Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 8 Feb 2025 14:27:29 -0800 Subject: [PATCH 678/937] adjust mml --- lib/compress/zstd_ldm.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index aa5743c5c..981287d85 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -147,10 +147,8 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, params->hashLog = MIN(MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog), ZSTD_HASHLOG_MAX); } if (params->minMatchLength == 0) { - params->minMatchLength = (params->hashRateLog < 6) ? - LDM_MIN_MATCH_LENGTH : - LDM_MIN_MATCH_LENGTH * 2; - if (cParams->strategy >= ZSTD_btultra2) + params->minMatchLength = LDM_MIN_MATCH_LENGTH; + if (cParams->strategy >= ZSTD_btultra) params->minMatchLength /= 2; } if (params->bucketSizeLog==0) { From 339bca66066e4a099bc91d04265c9bfbf15001bb Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 8 Feb 2025 16:16:35 -0800 Subject: [PATCH 679/937] update ldm compression results --- programs/zstd.1.md | 2 +- tests/regression/results.csv | 48 ++++++++++++++++++------------------ 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 1459abb9f..e5c1b7fd2 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -483,7 +483,7 @@ The list of available _options_: Larger/very small values usually decrease compression ratio. - The minimum _lmml_ is 4 and the maximum is 4096 (default: 32 to 128, depending on `strategy`). + The minimum _lmml_ is 4 and the maximum is 4096 (default: 32 to 64, depending on `strategy`). - `ldmBucketSizeLog`=_lblog_, `lblog`=_lblog_: Specify the size of each bucket for the hash table used for long distance diff --git a/tests/regression/results.csv b/tests/regression/results.csv index cc7500d96..c0d4f4ae7 100644 --- a/tests/regression/results.csv +++ b/tests/regression/results.csv @@ -111,9 +111,9 @@ silesia, level 9, zstdcli, silesia, level 13, zstdcli, 4488438 silesia, level 16, zstdcli, 4358150 silesia, level 19, zstdcli, 4265929 -silesia, long distance mode, zstdcli, 4827199 +silesia, long distance mode, zstdcli, 4824341 silesia, multithreaded, zstdcli, 4833113 -silesia, multithreaded long distance mode, zstdcli, 4827199 +silesia, multithreaded long distance mode, zstdcli, 4824341 silesia, small window log, zstdcli, 7094528 silesia, small hash log, zstdcli, 6527214 silesia, small chain log, zstdcli, 4911647 @@ -137,9 +137,9 @@ silesia.tar, level 13, zstdcli, silesia.tar, level 16, zstdcli, 4357018 silesia.tar, level 19, zstdcli, 4259593 silesia.tar, no source size, zstdcli, 4836000 -silesia.tar, long distance mode, zstdcli, 4831415 +silesia.tar, long distance mode, zstdcli, 4827830 silesia.tar, multithreaded, zstdcli, 4836004 -silesia.tar, multithreaded long distance mode, zstdcli, 4831415 +silesia.tar, multithreaded long distance mode, zstdcli, 4827830 silesia.tar, small window log, zstdcli, 7100110 silesia.tar, small hash log, zstdcli, 6530127 silesia.tar, small chain log, zstdcli, 4915865 @@ -217,9 +217,9 @@ github.tar, level 19, zstdcli, github.tar, level 19 with dict, zstdcli, 32705 github.tar, no source size, zstdcli, 38885 github.tar, no source size with dict, zstdcli, 38115 -github.tar, long distance mode, zstdcli, 38775 +github.tar, long distance mode, zstdcli, 40143 github.tar, multithreaded, zstdcli, 38888 -github.tar, multithreaded long distance mode, zstdcli, 38775 +github.tar, multithreaded long distance mode, zstdcli, 40143 github.tar, small window log, zstdcli, 198539 github.tar, small hash log, zstdcli, 129874 github.tar, small chain log, zstdcli, 41673 @@ -251,9 +251,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass, 4356799 silesia, level 19, advanced one pass, 4265851 silesia, no source size, advanced one pass, 4832054 -silesia, long distance mode, advanced one pass, 4826152 +silesia, long distance mode, advanced one pass, 4823264 silesia, multithreaded, advanced one pass, 4833065 -silesia, multithreaded long distance mode, advanced one pass, 4827151 +silesia, multithreaded long distance mode, advanced one pass, 4824293 silesia, small window log, advanced one pass, 7094480 silesia, small hash log, advanced one pass, 6525510 silesia, small chain log, advanced one pass, 4912248 @@ -285,9 +285,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass, 4355572 silesia.tar, level 19, advanced one pass, 4257629 silesia.tar, no source size, advanced one pass, 4829268 -silesia.tar, long distance mode, advanced one pass, 4819329 +silesia.tar, long distance mode, advanced one pass, 4815868 silesia.tar, multithreaded, advanced one pass, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass, 4831411 +silesia.tar, multithreaded long distance mode, advanced one pass, 4827826 silesia.tar, small window log, advanced one pass, 7100064 silesia.tar, small hash log, advanced one pass, 6530222 silesia.tar, small chain log, advanced one pass, 4915689 @@ -535,9 +535,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass, 32428 github.tar, no source size, advanced one pass, 38884 github.tar, no source size with dict, advanced one pass, 37995 -github.tar, long distance mode, advanced one pass, 38771 +github.tar, long distance mode, advanced one pass, 40156 github.tar, multithreaded, advanced one pass, 38884 -github.tar, multithreaded long distance mode, advanced one pass, 38771 +github.tar, multithreaded long distance mode, advanced one pass, 40139 github.tar, small window log, advanced one pass, 198535 github.tar, small hash log, advanced one pass, 129870 github.tar, small chain log, advanced one pass, 41669 @@ -569,9 +569,9 @@ silesia, level 13, advanced silesia, level 16, advanced one pass small out, 4356799 silesia, level 19, advanced one pass small out, 4265851 silesia, no source size, advanced one pass small out, 4832054 -silesia, long distance mode, advanced one pass small out, 4826152 +silesia, long distance mode, advanced one pass small out, 4823264 silesia, multithreaded, advanced one pass small out, 4833065 -silesia, multithreaded long distance mode, advanced one pass small out, 4827151 +silesia, multithreaded long distance mode, advanced one pass small out, 4824293 silesia, small window log, advanced one pass small out, 7094480 silesia, small hash log, advanced one pass small out, 6525510 silesia, small chain log, advanced one pass small out, 4912248 @@ -603,9 +603,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced one pass small out, 4355572 silesia.tar, level 19, advanced one pass small out, 4257629 silesia.tar, no source size, advanced one pass small out, 4829268 -silesia.tar, long distance mode, advanced one pass small out, 4819329 +silesia.tar, long distance mode, advanced one pass small out, 4815868 silesia.tar, multithreaded, advanced one pass small out, 4836000 -silesia.tar, multithreaded long distance mode, advanced one pass small out, 4831411 +silesia.tar, multithreaded long distance mode, advanced one pass small out, 4827826 silesia.tar, small window log, advanced one pass small out, 7100064 silesia.tar, small hash log, advanced one pass small out, 6530222 silesia.tar, small chain log, advanced one pass small out, 4915689 @@ -853,9 +853,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced one pass small out, 32428 github.tar, no source size, advanced one pass small out, 38884 github.tar, no source size with dict, advanced one pass small out, 37995 -github.tar, long distance mode, advanced one pass small out, 38771 +github.tar, long distance mode, advanced one pass small out, 40156 github.tar, multithreaded, advanced one pass small out, 38884 -github.tar, multithreaded long distance mode, advanced one pass small out, 38771 +github.tar, multithreaded long distance mode, advanced one pass small out, 40139 github.tar, small window log, advanced one pass small out, 198535 github.tar, small hash log, advanced one pass small out, 129870 github.tar, small chain log, advanced one pass small out, 41669 @@ -887,9 +887,9 @@ silesia, level 13, advanced silesia, level 16, advanced streaming, 4358094 silesia, level 19, advanced streaming, 4265908 silesia, no source size, advanced streaming, 4835768 -silesia, long distance mode, advanced streaming, 4829919 +silesia, long distance mode, advanced streaming, 4827032 silesia, multithreaded, advanced streaming, 4833065 -silesia, multithreaded long distance mode, advanced streaming, 4827151 +silesia, multithreaded long distance mode, advanced streaming, 4824293 silesia, small window log, advanced streaming, 7110591 silesia, small hash log, advanced streaming, 6525259 silesia, small chain log, advanced streaming, 4911577 @@ -921,9 +921,9 @@ silesia.tar, level 13, advanced silesia.tar, level 16, advanced streaming, 4358029 silesia.tar, level 19, advanced streaming, 4258228 silesia.tar, no source size, advanced streaming, 4846779 -silesia.tar, long distance mode, advanced streaming, 4829404 +silesia.tar, long distance mode, advanced streaming, 4825842 silesia.tar, multithreaded, advanced streaming, 4836000 -silesia.tar, multithreaded long distance mode, advanced streaming, 4831411 +silesia.tar, multithreaded long distance mode, advanced streaming, 4827826 silesia.tar, small window log, advanced streaming, 7117024 silesia.tar, small hash log, advanced streaming, 6529503 silesia.tar, small chain log, advanced streaming, 4915956 @@ -1171,9 +1171,9 @@ github.tar, level 19 with dict copy, advanced github.tar, level 19 with dict load, advanced streaming, 32428 github.tar, no source size, advanced streaming, 38881 github.tar, no source size with dict, advanced streaming, 38111 -github.tar, long distance mode, advanced streaming, 38771 +github.tar, long distance mode, advanced streaming, 40156 github.tar, multithreaded, advanced streaming, 38884 -github.tar, multithreaded long distance mode, advanced streaming, 38771 +github.tar, multithreaded long distance mode, advanced streaming, 40139 github.tar, small window log, advanced streaming, 199553 github.tar, small hash log, advanced streaming, 129870 github.tar, small chain log, advanced streaming, 41669 From 67fad95f7971b97085fb838e3aa47cd37e9d7908 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 9 Feb 2025 11:11:49 -0800 Subject: [PATCH 680/937] derive hashratelog from hashlog when only hashlog is set --- lib/compress/zstd_ldm.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 981287d85..6aa6197e9 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -133,18 +133,26 @@ done: } void ZSTD_ldm_adjustParameters(ldmParams_t* params, - ZSTD_compressionParameters const* cParams) + const ZSTD_compressionParameters* cParams) { params->windowLog = cParams->windowLog; ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX); DEBUGLOG(4, "ZSTD_ldm_adjustParameters"); if (params->hashRateLog == 0) { - assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); - /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ - params->hashRateLog = 7 - (cParams->strategy/3); + if (params->hashLog > 0) { + /* if params->hashLog is set, derive hashRateLog from it */ + assert(params->hashLog <= ZSTD_HASHLOG_MAX); + if (params->windowLog > params->hashLog) { + params->hashRateLog = params->windowLog - params->hashLog; + } + } else { + assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); + /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ + params->hashRateLog = 7 - (cParams->strategy/3); + } } if (params->hashLog == 0) { - params->hashLog = MIN(MAX(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog), ZSTD_HASHLOG_MAX); + params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX); } if (params->minMatchLength == 0) { params->minMatchLength = LDM_MIN_MATCH_LENGTH; @@ -152,11 +160,8 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, params->minMatchLength /= 2; } if (params->bucketSizeLog==0) { - params->bucketSizeLog = LDM_BUCKET_SIZE_LOG; - if (cParams->strategy > ZSTD_lazy) { - params->bucketSizeLog += (U32)cParams->strategy - (U32)ZSTD_lazy; - } - params->bucketSizeLog = MIN(params->bucketSizeLog, ZSTD_LDM_BUCKETSIZELOG_MAX); + assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); + params->bucketSizeLog = BOUNDED(LDM_BUCKET_SIZE_LOG, (U32)cParams->strategy, ZSTD_LDM_BUCKETSIZELOG_MAX); } params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog); } From d2c562b803a4c49dbd5afb1717db095aae1557b1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Feb 2025 10:48:56 -0800 Subject: [PATCH 681/937] update hrlog comment --- lib/compress/zstd_ldm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 6aa6197e9..070551cad 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -147,7 +147,7 @@ void ZSTD_ldm_adjustParameters(ldmParams_t* params, } } else { assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9); - /* mapping: strat1 -> rate8 ... strat9 -> rate4*/ + /* mapping from [fast, rate7] to [btultra2, rate4] */ params->hashRateLog = 7 - (cParams->strategy/3); } } From 815ca8c6784f59de825058b2b84bdb59b854feee Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 09:19:08 -0800 Subject: [PATCH 682/937] ubuntu 20 is being deprecated change ubuntu20 tests to use more modern ubuntu variants --- .github/workflows/dev-short-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 2b35354d2..392b005f6 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -38,7 +38,7 @@ jobs: CFLAGS="-m32 -O1 -fstack-protector" make check V=1 check-x32: - runs-on: ubuntu-20.04 # ubuntu-latest == ubuntu-22.04 have issues currently with x32 + runs-on: ubuntu-lastest # ubuntu-latest == ubuntu-22.04 have issues currently with x32 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: make check on x32 ABI # https://en.wikipedia.org/wiki/X32_ABI @@ -467,7 +467,7 @@ jobs: qemu-consistency: name: QEMU ${{ matrix.name }} - runs-on: ubuntu-20.04 + runs-on: ubuntu-22.04 strategy: fail-fast: false # 'false' means Don't stop matrix workflows even if some matrix failed. matrix: From fc1baf34637e7f230996cdc8ca259bf71809978a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 09:57:18 -0800 Subject: [PATCH 683/937] move qemu tests to ubuntu24 --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 392b005f6..d9610d3a4 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -467,7 +467,7 @@ jobs: qemu-consistency: name: QEMU ${{ matrix.name }} - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false # 'false' means Don't stop matrix workflows even if some matrix failed. matrix: From 75bcae1272cbd6e417a9eb2c0e35e9f02828fba4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 11:37:18 -0800 Subject: [PATCH 684/937] removing x32 tests this ABI is no longer supported by Ubuntu, and there is a wider consensus that this ABI is on the way out, with more and more distributions dropping it, and lingering questions about support of x32 in the kernel. --- .github/workflows/dev-short-tests.yml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index d9610d3a4..7cc7bd85f 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -37,18 +37,6 @@ jobs: APT_PACKAGES="gcc-multilib" make apt-install CFLAGS="-m32 -O1 -fstack-protector" make check V=1 - check-x32: - runs-on: ubuntu-lastest # ubuntu-latest == ubuntu-22.04 have issues currently with x32 - steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: make check on x32 ABI # https://en.wikipedia.org/wiki/X32_ABI - env: - CHECK_CONSTRAINED_MEM: true - run: | - sudo apt update - APT_PACKAGES="gcc-multilib" make apt-install - CFLAGS="-mx32 -O1 -fstack-protector" make check V=1 - build-c89: runs-on: ubuntu-latest steps: From 2b7c661ad2c022a56f6d0c58cbafa6f3d637ad4f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 11:43:23 -0800 Subject: [PATCH 685/937] update arm64 test for ubuntu-24 --- .github/workflows/dev-short-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7cc7bd85f..61fd9fb69 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -461,7 +461,7 @@ jobs: matrix: include: [ { name: ARM, xcc_pkg: gcc-arm-linux-gnueabi, xcc: arm-linux-gnueabi-gcc, xemu_pkg: qemu-system-arm, xemu: qemu-arm-static }, - { name: ARM64, xcc_pkg: gcc-aarch64-linux-gnu, xcc: aarch64-linux-gnu-gcc, xemu_pkg: qemu-system-arm, xemu: qemu-aarch64-static }, + { name: ARM64, xcc_pkg: gcc-aarch64-linux-gnu, xcc: aarch64-linux-gnu-gcc, xemu_pkg: qemu-system-aarch64,xemu: qemu-aarch64-static }, { name: PPC, xcc_pkg: gcc-powerpc-linux-gnu, xcc: powerpc-linux-gnu-gcc, xemu_pkg: qemu-system-ppc, xemu: qemu-ppc-static }, { name: PPC64LE, xcc_pkg: gcc-powerpc64le-linux-gnu, xcc: powerpc64le-linux-gnu-gcc, xemu_pkg: qemu-system-ppc, xemu: qemu-ppc64le-static }, { name: S390X, xcc_pkg: gcc-s390x-linux-gnu, xcc: s390x-linux-gnu-gcc, xemu_pkg: qemu-system-s390x, xemu: qemu-s390x-static }, @@ -494,7 +494,7 @@ jobs: - name: ARM64 if: ${{ matrix.name == 'ARM64' }} run: | - LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make clean check + CFLAGS="-march=armv8-a -Og" LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make clean check LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check - name: PPC if: ${{ matrix.name == 'PPC' }} From b73e06b83e0fc6f7f6999c2292b3250eb50b2084 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 12:52:59 -0800 Subject: [PATCH 686/937] updated FreeBSD VM to 14.2 14.1 seems no longer supported by gcloud --- .cirrus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index 9461de412..745024bc2 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -2,7 +2,7 @@ task: name: FreeBSD (make check) freebsd_instance: matrix: - image_family: freebsd-14-1 + image_family: freebsd-14-2 install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From 0b8119f0ad0b027faffb7955b835718e049399e6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 12:58:35 -0800 Subject: [PATCH 687/937] minor arm64 test script clarification --- .github/workflows/dev-short-tests.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 61fd9fb69..19446d18e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -494,8 +494,10 @@ jobs: - name: ARM64 if: ${{ matrix.name == 'ARM64' }} run: | - CFLAGS="-march=armv8-a -Og" LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make clean check - LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check + make clean + CFLAGS="-march=armv8-a -Og" LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make check + make clean + CFLAGS="-march=armv8-a -Og" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make check - name: PPC if: ${{ matrix.name == 'PPC' }} run: | From 85c39b78cfabf64fe0d8859f3c4ac5f240d52fc8 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 13:11:29 -0800 Subject: [PATCH 688/937] faster aarch64 test execution --- .github/workflows/dev-short-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 19446d18e..a163e0219 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -495,9 +495,9 @@ jobs: if: ${{ matrix.name == 'ARM64' }} run: | make clean - CFLAGS="-march=armv8-a -Og" LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make check + LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check make clean - CFLAGS="-march=armv8-a -Og" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make check + LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make check V=1 - name: PPC if: ${{ matrix.name == 'PPC' }} run: | From 2a58b047529ca385867fea53b4077526bb10486e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Feb 2025 13:20:15 -0800 Subject: [PATCH 689/937] disabled BTI test this test seems impossible on Ubuntu-24 --- .github/workflows/dev-short-tests.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index a163e0219..408331abc 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -496,8 +496,10 @@ jobs: run: | make clean LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check - make clean - LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make check V=1 +# This test is only compatible with standard libraries that support BTI (Branch Target Identification). +# Unfortunately, the standard library provided on Ubuntu 24.04 does not have this feature enabled. +# make clean +# LDFLAGS="-static -z force-bti" MOREFLAGS="-mbranch-protection=standard" CC=$XCC QEMU_SYS=$XEMU make check V=1 - name: PPC if: ${{ matrix.name == 'PPC' }} run: | From c26bde119ba984ae1f2efe76d610eb50d152b1ec Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Feb 2025 13:42:54 -0800 Subject: [PATCH 690/937] update changelog for v1.5.7 --- CHANGELOG | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index ac44affce..92df0f462 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,29 @@ +V1.5.7 (Feb 2025) +fix: compression bug in 32-bit mode associated with long-lasting sessions +api: new method `ZSTD_compressSequencesAndLiterals()` (#4217, #4232) +api: `ZSTD_getFrameHeader()` works on skippable frames (#4228) +perf: substantial compression speed improvements (up to +30%) on small data, by @TocarIP (#4144) and @cyan4973 (#4165) +perf: improved compression speed (~+5%) for dictionary compression at low levels (#4170) +perf: much faster speed for `--patch-from` at high compression levels (#4276) +perf: higher `--patch-from` compression ratios, notably at high levels (#4288) +perf: better speed for binaries on Windows (@pps83) and when compiled with Visual Studio (@MessyHack) +perf: slight compression ratio improvement thanks to better block boundaries (#4136, #4176, #4178) +perf: slight compression ratio improvement for `dfast`, aka levels 3 and 4 (#4171) +perf: runtime bmi2 detection enabled on x86 32-bit mode (#4251) +cli: multi-threading as default CLI setting, by @daniellerozenblit +cli: new `--max` command (#4290) +build: improve `msbuild` version autodetection, support VS2022, by @ManuelBlanc +build: fix `meson` build by @artem and @Victor-C-Zhang, and on Windows by @bgilbert +build: compatibility with Apple Framework, by @Treata11 +build: improve icc/icx compatibility, by @josepho0918 and @luau-project +build: improve compatibility with Android NDK, by Adenilson Cavalcanti +portability: linux kernel branch, with improved support for Sequence producers (@embg, @gcabiddu, @cyan4973) +portability: improved qnx compatibility, suggested by @rainbowball +portability: improved install script for FreeBSD, by @sunpoet +portability: fixed test suite compatibility with gnu hurd, by @diegonc +doc: clarify specification, by @elasota +misc: improved tests/decodecorpus validation tool (#4102), by antmicro + V1.5.6 (Mar 2024) api: Promote `ZSTD_c_targetCBlockSize` to Stable API by @felixhandte api: new `ZSTD_d_maxBlockSize` experimental parameter, to reduce streaming decompression memory, by @terrelln From 5c465fcabeea65e642aaf70d1059958acd6acd69 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Feb 2025 14:50:03 -0800 Subject: [PATCH 691/937] harden github actions script Android NDK Build --- .github/workflows/android-ndk-build.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index c77d5f0d1..175add4ff 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -6,6 +6,8 @@ on: push: branches: [ actionsTest, '*ndk*' ] +permissions: read-all + jobs: build: runs-on: ubuntu-latest @@ -14,13 +16,13 @@ jobs: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0 with: java-version: '17' distribution: 'temurin' - name: Setup Android SDK - uses: android-actions/setup-android@v3 + uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3.2.2 - name: Install Android NDK run: | From b14d76d88810f2984e0cd9ebd307269843a5d7d9 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Feb 2025 14:53:31 -0800 Subject: [PATCH 692/937] pinned dependency hash --- .github/workflows/dev-short-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 53ae03d79..7df105532 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -97,7 +97,7 @@ jobs: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 with: path: "${{ env.SRC_DIR }}" - - uses: ilammy/msvc-dev-cmd@v1 + - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 if: ${{ matrix.generator == 'NMake Makefiles' }} - name: cmake build on a source directory with spaces run: | @@ -722,4 +722,4 @@ jobs: - name: make check run: | source /opt/intel/oneapi/setvars.sh - make CC=icx check \ No newline at end of file + make CC=icx check From eb6608869fa58d324227b3e5484cc3347a8dd8ed Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Feb 2025 16:19:18 -0800 Subject: [PATCH 693/937] faster clang-msan-testzstd this is by far our longest CI test. Attempt to make it run a bit faster. --- .github/workflows/dev-long-tests.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 899a57b75..0aa85ff7e 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -222,16 +222,13 @@ jobs: sudo apt-get install clang CC=clang FUZZER_FLAGS="--long-tests" make clean msan-fuzztest - # lasts ~24mn clang-msan-testzstd: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - name: clang + MSan + Test Zstd run: | - sudo apt-get update - sudo apt-get install clang - CC=clang make msan-test-zstd HAVE_ZLIB=0 HAVE_LZ4=0 HAVE_LZMA=0 V=1 + CC=clang make -j msan-test-zstd HAVE_ZLIB=0 HAVE_LZ4=0 HAVE_LZMA=0 V=1 armfuzz: runs-on: ubuntu-latest From 37077c859be9a07884283602ffbccf32bba32e95 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 18 Feb 2025 21:22:02 -0800 Subject: [PATCH 694/937] updated benchmark numbers using latest version of @inikep's lzbench --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d91ef5df1..22a127dc9 100644 --- a/README.md +++ b/README.md @@ -30,9 +30,9 @@ a list of known ports and bindings is provided on [Zstandard homepage](https://f For reference, several fast compression algorithms were tested and compared on a desktop featuring a Core i7-9700K CPU @ 4.9GHz -and running Ubuntu 20.04 (`Linux ubu20 5.15.0-101-generic`), +and running Ubuntu 24.04 (`Linux 6.8.0-53-generic`), using [lzbench], an open-source in-memory benchmark by @inikep -compiled with [gcc] 9.4.0, +compiled with [gcc] 14.2.0, on the [Silesia compression corpus]. [lzbench]: https://github.com/inikep/lzbench @@ -41,16 +41,16 @@ on the [Silesia compression corpus]. | Compressor name | Ratio | Compression| Decompress.| | --------------- | ------| -----------| ---------- | -| **zstd 1.5.6 -1** | 2.887 | 510 MB/s | 1580 MB/s | -| [zlib] 1.2.11 -1 | 2.743 | 95 MB/s | 400 MB/s | -| brotli 1.0.9 -0 | 2.702 | 395 MB/s | 430 MB/s | -| **zstd 1.5.6 --fast=1** | 2.437 | 545 MB/s | 1890 MB/s | -| **zstd 1.5.6 --fast=3** | 2.239 | 650 MB/s | 2000 MB/s | -| quicklz 1.5.0 -1 | 2.238 | 525 MB/s | 750 MB/s | -| lzo1x 2.10 -1 | 2.106 | 650 MB/s | 825 MB/s | -| [lz4] 1.9.4 | 2.101 | 700 MB/s | 4000 MB/s | -| lzf 3.6 -1 | 2.077 | 420 MB/s | 830 MB/s | -| snappy 1.1.9 | 2.073 | 530 MB/s | 1660 MB/s | +| **zstd 1.5.7 -1** | 2.896 | 510 MB/s | 1550 MB/s | +| [zlib] 1.3.1 -1 | 2.743 | 105 MB/s | 390 MB/s | +| brotli 1.1.0 -0 | 2.702 | 400 MB/s | 425 MB/s | +| **zstd 1.5.7 --fast=1** | 2.439 | 545 MB/s | 1850 MB/s | +| **zstd 1.5.7 --fast=3** | 2.241 | 635 MB/s | 1980 MB/s | +| quicklz 1.5.0 -1 | 2.238 | 520 MB/s | 750 MB/s | +| lzo1x 2.10 -1 | 2.106 | 650 MB/s | 780 MB/s | +| [lz4] 1.10.0 | 2.101 | 675 MB/s | 3850 MB/s | +| snappy 1.2.1 | 2.089 | 520 MB/s | 1500 MB/s | +| lzf 3.6 -1 | 2.077 | 410 MB/s | 820 MB/s | [zlib]: https://www.zlib.net/ [lz4]: https://lz4.github.io/lz4/ From 6af3842118ea5325480b403213b2a9fbed3d3d74 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 19 Feb 2025 16:25:00 -0800 Subject: [PATCH 695/937] updated man pages and manual fixes #4301 --- doc/zstd_manual.html | 55 ++++---- programs/zstd.1 | 292 +++++++++++++++++++++++++++++++++++-------- programs/zstdgrep.1 | 2 +- programs/zstdless.1 | 2 +- 4 files changed, 273 insertions(+), 78 deletions(-) diff --git a/doc/zstd_manual.html b/doc/zstd_manual.html index 485d5eafb..89f0761f4 100644 --- a/doc/zstd_manual.html +++ b/doc/zstd_manual.html @@ -110,6 +110,7 @@ unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize); - 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. @@ -128,9 +129,8 @@ unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);


ZSTD_DEPRECATED("Replaced by ZSTD_getFrameContentSize")
-ZSTDLIB_API
 unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
-

NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize(). +

This function is now obsolete, in favor of ZSTD_getFrameContentSize(). Both functions work the same way, but ZSTD_getDecompressedSize() blends "empty", "unknown" and "error" results to the same return value (0), while ZSTD_getFrameContentSize() gives them separate return values. @@ -142,7 +142,12 @@ unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize); `srcSize` must be >= first frame size @return : the compressed size of the first frame starting at `src`, suitable to pass as `srcSize` to `ZSTD_decompress` or similar, - or an error code if input is invalid + or an error code if input is invalid + Note 1: this method is called _find*() because it's not enough to read the header, + it may have to scan through the frame's content, to reach its end. + Note 2: this method also works with Skippable Frames. In which case, + it returns the size of the complete skippable frame, + which is always equal to its content size + 8 bytes for headers.


Compression helper functions


@@ -166,8 +171,7 @@ size_t ZSTD_compressBound(size_t srcSize);
/*!< maximum compressed size in w


-

Error helper functions

#include "zstd_errors.h" /* list of errors */
-/* ZSTD_isError() :
+

Error helper functions

/* ZSTD_isError() :
  * Most ZSTD_* functions returning a size_t value can be tested for error,
  * using ZSTD_isError().
  * @return 1 if error, 0 otherwise
@@ -1239,7 +1243,7 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
 


ZSTDLIB_STATIC_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);
-

srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX. +

srcSize must be large enough, aka >= ZSTD_FRAMEHEADERSIZE_PREFIX. @return : size of the Frame Header, or an error code (if srcSize is too small)


@@ -1252,20 +1256,20 @@ size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict); unsigned blockSizeMax; ZSTD_FrameType_e frameType;
/* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */ unsigned headerSize; - unsigned dictID; + unsigned dictID; /* for ZSTD_skippableFrame, contains the skippable magic variant [0-15] */ unsigned checksumFlag; unsigned _reserved1; unsigned _reserved2; -} ZSTD_frameHeader; +} ZSTD_FrameHeader;

-
ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
+
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) */
 ZSTDLIB_STATIC_API size_t ZSTD_getFrameHeader_advanced(ZSTD_FrameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
-

decode Frame Header, or requires larger `srcSize`. - @return : 0, `zfhPtr` is correctly filled, - >0, `srcSize` is too small, value is wanted `srcSize` amount, +

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()


@@ -1421,7 +1425,7 @@ ZSTD_compressSequences(ZSTD_CCtx* cctx, ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const ZSTD_Sequence* inSeqs, size_t nbSequences, - const void* literals, size_t litSize, size_t litCapacity, + const void* literals, size_t litSize, size_t litBufCapacity, size_t decompressedSize);

This is a variant of ZSTD_compressSequences() which, instead of receiving (src,srcSize) as input parameter, receives (literals,litSize), @@ -1435,20 +1439,22 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx, - Not compatible with frame checksum, which must be disabled - If any block is incompressible, will fail and return an error - @litSize must be == sum of all @.litLength fields in @inSeqs. Any discrepancy will generate an error. - - the buffer @literals must have a size @litCapacity which is larger than @litSize by at least 8 bytes. + - @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. @return : final compressed size, or a ZSTD error code.


ZSTDLIB_STATIC_API size_t ZSTD_writeSkippableFrame(void* dst, size_t dstCapacity,
-                                const void* src, size_t srcSize, unsigned magicVariant);
+                                 const void* src, size_t srcSize,
+                                       unsigned magicVariant);
 

Generates a zstd skippable frame containing data given by src, and writes it to dst buffer. Skippable frames begin with a 4-byte magic number. There are 16 possible choices of magic number, ranging from ZSTD_MAGIC_SKIPPABLE_START to ZSTD_MAGIC_SKIPPABLE_START+15. - As such, the parameter magicVariant controls the exact skippable frame magic number variant used, so - the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. + As such, the parameter magicVariant controls the exact skippable frame magic number variant used, + so the magic number used will be ZSTD_MAGIC_SKIPPABLE_START + magicVariant. Returns an error if destination buffer is not large enough, if the source size is not representable with a 4-byte unsigned int, or if the parameter magicVariant is greater than 15 (and therefore invalid). @@ -1457,13 +1463,14 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,


-
size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity, unsigned* magicVariant,
-                                const void* src, size_t srcSize);
-

Retrieves a zstd skippable frame containing data given by src, and writes it to dst buffer. +

ZSTDLIB_STATIC_API size_t ZSTD_readSkippableFrame(void* dst, size_t dstCapacity,
+                                      unsigned* magicVariant,
+                                      const void* src, size_t srcSize);
+

Retrieves the content of a zstd skippable frame starting at @src, and writes it to @dst buffer. - The parameter magicVariant will receive the magicVariant that was supplied when the frame was written, - i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. This can be NULL if the caller is not interested - in the magicVariant. + The parameter @magicVariant will receive the magicVariant that was supplied when the frame was written, + i.e. magicNumber - ZSTD_MAGIC_SKIPPABLE_START. + This can be NULL if the caller is not interested in the magicVariant. Returns an error if destination buffer is not large enough, or if the frame is not skippable. @@ -1471,7 +1478,7 @@ ZSTD_compressSequencesAndLiterals(ZSTD_CCtx* cctx,


-
unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size);
+
ZSTDLIB_STATIC_API unsigned ZSTD_isSkippableFrame(const void* buffer, size_t size);
 

Tells if the content of `buffer` starts with a valid Frame Identifier for a skippable frame.


diff --git a/programs/zstd.1 b/programs/zstd.1 index 5f1519f33..5503a5b86 100644 --- a/programs/zstd.1 +++ b/programs/zstd.1 @@ -1,392 +1,580 @@ -.TH "ZSTD" "1" "October 2024" "zstd 1.5.6" "User Commands" +. +.TH "ZSTD" "1" "February 2025" "zstd 1.5.7" "User Commands" +. .SH "NAME" \fBzstd\fR \- zstd, zstdmt, unzstd, zstdcat \- Compress or decompress \.zst files +. .SH "SYNOPSIS" -.TS -allbox; -\fBzstd\fR [\fIOPTIONS\fR] [\- \fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR] -.TE +\fBzstd\fR [\fIOPTIONS\fR] [\-|\fIINPUT\-FILE\fR] [\-o \fIOUTPUT\-FILE\fR] +. .P \fBzstdmt\fR is equivalent to \fBzstd \-T0\fR +. .P \fBunzstd\fR is equivalent to \fBzstd \-d\fR +. .P \fBzstdcat\fR is equivalent to \fBzstd \-dcf\fR +. .SH "DESCRIPTION" \fBzstd\fR is a fast lossless compression algorithm and data compression tool, with command line syntax similar to \fBgzip\fR(1) and \fBxz\fR(1)\. It is based on the \fBLZ77\fR family, with further FSE & huff0 entropy stages\. \fBzstd\fR offers highly configurable compression speed, from fast modes at > 200 MB/s per core, to strong modes with excellent compression ratios\. It also features a very fast decoder, with speeds > 500 MB/s per core, which remains roughly stable at all compression settings\. +. .P \fBzstd\fR command line syntax is generally similar to gzip, but features the following few differences: +. .IP "\(bu" 4 -Source files are preserved by default\. It's possible to remove them automatically by using the \fB\-\-rm\fR command\. +Source files are preserved by default\. It\'s possible to remove them automatically by using the \fB\-\-rm\fR command\. +. .IP "\(bu" 4 When compressing a single file, \fBzstd\fR displays progress notifications and result summary by default\. Use \fB\-q\fR to turn them off\. +. .IP "\(bu" 4 \fBzstd\fR displays a short help page when command line is an error\. Use \fB\-q\fR to turn it off\. +. .IP "\(bu" 4 -\fBzstd\fR does not accept input from console, though it does accept \fBstdin\fR when it's not the console\. +\fBzstd\fR does not accept input from console, though it does accept \fBstdin\fR when it\'s not the console\. +. .IP "\(bu" 4 -\fBzstd\fR does not store the input's filename or attributes, only its contents\. +\fBzstd\fR does not store the input\'s filename or attributes, only its contents\. +. .IP "" 0 +. .P \fBzstd\fR processes each \fIfile\fR according to the selected operation mode\. If no \fIfiles\fR are given or \fIfile\fR is \fB\-\fR, \fBzstd\fR reads from standard input and writes the processed data to standard output\. \fBzstd\fR will refuse to write compressed data to standard output if it is a terminal: it will display an error message and skip the file\. Similarly, \fBzstd\fR will refuse to read compressed data from standard input if it is a terminal\. +. .P Unless \fB\-\-stdout\fR or \fB\-o\fR is specified, \fIfiles\fR are written to a new file whose name is derived from the source \fIfile\fR name: +. .IP "\(bu" 4 When compressing, the suffix \fB\.zst\fR is appended to the source filename to get the target filename\. +. .IP "\(bu" 4 When decompressing, the \fB\.zst\fR suffix is removed from the source filename to get the target filename +. .IP "" 0 +. .SS "Concatenation with \.zst Files" It is possible to concatenate multiple \fB\.zst\fR files\. \fBzstd\fR will decompress such agglomerated file as if it was a single \fB\.zst\fR file\. +. .SH "OPTIONS" +. .SS "Integer Suffixes and Special Values" In most places where an integer argument is expected, an optional suffix is supported to easily indicate large integers\. There must be no space between the integer and the suffix\. +. .TP \fBKiB\fR -Multiply the integer by 1,024 (2\e^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\. +Multiply the integer by 1,024 (2^10)\. \fBKi\fR, \fBK\fR, and \fBKB\fR are accepted as synonyms for \fBKiB\fR\. +. .TP \fBMiB\fR -Multiply the integer by 1,048,576 (2\e^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\. +Multiply the integer by 1,048,576 (2^20)\. \fBMi\fR, \fBM\fR, and \fBMB\fR are accepted as synonyms for \fBMiB\fR\. +. .SS "Operation Mode" If multiple operation mode options are given, the last one takes effect\. +. .TP \fB\-z\fR, \fB\-\-compress\fR Compress\. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, \fBunzstd\fR implies \fB\-\-decompress\fR)\. +. .TP \fB\-d\fR, \fB\-\-decompress\fR, \fB\-\-uncompress\fR Decompress\. +. .TP \fB\-t\fR, \fB\-\-test\fR Test the integrity of compressed \fIfiles\fR\. This option is equivalent to \fB\-\-decompress \-\-stdout > /dev/null\fR, decompressed data is discarded and checksummed for errors\. No files are created or removed\. +. .TP \fB\-b#\fR Benchmark file(s) using compression level \fI#\fR\. See \fIBENCHMARK\fR below for a description of this operation\. +. .TP \fB\-\-train FILES\fR Use \fIFILES\fR as a training set to create a dictionary\. The training set should contain a lot of small files (> 100)\. See \fIDICTIONARY BUILDER\fR below for a description of this operation\. +. .TP \fB\-l\fR, \fB\-\-list\fR -Display information related to a zstd compressed file, such as size, ratio, and checksum\. Some of these fields may not be available\. This command's output can be augmented with the \fB\-v\fR modifier\. +Display information related to a zstd compressed file, such as size, ratio, and checksum\. Some of these fields may not be available\. This command\'s output can be augmented with the \fB\-v\fR modifier\. +. .SS "Operation Modifiers" +. .IP "\(bu" 4 -\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)\. Higher compression levels \fIgenerally\fR produce higher compression ratio at the expense of speed and memory\. A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels\. Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below)\. Because the compressor's behavior highly depends on the content to compress, there's no guarantee of a smooth progression from one level to another\. +\fB\-#\fR: selects \fB#\fR compression level [1\-19] (default: 3)\. Higher compression levels \fIgenerally\fR produce higher compression ratio at the expense of speed and memory\. A rough rule of thumb is that compression speed is expected to be divided by 2 every 2 levels\. Technically, each level is mapped to a set of advanced parameters (that can also be modified individually, see below)\. Because the compressor\'s behavior highly depends on the content to compress, there\'s no guarantee of a smooth progression from one level to another\. +. .IP "\(bu" 4 \fB\-\-ultra\fR: unlocks high compression levels 20+ (maximum 22), using a lot more memory\. Note that decompression will also require more memory when using these levels\. +. .IP "\(bu" 4 \fB\-\-fast[=#]\fR: switch to ultra\-fast compression levels\. If \fB=#\fR is not present, it defaults to \fB1\fR\. The higher the value, the faster the compression speed, at the cost of some compression ratio\. This setting overwrites compression level if one was set previously\. Similarly, if a compression level is set after \fB\-\-fast\fR, it overrides it\. +. .IP "\(bu" 4 \fB\-T#\fR, \fB\-\-threads=#\fR: Compress using \fB#\fR working threads (default: 1)\. If \fB#\fR is 0, attempt to detect and use the number of physical CPU cores\. In all cases, the nb of threads is capped to \fBZSTDMT_NBWORKERS_MAX\fR, which is either 64 in 32\-bit mode, or 256 for 64\-bit environments\. This modifier does nothing if \fBzstd\fR is compiled without multithread support\. +. .IP "\(bu" 4 \fB\-\-single\-thread\fR: Use a single thread for both I/O and compression\. As compression is serialized with I/O, this can be slightly slower\. Single\-thread mode features significantly lower memory usage, which can be useful for systems with limited amount of memory, such as 32\-bit systems\. +. .IP Note 1: this mode is the only available one when multithread support is disabled\. +. .IP Note 2: this mode is different from \fB\-T1\fR, which spawns 1 compression thread in parallel with I/O\. Final compressed result is also slightly different from \fB\-T1\fR\. +. .IP "\(bu" 4 \fB\-\-auto\-threads={physical,logical} (default: physical)\fR: When using a default amount of threads via \fB\-T0\fR, choose the default based on the number of detected physical or logical cores\. +. .IP "\(bu" 4 \fB\-\-adapt[=min=#,max=#]\fR: \fBzstd\fR will dynamically adapt compression level to perceived I/O conditions\. Compression level adaptation can be observed live by using command \fB\-v\fR\. Adaptation can be constrained between supplied \fBmin\fR and \fBmax\fR levels\. The feature works when combined with multi\-threading and \fB\-\-long\fR mode\. It does not work with \fB\-\-single\-thread\fR\. It sets window size to 8 MiB by default (can be changed manually, see \fBwlog\fR)\. Due to the chaotic nature of dynamic adaptation, compressed result is not reproducible\. +. .IP \fINote\fR: at the time of this writing, \fB\-\-adapt\fR can remain stuck at low speed when combined with multiple worker threads (>=2)\. +. .IP "\(bu" 4 \fB\-\-long[=#]\fR: enables long distance matching with \fB#\fR \fBwindowLog\fR, if \fB#\fR is not present it defaults to \fB27\fR\. This increases the window size (\fBwindowLog\fR) and memory usage for both the compressor and decompressor\. This setting is designed to improve the compression ratio for files with long matches at a large distance\. +. .IP Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\. +. +.IP "\(bu" 4 +\fB\-\-max\fR: set advanced parameters to maximum compression\. warning: this setting is very slow and uses a lot of resources\. It\'s inappropriate for 32\-bit mode and therefore disabled in this mode\. +. .IP "\(bu" 4 \fB\-D DICT\fR: use \fBDICT\fR as Dictionary to compress or decompress FILE(s) +. .IP "\(bu" 4 -\fB\-\-patch\-from FILE\fR: Specify the file to be used as a reference point for zstd's diff engine\. This is effectively dictionary compression with some convenient parameter selection, namely that \fIwindowSize\fR > \fIsrcSize\fR\. +\fB\-\-patch\-from FILE\fR: Specify the file to be used as a reference point for zstd\'s diff engine\. This is effectively dictionary compression with some convenient parameter selection, namely that \fIwindowSize\fR > \fIsrcSize\fR\. +. .IP Note: cannot use both this and \fB\-D\fR together\. +. .IP Note: \fB\-\-long\fR mode will be automatically activated if \fIchainLog\fR < \fIfileLog\fR (\fIfileLog\fR being the \fIwindowLog\fR required to cover the whole file)\. You can also manually force it\. +. .IP -Note: up to level 15, you can use \fB\-\-patch\-from\fR in \fB\-\-single\-thread\fR mode to improve compression ratio marginally at the cost of speed\. Using '\-\-single\-thread' above level 15 will lead to lower compression ratios\. +Note: up to level 15, you can use \fB\-\-patch\-from\fR in \fB\-\-single\-thread\fR mode to improve compression ratio marginally at the cost of speed\. Using \'\-\-single\-thread\' above level 15 will lead to lower compression ratios\. +. .IP Note: for level 19, you can get increased compression ratio at the cost of speed by specifying \fB\-\-zstd=targetLength=\fR to be something large (i\.e\. 4096), and by setting a large \fB\-\-zstd=chainLog=\fR\. +. .IP "\(bu" 4 -\fB\-\-rsyncable\fR: \fBzstd\fR will periodically synchronize the compression state to make the compressed file more rsync\-friendly\. There is a negligible impact to compression ratio, and a potential impact to compression speed, perceptible at higher speeds, for example when combining \fB\-\-rsyncable\fR with many parallel worker threads\. This feature does not work with \fB\-\-single\-thread\fR\. You probably don't want to use it with long range mode, since it will decrease the effectiveness of the synchronization points, but your mileage may vary\. +\fB\-\-rsyncable\fR: \fBzstd\fR will periodically synchronize the compression state to make the compressed file more rsync\-friendly\. There is a negligible impact to compression ratio, and a potential impact to compression speed, perceptible at higher speeds, for example when combining \fB\-\-rsyncable\fR with many parallel worker threads\. This feature does not work with \fB\-\-single\-thread\fR\. You probably don\'t want to use it with long range mode, since it will decrease the effectiveness of the synchronization points, but your mileage may vary\. +. .IP "\(bu" 4 \fB\-C\fR, \fB\-\-[no\-]check\fR: add integrity check computed from uncompressed data (default: enabled) +. .IP "\(bu" 4 \fB\-\-[no\-]content\-size\fR: enable / disable whether or not the original size of the file is placed in the header of the compressed file\. The default option is \fB\-\-content\-size\fR (meaning that the original size will be placed in the header)\. +. .IP "\(bu" 4 -\fB\-\-no\-dictID\fR: do not store dictionary ID within frame header (dictionary compression)\. The decoder will have to rely on implicit knowledge about which dictionary to use, it won't be able to check if it's correct\. +\fB\-\-no\-dictID\fR: do not store dictionary ID within frame header (dictionary compression)\. The decoder will have to rely on implicit knowledge about which dictionary to use, it won\'t be able to check if it\'s correct\. +. .IP "\(bu" 4 \fB\-M#\fR, \fB\-\-memory=#\fR: Set a memory usage limit\. By default, \fBzstd\fR uses 128 MiB for decompression as the maximum amount of memory the decompressor is allowed to use, but you can override this manually if need be in either direction (i\.e\. you can increase or decrease it)\. +. .IP This is also used during compression when using with \fB\-\-patch\-from=\fR\. In this case, this parameter overrides that maximum size allowed for a dictionary\. (128 MiB)\. +. .IP Additionally, this can be used to limit memory for dictionary training\. This parameter overrides the default limit of 2 GiB\. zstd will load training samples up to the memory limit and ignore the rest\. +. .IP "\(bu" 4 \fB\-\-stream\-size=#\fR: Sets the pledged source size of input coming from a stream\. This value must be exact, as it will be included in the produced frame header\. Incorrect stream sizes will cause an error\. This information will be used to better optimize compression parameters, resulting in better and potentially faster compression, especially for smaller source sizes\. +. .IP "\(bu" 4 \fB\-\-size\-hint=#\fR: When handling input from a stream, \fBzstd\fR must guess how large the source size will be when optimizing compression parameters\. If the stream size is relatively small, this guess may be a poor one, resulting in a higher compression ratio than expected\. This feature allows for controlling the guess when needed\. Exact guesses result in better compression ratios\. Overestimates result in slightly degraded compression ratios, while underestimates may result in significant degradation\. +. .IP "\(bu" 4 \fB\-\-target\-compressed\-block\-size=#\fR: Attempt to produce compressed blocks of approximately this size\. This will split larger blocks in order to approach this target\. This feature is notably useful for improved latency, when the receiver can leverage receiving early incomplete data\. This parameter defines a loose target: compressed blocks will target this size "on average", but individual blocks can still be larger or smaller\. Enabling this feature can decrease compression speed by up to ~10% at level 1\. Higher levels will see smaller relative speed regression, becoming invisible at higher settings\. +. .IP "\(bu" 4 \fB\-f\fR, \fB\-\-force\fR: disable input and output checks\. Allows overwriting existing files, input from console, output to stdout, operating on links, block devices, etc\. During decompression and when the output destination is stdout, pass\-through unrecognized formats as\-is\. +. .IP "\(bu" 4 \fB\-c\fR, \fB\-\-stdout\fR: write to standard output (even if it is the console); keep original files (disable \fB\-\-rm\fR)\. +. .IP "\(bu" 4 \fB\-o FILE\fR: save result into \fBFILE\fR\. Note that this operation is in conflict with \fB\-c\fR\. If both operations are present on the command line, the last expressed one wins\. +. .IP "\(bu" 4 \fB\-\-[no\-]sparse\fR: enable / disable sparse FS support, to make files with many zeroes smaller on disk\. Creating sparse files may save disk space and speed up decompression by reducing the amount of disk I/O\. default: enabled when output is into a file, and disabled when output is stdout\. This setting overrides default and can force sparse mode over stdout\. +. .IP "\(bu" 4 \fB\-\-[no\-]pass\-through\fR enable / disable passing through uncompressed files as\-is\. During decompression when pass\-through is enabled, unrecognized formats will be copied as\-is from the input to the output\. By default, pass\-through will occur when the output destination is stdout and the force (\fB\-f\fR) option is set\. +. .IP "\(bu" 4 \fB\-\-rm\fR: remove source file(s) after successful compression or decompression\. This command is silently ignored if output is \fBstdout\fR\. If used in combination with \fB\-o\fR, triggers a confirmation prompt (which can be silenced with \fB\-f\fR), as this is a destructive operation\. +. .IP "\(bu" 4 \fB\-k\fR, \fB\-\-keep\fR: keep source file(s) after successful compression or decompression\. This is the default behavior\. +. .IP "\(bu" 4 \fB\-r\fR: operate recursively on directories\. It selects all files in the named directory and all its subdirectories\. This can be useful both to reduce command line typing, and to circumvent shell expansion limitations, when there are a lot of files and naming breaks the maximum size of a command line\. +. .IP "\(bu" 4 \fB\-\-filelist FILE\fR read a list of files to process as content from \fBFILE\fR\. Format is compatible with \fBls\fR output, with one file per line\. +. .IP "\(bu" 4 \fB\-\-output\-dir\-flat DIR\fR: resulting files are stored into target \fBDIR\fR directory, instead of same directory as origin file\. Be aware that this command can introduce name collision issues, if multiple files, from different directories, end up having the same name\. Collision resolution ensures first file with a given name will be present in \fBDIR\fR, while in combination with \fB\-f\fR, the last file will be present instead\. +. .IP "\(bu" 4 \fB\-\-output\-dir\-mirror DIR\fR: similar to \fB\-\-output\-dir\-flat\fR, the output files are stored underneath target \fBDIR\fR directory, but this option will replicate input directory hierarchy into output \fBDIR\fR\. +. .IP If input directory contains "\.\.", the files in this directory will be ignored\. If input directory is an absolute directory (i\.e\. "/var/tmp/abc"), it will be stored into the "output\-dir/var/tmp/abc"\. If there are multiple input files or directories, name collision resolution will follow the same rules as \fB\-\-output\-dir\-flat\fR\. +. .IP "\(bu" 4 \fB\-\-format=FORMAT\fR: compress and decompress in other formats\. If compiled with support, zstd can compress to or decompress from other compression algorithm formats\. Possibly available options are \fBzstd\fR, \fBgzip\fR, \fBxz\fR, \fBlzma\fR, and \fBlz4\fR\. If no such format is provided, \fBzstd\fR is the default\. +. .IP "\(bu" 4 \fB\-h\fR/\fB\-H\fR, \fB\-\-help\fR: display help/long help and exit +. .IP "\(bu" 4 \fB\-V\fR, \fB\-\-version\fR: display version number and immediately exit\. note that, since it exits, flags specified after \fB\-V\fR are effectively ignored\. Advanced: \fB\-vV\fR also displays supported formats\. \fB\-vvV\fR also displays POSIX support\. \fB\-qV\fR will only display the version number, suitable for machine reading\. +. .IP "\(bu" 4 \fB\-v\fR, \fB\-\-verbose\fR: verbose mode, display more information +. .IP "\(bu" 4 \fB\-q\fR, \fB\-\-quiet\fR: suppress warnings, interactivity, and notifications\. specify twice to suppress errors too\. +. .IP "\(bu" 4 \fB\-\-no\-progress\fR: do not display the progress bar, but keep all other messages\. +. .IP "\(bu" 4 \fB\-\-show\-default\-cparams\fR: shows the default compression parameters that will be used for a particular input file, based on the provided compression level and the input size\. If the provided file is not a regular file (e\.g\. a pipe), this flag will output the parameters used for inputs of unknown size\. +. .IP "\(bu" 4 \fB\-\-exclude\-compressed\fR: only compress files that are not already compressed\. +. .IP "\(bu" 4 \fB\-\-\fR: All arguments after \fB\-\-\fR are treated as files +. .IP "" 0 +. .SS "gzip Operation Modifiers" When invoked via a \fBgzip\fR symlink, \fBzstd\fR will support further options that intend to mimic the \fBgzip\fR behavior: +. .TP \fB\-n\fR, \fB\-\-no\-name\fR do not store the original filename and timestamps when compressing a file\. This is the default behavior and hence a no\-op\. +. .TP \fB\-\-best\fR alias to the option \fB\-9\fR\. +. .SS "Environment Variables" Employing environment variables to set parameters has security implications\. Therefore, this avenue is intentionally limited\. Only \fBZSTD_CLEVEL\fR and \fBZSTD_NBTHREADS\fR are currently supported\. They set the default compression level and number of threads to use during compression, respectively\. +. .P \fBZSTD_CLEVEL\fR can be used to set the level between 1 and 19 (the "normal" range)\. If the value of \fBZSTD_CLEVEL\fR is not a valid integer, it will be ignored with a warning message\. \fBZSTD_CLEVEL\fR just replaces the default compression level (\fB3\fR)\. +. .P -\fBZSTD_NBTHREADS\fR can be used to set the number of threads \fBzstd\fR will attempt to use during compression\. If the value of \fBZSTD_NBTHREADS\fR is not a valid unsigned integer, it will be ignored with a warning message\. \fBZSTD_NBTHREADS\fR has a default value of (\fB1\fR), and is capped at ZSTDMT_NBWORKERS_MAX==200\. \fBzstd\fR must be compiled with multithread support for this variable to have any effect\. +\fBZSTD_NBTHREADS\fR can be used to set the number of threads \fBzstd\fR will attempt to use during compression\. If the value of \fBZSTD_NBTHREADS\fR is not a valid unsigned integer, it will be ignored with a warning message\. \fBZSTD_NBTHREADS\fR has a default value of \fBmax(1, min(4, nbCores/4))\fR, and is capped at ZSTDMT_NBWORKERS_MAX==200\. \fBzstd\fR must be compiled with multithread support for this variable to have any effect\. +. .P They can both be overridden by corresponding command line arguments: \fB\-#\fR for compression level and \fB\-T#\fR for number of compression threads\. +. .SH "ADVANCED COMPRESSION OPTIONS" \fBzstd\fR provides 22 predefined regular compression levels plus the fast levels\. A compression level is translated internally into multiple advanced parameters that control the behavior of the compressor (one can observe the result of this translation with \fB\-\-show\-default\-cparams\fR)\. These advanced parameters can be overridden using advanced compression options\. +. .SS "\-\-zstd[=options]:" The \fIoptions\fR are provided as a comma\-separated list\. You may specify only the options you want to change and the rest will be taken from the selected or default compression level\. The list of available \fIoptions\fR: +. .TP \fBstrategy\fR=\fIstrat\fR, \fBstrat\fR=\fIstrat\fR Specify a strategy used by a match finder\. +. .IP There are 9 strategies numbered from 1 to 9, from fastest to strongest: 1=\fBZSTD_fast\fR, 2=\fBZSTD_dfast\fR, 3=\fBZSTD_greedy\fR, 4=\fBZSTD_lazy\fR, 5=\fBZSTD_lazy2\fR, 6=\fBZSTD_btlazy2\fR, 7=\fBZSTD_btopt\fR, 8=\fBZSTD_btultra\fR, 9=\fBZSTD_btultra2\fR\. +. .TP \fBwindowLog\fR=\fIwlog\fR, \fBwlog\fR=\fIwlog\fR Specify the maximum number of bits for a match distance\. +. .IP The higher number of increases the chance to find a match which usually improves compression ratio\. It also increases memory requirements for the compressor and decompressor\. The minimum \fIwlog\fR is 10 (1 KiB) and the maximum is 30 (1 GiB) on 32\-bit platforms and 31 (2 GiB) on 64\-bit platforms\. +. .IP Note: If \fBwindowLog\fR is set to larger than 27, \fB\-\-long=windowLog\fR or \fB\-\-memory=windowSize\fR needs to be passed to the decompressor\. +. .TP \fBhashLog\fR=\fIhlog\fR, \fBhlog\fR=\fIhlog\fR Specify the maximum number of bits for a hash table\. +. .IP Bigger hash tables cause fewer collisions which usually makes compression faster, but requires more memory during compression\. +. .IP The minimum \fIhlog\fR is 6 (64 entries / 256 B) and the maximum is 30 (1B entries / 4 GiB)\. +. .TP \fBchainLog\fR=\fIclog\fR, \fBclog\fR=\fIclog\fR Specify the maximum number of bits for the secondary search structure, whose form depends on the selected \fBstrategy\fR\. +. .IP Higher numbers of bits increases the chance to find a match which usually improves compression ratio\. It also slows down compression speed and increases memory requirements for compression\. This option is ignored for the \fBZSTD_fast\fR \fBstrategy\fR, which only has the primary hash table\. +. .IP The minimum \fIclog\fR is 6 (64 entries / 256 B) and the maximum is 29 (512M entries / 2 GiB) on 32\-bit platforms and 30 (1B entries / 4 GiB) on 64\-bit platforms\. +. .TP \fBsearchLog\fR=\fIslog\fR, \fBslog\fR=\fIslog\fR Specify the maximum number of searches in a hash chain or a binary tree using logarithmic scale\. +. .IP More searches increases the chance to find a match which usually increases compression ratio but decreases compression speed\. +. .IP -The minimum \fIslog\fR is 1 and the maximum is 'windowLog' \- 1\. +The minimum \fIslog\fR is 1 and the maximum is \'windowLog\' \- 1\. +. .TP \fBminMatch\fR=\fImml\fR, \fBmml\fR=\fImml\fR Specify the minimum searched length of a match in a hash table\. +. .IP Larger search lengths usually decrease compression ratio but improve decompression speed\. +. .IP The minimum \fImml\fR is 3 and the maximum is 7\. +. .TP \fBtargetLength\fR=\fItlen\fR, \fBtlen\fR=\fItlen\fR The impact of this field vary depending on selected strategy\. +. .IP For \fBZSTD_btopt\fR, \fBZSTD_btultra\fR and \fBZSTD_btultra2\fR, it specifies the minimum match length that causes match finder to stop searching\. A larger \fBtargetLength\fR usually improves compression ratio but decreases compression speed\. +. .IP For \fBZSTD_fast\fR, it triggers ultra\-fast mode when > 0\. The value represents the amount of data skipped between match sampling\. Impact is reversed: a larger \fBtargetLength\fR increases compression speed but decreases compression ratio\. +. .IP For all other strategies, this field has no impact\. +. .IP The minimum \fItlen\fR is 0 and the maximum is 128 KiB\. +. .TP \fBoverlapLog\fR=\fIovlog\fR, \fBovlog\fR=\fIovlog\fR Determine \fBoverlapSize\fR, amount of data reloaded from previous job\. This parameter is only available when multithreading is enabled\. Reloading more data improves compression ratio, but decreases speed\. +. .IP The minimum \fIovlog\fR is 0, and the maximum is 9\. 1 means "no overlap", hence completely independent jobs\. 9 means "full overlap", meaning up to \fBwindowSize\fR is reloaded from previous job\. Reducing \fIovlog\fR by 1 reduces the reloaded amount by a factor 2\. For example, 8 means "windowSize/2", and 6 means "windowSize/8"\. Value 0 is special and means "default": \fIovlog\fR is automatically determined by \fBzstd\fR\. In which case, \fIovlog\fR will range from 6 to 9, depending on selected \fIstrat\fR\. -.TP -\fBldmHashLog\fR=\fIlhlog\fR, \fBlhlog\fR=\fIlhlog\fR -Specify the maximum size for a hash table used for long distance matching\. -.IP -This option is ignored unless long distance matching is enabled\. -.IP -Bigger hash tables usually improve compression ratio at the expense of more memory during compression and a decrease in compression speed\. -.IP -The minimum \fIlhlog\fR is 6 and the maximum is 30 (default: 20)\. -.TP -\fBldmMinMatch\fR=\fIlmml\fR, \fBlmml\fR=\fIlmml\fR -Specify the minimum searched length of a match for long distance matching\. -.IP -This option is ignored unless long distance matching is enabled\. -.IP -Larger/very small values usually decrease compression ratio\. -.IP -The minimum \fIlmml\fR is 4 and the maximum is 4096 (default: 64)\. -.TP -\fBldmBucketSizeLog\fR=\fIlblog\fR, \fBlblog\fR=\fIlblog\fR -Specify the size of each bucket for the hash table used for long distance matching\. -.IP -This option is ignored unless long distance matching is enabled\. -.IP -Larger bucket sizes improve collision resolution but decrease compression speed\. -.IP -The minimum \fIlblog\fR is 1 and the maximum is 8 (default: 3)\. +. .TP \fBldmHashRateLog\fR=\fIlhrlog\fR, \fBlhrlog\fR=\fIlhrlog\fR Specify the frequency of inserting entries into the long distance matching hash table\. +. .IP This option is ignored unless long distance matching is enabled\. +. .IP Larger values will improve compression speed\. Deviating far from the default value will likely result in a decrease in compression ratio\. +. .IP -The default value is \fBwlog \- lhlog\fR\. +The default value varies between 4 and 7, depending on \fBstrategy\fR\. +. +.TP +\fBldmHashLog\fR=\fIlhlog\fR, \fBlhlog\fR=\fIlhlog\fR +Specify the maximum size for a hash table used for long distance matching\. +. +.IP +This option is ignored unless long distance matching is enabled\. +. +.IP +Bigger hash tables usually improve compression ratio at the expense of more memory during compression and a decrease in compression speed\. +. +.IP +The minimum \fIlhlog\fR is 6 and the maximum is 30 (default: \fBwindowLog \- ldmHashRateLog\fR)\. +. +.TP +\fBldmMinMatch\fR=\fIlmml\fR, \fBlmml\fR=\fIlmml\fR +Specify the minimum searched length of a match for long distance matching\. +. +.IP +This option is ignored unless long distance matching is enabled\. +. +.IP +Larger/very small values usually decrease compression ratio\. +. +.IP +The minimum \fIlmml\fR is 4 and the maximum is 4096 (default: 32 to 64, depending on \fBstrategy\fR)\. +. +.TP +\fBldmBucketSizeLog\fR=\fIlblog\fR, \fBlblog\fR=\fIlblog\fR +Specify the size of each bucket for the hash table used for long distance matching\. +. +.IP +This option is ignored unless long distance matching is enabled\. +. +.IP +Larger bucket sizes improve collision resolution but decrease compression speed\. +. +.IP +The minimum \fIlblog\fR is 1 and the maximum is 8 (default: 4 to 8, depending on \fBstrategy\fR)\. +. .SS "Example" The following parameters sets advanced compression options to something similar to predefined level 19 for files bigger than 256 KB: +. .P \fB\-\-zstd\fR=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6 +. .SS "\-B#:" Specify the size of each compression job\. This parameter is only available when multi\-threading is enabled\. Each compression job is run in parallel, so this value indirectly impacts the nb of active threads\. Default job size varies depending on compression level (generally \fB4 * windowSize\fR)\. \fB\-B#\fR makes it possible to manually select a custom size\. Note that job size must respect a minimum value which is enforced transparently\. This minimum is either 512 KB, or \fBoverlapSize\fR, whichever is largest\. Different job sizes will lead to non\-identical compressed frames\. +. .SH "DICTIONARY BUILDER" -\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It's possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\. +\fBzstd\fR offers \fIdictionary\fR compression, which greatly improves efficiency on small files and messages\. It\'s possible to train \fBzstd\fR with a set of samples, the result of which is saved into a file called a \fBdictionary\fR\. Then, during compression and decompression, reference the same dictionary, using command \fB\-D dictionaryFileName\fR\. Compression of small files similar to the sample set will be greatly improved\. +. .TP \fB\-\-train FILEs\fR Use FILEs as training set to create a dictionary\. The training set should ideally contain a lot of samples (> 100), and weight typically 100x the target dictionary size (for example, ~10 MB for a 100 KB dictionary)\. \fB\-\-train\fR can be combined with \fB\-r\fR to indicate a directory rather than listing all the files, which can be useful to circumvent shell expansion limits\. +. .IP Since dictionary compression is mostly effective for small files, the expectation is that the training set will only contain small files\. In the case where some samples happen to be large, only the first 128 KiB of these samples will be used for training\. +. .IP \fB\-\-train\fR supports multithreading if \fBzstd\fR is compiled with threading support (default)\. Additional advanced parameters can be specified with \fB\-\-train\-fastcover\fR\. The legacy dictionary builder can be accessed with \fB\-\-train\-legacy\fR\. The slower cover dictionary builder can be accessed with \fB\-\-train\-cover\fR\. Default \fB\-\-train\fR is equivalent to \fB\-\-train\-fastcover=d=8,steps=4\fR\. +. .TP \fB\-o FILE\fR Dictionary saved into \fBFILE\fR (default name: dictionary)\. +. .TP \fB\-\-maxdict=#\fR -Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it's possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\. +Limit dictionary to specified size (default: 112640 bytes)\. As usual, quantities are expressed in bytes by default, and it\'s possible to employ suffixes (like \fBKB\fR or \fBMB\fR) to specify larger values\. +. .TP \fB\-#\fR Use \fB#\fR compression level during training (optional)\. Will generate statistics more tuned for selected compression level, resulting in a \fIsmall\fR compression ratio improvement for this level\. +. .TP \fB\-B#\fR Split input files into blocks of size # (default: no split) +. .TP \fB\-M#\fR, \fB\-\-memory=#\fR Limit the amount of sample data loaded for training (default: 2 GB)\. Note that the default (2 GB) is also the maximum\. This parameter can be useful in situations where the training set size is not well controlled and could be potentially very large\. Since speed of the training process is directly correlated to the size of the training sample set, a smaller sample set leads to faster training\. +. .IP In situations where the training set is larger than maximum memory, the CLI will randomly select samples among the available ones, up to the maximum allowed memory budget\. This is meant to improve dictionary relevance by mitigating the potential impact of clustering, such as selecting only files from the beginning of a list sorted by modification date, or sorted by alphabetical order\. The randomization process is deterministic, so training of the same list of files with the same parameters will lead to the creation of the same dictionary\. +. .TP \fB\-\-dictID=#\fR -A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It's possible to provide an explicit number ID instead\. It's up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\. +A dictionary ID is a locally unique ID\. The decoder will use this value to verify it is using the right dictionary\. By default, zstd will create a 4\-bytes random number ID\. It\'s possible to provide an explicit number ID instead\. It\'s up to the dictionary manager to not assign twice the same ID to 2 different dictionaries\. Note that short numbers have an advantage: an ID < 256 will only need 1 byte in the compressed frame header, and an ID < 65536 will only need 2 bytes\. This compares favorably to 4 bytes default\. +. .IP -Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2\e^31, so they should not be used in public\. +Note that RFC8878 reserves IDs less than 32768 and greater than or equal to 2^31, so they should not be used in public\. +. .TP \fB\-\-train\-cover[=k#,d=#,steps=#,split=#,shrink[=#]]\fR Select parameters for the default dictionary builder algorithm named cover\. If \fId\fR is not specified, then it tries \fId\fR = 6 and \fId\fR = 8\. If \fIk\fR is not specified, then it tries \fIsteps\fR values in the range [50, 2000]\. If \fIsteps\fR is not specified, then the default value of 40 is used\. If \fIsplit\fR is not specified or split <= 0, then the default value of 100 is used\. Requires that \fId\fR <= \fIk\fR\. If \fIshrink\fR flag is not used, then the default value for \fIshrinkDict\fR of 0 is used\. If \fIshrink\fR is not specified, then the default value for \fIshrinkDictMaxRegression\fR of 1 is used\. +. .IP Selects segments of size \fIk\fR with highest score to put in the dictionary\. The score of a segment is computed by the sum of the frequencies of all the subsegments of size \fId\fR\. Generally \fId\fR should be in the range [6, 8], occasionally up to 16, but the algorithm will run faster with d <= \fI8\fR\. Good values for \fIk\fR vary widely based on the input data, but a safe range is [2 * \fId\fR, 2000]\. If \fIsplit\fR is 100, all input samples are used for both training and testing to find optimal \fId\fR and \fIk\fR to build dictionary\. Supports multithreading if \fBzstd\fR is compiled with threading support\. Having \fIshrink\fR enabled takes a truncated dictionary of minimum size and doubles in size until compression ratio of the truncated dictionary is at most \fIshrinkDictMaxRegression%\fR worse than the compression ratio of the largest dictionary\. +. .IP Examples: +. .IP \fBzstd \-\-train\-cover FILEs\fR +. .IP \fBzstd \-\-train\-cover=k=50,d=8 FILEs\fR +. .IP \fBzstd \-\-train\-cover=d=8,steps=500 FILEs\fR +. .IP \fBzstd \-\-train\-cover=k=50 FILEs\fR +. .IP \fBzstd \-\-train\-cover=k=50,split=60 FILEs\fR +. .IP \fBzstd \-\-train\-cover=shrink FILEs\fR +. .IP \fBzstd \-\-train\-cover=shrink=2 FILEs\fR +. .TP \fB\-\-train\-fastcover[=k#,d=#,f=#,steps=#,split=#,accel=#]\fR Same as cover but with extra parameters \fIf\fR and \fIaccel\fR and different default value of split If \fIsplit\fR is not specified, then it tries \fIsplit\fR = 75\. If \fIf\fR is not specified, then it tries \fIf\fR = 20\. Requires that 0 < \fIf\fR < 32\. If \fIaccel\fR is not specified, then it tries \fIaccel\fR = 1\. Requires that 0 < \fIaccel\fR <= 10\. Requires that \fId\fR = 6 or \fId\fR = 8\. +. .IP \fIf\fR is log of size of array that keeps track of frequency of subsegments of size \fId\fR\. The subsegment is hashed to an index in the range [0,2^\fIf\fR \- 1]\. It is possible that 2 different subsegments are hashed to the same index, and they are considered as the same subsegment when computing frequency\. Using a higher \fIf\fR reduces collision but takes longer\. +. .IP Examples: +. .IP \fBzstd \-\-train\-fastcover FILEs\fR +. .IP \fBzstd \-\-train\-fastcover=d=8,f=15,accel=2 FILEs\fR +. .TP \fB\-\-train\-legacy[=selectivity=#]\fR Use legacy dictionary builder algorithm with the given dictionary \fIselectivity\fR (default: 9)\. The smaller the \fIselectivity\fR value, the denser the dictionary, improving its efficiency but reducing its achievable maximum size\. \fB\-\-train\-legacy=s=#\fR is also accepted\. +. .IP Examples: +. .IP \fBzstd \-\-train\-legacy FILEs\fR +. .IP \fBzstd \-\-train\-legacy=selectivity=8 FILEs\fR +. .SH "BENCHMARK" -The \fBzstd\fR CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer's performance\. \fBzstd \-b [FILE(s)]\fR will benchmark \fBzstd\fR for both compression and decompression using default compression level\. Note that results are very dependent on the content being compressed\. It's possible to pass multiple files to the benchmark, and even a directory with \fB\-r DIRECTORY\fR\. When no \fBFILE\fR is provided, the benchmark will use a procedurally generated \fBlorem ipsum\fR text\. +The \fBzstd\fR CLI provides a benchmarking mode that can be used to easily find suitable compression parameters, or alternatively to benchmark a computer\'s performance\. \fBzstd \-b [FILE(s)]\fR will benchmark \fBzstd\fR for both compression and decompression using default compression level\. Note that results are very dependent on the content being compressed\. +. +.P +It\'s possible to pass multiple files to the benchmark, and even a directory with \fB\-r DIRECTORY\fR\. When no \fBFILE\fR is provided, the benchmark will use a procedurally generated \fBlorem ipsum\fR text\. +. +.P +Benchmarking will employ \fBmax(1, min(4, nbCores/4))\fR worker threads by default in order to match the behavior of the normal CLI I/O\. +. .IP "\(bu" 4 \fB\-b#\fR: benchmark file(s) using compression level # +. .IP "\(bu" 4 \fB\-e#\fR: benchmark file(s) using multiple compression levels, from \fB\-b#\fR to \fB\-e#\fR (inclusive) +. .IP "\(bu" 4 \fB\-d\fR: benchmark decompression speed only (requires providing a zstd\-compressed content) +. .IP "\(bu" 4 \fB\-i#\fR: minimum evaluation time, in seconds (default: 3s), benchmark mode only +. .IP "\(bu" 4 \fB\-B#\fR, \fB\-\-block\-size=#\fR: cut file(s) into independent chunks of size # (default: no chunking) +. .IP "\(bu" 4 \fB\-S\fR: output one benchmark result per input file (default: consolidated result) +. .IP "\(bu" 4 \fB\-D dictionary\fR benchmark using dictionary +. .IP "\(bu" 4 \fB\-\-priority=rt\fR: set process priority to real\-time (Windows) +. .IP "" 0 +. .P Beyond compression levels, benchmarking is also compatible with other parameters, such as number of threads (\fB\-T#\fR), advanced compression parameters (\fB\-\-zstd=###\fR), dictionary compression (\fB\-D dictionary\fR), or even disabling checksum verification for example\. +. .P \fBOutput Format:\fR CompressionLevel#Filename: InputSize \-> OutputSize (CompressionRatio), CompressionSpeed, DecompressionSpeed +. .P \fBMethodology:\fR For speed measurement, the entire input is compressed/decompressed in\-memory to measure speed\. A run lasts at least 1 sec, so when files are small, they are compressed/decompressed several times per run, in order to improve measurement accuracy\. +. .SH "SEE ALSO" \fBzstdgrep\fR(1), \fBzstdless\fR(1), \fBgzip\fR(1), \fBxz\fR(1) +. .P -The \fIzstandard\fR format is specified in Y\. Collet, "Zstandard Compression and the 'application/zstd' Media Type", https://www\.ietf\.org/rfc/rfc8878\.txt, Internet RFC 8878 (February 2021)\. +The \fIzstandard\fR format is specified in Y\. Collet, "Zstandard Compression and the \'application/zstd\' Media Type", https://www\.ietf\.org/rfc/rfc8878\.txt, Internet RFC 8878 (February 2021)\. +. .SH "BUGS" Report bugs at: https://github\.com/facebook/zstd/issues +. .SH "AUTHOR" Yann Collet diff --git a/programs/zstdgrep.1 b/programs/zstdgrep.1 index d7fda5833..fc79e82e3 100644 --- a/programs/zstdgrep.1 +++ b/programs/zstdgrep.1 @@ -1,5 +1,5 @@ . -.TH "ZSTDGREP" "1" "March 2024" "zstd 1.5.6" "User Commands" +.TH "ZSTDGREP" "1" "February 2025" "zstd 1.5.7" "User Commands" . .SH "NAME" \fBzstdgrep\fR \- print lines matching a pattern in zstandard\-compressed files diff --git a/programs/zstdless.1 b/programs/zstdless.1 index 7dd65f8fc..ad5048a02 100644 --- a/programs/zstdless.1 +++ b/programs/zstdless.1 @@ -1,5 +1,5 @@ . -.TH "ZSTDLESS" "1" "March 2024" "zstd 1.5.6" "User Commands" +.TH "ZSTDLESS" "1" "February 2025" "zstd 1.5.7" "User Commands" . .SH "NAME" \fBzstdless\fR \- view zstandard\-compressed files From 4690d66c7e41e8476838da588226ee2c185af5e8 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 20 Feb 2025 11:46:14 -0800 Subject: [PATCH 696/937] add CI check for zstd_manual before release ensures it's properly updated --- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/release_check.yml | 31 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/release_check.yml diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7df105532..38a3a0f92 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -41,7 +41,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - name: ensure zstd can be build with c89/c90 compilers (+ long long support + variadic macros) + - name: ensure zstd can be built with c89/c90 compilers (+ long long support + variadic macros) run: | make c89build V=1 diff --git a/.github/workflows/release_check.yml b/.github/workflows/release_check.yml new file mode 100644 index 000000000..aa1e817f4 --- /dev/null +++ b/.github/workflows/release_check.yml @@ -0,0 +1,31 @@ +name: check_manual + +on: + push: + branches: + - release + pull_request: + branches: + - release + +permissions: read-all + +jobs: + verify-manual: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v3 + + - name: Save current manual + run: mv doc/zstd_manual.html doc/zstd_manual_saved.html + + - name: Generate new manual + run: make manual + + - name: Compare manuals + run: | + if ! cmp -s doc/zstd_manual.html doc/zstd_manual_saved.html; then + echo "The manual was not updated before release !" + exit 1 + fi From c2ab0f9c4e6333f51b582676362946591d3278b6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 20 Feb 2025 13:14:11 -0800 Subject: [PATCH 697/937] check man page update --- .github/workflows/release_check.yml | 37 +++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release_check.yml b/.github/workflows/release_check.yml index aa1e817f4..160e4d516 100644 --- a/.github/workflows/release_check.yml +++ b/.github/workflows/release_check.yml @@ -1,4 +1,4 @@ -name: check_manual +name: release_checks on: push: @@ -26,6 +26,39 @@ jobs: - name: Compare manuals run: | if ! cmp -s doc/zstd_manual.html doc/zstd_manual_saved.html; then - echo "The manual was not updated before release !" + echo "The API manual was not updated before release !" exit 1 fi + + verify-man-pages: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v3 + + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y ruby ruby-dev + sudo gem install ronn + + - name: Display ronn version + run: ronn --version + + - name: Save current man pages + run: | + mv programs/zstd.1 programs/zstd.1.saved + mv programs/zstdgrep.1 programs/zstdgrep.1.saved + mv programs/zstdless.1 programs/zstdless.1.saved + + - name: Generate new manual pages + run: make -C programs man + + - name: Compare man pages + run: | + for file in zstd.1 zstdgrep.1 zstdless.1; do + if ! cmp -s programs/$file programs/$file.saved; then + echo "The man page $file should have been updated." + exit 1 + fi + done From 0c3345d6ec207c5207cb2b9bd50a32a0c709228b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 20 Feb 2025 15:21:48 -0800 Subject: [PATCH 698/937] [cmake] use target_compile_definitions which is considered best practice. --- build/cmake/lib/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 4e902a1fb..0a93e8d31 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -112,7 +112,7 @@ endif() macro (add_definition target var) if (NOT ("${${var}}" STREQUAL "")) - set_property(TARGET ${target} APPEND PROPERTY COMPILE_DEFINITIONS "${var}=__attribute__((visibility(\"${${var}}\")))") + target_compile_definitions(${target} PUBLIC "${var}=__attribute__((visibility(\"${${var}}\")))") endif () endmacro () @@ -126,7 +126,7 @@ if (ZSTD_BUILD_SHARED) target_include_directories(libzstd_shared INTERFACE $) list(APPEND library_targets libzstd_shared) if (ZSTD_MULTITHREAD_SUPPORT) - set_property(TARGET libzstd_shared APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") + target_compile_definitions(libzstd_shared PUBLIC ZSTD_MULTITHREAD) if (UNIX) target_link_libraries(libzstd_shared ${THREADS_LIBS}) endif () @@ -140,7 +140,7 @@ if (ZSTD_BUILD_STATIC) target_include_directories(libzstd_static INTERFACE $) list(APPEND library_targets libzstd_static) if (ZSTD_MULTITHREAD_SUPPORT) - set_property(TARGET libzstd_static APPEND PROPERTY COMPILE_DEFINITIONS "ZSTD_MULTITHREAD") + target_compile_definitions(libzstd_static PUBLIC ZSTD_MULTITHREAD) if (UNIX) target_link_libraries(libzstd_static ${THREADS_LIBS}) endif () @@ -207,7 +207,7 @@ if (ZSTD_BUILD_SHARED) OUTPUT_NAME zstd VERSION ${ZSTD_FULL_VERSION} SOVERSION ${zstd_VERSION_MAJOR}) - + if (ZSTD_FRAMEWORK) set_target_properties( libzstd_shared From 8ff47f3df0cdc79af358912eee4c96b863a5054b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 21 Feb 2025 09:57:55 -0800 Subject: [PATCH 699/937] added musl compilation test in CI --- .github/workflows/dev-short-tests.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7df105532..56a46a744 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -684,6 +684,17 @@ jobs: make -C programs zstd-pgo ./programs/zstd -b + musl-build: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - name: Install musl-tools + run: | + sudo apt install -y musl-tools + - name: Compile the project with musl-gcc + run: | + CC=musl-gcc make -j V=1 zstd + intel-cet-compatibility: runs-on: ubuntu-latest steps: From ebfa660b8297170fb0742ac8959aa64940292853 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 21 Feb 2025 11:36:30 -0800 Subject: [PATCH 700/937] introduce ZSTD_USE_C90_QSORT --- .github/workflows/dev-short-tests.yml | 2 +- lib/dictBuilder/cover.c | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 56a46a744..56401db0a 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -693,7 +693,7 @@ jobs: sudo apt install -y musl-tools - name: Compile the project with musl-gcc run: | - CC=musl-gcc make -j V=1 zstd + CC=musl-gcc CPPFLAGS=-DZSTD_USE_C90_QSORT make -j V=1 zstd intel-cet-compatibility: runs-on: ubuntu-latest diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 2ef33c73e..29820d7e1 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -24,9 +24,9 @@ /* qsort_r is an extension. */ #if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ defined(__CYGWIN__) || defined(__MSYS__) -#if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ -#define _GNU_SOURCE -#endif +# if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ +# define _GNU_SOURCE +# endif #endif #include /* fprintf */ @@ -241,8 +241,9 @@ typedef struct { unsigned d; } COVER_ctx_t; -#if !defined(_GNU_SOURCE) && !defined(__APPLE__) && !defined(_MSC_VER) -/* C90 only offers qsort() that needs a global context. */ +#if defined(ZSTD_USE_C90_QSORT) \ + || (!defined(_GNU_SOURCE) && !defined(__APPLE__) && !defined(_MSC_VER)) +/* Use global context for non-reentrant sort functions */ static COVER_ctx_t *g_coverCtx = NULL; #endif @@ -328,7 +329,7 @@ static void stableSort(COVER_ctx_t *ctx) { qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx, (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); -#elif defined(_GNU_SOURCE) +#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), ctx); @@ -342,7 +343,7 @@ static void stableSort(COVER_ctx_t *ctx) { (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); #else /* C90 fallback.*/ g_coverCtx = ctx; - /* TODO(cavalcanti): implement a reentrant qsort() when is not available. */ + /* TODO(cavalcanti): implement a reentrant qsort() when _r is not available. */ qsort(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); #endif From fd5498a1793f26b3a6995009449e1216a8c90dd0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 21 Feb 2025 12:48:26 -0800 Subject: [PATCH 701/937] document ZSTD_USE_C90_QSORT --- lib/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/README.md b/lib/README.md index b37f5fc4f..9df516c5a 100644 --- a/lib/README.md +++ b/lib/README.md @@ -193,6 +193,10 @@ The file structure is designed to make this selection manually achievable for an and assembly decoding loops. You may want to use this macro if these loops are slower on your platform. +- The macro `ZSTD_USE_C90_QSORT` forces usage of C90's `qsort()`, + for situations where the code cannot determine that `qsort_r()` is not supported, + such as, for example, older versions of `musl`. + #### Windows : using MinGW+MSYS to create DLL DLL can be created using MinGW+MSYS with the `make libzstd` command. From b40dabeda2893509c5c903c9c2647fe41e5d6c4d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Feb 2025 05:44:05 +0000 Subject: [PATCH 702/937] Bump ossf/scorecard-action from 2.4.0 to 2.4.1 Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.4.0 to 2.4.1. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/62b2cac7ed8198b15735ed49ab1e5cf35480ba46...f49aabe0b5af0936a0987cfb85d86b75731b0186) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index e532b03bf..6d49b886a 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -32,7 +32,7 @@ jobs: persist-credentials: false - name: "Run analysis" - uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # tag=v2.4.0 + uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # tag=v2.4.1 with: results_file: results.sarif results_format: sarif From e1e2f3873d0cd068d69b49659f7732dd18027115 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Feb 2025 05:44:08 +0000 Subject: [PATCH 703/937] Bump msys2/setup-msys2 from 2.26.0 to 2.27.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.26.0 to 2.27.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/d44ca8e88d8b43d56cf5670f91747359d5537f97...61f9e5e925871ba6c9e3e8da24ede83ea27fa91f) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 0aa85ff7e..c0dbe38d0 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -260,7 +260,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0 + - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 7df105532..aa098489d 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -544,7 +544,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 - - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0 + - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 35999476e..0334f1446 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -24,7 +24,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v3 - - uses: msys2/setup-msys2@d44ca8e88d8b43d56cf5670f91747359d5537f97 # tag=v2.26.0 + - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc From 2840631dc1a5923ee51f76792ea427e41b1a0de4 Mon Sep 17 00:00:00 2001 From: hirohira Date: Wed, 26 Feb 2025 08:23:48 +0900 Subject: [PATCH 704/937] Fix function signature mismatch for ZSTD_convertBlockSequences --- lib/compress/zstd_compress_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index ca5e2a4c5..c6bd166b1 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -1523,7 +1523,7 @@ typedef struct { /* 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; From 30281d889ff3217bd62d906d550f24c9303c651c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 07:41:34 -0800 Subject: [PATCH 705/937] fix conversion warning --- lib/common/bits.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/bits.h b/lib/common/bits.h index f452f0889..910ffa388 100644 --- a/lib/common/bits.h +++ b/lib/common/bits.h @@ -21,7 +21,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]; } } From e635221f1bf1ba5cf0d1d2d31bfa24b8d995b21f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 08:07:51 -0800 Subject: [PATCH 706/937] fixed -Wconversion for zdict --- lib/dictBuilder/zdict.c | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/lib/dictBuilder/zdict.c b/lib/dictBuilder/zdict.c index d5e60a4da..befa616b8 100644 --- a/lib/dictBuilder/zdict.c +++ b/lib/dictBuilder/zdict.c @@ -168,7 +168,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}; @@ -293,8 +293,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; @@ -306,8 +308,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); @@ -383,11 +387,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]; @@ -399,7 +403,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); @@ -467,8 +471,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)); @@ -503,11 +507,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++) From 8ffa27d93b5f2d5b0a7f0b3e051e983410575de5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 08:12:11 -0800 Subject: [PATCH 707/937] fixed -Wconversion for divsufsort.c --- lib/dictBuilder/divsufsort.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/dictBuilder/divsufsort.c b/lib/dictBuilder/divsufsort.c index a2870fb3b..e5b117b29 100644 --- a/lib/dictBuilder/divsufsort.c +++ b/lib/dictBuilder/divsufsort.c @@ -199,8 +199,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) ? @@ -909,8 +909,8 @@ sssort(const unsigned char *T, const int *PA, static INLINE int tr_ilg(int n) { - return (n & 0xffff0000) ? - ((n & 0xff000000) ? + return ((unsigned)n & 0xffff0000) ? + (((unsigned)n & 0xff000000) ? 24 + lg_table[(n >> 24) & 0xff] : 16 + lg_table[(n >> 16) & 0xff]) : ((n & 0x0000ff00) ? From 2413f1732268351b87aea8711f1d7fe6f1aaddbc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 08:33:01 -0800 Subject: [PATCH 708/937] fixed -Wconversion for cover.c --- lib/dictBuilder/cover.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 2ef33c73e..a71370c72 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -1183,7 +1183,7 @@ 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; + const int displayLevel = (int)parameters->zParams.notificationLevel; unsigned iteration = 1; unsigned d; unsigned k; @@ -1261,7 +1261,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)g_displayLevel; /* Check the parameters */ if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) { DISPLAYLEVEL(1, "Cover parameters incorrect\n"); From db2d205ada0c57a8b5611303a400987c278f15a6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 10:01:05 -0800 Subject: [PATCH 709/937] fixed -Wconversion for lib/decompress/zstd_decompress_block.c --- lib/common/compiler.h | 12 +-- lib/common/zstd_internal.h | 2 +- lib/compress/zstd_compress_internal.h | 4 +- lib/decompress/zstd_decompress_block.c | 116 +++++++++++++------------ 4 files changed, 71 insertions(+), 63 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 1f7da50e6..944774a7a 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -357,9 +357,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; } /** @@ -370,9 +370,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; } /** @@ -382,9 +382,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 diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index 2789a3591..c1647689b 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -213,7 +213,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; diff --git a/lib/compress/zstd_compress_internal.h b/lib/compress/zstd_compress_internal.h index ca5e2a4c5..90202003f 100644 --- a/lib/compress/zstd_compress_internal.h +++ b/lib/compress/zstd_compress_internal.h @@ -707,7 +707,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; } @@ -800,7 +800,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); diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 862785a49..ec8ebcda7 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -16,14 +16,13 @@ *********************************************************/ #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memmove, ZSTD_memset */ #include "../common/compiler.h" /* prefetch */ -#include "../common/cpu.h" /* bmi2 */ #include "../common/mem.h" /* low level memory routines */ +#include #define FSE_STATIC_LINKING_ONLY #include "../common/fse.h" #include "../common/huf.h" #include "../common/zstd_internal.h" #include "zstd_decompress_internal.h" /* ZSTD_DCtx */ -#include "zstd_ddict.h" /* ZSTD_DDictDictContent */ #include "zstd_decompress_block.h" #include "../common/bits.h" /* ZSTD_highbit32 */ @@ -734,9 +733,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, @@ -746,9 +746,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, @@ -758,9 +759,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, @@ -771,7 +773,7 @@ size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr, } } - return ip-istart; + return (size_t)(ip-istart); } @@ -801,7 +803,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 */ @@ -834,7 +837,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; @@ -849,7 +854,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); @@ -863,7 +869,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; } @@ -874,7 +880,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; @@ -885,7 +892,7 @@ static void ZSTD_safecopyDstBeforeSrc(BYTE* op, const BYTE* ip, ptrdiff_t length } if (op <= oend - WILDCOPY_OVERLENGTH && diff < -WILDCOPY_VECLEN) { - ZSTD_wildcopy(op, ip, oend - WILDCOPY_OVERLENGTH - op, ZSTD_no_overlap); + ZSTD_wildcopy(op, ip, (size_t)(oend - WILDCOPY_OVERLENGTH - op), ZSTD_no_overlap); ip += oend - WILDCOPY_OVERLENGTH - op; op += oend - WILDCOPY_OVERLENGTH - op; } @@ -936,11 +943,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); @@ -985,11 +992,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); @@ -1058,11 +1065,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 */ @@ -1079,7 +1086,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); @@ -1090,7 +1097,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; } @@ -1151,7 +1158,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; @@ -1171,7 +1178,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); @@ -1182,7 +1189,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; } @@ -1405,10 +1412,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 = ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -1423,7 +1428,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); @@ -1515,7 +1520,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"); @@ -1617,10 +1623,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) ? + ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) : + dctx->litBuffer; BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* const litEnd = litPtr + dctx->litSize; @@ -1635,7 +1641,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); @@ -1719,7 +1725,7 @@ 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); + const BYTE* const match = ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset); PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ } return prefetchPos + sequence.matchLength; @@ -1736,10 +1742,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 : + ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -1761,9 +1767,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); @@ -1782,9 +1787,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; @@ -1828,7 +1833,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); @@ -1867,7 +1873,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); @@ -1876,7 +1883,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); @@ -2094,7 +2102,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. From 97bc43cc68b2b2e7b55c1f00dfa68b30e8b8d6f8 Mon Sep 17 00:00:00 2001 From: "Sergey G. Brester" Date: Wed, 26 Feb 2025 19:27:44 +0100 Subject: [PATCH 710/937] build_package.bat: fix path to zstd_errors.h (it is in lib not in lib/common) closes gh-4318 --- lib/dll/example/build_package.bat | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 8baabc7b2..6a93efa25 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -15,6 +15,6 @@ COPY lib\dll\example\Makefile bin\example\ COPY lib\dll\example\fullbench-dll.* bin\example\ COPY lib\dll\example\README.md bin\ COPY lib\zstd.h bin\include\ -COPY lib\common\zstd_errors.h bin\include\ +COPY lib\zstd_errors.h bin\include\ COPY lib\dictBuilder\zdict.h bin\include\ COPY programs\zstd.exe bin\zstd.exe From f0d31732030091886bbaa50fc0197bdf8588787d Mon Sep 17 00:00:00 2001 From: "Sergey G. Brester" Date: Wed, 26 Feb 2025 20:02:48 +0100 Subject: [PATCH 711/937] build_package.bat: don't swallow the error(s) by copy, exit with error if failed somewhere --- lib/dll/example/build_package.bat | 46 +++++++++++++++++++------------ 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 6a93efa25..65ce367c2 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -1,20 +1,30 @@ @ECHO OFF MKDIR bin\dll bin\static bin\example bin\include -COPY tests\fullbench.c bin\example\ -COPY programs\datagen.c bin\example\ -COPY programs\datagen.h bin\example\ -COPY programs\util.h bin\example\ -COPY programs\platform.h bin\example\ -COPY lib\common\mem.h bin\example\ -COPY lib\common\zstd_internal.h bin\example\ -COPY lib\common\error_private.h bin\example\ -COPY lib\common\xxhash.h bin\example\ -COPY lib\libzstd.a bin\static\libzstd_static.lib -COPY lib\dll\libzstd.* bin\dll\ -COPY lib\dll\example\Makefile bin\example\ -COPY lib\dll\example\fullbench-dll.* bin\example\ -COPY lib\dll\example\README.md bin\ -COPY lib\zstd.h bin\include\ -COPY lib\zstd_errors.h bin\include\ -COPY lib\dictBuilder\zdict.h bin\include\ -COPY programs\zstd.exe bin\zstd.exe +SET CpyError= +COPY tests\fullbench.c bin\example\ || (SET CpyError=%CpyError% tests\fullbench.c) +COPY programs\datagen.c bin\example\ || (SET CpyError=%CpyError% programs\datagen.c) +COPY programs\datagen.h bin\example\ || (SET CpyError=%CpyError% programs\datagen.h) +COPY programs\util.h bin\example\ || (SET CpyError=%CpyError% programs\util.h) +COPY programs\platform.h bin\example\ || (SET CpyError=%CpyError% programs\platform.h) +COPY lib\common\mem.h bin\example\ || (SET CpyError=%CpyError% lib\common\mem.h) +COPY lib\common\zstd_internal.h bin\example\ || (SET CpyError=%CpyError% lib\common\zstd_internal.h) +COPY lib\common\error_private.h bin\example\ || (SET CpyError=%CpyError% lib\common\error_private.h) +COPY lib\common\xxhash.h bin\example\ || (SET CpyError=%CpyError% lib\common\xxhash.h) +COPY lib\libzstd.a bin\static\libzstd_static.lib || (SET CpyError=%CpyError% lib\libzstd.a) +COPY lib\dll\libzstd.* bin\dll\ || (SET CpyError=%CpyError% lib\dll\libzstd.*) +COPY lib\dll\example\Makefile bin\example\ || (SET CpyError=%CpyError% lib\dll\example\Makefile) +COPY lib\dll\example\fullbench-dll.* bin\example\ || (SET CpyError=%CpyError% lib\dll\example\fullbench) +COPY lib\dll\example\README.md bin\ || (SET CpyError=%CpyError% lib\dll\example\README.md) +COPY lib\zstd.h bin\include\ || (SET CpyError=%CpyError% lib\zstd.h) +COPY lib\zstd_errors.h bin\include\ || (SET CpyError=%CpyError% lib\zstd_errors.h) +COPY lib\dictBuilder\zdict.h bin\include\ || (SET CpyError=%CpyError% lib\dictBuilder\zdict.h) +COPY programs\zstd.exe bin\zstd.exe || (SET CpyError=%CpyError% programs\zstd.exe) + +IF "[%CpyError%]" == "[]" goto :EOF + +:error +echo Failed with error #%errorlevel%: unable to copy following files: +echo %CpyError% +exit /b %errorlevel% + +:EOF From 4d81b0000df94fe42477ceae755ea256595cba12 Mon Sep 17 00:00:00 2001 From: "Sergey G. Brester" Date: Wed, 26 Feb 2025 20:13:44 +0100 Subject: [PATCH 712/937] GHA/windows-artifacts.yml: don't ignore the error if build-package batch failed --- .github/workflows/windows-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 0334f1446..9b74969d3 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -46,7 +46,7 @@ jobs: - name: Create artifacts run: | - ./lib/dll/example/build_package.bat + ./lib/dll/example/build_package.bat || exit 1 mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ 7z a -tzip -mx9 zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ cd .. From dca9791862698f73a6d230feef64b4bb406481ff Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Feb 2025 14:30:29 -0800 Subject: [PATCH 713/937] fixed minor C++ compat warnings --- lib/decompress/huf_decompress.c | 11 ++++++----- lib/decompress/zstd_decompress_block.c | 12 ++++++------ 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c index f85dd0bee..c7e342648 100644 --- a/lib/decompress/huf_decompress.c +++ b/lib/decompress/huf_decompress.c @@ -15,6 +15,7 @@ /* ************************************************************** * Dependencies ****************************************************************/ +#include /* size_t */ #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset */ #include "../common/compiler.h" #include "../common/bitstream.h" /* BIT_* */ @@ -195,7 +196,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. @@ -578,7 +579,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; @@ -845,7 +846,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"); @@ -1362,7 +1363,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); @@ -1671,7 +1672,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); diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index ec8ebcda7..3a8e634f9 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1413,7 +1413,7 @@ ZSTD_decompressSequences_bodySplitLitBuffer( ZSTD_DCtx* dctx, const ZSTD_longOffset_e isLongOffset) { BYTE* const ostart = (BYTE*)dst; - BYTE* const oend = ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); + BYTE* const oend = (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -1625,7 +1625,7 @@ ZSTD_decompressSequences_body(ZSTD_DCtx* dctx, { BYTE* const ostart = (BYTE*)dst; BYTE* const oend = (dctx->litBufferLocation == ZSTD_not_in_dst) ? - ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) : + (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize) : dctx->litBuffer; BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; @@ -1725,7 +1725,7 @@ 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, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset); + const BYTE* const match = (const BYTE*)ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset); PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ } return prefetchPos + sequence.matchLength; @@ -1745,7 +1745,7 @@ ZSTD_decompressSequencesLong_body( BYTE* const ostart = (BYTE*)dst; BYTE* const oend = (dctx->litBufferLocation == ZSTD_in_dst) ? dctx->litBuffer : - ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); + (BYTE*)ZSTD_maybeNullPtrAdd(ostart, (ptrdiff_t)maxDstSize); BYTE* op = ostart; const BYTE* litPtr = dctx->litPtr; const BYTE* litBufferEnd = dctx->litBufferEnd; @@ -2001,9 +2001,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)((char*)curPtr - (const char*)virtualStart); } typedef struct { From bbf2801ddd6d68a1f36edc18a7b31114b27d2a66 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 15:44:40 -0800 Subject: [PATCH 714/937] try to fix the meson windows build apparently could be just a missing include --- contrib/pzstd/Logging.h | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/pzstd/Logging.h b/contrib/pzstd/Logging.h index 84a08d200..aa73a976b 100644 --- a/contrib/pzstd/Logging.h +++ b/contrib/pzstd/Logging.h @@ -10,6 +10,7 @@ #include #include +#include namespace pzstd { From e94e09dd7b16e9897c76809697e506c5c97851d4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 11:36:25 -0800 Subject: [PATCH 715/937] ensure that a copy error results in the task failing clearly error code != 0, red status checked by intentionally inserting an error in another run --- lib/dll/example/build_package.bat | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 65ce367c2..4c9ffa049 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -23,6 +23,7 @@ COPY programs\zstd.exe bin\zstd.exe || (SET CpyError=%CpyError% programs\zstd.ex IF "[%CpyError%]" == "[]" goto :EOF :error +SET errorlevel=1 echo Failed with error #%errorlevel%: unable to copy following files: echo %CpyError% exit /b %errorlevel% From 77e58994d21870fb23911df2704e669e4d359943 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 11:38:04 -0800 Subject: [PATCH 716/937] updated zlib version to more recent v1.3.1 --- .github/workflows/windows-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 9b74969d3..d6f934904 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -37,7 +37,7 @@ jobs: - name: Building zlib to static link run: | - git clone --depth 1 --branch v1.2.11 https://github.com/madler/zlib + git clone --depth 1 --branch v1.3.1 https://github.com/madler/zlib make -C zlib -f win32/Makefile.gcc libz.a - name: Building zstd programs From 7340657c6f378d3dfbb8793cad04ed06b875ed40 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 12:43:11 -0800 Subject: [PATCH 717/937] update build_package.bat by using a subrouting --- lib/dll/example/build_package.bat | 57 ++++++++++++++++--------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 4c9ffa049..4b750137e 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -1,31 +1,32 @@ -@ECHO OFF -MKDIR bin\dll bin\static bin\example bin\include -SET CpyError= -COPY tests\fullbench.c bin\example\ || (SET CpyError=%CpyError% tests\fullbench.c) -COPY programs\datagen.c bin\example\ || (SET CpyError=%CpyError% programs\datagen.c) -COPY programs\datagen.h bin\example\ || (SET CpyError=%CpyError% programs\datagen.h) -COPY programs\util.h bin\example\ || (SET CpyError=%CpyError% programs\util.h) -COPY programs\platform.h bin\example\ || (SET CpyError=%CpyError% programs\platform.h) -COPY lib\common\mem.h bin\example\ || (SET CpyError=%CpyError% lib\common\mem.h) -COPY lib\common\zstd_internal.h bin\example\ || (SET CpyError=%CpyError% lib\common\zstd_internal.h) -COPY lib\common\error_private.h bin\example\ || (SET CpyError=%CpyError% lib\common\error_private.h) -COPY lib\common\xxhash.h bin\example\ || (SET CpyError=%CpyError% lib\common\xxhash.h) -COPY lib\libzstd.a bin\static\libzstd_static.lib || (SET CpyError=%CpyError% lib\libzstd.a) -COPY lib\dll\libzstd.* bin\dll\ || (SET CpyError=%CpyError% lib\dll\libzstd.*) -COPY lib\dll\example\Makefile bin\example\ || (SET CpyError=%CpyError% lib\dll\example\Makefile) -COPY lib\dll\example\fullbench-dll.* bin\example\ || (SET CpyError=%CpyError% lib\dll\example\fullbench) -COPY lib\dll\example\README.md bin\ || (SET CpyError=%CpyError% lib\dll\example\README.md) -COPY lib\zstd.h bin\include\ || (SET CpyError=%CpyError% lib\zstd.h) -COPY lib\zstd_errors.h bin\include\ || (SET CpyError=%CpyError% lib\zstd_errors.h) -COPY lib\dictBuilder\zdict.h bin\include\ || (SET CpyError=%CpyError% lib\dictBuilder\zdict.h) -COPY programs\zstd.exe bin\zstd.exe || (SET CpyError=%CpyError% programs\zstd.exe) +@echo off +setlocal -IF "[%CpyError%]" == "[]" goto :EOF +rem Create required directories. +mkdir bin\dll bin\static bin\example bin\include -:error -SET errorlevel=1 -echo Failed with error #%errorlevel%: unable to copy following files: -echo %CpyError% -exit /b %errorlevel% +rem Copy files using a subroutine. Exits immediately on failure. +call :copyFile "tests\fullbench.c" "bin\example\" +call :copyFile "programs\datagen.c" "bin\example\" +call :copyFile "programs\datagen.h" "bin\example\" +call :copyFile "programs\util.h" "bin\example\" +call :copyFile "programs\platform.h" "bin\example\" +call :copyFile "lib\common\mem.h" "bin\example\" +call :copyFile "lib\common\zstd_internal.h" "bin\example\" +call :copyFile "lib\common\error_private.h" "bin\example\" +call :copyFile "lib\common\xxhash.h" "bin\example\" +call :copyFile "lib\libzstd.a" "bin\static\libzstd_static.lib" +call :copyFile "lib\dll\libzstd.*" "bin\dll\" +call :copyFile "lib\dll\example\Makefile" "bin\example\" +call :copyFile "lib\dll\example\fullbench-dll.*" "bin\example\" +call :copyFile "lib\dll\example\README.md" "bin\" +call :copyFile "lib\zstd.h" "bin\include\" +call :copyFile "lib\zstd_errors.h" "bin\include\" +call :copyFile "lib\dictBuilder\zdict.h" "bin\include\" +call :copyFile "programs\zstd.exe" "bin\zstd.exe" -:EOF +endlocal +exit /b + +:copyFile +copy "%~1" "%~2" || (echo Failure processing "%~1" & exit /b %errorlevel%) +goto :eof From 4e1723a7e47afb97a5ed55d0536706f719ed066e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 14:33:49 -0800 Subject: [PATCH 718/937] fixed the script so that it fails when a copy fails and also: fix the list of files, as `zdict.h` was incorrectly set. --- lib/dll/example/build_package.bat | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 4b750137e..5a03bdf25 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -21,12 +21,16 @@ call :copyFile "lib\dll\example\fullbench-dll.*" "bin\example\" call :copyFile "lib\dll\example\README.md" "bin\" call :copyFile "lib\zstd.h" "bin\include\" call :copyFile "lib\zstd_errors.h" "bin\include\" -call :copyFile "lib\dictBuilder\zdict.h" "bin\include\" +call :copyFile "lib\zdict.h" "bin\include\" call :copyFile "programs\zstd.exe" "bin\zstd.exe" endlocal -exit /b +exit /b 0 :copyFile -copy "%~1" "%~2" || (echo Failure processing "%~1" & exit /b %errorlevel%) -goto :eof +copy "%~1" "%~2" +if errorlevel 1 ( + echo Failed to copy "%~1" + exit 1 +) +exit /b From 88100bc62f8b28c1981a6d0d2cf28e4a7ec8a2b2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 27 Feb 2025 16:59:40 -0800 Subject: [PATCH 719/937] proper usage of standard variables --- .github/workflows/windows-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index d6f934904..bb8c127b9 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -42,7 +42,7 @@ jobs: - name: Building zstd programs run: | - CPPFLAGS=-I../zlib LDFLAGS=../zlib/libz.a make -j allzstd MOREFLAGS=-static V=1 + CPPFLAGS=-I../zlib LDLIBS=../zlib/libz.a LDFLAGS=-static make -j allzstd V=1 - name: Create artifacts run: | From a6d232dcad9602e8d840f2021dcfe96226a00ef6 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 28 Feb 2025 09:33:22 -0800 Subject: [PATCH 720/937] avoid double zipping --- .github/workflows/windows-artifacts.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index bb8c127b9..335389593 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -27,7 +27,7 @@ jobs: - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} - install: make zlib git p7zip mingw-w64-${{matrix.env}}-gcc + install: make zlib git mingw-w64-${{matrix.env}}-gcc update: true - name: display versions @@ -48,11 +48,10 @@ jobs: run: | ./lib/dll/example/build_package.bat || exit 1 mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - 7z a -tzip -mx9 zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - cd .. - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 with: - path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip - name: zstd-${{ github.ref_name }}-${{matrix.ziparch}}.zip + compression-level: 9 # maximum compression + path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + name: zstd-${{ github.ref_name }}-${{matrix.ziparch}} From bbbb2379ed0524496a531ba840953f31b62ee881 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 28 Feb 2025 09:42:50 -0800 Subject: [PATCH 721/937] test win artifact generation on pushing to release this will get a chance to check that win artifact generation works correctly before creating the release tag. --- .github/workflows/windows-artifacts.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 335389593..079552414 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -2,7 +2,7 @@ name: windows-artifacts on: push: - branches: [ test_artifacts, win_artifacts ] + branches: [ test_artifacts, win_artifacts, release ] release: types: - published @@ -53,5 +53,6 @@ jobs: uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 with: compression-level: 9 # maximum compression + if-no-files-found: error # defaults to `warn` path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ name: zstd-${{ github.ref_name }}-${{matrix.ziparch}} From e99be473a6e6c9c2852a21b3c5608029a2cbad00 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 28 Feb 2025 12:04:06 -0800 Subject: [PATCH 722/937] automatically upload windows artifact on Release Tag creation --- .github/workflows/windows-artifacts.yml | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 079552414..4c79c9420 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -11,6 +11,8 @@ permissions: read-all jobs: windows-artifacts: + permissions: + contents: write # to fetch code and upload artifacts # see https://ariya.io/2020/07/on-github-actions-with-msys2 runs-on: windows-latest # see https://github.com/msys2/setup-msys2 @@ -27,7 +29,7 @@ jobs: - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} - install: make zlib git mingw-w64-${{matrix.env}}-gcc + install: make zlib p7zip git mingw-w64-${{matrix.env}}-gcc update: true - name: display versions @@ -49,10 +51,24 @@ jobs: ./lib/dll/example/build_package.bat || exit 1 mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip + - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 with: compression-level: 9 # maximum compression if-no-files-found: error # defaults to `warn` path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ name: zstd-${{ github.ref_name }}-${{matrix.ziparch}} + + - name: Package artifact for upload + run: | + 7z a -tzip -mx9 "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip')" "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}')" + + - name: Upload release asset + if: github.event_name == 'release' + shell: pwsh + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release upload "${{ github.ref_name }}" "$env:GITHUB_WORKSPACE/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip" --clobber + + From 0727fc5ff9f1201b0873b403257c0b9a57e31096 Mon Sep 17 00:00:00 2001 From: Sergey Senozhatsky Date: Mon, 2 Sep 2024 19:55:49 +0900 Subject: [PATCH 723/937] lib: zstd: export API needed for dictionary support Patch series "zram: introduce custom comp backends API", v7. This series introduces support for run-time compression algorithms tuning, so users, for instance, can adjust compression/acceleration levels and provide pre-trained compression/decompression dictionaries which certain algorithms support. At this point we stop supporting (old/deprecated) comp API. We may add new acomp API support in the future, but before that zram needs to undergo some major rework (we are not ready for async compression). Some benchmarks for reference (look at column #2) *** init zstd /sys/block/zram0/mm_stat 1750659072 504622188 514355200 0 514355200 1 0 34204 34204 *** init zstd dict=/home/ss/zstd-dict-amd64 /sys/block/zram0/mm_stat 1750650880 465908890 475398144 0 475398144 1 0 34185 34185 *** init zstd level=8 dict=/home/ss/zstd-dict-amd64 /sys/block/zram0/mm_stat 1750654976 430803319 439873536 0 439873536 1 0 34185 34185 *** init lz4 /sys/block/zram0/mm_stat 1750646784 664266564 677060608 0 677060608 1 0 34288 34288 *** init lz4 dict=/home/ss/lz4-dict-amd64 /sys/block/zram0/mm_stat 1750650880 619990300 632102912 0 632102912 1 0 34278 34278 *** init lz4hc /sys/block/zram0/mm_stat 1750630400 609023822 621232128 0 621232128 1 0 34288 34288 *** init lz4hc dict=/home/ss/lz4-dict-amd64 /sys/block/zram0/mm_stat 1750659072 505133172 515231744 0 515231744 1 0 34278 34278 Recompress init zram zstd (prio=0), zstd level=5 (prio 1), zstd with dict (prio 2) *** zstd /sys/block/zram0/mm_stat 1750982656 504630584 514269184 0 514269184 1 0 34204 34204 *** idle recompress priority=1 (zstd level=5) /sys/block/zram0/mm_stat 1750982656 488645601 525438976 0 514269184 1 0 34204 34204 *** idle recompress priority=2 (zstd dict) /sys/block/zram0/mm_stat 1750982656 460869640 517914624 0 514269184 1 0 34185 34204 This patch (of 24): We need to export a number of API functions that enable advanced zstd usage - C/D dictionaries, dictionaries sharing between contexts, etc. Link: https://lkml.kernel.org/r/20240902105656.1383858-1-senozhatsky@chromium.org Link: https://lkml.kernel.org/r/20240902105656.1383858-2-senozhatsky@chromium.org Signed-off-by: Sergey Senozhatsky Cc: Nick Terrell Cc: Minchan Kim Cc: Sergey Senozhatsky Signed-off-by: Andrew Morton --- contrib/linux-kernel/linux_zstd.h | 166 ++++++++++++++++++ contrib/linux-kernel/zstd_compress_module.c | 49 ++++++ contrib/linux-kernel/zstd_decompress_module.c | 36 ++++ 3 files changed, 251 insertions(+) diff --git a/contrib/linux-kernel/linux_zstd.h b/contrib/linux-kernel/linux_zstd.h index dda8a2d7d..2f2a3c8b8 100644 --- a/contrib/linux-kernel/linux_zstd.h +++ b/contrib/linux-kernel/linux_zstd.h @@ -77,6 +77,30 @@ int zstd_min_clevel(void); */ int zstd_max_clevel(void); +/** + * zstd_default_clevel() - default compression level + * + * Return: Default compression level. + */ +int zstd_default_clevel(void); + +/** + * struct zstd_custom_mem - custom memory allocation + */ +typedef ZSTD_customMem zstd_custom_mem; + +/** + * struct zstd_dict_load_method - Dictionary load method. + * See zstd_lib.h. + */ +typedef ZSTD_dictLoadMethod_e zstd_dict_load_method; + +/** + * struct zstd_dict_content_type - Dictionary context type. + * See zstd_lib.h. + */ +typedef ZSTD_dictContentType_e zstd_dict_content_type; + /* ====== Parameter Selection ====== */ /** @@ -136,6 +160,18 @@ typedef ZSTD_parameters zstd_parameters; zstd_parameters zstd_get_params(int level, unsigned long long estimated_src_size); +/** + * zstd_get_cparams() - returns zstd_compression_parameters for selected level + * @level: The compression level + * @estimated_src_size: The estimated source size to compress or 0 + * if unknown. + * @dict_size: Dictionary size. + * + * Return: The selected zstd_compression_parameters. + */ +zstd_compression_parameters zstd_get_cparams(int level, + unsigned long long estimated_src_size, size_t dict_size); + typedef ZSTD_CCtx zstd_cctx; typedef ZSTD_cParameter zstd_cparameter; @@ -205,6 +241,71 @@ zstd_cctx *zstd_init_cctx(void *workspace, size_t workspace_size); size_t zstd_compress_cctx(zstd_cctx *cctx, void *dst, size_t dst_capacity, const void *src, size_t src_size, const zstd_parameters *parameters); +/** + * zstd_create_cctx_advanced() - Create compression context + * @custom_mem: Custom allocator. + * + * Return: NULL on error, pointer to compression context otherwise. + */ +zstd_cctx *zstd_create_cctx_advanced(zstd_custom_mem custom_mem); + +/** + * zstd_free_cctx() - Free compression context + * @cdict: Pointer to compression context. + * + * Return: Always 0. + */ +size_t zstd_free_cctx(zstd_cctx* cctx); + +/** + * struct zstd_cdict - Compression dictionary. + * See zstd_lib.h. + */ +typedef ZSTD_CDict zstd_cdict; + +/** + * zstd_create_cdict_byreference() - Create compression dictionary + * @dict: Pointer to dictionary buffer. + * @dict_size: Size of the dictionary buffer. + * @dict_load_method: Dictionary load method. + * @dict_content_type: Dictionary content type. + * @custom_mem: Memory allocator. + * + * Note, this uses @dict by reference (ZSTD_dlm_byRef), so it should be + * free before zstd_cdict is destroyed. + * + * Return: NULL on error, pointer to compression dictionary + * otherwise. + */ +zstd_cdict *zstd_create_cdict_byreference(const void *dict, size_t dict_size, + zstd_compression_parameters cparams, + zstd_custom_mem custom_mem); + +/** + * zstd_free_cdict() - Free compression dictionary + * @cdict: Pointer to compression dictionary. + * + * Return: Always 0. + */ +size_t zstd_free_cdict(zstd_cdict* cdict); + +/** + * zstd_compress_using_cdict() - compress src into dst using a dictionary + * @cctx: The context. Must have been initialized with zstd_init_cctx(). + * @dst: The buffer to compress src into. + * @dst_capacity: The size of the destination buffer. May be any size, but + * ZSTD_compressBound(srcSize) is guaranteed to be large enough. + * @src: The data to compress. + * @src_size: The size of the data to compress. + * @cdict: The dictionary to be used. + * + * Return: The compressed size or an error, which can be checked using + * zstd_is_error(). + */ +size_t zstd_compress_using_cdict(zstd_cctx *cctx, void *dst, + size_t dst_capacity, const void *src, size_t src_size, + const zstd_cdict *cdict); + /* ====== Single-pass Decompression ====== */ typedef ZSTD_DCtx zstd_dctx; @@ -245,6 +346,71 @@ zstd_dctx *zstd_init_dctx(void *workspace, size_t workspace_size); size_t zstd_decompress_dctx(zstd_dctx *dctx, void *dst, size_t dst_capacity, const void *src, size_t src_size); +/** + * struct zstd_ddict - Decompression dictionary. + * See zstd_lib.h. + */ +typedef ZSTD_DDict zstd_ddict; + +/** + * zstd_create_ddict_byreference() - Create decompression dictionary + * @dict: Pointer to dictionary buffer. + * @dict_size: Size of the dictionary buffer. + * @dict_load_method: Dictionary load method. + * @dict_content_type: Dictionary content type. + * @custom_mem: Memory allocator. + * + * Note, this uses @dict by reference (ZSTD_dlm_byRef), so it should be + * free before zstd_ddict is destroyed. + * + * Return: NULL on error, pointer to decompression dictionary + * otherwise. + */ +zstd_ddict *zstd_create_ddict_byreference(const void *dict, size_t dict_size, + zstd_custom_mem custom_mem); +/** + * zstd_free_ddict() - Free decompression dictionary + * @dict: Pointer to the dictionary. + * + * Return: Always 0. + */ +size_t zstd_free_ddict(zstd_ddict *ddict); + +/** + * zstd_create_dctx_advanced() - Create decompression context + * @custom_mem: Custom allocator. + * + * Return: NULL on error, pointer to decompression context otherwise. + */ +zstd_dctx *zstd_create_dctx_advanced(zstd_custom_mem custom_mem); + +/** + * zstd_free_dctx() -- Free decompression context + * @dctx: Pointer to decompression context. + * Return: Always 0. + */ +size_t zstd_free_dctx(zstd_dctx *dctx); + +/** + * zstd_decompress_using_ddict() - decompress src into dst using a dictionary + * @dctx: The decompression context. + * @dst: The buffer to decompress src into. + * @dst_capacity: The size of the destination buffer. Must be at least as large + * as the decompressed size. If the caller cannot upper bound the + * decompressed size, then it's better to use the streaming API. + * @src: The zstd compressed data to decompress. Multiple concatenated + * frames and skippable frames are allowed. + * @src_size: The exact size of the data to decompress. + * @ddict: The dictionary to be used. + * + * Return: The decompressed size or an error, which can be checked using + * zstd_is_error(). + */ +size_t zstd_decompress_using_ddict(zstd_dctx *dctx, + void *dst, size_t dst_capacity, const void *src, size_t src_size, + const zstd_ddict *ddict); + + /* ====== Streaming Buffers ====== */ /** diff --git a/contrib/linux-kernel/zstd_compress_module.c b/contrib/linux-kernel/zstd_compress_module.c index 804efe6d5..7651b5355 100644 --- a/contrib/linux-kernel/zstd_compress_module.c +++ b/contrib/linux-kernel/zstd_compress_module.c @@ -67,6 +67,12 @@ int zstd_max_clevel(void) } EXPORT_SYMBOL(zstd_max_clevel); +int zstd_default_clevel(void) +{ + return ZSTD_defaultCLevel(); +} +EXPORT_SYMBOL(zstd_default_clevel); + size_t zstd_compress_bound(size_t src_size) { return ZSTD_compressBound(src_size); @@ -80,6 +86,13 @@ zstd_parameters zstd_get_params(int level, } EXPORT_SYMBOL(zstd_get_params); +zstd_compression_parameters zstd_get_cparams(int level, + unsigned long long estimated_src_size, size_t dict_size) +{ + return ZSTD_getCParams(level, estimated_src_size, dict_size); +} +EXPORT_SYMBOL(zstd_get_cparams); + size_t zstd_cctx_set_param(zstd_cctx *cctx, ZSTD_cParameter param, int value) { return ZSTD_CCtx_setParameter(cctx, param, value); @@ -146,6 +159,33 @@ zstd_cctx *zstd_init_cctx(void *workspace, size_t workspace_size) } EXPORT_SYMBOL(zstd_init_cctx); +zstd_cctx *zstd_create_cctx_advanced(zstd_custom_mem custom_mem) +{ + return ZSTD_createCCtx_advanced(custom_mem); +} +EXPORT_SYMBOL(zstd_create_cctx_advanced); + +size_t zstd_free_cctx(zstd_cctx *cctx) +{ + return ZSTD_freeCCtx(cctx); +} +EXPORT_SYMBOL(zstd_free_cctx); + +zstd_cdict *zstd_create_cdict_byreference(const void *dict, size_t dict_size, + zstd_compression_parameters cparams, + zstd_custom_mem custom_mem) +{ + return ZSTD_createCDict_advanced(dict, dict_size, ZSTD_dlm_byRef, + ZSTD_dct_auto, cparams, custom_mem); +} +EXPORT_SYMBOL(zstd_create_cdict_byreference); + +size_t zstd_free_cdict(zstd_cdict *cdict) +{ + return ZSTD_freeCDict(cdict); +} +EXPORT_SYMBOL(zstd_free_cdict); + size_t zstd_compress_cctx(zstd_cctx *cctx, void *dst, size_t dst_capacity, const void *src, size_t src_size, const zstd_parameters *parameters) { @@ -154,6 +194,15 @@ size_t zstd_compress_cctx(zstd_cctx *cctx, void *dst, size_t dst_capacity, } EXPORT_SYMBOL(zstd_compress_cctx); +size_t zstd_compress_using_cdict(zstd_cctx *cctx, void *dst, + size_t dst_capacity, const void *src, size_t src_size, + const ZSTD_CDict *cdict) +{ + return ZSTD_compress_usingCDict(cctx, dst, dst_capacity, + src, src_size, cdict); +} +EXPORT_SYMBOL(zstd_compress_using_cdict); + size_t zstd_cstream_workspace_bound(const zstd_compression_parameters *cparams) { return ZSTD_estimateCStreamSize_usingCParams(*cparams); diff --git a/contrib/linux-kernel/zstd_decompress_module.c b/contrib/linux-kernel/zstd_decompress_module.c index 7d31518e9..0ae819f0c 100644 --- a/contrib/linux-kernel/zstd_decompress_module.c +++ b/contrib/linux-kernel/zstd_decompress_module.c @@ -44,6 +44,33 @@ size_t zstd_dctx_workspace_bound(void) } EXPORT_SYMBOL(zstd_dctx_workspace_bound); +zstd_dctx *zstd_create_dctx_advanced(zstd_custom_mem custom_mem) +{ + return ZSTD_createDCtx_advanced(custom_mem); +} +EXPORT_SYMBOL(zstd_create_dctx_advanced); + +size_t zstd_free_dctx(zstd_dctx *dctx) +{ + return ZSTD_freeDCtx(dctx); +} +EXPORT_SYMBOL(zstd_free_dctx); + +zstd_ddict *zstd_create_ddict_byreference(const void *dict, size_t dict_size, + zstd_custom_mem custom_mem) +{ + return ZSTD_createDDict_advanced(dict, dict_size, ZSTD_dlm_byRef, + ZSTD_dct_auto, custom_mem); + +} +EXPORT_SYMBOL(zstd_create_ddict_byreference); + +size_t zstd_free_ddict(zstd_ddict *ddict) +{ + return ZSTD_freeDDict(ddict); +} +EXPORT_SYMBOL(zstd_free_ddict); + zstd_dctx *zstd_init_dctx(void *workspace, size_t workspace_size) { if (workspace == NULL) @@ -59,6 +86,15 @@ size_t zstd_decompress_dctx(zstd_dctx *dctx, void *dst, size_t dst_capacity, } EXPORT_SYMBOL(zstd_decompress_dctx); +size_t zstd_decompress_using_ddict(zstd_dctx *dctx, + void *dst, size_t dst_capacity, const void* src, size_t src_size, + const zstd_ddict* ddict) +{ + return ZSTD_decompress_usingDDict(dctx, dst, dst_capacity, src, + src_size, ddict); +} +EXPORT_SYMBOL(zstd_decompress_using_ddict); + size_t zstd_dstream_workspace_bound(size_t max_window_size) { return ZSTD_estimateDStreamSize(max_window_size); From 83db5376d71f55e1394a7c5cdc49b9d3e37e0e93 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Mar 2025 05:44:17 +0000 Subject: [PATCH 724/937] Bump actions/checkout from 3 to 4 Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4. - [Release notes](https://github.com/actions/checkout/releases) - [Commits](https://github.com/actions/checkout/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- .github/workflows/dev-long-tests.yml | 52 ++++++------ .github/workflows/dev-short-tests.yml | 82 +++++++++---------- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/release_check.yml | 4 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 7 files changed, 73 insertions(+), 73 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 175add4ff..5746d86f7 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Set up JDK 17 uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0 diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index c0dbe38d0..275b22297 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -15,7 +15,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: make all run: make all @@ -26,7 +26,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: make test run: make test @@ -34,7 +34,7 @@ jobs: make-test-macos: runs-on: macos-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: make test on macos run: make test @@ -45,7 +45,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update @@ -56,21 +56,21 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream uasan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream @@ -78,7 +78,7 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest @@ -86,7 +86,7 @@ jobs: big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -97,7 +97,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -109,14 +109,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # tag=v4.1.1 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Sun, 2 Mar 2025 23:10:09 -0800 Subject: [PATCH 725/937] Update publish-release-artifacts.yml fix version comment --- .github/workflows/publish-release-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish-release-artifacts.yml b/.github/workflows/publish-release-artifacts.yml index 0d06ccbed..24d86db96 100644 --- a/.github/workflows/publish-release-artifacts.yml +++ b/.github/workflows/publish-release-artifacts.yml @@ -17,7 +17,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v3 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Archive env: From 3c6c472f01d2cdaa52fc87fbb65eaa9808205de0 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 2 Mar 2025 23:11:08 -0800 Subject: [PATCH 726/937] Update scorecards.yml edit version comment --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index f7bc9913e..4ca5b5312 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -27,7 +27,7 @@ jobs: steps: - name: "Checkout code" - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v3 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 with: persist-credentials: false From cab2a29c36c81d218e41ec48559dd2cdee4f0943 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 2 Mar 2025 23:11:35 -0800 Subject: [PATCH 727/937] Update windows-artifacts.yml edit version comment --- .github/workflows/windows-artifacts.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 3cfa841cb..79e910b57 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -25,7 +25,7 @@ jobs: run: shell: msys2 {0} steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v3 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} From 9ec1a7c0ac0ee1e93520424782b85b4df99a537c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 3 Mar 2025 14:27:43 -0800 Subject: [PATCH 728/937] update zstd build recipe to also support lz4 format --- .github/workflows/windows-artifacts.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 79e910b57..0394ec983 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -29,7 +29,7 @@ jobs: - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} - install: make zlib p7zip git mingw-w64-${{matrix.env}}-gcc + install: make zlib mingw-w64-x86_64-lz4 p7zip git mingw-w64-${{matrix.env}}-gcc update: true - name: display versions @@ -42,9 +42,16 @@ jobs: git clone --depth 1 --branch v1.3.1 https://github.com/madler/zlib make -C zlib -f win32/Makefile.gcc libz.a + - name: Building lz4 to static link + run: | + git clone --depth 1 --branch v1.10.0 https://github.com/lz4/lz4 + # ensure both libraries use the same version of libxxhash + cp lib/common/xxhash.* lz4/lib + CPPFLAGS=-DXXH_NAMESPACE=LZ4_ make -C lz4/lib liblz4.a V=1 + - name: Building zstd programs run: | - CPPFLAGS=-I../zlib LDLIBS=../zlib/libz.a LDFLAGS=-static make -j allzstd V=1 + CPPFLAGS="-I../zlib -I../lz4/lib" LDLIBS="../zlib/libz.a ../lz4/lib/liblz4.a" LDFLAGS=-static make -j allzstd V=1 - name: Create artifacts run: | From bceb8f2dbc6c28f3e0d546d5222a89b753bdeede Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 3 Mar 2025 15:54:29 -0800 Subject: [PATCH 729/937] attempt to no longer depend on system library presence for autodetection use explicit opt-in and path setting --- .github/workflows/windows-artifacts.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 0394ec983..4baa2f555 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -29,7 +29,7 @@ jobs: - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 with: msystem: ${{ matrix.msystem }} - install: make zlib mingw-w64-x86_64-lz4 p7zip git mingw-w64-${{matrix.env}}-gcc + install: make p7zip git mingw-w64-${{matrix.env}}-gcc update: true - name: display versions @@ -51,7 +51,7 @@ jobs: - name: Building zstd programs run: | - CPPFLAGS="-I../zlib -I../lz4/lib" LDLIBS="../zlib/libz.a ../lz4/lib/liblz4.a" LDFLAGS=-static make -j allzstd V=1 + CPPFLAGS="-I../zlib -I../lz4/lib" LDFLAGS=-static make -j allzstd V=1 HAVE_ZLIB=1 HAVE_LZ4=1 HAVE_LZMA=0 LDLIBS="../zlib/libz.a ../lz4/lib/liblz4.a" - name: Create artifacts run: | From d5dbdd6ece53ac5bcab2b91fcd7a1b776b84dfb1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 12:51:39 -0800 Subject: [PATCH 730/937] changed command --blocksize into --split to reduce confusion with the concept of "blocks" inside a Zstandard frame. We are now talking about "independent chunks" being produced by a `split` operation. updated documentation accordingly. Note: old commands "-B#` and `--blocksize=#` remain supported, to maintain compatibility with existing scripts. --- programs/benchzstd.h | 4 +-- programs/zstd.1.md | 18 ++++++------ programs/zstdcli.c | 66 +++++++++++++++++++++++++------------------- 3 files changed, 49 insertions(+), 39 deletions(-) diff --git a/programs/benchzstd.h b/programs/benchzstd.h index 4fd0e5a8a..db4d72f9d 100644 --- a/programs/benchzstd.h +++ b/programs/benchzstd.h @@ -92,9 +92,9 @@ typedef enum { } BMK_mode_t; typedef struct { - BMK_mode_t mode; /* 0: all, 1: compress only 2: decode only */ + BMK_mode_t mode; /* 0: both, 1: compress only 2: decode only */ unsigned nbSeconds; /* default timing is in nbSeconds */ - size_t blockSize; /* Maximum size of each block*/ + size_t blockSize; /* Maximum size of each independent chunk */ size_t targetCBlockSize;/* Approximative size of compressed blocks */ int nbWorkers; /* multithreading */ unsigned realTime; /* real time priority */ diff --git a/programs/zstd.1.md b/programs/zstd.1.md index e5c1b7fd2..3b7bc342a 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -113,7 +113,11 @@ the last one takes effect. Because the compressor's behavior highly depends on the content to compress, there's no guarantee of a smooth progression from one level to another. * `--ultra`: unlocks high compression levels 20+ (maximum 22), using a lot more memory. - Note that decompression will also require more memory when using these levels. + Decompression will also need more memory when using these levels. +* `--max`: + set advanced parameters to reach maximum compression. + warning: this setting is very slow and uses a lot of resources. + It's inappropriate for 32-bit mode and therefore disabled in this mode. * `--fast[=#]`: switch to ultra-fast compression levels. If `=#` is not present, it defaults to `1`. @@ -161,10 +165,6 @@ the last one takes effect. Note: If `windowLog` is set to larger than 27, `--long=windowLog` or `--memory=windowSize` needs to be passed to the decompressor. -* `--max`: - set advanced parameters to maximum compression. - warning: this setting is very slow and uses a lot of resources. - It's inappropriate for 32-bit mode and therefore disabled in this mode. * `-D DICT`: use `DICT` as Dictionary to compress or decompress FILE(s) * `--patch-from FILE`: @@ -554,8 +554,8 @@ Compression of small files similar to the sample set will be greatly improved. Use `#` compression level during training (optional). Will generate statistics more tuned for selected compression level, resulting in a _small_ compression ratio improvement for this level. -* `-B#`: - Split input files into blocks of size # (default: no split) +* `--split=#`: + Split input files into independent chunks of size # (default: no split) * `-M#`, `--memory=#`: Limit the amount of sample data loaded for training (default: 2 GB). Note that the default (2 GB) is also the maximum. @@ -683,8 +683,8 @@ Benchmarking will employ `max(1, min(4, nbCores/4))` worker threads by default i benchmark decompression speed only (requires providing a zstd-compressed content) * `-i#`: minimum evaluation time, in seconds (default: 3s), benchmark mode only -* `-B#`, `--block-size=#`: - cut file(s) into independent chunks of size # (default: no chunking) +* `--split=#`: + split input file(s) into independent chunks of size # (default: no chunking) * `-S`: output one benchmark result per input file (default: consolidated result) * `-D dictionary` diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 83d9b881e..38d00225f 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -307,7 +307,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" -b# Perform benchmarking with compression level #. [Default: %d]\n", ZSTDCLI_CLEVEL_DEFAULT); DISPLAYOUT(" -e# Test all compression levels up to #; starting level is `-b#`. [Default: 1]\n"); DISPLAYOUT(" -i# Set the minimum evaluation to time # seconds. [Default: 3]\n"); - DISPLAYOUT(" -B# Cut file into independent chunks of size #. [Default: No chunking]\n"); + DISPLAYOUT(" --split=# Split input into independent chunks of size #. [Default: No chunking]\n"); DISPLAYOUT(" -S Output one benchmark result per input file. [Default: Consolidated result]\n"); DISPLAYOUT(" -D dictionary Benchmark using dictionary \n"); DISPLAYOUT(" --priority=rt Set process priority to real-time.\n"); @@ -773,7 +773,7 @@ static int init_cLevel(void) { } #ifdef ZSTD_MULTITHREAD -static unsigned default_nbThreads(void) { +static int default_nbThreads(void) { const char* const env = getenv(ENV_NBTHREADS); if (env != NULL) { const char* ptr = env; @@ -783,7 +783,7 @@ static unsigned default_nbThreads(void) { DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env); return ZSTDCLI_NBTHREADS_DEFAULT; } else if (*ptr == 0) { - return nbThreads; + return (int)nbThreads; } } DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env); @@ -810,22 +810,31 @@ static unsigned default_nbThreads(void) { CLEAN_RETURN(1); \ } } } -#define NEXT_UINT32(val32) { \ - const char* __nb; \ - NEXT_FIELD(__nb); \ - val32 = readU32FromChar(&__nb); \ - if(*__nb != 0) { \ +#define NEXT_INT32(_vari32) { \ + const char* __nb; \ + NEXT_FIELD(__nb); \ + _vari32 = (int)readU32FromChar(&__nb); \ + if(*__nb != 0) { \ errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ - } \ + } \ } -#define NEXT_TSIZE(valTsize) { \ - const char* __nb; \ - NEXT_FIELD(__nb); \ - valTsize = readSizeTFromChar(&__nb); \ - if(*__nb != 0) { \ +#define NEXT_UINT32(_varu32) { \ + const char* __nb; \ + NEXT_FIELD(__nb); \ + _varu32 = readU32FromChar(&__nb); \ + if(*__nb != 0) { \ errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ - } \ + } \ +} + +#define NEXT_TSIZE(_varTsize) { \ + const char* __nb; \ + NEXT_FIELD(__nb); \ + _varTsize = readSizeTFromChar(&__nb); \ + if(*__nb != 0) { \ + errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ + } \ } typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode; @@ -871,7 +880,7 @@ int main(int argCount, const char* argv[]) int nbWorkers = -1; /* -1 means unset */ double compressibility = -1.0; /* lorem ipsum generator */ unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */ - size_t blockSize = 0; + size_t chunkSize = 0; FIO_prefs_t* const prefs = FIO_createPreferences(); FIO_ctx_t* const fCtx = FIO_createContext(); @@ -1069,11 +1078,12 @@ int main(int argCount, const char* argv[]) continue; } #endif - if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; } + if (longCommandWArg(&argument, "--threads")) { NEXT_INT32(nbWorkers); continue; } if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; } - if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(blockSize); continue; } + if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(chunkSize); continue; } /* hidden command, prefer --split below */ + if (longCommandWArg(&argument, "--split")) { NEXT_TSIZE(chunkSize); continue; } if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; } if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; } if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; } @@ -1256,10 +1266,10 @@ int main(int argCount, const char* argv[]) bench_nbSeconds = readU32FromChar(&argument); break; - /* cut input into blocks (benchmark only) */ + /* cut input into independent chunks (benchmark only) */ case 'B': argument++; - blockSize = readU32FromChar(&argument); + chunkSize = readU32FromChar(&argument); break; /* benchmark files separately (hidden option) */ @@ -1273,7 +1283,7 @@ int main(int argCount, const char* argv[]) /* nb of threads (hidden option) */ case 'T': argument++; - nbWorkers = readU32FromChar(&argument); + nbWorkers = (int)readU32FromChar(&argument); break; /* Dictionary Selection level */ @@ -1324,10 +1334,10 @@ int main(int argCount, const char* argv[]) if ((nbWorkers==0) && (!singleThread)) { /* automatically set # workers based on # of reported cpus */ if (defaultLogicalCores) { - nbWorkers = (unsigned)UTIL_countLogicalCores(); + nbWorkers = UTIL_countLogicalCores(); DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers); } else { - nbWorkers = (unsigned)UTIL_countPhysicalCores(); + nbWorkers = UTIL_countPhysicalCores(); DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers); } } @@ -1404,7 +1414,7 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n"); CLEAN_RETURN(1); } - benchParams.blockSize = blockSize; + benchParams.blockSize = chunkSize; benchParams.targetCBlockSize = targetCBlockSize; benchParams.nbWorkers = (int)nbWorkers; benchParams.realTime = (unsigned)setRealTimePrio; @@ -1464,18 +1474,18 @@ int main(int argCount, const char* argv[]) int const optimize = !coverParams.k || !coverParams.d; coverParams.nbThreads = (unsigned)nbWorkers; coverParams.zParams = zParams; - operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize, memLimit); + operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, chunkSize, NULL, &coverParams, NULL, optimize, memLimit); } else if (dict == fastCover) { int const optimize = !fastCoverParams.k || !fastCoverParams.d; fastCoverParams.nbThreads = (unsigned)nbWorkers; fastCoverParams.zParams = zParams; - operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize, memLimit); + operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, chunkSize, NULL, NULL, &fastCoverParams, optimize, memLimit); } else { ZDICT_legacy_params_t dictParams; memset(&dictParams, 0, sizeof(dictParams)); dictParams.selectivityLevel = dictSelect; dictParams.zParams = zParams; - operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0, memLimit); + operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, chunkSize, &dictParams, NULL, NULL, 0, memLimit); } #else (void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */ @@ -1583,7 +1593,7 @@ int main(int argCount, const char* argv[]) FIO_setCompressionType(prefs, cType); FIO_setContentSize(prefs, contentSize); FIO_setNbWorkers(prefs, (int)nbWorkers); - FIO_setBlockSize(prefs, (int)blockSize); + FIO_setBlockSize(prefs, (int)chunkSize); if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog); FIO_setLdmFlag(prefs, (unsigned)ldmFlag); FIO_setLdmHashLog(prefs, (int)g_ldmHashLog); From fcfb3160dcc58fa478e790cff0a625bddbe6bca7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 13:04:59 -0800 Subject: [PATCH 731/937] convert benchmark unit to use the new naming scheme chunks instead of blocks --- programs/benchzstd.c | 113 +++++++++++++++++++------------------------ programs/benchzstd.h | 2 +- programs/zstdcli.c | 2 +- 3 files changed, 53 insertions(+), 64 deletions(-) diff --git a/programs/benchzstd.c b/programs/benchzstd.c index f9274a517..f55c86975 100644 --- a/programs/benchzstd.c +++ b/programs/benchzstd.c @@ -208,7 +208,7 @@ BMK_advancedParams_t BMK_initAdvancedParams(void) BMK_advancedParams_t const res = { BMK_both, /* mode */ BMK_TIMETEST_DEFAULT_S, /* nbSeconds */ - 0, /* blockSize */ + 0, /* chunkSizeMax */ 0, /* targetCBlockSize */ 0, /* nbWorkers */ 0, /* realTime */ @@ -227,16 +227,6 @@ BMK_advancedParams_t BMK_initAdvancedParams(void) /* ******************************************************** * Bench functions **********************************************************/ -typedef struct { - const void* srcPtr; - size_t srcSize; - void* cPtr; - size_t cRoom; - size_t cSize; - void* resPtr; - size_t resSize; -} blockParam_t; - #undef MIN #undef MAX #define MIN(a, b) ((a) < (b) ? (a) : (b)) @@ -435,16 +425,16 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( const char* displayName, const BMK_advancedParams_t* adv) { - size_t const blockSize = - ((adv->blockSize >= 32 && (adv->mode != BMK_decodeOnly)) - ? adv->blockSize + size_t const chunkSizeMax = + ((adv->chunkSizeMax >= 32 && (adv->mode != BMK_decodeOnly)) + ? adv->chunkSizeMax : srcSize) + (!srcSize); /* avoid div by 0 */ BMK_benchResult_t benchResult; size_t const loadedCompressedSize = srcSize; size_t cSize = 0; double ratio = 0.; - U32 nbBlocks; + U32 nbChunks = 0; assert(cctx != NULL); assert(dctx != NULL); @@ -500,41 +490,42 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( } } - /* Init data blocks */ + /* Init data chunks */ { const char* srcPtr = (const char*)srcBuffer; char* cPtr = (char*)compressedBuffer; char* resPtr = (char*)(*resultBufferPtr); - U32 fileNb; - for (nbBlocks = 0, fileNb = 0; fileNb < nbFiles; fileNb++) { + U32 fileNb, chunkID; + for (chunkID = 0, fileNb = 0; fileNb < nbFiles; fileNb++) { size_t remaining = fileSizes[fileNb]; - U32 const nbBlocksforThisFile = (adv->mode == BMK_decodeOnly) + U32 const nbChunksforThisFile = (adv->mode == BMK_decodeOnly) ? 1 - : (U32)((remaining + (blockSize - 1)) / blockSize); - U32 const blockEnd = nbBlocks + nbBlocksforThisFile; - for (; nbBlocks < blockEnd; nbBlocks++) { - size_t const thisBlockSize = MIN(remaining, blockSize); - srcPtrs[nbBlocks] = srcPtr; - srcSizes[nbBlocks] = thisBlockSize; - cPtrs[nbBlocks] = cPtr; - cCapacities[nbBlocks] = (adv->mode == BMK_decodeOnly) - ? thisBlockSize - : ZSTD_compressBound(thisBlockSize); - resPtrs[nbBlocks] = resPtr; - resSizes[nbBlocks] = (adv->mode == BMK_decodeOnly) + : (U32)((remaining + (chunkSizeMax - 1)) / chunkSizeMax); + U32 const chunkIdEnd = chunkID + nbChunksforThisFile; + for (; chunkID < chunkIdEnd; chunkID++) { + size_t const chunkSize = MIN(remaining, chunkSizeMax); + srcPtrs[chunkID] = srcPtr; + srcSizes[chunkID] = chunkSize; + cPtrs[chunkID] = cPtr; + cCapacities[chunkID] = (adv->mode == BMK_decodeOnly) + ? chunkSize + : ZSTD_compressBound(chunkSize); + resPtrs[chunkID] = resPtr; + resSizes[chunkID] = (adv->mode == BMK_decodeOnly) ? (size_t)ZSTD_findDecompressedSize( - srcPtr, thisBlockSize) - : thisBlockSize; - srcPtr += thisBlockSize; - cPtr += cCapacities[nbBlocks]; - resPtr += thisBlockSize; - remaining -= thisBlockSize; + srcPtr, chunkSize) + : chunkSize; + srcPtr += chunkSize; + cPtr += cCapacities[chunkID]; + resPtr += chunkSize; + remaining -= chunkSize; if (adv->mode == BMK_decodeOnly) { - cSizes[nbBlocks] = thisBlockSize; - benchResult.cSize = thisBlockSize; + cSizes[chunkID] = chunkSize; + benchResult.cSize = chunkSize; } } } + nbChunks = chunkID; } /* warming up `compressedBuffer` */ @@ -569,7 +560,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( cbp.initFn = local_initCCtx; /* BMK_initCCtx */ cbp.initPayload = &cctxprep; cbp.errorFn = ZSTD_isError; - cbp.blockCount = nbBlocks; + cbp.blockCount = nbChunks; cbp.srcBuffers = srcPtrs; cbp.srcSizes = srcSizes; cbp.dstBuffers = cPtrs; @@ -588,7 +579,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( dbp.initFn = local_initDCtx; dbp.initPayload = &dctxprep; dbp.errorFn = ZSTD_isError; - dbp.blockCount = nbBlocks; + dbp.blockCount = nbChunks; dbp.srcBuffers = (const void* const*)cPtrs; dbp.srcSizes = cSizes; dbp.dstBuffers = resPtrs; @@ -690,8 +681,7 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( } /* while (!(compressionCompleted && decompressionCompleted)) */ /* CRC Checking */ - { - const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr); + { const BYTE* resultBuffer = (const BYTE*)(*resultBufferPtr); U64 const crcCheck = XXH64(resultBuffer, srcSize, 0); if ((adv->mode == BMK_both) && (crcOrig != crcCheck)) { size_t u; @@ -704,14 +694,14 @@ static BMK_benchOutcome_t BMK_benchMemAdvancedNoAlloc( unsigned segNb, bNb, pos; size_t bacc = 0; DISPLAY("Decoding error at pos %u ", (unsigned)u); - for (segNb = 0; segNb < nbBlocks; segNb++) { + for (segNb = 0; segNb < nbChunks; segNb++) { if (bacc + srcSizes[segNb] > u) break; bacc += srcSizes[segNb]; } pos = (U32)(u - bacc); bNb = pos / (128 KB); - DISPLAY("(sample %u, block %u, pos %u) \n", + DISPLAY("(sample %u, chunk %u, pos %u) \n", segNb, bNb, pos); @@ -795,25 +785,24 @@ BMK_benchOutcome_t BMK_benchMemAdvanced( int const dstParamsError = !dstBuffer ^ !dstCapacity; /* must be both NULL or none */ - size_t const blockSize = - ((adv->blockSize >= 32 && (adv->mode != BMK_decodeOnly)) - ? adv->blockSize + size_t const chunkSize = + ((adv->chunkSizeMax >= 32 && (adv->mode != BMK_decodeOnly)) + ? adv->chunkSizeMax : srcSize) + (!srcSize) /* avoid div by 0 */; - U32 const maxNbBlocks = - (U32)((srcSize + (blockSize - 1)) / blockSize) + nbFiles; + U32 const nbChunksMax = + (U32)((srcSize + (chunkSize - 1)) / chunkSize) + nbFiles; - /* these are the blockTable parameters, just split up */ const void** const srcPtrs = - (const void**)malloc(maxNbBlocks * sizeof(void*)); - size_t* const srcSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t)); + (const void**)malloc(nbChunksMax * sizeof(void*)); + size_t* const srcSizes = (size_t*)malloc(nbChunksMax * sizeof(size_t)); - void** const cPtrs = (void**)malloc(maxNbBlocks * sizeof(void*)); - size_t* const cSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t)); - size_t* const cCapacities = (size_t*)malloc(maxNbBlocks * sizeof(size_t)); + void** const cPtrs = (void**)malloc(nbChunksMax * sizeof(void*)); + size_t* const cSizes = (size_t*)malloc(nbChunksMax * sizeof(size_t)); + size_t* const cCapacities = (size_t*)malloc(nbChunksMax * sizeof(size_t)); - void** const resPtrs = (void**)malloc(maxNbBlocks * sizeof(void*)); - size_t* const resSizes = (size_t*)malloc(maxNbBlocks * sizeof(size_t)); + void** const resPtrs = (void**)malloc(nbChunksMax * sizeof(void*)); + size_t* const resSizes = (size_t*)malloc(nbChunksMax * sizeof(size_t)); BMK_timedFnState_t* timeStateCompress = BMK_createTimedFnState( adv->nbSeconds * 1000, BMK_RUNTEST_DEFAULT_MS); @@ -825,7 +814,7 @@ BMK_benchOutcome_t BMK_benchMemAdvanced( const size_t maxCompressedSize = dstCapacity ? dstCapacity - : ZSTD_compressBound(srcSize) + (maxNbBlocks * 1024); + : ZSTD_compressBound(srcSize) + (nbChunksMax * 1024); void* const internalDstBuffer = dstBuffer ? NULL : malloc(maxCompressedSize); @@ -964,12 +953,12 @@ static int BMK_benchCLevels( } if (displayLevel == 1 && !adv->additionalParam) /* --quiet mode */ - OUTPUT("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n", + OUTPUT("bench %s %s: input %u bytes, %u seconds, %u KB chunks\n", ZSTD_VERSION_STRING, ZSTD_GIT_COMMIT_STRING, (unsigned)benchedSize, adv->nbSeconds, - (unsigned)(adv->blockSize >> 10)); + (unsigned)(adv->chunkSizeMax >> 10)); for (level = startCLevel; level <= endCLevel; level++) { BMK_benchOutcome_t res = BMK_benchMemAdvanced( @@ -1000,7 +989,7 @@ int BMK_syntheticTest( { char nameBuff[20] = { 0 }; const char* name = nameBuff; - size_t const benchedSize = adv->blockSize ? adv->blockSize : 10000000; + size_t const benchedSize = adv->chunkSizeMax ? adv->chunkSizeMax : 10000000; /* Memory allocation */ void* const srcBuffer = malloc(benchedSize); diff --git a/programs/benchzstd.h b/programs/benchzstd.h index db4d72f9d..d62a33c0a 100644 --- a/programs/benchzstd.h +++ b/programs/benchzstd.h @@ -94,7 +94,7 @@ typedef enum { typedef struct { BMK_mode_t mode; /* 0: both, 1: compress only 2: decode only */ unsigned nbSeconds; /* default timing is in nbSeconds */ - size_t blockSize; /* Maximum size of each independent chunk */ + size_t chunkSizeMax; /* Maximum size of each independent chunk */ size_t targetCBlockSize;/* Approximative size of compressed blocks */ int nbWorkers; /* multithreading */ unsigned realTime; /* real time priority */ diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 38d00225f..7395e9585 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1414,7 +1414,7 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n"); CLEAN_RETURN(1); } - benchParams.blockSize = chunkSize; + benchParams.chunkSizeMax = chunkSize; benchParams.targetCBlockSize = targetCBlockSize; benchParams.nbWorkers = (int)nbWorkers; benchParams.realTime = (unsigned)setRealTimePrio; From 19ffcf81b88909f28757d7d367696d298f2c5e46 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 13:17:10 -0800 Subject: [PATCH 732/937] changed -B# command into --jobsize to reduce confusion with the term "block". -B# remains supported for existing scripts, but it's no longer documented, so it's effectively a hidden shortcut. --- programs/zstd.1.md | 8 ++++---- programs/zstdcli.c | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 3b7bc342a..cf1810d59 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -503,12 +503,12 @@ similar to predefined level 19 for files bigger than 256 KB: `--zstd`=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6 -### -B#: +### --jobsize=#: Specify the size of each compression job. -This parameter is only available when multi-threading is enabled. -Each compression job is run in parallel, so this value indirectly impacts the nb of active threads. +This parameter is only meaningful when multi-threading is enabled. +Each compression job is run in parallel, so this value can indirectly impact the nb of active threads. Default job size varies depending on compression level (generally `4 * windowSize`). -`-B#` makes it possible to manually select a custom size. +`--jobsize=#` makes it possible to manually select a custom size. Note that job size must respect a minimum value which is enforced transparently. This minimum is either 512 KB, or `overlapSize`, whichever is largest. Different job sizes will lead to non-identical compressed frames. diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 7395e9585..4b7f496d0 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1084,6 +1084,7 @@ int main(int argCount, const char* argv[]) if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(chunkSize); continue; } /* hidden command, prefer --split below */ if (longCommandWArg(&argument, "--split")) { NEXT_TSIZE(chunkSize); continue; } + if (longCommandWArg(&argument, "--jobsize")) { NEXT_TSIZE(chunkSize); continue; } /* note: overloaded variable */ if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; } if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; } if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; } @@ -1266,7 +1267,7 @@ int main(int argCount, const char* argv[]) bench_nbSeconds = readU32FromChar(&argument); break; - /* cut input into independent chunks (benchmark only) */ + /* hidden shortcut for --split=# and --jobsize=# */ case 'B': argument++; chunkSize = readU32FromChar(&argument); From 9b8b4148338da8ffc81c2e7a2e180ff5316cd31d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 13:22:01 -0800 Subject: [PATCH 733/937] updated playTests.sh to employ the new commands --- tests/playTests.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/playTests.sh b/tests/playTests.sh index 5435ff5b3..65aa5c0b1 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1093,8 +1093,8 @@ println "\n===> dictionary tests " println "- Test high/low compressibility corpus training" datagen -g12M -P90 > tmpCorpusHighCompress datagen -g12M -P5 > tmpCorpusLowCompress -zstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress -zstd --train -B2K tmpCorpusLowCompress -o tmpDictLowCompress +zstd --train --split=2K tmpCorpusHighCompress -o tmpDictHighCompress +zstd --train --split=2K tmpCorpusLowCompress -o tmpDictLowCompress rm -f tmpCorpusHighCompress tmpCorpusLowCompress tmpDictHighCompress tmpDictLowCompress println "- Test with raw dict (content only) " datagen > tmpDict @@ -1179,8 +1179,8 @@ rm -f tmp* dictionary println "- Test --memory for dictionary compression" datagen -g12M -P90 > tmpCorpusHighCompress -zstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=10K && die "Dictionary training should fail : --memory too low (10K)" -zstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=5MB 2> zstTrainWithMemLimitStdErr +zstd --train --split=2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=10K && die "Dictionary training should fail : --memory too low (10K)" +zstd --train --split=2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=5MB 2> zstTrainWithMemLimitStdErr cat zstTrainWithMemLimitStdErr | $GREP "setting manual memory limit for dictionary training data at 5 MB" cat zstTrainWithMemLimitStdErr | $GREP "Training samples set too large (12 MB); training on 5 MB only..." rm zstTrainWithMemLimitStdErr @@ -1555,7 +1555,7 @@ then roundTripTest -g4M "1 -T0 --auto-threads=logical" roundTripTest -g8M "3 -T2" roundTripTest -g8000K "2 --threads=2" - fileRoundTripTest -g4M "19 -T2 -B1M" + fileRoundTripTest -g4M "19 -T2 --split=1M" println "\n===> zstdmt long distance matching round-trip tests " roundTripTest -g8M "3 --long=24 -T2" @@ -1770,7 +1770,7 @@ then println "\n===> rsyncable mode " roundTripTest -g10M " --rsyncable" - roundTripTest -g10M " --rsyncable -B100K" + roundTripTest -g10M " --rsyncable --split=100K" println "===> test: --rsyncable must fail with --single-thread" zstd -f -vv --rsyncable --single-thread tmp && die "--rsyncable must fail with --single-thread" fi From 0298df50f956ab889daf8e5c7e1db8765db1ab11 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 14:43:06 -0800 Subject: [PATCH 734/937] update cli-tests --- programs/dibio.c | 6 +++--- programs/zstdcli.c | 4 ++-- tests/cli-tests/dict-builder/no-inputs.sh.stderr.exact | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/programs/dibio.c b/programs/dibio.c index 7ba22d15b..63c455a22 100644 --- a/programs/dibio.c +++ b/programs/dibio.c @@ -362,9 +362,9 @@ int DiB_trainFromFiles(const char* dictFileName, size_t maxDictSize, DISPLAYLEVEL(2, "! As a consequence, only the first %u bytes of each sample are loaded \n", SAMPLESIZE_MAX); } if (fs.nbSamples < 5) { - DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing ! \n"); - DISPLAYLEVEL(2, "! Please provide _one file per sample_. \n"); - DISPLAYLEVEL(2, "! Alternatively, split files into fixed-size blocks representative of samples, with -B# \n"); + DISPLAYLEVEL(2, "! Warning : nb of samples too low for proper processing !\n"); + DISPLAYLEVEL(2, "! Please provide _one file per sample_.\n"); + DISPLAYLEVEL(2, "! Alternatively, split file(s) into fixed-size samples, with --split=#\n"); EXM_THROW(14, "nb of samples too low"); /* we now clearly forbid this case */ } if (fs.totalSizeToLoad < (S64)maxDictSize * 8) { diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 4b7f496d0..8d3ebcefa 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -235,8 +235,8 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n"); DISPLAYOUT(" --auto-threads={physical|logical}\n"); DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n"); - DISPLAYOUT(" -B# Set job size to #. [Default: 0 (automatic)]\n"); - DISPLAYOUT(" --rsyncable Compress using a rsync-friendly method (`-B` sets block size). \n"); + DISPLAYOUT(" --jobsize=# Set job size to #. [Default: 0 (automatic)]\n"); + DISPLAYOUT(" --rsyncable Compress using a rsync-friendly method (`--jobsize=#` sets unit size). \n"); DISPLAYOUT("\n"); # endif DISPLAYOUT(" --exclude-compressed Only compress files that are not already compressed.\n\n"); diff --git a/tests/cli-tests/dict-builder/no-inputs.sh.stderr.exact b/tests/cli-tests/dict-builder/no-inputs.sh.stderr.exact index d7b3ea020..61f217c34 100644 --- a/tests/cli-tests/dict-builder/no-inputs.sh.stderr.exact +++ b/tests/cli-tests/dict-builder/no-inputs.sh.stderr.exact @@ -1,5 +1,5 @@ zstd --train -! Warning : nb of samples too low for proper processing ! -! Please provide _one file per sample_. -! Alternatively, split files into fixed-size blocks representative of samples, with -B# +! Warning : nb of samples too low for proper processing ! +! Please provide _one file per sample_. +! Alternatively, split file(s) into fixed-size samples, with --split=# Error 14 : nb of samples too low From 0b40c513fdd7c922ea48838790c3cbd9a229eab1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 14:55:25 -0800 Subject: [PATCH 735/937] update fileio to employ jobSize --- programs/fileio.c | 12 ++++++------ programs/fileio.h | 2 +- programs/fileio_types.h | 2 +- programs/zstdcli.c | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 0ecca40d2..3f4460594 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -288,7 +288,7 @@ FIO_prefs_t* FIO_createPreferences(void) ret->removeSrcFile = 0; ret->memLimit = 0; ret->nbWorkers = 1; - ret->blockSize = 0; + ret->jobSize = 0; ret->overlapLog = FIO_OVERLAP_LOG_NOTSET; ret->adaptiveMode = 0; ret->rsyncable = 0; @@ -377,10 +377,10 @@ void FIO_setExcludeCompressedFile(FIO_prefs_t* const prefs, int excludeCompresse void FIO_setAllowBlockDevices(FIO_prefs_t* const prefs, int allowBlockDevices) { prefs->allowBlockDevices = allowBlockDevices; } -void FIO_setBlockSize(FIO_prefs_t* const prefs, int blockSize) { - if (blockSize && prefs->nbWorkers==0) +void FIO_setJobSize(FIO_prefs_t* const prefs, int jobSize) { + if (jobSize && prefs->nbWorkers==0) DISPLAYLEVEL(2, "Setting block size is useless in single-thread mode \n"); - prefs->blockSize = blockSize; + prefs->jobSize = jobSize; } void FIO_setOverlapLog(FIO_prefs_t* const prefs, int overlapLog){ @@ -1183,7 +1183,7 @@ static cRess_t FIO_createCResources(FIO_prefs_t* const prefs, #ifdef ZSTD_MULTITHREAD DISPLAYLEVEL(5,"set nb workers = %u \n", prefs->nbWorkers); CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_nbWorkers, prefs->nbWorkers) ); - CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_jobSize, prefs->blockSize) ); + CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_jobSize, prefs->jobSize) ); if (prefs->overlapLog != FIO_OVERLAP_LOG_NOTSET) { DISPLAYLEVEL(3,"set overlapLog = %u \n", prefs->overlapLog); CHECK( ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_overlapLog, prefs->overlapLog) ); @@ -2118,7 +2118,7 @@ void FIO_displayCompressionParameters(const FIO_prefs_t* prefs) DISPLAY("%s", INDEX(sparseOptions, prefs->sparseFileSupport)); DISPLAY("%s", prefs->dictIDFlag ? "" : " --no-dictID"); DISPLAY("%s", INDEX(checkSumOptions, prefs->checksumFlag)); - DISPLAY(" --block-size=%d", prefs->blockSize); + DISPLAY(" --jobsize=%d", prefs->jobSize); if (prefs->adaptiveMode) DISPLAY(" --adapt=min=%d,max=%d", prefs->minAdaptLevel, prefs->maxAdaptLevel); DISPLAY("%s", INDEX(rowMatchFinderOptions, prefs->useRowMatchFinder)); diff --git a/programs/fileio.h b/programs/fileio.h index cb53ef537..5d7334ef5 100644 --- a/programs/fileio.h +++ b/programs/fileio.h @@ -70,7 +70,7 @@ void FIO_setAdaptiveMode(FIO_prefs_t* const prefs, int adapt); void FIO_setAdaptMin(FIO_prefs_t* const prefs, int minCLevel); void FIO_setAdaptMax(FIO_prefs_t* const prefs, int maxCLevel); void FIO_setUseRowMatchFinder(FIO_prefs_t* const prefs, int useRowMatchFinder); -void FIO_setBlockSize(FIO_prefs_t* const prefs, int blockSize); +void FIO_setJobSize(FIO_prefs_t* const prefs, int jobSize); void FIO_setChecksumFlag(FIO_prefs_t* const prefs, int checksumFlag); void FIO_setDictIDFlag(FIO_prefs_t* const prefs, int dictIDFlag); void FIO_setLdmBucketSizeLog(FIO_prefs_t* const prefs, int ldmBucketSizeLog); diff --git a/programs/fileio_types.h b/programs/fileio_types.h index 23bda4168..9bbb51549 100644 --- a/programs/fileio_types.h +++ b/programs/fileio_types.h @@ -37,7 +37,7 @@ typedef struct FIO_prefs_s { int sparseFileSupport; /* 0: no sparse allowed; 1: auto (file yes, stdout no); 2: force sparse */ int dictIDFlag; int checksumFlag; - int blockSize; + int jobSize; int overlapLog; int adaptiveMode; int useRowMatchFinder; diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 8d3ebcefa..c84e33858 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1089,7 +1089,7 @@ int main(int argCount, const char* argv[]) if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; } if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; } if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; } - if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; } + if (longCommandWArg(&argument, "--target-compressedlock-size")) { NEXT_TSIZE(targetCBlockSize); continue; } if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; } if (longCommandWArg(&argument, "--output-dir-flat")) { NEXT_FIELD(outDirName); @@ -1459,7 +1459,7 @@ int main(int argCount, const char* argv[]) } #else - (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility; + (void)bench_nbSeconds; (void)chunkSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility; #endif goto _end; } @@ -1594,7 +1594,7 @@ int main(int argCount, const char* argv[]) FIO_setCompressionType(prefs, cType); FIO_setContentSize(prefs, contentSize); FIO_setNbWorkers(prefs, (int)nbWorkers); - FIO_setBlockSize(prefs, (int)chunkSize); + FIO_setJobSize(prefs, (int)chunkSize); if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog); FIO_setLdmFlag(prefs, (unsigned)ldmFlag); FIO_setLdmHashLog(prefs, (int)g_ldmHashLog); From f5a0e047cbe3e4c4de2680e0aa30036330d0ee78 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 15:12:35 -0800 Subject: [PATCH 736/937] fix typo --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index c84e33858..e2771f534 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1089,7 +1089,7 @@ int main(int argCount, const char* argv[]) if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; } if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; } if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; } - if (longCommandWArg(&argument, "--target-compressedlock-size")) { NEXT_TSIZE(targetCBlockSize); continue; } + if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; } if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; } if (longCommandWArg(&argument, "--output-dir-flat")) { NEXT_FIELD(outDirName); From 5ae1cb9fa1f47a257d220dd5c07a2ecea4124f60 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 4 Mar 2025 15:24:43 -0800 Subject: [PATCH 737/937] added a cli test for new command --jobsize --- tests/cli-tests/compression/multi-threaded.sh | 1 + tests/cli-tests/compression/multi-threaded.sh.stderr.exact | 1 + 2 files changed, 2 insertions(+) diff --git a/tests/cli-tests/compression/multi-threaded.sh b/tests/cli-tests/compression/multi-threaded.sh index 17a5eb518..ac094129e 100755 --- a/tests/cli-tests/compression/multi-threaded.sh +++ b/tests/cli-tests/compression/multi-threaded.sh @@ -9,6 +9,7 @@ zstd --rsyncable -f file -q ; zstd -t file.zst zstd -T0 -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=logical -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=physical -f file -q ; zstd -t file.zst +zstd -T0 --jobsize=1M -f file -q ; zstd -t file.zst # multi-thread decompression warning test zstd -T0 -f file -q ; zstd -t file.zst; zstd -T0 -d file.zst -o file3 diff --git a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact index 11daff6ba..0dcf52ac4 100644 --- a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact +++ b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact @@ -7,5 +7,6 @@ file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes +file.zst : 65537 bytes Warning : decompression does not support multi-threading file.zst : 65537 bytes From d5b84f5a27956284d1c07bbb75672c8c224518df Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Tue, 4 Mar 2025 14:55:39 -0500 Subject: [PATCH 738/937] [zstd] Backport D49756856 --- lib/decompress/zstd_decompress_block.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 3a8e634f9..6174a250b 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1726,7 +1726,7 @@ size_t ZSTD_prefetchMatch(size_t prefetchPos, seq_t const sequence, /* 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 = (const BYTE*)ZSTD_wrappedPtrSub(ZSTD_wrappedPtrAdd(matchBase, (ptrdiff_t)prefetchPos), (ptrdiff_t)sequence.offset); - PREFETCH_L1(match); PREFETCH_L1(match+CACHELINE_SIZE); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */ + 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; } From 190a6209749a9461d11a2fd52cbe547d5c087f4a Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Tue, 4 Mar 2025 15:54:49 -0500 Subject: [PATCH 739/937] [zstd] Remove global variables in dictBuilder D50949782 fixed a race condition updating `g_displayLevel` by disabling display. Instead of disabling display, delete the global variable and always "capture" a local `displayLevel` variable. This also fixes `DISPLAYUPDATE()` by requiring the user to pass in the last update time as the first parameter. --- lib/dictBuilder/cover.c | 88 ++++++++++++++++++------------------- lib/dictBuilder/fastcover.c | 79 ++++++++++++++++----------------- 2 files changed, 82 insertions(+), 85 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 6d8889669..cfb756ff2 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -62,38 +62,30 @@ /*-************************************* * 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 @@ -239,6 +231,7 @@ typedef struct { U32 *freqs; U32 *dmerAt; unsigned d; + int displayLevel; } COVER_ctx_t; #if defined(ZSTD_USE_C90_QSORT) \ @@ -602,7 +595,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); @@ -611,6 +604,7 @@ 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; + ctx->displayLevel = displayLevel; /* Checks */ if (totalSamplesSize < MAX(d, sizeof(U64)) || totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) { @@ -695,14 +689,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, @@ -737,6 +731,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 @@ -770,6 +766,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)); } @@ -785,9 +782,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 = 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"); @@ -805,12 +801,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); @@ -1133,6 +1129,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; @@ -1184,21 +1181,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 = (int)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) { @@ -1218,19 +1216,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; @@ -1245,9 +1243,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); @@ -1262,7 +1260,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 = (unsigned)g_displayLevel; + data->parameters.zParams.notificationLevel = (unsigned)ctx.displayLevel; /* Check the parameters */ if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) { DISPLAYLEVEL(1, "Cover parameters incorrect\n"); @@ -1277,14 +1275,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; diff --git a/lib/dictBuilder/fastcover.c b/lib/dictBuilder/fastcover.c index a958eb337..56a081385 100644 --- a/lib/dictBuilder/fastcover.c +++ b/lib/dictBuilder/fastcover.c @@ -49,38 +49,30 @@ /*-************************************* * 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__) /*-************************************* @@ -136,6 +128,7 @@ typedef struct { unsigned d; unsigned f; FASTCOVER_accel_t accelParams; + int displayLevel; } FASTCOVER_ctx_t; @@ -314,7 +307,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); @@ -323,6 +317,7 @@ 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; + ctx->displayLevel = displayLevel; /* Checks */ if (totalSamplesSize < MAX(d, sizeof(U64)) || @@ -409,7 +404,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); @@ -447,6 +444,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)); } @@ -484,6 +482,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; @@ -555,8 +554,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; @@ -585,13 +583,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"); { @@ -646,25 +644,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); } @@ -679,19 +678,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; @@ -706,9 +704,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); @@ -723,7 +721,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)) { @@ -739,14 +737,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; From 0de49919425a82552bc0e5273c5e30537f0e1708 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 6 Mar 2025 17:31:57 -0500 Subject: [PATCH 740/937] Add a method for checking if ZSTD was compiled with flags that impact determinism --- lib/common/portability_macros.h | 19 +++++++++++++++++++ lib/common/zstd_common.c | 9 +++++++++ lib/zstd.h | 12 ++++++++++++ programs/zstdcli.c | 5 ++++- 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/common/portability_macros.h b/lib/common/portability_macros.h index 860734141..bcca634e4 100644 --- a/lib/common/portability_macros.h +++ b/lib/common/portability_macros.h @@ -168,4 +168,23 @@ # 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 */ diff --git a/lib/common/zstd_common.c b/lib/common/zstd_common.c index 3f04c22ab..985420618 100644 --- a/lib/common/zstd_common.c +++ b/lib/common/zstd_common.c @@ -46,3 +46,12 @@ 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 +} diff --git a/lib/zstd.h b/lib/zstd.h index b8c0644a7..4ce2f7742 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -3138,6 +3138,18 @@ 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) */ diff --git a/programs/zstdcli.c b/programs/zstdcli.c index e2771f534..66e9d064b 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -695,7 +695,10 @@ static void printVersion(void) #ifdef PLATFORM_POSIX_VERSION DISPLAYOUT("PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION); #endif - } } + + if (!ZSTD_isDeterministicBuild()) { + DISPLAYOUT("non-deterministic build\n"); + } } } } #define ZSTD_NB_STRATEGIES 9 From b16d193512d3ded82fd584fa822c19ecf67b09a0 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 6 Mar 2025 14:14:38 -0500 Subject: [PATCH 741/937] [test] Add tests for determinism Run compression & validate the compressed file matches a known checksum. To update the output run: ``` make -C tests update-cli-tests ``` --- .github/workflows/dev-short-tests.yml | 3 + tests/Makefile | 6 +- tests/cli-tests/common/platform.sh | 11 + tests/cli-tests/determinism/basic.sh | 36 + .../determinism/basic.sh.stderr.exact | 0 .../determinism/basic.sh.stdout.exact | 880 ++++++++++++++++++ tests/cli-tests/determinism/multithread.sh | 45 + .../determinism/multithread.sh.stderr.exact | 0 .../determinism/multithread.sh.stdout.exact | 260 ++++++ tests/cli-tests/determinism/reuse.sh | 44 + .../determinism/reuse.sh.stderr.exact | 0 .../determinism/reuse.sh.stdout.exact | 19 + tests/cli-tests/determinism/setup | 5 + tests/cli-tests/determinism/setup_once | 30 + tests/cli-tests/run.py | 1 + 15 files changed, 1339 insertions(+), 1 deletion(-) create mode 100755 tests/cli-tests/determinism/basic.sh create mode 100644 tests/cli-tests/determinism/basic.sh.stderr.exact create mode 100644 tests/cli-tests/determinism/basic.sh.stdout.exact create mode 100755 tests/cli-tests/determinism/multithread.sh create mode 100644 tests/cli-tests/determinism/multithread.sh.stderr.exact create mode 100644 tests/cli-tests/determinism/multithread.sh.stdout.exact create mode 100755 tests/cli-tests/determinism/reuse.sh create mode 100644 tests/cli-tests/determinism/reuse.sh.stderr.exact create mode 100644 tests/cli-tests/determinism/reuse.sh.stdout.exact create mode 100755 tests/cli-tests/determinism/setup create mode 100755 tests/cli-tests/determinism/setup_once diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 2e476d72b..2a97c32d0 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -36,6 +36,7 @@ jobs: sudo apt update APT_PACKAGES="gcc-multilib" make apt-install CFLAGS="-m32 -O1 -fstack-protector" make check V=1 + CFLAGS="-m32 -O1 -fstack-protector" make V=1 -C tests test-cli-tests build-c89: runs-on: ubuntu-latest @@ -496,6 +497,7 @@ jobs: run: | make clean LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check + LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests # This test is only compatible with standard libraries that support BTI (Branch Target Identification). # Unfortunately, the standard library provided on Ubuntu 24.04 does not have this feature enabled. # make clean @@ -734,3 +736,4 @@ jobs: run: | source /opt/intel/oneapi/setvars.sh make CC=icx check + make CC=icx -C tests test-cli-tests diff --git a/tests/Makefile b/tests/Makefile index 406c7f20b..b96986cae 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -359,7 +359,11 @@ test-zstd test-zstd32 test-zstd-nolegacy test-zstd-dll: datagen test-cli-tests: ZSTD = $(PRGDIR)/zstd test-cli-tests: zstd datagen file $(ZSTD) - ./cli-tests/run.py --exec-prefix="$(QEMU_SYS)" --zstd="$(ZSTD)" --datagen=./datagen + ./cli-tests/run.py --exec-prefix="$(QEMU_SYS)" --zstd="$(ZSTD)" --datagen=./datagen $(CLI_TEST_ARGS) + +.PHONY: update-cli-tests +update-cli-tests: CLI_TEST_ARGS = --set-exact-output +update-cli-tests: test-cli-tests .PHONY: test-fullbench test-fullbench: fullbench datagen diff --git a/tests/cli-tests/common/platform.sh b/tests/cli-tests/common/platform.sh index a07f229dc..a5bd2f9dc 100644 --- a/tests/cli-tests/common/platform.sh +++ b/tests/cli-tests/common/platform.sh @@ -23,6 +23,11 @@ case "$UNAME" in *) MD5SUM="md5sum" ;; esac +md5hash() { + $MD5SUM | dd bs=1 count=32 status=none + echo +} + DIFF="diff" case "$UNAME" in SunOS) DIFF="gdiff" ;; @@ -34,3 +39,9 @@ then else hasMT="true" fi + +if zstd -vv --version | grep -q 'non-deterministic'; then + NON_DETERMINISTIC="true" +else + NON_DETERMINISTIC="" +fi diff --git a/tests/cli-tests/determinism/basic.sh b/tests/cli-tests/determinism/basic.sh new file mode 100755 index 000000000..7d49956c8 --- /dev/null +++ b/tests/cli-tests/determinism/basic.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +. "$COMMON/platform.sh" + +set -e + +# To update checksums on version change run this from the tests/ directory +# make update-cli-tests + +if [ -n "$NON_DETERMINISTIC" ]; then + # Skip tests if we have a non-deterministic build + cat "$CLI_TESTS/determinism/basic.sh.stdout.exact" + exit 0 +fi + +for level in $(seq 1 19); do + for file in $(ls files/); do + file="files/$file" + echo "level $level, file $file" + zstd --single-thread -q -$level $file -c | md5hash + done +done + +for file in $(ls files/); do + file="files/$file" + echo "level 1, long=18, file $file" + zstd --long=18 --single-thread -q -1 $file -c | md5hash + echo "level 19, long=18, file $file" + zstd --long=18 --single-thread -q -19 $file -c | md5hash +done + +for file in $(ls files/); do + file="files/$file" + echo "level -1, file $file" + zstd -q --single-thread --fast=1 $file -c | md5hash +done diff --git a/tests/cli-tests/determinism/basic.sh.stderr.exact b/tests/cli-tests/determinism/basic.sh.stderr.exact new file mode 100644 index 000000000..e69de29bb diff --git a/tests/cli-tests/determinism/basic.sh.stdout.exact b/tests/cli-tests/determinism/basic.sh.stdout.exact new file mode 100644 index 000000000..bb1723b15 --- /dev/null +++ b/tests/cli-tests/determinism/basic.sh.stdout.exact @@ -0,0 +1,880 @@ +level 1, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 1, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 1, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 1, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 1, file files/g1000 +6bf2f4b179864fd8db4676037465feed +level 1, file files/g10000 +2ae44c4053b2b47724c8f612dfb60d24 +level 1, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 1, file files/g10000-P10 +2d0eeab6a966098583a1dfeafb5090c1 +level 1, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 1, file files/g10000-P25 +c64b5f512c44b6a647da81753791b9a7 +level 1, file files/g10000-P50 +3982325490d90c8307e734c1b25790df +level 1, file files/g10000-P75 +b7504f80fee16b5ba6a0f46571eb563a +level 1, file files/g10000-P90 +350892bec7f7ad6a7d6af01c5d8b07c7 +level 1, file files/g100000 +daa38a869130494c077290cf54f2d895 +level 1, file files/g1000000 +a1d548531221d408b95dc5d9c600b3f0 +level 1, file files/g20000 +1da5b56511e8693867c0cdd962c521aa +level 1, file files/g200000 +41fb3b3d46d4221f2f0b072c65dd6e0a +level 1, file files/g30000 +788bc5abca5e33d79bb79a4eca98b9cd +level 1, file files/g50000 +0bf9fafd84a2d56a788a9159f1f23f26 +level 1, file files/g500000 +73401d6df0657e091de20468f32579a9 +level 2, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 2, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 2, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 2, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 2, file files/g1000 +a14988fb331bc6f8b33d9eba3a0416dc +level 2, file files/g10000 +a8656ebab20efa8a3fb281327aab5d58 +level 2, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 2, file files/g10000-P10 +9db9877242632964c232ebd4485dba07 +level 2, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 2, file files/g10000-P25 +d7a7223240a607fe28a2e8fd641a969d +level 2, file files/g10000-P50 +86478908f9caa5ca4029454005063078 +level 2, file files/g10000-P75 +14f5dcdb347e87790d49c1eb99ac5069 +level 2, file files/g10000-P90 +05bdb42a2eeb5788d6288dc241cde12c +level 2, file files/g100000 +12c6a4c50fad3e479e0f0ffe1d4df324 +level 2, file files/g1000000 +4f9cdc0de37b22d657fd9d3c61ec5b44 +level 2, file files/g20000 +1e70c3fe429c1af41e9cb8a536fb6df1 +level 2, file files/g200000 +bb1cc37142783345db29c3fd5838ce4e +level 2, file files/g30000 +52528017fe0eec85b6c3244e6fceb4ed +level 2, file files/g50000 +a38bdd671b6d3bd76b479dfc01d1c7fb +level 2, file files/g500000 +cd2090a38bbd677b385238355c996c01 +level 3, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 3, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 3, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 3, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 3, file files/g1000 +3ec47dcb2d606b9fdef3f19b1304f8fe +level 3, file files/g10000 +69a9d518b84fe2a66b57dfb4ab8905ae +level 3, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 3, file files/g10000-P10 +ac9866ac355c4ed8939deb9fbeec1aef +level 3, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 3, file files/g10000-P25 +5e1fe7a3831f6632bc8c9873ab8b633d +level 3, file files/g10000-P50 +76295f181396a98565eb9cc69b96dc75 +level 3, file files/g10000-P75 +1f751dc70508e81fef197311e8583e99 +level 3, file files/g10000-P90 +47c7b061c299dc253c6aaaf489e936cb +level 3, file files/g100000 +4b30b2be3394f03f1cf1f37a08dcec12 +level 3, file files/g1000000 +4301dea72cc4dd6162e46caa59788a09 +level 3, file files/g20000 +30456361833d27c0962c2faaa254e615 +level 3, file files/g200000 +0f01c07c57d60298dd54c6b6b197c3d3 +level 3, file files/g30000 +0b3c506a1b1b6ccbb54a852c370f5cdc +level 3, file files/g50000 +81368c0b96bf1a2f318940b836b46074 +level 3, file files/g500000 +0c1ef9c6d3d75bfa0dd5d893f65da47c +level 4, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 4, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 4, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 4, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 4, file files/g1000 +6a1214c19ab13d15934244a4655fa327 +level 4, file files/g10000 +09bbd556d9ee9f74f36b36bfa6b17325 +level 4, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 4, file files/g10000-P10 +1adb177b7a441c3585ffd781654758ba +level 4, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 4, file files/g10000-P25 +3a62170477d7f17d64dc49b971388ff7 +level 4, file files/g10000-P50 +de93403eafd68786410fa52a95752514 +level 4, file files/g10000-P75 +f5466b3cfc3ba1e5afecb8d8bb91250f +level 4, file files/g10000-P90 +132869db4091a9b9bdbc5236435a1d98 +level 4, file files/g100000 +dd92f22c593f40e0ccd6b31ad09d9d18 +level 4, file files/g1000000 +cfe7c063909c635f22438f83eb824082 +level 4, file files/g20000 +f8be159b057c6ee827f36cdd2ee5c43f +level 4, file files/g200000 +71362cc7c28dcc730b591e3002fe888c +level 4, file files/g30000 +f0b899995c6ba86066bd7f407fc708ef +level 4, file files/g50000 +2f293e665d5161e68d8e1f86ac6841be +level 4, file files/g500000 +42c5c45c595af60d5cf28f4cdd8ab392 +level 5, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 5, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 5, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 5, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 5, file files/g1000 +d47284586e181d455017d821bd3de1ef +level 5, file files/g10000 +d6cd223f1c215d332654ca241a376549 +level 5, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 5, file files/g10000-P10 +66b935a7666ae668ac990d5c9aaac652 +level 5, file files/g10000-P100 +15fede9faa3d7c484dead66071fb8c5d +level 5, file files/g10000-P25 +b292339cacea797a184554a2de3c1ed3 +level 5, file files/g10000-P50 +10b65af5125bf21a6810b8fb7a30b8b1 +level 5, file files/g10000-P75 +04fc60ea83db4b6101778f91a73d6040 +level 5, file files/g10000-P90 +302c8c7355082a7f40efe4ea40912411 +level 5, file files/g100000 +338f5e822a469774462f144d7ae371a0 +level 5, file files/g1000000 +46b8608a1f833477387e2fc844a817d5 +level 5, file files/g20000 +b7a468d363a7797d3d7a48577cd20213 +level 5, file files/g200000 +5ed09b3fd58ba540128319c02f9259cb +level 5, file files/g30000 +fd4c0e5acb85271c101fd8ae1f411232 +level 5, file files/g50000 +2a14c76d629615bd50a370e587d13eb8 +level 5, file files/g500000 +cb1122167d4a747f3f8e0dd18bce6fa3 +level 6, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 6, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 6, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 6, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 6, file files/g1000 +19187f900e7540efdcab3735f489f718 +level 6, file files/g10000 +70c03e642fb98b896f2d96c0fa0eca74 +level 6, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 6, file files/g10000-P10 +70e2df33337095c818051d86ea68f188 +level 6, file files/g10000-P100 +15fede9faa3d7c484dead66071fb8c5d +level 6, file files/g10000-P25 +dd4ed2ced4ae48672d5c8c0d4a7d58a5 +level 6, file files/g10000-P50 +9182b845f45f4990c8993e1c54e1e2e6 +level 6, file files/g10000-P75 +d3e6bb5a8e9790d23dda0a38b3def532 +level 6, file files/g10000-P90 +21da6c8aefa00b3e16f7674c642aa043 +level 6, file files/g100000 +350a0f07d7ddbcd0c629da0bcf734f02 +level 6, file files/g1000000 +d40c700beee149ab272b94c7ef0f3811 +level 6, file files/g20000 +335bc3f5767a7d4ad479408b0e289459 +level 6, file files/g200000 +032e3313ca247a8f4687059fa708284c +level 6, file files/g30000 +a4b9fed2e1005298617125ee3b00cb06 +level 6, file files/g50000 +d7b3dab8d19fb992795c440d5f953c94 +level 6, file files/g500000 +44e59ccbf7a9794d4ea03f3f59f61ffd +level 7, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 7, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 7, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 7, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 7, file files/g1000 +19187f900e7540efdcab3735f489f718 +level 7, file files/g10000 +495f1e5d30de3b34c5a76301875fa231 +level 7, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 7, file files/g10000-P10 +8a91fa2460ec9bd0387baa31beb81060 +level 7, file files/g10000-P100 +15fede9faa3d7c484dead66071fb8c5d +level 7, file files/g10000-P25 +7dc0563f2e66a2e57c0f119e4d5e636e +level 7, file files/g10000-P50 +e93a6eb179f7b26daa896328b2583b04 +level 7, file files/g10000-P75 +cb1e5facfc34fca7323000c6188ad657 +level 7, file files/g10000-P90 +e9984c6557f5a392f16e5c139dbe4994 +level 7, file files/g100000 +6e493dbe2985fec69860ef34728ac01a +level 7, file files/g1000000 +455023a055f3a4de76c7295408ce3c8f +level 7, file files/g20000 +2359efcd587e36ac9b74a8344bbf0e53 +level 7, file files/g200000 +ca80dbc88183a5aabb4aae955c449dff +level 7, file files/g30000 +7e1be7e841c9fddd776dbe94b50db0ab +level 7, file files/g50000 +09b80b58d70622de6f2354a06c15cb2a +level 7, file files/g500000 +c90609f0558f0979eccb572ce0af4aa3 +level 8, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 8, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 8, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 8, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 8, file files/g1000 +19187f900e7540efdcab3735f489f718 +level 8, file files/g10000 +495f1e5d30de3b34c5a76301875fa231 +level 8, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 8, file files/g10000-P10 +8a91fa2460ec9bd0387baa31beb81060 +level 8, file files/g10000-P100 +15fede9faa3d7c484dead66071fb8c5d +level 8, file files/g10000-P25 +526c95fd77cbcc2079720bb1b5515a54 +level 8, file files/g10000-P50 +50d4e0154067af438e56729716c3eda7 +level 8, file files/g10000-P75 +c94a94cce795566b065f2d3dca554c28 +level 8, file files/g10000-P90 +8f83ce03eb280cba48bafafbd066b752 +level 8, file files/g100000 +dbc4c43d9dc0937e67e92a908688a51e +level 8, file files/g1000000 +5a4e6e44c89c3538fdb09823e649c8f6 +level 8, file files/g20000 +3653750b7ea2e8dc97d1d24ccec72153 +level 8, file files/g200000 +e978eb15e94cf221f1c7c55a059bbc4a +level 8, file files/g30000 +9668f8c1292931955e14b81d67c2c648 +level 8, file files/g50000 +36a864d5bb5d9167d19ac237ce3bef51 +level 8, file files/g500000 +eaaac1f3c4861d4d501d9c92fa67cc08 +level 9, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 9, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 9, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 9, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 9, file files/g1000 +42d1f8aa9ee42135013077f09b77fd1a +level 9, file files/g10000 +ae4166250554922e9ed27e436c13bf6b +level 9, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 9, file files/g10000-P10 +bd9ede6738524ef732c9516146536acd +level 9, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 9, file files/g10000-P25 +526c95fd77cbcc2079720bb1b5515a54 +level 9, file files/g10000-P50 +af6f029bd0d9baee1a78b8f7ffef5df3 +level 9, file files/g10000-P75 +f56895eec07a63269ea3eaeb59e87f40 +level 9, file files/g10000-P90 +c5cef2890886bfaf2d747b37ededc261 +level 9, file files/g100000 +f11c301dcf8c791e4f2db29e1b388eba +level 9, file files/g1000000 +f90563e0d0962955d31af45fc8f2b19d +level 9, file files/g20000 +49820710f3fbc6627b60071e91dba56d +level 9, file files/g200000 +4689b0eb28c34619d8a9087cfa33fc88 +level 9, file files/g30000 +c14b029711fa6abc627ed3a051902b4c +level 9, file files/g50000 +2d1cde6271f46081fbeaaba10f1c48bb +level 9, file files/g500000 +eaaac1f3c4861d4d501d9c92fa67cc08 +level 10, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 10, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 10, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 10, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 10, file files/g1000 +42d1f8aa9ee42135013077f09b77fd1a +level 10, file files/g10000 +ae4166250554922e9ed27e436c13bf6b +level 10, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 10, file files/g10000-P10 +bd9ede6738524ef732c9516146536acd +level 10, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 10, file files/g10000-P25 +526c95fd77cbcc2079720bb1b5515a54 +level 10, file files/g10000-P50 +6f821eef670933208d85daad6a9a2791 +level 10, file files/g10000-P75 +9c944c50c800d72294bdc9a9a452dc90 +level 10, file files/g10000-P90 +838a22c0731a67d185cac135b2bac5c7 +level 10, file files/g100000 +bbb2e91bdee192ae6f23404542a35bfb +level 10, file files/g1000000 +1e52803b3311c2d4428c56d059901721 +level 10, file files/g20000 +939b50f472cf67c6dfbc4d3074e04011 +level 10, file files/g200000 +adc5f0c58c75e79e4bc4800c015d2401 +level 10, file files/g30000 +43e46ec5aae76c55c890a18f49b0163b +level 10, file files/g50000 +65c57573aef37a38bd6c587ef4388800 +level 10, file files/g500000 +d3c45fce79c26bce889c3fa6a5480200 +level 11, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 11, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 11, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 11, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 11, file files/g1000 +4aa08662527d6d7f996705929e0dd8e0 +level 11, file files/g10000 +330f75029558d7cb6fa2756d85a998bd +level 11, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 11, file files/g10000-P10 +990879c5b3d1c99aa5ef39f6049cebc9 +level 11, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 11, file files/g10000-P25 +26a10f96c2008608a33a731ff39cd9c8 +level 11, file files/g10000-P50 +129c6082daea0da5f52358c71b252750 +level 11, file files/g10000-P75 +7ff21b2c10548b9fc8ec5b61f86b9db0 +level 11, file files/g10000-P90 +0def9775620838420b295c07fd50a196 +level 11, file files/g100000 +c115057c51f9bb603a7d0c6bdf76e422 +level 11, file files/g1000000 +d28d3aed914ba7368dd004a9431c0173 +level 11, file files/g20000 +650cf27ffca49ed98f0e5dbb8997d7eb +level 11, file files/g200000 +3210b89239e35e559be0ccd842577bb4 +level 11, file files/g30000 +09fe5a276e3fec09490c85962263fb26 +level 11, file files/g50000 +a9fa2677e4faab0eaa2334f278b3ec7d +level 11, file files/g500000 +86815b1a35a46312a081f1af4946a62e +level 12, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 12, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 12, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 12, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 12, file files/g1000 +6cb98f0115baf96a720638cf92b7803b +level 12, file files/g10000 +b73485abce0df9802dcfeee652c45a8d +level 12, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 12, file files/g10000-P10 +d00ac554fefc8a0f40420f908ff6fe69 +level 12, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 12, file files/g10000-P25 +9e20110ea128e4201c9a09eb48ad16c8 +level 12, file files/g10000-P50 +07287871c8b4ec3b5a925563a97451ce +level 12, file files/g10000-P75 +2a47bb2eb7fb84a157f4525da9f78a77 +level 12, file files/g10000-P90 +d9c87f3f0faf212ec2d60cb611dac8a9 +level 12, file files/g100000 +d5d45068ded1319342ac3b7867d8c8fd +level 12, file files/g1000000 +d28d3aed914ba7368dd004a9431c0173 +level 12, file files/g20000 +650cf27ffca49ed98f0e5dbb8997d7eb +level 12, file files/g200000 +077d0f0ef9e9af86b1a298624fc70062 +level 12, file files/g30000 +09fe5a276e3fec09490c85962263fb26 +level 12, file files/g50000 +a9fa2677e4faab0eaa2334f278b3ec7d +level 12, file files/g500000 +86815b1a35a46312a081f1af4946a62e +level 13, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 13, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 13, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 13, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 13, file files/g1000 +773b6b59d472db0932b5ad1ad75eac64 +level 13, file files/g10000 +dfd1e66b36c80b191c338d0b14813920 +level 13, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 13, file files/g10000-P10 +40b5f47e143e235198f6408a099208e8 +level 13, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 13, file files/g10000-P25 +deaa99c2458ca8ea661b358ef837ef58 +level 13, file files/g10000-P50 +dd575cdc1ac009a7f2407013063d02e3 +level 13, file files/g10000-P75 +0d411eb9beee65c6f5dd7764b639097b +level 13, file files/g10000-P90 +61db327f8fdd9a735e68259f05f71f0d +level 13, file files/g100000 +dece3af6a1b7ef4ab80cad69119a3b61 +level 13, file files/g1000000 +916989f734410afce6b3ae72a3352e68 +level 13, file files/g20000 +7ce4e5c10392cbae28ed79b0707f627f +level 13, file files/g200000 +ab3d3f2a0fb5d4e54f8e799213d7e995 +level 13, file files/g30000 +61f3ce2b87a584169e92791fa54c7361 +level 13, file files/g50000 +aba34c68e1d812fab8ce9863169e050b +level 13, file files/g500000 +9f16a159f5fa88b875e5c1e0574a999c +level 14, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 14, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 14, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 14, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 14, file files/g1000 +773b6b59d472db0932b5ad1ad75eac64 +level 14, file files/g10000 +dfd1e66b36c80b191c338d0b14813920 +level 14, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 14, file files/g10000-P10 +40b5f47e143e235198f6408a099208e8 +level 14, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 14, file files/g10000-P25 +deaa99c2458ca8ea661b358ef837ef58 +level 14, file files/g10000-P50 +246b1782db44f4226d32c8718e39ac8c +level 14, file files/g10000-P75 +023a4c9c041fbcd4f584d5e65f9b4444 +level 14, file files/g10000-P90 +d57d3ce213e81d7ce80930115afc9f71 +level 14, file files/g100000 +29c1d79c3dc1dc51ec4ee3fd19fdbd10 +level 14, file files/g1000000 +7721785c341760a66ac9e2fb39cfeb33 +level 14, file files/g20000 +1055a0a808598d1eedf0442fceff44e0 +level 14, file files/g200000 +87df6235943fd09ba3f6a1f24cbc3a3a +level 14, file files/g30000 +74c32e0cd8bcd62bd4e1cf599c193abf +level 14, file files/g50000 +10d3bbb5e9822fa5c31fc2e79aeae7e9 +level 14, file files/g500000 +f8865d65f1790f723184007b2f940127 +level 15, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 15, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 15, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 15, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 15, file files/g1000 +773b6b59d472db0932b5ad1ad75eac64 +level 15, file files/g10000 +dfd1e66b36c80b191c338d0b14813920 +level 15, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 15, file files/g10000-P10 +40b5f47e143e235198f6408a099208e8 +level 15, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 15, file files/g10000-P25 +deaa99c2458ca8ea661b358ef837ef58 +level 15, file files/g10000-P50 +91cc04148eef18ae4222038ad05f0586 +level 15, file files/g10000-P75 +aa5e9e619fe89644098c9ad17a8b9ad4 +level 15, file files/g10000-P90 +28d6d71a33f507d1e7acd56d586e3981 +level 15, file files/g100000 +29c1d79c3dc1dc51ec4ee3fd19fdbd10 +level 15, file files/g1000000 +de1091b6021db006820019edfcb1384c +level 15, file files/g20000 +1055a0a808598d1eedf0442fceff44e0 +level 15, file files/g200000 +0096718cf88b77da67fc2211bf85e3ca +level 15, file files/g30000 +74c32e0cd8bcd62bd4e1cf599c193abf +level 15, file files/g50000 +10d3bbb5e9822fa5c31fc2e79aeae7e9 +level 15, file files/g500000 +53aa49e42ffac4621397b88d4749c9c0 +level 16, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 16, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 16, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 16, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 16, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 16, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 16, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 16, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 16, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 16, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 16, file files/g10000-P50 +9af82247b7fe18900592ae4fd5f1890a +level 16, file files/g10000-P75 +d44f2305f023fbff3d1a872ab740958a +level 16, file files/g10000-P90 +517f98319c717526b5e211079f073fbc +level 16, file files/g100000 +95ec61667f371a3621b34a042f1f4a0a +level 16, file files/g1000000 +b71641629b58754f1961ac394f177d7c +level 16, file files/g20000 +7bd4e03d703ead21e15fddd4423ef79e +level 16, file files/g200000 +fd1c701e9872f304a71f0e7f7aa9f918 +level 16, file files/g30000 +bc2211b250b5f4ed0a7bd97d447132e0 +level 16, file files/g50000 +a6d98ebd2ed96688482c7d1181dded42 +level 16, file files/g500000 +44e339bb9e57842b77476f6d75ff3fbd +level 17, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 17, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 17, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 17, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 17, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 17, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 17, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 17, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 17, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 17, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 17, file files/g10000-P50 +607968cd37d41631312307f6c8a37ab4 +level 17, file files/g10000-P75 +818c2b0124e0dad26f9d95d753b11140 +level 17, file files/g10000-P90 +2d01bb79185ec88e5d7e684d3983eff8 +level 17, file files/g100000 +95ec61667f371a3621b34a042f1f4a0a +level 17, file files/g1000000 +cbd03f012664a02441271c50ba1330bf +level 17, file files/g20000 +7bd4e03d703ead21e15fddd4423ef79e +level 17, file files/g200000 +fd1c701e9872f304a71f0e7f7aa9f918 +level 17, file files/g30000 +bc2211b250b5f4ed0a7bd97d447132e0 +level 17, file files/g50000 +a6d98ebd2ed96688482c7d1181dded42 +level 17, file files/g500000 +01223076923dc7e3e06eeb3d71c467d2 +level 18, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 18, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 18, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 18, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 18, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 18, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 18, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 18, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 18, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 18, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 18, file files/g10000-P50 +c61ad9309da86f7229498e46daacd6d9 +level 18, file files/g10000-P75 +8bf1c42a6a1f46ff8549e87f7b6daa54 +level 18, file files/g10000-P90 +29077b7a282975006c20701bca0d439d +level 18, file files/g100000 +95ec61667f371a3621b34a042f1f4a0a +level 18, file files/g1000000 +1e598049810de86924756bcda8941085 +level 18, file files/g20000 +7bd4e03d703ead21e15fddd4423ef79e +level 18, file files/g200000 +ab03b5ab84b6ebe79fa325118a895c6b +level 18, file files/g30000 +bc2211b250b5f4ed0a7bd97d447132e0 +level 18, file files/g50000 +a6d98ebd2ed96688482c7d1181dded42 +level 18, file files/g500000 +1b5374095c0bdc676655fe4db94286d1 +level 19, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 19, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 19, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 19, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 19, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 19, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 19, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 19, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 19, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 19, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 19, file files/g10000-P50 +c61ad9309da86f7229498e46daacd6d9 +level 19, file files/g10000-P75 +d3171f297dfd08e444d481b30b1bbefa +level 19, file files/g10000-P90 +87c4a59ec6e15f6da86b26969044a8a4 +level 19, file files/g100000 +7ae11dc1919d94e80979d41d12a0b578 +level 19, file files/g1000000 +d4b9ee8879d7f30bed3ec9e70520ca67 +level 19, file files/g20000 +70028792166e24282f5497592b632192 +level 19, file files/g200000 +ab03b5ab84b6ebe79fa325118a895c6b +level 19, file files/g30000 +d698feea5119e141a08656439c4c1508 +level 19, file files/g50000 +b81384753f0db76004ac97681f6ef757 +level 19, file files/g500000 +0a25ba39483255a2c16899ab80a3ed8f +level 1, long=18, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 19, long=18, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 1, long=18, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 19, long=18, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 1, long=18, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 19, long=18, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 1, long=18, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 19, long=18, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 1, long=18, file files/g1000 +6bf2f4b179864fd8db4676037465feed +level 19, long=18, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 1, long=18, file files/g10000 +2ae44c4053b2b47724c8f612dfb60d24 +level 19, long=18, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 1, long=18, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 19, long=18, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 1, long=18, file files/g10000-P10 +6a8f6e75ab538eb08a422febc8b68006 +level 19, long=18, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 1, long=18, file files/g10000-P100 +5db6fbe04a2de772ad4e49f5357d0543 +level 19, long=18, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 1, long=18, file files/g10000-P25 +6fd603b31365845346faab9cd64fd647 +level 19, long=18, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 1, long=18, file files/g10000-P50 +d1de679e9a8c962ed1cc668a96bf930a +level 19, long=18, file files/g10000-P50 +c61ad9309da86f7229498e46daacd6d9 +level 1, long=18, file files/g10000-P75 +dcf9822423e2ad42a569985707cd5ab4 +level 19, long=18, file files/g10000-P75 +f0ea19930e3866ff7a1932931346e0ac +level 1, long=18, file files/g10000-P90 +87d249fd8c1ad0064d067a1e5ad97647 +level 19, long=18, file files/g10000-P90 +582e2c4c5a06e452d8dae22e7210c070 +level 1, long=18, file files/g100000 +daa38a869130494c077290cf54f2d895 +level 19, long=18, file files/g100000 +7ae11dc1919d94e80979d41d12a0b578 +level 1, long=18, file files/g1000000 +81b9ffd138f3b25254a7078b06950e5f +level 19, long=18, file files/g1000000 +db54f06bf3abdbfd57892ab3aad18233 +level 1, long=18, file files/g20000 +1da5b56511e8693867c0cdd962c521aa +level 19, long=18, file files/g20000 +70028792166e24282f5497592b632192 +level 1, long=18, file files/g200000 +17eb9ff8d912da9c445def85cb748e54 +level 19, long=18, file files/g200000 +ab03b5ab84b6ebe79fa325118a895c6b +level 1, long=18, file files/g30000 +788bc5abca5e33d79bb79a4eca98b9cd +level 19, long=18, file files/g30000 +d698feea5119e141a08656439c4c1508 +level 1, long=18, file files/g50000 +0bf9fafd84a2d56a788a9159f1f23f26 +level 19, long=18, file files/g50000 +b81384753f0db76004ac97681f6ef757 +level 1, long=18, file files/g500000 +f035223dc02f581daf5dd79773c4dc2b +level 19, long=18, file files/g500000 +97093f718faf7b9094e27ea822fd1a29 +level -1, file files/g0 +5d80401e01d33084c65e94f93351e94c +level -1, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level -1, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level -1, file files/g100 +eb805e7fdb95bc42231b20d0e12e2a53 +level -1, file files/g1000 +ac7c900e31b9e4fe37b7846a898c7d48 +level -1, file files/g10000 +55e1e6ed7fcf5581a17f72f3a32e0834 +level -1, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level -1, file files/g10000-P10 +0bf549bdfc20b644c37901918de0d0eb +level -1, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level -1, file files/g10000-P25 +b65475ee206e480b3adc9fcc7b79c54b +level -1, file files/g10000-P50 +ae4bf85c8343052ecb1d666bd9766fbc +level -1, file files/g10000-P75 +b0674333f519e71708f226f935ae63d5 +level -1, file files/g10000-P90 +2daa80aa34a8259fed7e04ae41397d6c +level -1, file files/g100000 +586e12a3aa574f35aedf0afadee3040c +level -1, file files/g1000000 +1cc8eb9ee1e4c20373fe3c1b0aa1a982 +level -1, file files/g20000 +b220e6387b1f5036c203f8be5f1a571c +level -1, file files/g200000 +fc42db710c19a4f4a27f004fb4678d9c +level -1, file files/g30000 +5350a7346d815f4ad42216b91ba8749a +level -1, file files/g50000 +4f00a5a94e8f98c6972053057f6ac971 +level -1, file files/g500000 +4abb2e46c936c273955778c00f3eb492 diff --git a/tests/cli-tests/determinism/multithread.sh b/tests/cli-tests/determinism/multithread.sh new file mode 100755 index 000000000..a3481dbaf --- /dev/null +++ b/tests/cli-tests/determinism/multithread.sh @@ -0,0 +1,45 @@ +#!/bin/sh + +. "$COMMON/platform.sh" + +set -e + +# To update checksums on version change run this from the tests/ directory +# make update-cli-tests + +if [ -n "$NON_DETERMINISTIC" ] || [ -z "$hasMT" ]; then + # Skip tests if we have a non-deterministic build + cat "$CLI_TESTS/determinism/multithread.sh.stdout.exact" + exit 0 +fi + +for level in 1 3 7 19; do + for file in $(ls files/); do + file="files/$file" + echo "level $level, file $file" + zstd -T2 -q -$level $file -c | md5hash + done +done + +for file in $(ls files/); do + file="files/$file" + echo "level 1, long=18, file $file" + zstd --long=18 -T2 -q -1 $file -c | md5hash + echo "level 19, long=18, file $file" + zstd --long=18 -T2 -q -19 $file -c | md5hash +done + +for file in $(ls files/); do + file="files/$file" + echo "Vary number of threads on $file" + zstd -qf -1 $file -o $file.zst.good + + zstd -qf -T1 -1 $file + $DIFF $file.zst $file.zst.good + + zstd -qf -T2 -1 $file + $DIFF $file.zst $file.zst.good + + zstd -qf -T4 -1 $file + $DIFF $file.zst $file.zst.good +done diff --git a/tests/cli-tests/determinism/multithread.sh.stderr.exact b/tests/cli-tests/determinism/multithread.sh.stderr.exact new file mode 100644 index 000000000..e69de29bb diff --git a/tests/cli-tests/determinism/multithread.sh.stdout.exact b/tests/cli-tests/determinism/multithread.sh.stdout.exact new file mode 100644 index 000000000..8de7664df --- /dev/null +++ b/tests/cli-tests/determinism/multithread.sh.stdout.exact @@ -0,0 +1,260 @@ +level 1, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 1, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 1, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 1, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 1, file files/g1000 +6bf2f4b179864fd8db4676037465feed +level 1, file files/g10000 +2ae44c4053b2b47724c8f612dfb60d24 +level 1, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 1, file files/g10000-P10 +2d0eeab6a966098583a1dfeafb5090c1 +level 1, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 1, file files/g10000-P25 +c64b5f512c44b6a647da81753791b9a7 +level 1, file files/g10000-P50 +3982325490d90c8307e734c1b25790df +level 1, file files/g10000-P75 +b7504f80fee16b5ba6a0f46571eb563a +level 1, file files/g10000-P90 +350892bec7f7ad6a7d6af01c5d8b07c7 +level 1, file files/g100000 +daa38a869130494c077290cf54f2d895 +level 1, file files/g1000000 +a1d548531221d408b95dc5d9c600b3f0 +level 1, file files/g20000 +1da5b56511e8693867c0cdd962c521aa +level 1, file files/g200000 +41fb3b3d46d4221f2f0b072c65dd6e0a +level 1, file files/g30000 +788bc5abca5e33d79bb79a4eca98b9cd +level 1, file files/g50000 +0bf9fafd84a2d56a788a9159f1f23f26 +level 1, file files/g500000 +73401d6df0657e091de20468f32579a9 +level 3, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 3, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 3, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 3, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 3, file files/g1000 +3ec47dcb2d606b9fdef3f19b1304f8fe +level 3, file files/g10000 +69a9d518b84fe2a66b57dfb4ab8905ae +level 3, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 3, file files/g10000-P10 +ac9866ac355c4ed8939deb9fbeec1aef +level 3, file files/g10000-P100 +93436482b4da30ce2300d356448c8990 +level 3, file files/g10000-P25 +5e1fe7a3831f6632bc8c9873ab8b633d +level 3, file files/g10000-P50 +76295f181396a98565eb9cc69b96dc75 +level 3, file files/g10000-P75 +1f751dc70508e81fef197311e8583e99 +level 3, file files/g10000-P90 +47c7b061c299dc253c6aaaf489e936cb +level 3, file files/g100000 +4b30b2be3394f03f1cf1f37a08dcec12 +level 3, file files/g1000000 +4301dea72cc4dd6162e46caa59788a09 +level 3, file files/g20000 +30456361833d27c0962c2faaa254e615 +level 3, file files/g200000 +0f01c07c57d60298dd54c6b6b197c3d3 +level 3, file files/g30000 +0b3c506a1b1b6ccbb54a852c370f5cdc +level 3, file files/g50000 +81368c0b96bf1a2f318940b836b46074 +level 3, file files/g500000 +0c1ef9c6d3d75bfa0dd5d893f65da47c +level 7, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 7, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 7, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 7, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 7, file files/g1000 +19187f900e7540efdcab3735f489f718 +level 7, file files/g10000 +495f1e5d30de3b34c5a76301875fa231 +level 7, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 7, file files/g10000-P10 +8a91fa2460ec9bd0387baa31beb81060 +level 7, file files/g10000-P100 +15fede9faa3d7c484dead66071fb8c5d +level 7, file files/g10000-P25 +7dc0563f2e66a2e57c0f119e4d5e636e +level 7, file files/g10000-P50 +e93a6eb179f7b26daa896328b2583b04 +level 7, file files/g10000-P75 +cb1e5facfc34fca7323000c6188ad657 +level 7, file files/g10000-P90 +e9984c6557f5a392f16e5c139dbe4994 +level 7, file files/g100000 +6e493dbe2985fec69860ef34728ac01a +level 7, file files/g1000000 +455023a055f3a4de76c7295408ce3c8f +level 7, file files/g20000 +2359efcd587e36ac9b74a8344bbf0e53 +level 7, file files/g200000 +ca80dbc88183a5aabb4aae955c449dff +level 7, file files/g30000 +7e1be7e841c9fddd776dbe94b50db0ab +level 7, file files/g50000 +09b80b58d70622de6f2354a06c15cb2a +level 7, file files/g500000 +c90609f0558f0979eccb572ce0af4aa3 +level 19, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 19, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 19, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 19, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 19, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 19, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 19, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 19, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 19, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 19, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 19, file files/g10000-P50 +c61ad9309da86f7229498e46daacd6d9 +level 19, file files/g10000-P75 +d3171f297dfd08e444d481b30b1bbefa +level 19, file files/g10000-P90 +87c4a59ec6e15f6da86b26969044a8a4 +level 19, file files/g100000 +7ae11dc1919d94e80979d41d12a0b578 +level 19, file files/g1000000 +d4b9ee8879d7f30bed3ec9e70520ca67 +level 19, file files/g20000 +70028792166e24282f5497592b632192 +level 19, file files/g200000 +ab03b5ab84b6ebe79fa325118a895c6b +level 19, file files/g30000 +d698feea5119e141a08656439c4c1508 +level 19, file files/g50000 +b81384753f0db76004ac97681f6ef757 +level 19, file files/g500000 +0a25ba39483255a2c16899ab80a3ed8f +level 1, long=18, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 19, long=18, file files/g0 +5d80401e01d33084c65e94f93351e94c +level 1, long=18, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 19, long=18, file files/g1 +8436b07a7eb916ac9c48af847b7e612f +level 1, long=18, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 19, long=18, file files/g10 +6cf177a3e6494ac3c76c857df6a9b31d +level 1, long=18, file files/g100 +c94d1ef6bbec8b4899486b06207ee829 +level 19, long=18, file files/g100 +e6e88e42b891fbc82c87a60928d88e97 +level 1, long=18, file files/g1000 +6bf2f4b179864fd8db4676037465feed +level 19, long=18, file files/g1000 +f3eeeae11e293292fe1810d8745d0ae1 +level 1, long=18, file files/g10000 +2ae44c4053b2b47724c8f612dfb60d24 +level 19, long=18, file files/g10000 +23c5d58cca20ab65ff8a5d780f09e075 +level 1, long=18, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 19, long=18, file files/g10000-P0 +6c2641d3b83775c50b766793b39967c4 +level 1, long=18, file files/g10000-P10 +6a8f6e75ab538eb08a422febc8b68006 +level 19, long=18, file files/g10000-P10 +cced9c0f5709262da932fc8540bb72f4 +level 1, long=18, file files/g10000-P100 +5db6fbe04a2de772ad4e49f5357d0543 +level 19, long=18, file files/g10000-P100 +049015191cf579b24653c8730fcc10f5 +level 1, long=18, file files/g10000-P25 +6fd603b31365845346faab9cd64fd647 +level 19, long=18, file files/g10000-P25 +6676c9b599408491f7abc00947782054 +level 1, long=18, file files/g10000-P50 +d1de679e9a8c962ed1cc668a96bf930a +level 19, long=18, file files/g10000-P50 +c61ad9309da86f7229498e46daacd6d9 +level 1, long=18, file files/g10000-P75 +dcf9822423e2ad42a569985707cd5ab4 +level 19, long=18, file files/g10000-P75 +f0ea19930e3866ff7a1932931346e0ac +level 1, long=18, file files/g10000-P90 +87d249fd8c1ad0064d067a1e5ad97647 +level 19, long=18, file files/g10000-P90 +582e2c4c5a06e452d8dae22e7210c070 +level 1, long=18, file files/g100000 +daa38a869130494c077290cf54f2d895 +level 19, long=18, file files/g100000 +7ae11dc1919d94e80979d41d12a0b578 +level 1, long=18, file files/g1000000 +2c410773bb02367d20d20569393faf1e +level 19, long=18, file files/g1000000 +e3f5ef0204aedbac03e80d4300b3afc7 +level 1, long=18, file files/g20000 +1da5b56511e8693867c0cdd962c521aa +level 19, long=18, file files/g20000 +70028792166e24282f5497592b632192 +level 1, long=18, file files/g200000 +17eb9ff8d912da9c445def85cb748e54 +level 19, long=18, file files/g200000 +ab03b5ab84b6ebe79fa325118a895c6b +level 1, long=18, file files/g30000 +788bc5abca5e33d79bb79a4eca98b9cd +level 19, long=18, file files/g30000 +d698feea5119e141a08656439c4c1508 +level 1, long=18, file files/g50000 +0bf9fafd84a2d56a788a9159f1f23f26 +level 19, long=18, file files/g50000 +b81384753f0db76004ac97681f6ef757 +level 1, long=18, file files/g500000 +f035223dc02f581daf5dd79773c4dc2b +level 19, long=18, file files/g500000 +97093f718faf7b9094e27ea822fd1a29 +Vary number of threads on files/g0 +Vary number of threads on files/g1 +Vary number of threads on files/g10 +Vary number of threads on files/g100 +Vary number of threads on files/g1000 +Vary number of threads on files/g10000 +Vary number of threads on files/g10000-P0 +Vary number of threads on files/g10000-P10 +Vary number of threads on files/g10000-P100 +Vary number of threads on files/g10000-P25 +Vary number of threads on files/g10000-P50 +Vary number of threads on files/g10000-P75 +Vary number of threads on files/g10000-P90 +Vary number of threads on files/g100000 +Vary number of threads on files/g1000000 +Vary number of threads on files/g20000 +Vary number of threads on files/g200000 +Vary number of threads on files/g30000 +Vary number of threads on files/g50000 +Vary number of threads on files/g500000 diff --git a/tests/cli-tests/determinism/reuse.sh b/tests/cli-tests/determinism/reuse.sh new file mode 100755 index 000000000..83e4088dd --- /dev/null +++ b/tests/cli-tests/determinism/reuse.sh @@ -0,0 +1,44 @@ +#!/bin/sh + +. "$COMMON/platform.sh" + +set -e + +# To update checksums on version change run this from the tests/ directory +# make update-cli-tests + +if [ -n "$NON_DETERMINISTIC" ]; then + # Skip tests if we have a non-deterministic build + cat "$CLI_TESTS/determinism/reuse.sh.stdout.exact" + exit 0 +fi + +datagen -g0 > file0 +datagen -g1 > file1 +datagen -g1000 > file1000 +datagen -g100000 > file100000 + +validate() { + $DIFF file0.zst file0.zst.good + $DIFF file1.zst file1.zst.good + $DIFF file1000.zst file1000.zst.good + $DIFF file100000.zst file100000.zst.good +} + +# Check that context reuse doesn't impact determinism +for level in $(seq 1 19); do + echo $level + zstd -qf --single-thread -$level file0 -o file0.zst.good + zstd -qf --single-thread -$level file1 -o file1.zst.good + zstd -qf --single-thread -$level file1000 -o file1000.zst.good + zstd -qf --single-thread -$level file100000 -o file100000.zst.good + + zstd -qf --single-thread -$level file0 file1 file1000 file100000 + validate + zstd -qf --single-thread -$level file1 file0 file1000 file100000 + validate + zstd -qf --single-thread -$level file1000 file1 file0 file100000 + validate + zstd -qf --single-thread -$level file100000 file1000 file1 file0 + validate +done diff --git a/tests/cli-tests/determinism/reuse.sh.stderr.exact b/tests/cli-tests/determinism/reuse.sh.stderr.exact new file mode 100644 index 000000000..e69de29bb diff --git a/tests/cli-tests/determinism/reuse.sh.stdout.exact b/tests/cli-tests/determinism/reuse.sh.stdout.exact new file mode 100644 index 000000000..ac30dc23a --- /dev/null +++ b/tests/cli-tests/determinism/reuse.sh.stdout.exact @@ -0,0 +1,19 @@ +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 diff --git a/tests/cli-tests/determinism/setup b/tests/cli-tests/determinism/setup new file mode 100755 index 000000000..c16029ebf --- /dev/null +++ b/tests/cli-tests/determinism/setup @@ -0,0 +1,5 @@ +#!/bin/sh + +set -e + +cp -r ../files . diff --git a/tests/cli-tests/determinism/setup_once b/tests/cli-tests/determinism/setup_once new file mode 100755 index 000000000..1d7b34c1f --- /dev/null +++ b/tests/cli-tests/determinism/setup_once @@ -0,0 +1,30 @@ +#!/bin/sh + +set -e + +. "$COMMON/platform.sh" + + +mkdir files/ + +datagen -g0 > files/g0 +datagen -g1 > files/g1 +datagen -g10 > files/g10 +datagen -g100 > files/g100 +datagen -g1000 > files/g1000 +datagen -g10000 > files/g10000 +datagen -g20000 > files/g20000 +datagen -g30000 > files/g30000 +datagen -g50000 > files/g50000 +datagen -g100000 > files/g100000 +datagen -g200000 > files/g200000 +datagen -g500000 > files/g500000 +datagen -g1000000 > files/g1000000 + +datagen -g10000 -P0 > files/g10000-P0 +datagen -g10000 -P10 > files/g10000-P10 +datagen -g10000 -P25 > files/g10000-P25 +datagen -g10000 -P50 > files/g10000-P50 +datagen -g10000 -P75 > files/g10000-P75 +datagen -g10000 -P90 > files/g10000-P90 +datagen -g10000 -P100 > files/g10000-P100 diff --git a/tests/cli-tests/run.py b/tests/cli-tests/run.py index 46564d2ff..011c8478e 100755 --- a/tests/cli-tests/run.py +++ b/tests/cli-tests/run.py @@ -705,6 +705,7 @@ if __name__ == "__main__": env["DATAGEN_BIN"] = os.path.abspath(args.datagen) env["ZSTDGREP_BIN"] = os.path.abspath(args.zstdgrep) env["ZSTDLESS_BIN"] = os.path.abspath(args.zstdless) + env["CLI_TESTS"] = os.path.abspath(args.test_dir) env["COMMON"] = os.path.abspath(os.path.join(args.test_dir, "common")) env["PATH"] = bin_dir + ":" + os.getenv("PATH", "") env["LC_ALL"] = "C" From d5986f235f6fbe4f72aabb943cf6d4b9fe51772f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 00:12:34 -0700 Subject: [PATCH 742/937] fix #4332: setting ZSTD_NBTHREADS=0 via environment variables --- programs/zstdcli.c | 55 ++++++++----------- tests/cli-tests/compression/multi-threaded.sh | 4 -- .../multi-threaded.sh.stderr.exact | 5 -- 3 files changed, 24 insertions(+), 40 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 66e9d064b..30a406a7d 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -44,7 +44,7 @@ #endif #ifndef ZSTDCLI_NBTHREADS_DEFAULT -#define ZSTDCLI_NBTHREADS_DEFAULT MAX(1, MIN(4, UTIL_countLogicalCores() / 4)) +#define ZSTDCLI_NBTHREADS_DEFAULT (unsigned)(MAX(1, MIN(4, UTIL_countLogicalCores() / 4))) #endif @@ -94,6 +94,7 @@ static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT; #define DEFAULT_ACCEL 1 +#define NBWORKERS_AUTOCPU 0 typedef enum { cover, fastCover, legacy } dictType; @@ -745,7 +746,7 @@ static void printActualCParams(const char* filename, const char* dictFileName, i /* Environment variables for parameter setting */ #define ENV_CLEVEL "ZSTD_CLEVEL" -#define ENV_NBTHREADS "ZSTD_NBTHREADS" /* takes lower precedence than directly specifying -T# in the CLI */ +#define ENV_NBWORKERS "ZSTD_NBTHREADS" /* takes lower precedence than directly specifying -T# in the CLI */ /* pick up environment variable */ static int init_cLevel(void) { @@ -775,26 +776,28 @@ static int init_cLevel(void) { return ZSTDCLI_CLEVEL_DEFAULT; } +static unsigned init_nbWorkers(void) { #ifdef ZSTD_MULTITHREAD -static int default_nbThreads(void) { - const char* const env = getenv(ENV_NBTHREADS); + const char* const env = getenv(ENV_NBWORKERS); if (env != NULL) { const char* ptr = env; if ((*ptr>='0') && (*ptr<='9')) { unsigned nbThreads; if (readU32FromCharChecked(&ptr, &nbThreads)) { - DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env); + DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBWORKERS, env); return ZSTDCLI_NBTHREADS_DEFAULT; } else if (*ptr == 0) { - return (int)nbThreads; + return nbThreads; } } - DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env); + DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBWORKERS, env); } return ZSTDCLI_NBTHREADS_DEFAULT; -} +#else + return 1; #endif +} #define NEXT_FIELD(ptr) { \ if (*argument == '=') { \ @@ -874,13 +877,15 @@ int main(int argCount, const char* argv[]) singleThread = 0, defaultLogicalCores = 0, showDefaultCParams = 0, - ultra=0, - contentSize=1, - removeSrcFile=0; - ZSTD_ParamSwitch_e mmapDict=ZSTD_ps_auto; + contentSize = 1, + removeSrcFile = 0, + cLevel = init_cLevel(), + ultra = 0, + cLevelLast = MINCLEVEL - 1; /* for benchmark range */ + unsigned nbWorkers = init_nbWorkers(); + ZSTD_ParamSwitch_e mmapDict = ZSTD_ps_auto; ZSTD_ParamSwitch_e useRowMatchFinder = ZSTD_ps_auto; FIO_compressionType_t cType = FIO_zstdCompression; - int nbWorkers = -1; /* -1 means unset */ double compressibility = -1.0; /* lorem ipsum generator */ unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */ size_t chunkSize = 0; @@ -890,8 +895,6 @@ int main(int argCount, const char* argv[]) FIO_progressSetting_e progress = FIO_ps_auto; zstd_operation_mode operation = zom_compress; ZSTD_compressionParameters compressionParams; - int cLevel = init_cLevel(); - int cLevelLast = MINCLEVEL - 1; /* lower than minimum */ unsigned recursive = 0; unsigned memLimit = 0; FileNamesTable* filenames = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */ @@ -930,7 +933,7 @@ int main(int argCount, const char* argv[]) programName = lastNameFromPath(programName); /* preset behaviors */ - if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0; + if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=NBWORKERS_AUTOCPU, singleThread=0; if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress; if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* supports multiple formats */ if (exeNameMatch(programName, ZSTD_ZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like zcat, also supports multiple formats */ @@ -938,7 +941,7 @@ int main(int argCount, const char* argv[]) suffix = GZ_EXTENSION; cType = FIO_gzipCompression; removeSrcFile=1; dictCLevel = cLevel = 6; /* gzip default is -6 */ } - if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; removeSrcFile=1; } /* behave like gunzip, also supports multiple formats */ + if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; removeSrcFile=1; } /* behave like gunzip, also supports multiple formats */ if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like gzcat, also supports multiple formats */ if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like lzma */ if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like unlzma, also supports multiple formats */ @@ -1081,7 +1084,7 @@ int main(int argCount, const char* argv[]) continue; } #endif - if (longCommandWArg(&argument, "--threads")) { NEXT_INT32(nbWorkers); continue; } + if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; } if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; } @@ -1287,7 +1290,7 @@ int main(int argCount, const char* argv[]) /* nb of threads (hidden option) */ case 'T': argument++; - nbWorkers = (int)readU32FromChar(&argument); + nbWorkers = readU32FromChar(&argument); break; /* Dictionary Selection level */ @@ -1332,10 +1335,7 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(3, WELCOME_MESSAGE); #ifdef ZSTD_MULTITHREAD - if ((operation==zom_decompress) && (nbWorkers > 1)) { - DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n"); - } - if ((nbWorkers==0) && (!singleThread)) { + if ((nbWorkers==NBWORKERS_AUTOCPU) && (!singleThread)) { /* automatically set # workers based on # of reported cpus */ if (defaultLogicalCores) { nbWorkers = UTIL_countLogicalCores(); @@ -1345,14 +1345,7 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers); } } - /* Resolve to default if nbWorkers is still unset */ - if (nbWorkers == -1) { - if (operation == zom_decompress) { - nbWorkers = 1; - } else { - nbWorkers = default_nbThreads(); - } - } + assert(nbWorkers >= 0); if (operation != zom_bench) DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); #else diff --git a/tests/cli-tests/compression/multi-threaded.sh b/tests/cli-tests/compression/multi-threaded.sh index ac094129e..25d862b45 100755 --- a/tests/cli-tests/compression/multi-threaded.sh +++ b/tests/cli-tests/compression/multi-threaded.sh @@ -10,7 +10,3 @@ zstd -T0 -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=logical -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=physical -f file -q ; zstd -t file.zst zstd -T0 --jobsize=1M -f file -q ; zstd -t file.zst - -# multi-thread decompression warning test -zstd -T0 -f file -q ; zstd -t file.zst; zstd -T0 -d file.zst -o file3 -zstd -T0 -f file -q ; zstd -t file.zst; zstd -T2 -d file.zst -o file4 diff --git a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact index 0dcf52ac4..cb3a24aad 100644 --- a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact +++ b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact @@ -5,8 +5,3 @@ file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes -file.zst : 65537 bytes -file.zst : 65537 bytes -file.zst : 65537 bytes -Warning : decompression does not support multi-threading -file.zst : 65537 bytes From 56e2ebf5c38a22e0264b709a802b1cfa2ce21167 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 09:54:06 -0700 Subject: [PATCH 743/937] removed useless assert() --- programs/zstdcli.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 30a406a7d..637567b95 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1338,14 +1338,13 @@ int main(int argCount, const char* argv[]) if ((nbWorkers==NBWORKERS_AUTOCPU) && (!singleThread)) { /* automatically set # workers based on # of reported cpus */ if (defaultLogicalCores) { - nbWorkers = UTIL_countLogicalCores(); + nbWorkers = (unsigned)UTIL_countLogicalCores(); DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers); } else { - nbWorkers = UTIL_countPhysicalCores(); + nbWorkers = (unsigned)UTIL_countPhysicalCores(); DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers); } } - assert(nbWorkers >= 0); if (operation != zom_bench) DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); #else From c18374bb16ecea2a34d003be769bf14b7e97b931 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 13:40:47 -0700 Subject: [PATCH 744/937] add test checks that ZSTD_NBTHREADS triggers the expected verbose message Also: checked that the new test script fails on current `dev` branch, and is fixed by this branch --- tests/playTests.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/playTests.sh b/tests/playTests.sh index 65aa5c0b1..366f9c741 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1570,7 +1570,11 @@ then ZSTD_NBTHREADS=3a7 zstd -f mt_tmp # malformed env var, warn and revert to default setting ZSTD_NBTHREADS=50000000000 zstd -f mt_tmp # numeric value too large, warn and revert to default setting= ZSTD_NBTHREADS=2 zstd -f mt_tmp # correct usage - ZSTD_NBTHREADS=1 zstd -f mt_tmp # correct usage: single thread + ZSTD_NBTHREADS=1 zstd -f mt_tmp # correct usage: single worker + ZSTD_NBTHREADS=4 zstd -f mt_tmp -vv 2>&1 | grep "4 worker threads" # check message + zstd -tq mt_tmp.zst + ZSTD_NBTHREADS=0 zstd -f mt_tmp -vv 2>&1 | grep "core(s) detected" # check core count autodetection is triggered + zstd -tq mt_tmp.zst # temporary envvar changes in the above tests would actually persist in macos /bin/sh unset ZSTD_NBTHREADS rm -f mt_tmp* From 2ff87aefac1be81601a46a98135b15f57ff3ca56 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 13:55:45 -0700 Subject: [PATCH 745/937] fix FreeBSD use an alias instead of a function also: added more traces and updated version nb to v1.5.8 --- lib/zstd.h | 2 +- programs/zstdcli.c | 10 ++++++++-- tests/playTests.sh | 24 ++++++++---------------- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 4ce2f7742..9fe542edc 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -111,7 +111,7 @@ extern "C" { /*------ Version ------*/ #define ZSTD_VERSION_MAJOR 1 #define ZSTD_VERSION_MINOR 5 -#define ZSTD_VERSION_RELEASE 7 +#define ZSTD_VERSION_RELEASE 8 #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) /*! ZSTD_versionNumber() : diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 637567b95..04e9218cf 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -686,6 +686,12 @@ static void printVersion(void) DISPLAYOUT("lz4 version %s\n", FIO_lz4Version()); DISPLAYOUT("lzma version %s\n", FIO_lzmaVersion()); + #ifdef ZSTD_MULTITHREAD + DISPLAYOUT("supports Multithreading \n"); + #else + DISPLAYOUT("single-thread operations only \n"); + #endif + /* posix support */ #ifdef _POSIX_C_SOURCE DISPLAYOUT("_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE); @@ -1336,7 +1342,7 @@ int main(int argCount, const char* argv[]) #ifdef ZSTD_MULTITHREAD if ((nbWorkers==NBWORKERS_AUTOCPU) && (!singleThread)) { - /* automatically set # workers based on # of reported cpus */ + /* automatically set # workers based on # of reported cpu cores */ if (defaultLogicalCores) { nbWorkers = (unsigned)UTIL_countLogicalCores(); DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers); @@ -1345,7 +1351,7 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers); } } - if (operation != zom_bench) + if (operation == zom_compress) DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); #else (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores; diff --git a/tests/playTests.sh b/tests/playTests.sh index 366f9c741..3d6bcdb0b 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1,7 +1,7 @@ #!/bin/sh set -e # exit immediately on error -# set -x # print commands before execution (debug) +set -x # print commands before execution (debug) unset ZSTD_CLEVEL unset ZSTD_NBTHREADS @@ -16,13 +16,7 @@ datagen() { "$DATAGEN_BIN" "$@" } -zstd() { - if [ -z "$EXE_PREFIX" ]; then - "$ZSTD_BIN" "$@" - else - "$EXE_PREFIX" "$ZSTD_BIN" "$@" - fi -} +alias zstd="$EXE_PREFIX $ZSTD_BIN" sudoZstd() { if [ -z "$EXE_PREFIX" ]; then @@ -1563,18 +1557,16 @@ then println "\n===> zstdmt environment variable tests " echo "multifoo" >> mt_tmp ZSTD_NBTHREADS=-3 zstd -f mt_tmp # negative value, warn and revert to default setting - ZSTD_NBTHREADS='' zstd -f mt_tmp # empty env var, warn and revert to default setting - ZSTD_NBTHREADS=- zstd -f mt_tmp # malformed env var, warn and revert to default setting - ZSTD_NBTHREADS=a zstd -f mt_tmp # malformed env var, warn and revert to default setting - ZSTD_NBTHREADS=+a zstd -f mt_tmp # malformed env var, warn and revert to default setting + ZSTD_NBTHREADS='' zstd -f mt_tmp # empty env var, warn and revert to default setting + ZSTD_NBTHREADS=- zstd -f mt_tmp # malformed env var, warn and revert to default setting + ZSTD_NBTHREADS=a zstd -f mt_tmp # malformed env var, warn and revert to default setting + ZSTD_NBTHREADS=+a zstd -f mt_tmp # malformed env var, warn and revert to default setting ZSTD_NBTHREADS=3a7 zstd -f mt_tmp # malformed env var, warn and revert to default setting ZSTD_NBTHREADS=50000000000 zstd -f mt_tmp # numeric value too large, warn and revert to default setting= ZSTD_NBTHREADS=2 zstd -f mt_tmp # correct usage ZSTD_NBTHREADS=1 zstd -f mt_tmp # correct usage: single worker - ZSTD_NBTHREADS=4 zstd -f mt_tmp -vv 2>&1 | grep "4 worker threads" # check message - zstd -tq mt_tmp.zst - ZSTD_NBTHREADS=0 zstd -f mt_tmp -vv 2>&1 | grep "core(s) detected" # check core count autodetection is triggered - zstd -tq mt_tmp.zst + ZSTD_NBTHREADS=4 zstd -f mt_tmp -vv 2>&1 | $GREP "4 worker threads" # check message + ZSTD_NBTHREADS=0 zstd -f mt_tmp -vv 2>&1 | $GREP "core(s) detected" # check core count autodetection is triggered # temporary envvar changes in the above tests would actually persist in macos /bin/sh unset ZSTD_NBTHREADS rm -f mt_tmp* From 3c4096c83e997adb181a7d2b8f5c02649bb98af5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 19:11:44 -0700 Subject: [PATCH 746/937] fixed ShellCheck warning --- tests/playTests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/playTests.sh b/tests/playTests.sh index 3d6bcdb0b..72a47d634 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -16,7 +16,7 @@ datagen() { "$DATAGEN_BIN" "$@" } -alias zstd="$EXE_PREFIX $ZSTD_BIN" +alias zstd='$EXE_PREFIX $ZSTD_BIN' sudoZstd() { if [ -z "$EXE_PREFIX" ]; then From c583c2c39ed24c0b155777f600ee2aa74268e37b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 10 Mar 2025 22:46:33 -0700 Subject: [PATCH 747/937] warn when requesting decompression with multiple threads restore #2918 fix --- programs/zstdcli.c | 18 +++++++----------- tests/cli-tests/compression/multi-threaded.sh | 10 ++++++++++ .../compression/multi-threaded.sh.stderr.exact | 14 ++++++++++++++ 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 04e9218cf..276910d91 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -822,15 +822,6 @@ static unsigned init_nbWorkers(void) { CLEAN_RETURN(1); \ } } } -#define NEXT_INT32(_vari32) { \ - const char* __nb; \ - NEXT_FIELD(__nb); \ - _vari32 = (int)readU32FromChar(&__nb); \ - if(*__nb != 0) { \ - errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ - } \ -} - #define NEXT_UINT32(_varu32) { \ const char* __nb; \ NEXT_FIELD(__nb); \ @@ -887,7 +878,8 @@ int main(int argCount, const char* argv[]) removeSrcFile = 0, cLevel = init_cLevel(), ultra = 0, - cLevelLast = MINCLEVEL - 1; /* for benchmark range */ + cLevelLast = MINCLEVEL - 1, /* for benchmark range */ + setThreads_non1 = 0; unsigned nbWorkers = init_nbWorkers(); ZSTD_ParamSwitch_e mmapDict = ZSTD_ps_auto; ZSTD_ParamSwitch_e useRowMatchFinder = ZSTD_ps_auto; @@ -1090,7 +1082,7 @@ int main(int argCount, const char* argv[]) continue; } #endif - if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; } + if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); setThreads_non1 = (nbWorkers != 1); continue; } if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; } if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; } @@ -1297,6 +1289,7 @@ int main(int argCount, const char* argv[]) case 'T': argument++; nbWorkers = readU32FromChar(&argument); + setThreads_non1 = (nbWorkers != 1); break; /* Dictionary Selection level */ @@ -1341,6 +1334,9 @@ int main(int argCount, const char* argv[]) DISPLAYLEVEL(3, WELCOME_MESSAGE); #ifdef ZSTD_MULTITHREAD + if ((operation==zom_decompress) && (setThreads_non1)) { + DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n"); + } if ((nbWorkers==NBWORKERS_AUTOCPU) && (!singleThread)) { /* automatically set # workers based on # of reported cpu cores */ if (defaultLogicalCores) { diff --git a/tests/cli-tests/compression/multi-threaded.sh b/tests/cli-tests/compression/multi-threaded.sh index 25d862b45..ba3aa0ce5 100755 --- a/tests/cli-tests/compression/multi-threaded.sh +++ b/tests/cli-tests/compression/multi-threaded.sh @@ -10,3 +10,13 @@ zstd -T0 -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=logical -f file -q ; zstd -t file.zst zstd -T0 --auto-threads=physical -f file -q ; zstd -t file.zst zstd -T0 --jobsize=1M -f file -q ; zstd -t file.zst + +# multi-thread decompression warning test +zstd -T0 -f file -q ; zstd -t file.zst; zstd -T0 -d file.zst -o file3 +zstd -T0 -f file -q ; zstd -t file.zst; zstd -T2 -d file.zst -o file4 +# setting multi-thread via environment variable does not trigger decompression warning +zstd -T0 -f file -q ; zstd -t file.zst; ZSTD_NBTHREADS=0 zstd -df file.zst -o file3 +zstd -T0 -f file -q ; zstd -t file.zst; ZSTD_NBTHREADS=2 zstd -df file.zst -o file4 +# setting nbThreads==1 does not trigger decompression warning +zstd -T0 -f file -q ; zstd -t file.zst; zstd -T1 -df file.zst -o file3 +zstd -T0 -f file -q ; zstd -t file.zst; zstd -T2 -T1 -df file.zst -o file4 diff --git a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact index cb3a24aad..346fe0e0c 100644 --- a/tests/cli-tests/compression/multi-threaded.sh.stderr.exact +++ b/tests/cli-tests/compression/multi-threaded.sh.stderr.exact @@ -5,3 +5,17 @@ file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes file.zst : 65537 bytes +file.zst : 65537 bytes +Warning : decompression does not support multi-threading +file.zst : 65537 bytes +file.zst : 65537 bytes +Warning : decompression does not support multi-threading +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes +file.zst : 65537 bytes From 19541b4d1abef6313f317dbe4ff744319f76abaf Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 00:17:45 -0700 Subject: [PATCH 748/937] fix minor unused variable warning --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 276910d91..4fed04e13 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1350,7 +1350,7 @@ int main(int argCount, const char* argv[]) if (operation == zom_compress) DISPLAYLEVEL(4, "Compressing with %u worker threads \n", nbWorkers); #else - (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores; + (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores; (void)setThreads_non1; #endif g_utilDisplayLevel = g_displayLevel; From 68dfd14a8c504bbb27013043e1f3466d5318e019 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Tue, 11 Mar 2025 11:53:20 -0700 Subject: [PATCH 749/937] [linux] Opt out of row based match finder for the kernel The row based match finder is slower without SIMD. We used to detect the presence of SIMD to set the lower bound to 17, but that breaks determinism. Instead, specifically opt into it for the kernel, because it is one of the rare cases that doesn't have SIMD support. --- lib/compress/zstd_compress.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index d928b1d3e..c8f6b2865 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -237,10 +237,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; } From 9a57bdc0bdac7bdf95ca9401c3d95b84ceae6306 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 01:14:39 -0700 Subject: [PATCH 750/937] attempt to reduce length of long cli tests by invoking -T0 --- tests/playTests.sh | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/tests/playTests.sh b/tests/playTests.sh index 72a47d634..15f6e7761 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -43,7 +43,7 @@ roundTripTest() { rm -f tmp1 tmp2 println "roundTripTest: datagen $1 $proba | zstd -v$cLevel | zstd -d$dLevel" datagen $1 $proba | $MD5SUM > tmp1 - datagen $1 $proba | zstd --ultra -v$cLevel | zstd -d$dLevel | $MD5SUM > tmp2 + datagen $1 $proba | zstd -T0 --ultra -v$cLevel | zstd -d$dLevel | $MD5SUM > tmp2 $DIFF -q tmp1 tmp2 } @@ -65,7 +65,7 @@ fileRoundTripTest() { println "fileRoundTripTest: datagen $1 $local_p > tmp && zstd -v$local_c -c tmp | zstd -d$local_d" datagen $1 $local_p > tmp < tmp $MD5SUM > tmp.md5.1 - zstd --ultra -v$local_c -c tmp | zstd -d$local_d | $MD5SUM > tmp.md5.2 + zstd -T0 --ultra -v$local_c -c tmp | zstd -d$local_d | $MD5SUM > tmp.md5.2 $DIFF -q tmp.md5.1 tmp.md5.2 } @@ -1885,36 +1885,36 @@ println "\n===> cover dictionary builder : advanced options " TESTFILE="$PRGDIR"/zstdcli.c datagen > tmpDict println "- Create first dictionary" -zstd --train-cover=k=46,d=8,split=80 "$TESTDIR"/*.c "$PRGDIR"/*.c -o tmpDict +zstd -T0 --train-cover=k=46,d=8,split=80 "$TESTDIR"/*.c "$PRGDIR"/*.c -o tmpDict cp "$TESTFILE" tmp zstd -f tmp -D tmpDict zstd -f tmp -D tmpDict --patch-from=tmpDict && die "error: can't use -D and --patch-from=#at the same time" zstd -d tmp.zst -D tmpDict -fo result $DIFF "$TESTFILE" result -zstd --train-cover=k=56,d=8 && die "Create dictionary without input file (should error)" +zstd -T0 --train-cover=k=56,d=8 && die "Create dictionary without input file (should error)" println "- Create second (different) dictionary" -zstd --train-cover=k=56,d=8 "$TESTDIR"/*.c "$PRGDIR"/*.c "$PRGDIR"/*.h -o tmpDictC +zstd -T0 --train-cover=k=56,d=8 "$TESTDIR"/*.c "$PRGDIR"/*.c "$PRGDIR"/*.h -o tmpDictC zstd -d tmp.zst -D tmpDictC -fo result && die "wrong dictionary not detected!" println "- Create dictionary using shrink-dict flag" -zstd --train-cover=steps=256,shrink "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict -zstd --train-cover=steps=256,shrink=1 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict1 -zstd --train-cover=steps=256,shrink=5 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict2 -zstd --train-cover=shrink=5,steps=256 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict3 +zstd -T0 --train-cover=steps=256,shrink "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict +zstd -T0 --train-cover=steps=256,shrink=1 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict1 +zstd -T0 --train-cover=steps=256,shrink=5 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict2 +zstd -T0 --train-cover=shrink=5,steps=256 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpShrinkDict3 println "- Create dictionary with short dictID" -zstd --train-cover=k=46,d=8,split=80 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpDict1 +zstd -T0 --train-cover=k=46,d=8,split=80 "$TESTDIR"/*.c "$PRGDIR"/*.c --dictID=1 -o tmpDict1 cmp tmpDict tmpDict1 && die "dictionaries should have different ID !" println "- Create dictionary with size limit" -zstd --train-cover=steps=8 "$TESTDIR"/*.c "$PRGDIR"/*.c -o tmpDict2 --maxdict=4K +zstd -T0 --train-cover=steps=8 "$TESTDIR"/*.c "$PRGDIR"/*.c -o tmpDict2 --maxdict=4K println "- Compare size of dictionary from 90% training samples with 80% training samples" -zstd --train-cover=split=90 -r "$TESTDIR"/*.c "$PRGDIR"/*.c -zstd --train-cover=split=80 -r "$TESTDIR"/*.c "$PRGDIR"/*.c +zstd -T0 --train-cover=split=90 -r "$TESTDIR"/*.c "$PRGDIR"/*.c +zstd -T0 --train-cover=split=80 -r "$TESTDIR"/*.c "$PRGDIR"/*.c println "- Create dictionary using all samples for both training and testing" -zstd --train-cover=split=100 -r "$TESTDIR"/*.c "$PRGDIR"/*.c +zstd -T0 --train-cover=split=100 -r "$TESTDIR"/*.c "$PRGDIR"/*.c println "- Test -o before --train-cover" rm -f tmpDict dictionary zstd -o tmpDict --train-cover "$TESTDIR"/*.c "$PRGDIR"/*.c test -f tmpDict -zstd --train-cover "$TESTDIR"/*.c "$PRGDIR"/*.c +zstd -T0 --train-cover "$TESTDIR"/*.c "$PRGDIR"/*.c test -f dictionary rm -f tmp* dictionary From 51b6e79f659f7ba18bf7c4bd2679ff58711aa34d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 01:57:24 -0700 Subject: [PATCH 751/937] fix #4312 and upgraded the test so that it would fail, both at compile time and at run time, without the fix --- lib/dictBuilder/cover.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index cfb756ff2..ed750e31d 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -284,7 +284,7 @@ static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) { */ #if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) static int WIN_CDECL COVER_strict_cmp(void* g_coverCtx, const void* lp, const void* rp) { -#elif defined(_GNU_SOURCE) +#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) static int COVER_strict_cmp(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp(const void *lp, const void *rp) { @@ -300,7 +300,7 @@ static int COVER_strict_cmp(const void *lp, const void *rp) { */ #if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) static int WIN_CDECL COVER_strict_cmp8(void* g_coverCtx, const void* lp, const void* rp) { -#elif defined(_GNU_SOURCE) +#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) static int COVER_strict_cmp8(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp8(const void *lp, const void *rp) { From dcf675886bc138c03c3f157f7464798c4140829f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 11:58:16 -0700 Subject: [PATCH 752/937] re-design qsort() selection in cover centralizes auto detection tests, then distribute the outcome in all the places where it's active. --- .github/workflows/dev-short-tests.yml | 2 +- lib/README.md | 8 +++-- lib/dictBuilder/cover.c | 51 +++++++++++++++++++++------ 3 files changed, 46 insertions(+), 15 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 2a97c32d0..164dc15c7 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -695,7 +695,7 @@ jobs: sudo apt install -y musl-tools - name: Compile the project with musl-gcc run: | - CC=musl-gcc CPPFLAGS=-DZSTD_USE_C90_QSORT make -j V=1 zstd + CC=musl-gcc CFLAGS="-Werror -O3" CPPFLAGS=-DZDICT_QSORT=ZDICT_QSORT_C90 make -j -C tests test-zstd V=1 intel-cet-compatibility: runs-on: ubuntu-latest diff --git a/lib/README.md b/lib/README.md index 9df516c5a..83bf00c19 100644 --- a/lib/README.md +++ b/lib/README.md @@ -193,9 +193,11 @@ The file structure is designed to make this selection manually achievable for an and assembly decoding loops. You may want to use this macro if these loops are slower on your platform. -- The macro `ZSTD_USE_C90_QSORT` forces usage of C90's `qsort()`, - for situations where the code cannot determine that `qsort_r()` is not supported, - such as, for example, older versions of `musl`. +- The macro `ZDICT_QSORT` can enforce selection of a specific sorting variant. + It can be notably set as `ZDICT_QSORT=ZDICT_QSORT_C90`, + for situations where autodetection fails, + for example with older versions of `musl`. + Other selectable suffixes are `_GNU`, `_APPLE` and `_MSVC`. #### Windows : using MinGW+MSYS to create DLL diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index ed750e31d..9ed360033 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -39,6 +39,7 @@ # define ZDICT_STATIC_LINKING_ONLY #endif +#include "../common/debug.h" /* DEBUG_STATIC_ASSERT */ #include "../common/mem.h" /* read */ #include "../common/pool.h" /* POOL_ctx */ #include "../common/threading.h" /* ZSTD_pthread_mutex_t */ @@ -60,6 +61,29 @@ #define COVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB)) #define COVER_DEFAULT_SPLITPOINT 1.0 +/** + * Select the qsort() variant used by cover + */ +#define ZDICT_QSORT_MIN 0 +#define ZDICT_QSORT_C90 ZDICT_QSORT_MIN +#define ZDICT_QSORT_GNU 1 +#define ZDICT_QSORT_APPLE 2 +#define ZDICT_QSORT_MSVC ZDICT_QSORT_MAX +#define ZDICT_QSORT_MAX 3 + +#ifndef ZDICT_QSORT +# if defined(__APPLE__) +# define ZDICT_QSORT ZDICT_QSORT_APPLE /* uses qsort_r() with a different order for parameters */ +# elif defined(_GNU_SOURCE) +# define ZDICT_QSORT ZDICT_QSORT_GNU /* uses qsort_r() */ +# elif defined(_WIN32) && defined(_MSC_VER) +# define ZDICT_QSORT ZDICT_QSORT_MSVC /* uses qsort_s() */ +# else +# define ZDICT_QSORT ZDICT_QSORT_C90 /* uses standard qsort() which is not re-entrant (requires global variable) */ +# endif +#endif + + /*-************************************* * Console display * @@ -234,8 +258,7 @@ typedef struct { int displayLevel; } COVER_ctx_t; -#if defined(ZSTD_USE_C90_QSORT) \ - || (!defined(_GNU_SOURCE) && !defined(__APPLE__) && !defined(_MSC_VER)) +#if ZDICT_QSORT == ZDICT_QSORT_C90 /* Use global context for non-reentrant sort functions */ static COVER_ctx_t *g_coverCtx = NULL; #endif @@ -282,9 +305,9 @@ 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 */ -#if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) +#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) { -#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) +#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) static int COVER_strict_cmp(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp(const void *lp, const void *rp) { @@ -298,9 +321,9 @@ static int COVER_strict_cmp(const void *lp, const void *rp) { /** * Faster version for d <= 8. */ -#if (defined(_WIN32) && defined(_MSC_VER)) || defined(__APPLE__) +#if (ZDICT_QSORT == ZDICT_QSORT_MSVC) || (ZDICT_QSORT == ZDICT_QSORT_APPLE) static int WIN_CDECL COVER_strict_cmp8(void* g_coverCtx, const void* lp, const void* rp) { -#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) +#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) static int COVER_strict_cmp8(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp8(const void *lp, const void *rp) { @@ -317,20 +340,26 @@ static int COVER_strict_cmp8(const void *lp, const void *rp) { * Hopefully when C11 become the norm, we will be able * to clean it up. */ -static void stableSort(COVER_ctx_t *ctx) { -#if defined(__APPLE__) +static void stableSort(COVER_ctx_t *ctx) +{ + DEBUG_STATIC_ASSERT(ZDICT_QSORT_MIN <= ZDICT_QSORT && ZDICT_QSORT <= ZDICT_QSORT_MAX); +#if (ZDICT_QSORT == ZDICT_QSORT_APPLE) qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx, (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); -#elif defined(_GNU_SOURCE) && !defined(ZSTD_USE_C90_QSORT) +#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) qsort_r(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), ctx); -#elif defined(_WIN32) && defined(_MSC_VER) +#elif (ZDICT_QSORT == ZDICT_QSORT_MSVC) qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), ctx); #elif defined(__OpenBSD__) + /* On OpenBSD, qsort() is not guaranteed to be stable, their mergesort() is. + * Note(@cyan): qsort() is never guaranteed to be stable, + * so why would this property only matter for OpenBSD ? + */ g_coverCtx = ctx; mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); @@ -782,7 +811,7 @@ ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover( BYTE* const dict = (BYTE*)dictBuffer; COVER_ctx_t ctx; COVER_map_t activeDmers; - const int displayLevel = parameters.zParams.notificationLevel; + const int displayLevel = (int)parameters.zParams.notificationLevel; parameters.splitPoint = 1.0; /* Checks */ if (!COVER_checkParameters(parameters, dictBufferCapacity)) { From a9b8fef2e808c227058da4d0f41768c877cfba4c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 13:30:25 -0700 Subject: [PATCH 753/937] add support for C11 Annex K qsort_s() standard defined re-entrant variant of qsort(). Unfortunately, Annex K is optional. --- .github/workflows/dev-short-tests.yml | 2 +- lib/dictBuilder/cover.c | 21 +++++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 164dc15c7..da35ec675 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -693,7 +693,7 @@ jobs: - name: Install musl-tools run: | sudo apt install -y musl-tools - - name: Compile the project with musl-gcc + - name: Compile with musl-gcc and test-zstd run: | CC=musl-gcc CFLAGS="-Werror -O3" CPPFLAGS=-DZDICT_QSORT=ZDICT_QSORT_C90 make -j -C tests test-zstd V=1 diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 9ed360033..467c1b17f 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -29,6 +29,8 @@ # endif #endif +#define __STDC_WANT_LIB_EXT1__ 1 /* request C11 Annex K, which includes qsort_s() */ + #include /* fprintf */ #include /* malloc, free, qsort_r */ @@ -68,8 +70,9 @@ #define ZDICT_QSORT_C90 ZDICT_QSORT_MIN #define ZDICT_QSORT_GNU 1 #define ZDICT_QSORT_APPLE 2 -#define ZDICT_QSORT_MSVC ZDICT_QSORT_MAX -#define ZDICT_QSORT_MAX 3 +#define ZDICT_QSORT_MSVC 3 +#define ZDICT_QSORT_C11 ZDICT_QSORT_MAX +#define ZDICT_QSORT_MAX 4 #ifndef ZDICT_QSORT # if defined(__APPLE__) @@ -77,7 +80,9 @@ # elif defined(_GNU_SOURCE) # define ZDICT_QSORT ZDICT_QSORT_GNU /* uses qsort_r() */ # elif defined(_WIN32) && defined(_MSC_VER) -# define ZDICT_QSORT ZDICT_QSORT_MSVC /* uses qsort_s() */ +# define ZDICT_QSORT ZDICT_QSORT_MSVC /* uses qsort_s() with a different order for parameters */ +# elif defined(STDC_LIB_EXT1) && (STDC_LIB_EXT1 > 0) /* C11 Annex K */ +# define ZDICT_QSORT ZDICT_QSORT_C11 /* uses qsort_s() */ # else # define ZDICT_QSORT ZDICT_QSORT_C90 /* uses standard qsort() which is not re-entrant (requires global variable) */ # endif @@ -204,7 +209,7 @@ static U32 *COVER_map_at(COVER_map_t *map, U32 key) { */ static void COVER_map_remove(COVER_map_t *map, U32 key) { U32 i = COVER_map_index(map, key); - COVER_map_pair_t *del = &map->data[i]; + COVER_map_pair_t* del = &map->data[i]; U32 shift = 1; if (del->value == MAP_EMPTY_VALUE) { return; @@ -307,7 +312,7 @@ static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) { */ #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) { -#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) +#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) || (ZDICT_QSORT == ZDICT_QSORT_C11) static int COVER_strict_cmp(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp(const void *lp, const void *rp) { @@ -323,7 +328,7 @@ static int COVER_strict_cmp(const void *lp, const void *rp) { */ #if (ZDICT_QSORT == ZDICT_QSORT_MSVC) || (ZDICT_QSORT == ZDICT_QSORT_APPLE) static int WIN_CDECL COVER_strict_cmp8(void* g_coverCtx, const void* lp, const void* rp) { -#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) +#elif (ZDICT_QSORT == ZDICT_QSORT_GNU) || (ZDICT_QSORT == ZDICT_QSORT_C11) static int COVER_strict_cmp8(const void *lp, const void *rp, void *g_coverCtx) { #else /* C90 fallback.*/ static int COVER_strict_cmp8(const void *lp, const void *rp) { @@ -355,6 +360,10 @@ static void stableSort(COVER_ctx_t *ctx) qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), ctx); +#elif (ZDICT_QSORT == ZDICT_QSORT_C11) + qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32), + (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), + ctx); #elif defined(__OpenBSD__) /* On OpenBSD, qsort() is not guaranteed to be stable, their mergesort() is. * Note(@cyan): qsort() is never guaranteed to be stable, From ddcb41a28204d5e298b052bef5cd839088d3bc6d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 11 Mar 2025 14:10:11 -0700 Subject: [PATCH 754/937] updated documentation --- lib/README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/README.md b/lib/README.md index 83bf00c19..89e53e6c8 100644 --- a/lib/README.md +++ b/lib/README.md @@ -193,11 +193,10 @@ The file structure is designed to make this selection manually achievable for an and assembly decoding loops. You may want to use this macro if these loops are slower on your platform. -- The macro `ZDICT_QSORT` can enforce selection of a specific sorting variant. - It can be notably set as `ZDICT_QSORT=ZDICT_QSORT_C90`, - for situations where autodetection fails, - for example with older versions of `musl`. - Other selectable suffixes are `_GNU`, `_APPLE` and `_MSVC`. +- The macro `ZDICT_QSORT` can enforce selection of a specific sorting variant, + which is useful when autodetection fails, for example with older versions of `musl`. + For this scenario, it can be set as `ZDICT_QSORT=ZDICT_QSORT_C90`. + Other selectable suffixes are `_GNU`, `_APPLE`, `_MSVC` and `_C11`. #### Windows : using MinGW+MSYS to create DLL From 4d53e27144b5ad02c6c37c27a998300986a4adaa Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 12 Mar 2025 09:55:14 -0700 Subject: [PATCH 755/937] removed OpenBSD specificity --- lib/dictBuilder/cover.c | 8 -------- 1 file changed, 8 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 467c1b17f..92c22a96c 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -364,14 +364,6 @@ static void stableSort(COVER_ctx_t *ctx) qsort_s(ctx->suffix, ctx->suffixSize, sizeof(U32), (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp), ctx); -#elif defined(__OpenBSD__) - /* On OpenBSD, qsort() is not guaranteed to be stable, their mergesort() is. - * Note(@cyan): qsort() is never guaranteed to be stable, - * so why would this property only matter for OpenBSD ? - */ - g_coverCtx = ctx; - mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32), - (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp)); #else /* C90 fallback.*/ g_coverCtx = ctx; /* TODO(cavalcanti): implement a reentrant qsort() when _r is not available. */ From cd8ca9d92e6fb3a4c962f8f6f50c3ee467177e06 Mon Sep 17 00:00:00 2001 From: "Z. Liu" Date: Thu, 20 Mar 2025 03:28:37 +0000 Subject: [PATCH 756/937] lib/zstd.h: move pragma before static otherwise will cause dev-python/zstandard build failed when compiling with clang as reported at https://bugs.gentoo.org/950259 the root cause is pycparser, which is unfixed since reported 2.5 years ago, :( Signed-off-by: Z. Liu --- lib/zstd.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 9fe542edc..850469490 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -1868,15 +1868,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 From 2fec3989c1567e0bd9b52100ad8c821886acf402 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 22 Mar 2025 18:23:31 -0700 Subject: [PATCH 757/937] add an assert to help static analyzers understand there is no overflow risk there. --- lib/compress/huf_compress.c | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/compress/huf_compress.c b/lib/compress/huf_compress.c index ea0007232..6f2194e79 100644 --- a/lib/compress/huf_compress.c +++ b/lib/compress/huf_compress.c @@ -425,6 +425,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]; From bea1e942f7f6e5c6502ad5dec8ce35954d41043e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 22 Mar 2025 23:52:45 -0700 Subject: [PATCH 758/937] [doc] minor clarification for maximum block size closes #4339 --- doc/zstd_compression_format.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index a2bf20cbc..7700c472d 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -0.4.3 (2024-10-07) +0.4.4 (2025-03-22) Introduction @@ -390,7 +390,7 @@ __`Block_Content`__ and __`Block_Maximum_Size`__ The size of `Block_Content` is limited by `Block_Maximum_Size`, which is the smallest of: - `Window_Size` -- 128 KB +- 128 KiB (131.072 bytes) `Block_Maximum_Size` is constant for a given frame. This maximum is applicable to both the decompressed size @@ -1742,6 +1742,7 @@ or at least provide a meaningful error code explaining for which reason it canno Version changes --------------- +- 0.4.4 : minor clarification for block size - 0.4.3 : clarifications for Huffman prefix code assignment example - 0.4.2 : refactor FSE table construction process, inspired by Donald Pian - 0.4.1 : clarifications on a few error scenarios, by Eric Lasota From 33f4d40d1eaa6fadca6960c3b8ec05e522cb6d99 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 23 Mar 2025 11:42:41 -0700 Subject: [PATCH 759/937] fix a risk of overflow on a time counter on Windows closes #4126 --- programs/timefn.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/programs/timefn.c b/programs/timefn.c index 4f045226b..d7f330974 100644 --- a/programs/timefn.c +++ b/programs/timefn.c @@ -28,18 +28,20 @@ UTIL_time_t UTIL_getTime(void) { static LARGE_INTEGER ticksPerSecond; + static double nsFactor = 1.0; static int init = 0; if (!init) { if (!QueryPerformanceFrequency(&ticksPerSecond)) { perror("timefn::QueryPerformanceFrequency"); abort(); } + nsFactor = 1000000000.0 / (double)ticksPerSecond.QuadPart; init = 1; } { UTIL_time_t r; LARGE_INTEGER x; QueryPerformanceCounter(&x); - r.t = (PTime)(x.QuadPart * 1000000000ULL / ticksPerSecond.QuadPart); + r.t = (PTime)((double)x.QuadPart * nsFactor); return r; } } From c59f7ac51ec943b5c5ea0746e97a225ee2d56881 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 23 Mar 2025 12:02:51 -0700 Subject: [PATCH 760/937] update benchmark result brotli uses -1 level, like all other compressors --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 22a127dc9..c542bb40e 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,8 @@ on the [Silesia compression corpus]. | Compressor name | Ratio | Compression| Decompress.| | --------------- | ------| -----------| ---------- | | **zstd 1.5.7 -1** | 2.896 | 510 MB/s | 1550 MB/s | +| brotli 1.1.0 -1 | 2.883 | 290 MB/s | 425 MB/s | | [zlib] 1.3.1 -1 | 2.743 | 105 MB/s | 390 MB/s | -| brotli 1.1.0 -0 | 2.702 | 400 MB/s | 425 MB/s | | **zstd 1.5.7 --fast=1** | 2.439 | 545 MB/s | 1850 MB/s | | **zstd 1.5.7 --fast=3** | 2.241 | 635 MB/s | 1980 MB/s | | quicklz 1.5.0 -1 | 2.238 | 520 MB/s | 750 MB/s | From 334af7228065f93e6d012f7edfa9593f0f1374af Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 23 Mar 2025 12:06:58 -0700 Subject: [PATCH 761/937] update zstd --fast benchmark result use --fast=4, instead of --fast=3, to make it more representative of a lzo equivalent scenario. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c542bb40e..3adacad51 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ on the [Silesia compression corpus]. | brotli 1.1.0 -1 | 2.883 | 290 MB/s | 425 MB/s | | [zlib] 1.3.1 -1 | 2.743 | 105 MB/s | 390 MB/s | | **zstd 1.5.7 --fast=1** | 2.439 | 545 MB/s | 1850 MB/s | -| **zstd 1.5.7 --fast=3** | 2.241 | 635 MB/s | 1980 MB/s | | quicklz 1.5.0 -1 | 2.238 | 520 MB/s | 750 MB/s | +| **zstd 1.5.7 --fast=4** | 2.146 | 665 MB/s | 2050 MB/s | | lzo1x 2.10 -1 | 2.106 | 650 MB/s | 780 MB/s | | [lz4] 1.10.0 | 2.101 | 675 MB/s | 3850 MB/s | | snappy 1.2.1 | 2.089 | 520 MB/s | 1500 MB/s | From eb168a0afc062f49b3d2180db69ce380c5085509 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 25 Mar 2025 14:23:14 -0700 Subject: [PATCH 762/937] add --patch-apply command as an equivalent for `-d --patch-from`. Requested by @sergeevabc in #2173. --- programs/zstdcli.c | 4 +++- tests/playTests.sh | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 4fed04e13..b9f961c16 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -230,7 +230,8 @@ static void usageAdvanced(const char* programName) #endif DISPLAYOUT(" --adapt Dynamically adapt compression level to I/O conditions.\n"); DISPLAYOUT(" --long[=#] Enable long distance matching with window log #. [Default: %u]\n", g_defaultMaxWindowLog); - DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n\n"); + DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n"); + DISPLAYOUT(" --patch-apply Equivalent for `-d --patch-from` \n\n"); # ifdef ZSTD_MULTITHREAD DISPLAYOUT(" -T# Spawn # compression threads. [Default: 1; pass 0 for core count.]\n"); DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n"); @@ -1124,6 +1125,7 @@ int main(int argCount, const char* argv[]) if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; } #endif if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); ultra = 1; continue; } + if (longCommandWArg(&argument, "--patch-apply")) { operation=zom_decompress; NEXT_FIELD(patchFromDictFileName); memLimit= 1U << ZSTD_WINDOWLOG_MAX; continue; } if (longCommandWArg(&argument, "--long")) { unsigned ldmWindowLog = 0; ldmFlag = 1; diff --git a/tests/playTests.sh b/tests/playTests.sh index 15f6e7761..486b395eb 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1777,11 +1777,15 @@ datagen -g1000 -P10 > tmp_patch zstd --patch-from=tmp_dict tmp_patch -o tmp_patch_diff zstd -d --patch-from=tmp_dict tmp_patch_diff -o tmp_patch_recon $DIFF -s tmp_patch_recon tmp_patch +zstd -f --patch-apply=tmp_dict tmp_patch_diff -o tmp_patch_recon +$DIFF -s tmp_patch_recon tmp_patch println "\n===> alternate syntax: patch-from origin" zstd -f --patch-from tmp_dict tmp_patch -o tmp_patch_diff zstd -df --patch-from tmp_dict tmp_patch_diff -o tmp_patch_recon $DIFF -s tmp_patch_recon tmp_patch +zstd -f --patch-apply tmp_dict tmp_patch_diff -o tmp_patch_recon +$DIFF -s tmp_patch_recon tmp_patch rm -rf tmp_* println "\n===> patch-from recursive tests" From 165e52ce627169e285c06d1d7879623fb75fcadd Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 24 Mar 2025 20:42:52 -0700 Subject: [PATCH 763/937] first implementation supporting Process Substitution --- programs/fileio.c | 8 +- programs/util.c | 192 ++++++++++++++++++++++++++++------------------ programs/util.h | 1 + 3 files changed, 123 insertions(+), 78 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 3f4460594..644a86ef4 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -537,15 +537,13 @@ static int FIO_removeFile(const char* path) return remove(path); } -/** FIO_openSrcFile() : - * condition : `srcFileName` must be non-NULL. `prefs` may be NULL. - * @result : FILE* to `srcFileName`, or NULL if it fails */ static FILE* FIO_openSrcFile(const FIO_prefs_t* const prefs, const char* srcFileName, stat_t* statbuf) { int allowBlockDevices = prefs != NULL ? prefs->allowBlockDevices : 0; assert(srcFileName != NULL); assert(statbuf != NULL); - if (!strcmp (srcFileName, stdinmark)) { + + if (!strcmp(srcFileName, stdinmark)) { DISPLAYLEVEL(4,"Using stdin for input \n"); SET_BINARY_MODE(stdin); return stdin; @@ -557,8 +555,10 @@ static FILE* FIO_openSrcFile(const FIO_prefs_t* const prefs, const char* srcFile return NULL; } + /* Accept regular files, FIFOs, and process substitution file descriptors */ if (!UTIL_isRegularFileStat(statbuf) && !UTIL_isFIFOStat(statbuf) + && !UTIL_isFileDescriptorPipe(srcFileName) /* Process substitution support */ && !(allowBlockDevices && UTIL_isBlockDevStat(statbuf)) ) { DISPLAYLEVEL(1, "zstd: %s is not a regular file -- ignored \n", diff --git a/programs/util.c b/programs/util.c index 065a35855..506bdd09e 100644 --- a/programs/util.c +++ b/programs/util.c @@ -448,6 +448,26 @@ int UTIL_isFIFOStat(const stat_t* statbuf) return 0; } +/* process substitution */ +int UTIL_isFileDescriptorPipe(const char* filename) +{ + UTIL_TRACE_CALL("UTIL_isFileDescriptorPipe(%s)", filename); + /* Check if the filename is a /dev/fd/ path which indicates a file descriptor */ + if (filename[0] == '/' && strncmp(filename, "/dev/fd/", 8) == 0) { + UTIL_TRACE_RET(1); + return 1; + } + + /* Check for alternative process substitution formats on different systems */ + if (filename[0] == '/' && strncmp(filename, "/proc/self/fd/", 14) == 0) { + UTIL_TRACE_RET(1); + return 1; + } + + UTIL_TRACE_RET(0); + return 0; /* Not recognized as a file descriptor pipe */ +} + /* UTIL_isBlockDevStat : distinguish named pipes */ int UTIL_isBlockDevStat(const stat_t* statbuf) { @@ -614,95 +634,119 @@ U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles) } -/* condition : @file must be valid, and not have reached its end. - * @return : length of line written into @buf, ended with `\0` instead of '\n', - * or 0, if there is no new line */ -static size_t readLineFromFile(char* buf, size_t len, FILE* file) -{ - assert(!feof(file)); - if ( fgets(buf, (int) len, file) == NULL ) return 0; - { size_t linelen = strlen(buf); - if (strlen(buf)==0) return 0; - if (buf[linelen-1] == '\n') linelen--; - buf[linelen] = '\0'; - return linelen+1; - } -} - -/* Conditions : - * size of @inputFileName file must be < @dstCapacity - * @dst must be initialized - * @return : nb of lines - * or -1 if there's an error - */ -static int -readLinesFromFile(void* dst, size_t dstCapacity, - const char* inputFileName) -{ - int nbFiles = 0; - size_t pos = 0; - char* const buf = (char*)dst; - FILE* const inputFile = fopen(inputFileName, "r"); - - assert(dst != NULL); - - if(!inputFile) { - if (g_utilDisplayLevel >= 1) perror("zstd:util:readLinesFromFile"); - return -1; - } - - while ( !feof(inputFile) ) { - size_t const lineLength = readLineFromFile(buf+pos, dstCapacity-pos, inputFile); - if (lineLength == 0) break; - assert(pos + lineLength <= dstCapacity); /* '=' for inputFile not terminated with '\n' */ - pos += lineLength; - ++nbFiles; - } - - CONTROL( fclose(inputFile) == 0 ); - - return nbFiles; -} - /*Note: buf is not freed in case function successfully created table because filesTable->fileNames[0] = buf*/ FileNamesTable* UTIL_createFileNamesTable_fromFileName(const char* inputFileName) { size_t nbFiles = 0; - char* buf; - size_t bufSize; - stat_t statbuf; + char* buf = NULL; + size_t bufSize = 0; + size_t totalRead = 0; + size_t bytesRead = 0; - if (!UTIL_stat(inputFileName, &statbuf) || !UTIL_isRegularFileStat(&statbuf)) - return NULL; - - { U64 const inputFileSize = UTIL_getFileSizeStat(&statbuf); - if(inputFileSize > MAX_FILE_OF_FILE_NAMES_SIZE) + /* Check if the input is a regular file or a file descriptor */ + { stat_t statbuf; + if (!UTIL_stat(inputFileName, &statbuf)) { + return NULL; + } + + if (!UTIL_isRegularFileStat(&statbuf) && + !UTIL_isFIFOStat(&statbuf) && + !UTIL_isFileDescriptorPipe(inputFileName)) { return NULL; - bufSize = (size_t)(inputFileSize + 1); /* (+1) to add '\0' at the end of last filename */ - } - - buf = (char*) malloc(bufSize); - CONTROL( buf != NULL ); - - { int const ret_nbFiles = readLinesFromFile(buf, bufSize, inputFileName); - - if (ret_nbFiles <= 0) { - free(buf); - return NULL; } - nbFiles = (size_t)ret_nbFiles; } - { const char** filenamesTable = (const char**) malloc(nbFiles * sizeof(*filenamesTable)); - CONTROL(filenamesTable != NULL); + /* Open the input file */ + { FILE* const inFile = fopen(inputFileName, "rb"); + if (inFile == NULL) return NULL; - { size_t fnb, pos = 0; + /* Start with a reasonable buffer size */ + bufSize = 64 * 1024; + buf = (char*)malloc(bufSize); + if (buf == NULL) { + fclose(inFile); + return NULL; + } + + /* Read the file incrementally */ + while ((bytesRead = fread(buf + totalRead, 1, bufSize - totalRead - 1, inFile)) > 0) { + totalRead += bytesRead; + + /* If buffer is nearly full, expand it */ + if (bufSize - totalRead < 1024) { + size_t newBufSize; + if (bufSize >= MAX_FILE_OF_FILE_NAMES_SIZE) { + /* Too large, abort */ + free(buf); + fclose(inFile); + return NULL; + } + + newBufSize = bufSize * 2; + if (newBufSize > MAX_FILE_OF_FILE_NAMES_SIZE) + newBufSize = MAX_FILE_OF_FILE_NAMES_SIZE; + + { char* newBuf = (char*)realloc(buf, newBufSize); + if (newBuf == NULL) { + free(buf); + fclose(inFile); + return NULL; + } + + buf = newBuf; + } + bufSize = newBufSize; + } + } + + fclose(inFile); + } + + /* Add null terminator to the end */ + buf[totalRead] = '\0'; + + /* Count and process the lines */ + { + size_t lineCount = 0; + size_t i = 0; + + /* Convert newlines to null terminators and count lines */ + while (i < totalRead) { + if (buf[i] == '\n') { + buf[i] = '\0'; /* Replace newlines with null terminators */ + lineCount++; + } + i++; + } + + /* Count the last line if it doesn't end with a newline */ + if (totalRead > 0 && buf[totalRead-1] != '\0') { + lineCount++; + } + + nbFiles = lineCount; + } + + if (nbFiles == 0) { + free(buf); + return NULL; + } + + /* Create the file names table */ + { const char** filenamesTable = (const char**)malloc(nbFiles * sizeof(*filenamesTable)); + if (filenamesTable == NULL) { + free(buf); + return NULL; + } + + { + size_t fnb, pos = 0; for (fnb = 0; fnb < nbFiles; fnb++) { filenamesTable[fnb] = buf+pos; pos += strlen(buf+pos)+1; /* +1 for the finishing `\0` */ } - assert(pos <= bufSize); + assert(pos <= bufSize); } return UTIL_assembleFileNamesTable(filenamesTable, nbFiles, buf); diff --git a/programs/util.h b/programs/util.h index d768e7660..5fd5de40b 100644 --- a/programs/util.h +++ b/programs/util.h @@ -191,6 +191,7 @@ int UTIL_isSameFileStat(const char* file1, const char* file2, const stat_t* file int UTIL_isCompressedFile(const char* infilename, const char *extensionList[]); int UTIL_isLink(const char* infilename); int UTIL_isFIFO(const char* infilename); +int UTIL_isFileDescriptorPipe(const char* filename); /** * Returns with the given file descriptor is a console. From 7630870b4747bc90cba2aa90fea0df4a89bfabc3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 24 Mar 2025 20:47:56 -0700 Subject: [PATCH 764/937] second implementation, better structured for improved maintenance --- programs/util.c | 192 ++++++++++++++++++++++++++---------------------- 1 file changed, 106 insertions(+), 86 deletions(-) diff --git a/programs/util.c b/programs/util.c index 506bdd09e..b6431b49f 100644 --- a/programs/util.c +++ b/programs/util.c @@ -151,7 +151,8 @@ int UTIL_requireUserConfirmation(const char* prompt, const char* abortMsg, /*-************************************* * Constants ***************************************/ -#define LIST_SIZE_INCREASE (8*1024) +#define KB * (1 << 10) +#define LIST_SIZE_INCREASE (8 KB) #define MAX_FILE_OF_FILE_NAMES_SIZE (1<<20)*50 @@ -634,125 +635,144 @@ U64 UTIL_getTotalFileSize(const char* const * fileNamesTable, unsigned nbFiles) } -/*Note: buf is not freed in case function successfully created table because filesTable->fileNames[0] = buf*/ -FileNamesTable* -UTIL_createFileNamesTable_fromFileName(const char* inputFileName) +/* Read the entire content of a file into a buffer with progressive resizing */ +static char* UTIL_readFileContent(FILE* inFile, size_t* totalReadPtr) { - size_t nbFiles = 0; - char* buf = NULL; - size_t bufSize = 0; + size_t bufSize = 64 KB; /* Start with a reasonable buffer size */ size_t totalRead = 0; size_t bytesRead = 0; + char* buf = (char*)malloc(bufSize); + if (buf == NULL) return NULL; - /* Check if the input is a regular file or a file descriptor */ - { stat_t statbuf; - if (!UTIL_stat(inputFileName, &statbuf)) { - return NULL; - } - if (!UTIL_isRegularFileStat(&statbuf) && - !UTIL_isFIFOStat(&statbuf) && - !UTIL_isFileDescriptorPipe(inputFileName)) { - return NULL; - } - } + /* Read the file incrementally */ + while ((bytesRead = fread(buf + totalRead, 1, bufSize - totalRead - 1, inFile)) > 0) { + totalRead += bytesRead; - /* Open the input file */ - { FILE* const inFile = fopen(inputFileName, "rb"); - if (inFile == NULL) return NULL; + /* If buffer is nearly full, expand it */ + if (bufSize - totalRead < 1 KB) { + if (bufSize >= MAX_FILE_OF_FILE_NAMES_SIZE) { + /* Too large, abort */ + free(buf); + return NULL; + } - /* Start with a reasonable buffer size */ - bufSize = 64 * 1024; - buf = (char*)malloc(bufSize); - if (buf == NULL) { - fclose(inFile); - return NULL; - } - - /* Read the file incrementally */ - while ((bytesRead = fread(buf + totalRead, 1, bufSize - totalRead - 1, inFile)) > 0) { - totalRead += bytesRead; - - /* If buffer is nearly full, expand it */ - if (bufSize - totalRead < 1024) { - size_t newBufSize; - if (bufSize >= MAX_FILE_OF_FILE_NAMES_SIZE) { - /* Too large, abort */ - free(buf); - fclose(inFile); - return NULL; - } - - newBufSize = bufSize * 2; + { size_t newBufSize = bufSize * 2; if (newBufSize > MAX_FILE_OF_FILE_NAMES_SIZE) newBufSize = MAX_FILE_OF_FILE_NAMES_SIZE; { char* newBuf = (char*)realloc(buf, newBufSize); if (newBuf == NULL) { free(buf); - fclose(inFile); return NULL; } buf = newBuf; - } - bufSize = newBufSize; - } - } - - fclose(inFile); + bufSize = newBufSize; + } } } } /* Add null terminator to the end */ buf[totalRead] = '\0'; + *totalReadPtr = totalRead; - /* Count and process the lines */ - { - size_t lineCount = 0; - size_t i = 0; + return buf; +} - /* Convert newlines to null terminators and count lines */ - while (i < totalRead) { - if (buf[i] == '\n') { - buf[i] = '\0'; /* Replace newlines with null terminators */ - lineCount++; - } - i++; - } +/* Process a buffer containing multiple lines and count the number of lines */ +static size_t UTIL_processLines(char* buffer, size_t bufferSize) +{ + size_t lineCount = 0; + size_t i = 0; - /* Count the last line if it doesn't end with a newline */ - if (totalRead > 0 && buf[totalRead-1] != '\0') { + /* Convert newlines to null terminators and count lines */ + while (i < bufferSize) { + if (buffer[i] == '\n') { + buffer[i] = '\0'; /* Replace newlines with null terminators */ lineCount++; } - - nbFiles = lineCount; + i++; } - if (nbFiles == 0) { - free(buf); + /* Count the last line if it doesn't end with a newline */ + if (bufferSize > 0 && (i == 0 || buffer[i-1] != '\0')) { + lineCount++; + } + + return lineCount; +} + +/* Create an array of pointers to the lines in a buffer */ +static const char** +UTIL_createLinePointers(char* buffer, size_t numLines, size_t bufferSize) +{ + size_t lineIndex = 0; + size_t pos = 0; + const char** linePointers = (const char**)malloc(numLines * sizeof(*linePointers)); + if (linePointers == NULL) return NULL; + + while (lineIndex < numLines && pos < bufferSize) { + linePointers[lineIndex++] = buffer + pos; + pos += strlen(buffer + pos) + 1; /* +1 for the finishing `\0` */ + } + + assert(pos <= bufferSize); + assert(lineIndex == numLines); + + return linePointers; +} + +FileNamesTable* +UTIL_createFileNamesTable_fromFileName(const char* inputFileName) +{ + stat_t statbuf; + FILE* inFile = NULL; + char* buffer = NULL; + const char** linePointers = NULL; + size_t numLines = 0; + size_t bufferSize = 0; + + /* Check if the input is a valid file */ + if (!UTIL_stat(inputFileName, &statbuf)) { return NULL; } - /* Create the file names table */ - { const char** filenamesTable = (const char**)malloc(nbFiles * sizeof(*filenamesTable)); - if (filenamesTable == NULL) { - free(buf); - return NULL; - } - - { - size_t fnb, pos = 0; - for (fnb = 0; fnb < nbFiles; fnb++) { - filenamesTable[fnb] = buf+pos; - pos += strlen(buf+pos)+1; /* +1 for the finishing `\0` */ - } - assert(pos <= bufSize); - } - - return UTIL_assembleFileNamesTable(filenamesTable, nbFiles, buf); + /* Check if the input is a supported type */ + if (!UTIL_isRegularFileStat(&statbuf) && + !UTIL_isFIFOStat(&statbuf) && + !UTIL_isFileDescriptorPipe(inputFileName)) { + return NULL; } + + /* Open the input file */ + inFile = fopen(inputFileName, "rb"); + if (inFile == NULL) return NULL; + + /* Read the file content */ + buffer = UTIL_readFileContent(inFile, &bufferSize); + fclose(inFile); + + if (buffer == NULL) return NULL; + + /* Process lines */ + numLines = UTIL_processLines(buffer, bufferSize); + if (numLines == 0) { + free(buffer); + return NULL; + } + + /* Create line pointers */ + linePointers = UTIL_createLinePointers(buffer, numLines, bufferSize); + if (linePointers == NULL) { + free(buffer); + return NULL; + } + + /* Create the final table */ + return UTIL_assembleFileNamesTable(linePointers, numLines, buffer); } + static FileNamesTable* UTIL_assembleFileNamesTable2(const char** filenames, size_t tableSize, size_t tableCapacity, char* buf) { From 76c2fdc7b76e1ab502dd058af9e58a22eeb382ad Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 24 Mar 2025 21:20:21 -0700 Subject: [PATCH 765/937] better naming and more narrow scope of local variables --- programs/util.c | 34 +++++++++++++++++----------------- programs/util.h | 4 ++-- programs/zstdcli.c | 2 +- tests/playTests.sh | 1 + 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/programs/util.c b/programs/util.c index b6431b49f..43f2b9408 100644 --- a/programs/util.c +++ b/programs/util.c @@ -723,34 +723,33 @@ UTIL_createLinePointers(char* buffer, size_t numLines, size_t bufferSize) } FileNamesTable* -UTIL_createFileNamesTable_fromFileName(const char* inputFileName) +UTIL_createFileNamesTable_fromFileList(const char* fileList) { stat_t statbuf; - FILE* inFile = NULL; char* buffer = NULL; - const char** linePointers = NULL; size_t numLines = 0; size_t bufferSize = 0; /* Check if the input is a valid file */ - if (!UTIL_stat(inputFileName, &statbuf)) { + if (!UTIL_stat(fileList, &statbuf)) { return NULL; } /* Check if the input is a supported type */ if (!UTIL_isRegularFileStat(&statbuf) && !UTIL_isFIFOStat(&statbuf) && - !UTIL_isFileDescriptorPipe(inputFileName)) { + !UTIL_isFileDescriptorPipe(fileList)) { return NULL; } /* Open the input file */ - inFile = fopen(inputFileName, "rb"); - if (inFile == NULL) return NULL; + { FILE* const inFile = fopen(fileList, "rb"); + if (inFile == NULL) return NULL; - /* Read the file content */ - buffer = UTIL_readFileContent(inFile, &bufferSize); - fclose(inFile); + /* Read the file content */ + buffer = UTIL_readFileContent(inFile, &bufferSize); + fclose(inFile); + } if (buffer == NULL) return NULL; @@ -762,14 +761,15 @@ UTIL_createFileNamesTable_fromFileName(const char* inputFileName) } /* Create line pointers */ - linePointers = UTIL_createLinePointers(buffer, numLines, bufferSize); - if (linePointers == NULL) { - free(buffer); - return NULL; - } + { const char** linePointers = UTIL_createLinePointers(buffer, numLines, bufferSize); + if (linePointers == NULL) { + free(buffer); + return NULL; + } - /* Create the final table */ - return UTIL_assembleFileNamesTable(linePointers, numLines, buffer); + /* Create the final table */ + return UTIL_assembleFileNamesTable(linePointers, numLines, buffer); + } } diff --git a/programs/util.h b/programs/util.h index 5fd5de40b..427bcf441 100644 --- a/programs/util.h +++ b/programs/util.h @@ -251,13 +251,13 @@ typedef struct size_t tableCapacity; } FileNamesTable; -/*! UTIL_createFileNamesTable_fromFileName() : +/*! UTIL_createFileNamesTable_fromFileList() : * read filenames from @inputFileName, and store them into returned object. * @return : a FileNamesTable*, or NULL in case of error (ex: @inputFileName doesn't exist). * Note: inputFileSize must be less than 50MB */ FileNamesTable* -UTIL_createFileNamesTable_fromFileName(const char* inputFileName); +UTIL_createFileNamesTable_fromFileList(const char* inputFileName); /*! UTIL_assembleFileNamesTable() : * This function takes ownership of its arguments, @filenames and @buf, diff --git a/programs/zstdcli.c b/programs/zstdcli.c index b9f961c16..fa7ea37b3 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1379,7 +1379,7 @@ int main(int argCount, const char* argv[]) size_t const nbFileLists = file_of_names->tableSize; size_t flNb; for (flNb=0; flNb < nbFileLists; flNb++) { - FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]); + FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileList(file_of_names->fileNames[flNb]); if (fnt==NULL) { DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]); CLEAN_RETURN(1); diff --git a/tests/playTests.sh b/tests/playTests.sh index 486b395eb..d3ce39846 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -848,6 +848,7 @@ ls tmp* > tmpList zstd -f tmp1 --filelist=tmpList --filelist=tmpList tmp2 tmp3 # can trigger an overflow of internal file list rm -rf tmp* + println "\n===> --[no-]content-size tests" datagen > tmp_contentsize From 94cfa0b5a064b91a61f8b49148ea857e042b51a1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 24 Mar 2025 21:31:51 -0700 Subject: [PATCH 766/937] minor: restore some code comment --- programs/fileio.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/programs/fileio.c b/programs/fileio.c index 644a86ef4..6514bf32c 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -537,6 +537,10 @@ static int FIO_removeFile(const char* path) return remove(path); } +/** FIO_openSrcFile() : + * condition : `srcFileName` must be non-NULL. + * optional: `prefs` may be NULL. + * @result : FILE* to `srcFileName`, or NULL if it fails */ static FILE* FIO_openSrcFile(const FIO_prefs_t* const prefs, const char* srcFileName, stat_t* statbuf) { int allowBlockDevices = prefs != NULL ? prefs->allowBlockDevices : 0; From 0bde39a9b32af17a9c21313b7f8cadaf9ae224cd Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 25 Mar 2025 15:22:55 -0700 Subject: [PATCH 767/937] visual studio fix --- programs/util.c | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/programs/util.c b/programs/util.c index 43f2b9408..94c40cc95 100644 --- a/programs/util.c +++ b/programs/util.c @@ -703,21 +703,34 @@ static size_t UTIL_processLines(char* buffer, size_t bufferSize) } /* Create an array of pointers to the lines in a buffer */ -static const char** -UTIL_createLinePointers(char* buffer, size_t numLines, size_t bufferSize) +static const char** UTIL_createLinePointers(char* buffer, size_t numLines, size_t bufferSize) { size_t lineIndex = 0; size_t pos = 0; - const char** linePointers = (const char**)malloc(numLines * sizeof(*linePointers)); - if (linePointers == NULL) return NULL; + void* const bufferPtrs = malloc(numLines * sizeof(const char**)); + const char** const linePointers = (const char**)bufferPtrs; + if (bufferPtrs == NULL) return NULL; while (lineIndex < numLines && pos < bufferSize) { - linePointers[lineIndex++] = buffer + pos; - pos += strlen(buffer + pos) + 1; /* +1 for the finishing `\0` */ + size_t len = 0; + linePointers[lineIndex++] = buffer+pos; + + /* Find the next null terminator, being careful not to go past the buffer */ + while ((pos + len < bufferSize) && buffer[pos + len] != '\0') { + len++; + } + + /* Move past this string and its null terminator */ + pos += len; + if (pos < bufferSize) pos++; /* Skip the null terminator if we're not at buffer end */ } - assert(pos <= bufferSize); - assert(lineIndex == numLines); + /* Verify we processed the expected number of lines */ + if (lineIndex != numLines) { + /* Something went wrong - we didn't find as many lines as expected */ + free(bufferPtrs); + return NULL; + } return linePointers; } From a293cdcb8581b3ff7c460c48fe7fe1b061bdd2e2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 25 Mar 2025 16:39:42 -0700 Subject: [PATCH 768/937] added CI test --- .github/workflows/dev-long-tests.yml | 5 +- tests/test_process_substitution.bash | 92 ++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) create mode 100755 tests/test_process_substitution.bash diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 275b22297..bf287857f 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -28,7 +28,10 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: make test - run: make test + run: | + make test + make -j zstd + ./tests/test_process_substitution.bash ./zstd # lasts ~26mn make-test-macos: diff --git a/tests/test_process_substitution.bash b/tests/test_process_substitution.bash new file mode 100755 index 000000000..586c42838 --- /dev/null +++ b/tests/test_process_substitution.bash @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# test_process_substitution.bash +# Test zstd's support for process substitution with --filelist + +# Process arguments +ZSTD_PATH="zstd" # Default to using zstd from PATH +if [ $# -ge 1 ]; then + ZSTD_PATH="$1" +fi + +echo "Using zstd executable: $ZSTD_PATH" + +set -e # Exit on error + +# Set up test directory and files +echo "Setting up test environment..." +TEST_DIR="tmp_process_substit" +rm -rf "$TEST_DIR" +mkdir -p "$TEST_DIR" +echo "Content of file 1" > "$TEST_DIR/file1.txt" +echo "Content of file 2" > "$TEST_DIR/file2.txt" +echo "Content of file 3" > "$TEST_DIR/file3.txt" + +# Clean up any previous test artifacts +rm -f "$TEST_DIR/output.zst" "$TEST_DIR/output_echo.zst" "$TEST_DIR/output_cat.zst" +rm -rf "$TEST_DIR/extracted" +mkdir -p "$TEST_DIR/extracted" + +echo "=== Testing process substitution with --filelist ===" + +# Test 1: Basic process substitution with find +echo "Test 1: Basic process substitution (find command)" +"$ZSTD_PATH" --filelist=<(find "$TEST_DIR" -name "*.txt" | sort) -c > "$TEST_DIR/output.zst" + +if [ -f "$TEST_DIR/output.zst" ]; then + echo "✓ Test 1 PASSED: Output file was created" +else + echo "✗ Test 1 FAILED: Output file was not created" + exit 1 +fi + +# Test 2: Process substitution with echo +echo "Test 2: Process substitution (echo command)" +"$ZSTD_PATH" --filelist=<(echo -e "$TEST_DIR/file1.txt\n$TEST_DIR/file2.txt") -c > "$TEST_DIR/output_echo.zst" + +if [ -f "$TEST_DIR/output_echo.zst" ]; then + echo "✓ Test 2 PASSED: Output file was created" +else + echo "✗ Test 2 FAILED: Output file was not created" + exit 1 +fi + +# Test 3: Process substitution with cat +echo "Test 3: Process substitution (cat command)" +echo -e "$TEST_DIR/file1.txt\n$TEST_DIR/file3.txt" > "$TEST_DIR/filelist.txt" +"$ZSTD_PATH" --filelist=<(cat "$TEST_DIR/filelist.txt") -c > "$TEST_DIR/output_cat.zst" + +if [ -f "$TEST_DIR/output_cat.zst" ]; then + echo "✓ Test 3 PASSED: Output file was created" +else + echo "✗ Test 3 FAILED: Output file was not created" + exit 1 +fi + +# Test 4: Verify contents of archives +echo "Test 4: Verifying archive contents" +"$ZSTD_PATH" -d "$TEST_DIR/output.zst" -o "$TEST_DIR/extracted/combined.out" + +if grep -q "Content of file 1" "$TEST_DIR/extracted/combined.out" && + grep -q "Content of file 2" "$TEST_DIR/extracted/combined.out" && + grep -q "Content of file 3" "$TEST_DIR/extracted/combined.out"; then + echo "✓ Test 4 PASSED: All files were correctly archived and extracted" +else + echo "✗ Test 4 FAILED: Not all expected content was found in the extracted file" + exit 1 +fi + +# Test 5: Edge case with empty list +echo "Test 5: Process substitution with empty input" +"$ZSTD_PATH" --filelist=<(echo "") -c > "$TEST_DIR/output_empty.zst" 2>/dev/null || true + +if [ -f "$TEST_DIR/output_empty.zst" ]; then + echo "✓ Test 5 PASSED: Handled empty input gracefully" +else + echo "✓ Test 5 PASSED: Properly rejected empty input" +fi + +# cleanup +rm -rf "$TEST_DIR" + +echo "All tests completed successfully!" + From 8626da73b6596bdd30c1289525db59f09737226d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Mar 2025 19:21:48 -0700 Subject: [PATCH 769/937] add error message clarification for inputs as process substitution --- programs/fileio.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/programs/fileio.c b/programs/fileio.c index 6514bf32c..6c6faa485 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -660,6 +660,9 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, #endif if (f == NULL) { DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno)); + if (UTIL_isFileDescriptorPipe(dstFileName)) { + DISPLAYLEVEL(1, "When using process substitution (<(...)), specify an output destination with -o or -c. \n"); + } } else { /* An increased buffer size can provide a significant performance * boost on some platforms. Note that providing a NULL buf with a From 0bdeb1d20451ae8dddffa19d9ff67917cf962a59 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 26 Mar 2025 21:33:26 -0700 Subject: [PATCH 770/937] fix test --- .../compress-file-to-dir-without-write-perm.sh.stderr.exact | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact index 95deaf2b1..515b63c60 100644 --- a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact +++ b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact @@ -23,4 +23,6 @@ Trace:FileStat: > UTIL_stat(-1, out/file.zst) Trace:FileStat: < 0 Trace:FileStat: < 0 zstd: out/file.zst: Permission denied +Trace:FileStat: > UTIL_isFileDescriptorPipe(out/file.zst) +Trace:FileStat: < 0 zstd: can't stat out/file.zst : Permission denied -- ignored From 2f9627863fb7ecd93b5f7f62b24ba9c7d7af1f77 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 28 Mar 2025 10:02:37 -0700 Subject: [PATCH 771/937] update error message --- programs/fileio.c | 5 +++-- .../compress-file-to-dir-without-write-perm.sh.stderr.exact | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 6c6faa485..dc7636949 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -659,9 +659,10 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, } #endif if (f == NULL) { - DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno)); if (UTIL_isFileDescriptorPipe(dstFileName)) { - DISPLAYLEVEL(1, "When using process substitution (<(...)), specify an output destination with -o or -c. \n"); + DISPLAYLEVEL(1, "zstd: error: no output specified (use -o or -c). \n"); + } else { + DISPLAYLEVEL(1, "zstd: %s: %s\n", dstFileName, strerror(errno)); } } else { /* An increased buffer size can provide a significant performance diff --git a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact index 515b63c60..9f254f8c2 100644 --- a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact +++ b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact @@ -22,7 +22,7 @@ Trace:FileStat: > UTIL_isRegularFile(out/file.zst) Trace:FileStat: > UTIL_stat(-1, out/file.zst) Trace:FileStat: < 0 Trace:FileStat: < 0 -zstd: out/file.zst: Permission denied Trace:FileStat: > UTIL_isFileDescriptorPipe(out/file.zst) Trace:FileStat: < 0 +zstd: out/file.zst: Permission denied zstd: can't stat out/file.zst : Permission denied -- ignored From 3bd5aa34046ef02ed0e8e04aa5e464a5a10bb042 Mon Sep 17 00:00:00 2001 From: Li-Yu Yu Date: Fri, 28 Mar 2025 21:16:29 +0000 Subject: [PATCH 772/937] Check regular file for sparse support after opening A regular file may be created by the open call. Checking after opening allows sparseFileSupport even if dstFileName does not already exist. --- programs/fileio.c | 23 +++++++++++------------ programs/util.c | 10 ++++++++++ programs/util.h | 1 + 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index dc7636949..b1303a2ad 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -585,8 +585,6 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, const char* srcFileName, const char* dstFileName, const int mode) { - int isDstRegFile; - if (prefs->testMode) return NULL; /* do not open file in test mode */ assert(dstFileName != NULL); @@ -606,16 +604,7 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, return NULL; } - isDstRegFile = UTIL_isRegularFile(dstFileName); /* invoke once */ - if (prefs->sparseFileSupport == 1) { - prefs->sparseFileSupport = ZSTD_SPARSE_DEFAULT; - if (!isDstRegFile) { - prefs->sparseFileSupport = 0; - DISPLAYLEVEL(4, "Sparse File Support is disabled when output is not a file \n"); - } - } - - if (isDstRegFile) { + if (UTIL_isRegularFile(dstFileName)) { /* Check if destination file already exists */ #if !defined(_WIN32) /* this test does not work on Windows : @@ -658,6 +647,16 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, f = fdopen(fd, "wb"); } #endif + + if (prefs->sparseFileSupport == 1) { + prefs->sparseFileSupport = ZSTD_SPARSE_DEFAULT; + /* Check regular file after opening with O_CREAT */ + if (!UTIL_isFdRegularFile(fd)) { + prefs->sparseFileSupport = 0; + DISPLAYLEVEL(4, "Sparse File Support is disabled when output is not a file \n"); + } + } + if (f == NULL) { if (UTIL_isFileDescriptorPipe(dstFileName)) { DISPLAYLEVEL(1, "zstd: error: no output specified (use -o or -c). \n"); diff --git a/programs/util.c b/programs/util.c index 94c40cc95..850bcacd2 100644 --- a/programs/util.c +++ b/programs/util.c @@ -197,6 +197,16 @@ int UTIL_stat(const char* filename, stat_t* statbuf) return UTIL_fstat(-1, filename, statbuf); } +int UTIL_isFdRegularFile(int fd) +{ + stat_t statbuf; + int ret; + UTIL_TRACE_CALL("UTIL_isFdRegularFile(%d)", fd); + ret = UTIL_fstat(fd, "", &statbuf) && UTIL_isRegularFileStat(&statbuf); + UTIL_TRACE_RET(ret); + return ret; +} + int UTIL_isRegularFile(const char* infilename) { stat_t statbuf; diff --git a/programs/util.h b/programs/util.h index 427bcf441..65e12633a 100644 --- a/programs/util.h +++ b/programs/util.h @@ -184,6 +184,7 @@ int UTIL_fchmod(const int fd, char const* filename, const stat_t* statbuf, mode_ * compute the needed information. */ +int UTIL_isFdRegularFile(int fd); int UTIL_isRegularFile(const char* infilename); int UTIL_isDirectory(const char* infilename); int UTIL_isSameFile(const char* file1, const char* file2); From 2a12bbaf909136ea28f2206441a10b0837c60325 Mon Sep 17 00:00:00 2001 From: Li-Yu Yu Date: Fri, 28 Mar 2025 21:45:47 +0000 Subject: [PATCH 773/937] Update cli-tests/file-stat tests --- programs/fileio.c | 6 ++++-- programs/util.c | 2 +- .../compress-file-to-dir-without-write-perm.sh.stderr.exact | 2 ++ ...sh.stderr.exact => compress-file-to-file.sh.stderr.glob} | 4 ++++ ...h.stderr.exact => compress-stdin-to-file.sh.stderr.glob} | 4 ++++ ....stderr.exact => decompress-file-to-file.sh.stderr.glob} | 4 ++++ ...stderr.exact => decompress-stdin-to-file.sh.stderr.glob} | 4 ++++ 7 files changed, 23 insertions(+), 3 deletions(-) rename tests/cli-tests/file-stat/{compress-file-to-file.sh.stderr.exact => compress-file-to-file.sh.stderr.glob} (91%) rename tests/cli-tests/file-stat/{compress-stdin-to-file.sh.stderr.exact => compress-stdin-to-file.sh.stderr.glob} (86%) rename tests/cli-tests/file-stat/{decompress-file-to-file.sh.stderr.exact => decompress-file-to-file.sh.stderr.glob} (90%) rename tests/cli-tests/file-stat/{decompress-stdin-to-file.sh.stderr.exact => decompress-stdin-to-file.sh.stderr.glob} (84%) diff --git a/programs/fileio.c b/programs/fileio.c index b1303a2ad..77f3d35f9 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -630,6 +630,7 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, } { + int isDstRegFile; #if defined(_WIN32) /* Windows requires opening the file as a "binary" file to avoid * mangling. This macro doesn't exist on unix. */ @@ -648,10 +649,11 @@ FIO_openDstFile(FIO_ctx_t* fCtx, FIO_prefs_t* const prefs, } #endif + /* Check regular file after opening with O_CREAT */ + isDstRegFile = UTIL_isFdRegularFile(fd); if (prefs->sparseFileSupport == 1) { prefs->sparseFileSupport = ZSTD_SPARSE_DEFAULT; - /* Check regular file after opening with O_CREAT */ - if (!UTIL_isFdRegularFile(fd)) { + if (!isDstRegFile) { prefs->sparseFileSupport = 0; DISPLAYLEVEL(4, "Sparse File Support is disabled when output is not a file \n"); } diff --git a/programs/util.c b/programs/util.c index 850bcacd2..d11f13cfd 100644 --- a/programs/util.c +++ b/programs/util.c @@ -202,7 +202,7 @@ int UTIL_isFdRegularFile(int fd) stat_t statbuf; int ret; UTIL_TRACE_CALL("UTIL_isFdRegularFile(%d)", fd); - ret = UTIL_fstat(fd, "", &statbuf) && UTIL_isRegularFileStat(&statbuf); + ret = fd >= 0 && UTIL_fstat(fd, "", &statbuf) && UTIL_isRegularFileStat(&statbuf); UTIL_TRACE_RET(ret); return ret; } diff --git a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact index 9f254f8c2..05d91ffc9 100644 --- a/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact +++ b/tests/cli-tests/file-stat/compress-file-to-dir-without-write-perm.sh.stderr.exact @@ -22,6 +22,8 @@ Trace:FileStat: > UTIL_isRegularFile(out/file.zst) Trace:FileStat: > UTIL_stat(-1, out/file.zst) Trace:FileStat: < 0 Trace:FileStat: < 0 +Trace:FileStat: > UTIL_isFdRegularFile(-1) +Trace:FileStat: < 0 Trace:FileStat: > UTIL_isFileDescriptorPipe(out/file.zst) Trace:FileStat: < 0 zstd: out/file.zst: Permission denied diff --git a/tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.exact b/tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.glob similarity index 91% rename from tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.exact rename to tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.glob index 32d248ee5..17a677deb 100644 --- a/tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.exact +++ b/tests/cli-tests/file-stat/compress-file-to-file.sh.stderr.glob @@ -22,6 +22,10 @@ Trace:FileStat: > UTIL_isRegularFile(file.zst) Trace:FileStat: > UTIL_stat(-1, file.zst) Trace:FileStat: < 0 Trace:FileStat: < 0 +Trace:FileStat: > UTIL_isFdRegularFile(*) +Trace:FileStat: > UTIL_stat(*, ) +Trace:FileStat: < 1 +Trace:FileStat: < 1 Trace:FileStat: > UTIL_isRegularFile(file.zst) Trace:FileStat: > UTIL_stat(-1, file.zst) Trace:FileStat: < 1 diff --git a/tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.exact b/tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.glob similarity index 86% rename from tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.exact rename to tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.glob index 9183c4674..38732cbe9 100644 --- a/tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.exact +++ b/tests/cli-tests/file-stat/compress-stdin-to-file.sh.stderr.glob @@ -14,6 +14,10 @@ Trace:FileStat: > UTIL_isRegularFile(file.zst) Trace:FileStat: > UTIL_stat(-1, file.zst) Trace:FileStat: < 0 Trace:FileStat: < 0 +Trace:FileStat: > UTIL_isFdRegularFile(*) +Trace:FileStat: > UTIL_stat(*, ) +Trace:FileStat: < 1 +Trace:FileStat: < 1 Trace:FileStat: > UTIL_isRegularFile(file.zst) Trace:FileStat: > UTIL_stat(-1, file.zst) Trace:FileStat: < 1 diff --git a/tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.exact b/tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.glob similarity index 90% rename from tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.exact rename to tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.glob index ad3a0deb8..ce194dfb3 100644 --- a/tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.exact +++ b/tests/cli-tests/file-stat/decompress-file-to-file.sh.stderr.glob @@ -22,6 +22,10 @@ Trace:FileStat: > UTIL_isRegularFile(file) Trace:FileStat: > UTIL_stat(-1, file) Trace:FileStat: < 0 Trace:FileStat: < 0 +Trace:FileStat: > UTIL_isFdRegularFile(*) +Trace:FileStat: > UTIL_stat(*, ) +Trace:FileStat: < 1 +Trace:FileStat: < 1 Trace:FileStat: > UTIL_isRegularFile(file) Trace:FileStat: > UTIL_stat(-1, file) Trace:FileStat: < 1 diff --git a/tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.exact b/tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.glob similarity index 84% rename from tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.exact rename to tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.glob index 716a7ac7b..9eb920883 100644 --- a/tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.exact +++ b/tests/cli-tests/file-stat/decompress-stdin-to-file.sh.stderr.glob @@ -14,6 +14,10 @@ Trace:FileStat: > UTIL_isRegularFile(file) Trace:FileStat: > UTIL_stat(-1, file) Trace:FileStat: < 0 Trace:FileStat: < 0 +Trace:FileStat: > UTIL_isFdRegularFile(*) +Trace:FileStat: > UTIL_stat(*, ) +Trace:FileStat: < 1 +Trace:FileStat: < 1 Trace:FileStat: > UTIL_isRegularFile(file) Trace:FileStat: > UTIL_stat(-1, file) Trace:FileStat: < 1 From 28ffb100aba333e2535021c5c0a672e68ea025bc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 05:21:33 +0000 Subject: [PATCH 774/937] Bump actions/setup-java from 4.7.0 to 4.7.1 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 4.7.0 to 4.7.1. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/3a4f6e1af504cf6a31855fa899c6aa5355ba6c12...c5195efecf7bdfc987ee8bae7a71cb8b11521c00) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 4.7.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 5746d86f7..7ba3958b8 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Set up JDK 17 - uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0 + uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 with: java-version: '17' distribution: 'temurin' From 8929d3b09f7391b4756dd5056fded3a6a90bc9a4 Mon Sep 17 00:00:00 2001 From: Etienne Cordonnier Date: Fri, 18 Apr 2025 14:37:50 +0200 Subject: [PATCH 775/937] Fix duplicate LC_RPATH error on MacOS After the update to MacOS 15.4, the dynamic loader dyld treats duplicated LC_RPATH as an error. The `FLAGS` variable already contains `LDFLAGS`, thus using both `FLAGS` and `LDFLAGS` duplicates all `LDFLAGS`, including `-Wl,rpath` parameters. The duplicate LC_RPATH causes this kind of errors: ``` dyld[29361]: Library not loaded: @loader_path/../lib/libzstd.1.dylib Referenced from: <7131C877-3CF0-33AC-AA05-257BA4FDD770> /Users/foobar/... Reason: tried: '/Users/foobar/..../lib/libzstd.1.dylib' (duplicate LC_RPATH '/usr/mypath.../lib') ``` Closes https://github.com/facebook/zstd/issues/4369 Signed-off-by: Etienne Cordonnier --- lib/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/Makefile b/lib/Makefile index a6a0eb09d..e9a50a8f7 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -166,7 +166,7 @@ $(ZSTD_DYNLIB): $(ZSTD_DYNLIB_OBJ) $(if $(filter -DZSTD_MULTITHREAD,$(CPPFLAGS)),\ @echo compiling multi-threaded dynamic library $(LIBVER),\ @echo compiling single-threaded dynamic library $(LIBVER)) - $(CC) $(FLAGS) $^ $(LDFLAGS) $(SONAME_FLAGS) -o $@ + $(CC) $(FLAGS) $^ $(SONAME_FLAGS) -o $@ @echo creating versioned links ln -sf $@ libzstd.$(SHARED_EXT_MAJOR) ln -sf $@ libzstd.$(SHARED_EXT) @@ -255,7 +255,7 @@ libzstd-nomt: $(ZSTD_NOMT_FILES) echo "Error: Found zstdmt in list."; \ exit 1; \ fi - $(CC) $(FLAGS) $^ $(LDFLAGS) $(SONAME_FLAGS) -o $@ + $(CC) $(FLAGS) $^ $(SONAME_FLAGS) -o $@ .PHONY: clean clean: From 7f907d5c232fe89c206af0a146794b755df8f1ae Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 29 Apr 2025 08:55:19 -0700 Subject: [PATCH 776/937] fix minor warning in zstreamtest --- tests/zstreamtest.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/zstreamtest.c b/tests/zstreamtest.c index 760d9f26c..88a20a3e2 100644 --- a/tests/zstreamtest.c +++ b/tests/zstreamtest.c @@ -1896,7 +1896,7 @@ static int basicUnitTests(U32 seed, double compressibility, int bigTests) CHECK_Z(ZSTD_CCtx_setParameter(zc, ZSTD_c_checksumFlag, 1)); /* Write a bunch of 6 byte blocks */ while (remainingInput > 0) { - char testBuffer[6] = "\xAA\xAA\xAA\xAA\xAA\xAA"; + char testBuffer[6] = { 0x66, 0x66, 0x66, 0x66, 0x66, 0x66 }; const size_t kSmallBlockSize = sizeof(testBuffer); ZSTD_inBuffer in = {testBuffer, kSmallBlockSize, 0}; From 2d224dc7457fb6a6267f801c59546b981d6552fb Mon Sep 17 00:00:00 2001 From: Nobuhiro Iwamatsu Date: Mon, 28 Apr 2025 18:03:33 +0900 Subject: [PATCH 777/937] Add License variable to pkg-config file The pkg-config file has License variable that allows you to set the license for the software. This sets 'BSD-3-Clause OR GPL-2.0-only' to License. Ref: https://github.com/pkgconf/pkgconf/blob/master/man/pc.5#L116 Signed-off-by: Nobuhiro Iwamatsu --- lib/libzstd.pc.in | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/libzstd.pc.in b/lib/libzstd.pc.in index d7b6c8582..2220a5797 100644 --- a/lib/libzstd.pc.in +++ b/lib/libzstd.pc.in @@ -14,3 +14,4 @@ Version: @VERSION@ Libs: -L${libdir} -lzstd @LIBS_MT@ Libs.private: @LIBS_PRIVATE@ Cflags: -I${includedir} @LIBS_MT@ +License: BSD-3-Clause OR GPL-2.0-only From 769723aee2540aaff8951ac432a1babed358aa71 Mon Sep 17 00:00:00 2001 From: Thomas Devoogdt Date: Tue, 1 Apr 2025 22:47:45 +0200 Subject: [PATCH 778/937] [cmake] only require a CXX compiler when tests are build Signed-off-by: Thomas Devoogdt --- build/cmake/CMakeLists.txt | 20 +++++++---- .../AddZstdCompilationFlags.cmake | 34 +++++++++---------- 2 files changed, 30 insertions(+), 24 deletions(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index 347d41c0f..f08905345 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -37,7 +37,6 @@ project(zstd VERSION "${ZSTD_FULL_VERSION}" LANGUAGES C # Main library is in C ASM # And ASM - CXX # Testing contributed code also utilizes CXX ) message(STATUS "ZSTD VERSION: ${zstd_VERSION}") @@ -54,12 +53,6 @@ endif() include(GNUInstallDirs) -#----------------------------------------------------------------------------- -# Add extra compilation flags -#----------------------------------------------------------------------------- -include(AddZstdCompilationFlags) -ADD_ZSTD_COMPILATION_FLAGS() - # Always hide XXHash symbols add_definitions(-DXXH_NAMESPACE=ZSTD_) @@ -123,6 +116,19 @@ if (MSVC) option(ZSTD_USE_STATIC_RUNTIME "LINK TO STATIC RUN-TIME LIBRARIES" OFF) endif () +# Enable C++ support for testing. +set(ZSTD_ENABLE_CXX ${ZSTD_BUILD_TESTS}) + +if(ZSTD_ENABLE_CXX) + enable_language(CXX) +endif() + +#----------------------------------------------------------------------------- +# Add extra compilation flags +#----------------------------------------------------------------------------- +include(AddZstdCompilationFlags) +ADD_ZSTD_COMPILATION_FLAGS(ON ZSTD_ENABLE_CXX ON) # C CXX LD + #----------------------------------------------------------------------------- # External dependencies #----------------------------------------------------------------------------- diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake index 5f381c656..25231b5ec 100644 --- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake +++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake @@ -49,7 +49,7 @@ function(EnableCompilerFlag _flag _C _CXX _LD) endif () endfunction() -macro(ADD_ZSTD_COMPILATION_FLAGS) +macro(ADD_ZSTD_COMPILATION_FLAGS _C _CXX _LD) # We set ZSTD_HAS_NOEXECSTACK if we are certain we've set all the required # compiler flags to mark the stack as non-executable. set(ZSTD_HAS_NOEXECSTACK false) @@ -63,26 +63,26 @@ macro(ADD_ZSTD_COMPILATION_FLAGS) # EnableCompilerFlag("-std=c99" true false) # Set C compilation to c99 standard if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND MSVC) # clang-cl normally maps -Wall to -Weverything. - EnableCompilerFlag("/clang:-Wall" true true false) + EnableCompilerFlag("/clang:-Wall" _C _CXX false) else () - EnableCompilerFlag("-Wall" true true false) + EnableCompilerFlag("-Wall" _C _CXX false) endif () - EnableCompilerFlag("-Wextra" true true false) - EnableCompilerFlag("-Wundef" true true false) - EnableCompilerFlag("-Wshadow" true true false) - EnableCompilerFlag("-Wcast-align" true true false) - EnableCompilerFlag("-Wcast-qual" true true false) - EnableCompilerFlag("-Wstrict-prototypes" true false false) + EnableCompilerFlag("-Wextra" _C _CXX false) + EnableCompilerFlag("-Wundef" _C _CXX false) + EnableCompilerFlag("-Wshadow" _C _CXX false) + EnableCompilerFlag("-Wcast-align" _C _CXX false) + EnableCompilerFlag("-Wcast-qual" _C _CXX false) + EnableCompilerFlag("-Wstrict-prototypes" _C false false) # Enable asserts in Debug mode if (CMAKE_BUILD_TYPE MATCHES "Debug") - EnableCompilerFlag("-DDEBUGLEVEL=1" true true false) + EnableCompilerFlag("-DDEBUGLEVEL=1" _C _CXX false) endif () # Add noexecstack flags # LDFLAGS - EnableCompilerFlag("-Wl,-z,noexecstack" false false true) + EnableCompilerFlag("-Wl,-z,noexecstack" false false _LD) # CFLAGS & CXXFLAGS - EnableCompilerFlag("-Qunused-arguments" true true false) - EnableCompilerFlag("-Wa,--noexecstack" true true false) + EnableCompilerFlag("-Qunused-arguments" _C _CXX false) + EnableCompilerFlag("-Wa,--noexecstack" _C _CXX false) # NOTE: Using 3 nested ifs because the variables are sometimes # empty if the condition is false, and sometimes equal to false. # This implicitly converts them to truthy values. There may be @@ -99,15 +99,15 @@ macro(ADD_ZSTD_COMPILATION_FLAGS) set(ACTIVATE_MULTITHREADED_COMPILATION "ON" CACHE BOOL "activate multi-threaded compilation (/MP flag)") if (CMAKE_GENERATOR MATCHES "Visual Studio" AND ACTIVATE_MULTITHREADED_COMPILATION) - EnableCompilerFlag("/MP" true true false) + EnableCompilerFlag("/MP" _C _CXX false) endif () # UNICODE SUPPORT - EnableCompilerFlag("/D_UNICODE" true true false) - EnableCompilerFlag("/DUNICODE" true true false) + EnableCompilerFlag("/D_UNICODE" _C _CXX false) + EnableCompilerFlag("/DUNICODE" _C _CXX false) # Enable asserts in Debug mode if (CMAKE_BUILD_TYPE MATCHES "Debug") - EnableCompilerFlag("/DDEBUGLEVEL=1" true true false) + EnableCompilerFlag("/DDEBUGLEVEL=1" _C _CXX false) endif () endif () From 6b0039abcf5fb9ef1f942ded9cc86ec10e062c1e Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Tue, 6 May 2025 21:55:22 -0400 Subject: [PATCH 779/937] seekable_format: Build with $(MAKE) This passes make flags, such as `-jN` for building in parallel, to the underlying make. --- contrib/seekable_format/examples/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/seekable_format/examples/Makefile b/contrib/seekable_format/examples/Makefile index fcc04587c..336d8c722 100644 --- a/contrib/seekable_format/examples/Makefile +++ b/contrib/seekable_format/examples/Makefile @@ -28,7 +28,7 @@ all: seekable_compression seekable_decompression seekable_decompression_mem \ parallel_processing $(ZSTDLIB): - make -C $(ZSTDLIB_PATH) $(ZSTDLIB_NAME) + $(MAKE) -C $(ZSTDLIB_PATH) $(ZSTDLIB_NAME) seekable_compression : seekable_compression.c $(SEEKABLE_OBJS) $(CC) $(CPPFLAGS) $(CFLAGS) $^ $(LDFLAGS) -o $@ From f5b6531902a8e12b679b10ea748aa55ac0d40d66 Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Tue, 6 May 2025 21:57:29 -0400 Subject: [PATCH 780/937] seekable_format: Link against multi-threaded libzstd.a Some of these examples are intended to be parallel, and don't make sense to link against single-threaded libzstd. The filename of mt and nomt libzstd are identical, so it's still possible to link against the single-threaded one, just harder. --- contrib/seekable_format/examples/Makefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contrib/seekable_format/examples/Makefile b/contrib/seekable_format/examples/Makefile index 336d8c722..f15a4a15a 100644 --- a/contrib/seekable_format/examples/Makefile +++ b/contrib/seekable_format/examples/Makefile @@ -11,6 +11,8 @@ ZSTDLIB_PATH = ../../../lib ZSTDLIB_NAME = libzstd.a +# Parallel tools only make sense against multi-threaded libzstd +ZSTDLIB_TARGET = $(ZSTDLIB_NAME)-mt ZSTDLIB = $(ZSTDLIB_PATH)/$(ZSTDLIB_NAME) CPPFLAGS += -DXXH_NAMESPACE=ZSTD_ -I../ -I../../../lib -I../../../lib/common @@ -28,7 +30,7 @@ all: seekable_compression seekable_decompression seekable_decompression_mem \ parallel_processing $(ZSTDLIB): - $(MAKE) -C $(ZSTDLIB_PATH) $(ZSTDLIB_NAME) + $(MAKE) -C $(ZSTDLIB_PATH) $(ZSTDLIB_TARGET) seekable_compression : seekable_compression.c $(SEEKABLE_OBJS) $(CC) $(CPPFLAGS) $(CFLAGS) $^ $(LDFLAGS) -o $@ From 2d4cff69c439d40b2bb39300f003522da8f2c6ab Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Tue, 6 May 2025 23:26:32 -0400 Subject: [PATCH 781/937] seekable_format: Make parallel_compression use memory properly Previously, parallel_compression would only handle each job's results after ALL jobs were successfully queued. This caused all src/dst buffers to remain in memory until then! It also polled to check whether a job completed, which is racy without any memory barrier. Now, we flush results as a side effect of completing a job. Completed frames are placed in an ordered linked-list, and any eligible frames are flushed. This may be zero or multiple frames, depending on the order in which jobs finish. This design also makes it simple to support streaming input, so that is now available. Just pass `-` as the filename, and stdin/stdout will be used for I/O. --- .../examples/parallel_compression.c | 215 +++++++++++------- 1 file changed, 127 insertions(+), 88 deletions(-) diff --git a/contrib/seekable_format/examples/parallel_compression.c b/contrib/seekable_format/examples/parallel_compression.c index 4e06fae32..d54704c11 100644 --- a/contrib/seekable_format/examples/parallel_compression.c +++ b/contrib/seekable_format/examples/parallel_compression.c @@ -23,6 +23,8 @@ #include "xxhash.h" +#define ZSTD_MULTITHREAD 1 +#include "threading.h" #include "pool.h" // use zstd thread pool for demo #include "../zstd_seekable.h" @@ -72,114 +74,87 @@ static size_t fclose_orDie(FILE* file) exit(6); } -static void fseek_orDie(FILE* file, long int offset, int origin) -{ - if (!fseek(file, offset, origin)) { - if (!fflush(file)) return; - } - /* error */ - perror("fseek"); - exit(7); -} - -static long int ftell_orDie(FILE* file) -{ - long int off = ftell(file); - if (off != -1) return off; - /* error */ - perror("ftell"); - exit(8); -} +struct state { + FILE* fout; + ZSTD_pthread_mutex_t mutex; + size_t nextID; + struct job* pending; + ZSTD_frameLog* frameLog; + const int compressionLevel; +}; struct job { - const void* src; + size_t id; + struct job* next; + struct state* state; + + void* src; size_t srcSize; void* dst; size_t dstSize; unsigned checksum; - - int compressionLevel; - int done; }; +static void addPending_inmutex(struct state* state, struct job* job) +{ + struct job** p = &state->pending; + while (*p && (*p)->id < job->id) + p = &(*p)->next; + job->next = *p; + *p = job; +} + +static void flushFrame(struct state* state, struct job* job) +{ + fwrite_orDie(job->dst, job->dstSize, state->fout); + free(job->dst); + + size_t ret = ZSTD_seekable_logFrame(state->frameLog, job->dstSize, job->srcSize, job->checksum); + if (ZSTD_isError(ret)) { + fprintf(stderr, "ZSTD_seekable_logFrame() error : %s \n", ZSTD_getErrorName(ret)); + exit(12); + } +} + +static void flushPending_inmutex(struct state* state) +{ + while (state->pending && state->pending->id == state->nextID) { + struct job* p = state->pending; + state->pending = p->next; + flushFrame(state, p); + free(p); + state->nextID++; + } +} + +static void finishFrame(struct job* job) +{ + struct state *state = job->state; + ZSTD_pthread_mutex_lock(&state->mutex); + addPending_inmutex(state, job); + flushPending_inmutex(state); + ZSTD_pthread_mutex_unlock(&state->mutex); +} + static void compressFrame(void* opaque) { struct job* job = opaque; job->checksum = XXH64(job->src, job->srcSize, 0); - size_t ret = ZSTD_compress(job->dst, job->dstSize, job->src, job->srcSize, job->compressionLevel); + size_t ret = ZSTD_compress(job->dst, job->dstSize, job->src, job->srcSize, job->state->compressionLevel); if (ZSTD_isError(ret)) { fprintf(stderr, "ZSTD_compress() error : %s \n", ZSTD_getErrorName(ret)); exit(20); } - job->dstSize = ret; - job->done = 1; -} -static void compressFile_orDie(const char* fname, const char* outName, int cLevel, unsigned frameSize, int nbThreads) -{ - POOL_ctx* pool = POOL_create(nbThreads, nbThreads); - if (pool == NULL) { fprintf(stderr, "POOL_create() error \n"); exit(9); } + // No longer need + free(job->src); + job->src = NULL; - FILE* const fin = fopen_orDie(fname, "rb"); - FILE* const fout = fopen_orDie(outName, "wb"); - - if (ZSTD_compressBound(frameSize) > 0xFFFFFFFFU) { fprintf(stderr, "Frame size too large \n"); exit(10); } - unsigned dstSize = ZSTD_compressBound(frameSize); - - - fseek_orDie(fin, 0, SEEK_END); - long int length = ftell_orDie(fin); - fseek_orDie(fin, 0, SEEK_SET); - - size_t numFrames = (length + frameSize - 1) / frameSize; - - struct job* jobs = malloc_orDie(sizeof(struct job) * numFrames); - - size_t i; - for(i = 0; i < numFrames; i++) { - void* in = malloc_orDie(frameSize); - void* out = malloc_orDie(dstSize); - - size_t inSize = fread_orDie(in, frameSize, fin); - - jobs[i].src = in; - jobs[i].srcSize = inSize; - jobs[i].dst = out; - jobs[i].dstSize = dstSize; - jobs[i].compressionLevel = cLevel; - jobs[i].done = 0; - POOL_add(pool, compressFrame, &jobs[i]); - } - - ZSTD_frameLog* fl = ZSTD_seekable_createFrameLog(1); - if (fl == NULL) { fprintf(stderr, "ZSTD_seekable_createFrameLog() failed \n"); exit(11); } - for (i = 0; i < numFrames; i++) { - while (!jobs[i].done) SLEEP(5); /* wake up every 5 milliseconds to check */ - fwrite_orDie(jobs[i].dst, jobs[i].dstSize, fout); - free((void*)jobs[i].src); - free(jobs[i].dst); - - size_t ret = ZSTD_seekable_logFrame(fl, jobs[i].dstSize, jobs[i].srcSize, jobs[i].checksum); - if (ZSTD_isError(ret)) { fprintf(stderr, "ZSTD_seekable_logFrame() error : %s \n", ZSTD_getErrorName(ret)); } - } - - { unsigned char seekTableBuff[1024]; - ZSTD_outBuffer out = {seekTableBuff, 1024, 0}; - while (ZSTD_seekable_writeSeekTable(fl, &out) != 0) { - fwrite_orDie(seekTableBuff, out.pos, fout); - out.pos = 0; - } - fwrite_orDie(seekTableBuff, out.pos, fout); - } - - ZSTD_seekable_freeFrameLog(fl); - free(jobs); - fclose_orDie(fout); - fclose_orDie(fin); + finishFrame(job); } static const char* createOutFilename_orDie(const char* filename) @@ -193,6 +168,71 @@ static const char* createOutFilename_orDie(const char* filename) return (const char*)outSpace; } +static void openInOut_orDie(const char* fname, FILE** fin, FILE** fout) { + if (strcmp(fname, "-") == 0) { + *fin = stdin; + *fout = stdout; + } else { + *fin = fopen_orDie(fname, "rb"); + const char* outName = createOutFilename_orDie(fname); + *fout = fopen_orDie(outName, "wb"); + } +} + +static void compressFile_orDie(const char* fname, int cLevel, unsigned frameSize, int nbThreads) +{ + struct state state = { + .nextID = 0, + .pending = NULL, + .compressionLevel = cLevel, + }; + ZSTD_pthread_mutex_init(&state.mutex, NULL); + state.frameLog = ZSTD_seekable_createFrameLog(1); + if (state.frameLog == NULL) { fprintf(stderr, "ZSTD_seekable_createFrameLog() failed \n"); exit(11); } + + POOL_ctx* pool = POOL_create(nbThreads, nbThreads); + if (pool == NULL) { fprintf(stderr, "POOL_create() error \n"); exit(9); } + + FILE* fin; + openInOut_orDie(fname, &fin, &state.fout); + + if (ZSTD_compressBound(frameSize) > 0xFFFFFFFFU) { fprintf(stderr, "Frame size too large \n"); exit(10); } + unsigned dstSize = ZSTD_compressBound(frameSize); + + for (size_t id = 0; 1; id++) { + struct job* job = malloc_orDie(sizeof(struct job)); + job->id = id; + job->next = NULL; + job->state = &state; + job->src = malloc_orDie(frameSize); + job->dst = malloc_orDie(dstSize); + job->srcSize = fread_orDie(job->src, frameSize, fin); + job->dstSize = dstSize; + POOL_add(pool, compressFrame, job); + if (feof(fin)) + break; + } + + POOL_joinJobs(pool); + if (state.pending) { + fprintf(stderr, "Unexpected leftover output blocks!\n"); + exit(13); + } + + { unsigned char seekTableBuff[1024]; + ZSTD_outBuffer out = {seekTableBuff, 1024, 0}; + while (ZSTD_seekable_writeSeekTable(state.frameLog, &out) != 0) { + fwrite_orDie(seekTableBuff, out.pos, state.fout); + out.pos = 0; + } + fwrite_orDie(seekTableBuff, out.pos, state.fout); + } + + ZSTD_seekable_freeFrameLog(state.frameLog); + fclose_orDie(state.fout); + fclose_orDie(fin); +} + int main(int argc, const char** argv) { const char* const exeName = argv[0]; if (argc!=4) { @@ -206,8 +246,7 @@ int main(int argc, const char** argv) { unsigned const frameSize = (unsigned)atoi(argv[2]); int const nbThreads = atoi(argv[3]); - const char* const outFileName = createOutFilename_orDie(inFileName); - compressFile_orDie(inFileName, outFileName, 5, frameSize, nbThreads); + compressFile_orDie(inFileName, 5, frameSize, nbThreads); } return 0; From 6fc8455a727f5e21c1ccd5402731b390e2a9076d Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Tue, 6 May 2025 23:45:04 -0400 Subject: [PATCH 782/937] seekable_format: Cleanup POOL in parallel_compression --- contrib/seekable_format/examples/parallel_compression.c | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/seekable_format/examples/parallel_compression.c b/contrib/seekable_format/examples/parallel_compression.c index d54704c11..a9f51bdbe 100644 --- a/contrib/seekable_format/examples/parallel_compression.c +++ b/contrib/seekable_format/examples/parallel_compression.c @@ -214,6 +214,7 @@ static void compressFile_orDie(const char* fname, int cLevel, unsigned frameSize } POOL_joinJobs(pool); + POOL_free(pool); if (state.pending) { fprintf(stderr, "Unexpected leftover output blocks!\n"); exit(13); From 01c973de8d85392156f4fa1400e0b3c52b50b23e Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Wed, 7 May 2025 00:10:10 -0400 Subject: [PATCH 783/937] seekable_format: Fix race in parallel_processing There was no memory barrier between writing and reading `done`, which would allow reordering to cause races. With so little data to handle after each job completes, we might as well just join. --- contrib/seekable_format/examples/parallel_processing.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/contrib/seekable_format/examples/parallel_processing.c b/contrib/seekable_format/examples/parallel_processing.c index 928371025..2757a9aba 100644 --- a/contrib/seekable_format/examples/parallel_processing.c +++ b/contrib/seekable_format/examples/parallel_processing.c @@ -100,13 +100,11 @@ struct sum_job { const char* fname; unsigned long long sum; unsigned frameNb; - int done; }; static void sumFrame(void* opaque) { struct sum_job* job = (struct sum_job*)opaque; - job->done = 0; FILE* const fin = fopen_orDie(job->fname, "rb"); @@ -128,7 +126,6 @@ static void sumFrame(void* opaque) sum += data[i]; } job->sum = sum; - job->done = 1; fclose(fin); ZSTD_seekable_free(seekable); @@ -153,14 +150,14 @@ static void sumFile_orDie(const char* fname, int nbThreads) unsigned fnb; for (fnb = 0; fnb < numFrames; fnb++) { - jobs[fnb] = (struct sum_job){ fname, 0, fnb, 0 }; + jobs[fnb] = (struct sum_job){ fname, 0, fnb }; POOL_add(pool, sumFrame, &jobs[fnb]); } + POOL_joinJobs(pool); unsigned long long total = 0; for (fnb = 0; fnb < numFrames; fnb++) { - while (!jobs[fnb].done) SLEEP(5); /* wake up every 5 milliseconds to check */ total += jobs[fnb].sum; } From 13cb7a10ae556c24896ee2f305624d084234042a Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Wed, 7 May 2025 01:43:36 -0400 Subject: [PATCH 784/937] seekable_format: Add test for parallel_compression memory usage Use ulimit to fail the test if we use O(filesize) memory, rather than O(threads). --- contrib/seekable_format/tests/.gitignore | 1 + contrib/seekable_format/tests/Makefile | 24 ++++++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/contrib/seekable_format/tests/.gitignore b/contrib/seekable_format/tests/.gitignore index f831eaf37..b59d08b34 100644 --- a/contrib/seekable_format/tests/.gitignore +++ b/contrib/seekable_format/tests/.gitignore @@ -1 +1,2 @@ seekable_tests +data.txt diff --git a/contrib/seekable_format/tests/Makefile b/contrib/seekable_format/tests/Makefile index a81f2229f..a23c0f43c 100644 --- a/contrib/seekable_format/tests/Makefile +++ b/contrib/seekable_format/tests/Makefile @@ -24,7 +24,7 @@ SEEKABLE_OBJS = ../zstdseek_compress.c ../zstdseek_decompress.c $(ZSTDLIB) .PHONY: default clean test default: test -test: seekable_tests +test: seekable_tests parallel_compression_test ./seekable_tests $(ZSTDLIB): @@ -32,7 +32,27 @@ $(ZSTDLIB): seekable_tests : $(SEEKABLE_OBJS) +EXAMPLES_PATH = ../examples +PARALLEL_COMPRESSION = $(EXAMPLES_PATH)/parallel_compression + +DATAGEN_PATH = ../../../tests +DATAGEN = $(DATAGEN_PATH)/datagen + +$(PARALLEL_COMPRESSION): + $(MAKE) -C $(EXAMPLES_PATH) parallel_compression + +$(DATAGEN): + $(MAKE) -C $(DATAGEN_PATH) datagen + +data.txt: $(DATAGEN) + $(DATAGEN) -g100M > $@ + +parallel_compression_test: $(PARALLEL_COMPRESSION) data.txt + ulimit -Sv 102400; $(PARALLEL_COMPRESSION) data.txt 1048576 2 + +.PHONY: parallel_compression_test parallel_comp + clean: @$(RM) core *.o tmp* result* *.zst \ - seekable_tests + seekable_tests data.txt @echo Cleaning completed From 448a09ff78c2a28ad666539357d6687c759f2bb6 Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Wed, 7 May 2025 02:12:29 -0400 Subject: [PATCH 785/937] seekable_format: Fix conversion warnings in parallel_compression --- .../seekable_format/examples/parallel_compression.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contrib/seekable_format/examples/parallel_compression.c b/contrib/seekable_format/examples/parallel_compression.c index a9f51bdbe..f8a73a36b 100644 --- a/contrib/seekable_format/examples/parallel_compression.c +++ b/contrib/seekable_format/examples/parallel_compression.c @@ -110,7 +110,7 @@ static void flushFrame(struct state* state, struct job* job) fwrite_orDie(job->dst, job->dstSize, state->fout); free(job->dst); - size_t ret = ZSTD_seekable_logFrame(state->frameLog, job->dstSize, job->srcSize, job->checksum); + size_t ret = ZSTD_seekable_logFrame(state->frameLog, (unsigned)job->dstSize, (unsigned)job->srcSize, job->checksum); if (ZSTD_isError(ret)) { fprintf(stderr, "ZSTD_seekable_logFrame() error : %s \n", ZSTD_getErrorName(ret)); exit(12); @@ -141,7 +141,7 @@ static void compressFrame(void* opaque) { struct job* job = opaque; - job->checksum = XXH64(job->src, job->srcSize, 0); + job->checksum = (unsigned)XXH64(job->src, job->srcSize, 0); size_t ret = ZSTD_compress(job->dst, job->dstSize, job->src, job->srcSize, job->state->compressionLevel); if (ZSTD_isError(ret)) { @@ -179,7 +179,7 @@ static void openInOut_orDie(const char* fname, FILE** fin, FILE** fout) { } } -static void compressFile_orDie(const char* fname, int cLevel, unsigned frameSize, int nbThreads) +static void compressFile_orDie(const char* fname, int cLevel, unsigned frameSize, size_t nbThreads) { struct state state = { .nextID = 0, @@ -197,7 +197,7 @@ static void compressFile_orDie(const char* fname, int cLevel, unsigned frameSize openInOut_orDie(fname, &fin, &state.fout); if (ZSTD_compressBound(frameSize) > 0xFFFFFFFFU) { fprintf(stderr, "Frame size too large \n"); exit(10); } - unsigned dstSize = ZSTD_compressBound(frameSize); + size_t dstSize = ZSTD_compressBound(frameSize); for (size_t id = 0; 1; id++) { struct job* job = malloc_orDie(sizeof(struct job)); @@ -245,7 +245,7 @@ int main(int argc, const char** argv) { { const char* const inFileName = argv[1]; unsigned const frameSize = (unsigned)atoi(argv[2]); - int const nbThreads = atoi(argv[3]); + size_t const nbThreads = (size_t)atoi(argv[3]); compressFile_orDie(inFileName, 5, frameSize, nbThreads); } From f9938c217da17ec3e9dcd2a2d99c5cf39536aeb9 Mon Sep 17 00:00:00 2001 From: Dave Vasilevsky Date: Wed, 7 May 2025 03:03:29 -0400 Subject: [PATCH 786/937] lz4: Remove ancient test helpers Building lz4 as root was causing `make clean` to fail with permission errors. We used to have to install lz4 from source back in Ubuntu 14.04, but nowadays the installed lz4 is fine. Get rid of ancient helpers and cruft! --- .github/workflows/dev-short-tests.yml | 1 - Makefile | 6 +----- tests/Makefile | 6 +++--- 3 files changed, 4 insertions(+), 9 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index da35ec675..227b01a0c 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -170,7 +170,6 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: LZ4, thread pool, and libs build testslib wrapper test run: | - make lz4install make -C tests test-lz4 make check < /dev/null | tee # mess with lz4 console detection make clean diff --git a/Makefile b/Makefile index e8e6bcffe..c9a640cba 100644 --- a/Makefile +++ b/Makefile @@ -351,7 +351,7 @@ apt-add-repo: sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test sudo apt-get update -y -qq -.PHONY: ppcinstall arminstall valgrindinstall libc6install gcc6install gcc7install gcc8install gpp6install clang38install lz4install +.PHONY: ppcinstall arminstall valgrindinstall libc6install gcc6install gcc7install gcc8install gpp6install clang38install ppcinstall: APT_PACKAGES="qemu-system-ppc qemu-user-static gcc-powerpc-linux-gnu" $(MAKE) apt-install @@ -379,10 +379,6 @@ gpp6install: apt-add-repo clang38install: APT_PACKAGES="clang-3.8" $(MAKE) apt-install -# Ubuntu 14.04 ships a too-old lz4 -lz4install: - [ -e lz4 ] || git clone https://github.com/lz4/lz4 && sudo $(MAKE) -C lz4 install - endif diff --git a/tests/Makefile b/tests/Makefile index b96986cae..643f8cd61 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -447,9 +447,9 @@ test-decodecorpus-cli: decodecorpus test-pool: poolTests $(QEMU_SYS) ./poolTests -test-lz4: ZSTD = LD_LIBRARY_PATH=/usr/local/lib $(PRGDIR)/zstd -test-lz4: ZSTD_LZ4 = LD_LIBRARY_PATH=/usr/local/lib ./lz4 -test-lz4: ZSTD_UNLZ4 = LD_LIBRARY_PATH=/usr/local/lib ./unlz4 +test-lz4: ZSTD = $(PRGDIR)/zstd +test-lz4: ZSTD_LZ4 = ./lz4 +test-lz4: ZSTD_UNLZ4 = ./unlz4 test-lz4: zstd decodecorpus datagen [ -f lz4 ] || ln -s $(PRGDIR)/zstd lz4 [ -f unlz4 ] || ln -s $(PRGDIR)/zstd unlz4 From 4618b255eae0a2a7e36cbdb50276d734f039bd52 Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Sun, 25 May 2025 15:21:23 -0400 Subject: [PATCH 787/937] Fix memory leak in function benchMem `speedPerRound` is allocated at the start of benchMem to collect per-round speeds, but is never freed, causing a leak on each invocation. --- contrib/largeNbDicts/largeNbDicts.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contrib/largeNbDicts/largeNbDicts.c b/contrib/largeNbDicts/largeNbDicts.c index 6502f1227..6b6cc34ca 100644 --- a/contrib/largeNbDicts/largeNbDicts.c +++ b/contrib/largeNbDicts/largeNbDicts.c @@ -739,6 +739,8 @@ static int benchMem(slice_collection_t dstBlocks, slice_collection_t srcBlocks, /* BMK_benchTimedFn may not run exactly nbRounds iterations */ double speedAggregated = aggregateData(speedPerRound, roundNb + 1, metricAggregatePref); + free(speedPerRound); + if (metricAggregatePref == fastest) DISPLAY("Fastest Speed : %.1f MB/s \n", speedAggregated); else From 4bd5654e72e8b0f03218d7d56f8b5329ba6445b3 Mon Sep 17 00:00:00 2001 From: shixuantong Date: Fri, 9 May 2025 22:47:08 +0800 Subject: [PATCH 788/937] update `--rm` cmd help info Starting from cee6bec9fa6aa249f2df9f84165b682eb793eab, --rm is ignored when the output is `stdout`. --- programs/README.md | 2 +- programs/zstdcli.c | 2 +- tests/cli-tests/basic/help.sh.stdout.glob | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/programs/README.md b/programs/README.md index 43ef07a45..2c2e94dc6 100644 --- a/programs/README.md +++ b/programs/README.md @@ -153,7 +153,7 @@ Usage: zstd [OPTIONS...] [INPUT... | -] [-o OUTPUT] Options: -o OUTPUT Write output to a single file, OUTPUT. -k, --keep Preserve INPUT file(s). [Default] - --rm Remove INPUT file(s) after successful (de)compression. + --rm Remove INPUT file(s) after successful (de)compression to file. -# Desired compression level, where `#` is a number between 1 and 19; lower numbers provide faster compression, higher numbers yield diff --git a/programs/zstdcli.c b/programs/zstdcli.c index fa7ea37b3..124ea47aa 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -147,7 +147,7 @@ static void usage(FILE* f, const char* programName) DISPLAY_F(f, "Options:\n"); DISPLAY_F(f, " -o OUTPUT Write output to a single file, OUTPUT.\n"); DISPLAY_F(f, " -k, --keep Preserve INPUT file(s). [Default] \n"); - DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression.\n"); + DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression to file.\n"); #ifdef ZSTD_GZCOMPRESS if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */ DISPLAY_F(f, " -n, --no-name Do not store original filename when compressing.\n\n"); diff --git a/tests/cli-tests/basic/help.sh.stdout.glob b/tests/cli-tests/basic/help.sh.stdout.glob index 21bc28c3f..66c6906cf 100644 --- a/tests/cli-tests/basic/help.sh.stdout.glob +++ b/tests/cli-tests/basic/help.sh.stdout.glob @@ -6,7 +6,7 @@ Usage: zstd *OPTIONS...* *INPUT... | -* *-o OUTPUT* Options: -o OUTPUT Write output to a single file, OUTPUT. -k, --keep Preserve INPUT file(s). *Default* - --rm Remove INPUT file(s) after successful (de)compression. + --rm Remove INPUT file(s) after successful (de)compression to file. -# Desired compression level, where `#` is a number between 1 and 19; lower numbers provide faster compression, higher numbers yield From d95123f2e68fc5a0feb222d03cacba5a044f03b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=AD=90=E5=BB=BA?= Date: Fri, 16 May 2025 14:57:32 +0800 Subject: [PATCH 789/937] Improve speed of ZSTD_compressSequencesAndLiterals() using RVV --- lib/common/compiler.h | 6 ++ lib/compress/zstd_compress.c | 151 +++++++++++++++++++++++++++++++++++ 2 files changed, 157 insertions(+) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 944774a7a..cafb35b71 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -218,6 +218,9 @@ # if defined(__ARM_NEON) || defined(_M_ARM64) # define ZSTD_ARCH_ARM_NEON # endif +# if defined(__riscv) && defined(__riscv_vector) +# define ZSTD_ARCH_RISCV_RVV +# endif # # if defined(ZSTD_ARCH_X86_AVX2) # include @@ -227,6 +230,9 @@ # elif defined(ZSTD_ARCH_ARM_NEON) # include # endif +# if defined(ZSTD_ARCH_RISCV_RVV) +# include +# endif #endif /* C-language Attributes are added in C23. */ diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index c8f6b2865..9b7aaf9f4 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7284,6 +7284,93 @@ static size_t convertSequences_noRepcodes( return longLen; } +#elif defined ZSTD_ARCH_RISCV_RVV +#include +/* + * Convert `vl` sequences per iteration, using AVX2 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. + */ +static size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) { + size_t longLen = 0; + + /* 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); + size_t vl = 0; + 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 int32_t*)&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( + (uint32_t*)&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 */ @@ -7451,6 +7538,70 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) } } +#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 i = 0; + int found_terminator = 0; + size_t vl_max = __riscv_vsetvlmax_e32m1(); + vuint32m1_t v_lit_sum = __riscv_vmv_v_x_u32m1(0, vl_max); + vuint32m1_t v_match_sum = __riscv_vmv_v_x_u32m1(0, vl_max); + + for (; i < nbSeqs; ) { + size_t vl = __riscv_vsetvl_e32m2(nbSeqs - i); + + ptrdiff_t stride = sizeof(ZSTD_Sequence); // 16 + vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4( + (const int32_t*)&seqs[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); + + // Check if any element has a matchLength of 0 + vbool16_t mask = __riscv_vmseq_vx_u32m2_b16(v_match, 0, vl); + int first_zero = __riscv_vfirst_m_b16(mask, vl); + + if (first_zero >= 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; + } + } + 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 = i; + bs.blockSize = litSize + totalMatchSize; + bs.litSize = litSize; + return bs; + } +} + #else BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) From dd4cee9190cce231f56bc4f318e71f6b69270993 Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Tue, 3 Jun 2025 15:28:11 -0400 Subject: [PATCH 790/937] Release resources before returning In main, resources were freed on the success path but not in the error path. This change ensures all allocated resources are released before returning. --- contrib/externalSequenceProducer/main.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/contrib/externalSequenceProducer/main.c b/contrib/externalSequenceProducer/main.c index e67e29538..c81e9bf40 100644 --- a/contrib/externalSequenceProducer/main.c +++ b/contrib/externalSequenceProducer/main.c @@ -27,6 +27,7 @@ do { \ } while (0) \ int main(int argc, char *argv[]) { + int retn = 0; if (argc != 2) { printf("Usage: externalSequenceProducer \n"); return 1; @@ -96,12 +97,12 @@ int main(int argc, char *argv[]) { break; } } - return 1; + retn = 1; } ZSTD_freeCCtx(zc); free(src); free(dst); free(val); - return 0; + return retn; } From a81ffe11d439d6336bbe9aca938264773beaf43d Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Wed, 4 Jun 2025 18:08:11 -0400 Subject: [PATCH 791/937] Release resources in error paths via cleanup Replace direct returns in error-handling branches with a unified cleanup block that frees allocated resources before returning, improving code quality and robustness. --- tests/bigdict.c | 31 +++++++++++++++---------------- tests/largeDictionary.c | 32 +++++++++++++++++--------------- tests/regression/method.c | 6 +++--- 3 files changed, 35 insertions(+), 34 deletions(-) diff --git a/tests/bigdict.c b/tests/bigdict.c index 748b60e79..33c4ab8ea 100644 --- a/tests/bigdict.c +++ b/tests/bigdict.c @@ -70,39 +70,38 @@ int main(int argc, const char** argv) char* buffer = (char*)malloc(bufferSize); void* out = malloc(outSize); void* roundtrip = malloc(dataSize); - int _exit_code = 0; + int _exit_code = 1; (void)argc; (void)argv; if (!buffer || !out || !roundtrip || !cctx || !dctx) { fprintf(stderr, "Allocation failure\n"); - _exit_code = 1; goto cleanup; } if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) - return 1; + goto cleanup; RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); @@ -112,16 +111,16 @@ int main(int argc, const char** argv) for (i = 0; i < 10; ++i) { fprintf(stderr, "Compressing 1 GB\n"); if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) - return 1; + goto cleanup; } } fprintf(stderr, "Compressing 1 GB\n"); if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) - return 1; + goto cleanup; fprintf(stderr, "Success!\n"); - goto cleanup; + _exit_code = 0; cleanup: free(roundtrip); diff --git a/tests/largeDictionary.c b/tests/largeDictionary.c index ff2bb2d70..998fd9fa8 100644 --- a/tests/largeDictionary.c +++ b/tests/largeDictionary.c @@ -70,37 +70,38 @@ int main(int argc, const char** argv) char* buffer = (char*)malloc(bufferSize); void* out = malloc(outSize); void* roundtrip = malloc(dataSize); + int _exit_code = 1; (void)argc; (void)argv; if (!buffer || !out || !roundtrip || !cctx || !dctx) { fprintf(stderr, "Allocation failure\n"); - return 1; + goto cleanup; } if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) - return 1; + goto cleanup; if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) - return 1; + goto cleanup; RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); @@ -110,19 +111,20 @@ int main(int argc, const char** argv) for (i = 0; i < 10; ++i) { fprintf(stderr, "Compressing 1 GB\n"); if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) - return 1; + goto cleanup; } } fprintf(stderr, "Compressing 1 GB\n"); if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) - return 1; + goto cleanup; fprintf(stderr, "Success!\n"); +cleanup: free(roundtrip); free(out); free(buffer); ZSTD_freeDCtx(dctx); ZSTD_freeCCtx(cctx); - return 0; + return _exit_code; } diff --git a/tests/regression/method.c b/tests/regression/method.c index f84a15ef3..ac6fdd712 100644 --- a/tests/regression/method.c +++ b/tests/regression/method.c @@ -159,15 +159,15 @@ static result_t compress_cctx_compress( return result_error(result_error_skip); int const level = config_get_level(config); - + result_t result; ZSTD_CCtx* cctx = ZSTD_createCCtx(); ZSTD_DCtx* dctx = ZSTD_createDCtx(); if (cctx == NULL || dctx == NULL) { fprintf(stderr, "context creation failed\n"); - return result_error(result_error_system_error); + result = result_error(result_error_system_error); + goto out; } - result_t result; result_data_t data = {.total_size = 0}; for (size_t i = 0; i < state->inputs.size; ++i) { data_buffer_t const input = state->inputs.buffers[i]; From 4be08ba12283ca60b3704002c3c761047eec879c Mon Sep 17 00:00:00 2001 From: Dominik Loidolt Date: Thu, 5 Jun 2025 15:36:29 +0200 Subject: [PATCH 792/937] fuzz: Fix FUZZ_malloc_rand() to return non-NULL for zero-size allocations The FUZZ_malloc_rand() function was incorrectly always returning NULL for zero-size allocations. The random offset generated by FUZZ_dataProducer_int32Range() was not being added to the pointer variable, causing the function to always return (void *)0. --- tests/fuzz/fuzz_helpers.c | 5 ++--- tests/fuzz/fuzz_helpers.h | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/fuzz/fuzz_helpers.c b/tests/fuzz/fuzz_helpers.c index f47ff2eb4..5c530f0e9 100644 --- a/tests/fuzz/fuzz_helpers.c +++ b/tests/fuzz/fuzz_helpers.c @@ -31,12 +31,11 @@ void* FUZZ_malloc_rand(size_t size, FUZZ_dataProducer_t *producer) return mem; } else { uintptr_t ptr = 0; - /* Add +- 1M 50% of the time */ + /* Return junk pointer 50% of the time */ if (FUZZ_dataProducer_uint32Range(producer, 0, 1)) - FUZZ_dataProducer_int32Range(producer, -1000000, 1000000); + ptr += FUZZ_dataProducer_int32Range(producer, -1000000, 1000000); return (void*)ptr; } - } int FUZZ_memcmp(void const* lhs, void const* rhs, size_t size) diff --git a/tests/fuzz/fuzz_helpers.h b/tests/fuzz/fuzz_helpers.h index f21ec4751..c5d75b402 100644 --- a/tests/fuzz/fuzz_helpers.h +++ b/tests/fuzz/fuzz_helpers.h @@ -66,6 +66,7 @@ void* FUZZ_malloc(size_t size); /** * malloc except returns random pointer for zero sized data and FUZZ_ASSERT * that malloc doesn't fail. + * WARNING: Only free the returned pointer if size > 0! */ void* FUZZ_malloc_rand(size_t size, FUZZ_dataProducer_t *producer); From 80cac404c7507e93591ac881e59f96327e8ee88e Mon Sep 17 00:00:00 2001 From: Michael Kolupaev Date: Thu, 17 Apr 2025 02:10:14 +0000 Subject: [PATCH 793/937] Add unwind information in huf_decompress_amd64.S --- lib/decompress/huf_decompress_amd64.S | 154 ++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/lib/decompress/huf_decompress_amd64.S b/lib/decompress/huf_decompress_amd64.S index 656aada95..66e12d11b 100644 --- a/lib/decompress/huf_decompress_amd64.S +++ b/lib/decompress/huf_decompress_amd64.S @@ -117,22 +117,55 @@ ZSTD_HIDE_ASM_FUNCTION(_HUF_decompress4X1_usingDTable_internal_fast_asm_loop) _HUF_decompress4X1_usingDTable_internal_fast_asm_loop: HUF_decompress4X1_usingDTable_internal_fast_asm_loop: ZSTD_CET_ENDBRANCH + .cfi_startproc + .cfi_def_cfa_offset 8 + .cfi_offset %rip, -8 /* Save all registers - even if they are callee saved for simplicity. */ push %rax + .cfi_def_cfa_offset 16 + .cfi_offset rax, -16 push %rbx + .cfi_def_cfa_offset 24 + .cfi_offset rbx, -24 push %rcx + .cfi_def_cfa_offset 32 + .cfi_offset rcx, -32 push %rdx + .cfi_def_cfa_offset 40 + .cfi_offset rdx, -40 push %rbp + .cfi_def_cfa_offset 48 + .cfi_offset rbp, -48 push %rsi + .cfi_def_cfa_offset 56 + .cfi_offset rsi, -56 push %rdi + .cfi_def_cfa_offset 64 + .cfi_offset rdi, -64 push %r8 + .cfi_def_cfa_offset 72 + .cfi_offset r8, -72 push %r9 + .cfi_def_cfa_offset 80 + .cfi_offset r9, -80 push %r10 + .cfi_def_cfa_offset 88 + .cfi_offset r10, -88 push %r11 + .cfi_def_cfa_offset 96 + .cfi_offset r11, -96 push %r12 + .cfi_def_cfa_offset 104 + .cfi_offset r12, -104 push %r13 + .cfi_def_cfa_offset 112 + .cfi_offset r13, -112 push %r14 + .cfi_def_cfa_offset 120 + .cfi_offset r14, -120 push %r15 + .cfi_def_cfa_offset 128 + .cfi_offset r15, -128 /* Read HUF_DecompressAsmArgs* args from %rax */ #if defined(_WIN32) @@ -154,11 +187,16 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: movq 88(%rax), %bits3 movq 96(%rax), %dtable push %rax /* argument */ + .cfi_def_cfa_offset 136 push 104(%rax) /* ilowest */ + .cfi_def_cfa_offset 144 push 112(%rax) /* oend */ + .cfi_def_cfa_offset 152 push %olimit /* olimit space */ + .cfi_def_cfa_offset 160 subq $24, %rsp + .cfi_def_cfa_offset 184 .L_4X1_compute_olimit: /* Computes how many iterations we can do safely @@ -334,12 +372,17 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: #undef RELOAD_BITS .L_4X1_exit: addq $24, %rsp + .cfi_def_cfa_offset 160 /* Restore stack (oend & olimit) */ pop %rax /* olimit */ + .cfi_def_cfa_offset 152 pop %rax /* oend */ + .cfi_def_cfa_offset 144 pop %rax /* ilowest */ + .cfi_def_cfa_offset 136 pop %rax /* arg */ + .cfi_def_cfa_offset 128 /* Save ip / op / bits */ movq %ip0, 0(%rax) @@ -357,41 +400,105 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: /* Restore registers */ pop %r15 + .cfi_restore r15 + .cfi_def_cfa_offset 120 pop %r14 + .cfi_restore r14 + .cfi_def_cfa_offset 112 pop %r13 + .cfi_restore r13 + .cfi_def_cfa_offset 104 pop %r12 + .cfi_restore r12 + .cfi_def_cfa_offset 96 pop %r11 + .cfi_restore r11 + .cfi_def_cfa_offset 88 pop %r10 + .cfi_restore r10 + .cfi_def_cfa_offset 80 pop %r9 + .cfi_restore r9 + .cfi_def_cfa_offset 72 pop %r8 + .cfi_restore r8 + .cfi_def_cfa_offset 64 pop %rdi + .cfi_restore rdi + .cfi_def_cfa_offset 56 pop %rsi + .cfi_restore rsi + .cfi_def_cfa_offset 48 pop %rbp + .cfi_restore rbp + .cfi_def_cfa_offset 40 pop %rdx + .cfi_restore rdx + .cfi_def_cfa_offset 32 pop %rcx + .cfi_restore rcx + .cfi_def_cfa_offset 24 pop %rbx + .cfi_restore rbx + .cfi_def_cfa_offset 16 pop %rax + .cfi_restore rax + .cfi_def_cfa_offset 8 ret + .cfi_endproc _HUF_decompress4X2_usingDTable_internal_fast_asm_loop: HUF_decompress4X2_usingDTable_internal_fast_asm_loop: ZSTD_CET_ENDBRANCH + .cfi_startproc + .cfi_def_cfa_offset 8 + .cfi_offset %rip, -8 /* Save all registers - even if they are callee saved for simplicity. */ push %rax + .cfi_def_cfa_offset 16 + .cfi_offset rax, -16 push %rbx + .cfi_def_cfa_offset 24 + .cfi_offset rbx, -24 push %rcx + .cfi_def_cfa_offset 32 + .cfi_offset rcx, -32 push %rdx + .cfi_def_cfa_offset 40 + .cfi_offset rdx, -40 push %rbp + .cfi_def_cfa_offset 48 + .cfi_offset rbp, -48 push %rsi + .cfi_def_cfa_offset 56 + .cfi_offset rsi, -56 push %rdi + .cfi_def_cfa_offset 64 + .cfi_offset rdi, -64 push %r8 + .cfi_def_cfa_offset 72 + .cfi_offset r8, -72 push %r9 + .cfi_def_cfa_offset 80 + .cfi_offset r9, -80 push %r10 + .cfi_def_cfa_offset 88 + .cfi_offset r10, -88 push %r11 + .cfi_def_cfa_offset 96 + .cfi_offset r11, -96 push %r12 + .cfi_def_cfa_offset 104 + .cfi_offset r12, -104 push %r13 + .cfi_def_cfa_offset 112 + .cfi_offset r13, -112 push %r14 + .cfi_def_cfa_offset 120 + .cfi_offset r14, -120 push %r15 + .cfi_def_cfa_offset 128 + .cfi_offset r15, -128 /* Read HUF_DecompressAsmArgs* args from %rax */ #if defined(_WIN32) @@ -413,23 +520,31 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: movq 88(%rax), %bits3 movq 96(%rax), %dtable push %rax /* argument */ + .cfi_def_cfa_offset 136 push %rax /* olimit */ + .cfi_def_cfa_offset 144 push 104(%rax) /* ilowest */ + .cfi_def_cfa_offset 152 movq 112(%rax), %rax push %rax /* oend3 */ + .cfi_def_cfa_offset 160 movq %op3, %rax push %rax /* oend2 */ + .cfi_def_cfa_offset 168 movq %op2, %rax push %rax /* oend1 */ + .cfi_def_cfa_offset 176 movq %op1, %rax push %rax /* oend0 */ + .cfi_def_cfa_offset 184 /* Scratch space */ subq $8, %rsp + .cfi_def_cfa_offset 192 .L_4X2_compute_olimit: /* Computes how many iterations we can do safely @@ -558,14 +673,22 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: #undef RELOAD_BITS .L_4X2_exit: addq $8, %rsp + .cfi_def_cfa_offset 184 /* Restore stack (oend & olimit) */ pop %rax /* oend0 */ + .cfi_def_cfa_offset 176 pop %rax /* oend1 */ + .cfi_def_cfa_offset 168 pop %rax /* oend2 */ + .cfi_def_cfa_offset 160 pop %rax /* oend3 */ + .cfi_def_cfa_offset 152 pop %rax /* ilowest */ + .cfi_def_cfa_offset 144 pop %rax /* olimit */ + .cfi_def_cfa_offset 136 pop %rax /* arg */ + .cfi_def_cfa_offset 128 /* Save ip / op / bits */ movq %ip0, 0(%rax) @@ -583,20 +706,51 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: /* Restore registers */ pop %r15 + .cfi_restore r15 + .cfi_def_cfa_offset 120 pop %r14 + .cfi_restore r14 + .cfi_def_cfa_offset 112 pop %r13 + .cfi_restore r13 + .cfi_def_cfa_offset 104 pop %r12 + .cfi_restore r12 + .cfi_def_cfa_offset 96 pop %r11 + .cfi_restore r11 + .cfi_def_cfa_offset 88 pop %r10 + .cfi_restore r10 + .cfi_def_cfa_offset 80 pop %r9 + .cfi_restore r9 + .cfi_def_cfa_offset 72 pop %r8 + .cfi_restore r8 + .cfi_def_cfa_offset 64 pop %rdi + .cfi_restore rdi + .cfi_def_cfa_offset 56 pop %rsi + .cfi_restore rsi + .cfi_def_cfa_offset 48 pop %rbp + .cfi_restore rbp + .cfi_def_cfa_offset 40 pop %rdx + .cfi_restore rdx + .cfi_def_cfa_offset 32 pop %rcx + .cfi_restore rcx + .cfi_def_cfa_offset 24 pop %rbx + .cfi_restore rbx + .cfi_def_cfa_offset 16 pop %rax + .cfi_restore rax + .cfi_def_cfa_offset 8 ret + .cfi_endproc #endif From a480191f9ec3704da1c79e4cccce726f29e4581b Mon Sep 17 00:00:00 2001 From: Michael Kolupaev Date: Thu, 17 Apr 2025 20:43:19 +0000 Subject: [PATCH 794/937] Fix Darwin build of huf_decompress_amd64.S --- lib/decompress/huf_decompress_amd64.S | 46 ++++++++++++++++----------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/lib/decompress/huf_decompress_amd64.S b/lib/decompress/huf_decompress_amd64.S index 66e12d11b..dc1f3d921 100644 --- a/lib/decompress/huf_decompress_amd64.S +++ b/lib/decompress/huf_decompress_amd64.S @@ -38,6 +38,16 @@ #endif +// There appears to be an unreconcilable syntax difference between Linux and Darwin assemblers. +// Name of a private label (i.e. not exported to symbol table) on Darwin has to start with "L", +// on Linux has to start with ".". There's no way to have a name start with both "." and "L", so +// we have to use a macro. +#if defined(__APPLE__) +#define LOCAL_LABEL(label) L_ ## label +#else +#define LOCAL_LABEL(label) .L_ ## label +#endif + #if ZSTD_ENABLE_ASM_X86_64_BMI2 /* Calling convention: @@ -198,7 +208,7 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: subq $24, %rsp .cfi_def_cfa_offset 184 -.L_4X1_compute_olimit: +LOCAL_LABEL(4X1_compute_olimit): /* Computes how many iterations we can do safely * %r15, %rax may be clobbered * rbx, rdx must be saved @@ -245,19 +255,19 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: /* If (op3 + 20 > olimit) */ movq %op3, %rax /* rax = op3 */ cmpq %rax, %olimit /* op3 == olimit */ - je .L_4X1_exit + je LOCAL_LABEL(4X1_exit) /* If (ip1 < ip0) go to exit */ cmpq %ip0, %ip1 - jb .L_4X1_exit + jb LOCAL_LABEL(4X1_exit) /* If (ip2 < ip1) go to exit */ cmpq %ip1, %ip2 - jb .L_4X1_exit + jb LOCAL_LABEL(4X1_exit) /* If (ip3 < ip2) go to exit */ cmpq %ip2, %ip3 - jb .L_4X1_exit + jb LOCAL_LABEL(4X1_exit) /* Reads top 11 bits from bits[n] * Loads dt[bits[n]] into var[n] @@ -318,7 +328,7 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: .p2align 6 -.L_4X1_loop_body: +LOCAL_LABEL(4X1_loop_body): /* Decode 5 symbols in each of the 4 streams (20 total) * Must have called GET_NEXT_DELT for each stream */ @@ -356,7 +366,7 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: /* If op3 < olimit: continue the loop */ cmp %op3, 24(%rsp) - ja .L_4X1_loop_body + ja LOCAL_LABEL(4X1_loop_body) /* Reload ip[1,2,3] from stack */ movq 0(%rsp), %ip1 @@ -364,13 +374,13 @@ HUF_decompress4X1_usingDTable_internal_fast_asm_loop: movq 16(%rsp), %ip3 /* Re-compute olimit */ - jmp .L_4X1_compute_olimit + jmp LOCAL_LABEL(4X1_compute_olimit) #undef GET_NEXT_DELT #undef DECODE_FROM_DELT #undef DECODE #undef RELOAD_BITS -.L_4X1_exit: +LOCAL_LABEL(4X1_exit): addq $24, %rsp .cfi_def_cfa_offset 160 @@ -546,7 +556,7 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: subq $8, %rsp .cfi_def_cfa_offset 192 -.L_4X2_compute_olimit: +LOCAL_LABEL(4X2_compute_olimit): /* Computes how many iterations we can do safely * %r15, %rax may be clobbered * rdx must be saved @@ -610,19 +620,19 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: /* If (op3 + 10 > olimit) */ movq %op3, %rax /* rax = op3 */ cmpq %rax, %olimit /* op3 == olimit */ - je .L_4X2_exit + je LOCAL_LABEL(4X2_exit) /* If (ip1 < ip0) go to exit */ cmpq %ip0, %ip1 - jb .L_4X2_exit + jb LOCAL_LABEL(4X2_exit) /* If (ip2 < ip1) go to exit */ cmpq %ip1, %ip2 - jb .L_4X2_exit + jb LOCAL_LABEL(4X2_exit) /* If (ip3 < ip2) go to exit */ cmpq %ip2, %ip3 - jb .L_4X2_exit + jb LOCAL_LABEL(4X2_exit) #define DECODE(n, idx) \ movq %bits##n, %rax; \ @@ -649,7 +659,7 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: .p2align 6 -.L_4X2_loop_body: +LOCAL_LABEL(4X2_loop_body): /* We clobber r8, so store it on the stack */ movq %r8, 0(%rsp) @@ -666,12 +676,12 @@ HUF_decompress4X2_usingDTable_internal_fast_asm_loop: FOR_EACH_STREAM(RELOAD_BITS) cmp %op3, 48(%rsp) - ja .L_4X2_loop_body - jmp .L_4X2_compute_olimit + ja LOCAL_LABEL(4X2_loop_body) + jmp LOCAL_LABEL(4X2_compute_olimit) #undef DECODE #undef RELOAD_BITS -.L_4X2_exit: +LOCAL_LABEL(4X2_exit): addq $8, %rsp .cfi_def_cfa_offset 184 /* Restore stack (oend & olimit) */ From a2dba85fd13f6dbd5158c14d9cc147fb5b31bf27 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 8 Jun 2025 20:25:25 +0000 Subject: [PATCH 795/937] ci: separate cmake tests into dedicated workflow file - Create new .github/workflows/cmake-tests.yml with all cmake-related jobs - Move cmake-build-and-test-check, cmake-source-directory-with-spaces, and cmake-visual-2022 jobs - Remove cmake tests from dev-short-tests.yml to improve organization - Maintain same trigger conditions and test configurations - Add dedicated concurrency group for cmake tests This separation allows cmake tests to run independently and makes the CI configuration more modular and easier to maintain. --- .github/workflows/cmake-tests.yml | 74 +++++++++++++++++++++++++++ .github/workflows/dev-short-tests.yml | 62 ---------------------- 2 files changed, 74 insertions(+), 62 deletions(-) create mode 100644 .github/workflows/cmake-tests.yml diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml new file mode 100644 index 000000000..ea4181359 --- /dev/null +++ b/.github/workflows/cmake-tests.yml @@ -0,0 +1,74 @@ +name: cmake-tests +# CMake-specific build and test workflows + +concurrency: + group: cmake-${{ github.ref }} + cancel-in-progress: true + +on: + pull_request: + branches: [ dev, release, actionsTest ] + +permissions: read-all + +jobs: + cmake-build-and-test-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - name: cmake build and test + run: | + sudo apt install liblzma-dev + FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1 + + cmake-source-directory-with-spaces: + runs-on: ${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-latest + generator: "Unix Makefiles" + - os: windows-latest + generator: "NMake Makefiles" + - os: macos-latest + generator: "Unix Makefiles" + env: + SRC_DIR: "source directory with spaces" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + with: + path: "${{ env.SRC_DIR }}" + - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 + if: ${{ matrix.generator == 'NMake Makefiles' }} + - name: cmake build on a source directory with spaces + run: | + cmake -S "${{ env.SRC_DIR }}/build/cmake" -B build -DBUILD_TESTING=ON -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release --install-prefix "${{ runner.temp }}/install" + cmake --build build --config Release + cmake --install build --config Release + + cmake-visual-2022: + strategy: + matrix: + include: + - generator: "Visual Studio 17 2022" + flags: "-A x64" + - generator: "Visual Studio 17 2022" + flags: "-A Win32" + - generator: "MinGW Makefiles" + - generator: "Visual Studio 17 2022" + flags: "-T ClangCL" + - generator: "Visual Studio 17 2022" + flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" + runs-on: windows-2022 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - name: Add MSBuild to PATH + uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 + - name: Build & Test + run: | + cd build\cmake + mkdir build + cd build + cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 .. + cmake.exe --build . + ctest.exe -V -C Debug diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 227b01a0c..8e8753658 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -72,40 +72,6 @@ jobs: # candidate test (for discussion) : underlink test # LDFLAGS=-Wl,--no-undefined : will make the linker fail if dll is underlinked - cmake-build-and-test-check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - name: cmake build and test - run: | - sudo apt install liblzma-dev - FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1 - - cmake-source-directory-with-spaces: - runs-on: ${{ matrix.os }} - strategy: - matrix: - include: - - os: ubuntu-latest - generator: "Unix Makefiles" - - os: windows-latest - generator: "NMake Makefiles" - - os: macos-latest - generator: "Unix Makefiles" - env: - SRC_DIR: "source directory with spaces" - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - with: - path: "${{ env.SRC_DIR }}" - - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 - if: ${{ matrix.generator == 'NMake Makefiles' }} - - name: cmake build on a source directory with spaces - run: | - cmake -S "${{ env.SRC_DIR }}/build/cmake" -B build -DBUILD_TESTING=ON -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release --install-prefix "${{ runner.temp }}/install" - cmake --build build --config Release - cmake --install build --config Release - cpp-gnu90-c99-compatibility: runs-on: ubuntu-latest steps: @@ -339,34 +305,6 @@ jobs: run: | meson install -C builddir --destdir staging/ - cmake-visual-2022: - strategy: - matrix: - include: - - generator: "Visual Studio 17 2022" - flags: "-A x64" - - generator: "Visual Studio 17 2022" - flags: "-A Win32" - - generator: "MinGW Makefiles" - - generator: "Visual Studio 17 2022" - flags: "-T ClangCL" - - generator: "Visual Studio 17 2022" - flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" - runs-on: windows-2022 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - - name: Build & Test - working-directory: ${{env.GITHUB_WORKSPACE}} - run: | - cd build\cmake - mkdir build - cd build - cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 .. - cmake.exe --build . - ctest.exe -V -C Debug - msbuild-visual-studio: strategy: fail-fast: false # 'false' means Don't stop matrix workflows even if some matrix failed. From b92277460210a34391e7da58eac67800e0c70afa Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 8 Jun 2025 21:39:59 +0000 Subject: [PATCH 796/937] refactor CMake tests workflow for readability --- .github/workflows/cmake-tests.yml | 55 +++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index ea4181359..0f91059af 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -1,5 +1,7 @@ name: cmake-tests # CMake-specific build and test workflows +# This workflow validates zstd builds across different CMake configurations, +# platforms, and edge cases to ensure broad compatibility. concurrency: group: cmake-${{ github.ref }} @@ -11,27 +13,48 @@ on: permissions: read-all +env: + # Centralized test timeouts for consistency + QUICK_TEST_TIME: "30s" + STANDARD_TEST_TIME: "1mn" + # Common CMake flags + COMMON_CMAKE_FLAGS: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" + jobs: - cmake-build-and-test-check: + # Ubuntu-based cmake build using make wrapper + # This test uses the make-driven cmake build to ensure compatibility + # with the existing build system integration + cmake-ubuntu-basic: + name: "CMake Ubuntu Basic Build" runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - name: cmake build and test + - name: Install dependencies run: | - sudo apt install liblzma-dev - FUZZERTEST=-T1mn ZSTREAM_TESTTIME=-T1mn make cmakebuild V=1 + sudo apt install liblzma-dev # Required for compression algorithms + - name: CMake build and test via make + run: | + # Use make wrapper for cmake build with quick test timeouts + FUZZERTEST=-T${{ env.STANDARD_TEST_TIME }} ZSTREAM_TESTTIME=-T${{ env.STANDARD_TEST_TIME }} make cmakebuild V=1 - cmake-source-directory-with-spaces: + # Cross-platform cmake build with edge case: source paths containing spaces + # This test ensures cmake handles filesystem paths with spaces correctly + # across different operating systems and build generators + cmake-cross-platform-spaces: + name: "CMake Cross-Platform (Spaces in Path)" runs-on: ${{ matrix.os }} strategy: matrix: include: - os: ubuntu-latest generator: "Unix Makefiles" + name: "Linux" - os: windows-latest generator: "NMake Makefiles" + name: "Windows NMake" - os: macos-latest generator: "Unix Makefiles" + name: "macOS" env: SRC_DIR: "source directory with spaces" steps: @@ -40,35 +63,47 @@ jobs: path: "${{ env.SRC_DIR }}" - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 if: ${{ matrix.generator == 'NMake Makefiles' }} - - name: cmake build on a source directory with spaces + - name: "CMake build and install (${{ matrix.name }})" run: | + # Test Release build with installation to verify packaging cmake -S "${{ env.SRC_DIR }}/build/cmake" -B build -DBUILD_TESTING=ON -G "${{ matrix.generator }}" -DCMAKE_BUILD_TYPE=Release --install-prefix "${{ runner.temp }}/install" cmake --build build --config Release cmake --install build --config Release - cmake-visual-2022: + # Windows-specific cmake testing with Visual Studio 2022 + # Tests multiple generators and toolchains to ensure broad Windows compatibility + # including MSVC, MinGW, and Clang-CL with various architectures and optimizations + cmake-windows-comprehensive: + name: "CMake Windows VS2022 (${{ matrix.name }})" + runs-on: windows-2022 strategy: matrix: include: - generator: "Visual Studio 17 2022" flags: "-A x64" + name: "MSVC x64" - generator: "Visual Studio 17 2022" flags: "-A Win32" + name: "MSVC Win32" - generator: "MinGW Makefiles" + flags: "" + name: "MinGW" - generator: "Visual Studio 17 2022" flags: "-T ClangCL" + name: "Clang-CL" - generator: "Visual Studio 17 2022" flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" - runs-on: windows-2022 + name: "Clang-CL AVX2" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - - name: Build & Test + - name: "Build & Test (${{ matrix.name }})" run: | + # Configure and build in Debug mode with comprehensive testing cd build\cmake mkdir build cd build - cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug -DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS:BOOL=ON -DZSTD_ZSTREAM_FLAGS=-T30s -DZSTD_FUZZER_FLAGS=-T30s -DZSTD_FULLBENCH_FLAGS=-i0 .. + cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug ${{ env.COMMON_CMAKE_FLAGS }} -DZSTD_ZSTREAM_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FUZZER_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FULLBENCH_FLAGS=-i0 .. cmake.exe --build . ctest.exe -V -C Debug From a168ae723286f54321abb69dcb10ad07f074802b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 8 Jun 2025 22:19:57 +0000 Subject: [PATCH 797/937] added windows arm64 runner to cmake tests --- .github/workflows/cmake-tests.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 0f91059af..5d9dac00d 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -72,28 +72,37 @@ jobs: # Windows-specific cmake testing with Visual Studio 2022 # Tests multiple generators and toolchains to ensure broad Windows compatibility - # including MSVC, MinGW, and Clang-CL with various architectures and optimizations + # including MSVC (x64, Win32, ARM64), MinGW, and Clang-CL with various architectures and optimizations cmake-windows-comprehensive: name: "CMake Windows VS2022 (${{ matrix.name }})" - runs-on: windows-2022 + runs-on: ${{ matrix.runner }} strategy: matrix: include: - generator: "Visual Studio 17 2022" flags: "-A x64" name: "MSVC x64" + runner: "windows-2022" - generator: "Visual Studio 17 2022" flags: "-A Win32" name: "MSVC Win32" + runner: "windows-2022" + - generator: "Visual Studio 17 2022" + flags: "-A ARM64" + name: "MSVC ARM64" + runner: "windows-2022-arm64" - generator: "MinGW Makefiles" flags: "" name: "MinGW" + runner: "windows-2022" - generator: "Visual Studio 17 2022" flags: "-T ClangCL" name: "Clang-CL" + runner: "windows-2022" - generator: "Visual Studio 17 2022" flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" name: "Clang-CL AVX2" + runner: "windows-2022" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Add MSBuild to PATH From c826c572cf246e1c08d6927a249e9e11bcb11679 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 8 Jun 2025 22:40:15 +0000 Subject: [PATCH 798/937] added macos arm64 tests and comment out windows arm64 tests due to unacceptably long queue time --- .github/workflows/cmake-tests.yml | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 5d9dac00d..0dae6c763 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -87,10 +87,10 @@ jobs: flags: "-A Win32" name: "MSVC Win32" runner: "windows-2022" - - generator: "Visual Studio 17 2022" - flags: "-A ARM64" - name: "MSVC ARM64" - runner: "windows-2022-arm64" + # - generator: "Visual Studio 17 2022" + # flags: "-A ARM64" + # name: "MSVC ARM64" + # runner: "windows-2022-arm64" # Disabled due to very long queue times - generator: "MinGW Makefiles" flags: "" name: "MinGW" @@ -116,3 +116,21 @@ jobs: cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug ${{ env.COMMON_CMAKE_FLAGS }} -DZSTD_ZSTREAM_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FUZZER_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FULLBENCH_FLAGS=-i0 .. cmake.exe --build . ctest.exe -V -C Debug + + # macOS ARM64 (Apple Silicon) specific cmake testing + # Validates zstd builds and runs correctly on Apple Silicon architecture + # Uses native ARM64 hardware for optimal performance and compatibility testing + cmake-macos-arm64: + name: "CMake macOS ARM64 (Apple Silicon)" + runs-on: macos-14 # ARM64 runner + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - name: "CMake build and test (ARM64)" + run: | + # Configure and build with ARM64-specific optimizations + cd build/cmake + mkdir build + cd build + cmake -DCMAKE_BUILD_TYPE=Release ${{ env.COMMON_CMAKE_FLAGS }} -DZSTD_ZSTREAM_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FUZZER_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FULLBENCH_FLAGS=-i1 .. + make -j$(sysctl -n hw.ncpu) + ctest -V From 75abb8bc1c4cf57c994204a7e01552c2fad94a90 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 8 Jun 2025 23:51:55 +0000 Subject: [PATCH 799/937] add cmake build test with ZSTD_BUILD_TESTS disabled should reproduce #4405 and fail --- .github/workflows/cmake-tests.yml | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 0dae6c763..f9212e254 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -83,10 +83,18 @@ jobs: flags: "-A x64" name: "MSVC x64" runner: "windows-2022" + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" - generator: "Visual Studio 17 2022" flags: "-A Win32" name: "MSVC Win32" runner: "windows-2022" + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" + - generator: "Visual Studio 17 2022" + flags: "-A x64" + name: "MSVC x64 (No ZSTD_BUILD_TESTS)" + runner: "windows-2022" + # Intentionally omit ZSTD_BUILD_TESTS to reproduce the CXX language configuration bug + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON" # - generator: "Visual Studio 17 2022" # flags: "-A ARM64" # name: "MSVC ARM64" @@ -95,26 +103,34 @@ jobs: flags: "" name: "MinGW" runner: "windows-2022" + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" - generator: "Visual Studio 17 2022" flags: "-T ClangCL" name: "Clang-CL" runner: "windows-2022" + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" - generator: "Visual Studio 17 2022" flags: "-T ClangCL -A x64 -DCMAKE_C_FLAGS=/arch:AVX2" name: "Clang-CL AVX2" runner: "windows-2022" + cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - - name: "Build & Test (${{ matrix.name }})" + - name: "Configure CMake (${{ matrix.name }})" run: | - # Configure and build in Debug mode with comprehensive testing cd build\cmake mkdir build cd build - cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug ${{ env.COMMON_CMAKE_FLAGS }} -DZSTD_ZSTREAM_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FUZZER_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FULLBENCH_FLAGS=-i0 .. + cmake.exe -G "${{matrix.generator}}" ${{matrix.flags}} -DCMAKE_BUILD_TYPE=Debug ${{ matrix.cmake_extra_flags }} -DZSTD_ZSTREAM_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FUZZER_FLAGS=-T${{ env.QUICK_TEST_TIME }} -DZSTD_FULLBENCH_FLAGS=-i0 .. + - name: "Build (${{ matrix.name }})" + run: | + cd build\cmake\build cmake.exe --build . + - name: "Test (${{ matrix.name }})" + run: | + cd build\cmake\build ctest.exe -V -C Debug # macOS ARM64 (Apple Silicon) specific cmake testing From 49fe2ec79332b6706bdcac3ddca6c15a84da85b1 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 9 Jun 2025 03:47:33 +0000 Subject: [PATCH 800/937] refactor: modularize CMakeLists.txt for better maintainability - Split monolithic 235-line CMakeLists.txt into focused modules - Main file reduced to 78 lines with clear section organization - Created 5 specialized modules: * ZstdVersion.cmake - CMake policies and version management * ZstdOptions.cmake - Build options and platform configuration * ZstdDependencies.cmake - External dependency management * ZstdBuild.cmake - Build targets and validation * ZstdPackage.cmake - Package configuration generation Benefits: - Improved readability and maintainability - Better separation of concerns - Easier debugging and modification - Preserved 100% backward compatibility - All existing build options and targets unchanged The refactored build system passes all tests and maintains identical functionality while being much easier to understand and maintain. --- build/cmake/CMakeLists.txt | 245 ++++-------------- build/cmake/CMakeModules/ZstdBuild.cmake | 42 +++ .../cmake/CMakeModules/ZstdDependencies.cmake | 30 +++ build/cmake/CMakeModules/ZstdOptions.cmake | 68 +++++ build/cmake/CMakeModules/ZstdPackage.cmake | 42 +++ build/cmake/CMakeModules/ZstdVersion.cmake | 31 +++ 6 files changed, 259 insertions(+), 199 deletions(-) create mode 100644 build/cmake/CMakeModules/ZstdBuild.cmake create mode 100644 build/cmake/CMakeModules/ZstdDependencies.cmake create mode 100644 build/cmake/CMakeModules/ZstdOptions.cmake create mode 100644 build/cmake/CMakeModules/ZstdPackage.cmake create mode 100644 build/cmake/CMakeModules/ZstdVersion.cmake diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index f08905345..753cf4a9e 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -9,226 +9,73 @@ cmake_minimum_required(VERSION 3.10 FATAL_ERROR) -# As of 2018-12-26 ZSTD has been validated to build with cmake version 3.13.2 new policies. -# Set and use the newest cmake policies that are validated to work -set(ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION "3") -set(ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION "13") #Policies never changed at PATCH level -if("${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}" EQUAL "${CMAKE_MAJOR_VERSION}" AND - "${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}" GREATER "${CMAKE_MINOR_VERSION}") - set(ZSTD_CMAKE_POLICY_VERSION "${CMAKE_VERSION}") -else() - set(ZSTD_CMAKE_POLICY_VERSION "${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}.${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}.0") -endif() -cmake_policy(VERSION ${ZSTD_CMAKE_POLICY_VERSION}) - -set(CMAKE_BUILD_WITH_INSTALL_RPATH on) - +#----------------------------------------------------------------------------- +# Setup CMake environment +#----------------------------------------------------------------------------- +set(CMAKE_BUILD_WITH_INSTALL_RPATH ON) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMakeModules") + +# Define project paths set(ZSTD_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../..") set(LIBRARY_DIR ${ZSTD_SOURCE_DIR}/lib) -# Parse version -include(GetZstdLibraryVersion) -GetZstdLibraryVersion(${LIBRARY_DIR}/zstd.h zstd_VERSION_MAJOR zstd_VERSION_MINOR zstd_VERSION_PATCH) - -set(ZSTD_SHORT_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}") -set(ZSTD_FULL_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}") - -project(zstd - VERSION "${ZSTD_FULL_VERSION}" - LANGUAGES C # Main library is in C - ASM # And ASM - ) - -message(STATUS "ZSTD VERSION: ${zstd_VERSION}") -set(zstd_HOMEPAGE_URL "https://facebook.github.io/zstd") -set(zstd_DESCRIPTION "Zstandard is a real-time compression algorithm, providing high compression ratios.") - -# Set a default build type if none was specified -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - message(STATUS "Setting build type to 'Release' as none was specified.") - set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) - # Set the possible values of build type for cmake-gui - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") -endif() - -include(GNUInstallDirs) - -# Always hide XXHash symbols -add_definitions(-DXXH_NAMESPACE=ZSTD_) #----------------------------------------------------------------------------- -# Installation variables +# Configure CMake policies and version +#----------------------------------------------------------------------------- +include(ZstdVersion) + +#----------------------------------------------------------------------------- +# Project declaration +#----------------------------------------------------------------------------- +project(zstd + VERSION "${ZSTD_FULL_VERSION}" + LANGUAGES C ASM # Main library is in C and ASM + HOMEPAGE_URL "${zstd_HOMEPAGE_URL}" + DESCRIPTION "${zstd_DESCRIPTION}" +) + +#----------------------------------------------------------------------------- +# Build type configuration +#----------------------------------------------------------------------------- +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + message(STATUS "Setting build type to 'Release' as none was specified.") + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") +endif() + +#----------------------------------------------------------------------------- +# Include standard modules +#----------------------------------------------------------------------------- +include(GNUInstallDirs) + +#----------------------------------------------------------------------------- +# Display installation information #----------------------------------------------------------------------------- message(STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}") message(STATUS "CMAKE_INSTALL_LIBDIR: ${CMAKE_INSTALL_LIBDIR}") #----------------------------------------------------------------------------- -# Options +# Configure build options #----------------------------------------------------------------------------- - -# Legacy support -option(ZSTD_LEGACY_SUPPORT "LEGACY SUPPORT" ON) - -if (ZSTD_LEGACY_SUPPORT) - message(STATUS "ZSTD_LEGACY_SUPPORT defined!") - set(ZSTD_LEGACY_LEVEL 5 CACHE STRING "") - add_definitions(-DZSTD_LEGACY_SUPPORT=${ZSTD_LEGACY_LEVEL}) -else () - message(STATUS "ZSTD_LEGACY_SUPPORT not defined!") - add_definitions(-DZSTD_LEGACY_SUPPORT=0) -endif () - -if (APPLE) - option(ZSTD_FRAMEWORK "Build as Apple Frameworks" OFF) -endif () - -if (ANDROID) - set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT OFF) - # Old versions of bionic libc don't have fseeko/ftello - if ((NOT ${ANDROID_PLATFORM_LEVEL}) OR ${ANDROID_PLATFORM_LEVEL} VERSION_LESS 24) - message(STATUS "Setting compile definitions for old Android API") - add_compile_definitions(LIBC_NO_FSEEKO) - endif () -else() - set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT ON) -endif() - -# Multi-threading support -option(ZSTD_MULTITHREAD_SUPPORT "MULTITHREADING SUPPORT" ${ZSTD_MULTITHREAD_SUPPORT_DEFAULT}) - -if (ZSTD_MULTITHREAD_SUPPORT) - message(STATUS "ZSTD_MULTITHREAD_SUPPORT is enabled") -else () - message(STATUS "ZSTD_MULTITHREAD_SUPPORT is disabled") -endif () - -option(ZSTD_BUILD_PROGRAMS "BUILD PROGRAMS" ON) -option(ZSTD_BUILD_CONTRIB "BUILD CONTRIB" OFF) - -# Respect the conventional CMake option for enabling tests if it was specified on the first configure -if (BUILD_TESTING) - set(ZSTD_BUILD_TESTS_default ON) -else() - set(ZSTD_BUILD_TESTS_default OFF) -endif() -option(ZSTD_BUILD_TESTS "BUILD TESTS" ${ZSTD_BUILD_TESTS_default}) -if (MSVC) - option(ZSTD_USE_STATIC_RUNTIME "LINK TO STATIC RUN-TIME LIBRARIES" OFF) -endif () - -# Enable C++ support for testing. -set(ZSTD_ENABLE_CXX ${ZSTD_BUILD_TESTS}) - -if(ZSTD_ENABLE_CXX) - enable_language(CXX) -endif() +include(ZstdOptions) #----------------------------------------------------------------------------- -# Add extra compilation flags +# Configure compilation flags #----------------------------------------------------------------------------- include(AddZstdCompilationFlags) -ADD_ZSTD_COMPILATION_FLAGS(ON ZSTD_ENABLE_CXX ON) # C CXX LD +ADD_ZSTD_COMPILATION_FLAGS(ON ZSTD_ENABLE_CXX ON) #----------------------------------------------------------------------------- -# External dependencies +# Configure dependencies #----------------------------------------------------------------------------- -# Define a function to handle special thread settings for HP-UX -# See https://github.com/facebook/zstd/pull/3862 for details. -function(setup_hpux_threads) - find_package(Threads) - if (NOT Threads_FOUND) - set(CMAKE_USE_PTHREADS_INIT 1 PARENT_SCOPE) - set(CMAKE_THREAD_LIBS_INIT -lpthread PARENT_SCOPE) - set(CMAKE_HAVE_THREADS_LIBRARY 1 PARENT_SCOPE) - set(Threads_FOUND TRUE PARENT_SCOPE) - endif() -endfunction() - -if (ZSTD_MULTITHREAD_SUPPORT AND UNIX) - if (CMAKE_SYSTEM_NAME MATCHES "HP-UX") - setup_hpux_threads() - else() - set(THREADS_PREFER_PTHREAD_FLAG ON) - find_package(Threads REQUIRED) - endif() - if (CMAKE_USE_PTHREADS_INIT) - set(THREADS_LIBS "${CMAKE_THREAD_LIBS_INIT}") - else() - message(SEND_ERROR "ZSTD currently does not support thread libraries other than pthreads") - endif() -endif () +include(ZstdDependencies) #----------------------------------------------------------------------------- -# Add source directories +# Configure build targets #----------------------------------------------------------------------------- -add_subdirectory(lib) - -option(ZSTD_PROGRAMS_LINK_SHARED "PROGRAMS LINK SHARED" OFF) - -if (ZSTD_BUILD_PROGRAMS) - if (NOT ZSTD_BUILD_STATIC AND NOT ZSTD_PROGRAMS_LINK_SHARED) - message(SEND_ERROR "You need to build static library to build zstd CLI") - elseif(NOT ZSTD_BUILD_SHARED AND ZSTD_PROGRAMS_LINK_SHARED) - message(SEND_ERROR "You need to build shared library to build zstd CLI") - endif () - - add_subdirectory(programs) -endif () - -if (ZSTD_BUILD_TESTS) - enable_testing() - if (NOT ZSTD_BUILD_STATIC) - message(SEND_ERROR "You need to build static library to build tests") - endif () - - add_subdirectory(tests) -endif () - -if (ZSTD_BUILD_CONTRIB) - add_subdirectory(contrib) -endif () +include(ZstdBuild) #----------------------------------------------------------------------------- -# Add clean-all target +# Configure package generation #----------------------------------------------------------------------------- -add_custom_target(clean-all - COMMAND ${CMAKE_BUILD_TOOL} clean - COMMAND rm -rf ${CMAKE_BINARY_DIR}/ -) - -#----------------------------------------------------------------------------- -# Generate Package Config files -# -# This section is based on the boiler plate code from: -# https://cmake.org/cmake/help/latest/manual/cmake-packages.7.html#creating-packages -#----------------------------------------------------------------------------- -include(CMakePackageConfigHelpers) -write_basic_package_version_file( - "${CMAKE_CURRENT_BINARY_DIR}/zstdConfigVersion.cmake" - VERSION ${zstd_VERSION} - COMPATIBILITY SameMajorVersion - ) - -# A Package Config file that works from the build directory -export(EXPORT zstdExports - FILE "${CMAKE_CURRENT_BINARY_DIR}/zstdTargets.cmake" - NAMESPACE zstd:: - ) - -# A Package Config file that works from the installation directory -set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/zstd) -install(EXPORT zstdExports - FILE zstdTargets.cmake - NAMESPACE zstd:: - DESTINATION ${ConfigPackageLocation} - ) -configure_package_config_file( - zstdConfig.cmake.in - "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake" - INSTALL_DESTINATION ${ConfigPackageLocation} -) -install(FILES - "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/zstdConfigVersion.cmake" - DESTINATION ${ConfigPackageLocation} - ) +include(ZstdPackage) diff --git a/build/cmake/CMakeModules/ZstdBuild.cmake b/build/cmake/CMakeModules/ZstdBuild.cmake new file mode 100644 index 000000000..ada44a966 --- /dev/null +++ b/build/cmake/CMakeModules/ZstdBuild.cmake @@ -0,0 +1,42 @@ +# ################################################################ +# ZSTD Build Targets Configuration +# ################################################################ + +# Always build the library first (this defines ZSTD_BUILD_STATIC/SHARED options) +add_subdirectory(lib) + +# Validate build configuration after lib options are defined +if(ZSTD_BUILD_PROGRAMS) + if(NOT ZSTD_BUILD_STATIC AND NOT ZSTD_PROGRAMS_LINK_SHARED) + message(SEND_ERROR "Static library required to build zstd CLI programs") + elseif(NOT ZSTD_BUILD_SHARED AND ZSTD_PROGRAMS_LINK_SHARED) + message(SEND_ERROR "Shared library required to build zstd CLI programs") + endif() +endif() + +if(ZSTD_BUILD_TESTS AND NOT ZSTD_BUILD_STATIC) + message(SEND_ERROR "Static library required to build test suite") +endif() + +# Add programs if requested +if(ZSTD_BUILD_PROGRAMS) + add_subdirectory(programs) +endif() + +# Add tests if requested +if(ZSTD_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() + +# Add contrib utilities if requested +if(ZSTD_BUILD_CONTRIB) + add_subdirectory(contrib) +endif() + +# Clean-all target for thorough cleanup +add_custom_target(clean-all + COMMAND ${CMAKE_BUILD_TOOL} clean + COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_BINARY_DIR}/ + COMMENT "Performing complete clean including build directory" +) diff --git a/build/cmake/CMakeModules/ZstdDependencies.cmake b/build/cmake/CMakeModules/ZstdDependencies.cmake new file mode 100644 index 000000000..4e90c5f1b --- /dev/null +++ b/build/cmake/CMakeModules/ZstdDependencies.cmake @@ -0,0 +1,30 @@ +# ################################################################ +# ZSTD Dependencies Configuration +# ################################################################ + +# Function to handle HP-UX thread configuration +function(setup_hpux_threads) + find_package(Threads) + if(NOT Threads_FOUND) + set(CMAKE_USE_PTHREADS_INIT 1 PARENT_SCOPE) + set(CMAKE_THREAD_LIBS_INIT -lpthread PARENT_SCOPE) + set(CMAKE_HAVE_THREADS_LIBRARY 1 PARENT_SCOPE) + set(Threads_FOUND TRUE PARENT_SCOPE) + endif() +endfunction() + +# Configure threading support +if(ZSTD_MULTITHREAD_SUPPORT AND UNIX) + if(CMAKE_SYSTEM_NAME MATCHES "HP-UX") + setup_hpux_threads() + else() + set(THREADS_PREFER_PTHREAD_FLAG ON) + find_package(Threads REQUIRED) + endif() + + if(CMAKE_USE_PTHREADS_INIT) + set(THREADS_LIBS "${CMAKE_THREAD_LIBS_INIT}") + else() + message(SEND_ERROR "ZSTD currently does not support thread libraries other than pthreads") + endif() +endif() diff --git a/build/cmake/CMakeModules/ZstdOptions.cmake b/build/cmake/CMakeModules/ZstdOptions.cmake new file mode 100644 index 000000000..3fca543a7 --- /dev/null +++ b/build/cmake/CMakeModules/ZstdOptions.cmake @@ -0,0 +1,68 @@ +# ################################################################ +# ZSTD Build Options Configuration +# ################################################################ + +# Legacy support configuration +option(ZSTD_LEGACY_SUPPORT "Enable legacy format support" ON) + +if(ZSTD_LEGACY_SUPPORT) + message(STATUS "ZSTD_LEGACY_SUPPORT enabled") + set(ZSTD_LEGACY_LEVEL 5 CACHE STRING "Legacy support level") + add_definitions(-DZSTD_LEGACY_SUPPORT=${ZSTD_LEGACY_LEVEL}) +else() + message(STATUS "ZSTD_LEGACY_SUPPORT disabled") + add_definitions(-DZSTD_LEGACY_SUPPORT=0) +endif() + +# Platform-specific options +if(APPLE) + option(ZSTD_FRAMEWORK "Build as Apple Framework" OFF) +endif() + +# Android-specific configuration +if(ANDROID) + set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT OFF) + # Handle old Android API levels + if((NOT ANDROID_PLATFORM_LEVEL) OR (ANDROID_PLATFORM_LEVEL VERSION_LESS 24)) + message(STATUS "Configuring for old Android API - disabling fseeko/ftello") + add_compile_definitions(LIBC_NO_FSEEKO) + endif() +else() + set(ZSTD_MULTITHREAD_SUPPORT_DEFAULT ON) +endif() + +# Multi-threading support +option(ZSTD_MULTITHREAD_SUPPORT "Enable multi-threading support" ${ZSTD_MULTITHREAD_SUPPORT_DEFAULT}) + +if(ZSTD_MULTITHREAD_SUPPORT) + message(STATUS "Multi-threading support enabled") +else() + message(STATUS "Multi-threading support disabled") +endif() + +# Build component options +option(ZSTD_BUILD_PROGRAMS "Build command-line programs" ON) +option(ZSTD_BUILD_CONTRIB "Build contrib utilities" OFF) +option(ZSTD_PROGRAMS_LINK_SHARED "Link programs against shared library" OFF) + +# Test configuration +if(BUILD_TESTING) + set(ZSTD_BUILD_TESTS_default ON) +else() + set(ZSTD_BUILD_TESTS_default OFF) +endif() +option(ZSTD_BUILD_TESTS "Build test suite" ${ZSTD_BUILD_TESTS_default}) + +# MSVC-specific options +if(MSVC) + option(ZSTD_USE_STATIC_RUNTIME "Link to static runtime libraries" OFF) +endif() + +# C++ support (needed for tests) +set(ZSTD_ENABLE_CXX ${ZSTD_BUILD_TESTS}) +if(ZSTD_ENABLE_CXX) + enable_language(CXX) +endif() + +# Set global definitions +add_definitions(-DXXH_NAMESPACE=ZSTD_) diff --git a/build/cmake/CMakeModules/ZstdPackage.cmake b/build/cmake/CMakeModules/ZstdPackage.cmake new file mode 100644 index 000000000..5e40dd2c1 --- /dev/null +++ b/build/cmake/CMakeModules/ZstdPackage.cmake @@ -0,0 +1,42 @@ +# ################################################################ +# ZSTD Package Configuration +# ################################################################ + +include(CMakePackageConfigHelpers) + +# Generate version file +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/zstdConfigVersion.cmake" + VERSION ${zstd_VERSION} + COMPATIBILITY SameMajorVersion +) + +# Export targets for build directory +export(EXPORT zstdExports + FILE "${CMAKE_CURRENT_BINARY_DIR}/zstdTargets.cmake" + NAMESPACE zstd:: +) + +# Configure package for installation +set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/zstd) + +# Install exported targets +install(EXPORT zstdExports + FILE zstdTargets.cmake + NAMESPACE zstd:: + DESTINATION ${ConfigPackageLocation} +) + +# Configure and install package config file +configure_package_config_file( + zstdConfig.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake" + INSTALL_DESTINATION ${ConfigPackageLocation} +) + +# Install config files +install(FILES + "${CMAKE_CURRENT_BINARY_DIR}/zstdConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/zstdConfigVersion.cmake" + DESTINATION ${ConfigPackageLocation} +) diff --git a/build/cmake/CMakeModules/ZstdVersion.cmake b/build/cmake/CMakeModules/ZstdVersion.cmake new file mode 100644 index 000000000..fceb0ec0c --- /dev/null +++ b/build/cmake/CMakeModules/ZstdVersion.cmake @@ -0,0 +1,31 @@ +# ################################################################ +# ZSTD Version Configuration +# ################################################################ + +# Setup CMake policy version +set(ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION "3") +set(ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION "13") + +# Determine appropriate policy version +if("${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}" EQUAL "${CMAKE_MAJOR_VERSION}" AND + "${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}" GREATER "${CMAKE_MINOR_VERSION}") + set(ZSTD_CMAKE_POLICY_VERSION "${CMAKE_VERSION}") +else() + set(ZSTD_CMAKE_POLICY_VERSION "${ZSTD_MAX_VALIDATED_CMAKE_MAJOR_VERSION}.${ZSTD_MAX_VALIDATED_CMAKE_MINOR_VERSION}.0") +endif() + +cmake_policy(VERSION ${ZSTD_CMAKE_POLICY_VERSION}) + +# Parse version from header file +include(GetZstdLibraryVersion) +GetZstdLibraryVersion(${LIBRARY_DIR}/zstd.h zstd_VERSION_MAJOR zstd_VERSION_MINOR zstd_VERSION_PATCH) + +# Set version variables +set(ZSTD_SHORT_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}") +set(ZSTD_FULL_VERSION "${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}") + +# Project metadata +set(zstd_HOMEPAGE_URL "https://facebook.github.io/zstd") +set(zstd_DESCRIPTION "Zstandard is a real-time compression algorithm, providing high compression ratios.") + +message(STATUS "ZSTD VERSION: ${zstd_VERSION_MAJOR}.${zstd_VERSION_MINOR}.${zstd_VERSION_PATCH}") From b6dc2924f81a07c1833c255e9e2a0dabef5f3619 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 9 Jun 2025 06:47:28 +0000 Subject: [PATCH 801/937] remove fail-fast so that the outcome of other tests can be observed --- .github/workflows/cmake-tests.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index f9212e254..b02385708 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -77,6 +77,7 @@ jobs: name: "CMake Windows VS2022 (${{ matrix.name }})" runs-on: ${{ matrix.runner }} strategy: + fail-fast: false matrix: include: - generator: "Visual Studio 17 2022" From 7e0324e124f0814fd6ffd1587f683313bcafe1f2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 9 Jun 2025 07:09:51 +0000 Subject: [PATCH 802/937] fixed cmake + windows + visual + clang-cl by removing processing of resource files in this case --- build/cmake/lib/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index 0a93e8d31..a6b894c4d 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -97,9 +97,11 @@ if (ZSTD_LEGACY_SUPPORT) ${LIBRARY_LEGACY_DIR}/zstd_v07.h) endif () -if (MSVC) +if (MSVC AND NOT (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")) set(MSVC_RESOURCE_DIR ${ZSTD_SOURCE_DIR}/build/VS2010/libzstd-dll) set(PlatformDependResources ${MSVC_RESOURCE_DIR}/libzstd-dll.rc) +else() + set(PlatformDependResources) endif () # Explicitly set the language to C for all files, including ASM files. From 472acf5d83e0f059c0d5938dea6556e21385a71c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 9 Jun 2025 07:24:03 +0000 Subject: [PATCH 803/937] fix #4405 --- build/cmake/CMakeModules/AddZstdCompilationFlags.cmake | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake index 25231b5ec..dbe4118eb 100644 --- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake +++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake @@ -1,5 +1,10 @@ -include(CheckCXXCompilerFlag) include(CheckCCompilerFlag) +if(CMAKE_CXX_COMPILER) + include(CheckCXXCompilerFlag) + set(ZSTD_CXX_ENABLED TRUE) +else() + set(ZSTD_CXX_ENABLED FALSE) +endif() if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.18) set(ZSTD_HAVE_CHECK_LINKER_FLAG true) @@ -21,7 +26,7 @@ function(EnableCompilerFlag _flag _C _CXX _LD) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_flag}" PARENT_SCOPE) endif () endif () - if (_CXX) + if (_CXX AND ZSTD_CXX_ENABLED) CHECK_CXX_COMPILER_FLAG(${_flag} CXX_FLAG_${varname}) if (CXX_FLAG_${varname}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${_flag}" PARENT_SCOPE) From de8d9e8914fbc26cb7d4e864429b906744514a38 Mon Sep 17 00:00:00 2001 From: shixuantong Date: Sun, 1 Jun 2025 00:37:57 +0800 Subject: [PATCH 804/937] Fix several locations with potential memory leak --- .../seekable_format/tests/seekable_tests.c | 12 +++ programs/util.c | 1 + tests/bigdict.c | 78 +++++++++++------ tests/largeDictionary.c | 85 +++++++++++++------ tests/legacy.c | 2 + tests/longmatch.c | 55 ++++++++---- 6 files changed, 162 insertions(+), 71 deletions(-) diff --git a/contrib/seekable_format/tests/seekable_tests.c b/contrib/seekable_format/tests/seekable_tests.c index f89bdc930..809ea6425 100644 --- a/contrib/seekable_format/tests/seekable_tests.c +++ b/contrib/seekable_format/tests/seekable_tests.c @@ -316,6 +316,10 @@ int main(int argc, const char** argv) for (pos = 0; pos < inSize; pos += 2) { size_t const decStatus = ZSTD_seekable_decompress(stream, outBuffer, 1, pos); if (decStatus != 1 || outBuffer[0] != inBuffer[pos]) { + free(seekBuffer); + free(outBuffer); + ZSTD_seekable_freeCStream(zscs); + ZSTD_seekable_free(stream); goto _test_error; } } @@ -323,6 +327,10 @@ int main(int argc, const char** argv) /* We read more than the compressed size, meaning there were some rereads. This is unneeded because we only seeked forward. */ printf("Too much data read: %zu read, with compressed size %zu\n", buffWrapper.totalRead, seekSize); + free(seekBuffer); + free(outBuffer); + ZSTD_seekable_freeCStream(zscs); + ZSTD_seekable_free(stream); goto _test_error; } @@ -342,6 +350,10 @@ int main(int argc, const char** argv) for (idx = 0; idx < sizeof(tests) / sizeof(tests[0]); idx++) { size_t const decStatus = ZSTD_seekable_decompress(stream, outBuffer, tests[idx].size, tests[idx].offset); if (decStatus != tests[idx].size || memcmp(outBuffer, inBuffer + tests[idx].offset, tests[idx].size) != 0) { + free(seekBuffer); + free(outBuffer); + ZSTD_seekable_freeCStream(zscs); + ZSTD_seekable_free(stream); goto _test_error; } } diff --git a/programs/util.c b/programs/util.c index d11f13cfd..652530b12 100644 --- a/programs/util.c +++ b/programs/util.c @@ -928,6 +928,7 @@ static int UTIL_prepareFileList(const char* dirName, hFile=FindFirstFileA(path, &cFile); if (hFile == INVALID_HANDLE_VALUE) { UTIL_DISPLAYLEVEL(1, "Cannot open directory '%s'\n", dirName); + free(path); return 0; } free(path); diff --git a/tests/bigdict.c b/tests/bigdict.c index 748b60e79..230e5b979 100644 --- a/tests/bigdict.c +++ b/tests/bigdict.c @@ -80,29 +80,51 @@ int main(int argc, const char** argv) goto cleanup; } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) - return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) { + _exit_code = 1; + goto cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) { + _exit_code = 1; + goto cleanup; + } - if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) - return 1; + if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) { + _exit_code = 1; + goto cleanup; + } RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); @@ -111,13 +133,17 @@ int main(int argc, const char** argv) int i; for (i = 0; i < 10; ++i) { fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) - return 1; + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) { + _exit_code = 1; + goto cleanup; + } } } fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) - return 1; + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) { + _exit_code = 1; + goto cleanup; + } fprintf(stderr, "Success!\n"); diff --git a/tests/largeDictionary.c b/tests/largeDictionary.c index ff2bb2d70..a3b96135f 100644 --- a/tests/largeDictionary.c +++ b/tests/largeDictionary.c @@ -72,35 +72,59 @@ int main(int argc, const char** argv) void* roundtrip = malloc(dataSize); (void)argc; (void)argv; + int _exit_code = 0; if (!buffer || !out || !roundtrip || !cctx || !dctx) { fprintf(stderr, "Allocation failure\n"); - return 1; + _exit_code = 1; + goto _cleanup; } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) - return 1; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) - return 1; + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) { + _exit_code = 1; + goto _cleanup; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) { + _exit_code = 1; + goto _cleanup; + } - if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) - return 1; + if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) { + _exit_code = 1; + goto _cleanup; + } RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); @@ -109,20 +133,25 @@ int main(int argc, const char** argv) int i; for (i = 0; i < 10; ++i) { fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) - return 1; + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) { + _exit_code = 1; + goto _cleanup; + } } } fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) - return 1; + if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) { + _exit_code = 1; + goto _cleanup; + } fprintf(stderr, "Success!\n"); +_cleanup: free(roundtrip); free(out); free(buffer); ZSTD_freeDCtx(dctx); ZSTD_freeCCtx(cctx); - return 0; + return _exit_code; } diff --git a/tests/legacy.c b/tests/legacy.c index 3be386495..8fe291c5a 100644 --- a/tests/legacy.c +++ b/tests/legacy.c @@ -56,6 +56,7 @@ static int testSimpleAPI(void) } else { DISPLAY("ERROR: %s\n", ZSTD_getErrorName(ret)); } + free(output); return 1; } if (ret != size) { @@ -64,6 +65,7 @@ static int testSimpleAPI(void) } if (memcmp(EXPECTED, output, size) != 0) { DISPLAY("ERROR: Wrong decoded output produced\n"); + free(output); return 1; } diff --git a/tests/longmatch.c b/tests/longmatch.c index 547b26190..8e4e51dc1 100644 --- a/tests/longmatch.c +++ b/tests/longmatch.c @@ -39,24 +39,39 @@ int main(int argc, const char** argv) unsigned windowLog = 18; (void)argc; (void)argv; + int _exit_code = 0; /* Create stream */ ctx = ZSTD_createCCtx(); if (!ctx) { return 1; } /* Set parameters */ - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_windowLog, windowLog))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_chainLog, 13))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_hashLog, 14))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_searchLog, 1))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_minMatch, 7))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_targetLength, 16))) - return 2; - if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_strategy, ZSTD_fast))) - return 2; + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_windowLog, windowLog))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_chainLog, 13))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_hashLog, 14))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_searchLog, 1))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_minMatch, 7))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_targetLength, 16))) { + _exit_code = 2; + goto _clean_ctx; + } + if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_strategy, ZSTD_fast))) { + _exit_code = 2; + goto _clean_ctx; + } { U64 compressed = 0; const U64 toCompress = ((U64)1) << 33; @@ -81,22 +96,28 @@ int main(int argc, const char** argv) } printf("Compressing, trying to generate a segfault \n"); if (compress(ctx, out, srcBuffer, size)) { - return 1; + _exit_code = 1; + goto _clean_buffer; } compressed += size; while (compressed < toCompress) { const size_t block = rand() % (size - pos + 1); if (pos == size) { pos = 0; } if (compress(ctx, out, srcBuffer + pos, block)) { - return 1; + _exit_code = 1; + goto _clean_buffer; } pos += block; compressed += block; } printf("Compression completed successfully (no error triggered)\n"); + +_clean_buffer: free(srcBuffer); free(dstBuffer); } + +_clean_ctx: ZSTD_freeCCtx(ctx); - return 0; + return _exit_code; } From 9a6fe9a428751b82be76cdf010cf89aae64897ce Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 9 Jun 2025 21:55:06 +0000 Subject: [PATCH 805/937] remove global variable overkill and leaky to transport a test result just in one place. --- build/cmake/CMakeModules/AddZstdCompilationFlags.cmake | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake index dbe4118eb..3e7bcce59 100644 --- a/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake +++ b/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake @@ -1,9 +1,6 @@ include(CheckCCompilerFlag) if(CMAKE_CXX_COMPILER) include(CheckCXXCompilerFlag) - set(ZSTD_CXX_ENABLED TRUE) -else() - set(ZSTD_CXX_ENABLED FALSE) endif() if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.18) @@ -26,7 +23,7 @@ function(EnableCompilerFlag _flag _C _CXX _LD) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_flag}" PARENT_SCOPE) endif () endif () - if (_CXX AND ZSTD_CXX_ENABLED) + if (_CXX AND CMAKE_CXX_COMPILER) CHECK_CXX_COMPILER_FLAG(${_flag} CXX_FLAG_${varname}) if (CXX_FLAG_${varname}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${_flag}" PARENT_SCOPE) From 7e4937bc7533914370be181234384650cf519b53 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Wed, 11 Jun 2025 12:14:22 +0000 Subject: [PATCH 806/937] AArch64: Add SVE2 implementation of histogram computation The existing scalar implementation uses a 4-way pipelined histogram calculation which is very efficient on out-of-order CPUs. However, this can be further accelerated using the SVE2 HISTSEG instructions - which compute a histogram for 16 byte chunks in a vector register. On a system with 128-bit vectors (VL128) we need 16 HISTSEG executions to compute the histogram for the whole symbol space (0..255) of 16 bytes input. However we can only accumulate 15 of such 16 byte strips before possible overflow. So we need to extend and save the 8-bit histogram accumulators to 16-bit after every 240 byte chunks of input. To store all in registers we would need 32 128-bit registers. Longer SVE2 vectors could help here, if such machines become available. The maximum input block size in Zstd is 128 KiB, so 16-bit accumulators would not be enough. However an LZ pass will prepend the histogram calculation, so it is impossible (my assumption) to overflow the 16-bit accumulators. The symbol distribution is also not uniform, the lower values are more common, so we used a 3 pass algorithm to prevent stack spilling. In the first pass we only compute histograms for 64 symbols (4-way SIMD) while also computing the maximum symbol value. If we have symbol values larger than 64 we start the second pass to compute the next 96 elements of the histogram. The final pass calculates the remaining part of the histogram (256 symbols in total) if needed. This split of histogram generation gave the best overall results for performance. This implementation is the best performing of a number of different cache blocking schemes tested. Compression uplifts on a Neoverse V2 system, using Zstd-1.5.8 (e26dde3d) as a baseline, compiled with "-O3 -march=armv8.2-a+sve2": Clang-20 GCC-14 1#silesia.tar: +6.173% +5.987% 2#silesia.tar: +5.200% +5.011% 3#silesia.tar: +4.332% +5.031% 4#silesia.tar: +2.789% +3.064% 5#silesia.tar: +2.028% +1.838% 6#silesia.tar: +1.562% +1.340% 7#silesia.tar: +1.160% +0.959% --- lib/common/compiler.h | 9 ++ lib/compress/hist.c | 261 +++++++++++++++++++++++++++++++++++++++++- lib/compress/hist.h | 4 + 3 files changed, 271 insertions(+), 3 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index cafb35b71..6131ad068 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -218,6 +218,12 @@ # 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) # define ZSTD_ARCH_RISCV_RVV # endif @@ -230,6 +236,9 @@ # 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 diff --git a/lib/compress/hist.c b/lib/compress/hist.c index 4ccf9a90a..3692bc250 100644 --- a/lib/compress/hist.c +++ b/lib/compress/hist.c @@ -19,6 +19,12 @@ #include "../common/error_private.h" /* ERROR */ #include "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); } @@ -65,6 +71,244 @@ unsigned HIST_count_simple(unsigned* count, unsigned* maxSymbolValuePtr, typedef enum { trustInput, checkMaxSymbolValue } HIST_checkInput_e; +#if defined(ZSTD_ARCH_ARM_SVE2) +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(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); + 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); + } +} +#endif + /* HIST_count_parallel_wksp() : * store histogram into 4 intermediate tables, recombined at the end. * this design makes better use of OoO cpus, @@ -73,8 +317,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) @@ -151,11 +395,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() : @@ -165,10 +415,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); } diff --git a/lib/compress/hist.h b/lib/compress/hist.h index bea2a9ebf..e526e9532 100644 --- a/lib/compress/hist.h +++ b/lib/compress/hist.h @@ -35,7 +35,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. From cad0b72ad8ca6d413843af453e274750ba717012 Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Thu, 12 Jun 2025 19:52:58 -0400 Subject: [PATCH 807/937] Ensure BMK_timedFnState is always freed in benchMem When an error occurs in BMK_isSuccessful_runOutcome, the code previously skipped the call to BMK_freeTimedFnState(tfs), leaking the allocated tfs object. Fiexed by calling BMK_freeTimedFnState(tfs) before goto _cleanOut. --- tests/fullbench.c | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/fullbench.c b/tests/fullbench.c index 12a27f48c..5841e5db5 100644 --- a/tests/fullbench.c +++ b/tests/fullbench.c @@ -890,6 +890,7 @@ static int benchMem(unsigned scenarioID, if (!BMK_isSuccessful_runOutcome(bOutcome)) { DISPLAY("ERROR: Scenario %u: %s \n", scenarioID, ZSTD_getErrorName(BMK_extract_errorResult(bOutcome))); errorcode = 1; + BMK_freeTimedFnState(tfs); goto _cleanOut; } From d28a7377505087174a5d3b259a232b8ab7f0cb60 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Wed, 11 Jun 2025 12:19:42 +0000 Subject: [PATCH 808/937] Add unit tests for HIST_count_wksp The following tests are included: - Empty input scenario test. - Workspace size and alignment tests. - Symbol out-of-range tests. - Cover multiple input sizes, vary permitted maximum symbol values, and include diverse symbol distributions. These tests verifies count table correctness, maxSymbolValuePtr updates, and error-handling paths. It enables automated regression of core histogram logic as well. --- .github/workflows/dev-short-tests.yml | 2 + tests/cli-tests/run.py | 2 +- tests/fuzzer.c | 126 ++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 8e8753658..31d44542f 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -435,6 +435,8 @@ jobs: make clean LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests + CFLAGS="-march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check + CFLAGS="-march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests # This test is only compatible with standard libraries that support BTI (Branch Target Identification). # Unfortunately, the standard library provided on Ubuntu 24.04 does not have this feature enabled. # make clean diff --git a/tests/cli-tests/run.py b/tests/cli-tests/run.py index 011c8478e..0addd6b1a 100755 --- a/tests/cli-tests/run.py +++ b/tests/cli-tests/run.py @@ -640,7 +640,7 @@ if __name__ == "__main__": help="Preserve the scratch directory TEST_DIR/scratch/ for debugging purposes." ) parser.add_argument("--verbose", action="store_true", help="Verbose test output.") - parser.add_argument("--timeout", default=200, type=int, help="Test case timeout in seconds. Set to 0 to disable timeouts.") + parser.add_argument("--timeout", default=800, type=int, help="Test case timeout in seconds. Set to 0 to disable timeouts.") parser.add_argument( "--exec-prefix", default=None, diff --git a/tests/fuzzer.c b/tests/fuzzer.c index b74460bb5..da380aced 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -44,6 +44,13 @@ /* must be included after util.h, due to ERROR macro redefinition issue on Visual Studio */ #include "zstd_internal.h" /* ZSTD_WORKSPACETOOLARGE_MAXDURATION, ZSTD_WORKSPACETOOLARGE_FACTOR, KB, MB */ #include "threading.h" /* ZSTD_pthread_create, ZSTD_pthread_join */ +#include "compress/hist.h" /* HIST_count_wksp */ + + +/*-************************************ +* Macros +**************************************/ +#define COUNTOF(array) (sizeof(array) / sizeof(*(array))) /*-************************************ @@ -567,6 +574,123 @@ static void test_decompressBound(unsigned tnb) DISPLAYLEVEL(3, "OK \n"); } +static unsigned test_histCountWksp(unsigned seed, unsigned testNb) +{ + static const unsigned symLowLimits[] = { 0, 27, 0, 0, 27, 42, 0, 0, 27, 42, 27, 42 }; + static const unsigned symHighLimits[] = { 255, 255, 210, 110, 42, 42, 210, 110, 42, 42, 42, 42 }; + static const unsigned symMaxLimits[] = { 255, 255, 255, 255, 255, 255, 230, 130, 99, 99, 42, 42 }; + static const size_t inputSizes[] = { 3367, 1761, 893, 117 }; + unsigned workspace[HIST_WKSP_SIZE_U32]; + size_t res, i, is, il; + + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp with empty source : ", testNb++); + { + /* With NULL source UBSan of older Clang could fail: applying zero offset to null pointer. */ + static const unsigned char source[4] = { 0 }; + unsigned count[1] = { 0 }; + unsigned maxSym = 0; + res = HIST_count_wksp(count, &maxSym, source, 0, workspace, sizeof(workspace)); + CHECK_EQ(res, 0); + CHECK_EQ(maxSym, 0); + CHECK_EQ(count[0], 0); + } + DISPLAYLEVEL(3, "OK \n"); + +#if HIST_WKSP_SIZE_U32 + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp with small workspace : ", testNb++); + { + unsigned count[1] = { 0 }; + unsigned maxSym = 0; + res = HIST_count_wksp(count, &maxSym, NULL, 0, workspace, sizeof(workspace) - 1); + CHECK_EQ(res, ERROR(workSpace_tooSmall)); + CHECK_EQ(maxSym, 0); + CHECK_EQ(count[0], 0); + } + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp with wrong workspace alignment : ", testNb++); + { + unsigned count[1] = { 0 }; + unsigned maxSym = 0; + res = HIST_count_wksp(count, &maxSym, NULL, 0, (unsigned*)(void*)((char*)workspace + 1), sizeof(workspace)); + CHECK_EQ(res, ERROR(GENERIC)); + CHECK_EQ(maxSym, 0); + CHECK_EQ(count[0], 0); + } + DISPLAYLEVEL(3, "OK \n"); +#endif + + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp with symbol out of range, small size : ", testNb++); + { + /* For less elements HIST_count_parallel_wksp would fail. */ + static const unsigned char source[4] = { 1, 4, 0, 2 }; + static const unsigned expected[6] = { 0 }; + unsigned count[6] = { 0 }; + unsigned maxSym = 2; + res = HIST_count_wksp(count, &maxSym, source, sizeof(source), workspace, sizeof(workspace)); + CHECK_EQ(res, ERROR(maxSymbolValue_tooSmall)); + CHECK_EQ(maxSym, 2); + for (i = 0; i < COUNTOF(expected); ++i) CHECK_EQ(count[i], expected[i]); + } + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp with symbol out of range, medium size : ", testNb++); + { + unsigned char source[3407]; + unsigned count[6] = { 0 }; + unsigned maxSym = 2; + for (i = 0; i < COUNTOF(source); ++i) { + source[i] = (48271 * (i + 1)) & 3; + } + res = HIST_count_wksp(count, &maxSym, source, sizeof(source), workspace, sizeof(workspace)); + CHECK_EQ(res, ERROR(maxSymbolValue_tooSmall)); + CHECK_EQ(maxSym, 2); + for (i = 0; i < COUNTOF(count); ++i) CHECK_EQ(count[i], 0); + } + DISPLAYLEVEL(3, "OK \n"); + + for (il = 0; il < COUNTOF(symMaxLimits); ++il) { + unsigned symMax = symMaxLimits[il]; + unsigned symLow = symLowLimits[il]; + unsigned symHigh = symHighLimits[il]; + unsigned symRange = symHigh - symLow + 1; + + for (is = 0; is < COUNTOF(inputSizes); ++is) { + unsigned char source[4000]; + size_t inputSize = inputSizes[is]; + assert(inputSize <= sizeof(source)); + DISPLAYLEVEL(3, "test%3u : HIST_count_wksp test in [%u..%u], symMax: %u, inputSize: %u : ", + testNb++, symLow, symHigh, symMax, (unsigned)inputSize); + { + unsigned count[260] = { 0 }; + unsigned expected[COUNTOF(count)] = { 0 }; + unsigned maxSym = symMax; + unsigned realMaxSym = symMax; + unsigned maxCount = 0; + for (i = 0; i < inputSize; ++i) { + unsigned prng = (48271 * (i + seed)) % symRange + symLow; + source[i] = (unsigned char)prng; + ++expected[prng]; + } + /* for basic buffer overwrite checks */ + for (i = maxSym + 1; i < COUNTOF(count); ++i) expected[i] = count[i] = ~0u; + for (i = 0; i <= maxSym; ++i) maxCount = MAX(maxCount, expected[i]); + for (i = realMaxSym; i > 0; --i) { + if (expected[i]) break; + --realMaxSym; + } + res = HIST_count_wksp(count, &maxSym, source, inputSize, workspace, sizeof(workspace)); + CHECK_EQ(res, maxCount); + CHECK_EQ(maxSym, realMaxSym); + for (i = 0; i < COUNTOF(expected); ++i) CHECK_EQ(count[i], expected[i]); + } + DISPLAYLEVEL(3, "OK \n"); + } + } + + return testNb; +} + static void test_setCParams(unsigned tnb) { ZSTD_CCtx* const cctx = ZSTD_createCCtx(); @@ -712,6 +836,8 @@ static int basicUnitTests(U32 const seed, double compressibility) } DISPLAYLEVEL(3, "OK \n"); + testNb = test_histCountWksp(seed, testNb); + DISPLAYLEVEL(3, "test%3u : compress %u bytes : ", testNb++, (unsigned)CNBuffSize); { ZSTD_CCtx* const cctx = ZSTD_createCCtx(); if (cctx==NULL) goto _output_error; From 57bd0eb6a700717500f0c8c9a00d2b468b728d15 Mon Sep 17 00:00:00 2001 From: Benjamin Gilbert Date: Sat, 14 Jun 2025 19:47:54 -0700 Subject: [PATCH 809/937] meson: use SPDX expression for license This is the format recommended by Meson documentation. --- build/meson/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/meson/meson.build b/build/meson/meson.build index 5c35478d5..bae4d2501 100644 --- a/build/meson/meson.build +++ b/build/meson/meson.build @@ -10,7 +10,7 @@ project('zstd', ['c', 'cpp'], - license: ['BSD', 'GPLv2'], + license: 'BSD-3-Clause OR GPL-2.0-only', default_options : [ # There shouldn't be any need to force a C standard convention for zstd # but in case one would want that anyway, this can be done here. From e315155cc2bbfa72243c51dc083f64931a08d4a3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 18 Jun 2025 15:07:32 -0700 Subject: [PATCH 810/937] removed duplicate this file is already present as `largeDictionary.c` --- tests/bigdict.c | 159 ------------------------------------------------ 1 file changed, 159 deletions(-) delete mode 100644 tests/bigdict.c diff --git a/tests/bigdict.c b/tests/bigdict.c deleted file mode 100644 index 230e5b979..000000000 --- a/tests/bigdict.c +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include -#include -#include "datagen.h" -#include "mem.h" -#define ZSTD_STATIC_LINKING_ONLY -#include "zstd.h" - -static int -compress(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx, - void* dst, size_t dstCapacity, - void const* src, size_t srcSize, - void* roundtrip, ZSTD_EndDirective end) -{ - ZSTD_inBuffer in = {src, srcSize, 0}; - ZSTD_outBuffer out = {dst, dstCapacity, 0}; - int ended = 0; - - while (!ended && (in.pos < in.size || out.pos > 0)) { - size_t rc; - out.pos = 0; - rc = ZSTD_compressStream2(cctx, &out, &in, end); - if (ZSTD_isError(rc)) - return 1; - if (end == ZSTD_e_end && rc == 0) - ended = 1; - { - ZSTD_inBuffer rtIn = {dst, out.pos, 0}; - ZSTD_outBuffer rtOut = {roundtrip, srcSize, 0}; - rc = 1; - while (rtIn.pos < rtIn.size || rtOut.pos > 0) { - rtOut.pos = 0; - rc = ZSTD_decompressStream(dctx, &rtOut, &rtIn); - if (ZSTD_isError(rc)) { - fprintf(stderr, "Decompression error: %s\n", ZSTD_getErrorName(rc)); - return 1; - } - if (rc == 0) - break; - } - if (ended && rc != 0) { - fprintf(stderr, "Frame not finished!\n"); - return 1; - } - } - } - - return 0; -} - -int main(int argc, const char** argv) -{ - ZSTD_CCtx* cctx = ZSTD_createCCtx(); - ZSTD_DCtx* dctx = ZSTD_createDCtx(); - const size_t dataSize = (size_t)1 << 30; - const size_t outSize = ZSTD_compressBound(dataSize); - const size_t bufferSize = (size_t)1 << 31; - char* buffer = (char*)malloc(bufferSize); - void* out = malloc(outSize); - void* roundtrip = malloc(dataSize); - int _exit_code = 0; - (void)argc; - (void)argv; - - if (!buffer || !out || !roundtrip || !cctx || !dctx) { - fprintf(stderr, "Allocation failure\n"); - _exit_code = 1; - goto cleanup; - } - - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) { - _exit_code = 1; - goto cleanup; - } - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) { - _exit_code = 1; - goto cleanup; - } - - if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) { - _exit_code = 1; - goto cleanup; - } - - RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); - - /* Compress 30 GB */ - { - int i; - for (i = 0; i < 10; ++i) { - fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) { - _exit_code = 1; - goto cleanup; - } - } - } - fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) { - _exit_code = 1; - goto cleanup; - } - - fprintf(stderr, "Success!\n"); - - goto cleanup; - -cleanup: - free(roundtrip); - free(out); - free(buffer); - ZSTD_freeCCtx(cctx); - ZSTD_freeDCtx(dctx); - return _exit_code; -} From 1e9d2006ae2601df6c3ec36464e1622921424a91 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Fri, 20 Jun 2025 14:48:33 +0000 Subject: [PATCH 811/937] AArch64: Use better block copy8 The vector copy is only necessary for 16-byte blocks on AArch64. Decompression uplifts on a Neoverse V2 system, using Zstd-1.5.8 compiled with "-O3 -march=armv8.2-a+sve2": Clang-19 Clang-20 GCC-14 GCC-15 1#silesia.tar: +0.316% +0.865% +0.025% +0.096% 2#silesia.tar: +0.689% +1.374% +0.027% +0.065% 3#silesia.tar: +0.811% +1.654% +0.034% +0.033% 4#silesia.tar: +0.912% +1.755% +0.027% +0.042% 5#silesia.tar: +0.995% +1.826% +0.062% +0.094% 6#silesia.tar: +0.976% +1.777% +0.065% +0.104% 7#silesia.tar: +0.910% +1.738% +0.077% +0.110% --- lib/common/zstd_internal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index c1647689b..791b6485d 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -168,7 +168,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); From a4b9ebcbebe551af315093f556250aacae1de33d Mon Sep 17 00:00:00 2001 From: Benjamin Gilbert Date: Fri, 20 Jun 2025 23:34:13 -0700 Subject: [PATCH 812/937] meson: drop unused variable --- build/meson/meson.build | 1 - 1 file changed, 1 deletion(-) diff --git a/build/meson/meson.build b/build/meson/meson.build index bae4d2501..a9768d43a 100644 --- a/build/meson/meson.build +++ b/build/meson/meson.build @@ -65,7 +65,6 @@ zstd_docdir = join_paths(zstd_datadir, 'doc', meson.project_name()) # Built-in options use_debug = get_option('debug') -buildtype = get_option('buildtype') default_library_type = get_option('default_library') # Custom options From 16e13ebdeb0cc29c90c4dd8884c366fdce7cd283 Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Sat, 21 Jun 2025 13:03:13 -0400 Subject: [PATCH 813/937] delete --- tests/bigdict.c | 132 ------------------------------------------------ 1 file changed, 132 deletions(-) delete mode 100644 tests/bigdict.c diff --git a/tests/bigdict.c b/tests/bigdict.c deleted file mode 100644 index 33c4ab8ea..000000000 --- a/tests/bigdict.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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. - */ - -#include -#include -#include -#include -#include -#include "datagen.h" -#include "mem.h" -#define ZSTD_STATIC_LINKING_ONLY -#include "zstd.h" - -static int -compress(ZSTD_CCtx* cctx, ZSTD_DCtx* dctx, - void* dst, size_t dstCapacity, - void const* src, size_t srcSize, - void* roundtrip, ZSTD_EndDirective end) -{ - ZSTD_inBuffer in = {src, srcSize, 0}; - ZSTD_outBuffer out = {dst, dstCapacity, 0}; - int ended = 0; - - while (!ended && (in.pos < in.size || out.pos > 0)) { - size_t rc; - out.pos = 0; - rc = ZSTD_compressStream2(cctx, &out, &in, end); - if (ZSTD_isError(rc)) - return 1; - if (end == ZSTD_e_end && rc == 0) - ended = 1; - { - ZSTD_inBuffer rtIn = {dst, out.pos, 0}; - ZSTD_outBuffer rtOut = {roundtrip, srcSize, 0}; - rc = 1; - while (rtIn.pos < rtIn.size || rtOut.pos > 0) { - rtOut.pos = 0; - rc = ZSTD_decompressStream(dctx, &rtOut, &rtIn); - if (ZSTD_isError(rc)) { - fprintf(stderr, "Decompression error: %s\n", ZSTD_getErrorName(rc)); - return 1; - } - if (rc == 0) - break; - } - if (ended && rc != 0) { - fprintf(stderr, "Frame not finished!\n"); - return 1; - } - } - } - - return 0; -} - -int main(int argc, const char** argv) -{ - ZSTD_CCtx* cctx = ZSTD_createCCtx(); - ZSTD_DCtx* dctx = ZSTD_createDCtx(); - const size_t dataSize = (size_t)1 << 30; - const size_t outSize = ZSTD_compressBound(dataSize); - const size_t bufferSize = (size_t)1 << 31; - char* buffer = (char*)malloc(bufferSize); - void* out = malloc(outSize); - void* roundtrip = malloc(dataSize); - int _exit_code = 1; - (void)argc; - (void)argv; - - if (!buffer || !out || !roundtrip || !cctx || !dctx) { - fprintf(stderr, "Allocation failure\n"); - goto cleanup; - } - - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 31))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, 1))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_overlapLog, 9))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_checksumFlag, 1))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_strategy, ZSTD_btopt))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_targetLength, 7))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_minMatch, 7))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_searchLog, 1))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, 10))) - goto cleanup; - if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_chainLog, 10))) - goto cleanup; - - if (ZSTD_isError(ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 31))) - goto cleanup; - - RDG_genBuffer(buffer, bufferSize, 1.0, 0.0, 0xbeefcafe); - - /* Compress 30 GB */ - { - int i; - for (i = 0; i < 10; ++i) { - fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_continue)) - goto cleanup; - } - } - fprintf(stderr, "Compressing 1 GB\n"); - if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) - goto cleanup; - - fprintf(stderr, "Success!\n"); - - _exit_code = 0; - -cleanup: - free(roundtrip); - free(out); - free(buffer); - ZSTD_freeCCtx(cctx); - ZSTD_freeDCtx(dctx); - return _exit_code; -} From 878be1c8f0260db5b028694da53bdd97635d8fc7 Mon Sep 17 00:00:00 2001 From: jinyaoguo Date: Sat, 21 Jun 2025 13:43:47 -0400 Subject: [PATCH 814/937] fix --- tests/largeDictionary.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/largeDictionary.c b/tests/largeDictionary.c index 30ff98d98..b824960fc 100644 --- a/tests/largeDictionary.c +++ b/tests/largeDictionary.c @@ -73,7 +73,6 @@ int main(int argc, const char** argv) int _exit_code = 1; (void)argc; (void)argv; - int _exit_code = 0; if (!buffer || !out || !roundtrip || !cctx || !dctx) { fprintf(stderr, "Allocation failure\n"); @@ -119,6 +118,7 @@ int main(int argc, const char** argv) if (compress(cctx, dctx, out, outSize, buffer, dataSize, roundtrip, ZSTD_e_end)) goto cleanup; + _exit_code = 0; fprintf(stderr, "Success!\n"); cleanup: @@ -128,5 +128,4 @@ cleanup: ZSTD_freeDCtx(dctx); ZSTD_freeCCtx(cctx); return _exit_code; - return _exit_code; } From d77a7b689546d62bb728caa2dd1d2d0f9820612d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 21 Jun 2025 10:55:34 -0700 Subject: [PATCH 815/937] added test-largeDictionary to dev-long CI script --- .github/workflows/dev-long-tests.yml | 8 ++++++++ tests/.gitignore | 1 + 2 files changed, 9 insertions(+) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index bf287857f..f92c777d0 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -56,6 +56,14 @@ jobs: make clean CFLAGS="-m32 -O2" make -j test V=1 + test-largeDictionary: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - name: largeDictionary + run: | + CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary + no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: diff --git a/tests/.gitignore b/tests/.gitignore index 311a8b5eb..0f155764b 100644 --- a/tests/.gitignore +++ b/tests/.gitignore @@ -5,6 +5,7 @@ fullbench-lib fuzzer fuzzer32 fuzzer-dll +largeDictionary zbufftest zbufftest32 zbufftest-dll From 2295826266c16d2e9e6d345ed67d513588eb967d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 21 Jun 2025 12:01:07 -0700 Subject: [PATCH 816/937] update tests duration indications --- .github/workflows/dev-long-tests.yml | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index f92c777d0..84eda4fa4 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -1,5 +1,5 @@ name: dev-long-tests -# Tests longer than 10mn +# Tests generally longer than 10mn concurrency: group: long-${{ github.ref }} @@ -12,6 +12,7 @@ on: permissions: read-all jobs: + # lasts ~7mn make-all: runs-on: ubuntu-latest steps: @@ -19,7 +20,7 @@ jobs: - name: make all run: make all - # lasts ~24mn + # lasts ~19mn make-test: runs-on: ubuntu-latest env: @@ -33,7 +34,7 @@ jobs: make -j zstd ./tests/test_process_substitution.bash ./zstd - # lasts ~26mn + # lasts ~16mn make-test-macos: runs-on: macos-latest steps: @@ -41,7 +42,7 @@ jobs: - name: make test on macos run: make test - # lasts ~24mn + # lasts ~10mn make-test-32bit: runs-on: ubuntu-latest env: @@ -56,6 +57,7 @@ jobs: make clean CFLAGS="-m32 -O2" make -j test V=1 + # lasts ~7mn test-largeDictionary: runs-on: ubuntu-latest steps: @@ -64,6 +66,7 @@ jobs: run: | CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary + # lasts ~9mn no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: @@ -71,6 +74,7 @@ jobs: - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest + # lasts ~8mn tsan-zstreamtest: runs-on: ubuntu-latest steps: @@ -85,7 +89,7 @@ jobs: - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream - # lasts ~15mn + # lasts ~11mn tsan-fuzztest: runs-on: ubuntu-latest steps: @@ -93,7 +97,6 @@ jobs: - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest - big-tests-zstreamtest32: runs-on: ubuntu-latest steps: @@ -104,7 +107,7 @@ jobs: make libc6install CC=clang make -C tests test-zstream32 FUZZER_FLAGS="--big-tests" - # lasts ~23mn + # lasts ~13mn gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: From 7b1b6a0d2da35d9b97aab060140d548e60503ccd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Jun 2025 06:24:00 +0000 Subject: [PATCH 817/937] Bump msys2/setup-msys2 from 2.27.0 to 2.28.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.27.0 to 2.28.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/61f9e5e925871ba6c9e3e8da24ede83ea27fa91f...40677d36a502eb2cf0fb808cc9dec31bf6152638) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.28.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 84eda4fa4..3fa971a34 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 + - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 31d44542f..53f640dae 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -485,7 +485,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 + - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 4baa2f555..6ffdb330a 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -26,7 +26,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - uses: msys2/setup-msys2@61f9e5e925871ba6c9e3e8da24ede83ea27fa91f # tag=v2.27.0 + - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 with: msystem: ${{ matrix.msystem }} install: make p7zip git mingw-w64-${{matrix.env}}-gcc From bd38fc2c5f21536bc523f9a42c5e642ea9407ae4 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Fri, 20 Jun 2025 15:29:17 +0000 Subject: [PATCH 818/937] AArch64: Enhance struct access in Huffman decode 2X MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the multi-stream multi-symbol Huffman decoder GCC generates suboptimal code - emitting more loads for HUF_DEltX2 struct member accesses. Forcing it to use 32-bit loads and bit arithmetic to extract the necessary parts (UBFX) improves the overall decode speed. Also avoid integer type conversions in the symbol decodes, which leads to better instruction selection in table lookup accesses. On AArch64 the decoder no longer runs into register-pressure limits, so we can simplify the hot path and improve throughput Decompression uplifts on a Neoverse V2 system, using Zstd-1.5.8 compiled with "-O3 -march=armv8.2-a+sve2": Clang-20 Clang-* GCC-13 GCC-14 GCC-15 1#silesia.tar: +0.820% +1.365% +2.480% +1.348% +0.987% 2#silesia.tar: +0.426% +0.784% +1.218% +0.665% +0.554% 3#silesia.tar: +0.112% +0.389% +0.508% +0.188% +0.261% * Requires Clang-21 support from LLVM commit hash `a53003fe23cb6c871e72d70ff2d3a075a7490da2` (Clang-21 hasn’t been released as of this writing) --- lib/decompress/huf_decompress.c | 90 ++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 41 deletions(-) diff --git a/lib/decompress/huf_decompress.c b/lib/decompress/huf_decompress.c index c7e342648..920206178 100644 --- a/lib/decompress/huf_decompress.c +++ b/lib/decompress/huf_decompress.c @@ -785,19 +785,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; \ @@ -816,11 +816,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: @@ -1603,57 +1603,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); + 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); - /* Decode one symbol from the final stream */ - HUF_4X2_DECODE_SYMBOL(3, 1); + /* In the 3-way case decode one symbol from the final stream. */ + HUF_4X2_DECODE_SYMBOL(3, HUF_4X2_3WAY); - /* 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. + /* 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: From a28e8182b1aa6e1e17bcdd099630ea67c4143d32 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Tue, 24 Jun 2025 11:26:58 +0000 Subject: [PATCH 819/937] AArch64: Improve ZSTD_decodeSequence performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LLVM's alias-analysis sometimes fails to see that a static-array member of a struct cannot alias other members. This patch: - Reduces array accesses via struct indirection to aid load/store alias analysis under Clang. - Converts dynamic array indexing into conditional-move arithmetic, eliminating branches and extra loads/stores on out-of-order CPUs. - Reloads the bitstream only when match-length bits are consumed (assuming each reload only needs to happen once per match-length read), improving branch-prediction rates. - Removes the UNLIKELY() hint, which recent compilers already handle well without cost. Decompression uplifts on a Neoverse V2 system, using Zstd-1.5.8 compiled with "-O3 -march=armv8.2-a+sve2": Clang-19 Clang-20 Clang-* GCC-14 GCC-15 1#silesia.tar: +11.556% +16.203% +0.240% +2.216% +7.891% 2#silesia.tar: +15.493% +21.140% -0.041% +2.850% +9.926% 3#silesia.tar: +16.887% +22.570% -0.183% +3.056% +10.660% 4#silesia.tar: +17.785% +23.315% -0.262% +3.343% +11.187% 5#silesia.tar: +18.125% +24.175% -0.466% +3.350% +11.228% 6#silesia.tar: +17.607% +23.339% -0.591% +3.175% +10.851% 7#silesia.tar: +17.463% +22.837% -0.486% +3.292% +10.868% * Requires Clang-21 support from LLVM commit hash `a53003fe23cb6c871e72d70ff2d3a075a7490da2` (Clang-21 hasn’t been released as of this writing) Co-authored by: David Sherwood, David.Sherwood@arm.com Ola Liljedahl, Ola.Liljedahl@arm.com --- lib/decompress/zstd_decompress_block.c | 127 +++++++++++++++++++++++-- 1 file changed, 119 insertions(+), 8 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index 6174a250b..b2ccd92a1 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1236,6 +1236,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 @@ -1244,7 +1248,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; @@ -1252,11 +1256,11 @@ 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 seq.matchLength = mlDInfo->baseValue; seq.litLength = llDInfo->baseValue; { U32 const ofBase = ofDInfo->baseValue; @@ -1275,10 +1279,116 @@ 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. + /* As GCC has better branch and block analyzers, sometimes it is only + * valuable to mark likeliness for Clang. + */ + + /* 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); + if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { + /* Always read extra bits, this keeps the logic simple, + * avoids branches, and avoids accidentally reading 0 bits. + */ + U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32; + offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); + BIT_reloadDStream(&seqState->DStream); + offset += BIT_readBitsFast(&seqState->DStream, extraBits); + } else { + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); + } + 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 (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) + BIT_reloadDStream(&seqState->DStream); + if (MEM_64bits() && (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*/); + + if (MEM_32bits()) + BIT_reloadDStream(&seqState->DStream); + + 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 */ + if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 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; + + U16 const llNext = llDInfo->nextState; + U16 const mlNext = mlDInfo->nextState; + U16 const ofNext = ofDInfo->nextState; + U32 const llnbBits = llDInfo->nbBits; + U32 const mlnbBits = mlDInfo->nbBits; + U32 const ofnbBits = ofDInfo->nbBits; + + 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. */ /* sequence */ @@ -1340,7 +1450,7 @@ 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 */ + /* 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 */ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ @@ -1348,6 +1458,7 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c BIT_reloadDStream(&seqState->DStream); } } +#endif /* defined(__aarch64__) */ return seq; } From 50f169411bf45e2cab1f221a5dcf3e97e273510d Mon Sep 17 00:00:00 2001 From: Rose Date: Mon, 26 May 2025 15:56:55 -0400 Subject: [PATCH 820/937] Remove redundant setting of allJobsCompleted to 1 This will do it automatically. --- lib/compress/zstdmt_compress.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 0f1fe6d74..6d6f8139b 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1268,8 +1268,7 @@ size_t ZSTDMT_initCStream_internal( if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */ ZSTDMT_waitForAllJobsCompleted(mtctx); - ZSTDMT_releaseAllJobResources(mtctx); - mtctx->allJobsCompleted = 1; + ZSTDMT_releaseAllJobResources(mtctx); /* Will set allJobsCompleted to 1 */ } mtctx->params = params; From 4efbd56749ff36a7238966e457029e5b64e7dbe3 Mon Sep 17 00:00:00 2001 From: Rose Date: Tue, 24 Jun 2025 14:05:08 -0400 Subject: [PATCH 821/937] Check for job before releasing ZSTDMT_freeCCtx calls ZSTDMT_releaseAllJobResources, but ZSTDMT_releaseAllJobResources may be called when ZSTDMT_freeCCtx is called when initialization fails, resulting in a NULL pointer dereference. --- lib/compress/zstdmt_compress.c | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/compress/zstdmt_compress.c b/lib/compress/zstdmt_compress.c index 0f1fe6d74..828d5723f 100644 --- a/lib/compress/zstdmt_compress.c +++ b/lib/compress/zstdmt_compress.c @@ -1008,18 +1008,20 @@ 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; From 40f64f34935737ed7af6ca727d6b240cba552f0a Mon Sep 17 00:00:00 2001 From: ZijianLi Date: Sun, 29 Jun 2025 15:33:50 +0800 Subject: [PATCH 822/937] add riscv rvv ci --- .github/workflows/dev-short-tests.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 53f640dae..c954353e2 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -461,6 +461,9 @@ jobs: if: ${{ matrix.name == 'RISC-V' }} run: | LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=128" make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=256" make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=512" make clean check - name: M68K if: ${{ matrix.name == 'M68K' }} run: | From 2c3f23b018c719451a69b043bb5eaaa28d4aa014 Mon Sep 17 00:00:00 2001 From: ZijianLi Date: Sun, 29 Jun 2025 15:36:25 +0800 Subject: [PATCH 823/937] fix dereferencing type-punned pointer error --- lib/compress/zstd_compress.c | 118 ++++++++++++++++++----------------- 1 file changed, 62 insertions(+), 56 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9b7aaf9f4..fc29b56ab 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7287,7 +7287,7 @@ static size_t convertSequences_noRepcodes( #elif defined ZSTD_ARCH_RISCV_RVV #include /* - * Convert `vl` sequences per iteration, using AVX2 intrinsics: + * Convert `vl` sequences per iteration, using RVV intrinsics: * - offset -> offBase = offset + 2 * - litLength -> (U16) litLength * - matchLength -> (U16)(matchLength - 3) @@ -7300,7 +7300,8 @@ static size_t convertSequences_noRepcodes( */ static 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); @@ -7310,62 +7311,68 @@ static size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* ZSTD_STATIC_ASSERT(offsetof(SeqDef, offBase) == 0); ZSTD_STATIC_ASSERT(offsetof(SeqDef, litLength) == 4); ZSTD_STATIC_ASSERT(offsetof(SeqDef, mlBase) == 6); - size_t vl = 0; + 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 int32_t*)&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); + 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); + 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( - (uint32_t*)&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); + // 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; + 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; @@ -7547,18 +7554,17 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) size_t i = 0; int found_terminator = 0; size_t vl_max = __riscv_vsetvlmax_e32m1(); + typedef uint32_t __attribute__((may_alias)) aliased_u32; vuint32m1_t v_lit_sum = __riscv_vmv_v_x_u32m1(0, vl_max); vuint32m1_t v_match_sum = __riscv_vmv_v_x_u32m1(0, vl_max); for (; i < nbSeqs; ) { size_t vl = __riscv_vsetvl_e32m2(nbSeqs - i); - ptrdiff_t stride = sizeof(ZSTD_Sequence); // 16 vuint32m2x4_t v_tuple = __riscv_vlseg4e32_v_u32m2x4( - (const int32_t*)&seqs[i], + (const aliased_u32*)((const void*)&seqs[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); From d04e7944dddd07962baa1f6e00c6cb0a92ca891c Mon Sep 17 00:00:00 2001 From: ZijianLi Date: Mon, 7 Jul 2025 23:07:39 +0800 Subject: [PATCH 824/937] add compiler version check. --- lib/common/compiler.h | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 6131ad068..410068de4 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -224,9 +224,17 @@ # if defined(__ARM_FEATURE_SVE2) # define ZSTD_ARCH_ARM_SVE2 # endif -# if defined(__riscv) && defined(__riscv_vector) -# define ZSTD_ARCH_RISCV_RVV -# endif +#if defined(__riscv) && defined(__riscv_vector) + #if defined(__GNUC__) + #if (__GNUC__ > 14 || (__GNUC__ == 14 && __GNUC_MINOR__ >= 1)) + #define ZSTD_ARCH_RISCV_RVV + #endif + #elif defined(__clang__) + #if __clang_major__ > 18 || (__clang_major__ == 18 && __clang_minor__ >= 1) + #define ZSTD_ARCH_RISCV_RVV + #endif + #endif +#endif # # if defined(ZSTD_ARCH_X86_AVX2) # include From 8e4400463adc7bc7633641d6a485cfef4f28bc31 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Tue, 8 Jul 2025 17:05:45 +0000 Subject: [PATCH 825/937] Improve ZSTD_get1BlockSummary Add a faster scalar implementation of ZSTD_get1BlockSummary which removes the data dependency of the accumulators in the hot loop to leverage the superscalar potential of recent out-of-order CPUs. The new algorithm leverages SWAR (SIMD Within A Register) methodology to exploit the capabilities of 64-bit architectures. It achieves this by packing two 32-bit data elements into a single 64-bit register, enabling parallel operations on these subcomponents while ensuring that the 32-bit boundaries prevent overflow, thereby optimizing computational efficiency. Corresponding unit tests are included. Relative performance to GCC-13 using: `./fullbench -b19 -l5 enwik5` Neoverse-V2 before after GCC-13: 100.000% 290.527% GCC-14: 100.000% 291.714% GCC-15: 99.914% 291.495% Clang-18: 148.072% 264.524% Clang-19: 148.075% 264.512% Clang-20: 148.062% 264.490% Cortex-A720 before after GCC-13: 100.000% 235.261% GCC-14: 101.064% 234.903% GCC-15: 112.977% 218.547% Clang-18: 127.135% 180.359% Clang-19: 127.149% 180.297% Clang-20: 127.154% 180.260% Co-authored by, Thomas Daubney --- lib/compress/zstd_compress.c | 101 ++++++++++++++++++++++++++++++----- tests/fuzzer.c | 83 ++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 13 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 9b7aaf9f4..16423f6ee 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7604,29 +7604,104 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) #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) { - size_t totalMatchSize = 0; - size_t litSize = 0; - size_t n; + /* 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); - for (n=0; n 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); - break; + goto _out; } } - if (n==nbSeqs) { - BlockSummary bs; + /* 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; - bs.blockSize = litSize + totalMatchSize; - bs.litSize = litSize; + 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; } } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index da380aced..8e30d207d 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -45,6 +45,7 @@ #include "zstd_internal.h" /* ZSTD_WORKSPACETOOLARGE_MAXDURATION, ZSTD_WORKSPACETOOLARGE_FACTOR, KB, MB */ #include "threading.h" /* ZSTD_pthread_create, ZSTD_pthread_join */ #include "compress/hist.h" /* HIST_count_wksp */ +#include "compress/zstd_compress_internal.h" /* ZSTD_get1BlockSummary */ /*-************************************ @@ -769,6 +770,86 @@ static void test_blockSplitter_incompressibleExpansionProtection(unsigned testNb DISPLAYLEVEL(3, "OK \n"); } +static unsigned test_get1BlockSummary(unsigned testNb) +{ + static const ZSTD_Sequence nseqs[] = { + { 10, 2, 4, 1 }, + { 20, 3, 5, 2 }, + { 30, 6, 8, 3 }, + { 40, 7, 9, 4 }, + { 50, 10, 12, 5 }, + { 60, 11, 13, 6 }, + { 0, 14, 0, 7 }, + { 70, 15, 17, 8 }, + { 80, 16, 18, 9 }, + { 90, 19, 21, 1 }, + { 99, 20, 22, 2 }, + }; + static const BlockSummary blocks[] = { + { 7, 104, 53 }, + { 6, 98, 51 }, + { 5, 90, 48 }, + { 4, 76, 42 }, + { 3, 60, 35 }, + { 2, 38, 25 }, + { 1, 14, 14 }, + }; + size_t i; + + DISPLAYLEVEL(3, "test%3u : ZSTD_get1BlockSummary with empty array : ", testNb++); + { + BlockSummary bs = ZSTD_get1BlockSummary(nseqs, 0); + CHECK_EQ(bs.nbSequences, ERROR(externalSequences_invalid)); + } + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3u : ZSTD_get1BlockSummary with 1 literal only : ", testNb++); + { + static const ZSTD_Sequence seqs[] = { { 0, 5, 0, 0 } }; + BlockSummary bs = ZSTD_get1BlockSummary(seqs, 1); + CHECK_EQ(bs.nbSequences, 1); + CHECK_EQ(bs.litSize, 5); + CHECK_EQ(bs.blockSize, 5); + } + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3u : ZSTD_get1BlockSummary with no terminator : ", testNb++); + { + static const ZSTD_Sequence seqs[] = { { 10, 2, 4, 0 }, { 20, 3, 5, 0 } }; + BlockSummary bs = ZSTD_get1BlockSummary(seqs, 2); + CHECK_EQ(bs.nbSequences, ERROR(externalSequences_invalid)); + } + DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3u : ZSTD_get1BlockSummary with rep ignored : ", testNb++); + { + static const ZSTD_Sequence seqs[] = { + { 10, 2, 4, 2 }, + { 10, 3, 5, 2 }, + { 0, 7, 0, 3 }, + }; + BlockSummary bs = ZSTD_get1BlockSummary(seqs, 3); + CHECK_EQ(bs.nbSequences, 3); + CHECK_EQ(bs.litSize, 2 + 3 + 7); + CHECK_EQ(bs.blockSize, (4 + 5) + (2 + 3 + 7)); + } + DISPLAYLEVEL(3, "OK \n"); + + assert(COUNTOF(nseqs) > COUNTOF(blocks)); + for (i = 0; i < COUNTOF(blocks); ++i) { + BlockSummary bs; + DISPLAYLEVEL(3, "test%3u : ZSTD_get1BlockSummary with %u inputs : ", + testNb++, (unsigned)(COUNTOF(nseqs) - i)); + bs = ZSTD_get1BlockSummary(nseqs + i, COUNTOF(nseqs) - i); + CHECK_EQ(bs.nbSequences, blocks[i].nbSequences); + CHECK_EQ(bs.litSize, blocks[i].litSize); + CHECK_EQ(bs.blockSize, blocks[i].blockSize); + DISPLAYLEVEL(3, "OK \n"); + } + + return testNb; +} + /* ============================================================= */ static int basicUnitTests(U32 const seed, double compressibility) @@ -4004,6 +4085,8 @@ static int basicUnitTests(U32 const seed, double compressibility) } DISPLAYLEVEL(3, "OK \n"); + testNb = test_get1BlockSummary(testNb); + DISPLAYLEVEL(3, "test%3i : ZSTD_compressSequencesAndLiterals : ", testNb++); { const size_t srcSize = 497000; From 07cd78d3668271cffc9b586d857455bf47aef4fb Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Tue, 8 Jul 2025 17:07:41 +0000 Subject: [PATCH 826/937] AArch64: Add Neon path for convertSequences_noRepcodes Add a 4-way Neon implementation for the convertSequences_noRepcodes function. Remove 'static' keywords from all of its implementations to be able to add unit tests. Relative performance to Clang-18 using: `./fullbench -b18 -l5 enwik5` Neoverse-V2 before after Clang-18: 100.000% 311.703% Clang-19: 100.191% 311.714% Clang-20: 100.181% 311.723% GCC-13: 107.520% 252.309% GCC-14: 107.652% 253.158% GCC-15: 107.674% 253.168% Cortex-A720 before after Clang-18: 100.000% 204.512% Clang-19: 102.825% 204.600% Clang-20: 102.807% 204.558% GCC-13: 110.668% 203.594% GCC-14: 110.684% 203.978% GCC-15: 102.864% 204.299% Co-authored by, Thomas Daubney --- lib/compress/zstd_compress.c | 142 +++++++++++++++++++++++++++++++++-- tests/fuzzer.c | 126 +++++++++++++++++++++++++++++++ 2 files changed, 262 insertions(+), 6 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 16423f6ee..008eaba35 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -56,6 +56,14 @@ # define ZSTD_HASHLOG3_MAX 17 #endif + +/*-************************************* +* Forward declarations +***************************************/ +size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, + size_t nbSequences); + + /*-************************************* * Helper functions ***************************************/ @@ -7118,7 +7126,7 @@ size_t ZSTD_compressSequences(ZSTD_CCtx* cctx, } -#if defined(__AVX2__) +#if defined(ZSTD_ARCH_X86_AVX2) #include /* AVX2 intrinsics */ @@ -7138,7 +7146,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) @@ -7298,7 +7306,7 @@ static size_t convertSequences_noRepcodes( * @returns > 0 if there is one long length (> 65535), * indicating the position, and type. */ -static size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) { +size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, size_t nbSequences) { size_t longLen = 0; /* RVV depends on the specific definition of target structures */ @@ -7375,9 +7383,131 @@ static size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* * 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_NEON) && (defined(__aarch64__) || defined(_M_ARM64)) -static size_t convertSequences_noRepcodes( +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) @@ -7388,7 +7518,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; diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 8e30d207d..0bc160efa 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -770,6 +770,130 @@ static void test_blockSplitter_incompressibleExpansionProtection(unsigned testNb DISPLAYLEVEL(3, "OK \n"); } +size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, + size_t nbSequences); + +static size_t convertSequences_noRepcodes_ref( + SeqDef* dstSeqs, + const ZSTD_Sequence* inSeqs, + size_t nbSequences) +{ + size_t longLen = 0; + size_t n; + for (n=0; n 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; +} + +static unsigned test_convertSequences_noRepcodes(unsigned seed, unsigned testNb) +{ + ZSTD_Sequence nsrc[12]; + SeqDef ndst[12], rdst[12]; + size_t ref, ret, i, j; + + seed += 0xDEADBEEF; + for (i = 0; i < COUNTOF(nsrc); ++i) { + seed = 48271 * ((unsigned)i + seed); + nsrc[i].offset = (seed & 0xFFFF) | 1; /* Offset shall not be zero. */ + seed = 48271 * ((unsigned)i + seed); + nsrc[i].litLength = seed & 0xFFFF; + seed = 48271 * ((unsigned)i + seed); + nsrc[i].matchLength = (seed & 0xFFFFFF) % (65536 + MINMATCH); + seed = 48271 * ((unsigned)i + seed); + nsrc[i].rep = seed & 0xFF; + } + + /* For near overflow and proper negative value handling. */ + nsrc[5].matchLength = 65535 + MINMATCH; + nsrc[6].litLength = 65535; + nsrc[6].matchLength = 0; + nsrc[7].litLength = 0; + nsrc[7].matchLength = MINMATCH; + + for (i = 0; i <= COUNTOF(nsrc); ++i) { + DISPLAYLEVEL(3, "test%3u : convertSequences_noRepcodes with %u inputs : ", + testNb++, (unsigned)i); + memset(ndst, 0, sizeof(ndst)); + memset(rdst, 0, sizeof(rdst)); + ref = convertSequences_noRepcodes_ref(rdst, nsrc, i); + ret = convertSequences_noRepcodes(ndst, nsrc, i); + CHECK_EQ(ret, ref); + CHECK_EQ(memcmp(rdst, ndst, sizeof(ndst)), 0); + DISPLAYLEVEL(3, "OK \n"); + } + + nsrc[7].matchLength = 65536 + MINMATCH; + for (i = 8; i <= COUNTOF(nsrc); ++i) { + DISPLAYLEVEL(3, "test%3u : convertSequences_noRepcodes with %u inputs and " + "matchLength overflow : ", + testNb++, (unsigned)i); + memset(ndst, 0, sizeof(ndst)); + memset(rdst, 0, sizeof(rdst)); + ref = convertSequences_noRepcodes_ref(rdst, nsrc, i); + ret = convertSequences_noRepcodes(ndst, nsrc, i); + CHECK_EQ(ret, ref); + CHECK_EQ(memcmp(rdst, ndst, sizeof(ndst)), 0); + DISPLAYLEVEL(3, "OK \n"); + + assert(COUNTOF(nsrc) > 8); + for (j = 4; j < 8; ++j) { + DISPLAYLEVEL(3, "test%3u : convertSequences_noRepcodes with %u inputs and " + "matchLength overflow #%u : ", + testNb++, (unsigned)i, (unsigned)(i - j)); + memset(ndst, 0, sizeof(ndst)); + memset(rdst, 0, sizeof(rdst)); + ref = convertSequences_noRepcodes_ref(rdst, nsrc + j, i - j); + ret = convertSequences_noRepcodes(ndst, nsrc + j, i - j); + CHECK_EQ(ret, ref); + CHECK_EQ(memcmp(rdst, ndst, sizeof(ndst)), 0); + DISPLAYLEVEL(3, "OK \n"); + } + } + nsrc[7].matchLength = 1; + + nsrc[7].litLength = 65536; + for (i = 8; i <= COUNTOF(nsrc); ++i) { + DISPLAYLEVEL(3, "test%3u : convertSequences_noRepcodes with %u inputs and " + "litLength overflow: ", + testNb++, (unsigned)i); + memset(ndst, 0, sizeof(ndst)); + memset(rdst, 0, sizeof(rdst)); + ref = convertSequences_noRepcodes_ref(rdst, nsrc, i); + ret = convertSequences_noRepcodes(ndst, nsrc, i); + CHECK_EQ(ret, ref); + CHECK_EQ(memcmp(rdst, ndst, sizeof(ndst)), 0); + DISPLAYLEVEL(3, "OK \n"); + + assert(COUNTOF(nsrc) > 8); + for (j = 4; j < 8; ++j) { + DISPLAYLEVEL(3, "test%3u : convertSequences_noRepcodes with %u inputs and " + "litLength overflow #%u: ", + testNb++, (unsigned)i, (unsigned)(i - j)); + memset(ndst, 0, sizeof(ndst)); + memset(rdst, 0, sizeof(rdst)); + ref = convertSequences_noRepcodes_ref(rdst, nsrc + j, i - j); + ret = convertSequences_noRepcodes(ndst, nsrc + j, i - j); + CHECK_EQ(ret, ref); + CHECK_EQ(memcmp(rdst, ndst, sizeof(ndst)), 0); + DISPLAYLEVEL(3, "OK \n"); + } + } + + return testNb; +} + static unsigned test_get1BlockSummary(unsigned testNb) { static const ZSTD_Sequence nseqs[] = { @@ -4085,6 +4209,8 @@ static int basicUnitTests(U32 const seed, double compressibility) } DISPLAYLEVEL(3, "OK \n"); + testNb = test_convertSequences_noRepcodes(seed, testNb); + testNb = test_get1BlockSummary(testNb); DISPLAYLEVEL(3, "test%3i : ZSTD_compressSequencesAndLiterals : ", testNb++); From 703f85573467da90f41d729117f75868b91be5cb Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Tue, 8 Jul 2025 17:09:09 +0000 Subject: [PATCH 827/937] AArch64: Enable optimized QEMU CI builds Add missing `-O3` flag to the compilation of AArch64 SVE2 builds executed by QEMU. This can decrease the CI job runtime considerably. --- .github/workflows/dev-short-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 53f640dae..af6a2997a 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -435,8 +435,8 @@ jobs: make clean LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests - CFLAGS="-march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check - CFLAGS="-march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests + CFLAGS="-O3 -march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j check + CFLAGS="-O3 -march=armv8.2-a+sve2" LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make -j -C tests test-cli-tests # This test is only compatible with standard libraries that support BTI (Branch Target Identification). # Unfortunately, the standard library provided on Ubuntu 24.04 does not have this feature enabled. # make clean From 7325384a68f7bfc321740acd662ffa8b43ffeaa7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 11 Jul 2025 10:29:07 -0700 Subject: [PATCH 828/937] removed VS2019 runners replaced by one vs2025 runner, which is badly named since it still running MSVC 2022, but it's a good test that shows that the matrix is able to handle multiple MSVC versions. --- .github/workflows/dev-short-tests.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 53f640dae..e8c663036 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -314,8 +314,7 @@ jobs: { name: "VS 2022 Win32 Debug", platform: Win32, configuration: Debug, toolset: v143, runner: "windows-2022", arch: "" }, { name: "VS 2022 x64 Release", platform: x64, configuration: Release, toolset: v143, runner: "windows-2022", arch: ""}, { name: "VS 2022 Win32 Release", platform: Win32, configuration: Release, toolset: v143, runner: "windows-2022", arch: ""}, - { name: "VS 2019 x64 Release", platform: Win32, configuration: Release, toolset: v142, runner: "windows-2019", arch: ""}, - { name: "VS 2019 Win32 Release", platform: x64, configuration: Release, toolset: v142, runner: "windows-2019", arch: ""}, + { name: "VS 2025 x64 Debug", platform: x64, configuration: Debug, toolset: v143, runner: "windows-2025", arch: ""}, { name: "VS 2022 x64 Release AVX2", platform: x64, configuration: Release, toolset: v143, runner: "windows-2022", arch: "AdvancedVectorExtensions2" }, ] runs-on: ${{matrix.runner}} From 534860c90b7e3bd605ea94bdde176baaaa3be9fb Mon Sep 17 00:00:00 2001 From: ZijianLi Date: Sun, 13 Jul 2025 10:46:00 +0800 Subject: [PATCH 829/937] add -DMEM_FORCE_MEMORY_ACCESS=0 in CI RVV test --- .github/workflows/dev-short-tests.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index c954353e2..97fc3ffa6 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -461,9 +461,9 @@ jobs: if: ${{ matrix.name == 'RISC-V' }} run: | LDFLAGS="-static" CC=$XCC QEMU_SYS=$XEMU make clean check - CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=128" make clean check - CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=256" make clean check - CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=512" make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static -DMEM_FORCE_MEMORY_ACCESS=0" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=128" make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static -DMEM_FORCE_MEMORY_ACCESS=0" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=256" make clean check + CFLAGS="-march=rv64gcv -O3" LDFLAGS="-static -DMEM_FORCE_MEMORY_ACCESS=0" CC=$XCC QEMU_SYS="$XEMU -cpu rv64,v=true,vlen=512" make clean check - name: M68K if: ${{ matrix.name == 'M68K' }} run: | From 3ce4d1cba3d61fa95099621a161cf8a5945cf19b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 14 Jul 2025 06:27:46 +0000 Subject: [PATCH 830/937] Bump cygwin/cygwin-install-action from 5 to 6 Bumps [cygwin/cygwin-install-action](https://github.com/cygwin/cygwin-install-action) from 5 to 6. - [Release notes](https://github.com/cygwin/cygwin-install-action/releases) - [Commits](https://github.com/cygwin/cygwin-install-action/compare/f61179d72284ceddc397ed07ddb444d82bf9e559...f2009323764960f80959895c7bc3bb30210afe4d) --- updated-dependencies: - dependency-name: cygwin/cygwin-install-action dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index e8c663036..1b524392a 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -541,7 +541,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 - - uses: cygwin/cygwin-install-action@f61179d72284ceddc397ed07ddb444d82bf9e559 # tag=v5 + - uses: cygwin/cygwin-install-action@f2009323764960f80959895c7bc3bb30210afe4d # tag=v6 with: platform: x86_64 packages: >- From 0055ce7a02cb39b55ffc6bc468641ecbb65e90a4 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 18 Jul 2025 21:21:47 -0700 Subject: [PATCH 831/937] simplify sequence resolution in zstd_opt initially hinted by @pitaj in #4442 --- lib/compress/zstd_opt.c | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/lib/compress/zstd_opt.c b/lib/compress/zstd_opt.c index 3d7171b75..562a6b17b 100644 --- a/lib/compress/zstd_opt.c +++ b/lib/compress/zstd_opt.c @@ -1382,16 +1382,8 @@ _shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */ 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; From 3b23f0c673ceb365fe2d28e00f40246fce5e0e8e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Jul 2025 14:54:18 -0700 Subject: [PATCH 832/937] added android cmake build is expecte to fail, due to #4444 --- .github/workflows/android-ndk-build.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 7ba3958b8..395359fda 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -37,3 +37,14 @@ jobs: RANLIB=llvm-ranlib \ STRIP=llvm-strip + - name: Build with CMake and NDK + run: | + mkdir -p build-android + cd build-android + cmake --version + cmake ../build/cmake \ + -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ + -DANDROID_ABI=arm64-v8a \ + -DANDROID_PLATFORM=android-21 \ + -DCMAKE_BUILD_TYPE=Release + cmake --build . --parallel From 96f316a246b2274616e10c1e5e51256756a3d2f0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Jul 2025 06:30:43 +0000 Subject: [PATCH 833/937] Bump github/codeql-action from 3.28.9 to 3.29.4 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.29.4. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...4e828ff8d448a8a6e532957b1811f387a63867e8) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 3.29.4 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 47d528503..d49f3e836 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # tag=v3.28.9 + uses: github/codeql-action/upload-sarif@4e828ff8d448a8a6e532957b1811f387a63867e8 # tag=v3.29.4 with: sarif_file: results.sarif From 8bca04ba9f2c3bc53b9bd4973875a55f8ed5583f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 23 Jul 2025 15:59:23 -0700 Subject: [PATCH 834/937] regroup list of OSes for install inside common variable within lib/install_oses.mk. fixes #4445 --- Makefile | 5 ++++- lib/Makefile | 14 +++++++------- lib/install_oses.mk | 17 +++++++++++++++++ lib/libzstd.mk | 5 ++++- programs/Makefile | 16 ++++++++-------- 5 files changed, 40 insertions(+), 17 deletions(-) create mode 100644 lib/install_oses.mk diff --git a/Makefile b/Makefile index c9a640cba..b726f7970 100644 --- a/Makefile +++ b/Makefile @@ -144,10 +144,13 @@ clean: $(Q)$(RM) -r lz4 cmakebuild mesonbuild install @echo Cleaning completed +LIBZSTD_MK_DIR = $(ZSTDDIR) +include $(LIBZSTD_MK_DIR)/install_oses.mk # UNAME, INSTALL_OS_LIST + #------------------------------------------------------------------------------ # make install is validated only for Linux, macOS, Hurd and some BSD targets #------------------------------------------------------------------------------ -ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD DragonFly NetBSD MSYS_NT% CYGWIN_NT% Haiku AIX,$(shell sh -c 'MSYSTEM="MSYS" uname') )) +ifneq (,$(filter $(INSTALL_OS_LIST),$(UNAME))) HOST_OS = POSIX diff --git a/lib/Makefile b/lib/Makefile index e9a50a8f7..569bd6090 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -128,7 +128,7 @@ $(ZSTD_STATICLIB): $(ZSTD_STATICLIB_OBJ) $(AR) $(ARFLAGS) $@ $^ libzstd.a: $(ZSTD_STATICLIB) - cp -f $< $@ + $(CP) $< $@ endif @@ -168,11 +168,11 @@ $(ZSTD_DYNLIB): $(ZSTD_DYNLIB_OBJ) @echo compiling single-threaded dynamic library $(LIBVER)) $(CC) $(FLAGS) $^ $(SONAME_FLAGS) -o $@ @echo creating versioned links - ln -sf $@ libzstd.$(SHARED_EXT_MAJOR) - ln -sf $@ libzstd.$(SHARED_EXT) + $(LN) -sf $@ libzstd.$(SHARED_EXT_MAJOR) + $(LN) -sf $@ libzstd.$(SHARED_EXT) $(LIBZSTD): $(ZSTD_DYNLIB) - cp -f $< $@ + $(CP) $< $@ endif # ifndef BUILD_DIR endif # if windows @@ -268,7 +268,7 @@ clean: #----------------------------------------------------------------------------- # make install is validated only for below listed environments #----------------------------------------------------------------------------- -ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT% CYGWIN_NT%,$(UNAME))) +ifneq (,$(filter $(INSTALL_OS_LIST),$(UNAME))) lib: libzstd.pc @@ -363,8 +363,8 @@ install-shared: [ -e $(DESTDIR)$(LIBDIR) ] || $(INSTALL) -d -m 755 $(DESTDIR)$(LIBDIR)/ @echo Installing shared library $(INSTALL_PROGRAM) $(LIBZSTD) $(DESTDIR)$(LIBDIR) - ln -sf $(LIBZSTD) $(DESTDIR)$(LIBDIR)/libzstd.$(SHARED_EXT_MAJOR) - ln -sf $(LIBZSTD) $(DESTDIR)$(LIBDIR)/libzstd.$(SHARED_EXT) + $(LN) -sf $(LIBZSTD) $(DESTDIR)$(LIBDIR)/libzstd.$(SHARED_EXT_MAJOR) + $(LN) -sf $(LIBZSTD) $(DESTDIR)$(LIBDIR)/libzstd.$(SHARED_EXT) .PHONY: install-includes install-includes: diff --git a/lib/install_oses.mk b/lib/install_oses.mk new file mode 100644 index 000000000..c2cdd1635 --- /dev/null +++ b/lib/install_oses.mk @@ -0,0 +1,17 @@ +# ################################################################ +# 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. +# ################################################################ + +# This included Makefile provides the following variables : +# UNAME, INSTALL_OS_LIST + +UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') + +# List of OSes for which target install is supported +INSTALL_OS_LIST ?= Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT% CYGWIN_NT% diff --git a/lib/libzstd.mk b/lib/libzstd.mk index 91bd4caf3..d1744973e 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -206,7 +206,10 @@ endif endif CPPFLAGS += -DZSTD_LEGACY_SUPPORT=$(ZSTD_LEGACY_SUPPORT) -UNAME := $(shell sh -c 'MSYSTEM="MSYS" uname') +# Include install_oses.mk from the same directory +include $(dir $(lastword $(MAKEFILE_LIST)))/install_oses.mk +LN ?= ln +CP ?= cp -f ifndef BUILD_DIR ifeq ($(UNAME), Darwin) diff --git a/programs/Makefile b/programs/Makefile index f4af5e981..94f2179d0 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -170,7 +170,7 @@ endif zstd : $(BUILD_DIR)/zstd if [ $(BIN_ISDIFFERENT) -eq 1 ]; then \ - cp -f $<$(EXT) $@$(EXT); \ + $(CP) $<$(EXT) $@$(EXT); \ echo zstd build completed; \ else \ echo zstd already built; \ @@ -271,7 +271,7 @@ zstd-dictBuilder: $(ZSTDLIB_COMMON_SRC) $(ZSTDLIB_COMPRESS_SRC) $(ZDICT_SRC) zst CLEAN += zstdmt zstdmt: zstd - ln -sf zstd zstdmt + $(LN) -sf zstd zstdmt .PHONY: generate_res generate_res: $(RES64_FILE) $(RES32_FILE) @@ -345,7 +345,7 @@ include $(wildcard $(DEPFILES)) #----------------------------------------------------------------------------- # make install is validated only for Linux, macOS, BSD, Hurd and Solaris targets #----------------------------------------------------------------------------- -ifneq (,$(filter Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS Haiku AIX MSYS_NT% CYGWIN_NT%,$(UNAME))) +ifneq (,$(filter $(INSTALL_OS_LIST),$(UNAME))) HAVE_COLORNEVER = $(shell echo a | egrep --color=never a > /dev/null 2> /dev/null && echo 1 || echo 0) EGREP_OPTIONS ?= @@ -414,15 +414,15 @@ install: [ -e $(DESTDIR)$(MAN1DIR) ] || $(INSTALL) -d -m 755 $(DESTDIR)$(MAN1DIR)/ @echo Installing binaries $(INSTALL_PROGRAM) zstd$(EXT) $(DESTDIR)$(BINDIR)/zstd$(EXT) - ln -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/zstdcat$(EXT) - ln -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/unzstd$(EXT) - ln -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/zstdmt$(EXT) + $(LN) -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/zstdcat$(EXT) + $(LN) -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/unzstd$(EXT) + $(LN) -sf zstd$(EXT) $(DESTDIR)$(BINDIR)/zstdmt$(EXT) $(INSTALL_SCRIPT) zstdless $(DESTDIR)$(BINDIR)/zstdless $(INSTALL_SCRIPT) zstdgrep $(DESTDIR)$(BINDIR)/zstdgrep @echo Installing man pages $(INSTALL_MAN) zstd.1 $(DESTDIR)$(MAN1DIR)/zstd.1 - ln -sf zstd.1 $(DESTDIR)$(MAN1DIR)/zstdcat.1 - ln -sf zstd.1 $(DESTDIR)$(MAN1DIR)/unzstd.1 + $(LN) -sf zstd.1 $(DESTDIR)$(MAN1DIR)/zstdcat.1 + $(LN) -sf zstd.1 $(DESTDIR)$(MAN1DIR)/unzstd.1 $(INSTALL_MAN) zstdgrep.1 $(DESTDIR)$(MAN1DIR)/zstdgrep.1 $(INSTALL_MAN) zstdless.1 $(DESTDIR)$(MAN1DIR)/zstdless.1 @echo zstd installation completed From 1e1db4732380530c01868837436f77defe49b7cb Mon Sep 17 00:00:00 2001 From: Margen67 Date: Sun, 17 Aug 2025 00:44:39 -0700 Subject: [PATCH 835/937] Remove need for trailing forward slash in dir --- contrib/premake/zstd.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/premake/zstd.lua b/contrib/premake/zstd.lua index df1ace3ee..f3fd5b293 100644 --- a/contrib/premake/zstd.lua +++ b/contrib/premake/zstd.lua @@ -2,6 +2,7 @@ -- Basic usage: project_zstd(ZSTD_DIR) function project_zstd(dir, compression, decompression, deprecated, dictbuilder, legacy) + if string.sub(dir, -1, 1) ~= '/' then dir = dir .. '/' end if compression == nil then compression = true end if decompression == nil then decompression = true end if deprecated == nil then deprecated = false end From 0e69452a30c9fa51282baaf8050197bda070aab1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 18 Aug 2025 08:13:07 +0000 Subject: [PATCH 836/937] Bump actions/checkout from 4 to 5 Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5. - [Release notes](https://github.com/actions/checkout/releases) - [Commits](https://github.com/actions/checkout/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- .github/workflows/cmake-tests.yml | 8 +- .github/workflows/commit.yml | 6 +- .github/workflows/dev-long-tests.yml | 54 ++++++------- .github/workflows/dev-short-tests.yml | 76 +++++++++---------- .github/workflows/nightly.yml | 2 +- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/release_check.yml | 4 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 10 files changed, 79 insertions(+), 79 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 395359fda..330d58ffe 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: Set up JDK 17 uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index b02385708..0ce2a7d8f 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -28,7 +28,7 @@ jobs: name: "CMake Ubuntu Basic Build" runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: Install dependencies run: | sudo apt install liblzma-dev # Required for compression algorithms @@ -58,7 +58,7 @@ jobs: env: SRC_DIR: "source directory with spaces" steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 with: path: "${{ env.SRC_DIR }}" - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 @@ -116,7 +116,7 @@ jobs: runner: "windows-2022" cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - name: "Configure CMake (${{ matrix.name }})" @@ -141,7 +141,7 @@ jobs: name: "CMake macOS ARM64 (Apple Silicon)" runs-on: macos-14 # ARM64 runner steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: "CMake build and test (ARM64)" run: | # Configure and build with ARM64-specific optimizations diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 659072861..fe91f2fcc 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -17,7 +17,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Install Dependencies run: | sudo apt-get update @@ -40,7 +40,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Install Dependencies run: | sudo apt-get update @@ -73,7 +73,7 @@ jobs: env: CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: restore_cache uses: actions/cache@v4 with: diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 3fa971a34..caf86a11f 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -16,7 +16,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: make all run: make all @@ -27,7 +27,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: make test run: | make test @@ -38,7 +38,7 @@ jobs: make-test-macos: runs-on: macos-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: make test on macos run: make test @@ -49,7 +49,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update @@ -61,7 +61,7 @@ jobs: test-largeDictionary: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: largeDictionary run: | CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary @@ -70,7 +70,7 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest @@ -78,14 +78,14 @@ jobs: tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream uasan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream @@ -93,14 +93,14 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -111,7 +111,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -123,14 +123,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # tag=v4.2.2 + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Tue, 19 Aug 2025 09:23:38 -0400 Subject: [PATCH 837/937] Check for build environment instead of just _GNU_SOURCE Fixes the build on OpenBSD and NetBSD. It is too easy for _GNU_SOURCE to be defined even on non-Linux systems. Found via py-zstandard with the embedded copy of zstandard and Python defines _GNU_SOURCE. Also simplify the Linux checking, there is no need to check the rest of the symbol names. --- lib/dictBuilder/cover.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/dictBuilder/cover.c b/lib/dictBuilder/cover.c index 92c22a96c..06d1cb93a 100644 --- a/lib/dictBuilder/cover.c +++ b/lib/dictBuilder/cover.c @@ -21,10 +21,12 @@ /*-************************************* * Dependencies ***************************************/ -/* qsort_r is an extension. */ -#if defined(__linux) || defined(__linux__) || defined(linux) || defined(__gnu_linux__) || \ - defined(__CYGWIN__) || defined(__MSYS__) -# if !defined(_GNU_SOURCE) && !defined(__ANDROID__) /* NDK doesn't ship qsort_r(). */ +/* qsort_r is an extension. + * + * Android NDK does not ship qsort_r(). + */ +#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__CYGWIN__) || defined(__MSYS__) +# ifndef _GNU_SOURCE # define _GNU_SOURCE # endif #endif @@ -77,7 +79,7 @@ #ifndef ZDICT_QSORT # if defined(__APPLE__) # define ZDICT_QSORT ZDICT_QSORT_APPLE /* uses qsort_r() with a different order for parameters */ -# elif defined(_GNU_SOURCE) +# elif (defined(__linux__) && !defined(__ANDROID__)) || defined(__CYGWIN__) || defined(__MSYS__) # define ZDICT_QSORT ZDICT_QSORT_GNU /* uses qsort_r() */ # elif defined(_WIN32) && defined(_MSC_VER) # define ZDICT_QSORT ZDICT_QSORT_MSVC /* uses qsort_s() with a different order for parameters */ From ae64545c6b6257c226dca6240be7b2d345d9bee5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 19 Aug 2025 17:13:15 -0700 Subject: [PATCH 838/937] fixed a potential division by 0 in the cli trace unit --- programs/zstdcli_trace.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/programs/zstdcli_trace.c b/programs/zstdcli_trace.c index 35075a52c..f73071a5c 100644 --- a/programs/zstdcli_trace.c +++ b/programs/zstdcli_trace.c @@ -81,8 +81,9 @@ static void TRACE_log(char const* method, PTime duration, ZSTD_Trace const* trac { int level = 0; int workers = 0; + double const durationAsDouble = duration ? (double)duration : .1; double const ratio = (double)trace->uncompressedSize / (double)trace->compressedSize; - double const speed = ((double)trace->uncompressedSize * 1000) / (double)duration; + double const speed = ((double)trace->uncompressedSize * 1000) / durationAsDouble; if (trace->params) { ZSTD_CCtxParams_getParameter(trace->params, ZSTD_c_compressionLevel, &level); ZSTD_CCtxParams_getParameter(trace->params, ZSTD_c_nbWorkers, &workers); From 42243c3d465e5f8930a0938f5c5dbb260c3da800 Mon Sep 17 00:00:00 2001 From: Thirumalai Nagalingam Date: Wed, 20 Aug 2025 17:12:05 +0530 Subject: [PATCH 839/937] CI: Update build_package.bat for CMake builds --- lib/dll/example/build_package.bat | 33 ++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/lib/dll/example/build_package.bat b/lib/dll/example/build_package.bat index 5a03bdf25..bd3103de5 100644 --- a/lib/dll/example/build_package.bat +++ b/lib/dll/example/build_package.bat @@ -1,10 +1,16 @@ @echo off setlocal -rem Create required directories. +rem Detect build type based on available files +set BUILD_TYPE=make +if exist "build\cmake\build\lib\Release\zstd_static.lib" set BUILD_TYPE=cmake + +echo Detected build type: %BUILD_TYPE% + +rem Create required directories mkdir bin\dll bin\static bin\example bin\include -rem Copy files using a subroutine. Exits immediately on failure. +rem Copy common files using a subroutine. Exits immediately on failure. call :copyFile "tests\fullbench.c" "bin\example\" call :copyFile "programs\datagen.c" "bin\example\" call :copyFile "programs\datagen.h" "bin\example\" @@ -14,16 +20,29 @@ call :copyFile "lib\common\mem.h" "bin\example\" call :copyFile "lib\common\zstd_internal.h" "bin\example\" call :copyFile "lib\common\error_private.h" "bin\example\" call :copyFile "lib\common\xxhash.h" "bin\example\" -call :copyFile "lib\libzstd.a" "bin\static\libzstd_static.lib" -call :copyFile "lib\dll\libzstd.*" "bin\dll\" call :copyFile "lib\dll\example\Makefile" "bin\example\" call :copyFile "lib\dll\example\fullbench-dll.*" "bin\example\" -call :copyFile "lib\dll\example\README.md" "bin\" call :copyFile "lib\zstd.h" "bin\include\" call :copyFile "lib\zstd_errors.h" "bin\include\" call :copyFile "lib\zdict.h" "bin\include\" -call :copyFile "programs\zstd.exe" "bin\zstd.exe" +rem Copy build-specific files +if "%BUILD_TYPE%"=="cmake" ( + echo Copying CMake build artifacts... + call :copyFile "build\cmake\build\lib\Release\zstd_static.lib" "bin\static\libzstd_static.lib" + call :copyFile "build\cmake\build\lib\Release\zstd.dll" "bin\dll\libzstd.dll" + call :copyFile "build\cmake\build\lib\Release\zstd.lib" "bin\dll\zstd.lib" + call :copyFile "build\cmake\build\programs\Release\zstd.exe" "bin\zstd.exe" + call :copyFile "lib\dll\example\README.md" "bin\README.md" +) else ( + echo Copying Make build artifacts... + call :copyFile "lib\libzstd.a" "bin\static\libzstd_static.lib" + call :copyFile "lib\dll\libzstd.*" "bin\dll\" + call :copyFile "programs\zstd.exe" "bin\zstd.exe" + call :copyFile "lib\dll\example\README.md" "bin\" +) + +echo Build package created successfully for %BUILD_TYPE% build! endlocal exit /b 0 @@ -33,4 +52,4 @@ if errorlevel 1 ( echo Failed to copy "%~1" exit 1 ) -exit /b +exit /b \ No newline at end of file From 002c227596c3f14ffc4e10d0851e021c6bef2324 Mon Sep 17 00:00:00 2001 From: Thirumalai Nagalingam Date: Wed, 20 Aug 2025 17:12:21 +0530 Subject: [PATCH 840/937] CI: Add CI setup for packaging Win-ARM64 artifacts --- .github/workflows/windows-artifacts.yml | 138 +++++++++++++++--------- 1 file changed, 88 insertions(+), 50 deletions(-) diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 2a599d447..d097acf96 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -13,69 +13,107 @@ jobs: windows-artifacts: permissions: contents: write # to fetch code and upload artifacts - # see https://ariya.io/2020/07/on-github-actions-with-msys2 - runs-on: windows-latest - # see https://github.com/msys2/setup-msys2 + # For msys2, see https://ariya.io/2020/07/on-github-actions-with-msys2 + runs-on: ${{ matrix.shell == 'cmake' && 'windows-11-arm' || 'windows-latest' }} strategy: + # For msys2, see https://github.com/msys2/setup-msys2 matrix: include: - - { msystem: mingw64, env: x86_64, ziparch: win64 } - - { msystem: mingw32, env: i686, ziparch: win32 } + - { msystem: mingw64, env: x86_64, ziparch: win64, shell: msys2 } + - { msystem: mingw32, env: i686, ziparch: win32, shell: msys2 } + - { msystem: null, env: arm64, ziparch: win-arm64, shell: cmake } + defaults: run: - shell: msys2 {0} + shell: ${{ matrix.shell == 'cmake' && 'pwsh' || 'msys2 {0}' }} + steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 - with: - msystem: ${{ matrix.msystem }} - install: make p7zip git mingw-w64-${{matrix.env}}-gcc - update: true + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - - name: display versions - run: | - make -v - cc -v + # MSYS2 setup + - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 + if: matrix.shell == 'msys2' + with: + msystem: ${{ matrix.msystem }} + install: make p7zip git mingw-w64-${{matrix.env}}-gcc + update: true - - name: Building zlib to static link - run: | - git clone --depth 1 --branch v1.3.1 https://github.com/madler/zlib - make -C zlib -f win32/Makefile.gcc libz.a + - name: display versions (MSYS2) + if: matrix.shell == 'msys2' + run: | + make -v + cc -v - - name: Building lz4 to static link - run: | - git clone --depth 1 --branch v1.10.0 https://github.com/lz4/lz4 - # ensure both libraries use the same version of libxxhash - cp lib/common/xxhash.* lz4/lib - CPPFLAGS=-DXXH_NAMESPACE=LZ4_ make -C lz4/lib liblz4.a V=1 + - name: display versions (CMake) + if: matrix.shell == 'cmake' + run: | + cmake --version - - name: Building zstd programs - run: | - CPPFLAGS="-I../zlib -I../lz4/lib" LDFLAGS=-static make -j allzstd V=1 HAVE_ZLIB=1 HAVE_LZ4=1 HAVE_LZMA=0 LDLIBS="../zlib/libz.a ../lz4/lib/liblz4.a" + # Build dependencies (MSYS2 only) + - name: Building zlib to static link + if: matrix.shell == 'msys2' + run: | + git clone --depth 1 --branch v1.3.1 https://github.com/madler/zlib + make -C zlib -f win32/Makefile.gcc libz.a - - name: Create artifacts - run: | - ./lib/dll/example/build_package.bat || exit 1 - mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + - name: Building lz4 to static link + if: matrix.shell == 'msys2' + run: | + git clone --depth 1 --branch v1.10.0 https://github.com/lz4/lz4 + # ensure both libraries use the same version of libxxhash + cp lib/common/xxhash.* lz4/lib + CPPFLAGS=-DXXH_NAMESPACE=LZ4_ make -C lz4/lib liblz4.a V=1 - - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 - with: - compression-level: 9 # maximum compression - if-no-files-found: error # defaults to `warn` - path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - name: zstd-${{ github.ref_name }}-${{matrix.ziparch}} + # Build zstd + - name: Building zstd programs + if: matrix.shell == 'msys2' + run: | + CPPFLAGS="-I../zlib -I../lz4/lib" LDFLAGS=-static make -j allzstd V=1 HAVE_ZLIB=1 HAVE_LZ4=1 HAVE_LZMA=0 LDLIBS="../zlib/libz.a ../lz4/lib/liblz4.a" - - name: Package artifact for upload - run: | - 7z a -tzip -mx9 "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip')" "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}')" + - name: Build zstd (CMake ARM64) + if: matrix.shell == 'cmake' + run: | + cd build\cmake + mkdir build + cd build + cmake.exe -G "Visual Studio 17 2022" -A ARM64 -DCMAKE_BUILD_TYPE=Release -DZSTD_BUILD_PROGRAMS=ON -DZSTD_BUILD_SHARED=ON -DZSTD_BUILD_STATIC=ON .. + cmake.exe --build . --config Release --parallel - - name: Upload release asset - if: github.event_name == 'release' - shell: pwsh - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh release upload "${{ github.ref_name }}" "$env:GITHUB_WORKSPACE/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip" --clobber + - name: Create artifacts (MSYS2) + if: matrix.shell == 'msys2' + run: | + ./lib/dll/example/build_package.bat || exit 1 + mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + - name: Create artifacts (CMake) + if: matrix.shell == 'cmake' + run: | + .\lib\dll\example\build_package.bat + if ($LASTEXITCODE -ne 0) { exit 1 } + mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection + uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 + with: + compression-level: 9 # maximum compression + if-no-files-found: error # defaults to `warn` + path: ${{ github.workspace }}/zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ + name: zstd-${{ github.ref_name }}-${{matrix.ziparch}} + + - name: Package artifact for upload (MSYS2) + if: matrix.shell == 'msys2' + run: | + 7z a -tzip -mx9 "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip')" "$(cygpath -u '${{ github.workspace }}/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}')" + + - name: Package artifact for upload (CMake) + if: matrix.shell == 'cmake' + run: | + Compress-Archive -Path "zstd-${{ github.ref_name }}-${{ matrix.ziparch }}" -DestinationPath "zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip" -CompressionLevel Optimal + + - name: Upload release asset + if: github.event_name == 'release' + shell: pwsh + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release upload "${{ github.ref_name }}" "$env:GITHUB_WORKSPACE/zstd-${{ github.ref_name }}-${{ matrix.ziparch }}.zip" --clobber \ No newline at end of file From 076283fa8870224876df0b5098a241f57c507453 Mon Sep 17 00:00:00 2001 From: Thirumalai Nagalingam Date: Wed, 20 Aug 2025 17:19:48 +0530 Subject: [PATCH 841/937] CI: Enable MSVC ARM64 job using Github WOA runner - Reintroduce the MSVC ARM64 build configuration with "Visual Studio 17 2022" - Update runner to `windows-11-arm` (GitHub-hosted Windows on ARM) --- .github/workflows/cmake-tests.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 0ce2a7d8f..f1ed1f850 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -96,10 +96,10 @@ jobs: runner: "windows-2022" # Intentionally omit ZSTD_BUILD_TESTS to reproduce the CXX language configuration bug cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON" - # - generator: "Visual Studio 17 2022" - # flags: "-A ARM64" - # name: "MSVC ARM64" - # runner: "windows-2022-arm64" # Disabled due to very long queue times + - generator: "Visual Studio 17 2022" + flags: "-A ARM64" + name: "MSVC ARM64" + runner: "windows-11-arm" # githuh runner for WOA instance - generator: "MinGW Makefiles" flags: "" name: "MinGW" From 2849f3a5d1497a0b84d613f03949315a5b430153 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Thu, 17 Jul 2025 07:46:01 +0000 Subject: [PATCH 842/937] AArch64: Add SVE2 path for convertSequences_noRepcodes Add an 8-way vector length agnostic (VLA) SVE2 code path for convertSequences_noRepcodes. It works with any SVE vector length. Relative performance to GCC-13 using: `./fullbench -b18 -l5 enwik5` Neon SVE2 Neoverse-V2 before after uplift GCC-13: 100.000% 103.209% 1.032x GCC-14: 100.309% 134.872% 1.344x GCC-15: 100.355% 134.827% 1.343x Clang-18: 123.614% 128.565% 1.040x Clang-19: 123.587% 132.984% 1.076x Clang-20: 123.629% 133.023% 1.075x Neon SVE2 Cortex-A720 before after uplift GCC-13: 100.000% 116.032% 1.160x GCC-14: 99.700% 116.648% 1.169x GCC-15: 100.354% 117.047% 1.166x Clang-18: 100.447% 116.762% 1.162x Clang-19: 100.454% 116.627% 1.160x Clang-20: 100.452% 116.649% 1.161x --- lib/compress/zstd_compress.c | 149 +++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 008eaba35..71884278d 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7383,6 +7383,155 @@ size_t convertSequences_noRepcodes(SeqDef* dstSeqs, const ZSTD_Sequence* inSeqs, * but since this implementation is targeting modern systems (>= Sapphire Rapid), * it's not useful to develop and maintain code for older pre-AVX2 platforms */ +#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); +} + +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( From 0ee187c540653da0ca39aebc9e934fbef702b82b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Aug 2025 09:00:57 +0000 Subject: [PATCH 843/937] Bump actions/setup-java from 4.7.1 to 5.0.0 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 4.7.1 to 5.0.0. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/c5195efecf7bdfc987ee8bae7a71cb8b11521c00...dded0888837ed1f317902acf8a20df0ad188d165) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 5.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 330d58ffe..99183049c 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - name: Set up JDK 17 - uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1 + uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0 with: java-version: '17' distribution: 'temurin' From ba59aeb67408c5ca6979e6d971915c86cfbcee90 Mon Sep 17 00:00:00 2001 From: Benjamin Gilbert Date: Thu, 28 Aug 2025 18:50:34 -0500 Subject: [PATCH 844/937] meson: Call meson.override_dependency() if Meson is new enough This tells Meson that we intend libzstd_dep to be used by a parent project if the parent looks for a dependency named "libzstd". Without this, the mapping from "libzstd" to our variable libzstd_dep must be encoded in the Meson wrap file or in the parent's meson.build. --- build/meson/lib/meson.build | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build/meson/lib/meson.build b/build/meson/lib/meson.build index d086fc2d7..81fc313f9 100644 --- a/build/meson/lib/meson.build +++ b/build/meson/lib/meson.build @@ -127,6 +127,10 @@ libzstd = library('zstd', libzstd_dep = declare_dependency(link_with: libzstd, include_directories: join_paths(zstd_rootdir,'lib')) # Do not expose private headers +if meson.version().version_compare('>=0.54.0') + meson.override_dependency('libzstd', libzstd_dep) +endif + # we link to both: # - the shared library (for public symbols) # - the static library (for private symbols) From 64c4288e9272c7b65f381d456e70eec35fc3cfd3 Mon Sep 17 00:00:00 2001 From: Jamie Lokier Date: Tue, 2 Sep 2025 16:44:09 +0100 Subject: [PATCH 845/937] Update manual about the default value of `-T#`/`--threads=#` The section about `ZSTD_NBTHREADS` already explains the default number of threads, since it changed from 1 (commit 17beeb5). But the option description for `-T#`/`--threads=#` incorrectly said the default was still 1. I noticed this when I found compression slower with `-T1` than without it. --- programs/zstd.1 | 2 +- programs/zstd.1.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/programs/zstd.1 b/programs/zstd.1 index 5503a5b86..e49a182d5 100644 --- a/programs/zstd.1 +++ b/programs/zstd.1 @@ -108,7 +108,7 @@ Display information related to a zstd compressed file, such as size, ratio, and \fB\-\-fast[=#]\fR: switch to ultra\-fast compression levels\. If \fB=#\fR is not present, it defaults to \fB1\fR\. The higher the value, the faster the compression speed, at the cost of some compression ratio\. This setting overwrites compression level if one was set previously\. Similarly, if a compression level is set after \fB\-\-fast\fR, it overrides it\. . .IP "\(bu" 4 -\fB\-T#\fR, \fB\-\-threads=#\fR: Compress using \fB#\fR working threads (default: 1)\. If \fB#\fR is 0, attempt to detect and use the number of physical CPU cores\. In all cases, the nb of threads is capped to \fBZSTDMT_NBWORKERS_MAX\fR, which is either 64 in 32\-bit mode, or 256 for 64\-bit environments\. This modifier does nothing if \fBzstd\fR is compiled without multithread support\. +\fB\-T#\fR, \fB\-\-threads=#\fR: Compress using \fB#\fR working threads (default: between 1 and 4 depending on physical CPU cores; see \fBZSTD_NBTHREADS\fR below)\. If \fB#\fR is 0, attempt to detect and use the number of physical CPU cores\. In all cases, the nb of threads is capped to \fBZSTDMT_NBWORKERS_MAX\fR, which is either 64 in 32\-bit mode, or 256 for 64\-bit environments\. This modifier does nothing if \fBzstd\fR is compiled without multithread support\. . .IP "\(bu" 4 \fB\-\-single\-thread\fR: Use a single thread for both I/O and compression\. As compression is serialized with I/O, this can be slightly slower\. Single\-thread mode features significantly lower memory usage, which can be useful for systems with limited amount of memory, such as 32\-bit systems\. diff --git a/programs/zstd.1.md b/programs/zstd.1.md index cf1810d59..bb9258d57 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -126,7 +126,7 @@ the last one takes effect. This setting overwrites compression level if one was set previously. Similarly, if a compression level is set after `--fast`, it overrides it. * `-T#`, `--threads=#`: - Compress using `#` working threads (default: 1). + Compress using `#` working threads (default: between 1 and 4 depending on physical CPU cores; see `ZSTD_NBTHREADS` below). If `#` is 0, attempt to detect and use the number of physical CPU cores. In all cases, the nb of threads is capped to `ZSTDMT_NBWORKERS_MAX`, which is either 64 in 32-bit mode, or 256 for 64-bit environments. From 1c5d45fc11529e72c78a8108bddeb794cca905b7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 2 Sep 2025 15:46:51 -0700 Subject: [PATCH 846/937] fixed -T# documentation in zstd -H provide the local value for default nbThreads which is dynamic and depends on local nb of cores. --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 124ea47aa..142fc4c53 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -233,7 +233,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n"); DISPLAYOUT(" --patch-apply Equivalent for `-d --patch-from` \n\n"); # ifdef ZSTD_MULTITHREAD - DISPLAYOUT(" -T# Spawn # compression threads. [Default: 1; pass 0 for core count.]\n"); + DISPLAYOUT(" -T# Spawn # compression threads. [Default: %i; pass 0 for core count.]\n", ZSTDCLI_NBTHREADS_DEFAULT); DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n"); DISPLAYOUT(" --auto-threads={physical|logical}\n"); DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n"); From 6551db345922c9b40aa48a8a57c9bfb48fd1855b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 2 Sep 2025 15:53:45 -0700 Subject: [PATCH 847/937] specify nb of threads used during benchmarking used to require `-v` (verbose) modifier --- programs/zstdcli.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 142fc4c53..e44384ea1 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1435,7 +1435,7 @@ int main(int argCount, const char* argv[]) if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel(); if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel(); if (cLevelLast < cLevel) cLevelLast = cLevel; - DISPLAYLEVEL(3, "Benchmarking "); + DISPLAYLEVEL(2, "Benchmarking "); if (filenames->tableSize > 1) DISPLAYLEVEL(3, "%u files ", (unsigned)filenames->tableSize); if (cLevelLast > cLevel) { @@ -1443,7 +1443,7 @@ int main(int argCount, const char* argv[]) } else { DISPLAYLEVEL(3, "at level %d ", cLevel); } - DISPLAYLEVEL(3, "using %i threads \n", nbWorkers); + DISPLAYLEVEL(2, "using %i threads \n", nbWorkers); if (filenames->tableSize > 0) { if(separateFiles) { unsigned i; From c41fc1aa01a4bbc4ccd6877f4d198e0c76eb122d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 2 Sep 2025 16:05:35 -0700 Subject: [PATCH 848/937] only display nbThread Msg in nbThreads > 1 --- programs/zstdcli.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index e44384ea1..cb87604b1 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1410,6 +1410,7 @@ int main(int argCount, const char* argv[]) /* Check if benchmark is selected */ if (operation==zom_bench) { #ifndef ZSTD_NOBENCH + int const benchThreadsMsgLevel = 2 + (nbWorkers <= 1); if (cType != FIO_zstdCompression) { DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n"); CLEAN_RETURN(1); @@ -1435,7 +1436,7 @@ int main(int argCount, const char* argv[]) if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel(); if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel(); if (cLevelLast < cLevel) cLevelLast = cLevel; - DISPLAYLEVEL(2, "Benchmarking "); + DISPLAYLEVEL(benchThreadsMsgLevel, "Benchmarking "); if (filenames->tableSize > 1) DISPLAYLEVEL(3, "%u files ", (unsigned)filenames->tableSize); if (cLevelLast > cLevel) { @@ -1443,7 +1444,7 @@ int main(int argCount, const char* argv[]) } else { DISPLAYLEVEL(3, "at level %d ", cLevel); } - DISPLAYLEVEL(2, "using %i threads \n", nbWorkers); + DISPLAYLEVEL(benchThreadsMsgLevel, "using %i threads \n", nbWorkers); if (filenames->tableSize > 0) { if(separateFiles) { unsigned i; From 725a152c7bf91244b0e16eabc312762a39dad583 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 2 Sep 2025 16:21:48 -0700 Subject: [PATCH 849/937] benchmark uses 1 thread by default --- programs/zstdcli.c | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index cb87604b1..696e4a1ba 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -47,7 +47,7 @@ #define ZSTDCLI_NBTHREADS_DEFAULT (unsigned)(MAX(1, MIN(4, UTIL_countLogicalCores() / 4))) #endif - +static unsigned init_nbWorkers(unsigned defaultNbWorkers); /*-************************************ * Constants @@ -95,6 +95,7 @@ static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT; #define DEFAULT_ACCEL 1 #define NBWORKERS_AUTOCPU 0 +#define NBWORKERS_UNSET UINT_MAX typedef enum { cover, fastCover, legacy } dictType; @@ -233,7 +234,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n"); DISPLAYOUT(" --patch-apply Equivalent for `-d --patch-from` \n\n"); # ifdef ZSTD_MULTITHREAD - DISPLAYOUT(" -T# Spawn # compression threads. [Default: %i; pass 0 for core count.]\n", ZSTDCLI_NBTHREADS_DEFAULT); + DISPLAYOUT(" -T# Spawn # compression threads. [Default: %u; pass 0 for core count.]\n", init_nbWorkers(ZSTDCLI_NBTHREADS_DEFAULT)); DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n"); DISPLAYOUT(" --auto-threads={physical|logical}\n"); DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n"); @@ -783,7 +784,7 @@ static int init_cLevel(void) { return ZSTDCLI_CLEVEL_DEFAULT; } -static unsigned init_nbWorkers(void) { +static unsigned init_nbWorkers(unsigned defaultNbWorkers) { #ifdef ZSTD_MULTITHREAD const char* const env = getenv(ENV_NBWORKERS); if (env != NULL) { @@ -792,7 +793,7 @@ static unsigned init_nbWorkers(void) { unsigned nbThreads; if (readU32FromCharChecked(&ptr, &nbThreads)) { DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBWORKERS, env); - return ZSTDCLI_NBTHREADS_DEFAULT; + return defaultNbWorkers; } else if (*ptr == 0) { return nbThreads; } @@ -800,7 +801,7 @@ static unsigned init_nbWorkers(void) { DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBWORKERS, env); } - return ZSTDCLI_NBTHREADS_DEFAULT; + return defaultNbWorkers; #else return 1; #endif @@ -881,7 +882,7 @@ int main(int argCount, const char* argv[]) ultra = 0, cLevelLast = MINCLEVEL - 1, /* for benchmark range */ setThreads_non1 = 0; - unsigned nbWorkers = init_nbWorkers(); + unsigned nbWorkers = init_nbWorkers(NBWORKERS_UNSET); ZSTD_ParamSwitch_e mmapDict = ZSTD_ps_auto; ZSTD_ParamSwitch_e useRowMatchFinder = ZSTD_ps_auto; FIO_compressionType_t cType = FIO_zstdCompression; @@ -1410,7 +1411,9 @@ int main(int argCount, const char* argv[]) /* Check if benchmark is selected */ if (operation==zom_bench) { #ifndef ZSTD_NOBENCH - int const benchThreadsMsgLevel = 2 + (nbWorkers <= 1); + int benchThreadsMsgLevel = 2; + if (nbWorkers == NBWORKERS_UNSET) nbWorkers = 1; + if (nbWorkers <= 1) benchThreadsMsgLevel = 3; if (cType != FIO_zstdCompression) { DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n"); CLEAN_RETURN(1); @@ -1471,6 +1474,7 @@ int main(int argCount, const char* argv[]) zParams.compressionLevel = dictCLevel; zParams.notificationLevel = (unsigned)g_displayLevel; zParams.dictID = dictID; + if (nbWorkers == NBWORKERS_UNSET) nbWorkers = init_nbWorkers(ZSTDCLI_NBTHREADS_DEFAULT); if (dict == cover) { int const optimize = !coverParams.k || !coverParams.d; coverParams.nbThreads = (unsigned)nbWorkers; @@ -1593,6 +1597,7 @@ int main(int argCount, const char* argv[]) #ifndef ZSTD_NOCOMPRESS FIO_setCompressionType(prefs, cType); FIO_setContentSize(prefs, contentSize); + if (nbWorkers == NBWORKERS_UNSET) nbWorkers = init_nbWorkers(ZSTDCLI_NBTHREADS_DEFAULT); FIO_setNbWorkers(prefs, (int)nbWorkers); FIO_setJobSize(prefs, (int)chunkSize); if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog); From 249e4a07d53415a8161ce5ad65a725ffd99060ac Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 2 Sep 2025 16:36:44 -0700 Subject: [PATCH 850/937] fixed minor unused variable warning in certain compilation modes --- programs/zstdcli.c | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 696e4a1ba..01760ff8c 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -803,6 +803,7 @@ static unsigned init_nbWorkers(unsigned defaultNbWorkers) { return defaultNbWorkers; #else + (void)defaultNbWorkers; return 1; #endif } From d3536643a91c6de403cf9913d85abc896e94cd11 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Sep 2025 05:06:40 +0000 Subject: [PATCH 851/937] Bump msys2/setup-msys2 from 2.28.0 to 2.29.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.28.0 to 2.29.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/40677d36a502eb2cf0fb808cc9dec31bf6152638...fb197b72ce45fb24f17bf3f807a388985654d1f2) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.29.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index caf86a11f..0450324ee 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 + - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 4b06d5e3b..59f4c1b77 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -487,7 +487,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 - - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 + - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index d097acf96..fcc81c395 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 # MSYS2 setup - - uses: msys2/setup-msys2@40677d36a502eb2cf0fb808cc9dec31bf6152638 # tag=v2.28.0 + - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 if: matrix.shell == 'msys2' with: msystem: ${{ matrix.msystem }} From ef4bab9079c2b1ac745d650efe546756faba27e0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Sep 2025 05:06:48 +0000 Subject: [PATCH 852/937] Bump github/codeql-action from 3.29.4 to 3.30.1 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.4 to 3.30.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/4e828ff8d448a8a6e532957b1811f387a63867e8...f1f6e5f6af878fb37288ce1c627459e94dbf7d01) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 3.30.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index e34ebfa7b..be14cb5d5 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@4e828ff8d448a8a6e532957b1811f387a63867e8 # tag=v3.29.4 + uses: github/codeql-action/upload-sarif@f1f6e5f6af878fb37288ce1c627459e94dbf7d01 # tag=v3.30.1 with: sarif_file: results.sarif From c9d2cbd5bacf493362aa9a81057938a11961369a Mon Sep 17 00:00:00 2001 From: w1m024 Date: Tue, 9 Sep 2025 06:20:55 +0000 Subject: [PATCH 853/937] add RVV optimization for ZSTD_row_getMatchMask Co-authored-by: gong-flying --- lib/compress/zstd_lazy.c | 42 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index 272ebe0ec..ca8fb4194 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1050,6 +1050,36 @@ 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 nbChunks, const BYTE* const src, const BYTE tag, const U32 head) +{ + U16 matches[4] = {0}; + int i; + assert(nbChunks == 1 || nbChunks == 2 || nbChunks == 4); + + size_t vl = __riscv_vsetvl_e8m1(16); + + for (i = 0; i < nbChunks; i++) { + vuint8m1_t chunk = __riscv_vle8_v_u8m1((const uint8_t*)(src + 16 * i), vl); + vbool8_t equalMask = __riscv_vmseq_vx_u8m1_b8(chunk, tag, vl); + + size_t vl_w = __riscv_vsetvl_e16m2(16); + vuint16m2_t one = __riscv_vmv_v_x_u16m2(1, vl_w); + vuint16m2_t indices = __riscv_vid_v_u16m2(vl_w); + vuint16m2_t powers_of_2 = __riscv_vsll_vv_u16m2(one, indices, vl_w); + vuint16m2_t zero = __riscv_vmv_v_x_u16m2(0, vl_w); + vuint16m2_t selected_bits = __riscv_vmerge_vvm_u16m2(zero, powers_of_2, equalMask, vl_w); + vuint16m1_t reduction = __riscv_vredor_vs_u16m2_u16m1(selected_bits, __riscv_vmv_s_x_u16m1(0, vl_w), vl_w); + matches[i] = __riscv_vmv_x_s_u16m1_u16(reduction); + } + + if (nbChunks == 1) return ZSTD_rotateRight_U16(matches[0], head); + if (nbChunks == 2) return ZSTD_rotateRight_U32((U32)matches[1] << 16 | (U32)matches[0], head); + assert(nbChunks == 4); + return ZSTD_rotateRight_U64((U64)matches[3] << 48 | (U64)matches[2] << 32 | (U64)matches[1] << 16 | (U64)matches[0], 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" @@ -1069,14 +1099,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); From fb7a86f20f7b3825ccf2a77153d4fb104733b2f4 Mon Sep 17 00:00:00 2001 From: w1m024 Date: Thu, 11 Sep 2025 20:42:40 +0000 Subject: [PATCH 854/937] Refactor ZSTD_row_getMatchMask for RVV optimization Performance (vs. SWAR) - 16-byte data: 5.87x speedup - 32-byte data: 9.63x speedup - 64-byte data: 17.98x speedup Co-authored-by: gong-flying --- lib/compress/zstd_lazy.c | 44 +++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index ca8fb4194..f5efa8d8a 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1054,30 +1054,32 @@ ZSTD_row_getNEONMask(const U32 rowEntries, const BYTE* const src, const BYTE tag FORCE_INLINE_TEMPLATE ZSTD_VecMask ZSTD_row_getRVVMask(int nbChunks, const BYTE* const src, const BYTE tag, const U32 head) { - U16 matches[4] = {0}; - int i; - assert(nbChunks == 1 || nbChunks == 2 || nbChunks == 4); + ZSTD_VecMask matches; + size_t vl; - size_t vl = __riscv_vsetvl_e8m1(16); + 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); - for (i = 0; i < nbChunks; i++) { - vuint8m1_t chunk = __riscv_vle8_v_u8m1((const uint8_t*)(src + 16 * i), vl); - vbool8_t equalMask = __riscv_vmseq_vx_u8m1_b8(chunk, tag, vl); - - size_t vl_w = __riscv_vsetvl_e16m2(16); - vuint16m2_t one = __riscv_vmv_v_x_u16m2(1, vl_w); - vuint16m2_t indices = __riscv_vid_v_u16m2(vl_w); - vuint16m2_t powers_of_2 = __riscv_vsll_vv_u16m2(one, indices, vl_w); - vuint16m2_t zero = __riscv_vmv_v_x_u16m2(0, vl_w); - vuint16m2_t selected_bits = __riscv_vmerge_vvm_u16m2(zero, powers_of_2, equalMask, vl_w); - vuint16m1_t reduction = __riscv_vredor_vs_u16m2_u16m1(selected_bits, __riscv_vmv_s_x_u16m1(0, vl_w), vl_w); - matches[i] = __riscv_vmv_x_s_u16m1_u16(reduction); + } 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); } - - if (nbChunks == 1) return ZSTD_rotateRight_U16(matches[0], head); - if (nbChunks == 2) return ZSTD_rotateRight_U32((U32)matches[1] << 16 | (U32)matches[0], head); - assert(nbChunks == 4); - return ZSTD_rotateRight_U64((U64)matches[3] << 48 | (U64)matches[2] << 32 | (U64)matches[1] << 16 | (U64)matches[0], head); } #endif From c59812e558dd6ba24f592c77662204b721bb1dbb Mon Sep 17 00:00:00 2001 From: Ryan Lefkowitz Date: Mon, 15 Sep 2025 18:20:01 -0400 Subject: [PATCH 855/937] =?UTF-8?q?=F0=9F=94=A7=20Fix=20memory=20leak=20in?= =?UTF-8?q?=20pthread=20init=20functions=20on=20failure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When pthread_mutex_init() or pthread_cond_init() fails in the debug implementation (DEBUGLEVEL >= 1), the previously allocated memory was not freed, causing a memory leak. This fix ensures that allocated memory is properly freed when pthread initialization functions fail, preventing resource leaks in error conditions. The issue affects: - ZSTD_pthread_mutex_init() at lib/common/threading.c:146 - ZSTD_pthread_cond_init() at lib/common/threading.c:167 This is particularly important for long-running applications or scenarios with resource constraints where pthread initialization might fail due to system limits. --- lib/common/threading.c | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/common/threading.c b/lib/common/threading.c index 25bb8b981..1d5c97d3c 100644 --- a/lib/common/threading.c +++ b/lib/common/threading.c @@ -143,7 +143,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) @@ -164,7 +171,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) From 96fdb9bd1607d034d5ec5c824ad9e6a58a53efd9 Mon Sep 17 00:00:00 2001 From: Neil Johari Date: Mon, 15 Sep 2025 23:58:45 -0700 Subject: [PATCH 856/937] Add debug logging and simple repro --- programs/dibio.c | 20 +++++++++++++++++++ test_allocation_bug.sh | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100755 test_allocation_bug.sh diff --git a/programs/dibio.c b/programs/dibio.c index 63c455a22..f5f33f1bd 100644 --- a/programs/dibio.c +++ b/programs/dibio.c @@ -279,10 +279,16 @@ static fileStats DiB_fileStats(const char** fileNamesTable, int nbFiles, size_t for (n=0; n alloc_test/good_$i.txt +done + +echo "Valid files created (about 6 bytes each = 30 bytes total)" +echo "" + +# We need enough bad files to make totalSizeToLoad negative +# 30 bytes positive, so we need at least 31 bad files +echo "Adding 1000 non-existent files to make totalSizeToLoad very negative..." +echo "Expected: totalSizeToLoad = 30 + (1000 * -1) = -970 bytes" +echo "" + +# Build command +CMD="./zstd --train alloc_test/good_*.txt" +for i in {1..1000}; do + CMD="$CMD alloc_test/BAD_$i" +done +CMD="$CMD -o alloc_test/dict.zst --maxdict=65536 2>&1" + +echo "Running command..." +echo "=================" + +# Run and capture ALL debug output related to our issue +eval $CMD | grep -E "\[DEBUG FINAL\]|\[DEBUG\] Memory calc|\[BUG\]|About to malloc|Error|not enough memory" + +echo "" +echo "Output should show something like the following:" +echo "1. [DEBUG FINAL] fileStats: totalSizeToLoad=-970 (NEGATIVE!)" +echo "2. [BUG] totalSizeToLoad is NEGATIVE!" +echo "3. [DEBUG] Memory calc: showing huge loadedSize value" +echo "4. Error about memory allocation" From 85f4a7e84e266d9545a309ff3f25e71345d8be62 Mon Sep 17 00:00:00 2001 From: Neil Johari Date: Tue, 16 Sep 2025 00:02:04 -0700 Subject: [PATCH 857/937] Fix bug --- programs/dibio.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/programs/dibio.c b/programs/dibio.c index f5f33f1bd..29a27d9db 100644 --- a/programs/dibio.c +++ b/programs/dibio.c @@ -282,13 +282,16 @@ static fileStats DiB_fileStats(const char** fileNamesTable, int nbFiles, size_t DISPLAYLEVEL(1, "[DEBUG] File '%s': size=%lld\n", fileNamesTable[n], (long long)fileSize); /* TODO: is there a minimum sample size? What if the file is 1-byte? */ - if (fileSize == 0) { - DISPLAYLEVEL(3, "Sample file '%s' has zero size, skipping...\n", fileNamesTable[n]); + /* Skip empty or invalid files */ + if (fileSize <= 0) { + if (fileSize < 0) { + DISPLAYLEVEL(3, "Sample file '%s' is unreadable or stat failed, skipping...\n", + fileNamesTable[n]); + } else { + DISPLAYLEVEL(3, "Sample file '%s' has zero size, skipping...\n", + fileNamesTable[n]); + } continue; - } else if (fileSize < 0) { - /* BUG: This path is NOT skipped but should be! */ - DISPLAYLEVEL(1, "[BUG] File '%s' has NEGATIVE size %lld but is NOT skipped!\n", - fileNamesTable[n], (long long)fileSize); } /* the case where we are breaking up files in sample chunks */ From 236e44f00fed5cbcd02b4936b765f3bb97ad0e98 Mon Sep 17 00:00:00 2001 From: Neil Johari Date: Tue, 16 Sep 2025 00:03:08 -0700 Subject: [PATCH 858/937] Remove debug logging --- programs/dibio.c | 16 --------------- test_allocation_bug.sh | 44 ------------------------------------------ 2 files changed, 60 deletions(-) delete mode 100755 test_allocation_bug.sh diff --git a/programs/dibio.c b/programs/dibio.c index 29a27d9db..dc629103b 100644 --- a/programs/dibio.c +++ b/programs/dibio.c @@ -279,8 +279,6 @@ static fileStats DiB_fileStats(const char** fileNamesTable, int nbFiles, size_t for (n=0; n alloc_test/good_$i.txt -done - -echo "Valid files created (about 6 bytes each = 30 bytes total)" -echo "" - -# We need enough bad files to make totalSizeToLoad negative -# 30 bytes positive, so we need at least 31 bad files -echo "Adding 1000 non-existent files to make totalSizeToLoad very negative..." -echo "Expected: totalSizeToLoad = 30 + (1000 * -1) = -970 bytes" -echo "" - -# Build command -CMD="./zstd --train alloc_test/good_*.txt" -for i in {1..1000}; do - CMD="$CMD alloc_test/BAD_$i" -done -CMD="$CMD -o alloc_test/dict.zst --maxdict=65536 2>&1" - -echo "Running command..." -echo "=================" - -# Run and capture ALL debug output related to our issue -eval $CMD | grep -E "\[DEBUG FINAL\]|\[DEBUG\] Memory calc|\[BUG\]|About to malloc|Error|not enough memory" - -echo "" -echo "Output should show something like the following:" -echo "1. [DEBUG FINAL] fileStats: totalSizeToLoad=-970 (NEGATIVE!)" -echo "2. [BUG] totalSizeToLoad is NEGATIVE!" -echo "3. [DEBUG] Memory calc: showing huge loadedSize value" -echo "4. Error about memory allocation" From be072c708ef35ccdef0683421dff3c6b00590b9b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 20 Sep 2025 16:33:41 +0000 Subject: [PATCH 859/937] Added documentation details for Makefile installation and pkg-config. --- README.md | 10 +++++----- lib/README.md | 22 ++++++++++++++++++---- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 3adacad51..5af79386f 100644 --- a/README.md +++ b/README.md @@ -127,19 +127,19 @@ When your system allows it, prefer using `make` to build `zstd` and `libzstd`. ### Makefile -If your system is compatible with standard `make` (or `gmake`), +Assuming your system supports standard `make` (or `gmake`), invoking `make` in root directory will generate `zstd` cli in root directory. It will also create `libzstd` into `lib/`. -Other available options include: +Other standard targets include: - `make install` : create and install zstd cli, library and man pages - `make check` : create and run `zstd`, test its behavior on local platform The `Makefile` follows the [GNU Standard Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html), -allowing staged install, standard flags, directory variables and command variables. +allowing staged install, standard compilation flags, directory variables and command variables. -For advanced use cases, specialized compilation flags which control binary generation -are documented in [`lib/README.md`](lib/README.md#modular-build) for the `libzstd` library +For advanced use cases, specialized flags which control binary generation and installation paths are documented +in [`lib/README.md`](lib/README.md#modular-build) for the `libzstd` library and in [`programs/README.md`](programs/README.md#compilation-variables) for the `zstd` CLI. ### cmake diff --git a/lib/README.md b/lib/README.md index 89e53e6c8..3974de160 100644 --- a/lib/README.md +++ b/lib/README.md @@ -7,15 +7,29 @@ in order to make it easier to select or exclude features. #### Building -`Makefile` script is provided, supporting [Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html#Makefile-Conventions), +A `Makefile` script is provided, supporting [Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html#Makefile-Conventions), including commands variables, staged install, directory variables and standard targets. - `make` : generates both static and dynamic libraries -- `make install` : install libraries and headers in target system directories +- `make install` : install libraries, headers and pkg-config in local system directories -`libzstd` default scope is pretty large, including compression, decompression, dictionary builder, -and support for decoding legacy formats >= v0.5.0. +`libzstd` default scope is extensive, including compression, decompression, dictionary builder, +and support for decoding legacy formats >= v0.5.0 by default. The scope can be reduced on demand (see paragraph _modular build_). +#### Multiarch Support + +For multiarch systems (like Debian/Ubuntu), libraries should be installed to architecture-specific directories. +When creating packages for such systems, use the `LIBDIR` variable to specify the correct multiarch path: + +```bash +# For x86_64 systems on Ubuntu/Debian: +make install PREFIX=/usr LIBDIR=/usr/lib/x86_64-linux-gnu + +# For ARM64 systems on Ubuntu/Debian: +make install PREFIX=/usr LIBDIR=/usr/lib/aarch64-linux-gnu +``` + +This will not only install the files in the correct directories, but also generate the correct paths for `pkg-config`. #### Multithreading support From 0c6d32df9a6f29e8b2b5d6232981e2606d35f8a3 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 20 Sep 2025 22:13:49 -0700 Subject: [PATCH 860/937] added profiling notes for Visual Studio --- CONTRIBUTING.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 57be94bf5..a9ad99ebd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -373,7 +373,12 @@ counter `L1-dcache-load-misses` #### Visual Studio -TODO +Build Zstd with symbols first (for example `cmake -B build -S build/cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo && ninja -C build zstd`) so the profiler resolves call stacks. + +* Launch Visual Studio’s Performance Profiler (`Alt+F2`), enable CPU Usage (optionally Instrumentation), and point it at the `programs/zstd` benchmark you want to run. +* If you prefer to start the benchmark from a terminal, use “Attach to running process” to latch onto it mid-run; keep frame pointers (`-fno-omit-frame-pointer`) for clean stacks. +* When you stop the capture, review the call tree, hot path, and annotated source panes +* Microsoft’s [Performance Profiling docs](https://learn.microsoft.com/en-us/visualstudio/profiling/?view=vs-2022) cover deeper sampling, ETW, and collection options if required. ## Issues We use GitHub issues to track public bugs. Please ensure your description is From eb062bc339dc0e1f12da9b28213d0efd46127c21 Mon Sep 17 00:00:00 2001 From: Cristian Le Date: Tue, 23 Sep 2025 10:29:44 +0200 Subject: [PATCH 861/937] Split lib target types in their own export groups This allows for the non-primary library to be missing in the Config.cmake file, e.g. if the devel files have a separate static-devel package Signed-off-by: Cristian Le --- build/cmake/CMakeModules/ZstdPackage.cmake | 27 ++++++++++--------- build/cmake/lib/CMakeLists.txt | 31 ++++++++++------------ build/cmake/zstdConfig.cmake.in | 3 +++ 3 files changed, 32 insertions(+), 29 deletions(-) diff --git a/build/cmake/CMakeModules/ZstdPackage.cmake b/build/cmake/CMakeModules/ZstdPackage.cmake index 5e40dd2c1..ed20f3c97 100644 --- a/build/cmake/CMakeModules/ZstdPackage.cmake +++ b/build/cmake/CMakeModules/ZstdPackage.cmake @@ -11,21 +11,24 @@ write_basic_package_version_file( COMPATIBILITY SameMajorVersion ) -# Export targets for build directory -export(EXPORT zstdExports - FILE "${CMAKE_CURRENT_BINARY_DIR}/zstdTargets.cmake" - NAMESPACE zstd:: -) - # Configure package for installation set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/zstd) -# Install exported targets -install(EXPORT zstdExports - FILE zstdTargets.cmake - NAMESPACE zstd:: - DESTINATION ${ConfigPackageLocation} -) +foreach(target_suffix IN ITEMS "_shared" "_static" "") + if(TARGET "libzstd${target_suffix}") + # Export targets for build directory + export(EXPORT "zstdExports${target_suffix}" + FILE "${CMAKE_CURRENT_BINARY_DIR}/zstdTargets${target_suffix}.cmake" + NAMESPACE zstd:: + ) + # Install exported targets + install(EXPORT "zstdExports${target_suffix}" + FILE "zstdTargets${target_suffix}.cmake" + NAMESPACE zstd:: + DESTINATION ${ConfigPackageLocation} + ) + endif() +endforeach() # Configure and install package config file configure_package_config_file( diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index a6b894c4d..04177925f 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -122,11 +122,9 @@ endmacro () set(PUBLIC_INCLUDE_DIRS ${LIBRARY_DIR}) set(CMAKE_RC_FLAGS "${CMAKE_RC_FLAGS} /I \"${LIBRARY_DIR}\"") # Split project to static and shared libraries build -set(library_targets) if (ZSTD_BUILD_SHARED) add_library(libzstd_shared SHARED ${Sources} ${Headers} ${PlatformDependResources}) target_include_directories(libzstd_shared INTERFACE $) - list(APPEND library_targets libzstd_shared) if (ZSTD_MULTITHREAD_SUPPORT) target_compile_definitions(libzstd_shared PUBLIC ZSTD_MULTITHREAD) if (UNIX) @@ -140,7 +138,6 @@ endif () if (ZSTD_BUILD_STATIC) add_library(libzstd_static STATIC ${Sources} ${Headers}) target_include_directories(libzstd_static INTERFACE $) - list(APPEND library_targets libzstd_static) if (ZSTD_MULTITHREAD_SUPPORT) target_compile_definitions(libzstd_static PUBLIC ZSTD_MULTITHREAD) if (UNIX) @@ -159,7 +156,6 @@ if (ZSTD_BUILD_SHARED AND NOT ZSTD_BUILD_STATIC) endif () add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_shared) - list(APPEND library_targets libzstd) endif () if (ZSTD_BUILD_STATIC AND NOT ZSTD_BUILD_SHARED) if (BUILD_SHARED_LIBS) @@ -167,7 +163,6 @@ if (ZSTD_BUILD_STATIC AND NOT ZSTD_BUILD_SHARED) endif () add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_static) - list(APPEND library_targets libzstd) endif () if (ZSTD_BUILD_SHARED AND ZSTD_BUILD_STATIC) # If both ZSTD_BUILD_SHARED and ZSTD_BUILD_STATIC are set, which is the @@ -176,11 +171,9 @@ if (ZSTD_BUILD_SHARED AND ZSTD_BUILD_STATIC) if (BUILD_SHARED_LIBS) add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_shared) - list(APPEND library_targets libzstd) else () add_library(libzstd INTERFACE) target_link_libraries(libzstd INTERFACE libzstd_static) - list(APPEND library_targets libzstd) endif () endif () @@ -274,16 +267,20 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libzstd.pc" DESTINATION "${CMAKE_INST # install target install(FILES ${PublicHeaders} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") -install(TARGETS ${library_targets} - EXPORT zstdExports - INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" - ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" - RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" - BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}" - FRAMEWORK DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT runtime OPTIONAL - PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" - ) +foreach(target_suffix IN ITEMS "_shared" "_static" "") + if(TARGET "libzstd${target_suffix}") + install(TARGETS "libzstd${target_suffix}" + EXPORT "zstdExports${target_suffix}" + INCLUDES DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}" + FRAMEWORK DESTINATION "${CMAKE_INSTALL_LIBDIR}" COMPONENT runtime OPTIONAL + PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + ) + endif() +endforeach() # uninstall target if (NOT TARGET uninstall) diff --git a/build/cmake/zstdConfig.cmake.in b/build/cmake/zstdConfig.cmake.in index f4190f989..a719d7899 100644 --- a/build/cmake/zstdConfig.cmake.in +++ b/build/cmake/zstdConfig.cmake.in @@ -5,6 +5,9 @@ if(@ZSTD_MULTITHREAD_SUPPORT@ AND "@UNIX@") find_dependency(Threads) endif() +foreach(lib_suffix IN ITEMS "_shared" "_static") + include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets${lib_suffix}.cmake" OPTIONAL) +endforeach() include("${CMAKE_CURRENT_LIST_DIR}/zstdTargets.cmake") check_required_components("zstd") From 4c1f86c7773dca5233aa75cd33515504bc3fba96 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 23 Sep 2025 11:25:54 -0700 Subject: [PATCH 862/937] fix minor warning in legacy decoders for mingw + clang CI test --- lib/legacy/zstd_v01.c | 2 +- lib/legacy/zstd_v03.c | 2 +- lib/legacy/zstd_v04.c | 2 +- lib/legacy/zstd_v05.c | 2 +- lib/legacy/zstd_v06.c | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/legacy/zstd_v01.c b/lib/legacy/zstd_v01.c index ad3c9330e..29e875713 100644 --- a/lib/legacy/zstd_v01.c +++ b/lib/legacy/zstd_v01.c @@ -430,7 +430,7 @@ static unsigned FSE_isError(size_t code) { return (code > (size_t)(-FSE_ERROR_ma static short FSE_abs(short a) { - return a<0? -a : a; + return a<0? (short)-a : a; } diff --git a/lib/legacy/zstd_v03.c b/lib/legacy/zstd_v03.c index 7d82db666..50fa87cf3 100644 --- a/lib/legacy/zstd_v03.c +++ b/lib/legacy/zstd_v03.c @@ -1111,7 +1111,7 @@ static unsigned FSE_isError(size_t code) { return ERR_isError(code); } ****************************************************************/ static short FSE_abs(short a) { - return a<0 ? -a : a; + return a<0 ? (short)-a : a; } static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, diff --git a/lib/legacy/zstd_v04.c b/lib/legacy/zstd_v04.c index 0da316c15..31c205258 100644 --- a/lib/legacy/zstd_v04.c +++ b/lib/legacy/zstd_v04.c @@ -1094,7 +1094,7 @@ static unsigned FSE_isError(size_t code) { return ERR_isError(code); } ****************************************************************/ static short FSE_abs(short a) { - return a<0 ? -a : a; + return a<0 ? (short)-a : a; } static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, diff --git a/lib/legacy/zstd_v05.c b/lib/legacy/zstd_v05.c index 7a3af4214..e1efca597 100644 --- a/lib/legacy/zstd_v05.c +++ b/lib/legacy/zstd_v05.c @@ -1224,7 +1224,7 @@ const char* FSEv05_getErrorName(size_t code) { return ERR_getErrorName(code); } /*-************************************************************** * FSEv05 NCount encoding-decoding ****************************************************************/ -static short FSEv05_abs(short a) { return a<0 ? -a : a; } +static short FSEv05_abs(short a) { return a<0 ? (short)-a : a; } size_t FSEv05_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, diff --git a/lib/legacy/zstd_v06.c b/lib/legacy/zstd_v06.c index 88a39e2a0..fb8c14df9 100644 --- a/lib/legacy/zstd_v06.c +++ b/lib/legacy/zstd_v06.c @@ -1202,7 +1202,7 @@ static unsigned HUFv06_isError(size_t code) { return ERR_isError(code); } /*-************************************************************** * FSE NCount encoding-decoding ****************************************************************/ -static short FSEv06_abs(short a) { return a<0 ? -a : a; } +static short FSEv06_abs(short a) { return a<0 ? (short)-a : a; } size_t FSEv06_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, const void* headerBuffer, size_t hbSize) From c15fa3cd4038892bf3e9abe852abb950bb10deca Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 23 Sep 2025 23:17:11 -0700 Subject: [PATCH 863/937] update documentation of ZSTD_getFrameContentSize() hopefully answering #4495 --- lib/zstd.h | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 850469490..415474d01 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -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); From 17888b3fbeb04c0c518b9694a357818d736dab42 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 24 Sep 2025 22:08:03 -0700 Subject: [PATCH 864/937] fix minor initialization warnings --- lib/legacy/zstd_v01.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/legacy/zstd_v01.c b/lib/legacy/zstd_v01.c index 29e875713..d3322f93e 100644 --- a/lib/legacy/zstd_v01.c +++ b/lib/legacy/zstd_v01.c @@ -1823,11 +1823,12 @@ static size_t ZSTD_decompressSequences( BYTE* const ostart = (BYTE* const)dst; BYTE* op = ostart; BYTE* const oend = ostart + maxDstSize; - size_t errorCode, dumpsLength; + size_t errorCode = 0; + size_t dumpsLength = 0; const BYTE* litPtr = litStart; const BYTE* const litEnd = litStart + litSize; - int nbSeq; - const BYTE* dumps; + int nbSeq = 0; + const BYTE* dumps = NULL; U32* DTableLL = dctx->LLTable; U32* DTableML = dctx->MLTable; U32* DTableOffb = dctx->OffTable; @@ -1915,7 +1916,7 @@ size_t ZSTDv01_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const voi size_t remainingSize = srcSize; U32 magicNumber; size_t errorCode=0; - blockProperties_t blockProperties; + blockProperties_t blockProperties = { 0 }; /* Frame Header */ if (srcSize < ZSTD_frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong); From c9d3af9ed0fa28b674270616c17e732e2ffcd8eb Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 20 Sep 2025 22:49:20 -0700 Subject: [PATCH 865/937] [cmake] root wrapper allow the existence of a `CMakeLists.txt` file at root, for easier integration with other projects expecting this file at root. Existing integration point, within `build/cmake/`, still works as expected. --- .gitignore | 21 +++++++++++---------- CMakeLists.txt | 11 +++++++++++ README.md | 43 +++++++++++++++++++++++++------------------ build/cmake/README.md | 9 +++++++++ 4 files changed, 56 insertions(+), 28 deletions(-) create mode 100644 CMakeLists.txt diff --git a/.gitignore b/.gitignore index 4b50bb186..03ecbde6a 100644 --- a/.gitignore +++ b/.gitignore @@ -22,16 +22,6 @@ zstdmt *.out *.app -# Test artefacts -tmp* -*.zst -*.zstd -dictionary. -dictionary -NUL -cmakebuild/ -install/ - # Build artefacts contrib/linux-kernel/linux/ projects/ @@ -40,6 +30,17 @@ bin/ buck-out/ build-* *.gcda +cmakebuild/ +cmake-build/ + +# Test artefacts +tmp* +*.zst +*.zstd +dictionary. +dictionary +NUL +install/ # IDE .clang_complete diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..10fef39b9 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 3.10) + +# Thin wrapper so `cmake -S .` behaves like `cmake -S build/cmake`. +# Policy lives in build/cmake; keep parent project language-less. +project(zstd-superbuild LANGUAGES NONE) + +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR) + message(FATAL_ERROR "In-source builds are not supported. Specify -B .") +endif() + +add_subdirectory(build/cmake) diff --git a/README.md b/README.md index 5af79386f..3aa01a0c1 100644 --- a/README.md +++ b/README.md @@ -120,20 +120,20 @@ Dictionary gains are mostly effective in the first few KB. Then, the compression ## Build instructions -`make` is the officially maintained build system of this project. -All other build systems are "compatible" and 3rd-party maintained, -they may feature small differences in advanced options. -When your system allows it, prefer using `make` to build `zstd` and `libzstd`. +`make` is the main build system of this project. +It is the reference, and other build systems are periodically updated to stay compatible. +However, small drifts and feature differences can be present, since perfect synchronization is difficult. +For this reason, when your build system allows it, prefer employing `make`. ### Makefile Assuming your system supports standard `make` (or `gmake`), -invoking `make` in root directory will generate `zstd` cli in root directory. -It will also create `libzstd` into `lib/`. +just invoking `make` in root directory generates `zstd` cli at root, +and also generates `libzstd` into `lib/`. Other standard targets include: -- `make install` : create and install zstd cli, library and man pages -- `make check` : create and run `zstd`, test its behavior on local platform +- `make install` : install zstd cli, library and man pages +- `make check` : run `zstd`, test its essential behavior on local platform The `Makefile` follows the [GNU Standard Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html), allowing staged install, standard compilation flags, directory variables and command variables. @@ -144,9 +144,16 @@ and in [`programs/README.md`](programs/README.md#compilation-variables) for the ### cmake -A `cmake` project generator is provided within `build/cmake`. -It can generate Makefiles or other build scripts -to create `zstd` binary, and `libzstd` dynamic and static libraries. +A `cmake` project generator is available for generating Makefiles or other build scripts +to create the `zstd` binary as well as `libzstd` dynamic and static libraries. +The repository root now contains a minimal `CMakeLists.txt` that forwards to `build/cmake`, +so you can configure the project with a standard `cmake -S .` invocation, +while the historical `cmake -S build/cmake` entry point remains fully supported. + +```bash +cmake -S . -B build-cmake +cmake --build build-cmake +``` By default, `CMAKE_BUILD_TYPE` is set to `Release`. @@ -156,7 +163,7 @@ By default, `CMAKE_BUILD_TYPE` is set to `Release`. To perform a Fat/Universal2 build and install use the following commands: ```bash -cmake -B build-cmake-debug -S build/cmake -G Ninja -DCMAKE_OSX_ARCHITECTURES="x86_64;x86_64h;arm64" +cmake -S . -B build-cmake-debug -G Ninja -DCMAKE_OSX_ARCHITECTURES="x86_64;x86_64h;arm64" cd build-cmake-debug ninja sudo ninja install @@ -198,10 +205,11 @@ If the version is out of date, please [create an issue or pull request](https:// ### Visual Studio (Windows) Going into `build` directory, you will find additional possibilities: -- Projects for Visual Studio 2005, 2008 and 2010. +- Projects for Visual Studio 2008 and 2010. + VS2010 project is compatible with VS2012, VS2013, VS2015 and VS2017. - Automated build scripts for Visual compiler by [@KrzysFR](https://github.com/KrzysFR), in `build/VS_scripts`, which will build `zstd` cli and `libzstd` library without any need to open Visual Studio solution. +- It is now recommended to generate Visual Studio solutions from `cmake` ### Buck @@ -210,7 +218,7 @@ The output binary will be in `buck-out/gen/programs/`. ### Bazel -You easily can integrate zstd into your Bazel project by using the module hosted on the [Bazel Central Repository](https://registry.bazel.build/modules/zstd). +You can integrate zstd into your Bazel project by using the module hosted on the [Bazel Central Repository](https://registry.bazel.build/modules/zstd). ## Testing @@ -221,9 +229,9 @@ For information on CI testing, please refer to `TESTING.md`. ## Status -Zstandard is currently deployed within Facebook and many other large cloud infrastructures. -It is run continuously to compress large amounts of data in multiple formats and use cases. -Zstandard is considered safe for production environments. +Zstandard is deployed within Meta and many other large cloud infrastructures, +to compress humongous amounts of data in various formats and use cases. +It is also continuously fuzzed for security issues by Google's [oss-fuzz](https://github.com/google/oss-fuzz/tree/master/projects/zstd) program. ## License @@ -232,6 +240,5 @@ Zstandard is dual-licensed under [BSD](LICENSE) OR [GPLv2](COPYING). ## Contributing The `dev` branch is the one where all contributions are merged before reaching `release`. -If you plan to propose a patch, please commit into the `dev` branch, or its own feature branch. Direct commit to `release` are not permitted. For more information, please read [CONTRIBUTING](CONTRIBUTING.md). diff --git a/build/cmake/README.md b/build/cmake/README.md index 6baa5974b..41c8bbb1a 100644 --- a/build/cmake/README.md +++ b/build/cmake/README.md @@ -7,6 +7,15 @@ variables. ## How to build +You can configure the project from the repository root thanks to the forwarding +`CMakeLists.txt`: +```sh +cmake -S . -B build-cmake +cmake --build build-cmake +``` +The historical workflow that starts configuration from `build/cmake` continues +to work as described below. + As cmake doesn't support command like `cmake clean`, it's recommended to perform an "out of source build". To do this, you can create a new directory and build in it: ```sh From 7758cc3e7a9821ab2a3870d47204246c90ac602f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 24 Sep 2025 21:55:31 -0700 Subject: [PATCH 866/937] [cmake] add minimal build test for CMakeLists.txt at root --- .github/workflows/cmake-tests.yml | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index f1ed1f850..5534cdf89 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -21,11 +21,26 @@ env: COMMON_CMAKE_FLAGS: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" jobs: + # Basic cmake build using the root CMakeLists.txt + # Provides a lightweight sanity check that the top-level project config builds + # with the default Unix Makefiles generator driven purely through cmake commands + cmake-root-basic: + name: "CMake Root Build" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - name: Configure (Root) + run: | + cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release ${{ env.COMMON_CMAKE_FLAGS }} + - name: Build (Root) + run: | + cmake --build cmake-build --config Release + # Ubuntu-based cmake build using make wrapper # This test uses the make-driven cmake build to ensure compatibility # with the existing build system integration cmake-ubuntu-basic: - name: "CMake Ubuntu Basic Build" + name: "CMake build using make wrapper" runs-on: ubuntu-latest steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 From 87cc127705f4094e21d0428545d22ac651b80b24 Mon Sep 17 00:00:00 2001 From: ZijianLi Date: Fri, 26 Sep 2025 14:26:52 +0800 Subject: [PATCH 867/937] - Modify the GCC version used for CI testing of the RISCV architecture - Fix a bug in the ZSTD_row_getRVVMask function - Improve some performance for ZSTD_copy16() --- .github/workflows/dev-short-tests.yml | 2 +- lib/common/compiler.h | 15 ++++------- lib/common/zstd_internal.h | 2 ++ lib/compress/zstd_compress.c | 4 +-- lib/compress/zstd_lazy.c | 38 ++++++++++++++++----------- 5 files changed, 32 insertions(+), 29 deletions(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 59f4c1b77..20a11335f 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -403,7 +403,7 @@ jobs: { name: PPC64LE, xcc_pkg: gcc-powerpc64le-linux-gnu, xcc: powerpc64le-linux-gnu-gcc, xemu_pkg: qemu-system-ppc, xemu: qemu-ppc64le-static }, { name: S390X, xcc_pkg: gcc-s390x-linux-gnu, xcc: s390x-linux-gnu-gcc, xemu_pkg: qemu-system-s390x, xemu: qemu-s390x-static }, { name: MIPS, xcc_pkg: gcc-mips-linux-gnu, xcc: mips-linux-gnu-gcc, xemu_pkg: qemu-system-mips, xemu: qemu-mips-static }, - { name: RISC-V, xcc_pkg: gcc-riscv64-linux-gnu, xcc: riscv64-linux-gnu-gcc, xemu_pkg: qemu-system-riscv64,xemu: qemu-riscv64-static }, + { name: RISC-V, xcc_pkg: gcc-14-riscv64-linux-gnu, xcc: riscv64-linux-gnu-gcc-14, xemu_pkg: qemu-system-riscv64,xemu: qemu-riscv64-static }, { name: M68K, xcc_pkg: gcc-m68k-linux-gnu, xcc: m68k-linux-gnu-gcc, xemu_pkg: qemu-system-m68k, xemu: qemu-m68k-static }, { name: SPARC, xcc_pkg: gcc-sparc64-linux-gnu, xcc: sparc64-linux-gnu-gcc, xemu_pkg: qemu-system-sparc, xemu: qemu-sparc64-static }, ] diff --git a/lib/common/compiler.h b/lib/common/compiler.h index 410068de4..5e70570ec 100644 --- a/lib/common/compiler.h +++ b/lib/common/compiler.h @@ -224,16 +224,11 @@ # if defined(__ARM_FEATURE_SVE2) # define ZSTD_ARCH_ARM_SVE2 # endif -#if defined(__riscv) && defined(__riscv_vector) - #if defined(__GNUC__) - #if (__GNUC__ > 14 || (__GNUC__ == 14 && __GNUC_MINOR__ >= 1)) - #define ZSTD_ARCH_RISCV_RVV - #endif - #elif defined(__clang__) - #if __clang_major__ > 18 || (__clang_major__ == 18 && __clang_minor__ >= 1) - #define ZSTD_ARCH_RISCV_RVV - #endif - #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) diff --git a/lib/common/zstd_internal.h b/lib/common/zstd_internal.h index 791b6485d..86a0fc5c8 100644 --- a/lib/common/zstd_internal.h +++ b/lib/common/zstd_internal.h @@ -185,6 +185,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 diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index ce5891067..1d6f0fcae 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -7292,7 +7292,7 @@ size_t convertSequences_noRepcodes( return longLen; } -#elif defined ZSTD_ARCH_RISCV_RVV +#elif defined (ZSTD_ARCH_RISCV_RVV) #include /* * Convert `vl` sequences per iteration, using RVV intrinsics: @@ -7824,7 +7824,7 @@ BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) } } -#elif defined ZSTD_ARCH_RISCV_RVV +#elif defined (ZSTD_ARCH_RISCV_RVV) BlockSummary ZSTD_get1BlockSummary(const ZSTD_Sequence* seqs, size_t nbSeqs) { diff --git a/lib/compress/zstd_lazy.c b/lib/compress/zstd_lazy.c index f5efa8d8a..18b7b4394 100644 --- a/lib/compress/zstd_lazy.c +++ b/lib/compress/zstd_lazy.c @@ -1052,33 +1052,39 @@ 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 nbChunks, const BYTE* const src, const BYTE tag, const U32 head) +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); + { + 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); + { + 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); + { + 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 From f94a01de746aacd16afe3ea84ddd671a6754de3b Mon Sep 17 00:00:00 2001 From: Radek Zikmund Date: Thu, 2 Oct 2025 14:40:11 +0200 Subject: [PATCH 868/937] Enable ASM language during CMake configure time only when needed --- build/cmake/CMakeLists.txt | 2 +- build/cmake/lib/CMakeLists.txt | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index 753cf4a9e..7cb0b6843 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -29,7 +29,7 @@ include(ZstdVersion) #----------------------------------------------------------------------------- project(zstd VERSION "${ZSTD_FULL_VERSION}" - LANGUAGES C ASM # Main library is in C and ASM + LANGUAGES C # Main library is in C and ASM, ASM is enabled conditionally HOMEPAGE_URL "${zstd_HOMEPAGE_URL}" DESCRIPTION "${zstd_DESCRIPTION}" ) diff --git a/build/cmake/lib/CMakeLists.txt b/build/cmake/lib/CMakeLists.txt index a6b894c4d..0cd02d623 100644 --- a/build/cmake/lib/CMakeLists.txt +++ b/build/cmake/lib/CMakeLists.txt @@ -7,7 +7,7 @@ # in the COPYING file in the root directory of this source tree). # ################################################################ -project(libzstd C ASM) +project(libzstd C) # ASM language is conditionally enabled where supported set(CMAKE_INCLUDE_CURRENT_DIR TRUE) option(ZSTD_BUILD_STATIC "BUILD STATIC LIBRARIES" ON) @@ -40,6 +40,7 @@ if (MSVC) add_compile_options(-DZSTD_DISABLE_ASM) else () if(CMAKE_SYSTEM_PROCESSOR MATCHES "amd64.*|AMD64.*|x86_64.*|X86_64.*" AND ${ZSTD_HAS_NOEXECSTACK}) + enable_language(ASM) set(DecompressSources ${DecompressSources} ${LIBRARY_DIR}/decompress/huf_decompress_amd64.S) else() add_compile_options(-DZSTD_DISABLE_ASM) From 33618c89e511637f8a6ef955b3501766d71feb53 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Wed, 8 Oct 2025 18:58:45 +0000 Subject: [PATCH 869/937] AArch64: Revert previous branch optimization Revert a branch optimization that was based on an incorrect assumption in the AArch64 part of ZSTD_decodeSequence. In extreme cases the existing implementation could lead to data corruption. Insert an UNLIKELY hint to guide the compilers toward generating more efficient machine code. --- lib/decompress/zstd_decompress_block.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index b2ccd92a1..b4cc731ac 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1332,14 +1332,11 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c seq.offset = offset; } - if (mlBits > 0) { + if (mlBits > 0) seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/); - if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32)) - BIT_reloadDStream(&seqState->DStream); - if (MEM_64bits() && (totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog))) - BIT_reloadDStream(&seqState->DStream); - } + 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); From 0dffae42e3ba81d08e1bc387d3f6d9d2ea303026 Mon Sep 17 00:00:00 2001 From: Arpad Panyik Date: Wed, 8 Oct 2025 18:59:24 +0000 Subject: [PATCH 870/937] AArch64: Remove 32-bit code from ZSTD_decodeSequence Remove the 32-bit code paths from the AArch64 only sections of ZSTD_decodeSequence. --- lib/decompress/zstd_decompress_block.c | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/lib/decompress/zstd_decompress_block.c b/lib/decompress/zstd_decompress_block.c index b4cc731ac..56e1f9eda 100644 --- a/lib/decompress/zstd_decompress_block.c +++ b/lib/decompress/zstd_decompress_block.c @@ -1261,6 +1261,7 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c const ZSTD_seqSymbol* const mlDInfo = seqState->stateML.table + seqState->stateML.state; const ZSTD_seqSymbol* const ofDInfo = seqState->stateOffb.table + seqState->stateOffb.state; # endif + (void)longOffsets; seq.matchLength = mlDInfo->baseValue; seq.litLength = llDInfo->baseValue; { U32 const ofBase = ofDInfo->baseValue; @@ -1290,18 +1291,7 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c 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); - if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) { - /* Always read extra bits, this keeps the logic simple, - * avoids branches, and avoids accidentally reading 0 bits. - */ - U32 const extraBits = LONG_OFFSETS_MAX_EXTRA_BITS_32; - offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits); - BIT_reloadDStream(&seqState->DStream); - offset += BIT_readBitsFast(&seqState->DStream, extraBits); - } else { - offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ - if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); - } + offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */ prevOffset2 = prevOffset1; prevOffset1 = prevOffset0; prevOffset0 = offset; @@ -1344,9 +1334,6 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c if (llBits > 0) seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/); - if (MEM_32bits()) - BIT_reloadDStream(&seqState->DStream); - DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u", (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset); @@ -1354,7 +1341,6 @@ ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, c /* 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 */ - if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */ ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofNext, ofnbBits); /* <= 8 bits */ BIT_reloadDStream(&seqState->DStream); } From 5539fcfb6afb6ac1acf223bcef7de71449572896 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 23 Oct 2025 07:01:01 -0700 Subject: [PATCH 871/937] minor: fix mingw warnings: calloc argument order --- tests/paramgrill.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/paramgrill.c b/tests/paramgrill.c index 869e966e0..718196c9b 100644 --- a/tests/paramgrill.c +++ b/tests/paramgrill.c @@ -1242,7 +1242,7 @@ static int createBuffers(buffers_t* buff, const char* const * const fileNamesTab size_t n; size_t totalSizeToLoad = (size_t)UTIL_getTotalFileSize(fileNamesTable, (U32)nbFiles); size_t benchedSize = MIN(BMK_findMaxMem(totalSizeToLoad * 3) / 3, totalSizeToLoad); - size_t* fileSizes = calloc(sizeof(size_t), nbFiles); + size_t* fileSizes = calloc(nbFiles, sizeof(size_t)); void* srcBuffer = NULL; int ret = 0; @@ -1457,7 +1457,7 @@ createMemoTableArray(const paramValues_t p, const size_t varyLen, const U32 memoTableLog) { - memoTable_t* const mtAll = (memoTable_t*)calloc(sizeof(memoTable_t),(ZSTD_STRATEGY_MAX + 1)); + memoTable_t* const mtAll = (memoTable_t*)calloc((ZSTD_STRATEGY_MAX + 1), sizeof(memoTable_t)); ZSTD_strategy i, stratMin = ZSTD_STRATEGY_MIN, stratMax = ZSTD_STRATEGY_MAX; if(mtAll == NULL) { @@ -1494,7 +1494,7 @@ createMemoTableArray(const paramValues_t p, mtl = ((size_t)1 << memoTableLog); } - mtAll[i].table = (BYTE*)calloc(sizeof(BYTE), mtl); + mtAll[i].table = (BYTE*)calloc(mtl, sizeof(BYTE)); mtAll[i].tableLen = mtl; if(mtAll[i].table == NULL) { From c72eea13bff1e3c1c68e9428a69b0399ff10e91d Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 23 Oct 2025 06:08:36 +0200 Subject: [PATCH 872/937] Fix undefined names in automated_benchmarking.py Fix variable name typos in automated_benchmarking.py % `ruff check` ``` Error: tests/automated_benchmarking.py:237:21: F821 Undefined name `baseline_label` Error: tests/automated_benchmarking.py:250:21: F821 Undefined name `baseline_label` Error: tests/automated_benchmarking.py:318:55: F821 Undefined name `frequenc` Error: Process completed with exit code 1. ``` % [`ruff rule F821`](https://docs.astral.sh/ruff/rules/undefined-name) --- tests/automated_benchmarking.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/automated_benchmarking.py b/tests/automated_benchmarking.py index 153e7db4c..0935d1db4 100644 --- a/tests/automated_benchmarking.py +++ b/tests/automated_benchmarking.py @@ -225,7 +225,7 @@ def get_regressions_dictionary(baseline_build, test_build, filenames_directory, for j, level in enumerate(levels): old_cspeed, old_dspeed = old[j] new_cspeed, new_dspeed = new[j] - cspeed_reg, dspeed_reg, baesline_label, test_label = parse_regressions_and_labels( + cspeed_reg, dspeed_reg, baseline_label, test_label = parse_regressions_and_labels( old_cspeed, new_cspeed, old_dspeed, new_dspeed, baseline_build, test_build ) if cspeed_reg > CSPEED_REGRESSION_TOLERANCE: @@ -315,7 +315,7 @@ if __name__ == "__main__": quit() if mode == "onetime": - main(filenames, levels, iterations, frequency=frequenc, dictionary_filename=dictionary_filename) + main(filenames, levels, iterations, frequency=frequency, dictionary_filename=dictionary_filename) elif mode == "current": builds = [{"user": None, "branch": "None", "hash": None}] main(filenames, levels, iterations, builds, frequency=frequency, dictionary_filename=dictionary_filename) From 44cd3c8451dbd64d40725655bebcb9b7d245e87d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 25 Oct 2025 00:50:55 -0700 Subject: [PATCH 873/937] disable asyncio during compression it's not helpful for performance, and can in some times be detrimental. the synchronous mode is also much easier to follow and debug. --- programs/fileio.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 77f3d35f9..fec0e2d66 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -1147,8 +1147,14 @@ static cRess_t FIO_createCResources(FIO_prefs_t* const prefs, dictBufferType = (useMMap && !forceNoUseMMap) ? FIO_mmapDict : FIO_mallocDict; FIO_initDict(&ress.dict, dictFileName, prefs, &ress.dictFileStat, dictBufferType); /* works with dictFileName==NULL */ - ress.writeCtx = AIO_WritePool_create(prefs, ZSTD_CStreamOutSize()); - ress.readCtx = AIO_ReadPool_create(prefs, ZSTD_CStreamInSize()); + { + /* Compression paths stay synchronous for now: lower overhead and easier upkeep. */ + int const savedAsyncIO = prefs->asyncIO; + prefs->asyncIO = 0; + ress.writeCtx = AIO_WritePool_create(prefs, ZSTD_CStreamOutSize()); + ress.readCtx = AIO_ReadPool_create(prefs, ZSTD_CStreamInSize()); + prefs->asyncIO = savedAsyncIO; + } /* Advanced parameters, including dictionary */ if (dictFileName && (ress.dict.dictBuffer==NULL)) @@ -2070,16 +2076,12 @@ FIO_compressFilename_srcFile(FIO_ctx_t* const fCtx, srcFile = FIO_openSrcFile(prefs, srcFileName, &srcFileStat); if (srcFile == NULL) return 1; /* srcFile could not be opened */ - /* Don't use AsyncIO for small files */ + /* AsyncIO is disabled for compression to favor predictable performance and simpler upkeep. */ if (strcmp(srcFileName, stdinmark)) /* Stdin doesn't have stats */ fileSize = UTIL_getFileSizeStat(&srcFileStat); - if(fileSize != UTIL_FILESIZE_UNKNOWN && fileSize < ZSTD_BLOCKSIZE_MAX * 3) { - AIO_ReadPool_setAsync(ress.readCtx, 0); - AIO_WritePool_setAsync(ress.writeCtx, 0); - } else { - AIO_ReadPool_setAsync(ress.readCtx, 1); - AIO_WritePool_setAsync(ress.writeCtx, 1); - } + (void)fileSize; + AIO_ReadPool_setAsync(ress.readCtx, 0); + AIO_WritePool_setAsync(ress.writeCtx, 0); AIO_ReadPool_setFile(ress.readCtx, srcFile); result = FIO_compressFilename_dstFile( From d1dd7e1481d76db7f0c94f90ba57a607c4e5df9e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 25 Oct 2025 11:02:51 -0700 Subject: [PATCH 874/937] removed asyncio completely for compression path this does not provide speed benefits, since most of the leverage happens internally within the library, and can even become detrimental in certain scenario, due to complex and wasteful memory management. At a minimum, it makes the logic simpler, easier to debug, at essentially the same performance. --- programs/fileio.c | 498 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 366 insertions(+), 132 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index fec0e2d66..1e767ee64 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -48,6 +48,36 @@ FIO_display_prefs_t g_display_prefs = {2, FIO_ps_auto}; UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER; +/* ************************************* +* Synchronous compression IO helpers +***************************************/ +typedef struct { + const FIO_prefs_t* prefs; + FILE* srcFile; + FILE* dstFile; + unsigned storedSkips; + U8* inBuffer; + size_t inCapacity; + U8* srcBuffer; + size_t srcBufferLoaded; + U8* outBuffer; + size_t outCapacity; +} FIO_SyncCompressIO; + +static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, + const FIO_prefs_t* prefs, + size_t inCapacity, + size_t outCapacity); +static void FIO_SyncCompressIO_free(FIO_SyncCompressIO* io); +static void FIO_SyncCompressIO_setSrc(FIO_SyncCompressIO* io, FILE* file); +static void FIO_SyncCompressIO_clearSrc(FIO_SyncCompressIO* io); +static void FIO_SyncCompressIO_setDst(FIO_SyncCompressIO* io, FILE* file); +static int FIO_SyncCompressIO_closeDst(FIO_SyncCompressIO* io); +static size_t FIO_SyncCompressIO_fillBuffer(FIO_SyncCompressIO* io, size_t minToHave); +static void FIO_SyncCompressIO_consumeBytes(FIO_SyncCompressIO* io, size_t n); +static void FIO_SyncCompressIO_commitOut(FIO_SyncCompressIO* io, const void* buffer, size_t size); +static void FIO_SyncCompressIO_finish(FIO_SyncCompressIO* io); + #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_magicNumber, ZSTD_frameHeaderSize_max */ #include "../lib/zstd.h" #include "../lib/zstd_errors.h" /* ZSTD_error_frameParameter_windowTooLarge */ @@ -125,6 +155,233 @@ char const* FIO_lzmaVersion(void) #define TEMPORARY_FILE_PERMISSIONS (0600) #endif +static unsigned FIO_sparseWrite(FILE* file, + const void* buffer, size_t bufferSize, + const FIO_prefs_t* const prefs, + unsigned storedSkips) +{ + const size_t* const bufferT = (const size_t*)buffer; /* Buffer is supposed malloc'ed, hence aligned on size_t */ + size_t bufferSizeT = bufferSize / sizeof(size_t); + const size_t* const bufferTEnd = bufferT + bufferSizeT; + const size_t* ptrT = bufferT; + static const size_t segmentSizeT = (32 KB) / sizeof(size_t); /* check every 32 KB */ + + if (prefs->testMode) return 0; /* do not output anything in test mode */ + + if (!prefs->sparseFileSupport) { /* normal write */ + size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file); + if (sizeCheck != bufferSize) + EXM_THROW(70, "Write error : cannot write block : %s", + strerror(errno)); + return 0; + } + + /* avoid int overflow */ + if (storedSkips > 1 GB) { + if (LONG_SEEK(file, 1 GB, SEEK_CUR) != 0) + EXM_THROW(91, "1 GB skip error (sparse file support)"); + storedSkips -= 1 GB; + } + + while (ptrT < bufferTEnd) { + size_t nb0T; + + /* adjust last segment if < 32 KB */ + size_t seg0SizeT = segmentSizeT; + if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT; + bufferSizeT -= seg0SizeT; + + /* count leading zeroes */ + for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ; + storedSkips += (unsigned)(nb0T * sizeof(size_t)); + + if (nb0T != seg0SizeT) { /* not all 0s */ + size_t const nbNon0ST = seg0SizeT - nb0T; + /* skip leading zeros */ + if (LONG_SEEK(file, storedSkips, SEEK_CUR) != 0) + EXM_THROW(92, "Sparse skip error ; try --no-sparse"); + storedSkips = 0; + /* write the rest */ + if (fwrite(ptrT + nb0T, sizeof(size_t), nbNon0ST, file) != nbNon0ST) + EXM_THROW(93, "Write error : cannot write block : %s", + strerror(errno)); + } + ptrT += seg0SizeT; + } + + { static size_t const maskT = sizeof(size_t)-1; + if (bufferSize & maskT) { + /* size not multiple of sizeof(size_t) : implies end of block */ + const char* const restStart = (const char*)bufferTEnd; + const char* restPtr = restStart; + const char* const restEnd = (const char*)buffer + bufferSize; + assert(restEnd > restStart && restEnd < restStart + sizeof(size_t)); + for ( ; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ; + storedSkips += (unsigned) (restPtr - restStart); + if (restPtr != restEnd) { + /* not all remaining bytes are 0 */ + size_t const restSize = (size_t)(restEnd - restPtr); + if (LONG_SEEK(file, storedSkips, SEEK_CUR) != 0) + EXM_THROW(92, "Sparse skip error ; try --no-sparse"); + if (fwrite(restPtr, 1, restSize, file) != restSize) + EXM_THROW(95, "Write error : cannot write end of decoded block : %s", + strerror(errno)); + storedSkips = 0; + } } } + + return storedSkips; +} + +static void FIO_sparseWriteEnd(const FIO_prefs_t* const prefs, FILE* file, unsigned storedSkips) +{ + if (file == NULL) return; + if (prefs->testMode) { + assert(storedSkips == 0); + return; + } + if (storedSkips>0) { + assert(prefs->sparseFileSupport > 0); /* storedSkips>0 implies sparse support is enabled */ + if (LONG_SEEK(file, storedSkips-1, SEEK_CUR) != 0) + EXM_THROW(69, "Final skip error (sparse file support)"); + /* last zero must be explicitly written, + * so that skipped ones get implicitly translated as zero by FS */ + { const char lastZeroByte[1] = { 0 }; + if (fwrite(lastZeroByte, 1, 1, file) != 1) + EXM_THROW(69, "Write error : cannot write last zero : %s", strerror(errno)); + } + } +} + +static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, + const FIO_prefs_t* prefs, + size_t inCapacity, + size_t outCapacity) +{ + memset(io, 0, sizeof(*io)); + io->prefs = prefs; + io->inCapacity = inCapacity; + io->outCapacity = outCapacity; + io->inBuffer = (U8*)malloc(inCapacity); + if (!io->inBuffer) + EXM_THROW(101, "Allocation error : not enough memory"); + io->outBuffer = (U8*)malloc(outCapacity); + if (!io->outBuffer) { + free(io->inBuffer); + io->inBuffer = NULL; + EXM_THROW(101, "Allocation error : not enough memory"); + } + io->srcBuffer = io->inBuffer; + io->srcBufferLoaded = 0; +} + +static void FIO_SyncCompressIO_free(FIO_SyncCompressIO* io) +{ + if (!io) return; + free(io->inBuffer); + free(io->outBuffer); + io->inBuffer = NULL; + io->outBuffer = NULL; + io->srcBuffer = NULL; + io->srcBufferLoaded = 0; + io->srcFile = NULL; + io->dstFile = NULL; + io->storedSkips = 0; +} + +static void FIO_SyncCompressIO_setSrc(FIO_SyncCompressIO* io, FILE* file) +{ + io->srcFile = file; + io->srcBuffer = io->inBuffer; + io->srcBufferLoaded = 0; +} + +static void FIO_SyncCompressIO_clearSrc(FIO_SyncCompressIO* io) +{ + io->srcFile = NULL; + io->srcBuffer = io->inBuffer; + io->srcBufferLoaded = 0; +} + +static void FIO_SyncCompressIO_setDst(FIO_SyncCompressIO* io, FILE* file) +{ + io->dstFile = file; + io->storedSkips = 0; +} + +static int FIO_SyncCompressIO_closeDst(FIO_SyncCompressIO* io) +{ + int result = 0; + if (io->dstFile != NULL) { + FIO_SyncCompressIO_finish(io); + result = fclose(io->dstFile); + io->dstFile = NULL; + } + return result; +} + +static size_t FIO_SyncCompressIO_fillBuffer(FIO_SyncCompressIO* io, size_t minToHave) +{ + size_t added = 0; + if (io->srcFile == NULL) + return 0; + + if (minToHave > io->inCapacity) + minToHave = io->inCapacity; + + if (io->srcBufferLoaded >= minToHave) + return 0; + + if (io->srcBuffer != io->inBuffer) { + if (io->srcBufferLoaded > 0) + memmove(io->inBuffer, io->srcBuffer, io->srcBufferLoaded); + io->srcBuffer = io->inBuffer; + } + + while (io->srcBufferLoaded < minToHave) { + size_t const toRead = io->inCapacity - io->srcBufferLoaded; + size_t const readBytes = fread(io->inBuffer + io->srcBufferLoaded, 1, toRead, io->srcFile); + if (readBytes == 0) { + if (ferror(io->srcFile)) + EXM_THROW(37, "Read error"); + break; /* EOF */ + } + io->srcBufferLoaded += readBytes; + added += readBytes; + if (readBytes < toRead) + break; + } + + return added; +} + +static void FIO_SyncCompressIO_consumeBytes(FIO_SyncCompressIO* io, size_t n) +{ + assert(n <= io->srcBufferLoaded); + io->srcBuffer += n; + io->srcBufferLoaded -= n; + if (io->srcBufferLoaded == 0) + io->srcBuffer = io->inBuffer; +} + +static void FIO_SyncCompressIO_commitOut(FIO_SyncCompressIO* io, const void* buffer, size_t size) +{ + if (size == 0) + return; + if (io->dstFile == NULL) { + assert(io->prefs->testMode); + return; + } + io->storedSkips = FIO_sparseWrite(io->dstFile, buffer, size, io->prefs, io->storedSkips); +} + +static void FIO_SyncCompressIO_finish(FIO_SyncCompressIO* io) +{ + if (io->dstFile == NULL) + return; + FIO_sparseWriteEnd(io->prefs, io->dstFile, io->storedSkips); + io->storedSkips = 0; +} + /*-************************************ * Signal (Ctrl-C trapping) **************************************/ @@ -1078,8 +1335,7 @@ typedef struct { const char* dictFileName; stat_t dictFileStat; ZSTD_CStream* cctx; - WritePoolCtx_t *writeCtx; - ReadPoolCtx_t *readCtx; + FIO_SyncCompressIO io; } cRess_t; /** ZSTD_cycleLog() : @@ -1147,14 +1403,7 @@ static cRess_t FIO_createCResources(FIO_prefs_t* const prefs, dictBufferType = (useMMap && !forceNoUseMMap) ? FIO_mmapDict : FIO_mallocDict; FIO_initDict(&ress.dict, dictFileName, prefs, &ress.dictFileStat, dictBufferType); /* works with dictFileName==NULL */ - { - /* Compression paths stay synchronous for now: lower overhead and easier upkeep. */ - int const savedAsyncIO = prefs->asyncIO; - prefs->asyncIO = 0; - ress.writeCtx = AIO_WritePool_create(prefs, ZSTD_CStreamOutSize()); - ress.readCtx = AIO_ReadPool_create(prefs, ZSTD_CStreamInSize()); - prefs->asyncIO = savedAsyncIO; - } + FIO_SyncCompressIO_init(&ress.io, prefs, ZSTD_CStreamInSize(), ZSTD_CStreamOutSize()); /* Advanced parameters, including dictionary */ if (dictFileName && (ress.dict.dictBuffer==NULL)) @@ -1218,21 +1467,20 @@ static cRess_t FIO_createCResources(FIO_prefs_t* const prefs, static void FIO_freeCResources(cRess_t* const ress) { FIO_freeDict(&(ress->dict)); - AIO_WritePool_free(ress->writeCtx); - AIO_ReadPool_free(ress->readCtx); + FIO_SyncCompressIO_free(&ress->io); ZSTD_freeCStream(ress->cctx); /* never fails */ } #ifdef ZSTD_GZCOMPRESS static unsigned long long -FIO_compressGzFrame(const cRess_t* ress, /* buffers & handlers are used, but not changed */ +FIO_compressGzFrame(cRess_t* ress, const char* srcFileName, U64 const srcFileSize, int compressionLevel, U64* readsize) { + FIO_SyncCompressIO* const io = &ress->io; unsigned long long inFileSize = 0, outFileSize = 0; z_stream strm; - IOJob_t *writeJob = NULL; if (compressionLevel > Z_BEST_COMPRESSION) compressionLevel = Z_BEST_COMPRESSION; @@ -1248,37 +1496,36 @@ FIO_compressGzFrame(const cRess_t* ress, /* buffers & handlers are used, but no EXM_THROW(71, "zstd: %s: deflateInit2 error %d \n", srcFileName, ret); } } - writeJob = AIO_WritePool_acquireJob(ress->writeCtx); strm.next_in = 0; strm.avail_in = 0; - strm.next_out = (Bytef*)writeJob->buffer; - strm.avail_out = (uInt)writeJob->bufferSize; + strm.next_out = (Bytef*)io->outBuffer; + strm.avail_out = (uInt)io->outCapacity; while (1) { int ret; if (strm.avail_in == 0) { - AIO_ReadPool_fillBuffer(ress->readCtx, ZSTD_CStreamInSize()); - if (ress->readCtx->srcBufferLoaded == 0) break; - inFileSize += ress->readCtx->srcBufferLoaded; - strm.next_in = (z_const unsigned char*)ress->readCtx->srcBuffer; - strm.avail_in = (uInt)ress->readCtx->srcBufferLoaded; + size_t const added = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); + if (io->srcBufferLoaded == 0) break; + inFileSize += added; + *readsize += added; + strm.next_in = (z_const unsigned char*)io->srcBuffer; + strm.avail_in = (uInt)io->srcBufferLoaded; } { size_t const availBefore = strm.avail_in; ret = deflate(&strm, Z_NO_FLUSH); - AIO_ReadPool_consumeBytes(ress->readCtx, availBefore - strm.avail_in); + FIO_SyncCompressIO_consumeBytes(io, availBefore - strm.avail_in); } if (ret != Z_OK) EXM_THROW(72, "zstd: %s: deflate error %d \n", srcFileName, ret); - { size_t const cSize = writeJob->bufferSize - strm.avail_out; + { size_t const cSize = (size_t)((uInt)io->outCapacity - strm.avail_out); if (cSize) { - writeJob->usedBufferSize = cSize; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, cSize); outFileSize += cSize; - strm.next_out = (Bytef*)writeJob->buffer; - strm.avail_out = (uInt)writeJob->bufferSize; + strm.next_out = (Bytef*)io->outBuffer; + strm.avail_out = (uInt)io->outCapacity; } } if (srcFileSize == UTIL_FILESIZE_UNKNOWN) { DISPLAYUPDATE_PROGRESS( @@ -1294,13 +1541,12 @@ FIO_compressGzFrame(const cRess_t* ress, /* buffers & handlers are used, but no while (1) { int const ret = deflate(&strm, Z_FINISH); - { size_t const cSize = writeJob->bufferSize - strm.avail_out; + { size_t const cSize = (size_t)((uInt)io->outCapacity - strm.avail_out); if (cSize) { - writeJob->usedBufferSize = cSize; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, cSize); outFileSize += cSize; - strm.next_out = (Bytef*)writeJob->buffer; - strm.avail_out = (uInt)writeJob->bufferSize; + strm.next_out = (Bytef*)io->outBuffer; + strm.avail_out = (uInt)io->outCapacity; } } if (ret == Z_STREAM_END) break; if (ret != Z_BUF_ERROR) @@ -1312,8 +1558,7 @@ FIO_compressGzFrame(const cRess_t* ress, /* buffers & handlers are used, but no EXM_THROW(79, "zstd: %s: deflateEnd error %d \n", srcFileName, ret); } } *readsize = inFileSize; - AIO_WritePool_releaseIoJob(writeJob); - AIO_WritePool_sparseWriteEnd(ress->writeCtx); + FIO_SyncCompressIO_finish(io); return outFileSize; } #endif @@ -1325,11 +1570,11 @@ FIO_compressLzmaFrame(cRess_t* ress, const char* srcFileName, U64 const srcFileSize, int compressionLevel, U64* readsize, int plain_lzma) { + FIO_SyncCompressIO* const io = &ress->io; unsigned long long inFileSize = 0, outFileSize = 0; lzma_stream strm = LZMA_STREAM_INIT; lzma_action action = LZMA_RUN; lzma_ret ret; - IOJob_t *writeJob = NULL; if (compressionLevel < 0) compressionLevel = 0; if (compressionLevel > 9) compressionLevel = 9; @@ -1347,37 +1592,35 @@ FIO_compressLzmaFrame(cRess_t* ress, EXM_THROW(83, "zstd: %s: lzma_easy_encoder error %d", srcFileName, ret); } - writeJob =AIO_WritePool_acquireJob(ress->writeCtx); - strm.next_out = (BYTE*)writeJob->buffer; - strm.avail_out = writeJob->bufferSize; + strm.next_out = (BYTE*)io->outBuffer; + strm.avail_out = io->outCapacity; strm.next_in = 0; strm.avail_in = 0; while (1) { if (strm.avail_in == 0) { - size_t const inSize = AIO_ReadPool_fillBuffer(ress->readCtx, ZSTD_CStreamInSize()); - if (ress->readCtx->srcBufferLoaded == 0) action = LZMA_FINISH; - inFileSize += inSize; - strm.next_in = (BYTE const*)ress->readCtx->srcBuffer; - strm.avail_in = ress->readCtx->srcBufferLoaded; + size_t const added = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); + if (io->srcBufferLoaded == 0) action = LZMA_FINISH; + inFileSize += added; + *readsize += added; + strm.next_in = (BYTE const*)io->srcBuffer; + strm.avail_in = io->srcBufferLoaded; } { size_t const availBefore = strm.avail_in; ret = lzma_code(&strm, action); - AIO_ReadPool_consumeBytes(ress->readCtx, availBefore - strm.avail_in); + FIO_SyncCompressIO_consumeBytes(io, availBefore - strm.avail_in); } - if (ret != LZMA_OK && ret != LZMA_STREAM_END) EXM_THROW(84, "zstd: %s: lzma_code encoding error %d", srcFileName, ret); - { size_t const compBytes = writeJob->bufferSize - strm.avail_out; + { size_t const compBytes = io->outCapacity - strm.avail_out; if (compBytes) { - writeJob->usedBufferSize = compBytes; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, compBytes); outFileSize += compBytes; - strm.next_out = (BYTE*)writeJob->buffer; - strm.avail_out = writeJob->bufferSize; + strm.next_out = (BYTE*)io->outBuffer; + strm.avail_out = io->outCapacity; } } if (srcFileSize == UTIL_FILESIZE_UNKNOWN) DISPLAYUPDATE_PROGRESS("\rRead : %u MB ==> %.2f%%", @@ -1393,8 +1636,7 @@ FIO_compressLzmaFrame(cRess_t* ress, lzma_end(&strm); *readsize = inFileSize; - AIO_WritePool_releaseIoJob(writeJob); - AIO_WritePool_sparseWriteEnd(ress->writeCtx); + FIO_SyncCompressIO_finish(io); return outFileSize; } @@ -1415,21 +1657,20 @@ FIO_compressLz4Frame(cRess_t* ress, int compressionLevel, int checksumFlag, U64* readsize) { + FIO_SyncCompressIO* const io = &ress->io; const size_t blockSize = FIO_LZ4_GetBlockSize_FromBlockId(LZ4F_max64KB); unsigned long long inFileSize = 0, outFileSize = 0; LZ4F_preferences_t prefs; LZ4F_compressionContext_t ctx; - IOJob_t* writeJob = AIO_WritePool_acquireJob(ress->writeCtx); - LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); if (LZ4F_isError(errorCode)) EXM_THROW(31, "zstd: failed to create lz4 compression context"); memset(&prefs, 0, sizeof(prefs)); - assert(blockSize <= ress->readCtx->base.jobBufferSize); + assert(blockSize <= io->inCapacity); /* autoflush off to mitigate a bug in lz4<=1.9.3 for compression level 12 */ prefs.autoFlush = 0; @@ -1440,25 +1681,26 @@ FIO_compressLz4Frame(cRess_t* ress, #if LZ4_VERSION_NUMBER >= 10600 prefs.frameInfo.contentSize = (srcFileSize==UTIL_FILESIZE_UNKNOWN) ? 0 : srcFileSize; #endif - assert(LZ4F_compressBound(blockSize, &prefs) <= writeJob->bufferSize); + assert(LZ4F_compressBound(blockSize, &prefs) <= io->outCapacity); { - size_t headerSize = LZ4F_compressBegin(ctx, writeJob->buffer, writeJob->bufferSize, &prefs); + size_t headerSize = LZ4F_compressBegin(ctx, io->outBuffer, io->outCapacity, &prefs); if (LZ4F_isError(headerSize)) EXM_THROW(33, "File header generation failed : %s", LZ4F_getErrorName(headerSize)); - writeJob->usedBufferSize = headerSize; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, headerSize); outFileSize += headerSize; - /* Read first block */ - inFileSize += AIO_ReadPool_fillBuffer(ress->readCtx, blockSize); + { + size_t const added = FIO_SyncCompressIO_fillBuffer(io, blockSize); + inFileSize += added; + *readsize += added; + } - /* Main Loop */ - while (ress->readCtx->srcBufferLoaded) { - size_t inSize = MIN(blockSize, ress->readCtx->srcBufferLoaded); - size_t const outSize = LZ4F_compressUpdate(ctx, writeJob->buffer, writeJob->bufferSize, - ress->readCtx->srcBuffer, inSize, NULL); + while (io->srcBufferLoaded) { + size_t const inSize = MIN(blockSize, io->srcBufferLoaded); + size_t const outSize = LZ4F_compressUpdate(ctx, io->outBuffer, io->outCapacity, + io->srcBuffer, inSize, NULL); if (LZ4F_isError(outSize)) EXM_THROW(35, "zstd: %s: lz4 compression failed : %s", srcFileName, LZ4F_getErrorName(outSize)); @@ -1473,30 +1715,27 @@ FIO_compressLz4Frame(cRess_t* ress, (double)outFileSize/(double)inFileSize*100); } - /* Write Block */ - writeJob->usedBufferSize = outSize; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, outSize); - /* Read next block */ - AIO_ReadPool_consumeBytes(ress->readCtx, inSize); - inFileSize += AIO_ReadPool_fillBuffer(ress->readCtx, blockSize); + FIO_SyncCompressIO_consumeBytes(io, inSize); + { + size_t const added = FIO_SyncCompressIO_fillBuffer(io, blockSize); + inFileSize += added; + *readsize += added; + } } - /* End of Stream mark */ - headerSize = LZ4F_compressEnd(ctx, writeJob->buffer, writeJob->bufferSize, NULL); + headerSize = LZ4F_compressEnd(ctx, io->outBuffer, io->outCapacity, NULL); if (LZ4F_isError(headerSize)) EXM_THROW(38, "zstd: %s: lz4 end of file generation failed : %s", srcFileName, LZ4F_getErrorName(headerSize)); - writeJob->usedBufferSize = headerSize; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, headerSize); outFileSize += headerSize; } - *readsize = inFileSize; LZ4F_freeCompressionContext(ctx); - AIO_WritePool_releaseIoJob(writeJob); - AIO_WritePool_sparseWriteEnd(ress->writeCtx); + FIO_SyncCompressIO_finish(io); return outFileSize; } @@ -1505,12 +1744,11 @@ FIO_compressLz4Frame(cRess_t* ress, static unsigned long long FIO_compressZstdFrame(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, - const cRess_t* ressPtr, + cRess_t* ress, const char* srcFileName, U64 fileSize, int compressionLevel, U64* readsize) { - cRess_t const ress = *ressPtr; - IOJob_t* writeJob = AIO_WritePool_acquireJob(ressPtr->writeCtx); + FIO_SyncCompressIO* const io = &ress->io; U64 compressedfilesize = 0; ZSTD_EndDirective directive = ZSTD_e_continue; @@ -1535,16 +1773,16 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, /* init */ if (fileSize != UTIL_FILESIZE_UNKNOWN) { pledgedSrcSize = fileSize; - CHECK(ZSTD_CCtx_setPledgedSrcSize(ress.cctx, fileSize)); + CHECK(ZSTD_CCtx_setPledgedSrcSize(ress->cctx, fileSize)); } else if (prefs->streamSrcSize > 0) { /* unknown source size; use the declared stream size */ pledgedSrcSize = prefs->streamSrcSize; - CHECK( ZSTD_CCtx_setPledgedSrcSize(ress.cctx, prefs->streamSrcSize) ); + CHECK( ZSTD_CCtx_setPledgedSrcSize(ress->cctx, prefs->streamSrcSize) ); } { int windowLog; UTIL_HumanReadableSize_t windowSize; - CHECK(ZSTD_CCtx_getParameter(ress.cctx, ZSTD_c_windowLog, &windowLog)); + CHECK(ZSTD_CCtx_getParameter(ress->cctx, ZSTD_c_windowLog, &windowLog)); if (windowLog == 0) { if (prefs->ldmFlag) { /* If long mode is set without a window size libzstd will set this size internally */ @@ -1562,12 +1800,12 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, do { size_t stillToFlush; /* Fill input Buffer */ - size_t const inSize = AIO_ReadPool_fillBuffer(ress.readCtx, ZSTD_CStreamInSize()); - ZSTD_inBuffer inBuff = setInBuffer( ress.readCtx->srcBuffer, ress.readCtx->srcBufferLoaded, 0 ); + size_t const inSize = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); + ZSTD_inBuffer inBuff = setInBuffer( io->srcBuffer, io->srcBufferLoaded, 0 ); DISPLAYLEVEL(6, "fread %u bytes from source \n", (unsigned)inSize); *readsize += inSize; - if ((ress.readCtx->srcBufferLoaded == 0) || (*readsize == fileSize)) + if ((io->srcBufferLoaded == 0) || (*readsize == fileSize)) directive = ZSTD_e_end; stillToFlush = 1; @@ -1575,10 +1813,10 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, || (directive == ZSTD_e_end && stillToFlush != 0) ) { size_t const oldIPos = inBuff.pos; - ZSTD_outBuffer outBuff = setOutBuffer( writeJob->buffer, writeJob->bufferSize, 0 ); - size_t const toFlushNow = ZSTD_toFlushNow(ress.cctx); - CHECK_V(stillToFlush, ZSTD_compressStream2(ress.cctx, &outBuff, &inBuff, directive)); - AIO_ReadPool_consumeBytes(ress.readCtx, inBuff.pos - oldIPos); + ZSTD_outBuffer outBuff = setOutBuffer( io->outBuffer, io->outCapacity, 0 ); + size_t const toFlushNow = ZSTD_toFlushNow(ress->cctx); + CHECK_V(stillToFlush, ZSTD_compressStream2(ress->cctx, &outBuff, &inBuff, directive)); + FIO_SyncCompressIO_consumeBytes(io, inBuff.pos - oldIPos); /* count stats */ inputPresented++; @@ -1589,14 +1827,13 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, DISPLAYLEVEL(6, "ZSTD_compress_generic(end:%u) => input pos(%u)<=(%u)size ; output generated %u bytes \n", (unsigned)directive, (unsigned)inBuff.pos, (unsigned)inBuff.size, (unsigned)outBuff.pos); if (outBuff.pos) { - writeJob->usedBufferSize = outBuff.pos; - AIO_WritePool_enqueueAndReacquireWriteJob(&writeJob); + FIO_SyncCompressIO_commitOut(io, io->outBuffer, outBuff.pos); compressedfilesize += outBuff.pos; } /* adaptive mode : statistics measurement and speed correction */ if (prefs->adaptiveMode && UTIL_clockSpanMicro(lastAdaptTime) > adaptEveryMicro) { - ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress.cctx); + ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress->cctx); lastAdaptTime = UTIL_getTime(); @@ -1669,14 +1906,14 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, if (compressionLevel > ZSTD_maxCLevel()) compressionLevel = ZSTD_maxCLevel(); if (compressionLevel > prefs->maxAdaptLevel) compressionLevel = prefs->maxAdaptLevel; compressionLevel += (compressionLevel == 0); /* skip 0 */ - ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_compressionLevel, compressionLevel); + ZSTD_CCtx_setParameter(ress->cctx, ZSTD_c_compressionLevel, compressionLevel); } if (speedChange == faster) { DISPLAYLEVEL(6, "faster speed , lighter compression \n") compressionLevel --; if (compressionLevel < prefs->minAdaptLevel) compressionLevel = prefs->minAdaptLevel; compressionLevel -= (compressionLevel == 0); /* skip 0 */ - ZSTD_CCtx_setParameter(ress.cctx, ZSTD_c_compressionLevel, compressionLevel); + ZSTD_CCtx_setParameter(ress->cctx, ZSTD_c_compressionLevel, compressionLevel); } speedChange = noChange; @@ -1686,7 +1923,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, /* display notification */ if (SHOULD_DISPLAY_PROGRESS() && READY_FOR_UPDATE()) { - ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress.cctx); + ZSTD_frameProgression const zfp = ZSTD_getFrameProgression(ress->cctx); double const cShare = (double)zfp.produced / (double)(zfp.consumed + !zfp.consumed/*avoid div0*/) * 100; UTIL_HumanReadableSize_t const buffered_hrs = UTIL_makeHumanReadableSize(zfp.ingested - zfp.consumed); UTIL_HumanReadableSize_t const consumed_hrs = UTIL_makeHumanReadableSize(zfp.consumed); @@ -1733,8 +1970,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, (unsigned long long)*readsize, (unsigned long long)fileSize); } - AIO_WritePool_releaseIoJob(writeJob); - AIO_WritePool_sparseWriteEnd(ressPtr->writeCtx); + FIO_SyncCompressIO_finish(io); return compressedfilesize; } @@ -1747,7 +1983,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, static int FIO_compressFilename_internal(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, - cRess_t ress, + cRess_t* ress, const char* dstFileName, const char* srcFileName, int compressionLevel) { @@ -1762,12 +1998,12 @@ FIO_compressFilename_internal(FIO_ctx_t* const fCtx, switch (prefs->compressionType) { default: case FIO_zstdCompression: - compressedfilesize = FIO_compressZstdFrame(fCtx, prefs, &ress, srcFileName, fileSize, compressionLevel, &readsize); + compressedfilesize = FIO_compressZstdFrame(fCtx, prefs, ress, srcFileName, fileSize, compressionLevel, &readsize); break; case FIO_gzipCompression: #ifdef ZSTD_GZCOMPRESS - compressedfilesize = FIO_compressGzFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize); + compressedfilesize = FIO_compressGzFrame(ress, srcFileName, fileSize, compressionLevel, &readsize); #else (void)compressionLevel; EXM_THROW(20, "zstd: %s: file cannot be compressed as gzip (zstd compiled without ZSTD_GZCOMPRESS) -- ignored \n", @@ -1778,7 +2014,7 @@ FIO_compressFilename_internal(FIO_ctx_t* const fCtx, case FIO_xzCompression: case FIO_lzmaCompression: #ifdef ZSTD_LZMACOMPRESS - compressedfilesize = FIO_compressLzmaFrame(&ress, srcFileName, fileSize, compressionLevel, &readsize, prefs->compressionType==FIO_lzmaCompression); + compressedfilesize = FIO_compressLzmaFrame(ress, srcFileName, fileSize, compressionLevel, &readsize, prefs->compressionType==FIO_lzmaCompression); #else (void)compressionLevel; EXM_THROW(20, "zstd: %s: file cannot be compressed as xz/lzma (zstd compiled without ZSTD_LZMACOMPRESS) -- ignored \n", @@ -1788,7 +2024,7 @@ FIO_compressFilename_internal(FIO_ctx_t* const fCtx, case FIO_lz4Compression: #ifdef ZSTD_LZ4COMPRESS - compressedfilesize = FIO_compressLz4Frame(&ress, srcFileName, fileSize, compressionLevel, prefs->checksumFlag, &readsize); + compressedfilesize = FIO_compressLz4Frame(ress, srcFileName, fileSize, compressionLevel, prefs->checksumFlag, &readsize); #else (void)compressionLevel; EXM_THROW(20, "zstd: %s: file cannot be compressed as lz4 (zstd compiled without ZSTD_LZ4COMPRESS) -- ignored \n", @@ -1844,7 +2080,7 @@ FIO_compressFilename_internal(FIO_ctx_t* const fCtx, */ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, - cRess_t ress, + cRess_t* ress, const char* dstFileName, const char* srcFileName, const stat_t* srcFileStat, @@ -1855,8 +2091,7 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx, int transferStat = 0; int dstFd = -1; - assert(AIO_ReadPool_getFile(ress.readCtx) != NULL); - if (AIO_WritePool_getFile(ress.writeCtx) == NULL) { + if (ress->io.dstFile == NULL) { int dstFileInitialPermissions = DEFAULT_FILE_PERMISSIONS; if ( strcmp (srcFileName, stdinmark) && strcmp (dstFileName, stdoutmark) @@ -1867,15 +2102,13 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx, closeDstFile = 1; DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: opening dst: %s \n", dstFileName); - { FILE *dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName, dstFileInitialPermissions); + { + FILE *dstFile = FIO_openDstFile(fCtx, prefs, srcFileName, dstFileName, dstFileInitialPermissions); if (dstFile==NULL) return 1; /* could not open dstFileName */ dstFd = fileno(dstFile); - AIO_WritePool_setFile(ress.writeCtx, dstFile); + FIO_SyncCompressIO_setDst(&ress->io, dstFile); } - /* Must only be added after FIO_openDstFile() succeeds. - * Otherwise we may delete the destination file if it already exists, - * and the user presses Ctrl-C when asked if they wish to overwrite. - */ + /* Must only be added after FIO_openDstFile() succeeds. */ addHandler(dstFileName); } @@ -1889,7 +2122,7 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx, } DISPLAYLEVEL(6, "FIO_compressFilename_dstFile: closing dst: %s \n", dstFileName); - if (AIO_WritePool_closeFile(ress.writeCtx)) { /* error closing file */ + if (FIO_SyncCompressIO_closeDst(&ress->io)) { /* error closing file */ DISPLAYLEVEL(1, "zstd: %s: %s \n", dstFileName, strerror(errno)); result=1; } @@ -1898,10 +2131,9 @@ static int FIO_compressFilename_dstFile(FIO_ctx_t* const fCtx, UTIL_utime(dstFileName, srcFileStat); } - if ( (result != 0) /* operation failure */ - && strcmp(dstFileName, stdoutmark) /* special case : don't remove() stdout */ - ) { - FIO_removeFile(dstFileName); /* remove compression artefact; note don't do anything special if remove() fails */ + if ( (result != 0) + && strcmp(dstFileName, stdoutmark) ) { + FIO_removeFile(dstFileName); } } @@ -2035,7 +2267,7 @@ static const char *compressedFileExtensions[] = { static int FIO_compressFilename_srcFile(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, - cRess_t ress, + cRess_t* ress, const char* dstFileName, const char* srcFileName, int compressionLevel) @@ -2057,7 +2289,7 @@ FIO_compressFilename_srcFile(FIO_ctx_t* const fCtx, } /* ensure src is not the same as dict (if present) */ - if (ress.dictFileName != NULL && UTIL_isSameFileStat(srcFileName, ress.dictFileName, &srcFileStat, &ress.dictFileStat)) { + if (ress->dictFileName != NULL && UTIL_isSameFileStat(srcFileName, ress->dictFileName, &srcFileStat, &ress->dictFileStat)) { DISPLAYLEVEL(1, "zstd: cannot use %s as an input file and dictionary \n", srcFileName); return 1; } @@ -2076,19 +2308,21 @@ FIO_compressFilename_srcFile(FIO_ctx_t* const fCtx, srcFile = FIO_openSrcFile(prefs, srcFileName, &srcFileStat); if (srcFile == NULL) return 1; /* srcFile could not be opened */ - /* AsyncIO is disabled for compression to favor predictable performance and simpler upkeep. */ if (strcmp(srcFileName, stdinmark)) /* Stdin doesn't have stats */ fileSize = UTIL_getFileSizeStat(&srcFileStat); (void)fileSize; - AIO_ReadPool_setAsync(ress.readCtx, 0); - AIO_WritePool_setAsync(ress.writeCtx, 0); - AIO_ReadPool_setFile(ress.readCtx, srcFile); + FIO_SyncCompressIO_setSrc(&ress->io, srcFile); result = FIO_compressFilename_dstFile( fCtx, prefs, ress, dstFileName, srcFileName, &srcFileStat, compressionLevel); - AIO_ReadPool_closeFile(ress.readCtx); + FIO_SyncCompressIO_clearSrc(&ress->io); + + if (srcFile != NULL && fclose(srcFile)) { + DISPLAYLEVEL(1, "zstd: %s: %s \n", srcFileName, strerror(errno)); + return 1; + } if ( prefs->removeSrcFile /* --rm */ && result == 0 /* success */ @@ -2155,7 +2389,7 @@ int FIO_compressFilename(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, const int compressionLevel, ZSTD_compressionParameters comprParams) { cRess_t ress = FIO_createCResources(prefs, dictFileName, UTIL_getFileSize(srcFileName), compressionLevel, comprParams); - int const result = FIO_compressFilename_srcFile(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel); + int const result = FIO_compressFilename_srcFile(fCtx, prefs, &ress, dstFileName, srcFileName, compressionLevel); #define DISPLAY_LEVEL_DEFAULT 2 @@ -2252,13 +2486,13 @@ int FIO_compressMultipleFilenames(FIO_ctx_t* const fCtx, if (dstFile == NULL) { /* could not open outFileName */ error = 1; } else { - AIO_WritePool_setFile(ress.writeCtx, dstFile); + FIO_SyncCompressIO_setDst(&ress.io, dstFile); for (; fCtx->currFileIdx < fCtx->nbFilesTotal; ++fCtx->currFileIdx) { - status = FIO_compressFilename_srcFile(fCtx, prefs, ress, outFileName, inFileNamesTable[fCtx->currFileIdx], compressionLevel); + status = FIO_compressFilename_srcFile(fCtx, prefs, &ress, outFileName, inFileNamesTable[fCtx->currFileIdx], compressionLevel); if (!status) fCtx->nbFilesProcessed++; error |= status; } - if (AIO_WritePool_closeFile(ress.writeCtx)) + if (FIO_SyncCompressIO_closeDst(&ress.io)) EXM_THROW(29, "Write error (%s) : cannot properly close %s", strerror(errno), outFileName); } @@ -2282,7 +2516,7 @@ int FIO_compressMultipleFilenames(FIO_ctx_t* const fCtx, } else { dstFileName = FIO_determineCompressedName(srcFileName, outDirName, suffix); /* cannot fail */ } - status = FIO_compressFilename_srcFile(fCtx, prefs, ress, dstFileName, srcFileName, compressionLevel); + status = FIO_compressFilename_srcFile(fCtx, prefs, &ress, dstFileName, srcFileName, compressionLevel); if (!status) fCtx->nbFilesProcessed++; error |= status; } From ccadc33a599d61f1a8cbeee7a96cd07a7cc8de24 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 25 Oct 2025 11:11:48 -0700 Subject: [PATCH 875/937] minor: use init/destroy pair naming convention --- programs/fileio.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index 1e767ee64..a6e361821 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -68,7 +68,7 @@ static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, const FIO_prefs_t* prefs, size_t inCapacity, size_t outCapacity); -static void FIO_SyncCompressIO_free(FIO_SyncCompressIO* io); +static void FIO_SyncCompressIO_destroy(FIO_SyncCompressIO* io); static void FIO_SyncCompressIO_setSrc(FIO_SyncCompressIO* io, FILE* file); static void FIO_SyncCompressIO_clearSrc(FIO_SyncCompressIO* io); static void FIO_SyncCompressIO_setDst(FIO_SyncCompressIO* io, FILE* file); @@ -274,7 +274,7 @@ static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, io->srcBufferLoaded = 0; } -static void FIO_SyncCompressIO_free(FIO_SyncCompressIO* io) +static void FIO_SyncCompressIO_destroy(FIO_SyncCompressIO* io) { if (!io) return; free(io->inBuffer); @@ -1467,7 +1467,7 @@ static cRess_t FIO_createCResources(FIO_prefs_t* const prefs, static void FIO_freeCResources(cRess_t* const ress) { FIO_freeDict(&(ress->dict)); - FIO_SyncCompressIO_free(&ress->io); + FIO_SyncCompressIO_destroy(&ress->io); ZSTD_freeCStream(ress->cctx); /* never fails */ } From 41f2673acda6543c6e8f3780926733439030e797 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 25 Oct 2025 11:23:16 -0700 Subject: [PATCH 876/937] changed name to syncIO for clarity --- programs/fileio.c | 110 +++++++++++++++++++++++----------------------- 1 file changed, 56 insertions(+), 54 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index a6e361821..eb489d210 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -50,6 +50,8 @@ UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER; /* ************************************* * Synchronous compression IO helpers +* Lightweight wrapper used by compression paths to manage buffered +* reads/writes without the async job machinery. ***************************************/ typedef struct { const FIO_prefs_t* prefs; @@ -1478,7 +1480,7 @@ FIO_compressGzFrame(cRess_t* ress, const char* srcFileName, U64 const srcFileSize, int compressionLevel, U64* readsize) { - FIO_SyncCompressIO* const io = &ress->io; + FIO_SyncCompressIO* const syncIO = &ress->io; unsigned long long inFileSize = 0, outFileSize = 0; z_stream strm; @@ -1498,34 +1500,34 @@ FIO_compressGzFrame(cRess_t* ress, strm.next_in = 0; strm.avail_in = 0; - strm.next_out = (Bytef*)io->outBuffer; - strm.avail_out = (uInt)io->outCapacity; + strm.next_out = (Bytef*)syncIO->outBuffer; + strm.avail_out = (uInt)syncIO->outCapacity; while (1) { int ret; if (strm.avail_in == 0) { - size_t const added = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); - if (io->srcBufferLoaded == 0) break; + size_t const added = FIO_SyncCompressIO_fillBuffer(syncIO, ZSTD_CStreamInSize()); + if (syncIO->srcBufferLoaded == 0) break; inFileSize += added; *readsize += added; - strm.next_in = (z_const unsigned char*)io->srcBuffer; - strm.avail_in = (uInt)io->srcBufferLoaded; + strm.next_in = (z_const unsigned char*)syncIO->srcBuffer; + strm.avail_in = (uInt)syncIO->srcBufferLoaded; } { size_t const availBefore = strm.avail_in; ret = deflate(&strm, Z_NO_FLUSH); - FIO_SyncCompressIO_consumeBytes(io, availBefore - strm.avail_in); + FIO_SyncCompressIO_consumeBytes(syncIO, availBefore - strm.avail_in); } if (ret != Z_OK) EXM_THROW(72, "zstd: %s: deflate error %d \n", srcFileName, ret); - { size_t const cSize = (size_t)((uInt)io->outCapacity - strm.avail_out); + { size_t const cSize = (size_t)((uInt)syncIO->outCapacity - strm.avail_out); if (cSize) { - FIO_SyncCompressIO_commitOut(io, io->outBuffer, cSize); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, cSize); outFileSize += cSize; - strm.next_out = (Bytef*)io->outBuffer; - strm.avail_out = (uInt)io->outCapacity; + strm.next_out = (Bytef*)syncIO->outBuffer; + strm.avail_out = (uInt)syncIO->outCapacity; } } if (srcFileSize == UTIL_FILESIZE_UNKNOWN) { DISPLAYUPDATE_PROGRESS( @@ -1541,12 +1543,12 @@ FIO_compressGzFrame(cRess_t* ress, while (1) { int const ret = deflate(&strm, Z_FINISH); - { size_t const cSize = (size_t)((uInt)io->outCapacity - strm.avail_out); + { size_t const cSize = (size_t)((uInt)syncIO->outCapacity - strm.avail_out); if (cSize) { - FIO_SyncCompressIO_commitOut(io, io->outBuffer, cSize); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, cSize); outFileSize += cSize; - strm.next_out = (Bytef*)io->outBuffer; - strm.avail_out = (uInt)io->outCapacity; + strm.next_out = (Bytef*)syncIO->outBuffer; + strm.avail_out = (uInt)syncIO->outCapacity; } } if (ret == Z_STREAM_END) break; if (ret != Z_BUF_ERROR) @@ -1558,7 +1560,7 @@ FIO_compressGzFrame(cRess_t* ress, EXM_THROW(79, "zstd: %s: deflateEnd error %d \n", srcFileName, ret); } } *readsize = inFileSize; - FIO_SyncCompressIO_finish(io); + FIO_SyncCompressIO_finish(syncIO); return outFileSize; } #endif @@ -1570,7 +1572,7 @@ FIO_compressLzmaFrame(cRess_t* ress, const char* srcFileName, U64 const srcFileSize, int compressionLevel, U64* readsize, int plain_lzma) { - FIO_SyncCompressIO* const io = &ress->io; + FIO_SyncCompressIO* const syncIO = &ress->io; unsigned long long inFileSize = 0, outFileSize = 0; lzma_stream strm = LZMA_STREAM_INIT; lzma_action action = LZMA_RUN; @@ -1592,35 +1594,35 @@ FIO_compressLzmaFrame(cRess_t* ress, EXM_THROW(83, "zstd: %s: lzma_easy_encoder error %d", srcFileName, ret); } - strm.next_out = (BYTE*)io->outBuffer; - strm.avail_out = io->outCapacity; + strm.next_out = (BYTE*)syncIO->outBuffer; + strm.avail_out = syncIO->outCapacity; strm.next_in = 0; strm.avail_in = 0; while (1) { if (strm.avail_in == 0) { - size_t const added = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); - if (io->srcBufferLoaded == 0) action = LZMA_FINISH; + size_t const added = FIO_SyncCompressIO_fillBuffer(syncIO, ZSTD_CStreamInSize()); + if (syncIO->srcBufferLoaded == 0) action = LZMA_FINISH; inFileSize += added; *readsize += added; - strm.next_in = (BYTE const*)io->srcBuffer; - strm.avail_in = io->srcBufferLoaded; + strm.next_in = (BYTE const*)syncIO->srcBuffer; + strm.avail_in = syncIO->srcBufferLoaded; } { size_t const availBefore = strm.avail_in; ret = lzma_code(&strm, action); - FIO_SyncCompressIO_consumeBytes(io, availBefore - strm.avail_in); + FIO_SyncCompressIO_consumeBytes(syncIO, availBefore - strm.avail_in); } if (ret != LZMA_OK && ret != LZMA_STREAM_END) EXM_THROW(84, "zstd: %s: lzma_code encoding error %d", srcFileName, ret); - { size_t const compBytes = io->outCapacity - strm.avail_out; + { size_t const compBytes = syncIO->outCapacity - strm.avail_out; if (compBytes) { - FIO_SyncCompressIO_commitOut(io, io->outBuffer, compBytes); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, compBytes); outFileSize += compBytes; - strm.next_out = (BYTE*)io->outBuffer; - strm.avail_out = io->outCapacity; + strm.next_out = (BYTE*)syncIO->outBuffer; + strm.avail_out = syncIO->outCapacity; } } if (srcFileSize == UTIL_FILESIZE_UNKNOWN) DISPLAYUPDATE_PROGRESS("\rRead : %u MB ==> %.2f%%", @@ -1636,7 +1638,7 @@ FIO_compressLzmaFrame(cRess_t* ress, lzma_end(&strm); *readsize = inFileSize; - FIO_SyncCompressIO_finish(io); + FIO_SyncCompressIO_finish(syncIO); return outFileSize; } @@ -1657,7 +1659,7 @@ FIO_compressLz4Frame(cRess_t* ress, int compressionLevel, int checksumFlag, U64* readsize) { - FIO_SyncCompressIO* const io = &ress->io; + FIO_SyncCompressIO* const syncIO = &ress->io; const size_t blockSize = FIO_LZ4_GetBlockSize_FromBlockId(LZ4F_max64KB); unsigned long long inFileSize = 0, outFileSize = 0; @@ -1670,7 +1672,7 @@ FIO_compressLz4Frame(cRess_t* ress, memset(&prefs, 0, sizeof(prefs)); - assert(blockSize <= io->inCapacity); + assert(blockSize <= syncIO->inCapacity); /* autoflush off to mitigate a bug in lz4<=1.9.3 for compression level 12 */ prefs.autoFlush = 0; @@ -1681,26 +1683,26 @@ FIO_compressLz4Frame(cRess_t* ress, #if LZ4_VERSION_NUMBER >= 10600 prefs.frameInfo.contentSize = (srcFileSize==UTIL_FILESIZE_UNKNOWN) ? 0 : srcFileSize; #endif - assert(LZ4F_compressBound(blockSize, &prefs) <= io->outCapacity); + assert(LZ4F_compressBound(blockSize, &prefs) <= syncIO->outCapacity); { - size_t headerSize = LZ4F_compressBegin(ctx, io->outBuffer, io->outCapacity, &prefs); + size_t headerSize = LZ4F_compressBegin(ctx, syncIO->outBuffer, syncIO->outCapacity, &prefs); if (LZ4F_isError(headerSize)) EXM_THROW(33, "File header generation failed : %s", LZ4F_getErrorName(headerSize)); - FIO_SyncCompressIO_commitOut(io, io->outBuffer, headerSize); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, headerSize); outFileSize += headerSize; { - size_t const added = FIO_SyncCompressIO_fillBuffer(io, blockSize); + size_t const added = FIO_SyncCompressIO_fillBuffer(syncIO, blockSize); inFileSize += added; *readsize += added; } - while (io->srcBufferLoaded) { - size_t const inSize = MIN(blockSize, io->srcBufferLoaded); - size_t const outSize = LZ4F_compressUpdate(ctx, io->outBuffer, io->outCapacity, - io->srcBuffer, inSize, NULL); + while (syncIO->srcBufferLoaded) { + size_t const inSize = MIN(blockSize, syncIO->srcBufferLoaded); + size_t const outSize = LZ4F_compressUpdate(ctx, syncIO->outBuffer, syncIO->outCapacity, + syncIO->srcBuffer, inSize, NULL); if (LZ4F_isError(outSize)) EXM_THROW(35, "zstd: %s: lz4 compression failed : %s", srcFileName, LZ4F_getErrorName(outSize)); @@ -1715,27 +1717,27 @@ FIO_compressLz4Frame(cRess_t* ress, (double)outFileSize/(double)inFileSize*100); } - FIO_SyncCompressIO_commitOut(io, io->outBuffer, outSize); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, outSize); - FIO_SyncCompressIO_consumeBytes(io, inSize); + FIO_SyncCompressIO_consumeBytes(syncIO, inSize); { - size_t const added = FIO_SyncCompressIO_fillBuffer(io, blockSize); + size_t const added = FIO_SyncCompressIO_fillBuffer(syncIO, blockSize); inFileSize += added; *readsize += added; } } - headerSize = LZ4F_compressEnd(ctx, io->outBuffer, io->outCapacity, NULL); + headerSize = LZ4F_compressEnd(ctx, syncIO->outBuffer, syncIO->outCapacity, NULL); if (LZ4F_isError(headerSize)) EXM_THROW(38, "zstd: %s: lz4 end of file generation failed : %s", srcFileName, LZ4F_getErrorName(headerSize)); - FIO_SyncCompressIO_commitOut(io, io->outBuffer, headerSize); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, headerSize); outFileSize += headerSize; } LZ4F_freeCompressionContext(ctx); - FIO_SyncCompressIO_finish(io); + FIO_SyncCompressIO_finish(syncIO); return outFileSize; } @@ -1748,7 +1750,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, const char* srcFileName, U64 fileSize, int compressionLevel, U64* readsize) { - FIO_SyncCompressIO* const io = &ress->io; + FIO_SyncCompressIO* const syncIO = &ress->io; U64 compressedfilesize = 0; ZSTD_EndDirective directive = ZSTD_e_continue; @@ -1800,12 +1802,12 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, do { size_t stillToFlush; /* Fill input Buffer */ - size_t const inSize = FIO_SyncCompressIO_fillBuffer(io, ZSTD_CStreamInSize()); - ZSTD_inBuffer inBuff = setInBuffer( io->srcBuffer, io->srcBufferLoaded, 0 ); + size_t const inSize = FIO_SyncCompressIO_fillBuffer(syncIO, ZSTD_CStreamInSize()); + ZSTD_inBuffer inBuff = setInBuffer( syncIO->srcBuffer, syncIO->srcBufferLoaded, 0 ); DISPLAYLEVEL(6, "fread %u bytes from source \n", (unsigned)inSize); *readsize += inSize; - if ((io->srcBufferLoaded == 0) || (*readsize == fileSize)) + if ((syncIO->srcBufferLoaded == 0) || (*readsize == fileSize)) directive = ZSTD_e_end; stillToFlush = 1; @@ -1813,10 +1815,10 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, || (directive == ZSTD_e_end && stillToFlush != 0) ) { size_t const oldIPos = inBuff.pos; - ZSTD_outBuffer outBuff = setOutBuffer( io->outBuffer, io->outCapacity, 0 ); + ZSTD_outBuffer outBuff = setOutBuffer( syncIO->outBuffer, syncIO->outCapacity, 0 ); size_t const toFlushNow = ZSTD_toFlushNow(ress->cctx); CHECK_V(stillToFlush, ZSTD_compressStream2(ress->cctx, &outBuff, &inBuff, directive)); - FIO_SyncCompressIO_consumeBytes(io, inBuff.pos - oldIPos); + FIO_SyncCompressIO_consumeBytes(syncIO, inBuff.pos - oldIPos); /* count stats */ inputPresented++; @@ -1827,7 +1829,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, DISPLAYLEVEL(6, "ZSTD_compress_generic(end:%u) => input pos(%u)<=(%u)size ; output generated %u bytes \n", (unsigned)directive, (unsigned)inBuff.pos, (unsigned)inBuff.size, (unsigned)outBuff.pos); if (outBuff.pos) { - FIO_SyncCompressIO_commitOut(io, io->outBuffer, outBuff.pos); + FIO_SyncCompressIO_commitOut(syncIO, syncIO->outBuffer, outBuff.pos); compressedfilesize += outBuff.pos; } @@ -1970,7 +1972,7 @@ FIO_compressZstdFrame(FIO_ctx_t* const fCtx, (unsigned long long)*readsize, (unsigned long long)fileSize); } - FIO_SyncCompressIO_finish(io); + FIO_SyncCompressIO_finish(syncIO); return compressedfilesize; } From 7a3c940e7f6df29124f31f7e8c64d4f4dc59786e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 26 Oct 2025 09:48:45 -0700 Subject: [PATCH 877/937] syncio interface only enabled when compression is enabled --- programs/fileio.c | 70 +++++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/programs/fileio.c b/programs/fileio.c index eb489d210..4000c5b62 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -48,38 +48,6 @@ FIO_display_prefs_t g_display_prefs = {2, FIO_ps_auto}; UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER; -/* ************************************* -* Synchronous compression IO helpers -* Lightweight wrapper used by compression paths to manage buffered -* reads/writes without the async job machinery. -***************************************/ -typedef struct { - const FIO_prefs_t* prefs; - FILE* srcFile; - FILE* dstFile; - unsigned storedSkips; - U8* inBuffer; - size_t inCapacity; - U8* srcBuffer; - size_t srcBufferLoaded; - U8* outBuffer; - size_t outCapacity; -} FIO_SyncCompressIO; - -static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, - const FIO_prefs_t* prefs, - size_t inCapacity, - size_t outCapacity); -static void FIO_SyncCompressIO_destroy(FIO_SyncCompressIO* io); -static void FIO_SyncCompressIO_setSrc(FIO_SyncCompressIO* io, FILE* file); -static void FIO_SyncCompressIO_clearSrc(FIO_SyncCompressIO* io); -static void FIO_SyncCompressIO_setDst(FIO_SyncCompressIO* io, FILE* file); -static int FIO_SyncCompressIO_closeDst(FIO_SyncCompressIO* io); -static size_t FIO_SyncCompressIO_fillBuffer(FIO_SyncCompressIO* io, size_t minToHave); -static void FIO_SyncCompressIO_consumeBytes(FIO_SyncCompressIO* io, size_t n); -static void FIO_SyncCompressIO_commitOut(FIO_SyncCompressIO* io, const void* buffer, size_t size); -static void FIO_SyncCompressIO_finish(FIO_SyncCompressIO* io); - #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_magicNumber, ZSTD_frameHeaderSize_max */ #include "../lib/zstd.h" #include "../lib/zstd_errors.h" /* ZSTD_error_frameParameter_windowTooLarge */ @@ -157,6 +125,42 @@ char const* FIO_lzmaVersion(void) #define TEMPORARY_FILE_PERMISSIONS (0600) #endif + +#ifndef ZSTD_NOCOMPRESS + +/* ************************************* +* Synchronous compression IO helpers +* Lightweight wrapper used by compression paths to manage buffered +* reads/writes without the async job machinery. +***************************************/ +typedef struct { + const FIO_prefs_t* prefs; + FILE* srcFile; + FILE* dstFile; + unsigned storedSkips; + U8* inBuffer; + size_t inCapacity; + U8* srcBuffer; + size_t srcBufferLoaded; + U8* outBuffer; + size_t outCapacity; +} FIO_SyncCompressIO; + +static void FIO_SyncCompressIO_init(FIO_SyncCompressIO* io, + const FIO_prefs_t* prefs, + size_t inCapacity, + size_t outCapacity); +static void FIO_SyncCompressIO_destroy(FIO_SyncCompressIO* io); +static void FIO_SyncCompressIO_setSrc(FIO_SyncCompressIO* io, FILE* file); +static void FIO_SyncCompressIO_clearSrc(FIO_SyncCompressIO* io); +static void FIO_SyncCompressIO_setDst(FIO_SyncCompressIO* io, FILE* file); +static int FIO_SyncCompressIO_closeDst(FIO_SyncCompressIO* io); +static size_t FIO_SyncCompressIO_fillBuffer(FIO_SyncCompressIO* io, size_t minToHave); +static void FIO_SyncCompressIO_consumeBytes(FIO_SyncCompressIO* io, size_t n); +static void FIO_SyncCompressIO_commitOut(FIO_SyncCompressIO* io, const void* buffer, size_t size); +static void FIO_SyncCompressIO_finish(FIO_SyncCompressIO* io); + + static unsigned FIO_sparseWrite(FILE* file, const void* buffer, size_t bufferSize, const FIO_prefs_t* const prefs, @@ -384,6 +388,8 @@ static void FIO_SyncCompressIO_finish(FIO_SyncCompressIO* io) io->storedSkips = 0; } +#endif /* ZSTD_NOCOMPRESS */ + /*-************************************ * Signal (Ctrl-C trapping) **************************************/ From 129769d04c459866697391d0e21f0121a614052d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Oct 2025 05:18:47 +0000 Subject: [PATCH 878/937] Bump actions/upload-artifact from 4 to 5 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index fe91f2fcc..872e3b734 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -99,6 +99,6 @@ jobs: echo " are still good, copy it into the repo and commit it." echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v5 with: path: "/tmp/circleci-artifacts" diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 0450324ee..4b2d2b3f1 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -317,7 +317,7 @@ jobs: dry-run: false sanitizer: ${{ matrix.sanitizer }} - name: Upload Crash - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 if: failure() && steps.build.outcome == 'success' with: name: ${{ matrix.sanitizer }}-artifacts diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index be14cb5d5..f4d49c218 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -51,7 +51,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 with: name: SARIF file path: results.sarif diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index fcc81c395..249ef28b2 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -93,7 +93,7 @@ jobs: mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # tag=v4.3.1 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 with: compression-level: 9 # maximum compression if-no-files-found: error # defaults to `warn` From 273ab1bbdf479f68a25290d25e540cd41f9dacf5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 3 Nov 2025 05:08:56 +0000 Subject: [PATCH 879/937] Bump github/codeql-action from 3.30.1 to 4.31.2 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.30.1 to 4.31.2. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/f1f6e5f6af878fb37288ce1c627459e94dbf7d01...0499de31b99561a6d14a36a5f662c2a54f91beee) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 4.31.2 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index f4d49c218..5fd3b4870 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@f1f6e5f6af878fb37288ce1c627459e94dbf7d01 # tag=v3.30.1 + uses: github/codeql-action/upload-sarif@0499de31b99561a6d14a36a5f662c2a54f91beee # tag=v4.31.2 with: sarif_file: results.sarif From 71146f5b6d975d0b6d20426ee14ce28afbfb0d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E5=B0=9A=E8=AF=9A10330306?= Date: Mon, 3 Nov 2025 16:37:05 +0800 Subject: [PATCH 880/937] Add RISC-V 64-bit architecture detection --- programs/platform.h | 1 + 1 file changed, 1 insertion(+) diff --git a/programs/platform.h b/programs/platform.h index e2cc1c3e6..9f1c968f4 100644 --- a/programs/platform.h +++ b/programs/platform.h @@ -35,6 +35,7 @@ || defined __x86_64__ || defined _M_X64 /* x86 64-bit */ \ || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__ /* ARM 64-bit */ \ || (defined __mips && (__mips == 64 || __mips == 4 || __mips == 3)) /* MIPS 64-bit */ \ + || (defined(__riscv) && __riscv_xlen == 64) /* RISC-V 64-bit */ \ || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \ || (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */ # if !defined(__64BIT__) From e23477ce3e387279339e68b91ec5feffe432eb3c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Nov 2025 05:05:06 +0000 Subject: [PATCH 881/937] Bump actions/checkout from 5.0.0 to 6.0.0 Bumps [actions/checkout](https://github.com/actions/checkout) from 5.0.0 to 6.0.0. - [Release notes](https://github.com/actions/checkout/releases) - [Commits](https://github.com/actions/checkout/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: 6.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- .github/workflows/cmake-tests.yml | 10 +-- .github/workflows/commit.yml | 6 +- .github/workflows/dev-long-tests.yml | 54 ++++++------- .github/workflows/dev-short-tests.yml | 76 +++++++++---------- .github/workflows/nightly.yml | 2 +- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/release_check.yml | 4 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 10 files changed, 80 insertions(+), 80 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 99183049c..23f5601fd 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: Set up JDK 17 uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0 diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 5534cdf89..fd936c130 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -28,7 +28,7 @@ jobs: name: "CMake Root Build" runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: Configure (Root) run: | cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release ${{ env.COMMON_CMAKE_FLAGS }} @@ -43,7 +43,7 @@ jobs: name: "CMake build using make wrapper" runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: Install dependencies run: | sudo apt install liblzma-dev # Required for compression algorithms @@ -73,7 +73,7 @@ jobs: env: SRC_DIR: "source directory with spaces" steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 with: path: "${{ env.SRC_DIR }}" - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 @@ -131,7 +131,7 @@ jobs: runner: "windows-2022" cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - name: "Configure CMake (${{ matrix.name }})" @@ -156,7 +156,7 @@ jobs: name: "CMake macOS ARM64 (Apple Silicon)" runs-on: macos-14 # ARM64 runner steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: "CMake build and test (ARM64)" run: | # Configure and build with ARM64-specific optimizations diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 872e3b734..071b8f94d 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -17,7 +17,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6.0.0 - name: Install Dependencies run: | sudo apt-get update @@ -40,7 +40,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6.0.0 - name: Install Dependencies run: | sudo apt-get update @@ -73,7 +73,7 @@ jobs: env: CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6.0.0 - name: restore_cache uses: actions/cache@v4 with: diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 4b2d2b3f1..f9ad1d975 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -16,7 +16,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: make all run: make all @@ -27,7 +27,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: make test run: | make test @@ -38,7 +38,7 @@ jobs: make-test-macos: runs-on: macos-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: make test on macos run: make test @@ -49,7 +49,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update @@ -61,7 +61,7 @@ jobs: test-largeDictionary: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: largeDictionary run: | CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary @@ -70,7 +70,7 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest @@ -78,14 +78,14 @@ jobs: tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream uasan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream @@ -93,14 +93,14 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -111,7 +111,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -123,14 +123,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # tag=v5.0.0 + - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Tue, 25 Nov 2025 16:38:08 +0100 Subject: [PATCH 882/937] modulemap: remove `config_macros` --- lib/module.modulemap | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/lib/module.modulemap b/lib/module.modulemap index eff98dfac..e66a210d0 100644 --- a/lib/module.modulemap +++ b/lib/module.modulemap @@ -1,27 +1,6 @@ module libzstd [extern_c] { header "zstd.h" export * - config_macros [exhaustive] \ - /* zstd.h */ \ - ZSTD_STATIC_LINKING_ONLY, \ - ZSTDLIB_VISIBILITY, \ - ZSTDLIB_VISIBLE, \ - ZSTDLIB_HIDDEN, \ - ZSTD_DLL_EXPORT, \ - ZSTDLIB_STATIC_API, \ - ZSTD_DISABLE_DEPRECATE_WARNINGS, \ - ZSTD_CLEVEL_DEFAULT, \ - /* zdict.h */ \ - ZDICT_STATIC_LINKING_ONLY, \ - ZDICTLIB_VISIBLE, \ - ZDICTLIB_HIDDEN, \ - ZDICTLIB_VISIBILITY, \ - ZDICTLIB_STATIC_API, \ - ZDICT_DISABLE_DEPRECATE_WARNINGS, \ - /* zstd_errors.h */ \ - ZSTDERRORLIB_VISIBLE, \ - ZSTDERRORLIB_HIDDEN, \ - ZSTDERRORLIB_VISIBILITY module dictbuilder [extern_c] { header "zdict.h" From 757f1bf465ec80fff2b98ee68a63eda6cd4255a1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Dec 2025 05:05:30 +0000 Subject: [PATCH 883/937] Bump actions/checkout from 6.0.0 to 6.0.1 Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.0 to 6.0.1. - [Release notes](https://github.com/actions/checkout/releases) - [Commits](https://github.com/actions/checkout/compare/v6...v6.0.1) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: 6.0.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- .github/workflows/cmake-tests.yml | 10 +-- .github/workflows/commit.yml | 6 +- .github/workflows/dev-long-tests.yml | 54 ++++++------- .github/workflows/dev-short-tests.yml | 76 +++++++++---------- .github/workflows/nightly.yml | 2 +- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/release_check.yml | 4 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 10 files changed, 80 insertions(+), 80 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 23f5601fd..826ca5553 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Set up JDK 17 uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0 diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index fd936c130..a293e77cf 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -28,7 +28,7 @@ jobs: name: "CMake Root Build" runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Configure (Root) run: | cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release ${{ env.COMMON_CMAKE_FLAGS }} @@ -43,7 +43,7 @@ jobs: name: "CMake build using make wrapper" runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Install dependencies run: | sudo apt install liblzma-dev # Required for compression algorithms @@ -73,7 +73,7 @@ jobs: env: SRC_DIR: "source directory with spaces" steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 with: path: "${{ env.SRC_DIR }}" - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 @@ -131,7 +131,7 @@ jobs: runner: "windows-2022" cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - name: "Configure CMake (${{ matrix.name }})" @@ -156,7 +156,7 @@ jobs: name: "CMake macOS ARM64 (Apple Silicon)" runs-on: macos-14 # ARM64 runner steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: "CMake build and test (ARM64)" run: | # Configure and build with ARM64-specific optimizations diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 071b8f94d..3aeffdf36 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -17,7 +17,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v6.0.0 + - uses: actions/checkout@v6.0.1 - name: Install Dependencies run: | sudo apt-get update @@ -40,7 +40,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v6.0.0 + - uses: actions/checkout@v6.0.1 - name: Install Dependencies run: | sudo apt-get update @@ -73,7 +73,7 @@ jobs: env: CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - - uses: actions/checkout@v6.0.0 + - uses: actions/checkout@v6.0.1 - name: restore_cache uses: actions/cache@v4 with: diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index f9ad1d975..56d42f503 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -16,7 +16,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: make all run: make all @@ -27,7 +27,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: make test run: | make test @@ -38,7 +38,7 @@ jobs: make-test-macos: runs-on: macos-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: make test on macos run: make test @@ -49,7 +49,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update @@ -61,7 +61,7 @@ jobs: test-largeDictionary: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: largeDictionary run: | CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary @@ -70,7 +70,7 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest @@ -78,14 +78,14 @@ jobs: tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream uasan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream @@ -93,14 +93,14 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -111,7 +111,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -123,14 +123,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # tag=v6.0.0 + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Mon, 8 Dec 2025 23:25:45 +0000 Subject: [PATCH 884/937] Bump actions/setup-java from 5.0.0 to 5.1.0 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5.0.0 to 5.1.0. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/dded0888837ed1f317902acf8a20df0ad188d165...f2beeb24e141e01a676f977032f5a29d81c9e27e) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 5.1.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 826ca5553..3fc5cd317 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Set up JDK 17 - uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0 + uses: actions/setup-java@f2beeb24e141e01a676f977032f5a29d81c9e27e # v5.1.0 with: java-version: '17' distribution: 'temurin' From c7c29693c994114b69842314ef568d618a65aad7 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 9 Dec 2025 08:30:24 +0900 Subject: [PATCH 885/937] [ci] update freebsd image --- .cirrus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index 745024bc2..13258eded 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -2,7 +2,7 @@ task: name: FreeBSD (make check) freebsd_instance: matrix: - image_family: freebsd-14-2 + image_family: freebsd-16-0-snap install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From 1e06c42eece420f6659e635e9283b1419b277012 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 15 Dec 2025 05:04:44 +0000 Subject: [PATCH 886/937] Bump msys2/setup-msys2 from 2.29.0 to 2.30.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.29.0 to 2.30.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/fb197b72ce45fb24f17bf3f807a388985654d1f2...4f806de0a5a7294ffabaff804b38a9b435a73bda) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.30.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 56d42f503..ae9f5534e 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 + - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index e5e8d233f..33f7f3d67 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -487,7 +487,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 + - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 5f42b05cf..834b834ac 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 # MSYS2 setup - - uses: msys2/setup-msys2@fb197b72ce45fb24f17bf3f807a388985654d1f2 # tag=v2.29.0 + - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 if: matrix.shell == 'msys2' with: msystem: ${{ matrix.msystem }} From c26db2d0e8fdfabc682241122e509a9be13c42cb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 15 Dec 2025 05:04:53 +0000 Subject: [PATCH 887/937] Bump actions/upload-artifact from 5.0.0 to 6.0.0 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5.0.0 to 6.0.0. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: 6.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 3aeffdf36..6a278d6cd 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -99,6 +99,6 @@ jobs: echo " are still good, copy it into the repo and commit it." echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv - - uses: actions/upload-artifact@v5 + - uses: actions/upload-artifact@v6.0.0 with: path: "/tmp/circleci-artifacts" diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 56d42f503..478d09d8d 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -317,7 +317,7 @@ jobs: dry-run: false sanitizer: ${{ matrix.sanitizer }} - name: Upload Crash - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 if: failure() && steps.build.outcome == 'success' with: name: ${{ matrix.sanitizer }}-artifacts diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 22fbf0b21..0d635c38d 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -51,7 +51,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 with: name: SARIF file path: results.sarif diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 5f42b05cf..cd13dc729 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -93,7 +93,7 @@ jobs: mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # tag=v5.0.0 + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 with: compression-level: 9 # maximum compression if-no-files-found: error # defaults to `warn` From de9b0810ec8612dac8f3027db6e8fddb1bc61c70 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 15 Dec 2025 05:04:57 +0000 Subject: [PATCH 888/937] Bump actions/cache from 4 to 5 Bumps [actions/cache](https://github.com/actions/cache) from 4 to 5. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/cache dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 3aeffdf36..4bbfe6b9f 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -75,7 +75,7 @@ jobs: steps: - uses: actions/checkout@v6.0.1 - name: restore_cache - uses: actions/cache@v4 + uses: actions/cache@v5 with: key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 path: tests/regression/cache From 85c5fa09fd3da5fde6ddd11d79ec8a1bdaeaf6cc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 09:40:47 -0800 Subject: [PATCH 889/937] changed to freebsd 15 since the image 16 does not seem to work --- .cirrus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cirrus.yml b/.cirrus.yml index 13258eded..b8782ca48 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -2,7 +2,7 @@ task: name: FreeBSD (make check) freebsd_instance: matrix: - image_family: freebsd-16-0-snap + image_family: freebsd-15-0-amd64-zfs install_script: pkg install -y gmake coreutils script: | MOREFLAGS="-Werror" gmake -j all From 38cce02684b5628ff1e3da5e327e565f4293558b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 12:59:14 -0800 Subject: [PATCH 890/937] Makefile: remove support of legacy formats by default can still be changed manually by setting `ZSTD_LEGACY_SUPPORT` to a different value --- lib/libzstd.mk | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/libzstd.mk b/lib/libzstd.mk index d1744973e..60928b0ee 100644 --- a/lib/libzstd.mk +++ b/lib/libzstd.mk @@ -28,12 +28,8 @@ LIB_BINDIR ?= $(LIB_SRCDIR) # configures a bunch of other variables to space-optimized defaults. ZSTD_LIB_MINIFY ?= 0 -# Legacy support -ifneq ($(ZSTD_LIB_MINIFY), 0) - ZSTD_LEGACY_SUPPORT ?= 0 -else - ZSTD_LEGACY_SUPPORT ?= 5 -endif +# Legacy support disabled by default +ZSTD_LEGACY_SUPPORT ?= 0 ZSTD_LEGACY_MULTITHREADED_API ?= 0 # Build size optimizations From b79e86291b306d6372702ed725ac600e6c6e1923 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:11:37 -0800 Subject: [PATCH 891/937] [cmake] disable legacy support by default can still be explicitly enabled --- build/cmake/CMakeModules/ZstdOptions.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build/cmake/CMakeModules/ZstdOptions.cmake b/build/cmake/CMakeModules/ZstdOptions.cmake index 3fca543a7..dc7813444 100644 --- a/build/cmake/CMakeModules/ZstdOptions.cmake +++ b/build/cmake/CMakeModules/ZstdOptions.cmake @@ -2,8 +2,8 @@ # ZSTD Build Options Configuration # ################################################################ -# Legacy support configuration -option(ZSTD_LEGACY_SUPPORT "Enable legacy format support" ON) +# Legacy support configuration (disabled by default) +option(ZSTD_LEGACY_SUPPORT "Enable legacy format support" OFF) if(ZSTD_LEGACY_SUPPORT) message(STATUS "ZSTD_LEGACY_SUPPORT enabled") From 073c7fb6eaf4d121d3757d83d2433d413fe789ef Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:13:56 -0800 Subject: [PATCH 892/937] update dev version number to v1.6.0 to reflect the relatively big scope change by removing support of legacy formats. --- lib/zstd.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/zstd.h b/lib/zstd.h index 415474d01..97fef316f 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -110,8 +110,8 @@ extern "C" { /*------ Version ------*/ #define ZSTD_VERSION_MAJOR 1 -#define ZSTD_VERSION_MINOR 5 -#define ZSTD_VERSION_RELEASE 8 +#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() : From 6c3e805e5061b2f800b2664ce7b09d0a4cc34f6f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:19:11 -0800 Subject: [PATCH 893/937] doc: legacy support is now disabled by default --- CHANGELOG | 4 ++++ lib/README.md | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 92df0f462..eb46d7118 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +v1.6.0 (Dec 2025) +api: legacy format support is now disabled by default +build: `ZSTD_LEGACY_SUPPORT` defaults to `0` in Makefile and CMake + V1.5.7 (Feb 2025) fix: compression bug in 32-bit mode associated with long-lasting sessions api: new method `ZSTD_compressSequencesAndLiterals()` (#4217, #4232) diff --git a/lib/README.md b/lib/README.md index 3974de160..aa92bd659 100644 --- a/lib/README.md +++ b/lib/README.md @@ -12,8 +12,9 @@ including commands variables, staged install, directory variables and standard t - `make` : generates both static and dynamic libraries - `make install` : install libraries, headers and pkg-config in local system directories -`libzstd` default scope is extensive, including compression, decompression, dictionary builder, -and support for decoding legacy formats >= v0.5.0 by default. +`libzstd` default scope includes compression, decompression, and dictionary builder. +Note: starting v1.6.0, support for decoding legacy formats is disabled by default. +See _modular build_ below to learn how to enable it. The scope can be reduced on demand (see paragraph _modular build_). #### Multiarch Support @@ -99,7 +100,7 @@ The file structure is designed to make this selection manually achievable for an Specifying a number limits versions supported to that version onward. For example, `ZSTD_LEGACY_SUPPORT=2` means : "support legacy formats >= v0.2.0". Conversely, `ZSTD_LEGACY_SUPPORT=0` means "do __not__ support legacy formats". - By default, this build macro is set as `ZSTD_LEGACY_SUPPORT=5`. + By default, this build macro is set as `ZSTD_LEGACY_SUPPORT=0` (disabled). Decoding supported legacy format is a transparent capability triggered within decompression functions. It's also allowed to invoke legacy API directly, exposed in `lib/legacy/zstd_legacy.h`. Each version does also provide its own set of advanced API. From f818f97be64bdbd6989c80ea92b034c1965eadde Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:24:02 -0800 Subject: [PATCH 894/937] build: set ZSTD_LEGACY_SUPPORT=0 in remaining build systems Summary: Completes the transition to disabled legacy support by default across all build systems. This follows up on the previous Makefile and CMake changes to ensure consistent default behavior regardless of the build system used. Updated build configurations: Meson, tests/Makefile, Visual Studio 2008/2010 projects, and BUCK. Test Plan: Verified changes compile correctly via `make lib-release`. Build system configurations have been updated consistently across all platforms. --- build/VS2008/zstd/zstd.vcproj | 8 ++++---- build/VS2008/zstdlib/zstdlib.vcproj | 8 ++++---- build/VS2010/libzstd-dll/libzstd-dll.vcxproj | 8 ++++---- build/VS2010/libzstd/libzstd.vcxproj | 8 ++++---- build/VS2010/zstd/zstd.vcxproj | 8 ++++---- build/meson/meson_options.txt | 4 ++-- lib/BUCK | 2 +- tests/Makefile | 2 +- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/build/VS2008/zstd/zstd.vcproj b/build/VS2008/zstd/zstd.vcproj index de1501d20..fc87625a9 100644 --- a/build/VS2008/zstd/zstd.vcproj +++ b/build/VS2008/zstd/zstd.vcproj @@ -45,7 +45,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\dictBuilder;$(SolutionDir)..\..\lib\compress" - PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -122,7 +122,7 @@ EnableIntrinsicFunctions="true" OmitFramePointers="true" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\dictBuilder;$(SolutionDir)..\..\lib\compress" - PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE" RuntimeLibrary="0" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" @@ -197,7 +197,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\dictBuilder;$(SolutionDir)..\..\lib\compress" - PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -275,7 +275,7 @@ EnableIntrinsicFunctions="true" OmitFramePointers="true" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\lib\dictBuilder;$(SolutionDir)..\..\lib\compress" - PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE" RuntimeLibrary="0" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" diff --git a/build/VS2008/zstdlib/zstdlib.vcproj b/build/VS2008/zstdlib/zstdlib.vcproj index 88c1aee26..61c88f5bc 100644 --- a/build/VS2008/zstdlib/zstdlib.vcproj +++ b/build/VS2008/zstdlib/zstdlib.vcproj @@ -45,7 +45,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\programs\legacy;$(SolutionDir)..\..\lib\dictBuilder" - PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -121,7 +121,7 @@ EnableIntrinsicFunctions="true" OmitFramePointers="true" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\programs\legacy;$(SolutionDir)..\..\lib\dictBuilder" - PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE" RuntimeLibrary="0" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" @@ -195,7 +195,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\programs\legacy;$(SolutionDir)..\..\lib\dictBuilder" - PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -272,7 +272,7 @@ EnableIntrinsicFunctions="true" OmitFramePointers="true" AdditionalIncludeDirectories="$(SolutionDir)..\..\lib;$(SolutionDir)..\..\lib\common;$(SolutionDir)..\..\lib\legacy;$(SolutionDir)..\..\programs\legacy;$(SolutionDir)..\..\lib\dictBuilder" - PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE" + PreprocessorDefinitions="ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE" RuntimeLibrary="0" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" diff --git a/build/VS2010/libzstd-dll/libzstd-dll.vcxproj b/build/VS2010/libzstd-dll/libzstd-dll.vcxproj index 6925e0f9e..ddb8e3216 100644 --- a/build/VS2010/libzstd-dll/libzstd-dll.vcxproj +++ b/build/VS2010/libzstd-dll/libzstd-dll.vcxproj @@ -169,7 +169,7 @@ Level4 Disabled - ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL EditAndContinue @@ -188,7 +188,7 @@ Level4 Disabled - ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL @@ -208,7 +208,7 @@ MaxSpeed true true - ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false MultiThreaded ProgramDatabase @@ -229,7 +229,7 @@ MaxSpeed true true - ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_DLL_EXPORT=1;ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false false MultiThreaded diff --git a/build/VS2010/libzstd/libzstd.vcxproj b/build/VS2010/libzstd/libzstd.vcxproj index 82a2d8268..09ead245a 100644 --- a/build/VS2010/libzstd/libzstd.vcxproj +++ b/build/VS2010/libzstd/libzstd.vcxproj @@ -162,7 +162,7 @@ Level4 Disabled - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) EnableFastChecks MultiThreadedDebugDLL EditAndContinue @@ -181,7 +181,7 @@ Level4 Disabled - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebugDLL @@ -201,7 +201,7 @@ MaxSpeed true true - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false MultiThreaded ProgramDatabase @@ -222,7 +222,7 @@ MaxSpeed true true - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) false false MultiThreaded diff --git a/build/VS2010/zstd/zstd.vcxproj b/build/VS2010/zstd/zstd.vcxproj index 0558687f5..230fd7d09 100644 --- a/build/VS2010/zstd/zstd.vcxproj +++ b/build/VS2010/zstd/zstd.vcxproj @@ -187,7 +187,7 @@ Level4 Disabled - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true false $(InstructionSet) @@ -204,7 +204,7 @@ Level4 Disabled - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true false $(InstructionSet) @@ -223,7 +223,7 @@ MaxSpeed true true - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) false false MultiThreaded @@ -245,7 +245,7 @@ MaxSpeed true true - ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=5;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + ZSTD_MULTITHREAD=1;ZSTD_LEGACY_SUPPORT=0;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) false false MultiThreaded diff --git a/build/meson/meson_options.txt b/build/meson/meson_options.txt index 470517827..8d7b8856e 100644 --- a/build/meson/meson_options.txt +++ b/build/meson/meson_options.txt @@ -10,8 +10,8 @@ # Read guidelines from https://wiki.gnome.org/Initiatives/GnomeGoals/MesonPorting -option('legacy_level', type: 'integer', min: 0, max: 7, value: 5, - description: 'Support any legacy format: 7 to 1 for v0.7+ to v0.1+') +option('legacy_level', type: 'integer', min: 0, max: 7, value: 0, + description: 'Support legacy format: 0=disabled, 1-7=support v0.1+ to v0.7+') option('debug_level', type: 'integer', min: 0, max: 9, value: 1, description: 'Enable run-time debug. See lib/common/debug.h') option('backtrace', type: 'feature', value: 'disabled', diff --git a/lib/BUCK b/lib/BUCK index 60c6bbb54..8c555a8be 100644 --- a/lib/BUCK +++ b/lib/BUCK @@ -57,7 +57,7 @@ cxx_library( srcs=glob(['legacy/*.c']), deps=[':common'], exported_preprocessor_flags=[ - '-DZSTD_LEGACY_SUPPORT=4', + '-DZSTD_LEGACY_SUPPORT=0', ], ) diff --git a/tests/Makefile b/tests/Makefile index 643f8cd61..c74c219dc 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -20,7 +20,7 @@ # zstreamtest32: Same as zstreamtest, but forced to compile in 32-bits mode # ########################################################################## -ZSTD_LEGACY_SUPPORT ?= 5 +ZSTD_LEGACY_SUPPORT ?= 0 export ZSTD_LEGACY_SUPPORT DEBUGLEVEL ?= 2 From 8ba2f20a905386bb3524edb95335d101de9f5f66 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:39:28 -0800 Subject: [PATCH 895/937] test: update libzstd_builds.sh for disabled legacy default Summary: Updates the library build tests to reflect that legacy format support is now disabled by default. Also adds a new test case to verify that legacy support can still be explicitly enabled via ZSTD_LEGACY_SUPPORT=5. Test Plan: Run `bash tests/libzstd_builds.sh` on a Linux environment. --- tests/libzstd_builds.sh | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/tests/libzstd_builds.sh b/tests/libzstd_builds.sh index f9e1e76c6..3b019c8b8 100755 --- a/tests/libzstd_builds.sh +++ b/tests/libzstd_builds.sh @@ -21,14 +21,14 @@ mustBeAbsent() { $ECHO "$@ correctly not present" # for some reason, this $ECHO must exist, otherwise mustBeAbsent() always fails (??) } -# default compilation : all features enabled - no zbuff +# default compilation : all features enabled - no zbuff, no legacy $ECHO "testing default library compilation" CFLAGS= make -C $DIR/../lib libzstd libzstd.a > $INTOVOID nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog isPresent "zstd_compress.o" isPresent "zstd_decompress.o" isPresent "zdict.o" -isPresent "zstd_v07.o" +mustBeAbsent "zstd_v07.o" mustBeAbsent "zbuff_compress.o" $RM tmplog @@ -44,7 +44,7 @@ nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog mustBeAbsent "zstd_compress.o" isPresent "zstd_decompress.o" mustBeAbsent "zdict.o" -isPresent "zstd_v07.o" +mustBeAbsent "zstd_v07.o" mustBeAbsent "zbuff_compress.o" $RM $DIR/../lib/libzstd.a tmplog @@ -66,7 +66,7 @@ nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog isPresent "zstd_compress.o" isPresent "zstd_decompress.o" isPresent "zdict.o" -isPresent "zstd_v07.o" +mustBeAbsent "zstd_v07.o" mustBeAbsent "zbuff_compress.o" $RM $DIR/../lib/libzstd.a tmplog @@ -77,7 +77,7 @@ nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog isPresent "zstd_compress.o" isPresent "zstd_decompress.o" isPresent "zdict.o" -isPresent "zstd_v07.o" +mustBeAbsent "zstd_v07.o" isPresent "zbuff_compress.o" $RM $DIR/../lib/libzstd.a tmplog @@ -88,7 +88,7 @@ nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog isPresent "zstd_compress.o" isPresent "zstd_decompress.o" mustBeAbsent "zdict.o" -isPresent "zstd_v07.o" +mustBeAbsent "zstd_v07.o" mustBeAbsent "zbuff_compress.o" $RM $DIR/../lib/libzstd.a tmplog @@ -102,3 +102,14 @@ mustBeAbsent "zdict.o" mustBeAbsent "zstd_v07.o" mustBeAbsent "zbuff_compress.o" $RM $DIR/../lib/libzstd.a tmplog + +# legacy support explicitly enabled +$ECHO "testing with legacy support explicitly enabled" +ZSTD_LEGACY_SUPPORT=5 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID +nm $DIR/../lib/libzstd.a | $GREP "\.o" > tmplog +isPresent "zstd_compress.o" +isPresent "zstd_decompress.o" +isPresent "zdict.o" +isPresent "zstd_v07.o" +mustBeAbsent "zbuff_compress.o" +$RM $DIR/../lib/libzstd.a tmplog From a87d0cc476e4947ccaa5531734f7afd1c49ef766 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 13:50:56 -0800 Subject: [PATCH 896/937] test: enable legacy support in version compatibility test Summary: The version compatibility test needs to decode legacy frames (v0.5.x - v0.7.x) to verify cross-version interoperability. Since legacy support is now disabled by default (v1.6.0), head must be built with ZSTD_LEGACY_SUPPORT=5 for this test. Test Plan: Run `python3 tests/test-zstd-versions.py` to verify cross-version compatibility testing works correctly. --- tests/test-zstd-versions.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test-zstd-versions.py b/tests/test-zstd-versions.py index 1bcf39e2b..703faa478 100755 --- a/tests/test-zstd-versions.py +++ b/tests/test-zstd-versions.py @@ -259,13 +259,16 @@ if __name__ == '__main__': shutil.copy2('dictBuilder', '{}/dictBuilder.{}'.format(tmp_dir, tag)) os.chdir(r_dir + '/programs') # /path/to/zstd/tests/versionsTest//programs make(['clean'], False) # separate 'clean' target to allow parallel build - make(['zstd'], False) + # Enable legacy support for cross-version compatibility testing + make(['zstd', 'ZSTD_LEGACY_SUPPORT=5'], False) else: os.chdir(programs_dir) print('-----------------------------------------------') print('compiling head') print('-----------------------------------------------') - make(['zstd'], False) + # Enable legacy support for head to test cross-version compatibility + # (legacy support is disabled by default since v1.6.0) + make(['zstd', 'ZSTD_LEGACY_SUPPORT=5'], False) shutil.copy2('zstd', dst_zstd) # remove any remaining *.zst and *.dec from previous test From 3a3c506b5168966fb6b350073dbb1866d67cbf78 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 15:52:11 -0800 Subject: [PATCH 897/937] Fix #4553 This is a bug in the streaming implementation of the v0.5 decoder. The bug has always been there. It requires an uncommon block configuration, which wasn't tested at the time. v0.5 is deprecated now, latest version to produce such format is v0.5.1 from February 2016. It was superceded in April 2016. So it's both short lived and very old. Another PR will remove support of this format, but it will still be possible to explicitely request this support on demand, so better fix the issue. --- lib/legacy/zstd_v05.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/legacy/zstd_v05.c b/lib/legacy/zstd_v05.c index e1efca597..ee180487e 100644 --- a/lib/legacy/zstd_v05.c +++ b/lib/legacy/zstd_v05.c @@ -3972,8 +3972,15 @@ size_t ZBUFFv05_decompressContinue(ZBUFFv05_DCtx* zbc, void* dst, size_t* maxDst zbc->outStart += flushedSize; if (flushedSize == toFlushSize) { zbc->stage = ZBUFFv05ds_read; - if (zbc->outStart + BLOCKSIZE > zbc->outBuffSize) - zbc->outStart = zbc->outEnd = 0; + if (zbc->outStart + BLOCKSIZE > zbc->outBuffSize) { + /* Not enough room for next block - need to wrap buffer. + * Preserve history: copy the last windowSize bytes to the + * beginning so that back-references can still find valid data. */ + size_t const windowSize = (size_t)1 << zbc->params.windowLog; + size_t const preserveSize = MIN(zbc->outEnd, windowSize); + memmove(zbc->outBuff, zbc->outBuff + zbc->outEnd - preserveSize, preserveSize); + zbc->outStart = zbc->outEnd = preserveSize; + } break; } /* cannot flush everything */ From 1dae4f0188daff25cfef78de72627e7299a01b86 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 18 Dec 2025 15:36:07 -0800 Subject: [PATCH 898/937] test: fix versionsTest build for old zstd versions Summary: Some old zstd versions (notably v0.6.x) have a bug in fileio.c where header includes check for `ZSTD_LEGACY_SUPPORT==1` but code usage checks for `ZSTD_LEGACY_SUPPORT>=1`. Using value 5 causes compilation failure because headers aren't included but the code tries to use legacy functions. Changing to `ZSTD_LEGACY_SUPPORT=1` for old version builds fixes the compilation while still enabling legacy format support. Test Plan: Run `make versionsTest` or `python3 tests/test-zstd-versions.py` to verify all old versions compile and cross-version decompression works correctly. --- tests/test-zstd-versions.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/test-zstd-versions.py b/tests/test-zstd-versions.py index 703faa478..57131c243 100755 --- a/tests/test-zstd-versions.py +++ b/tests/test-zstd-versions.py @@ -259,8 +259,15 @@ if __name__ == '__main__': shutil.copy2('dictBuilder', '{}/dictBuilder.{}'.format(tmp_dir, tag)) os.chdir(r_dir + '/programs') # /path/to/zstd/tests/versionsTest//programs make(['clean'], False) # separate 'clean' target to allow parallel build - # Enable legacy support for cross-version compatibility testing - make(['zstd', 'ZSTD_LEGACY_SUPPORT=5'], False) + # Enable legacy support for cross-version compatibility testing. + # Use ZSTD_LEGACY_SUPPORT=1 for v0.6.x due to a bug where headers + # check for ==1 but code checks for >=1. + # Use ZSTD_LEGACY_SUPPORT=5 for v1.2.0+ because =1 includes old + # legacy files (v01-v04) that have missing includes in newer versions. + if tag < 'v1.2.0': + make(['zstd', 'ZSTD_LEGACY_SUPPORT=1'], False) + else: + make(['zstd', 'ZSTD_LEGACY_SUPPORT=5'], False) else: os.chdir(programs_dir) print('-----------------------------------------------') From a8319c39de9aa0ee945b866d0b77e8f5cadea81f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Jan 2026 05:50:49 +0000 Subject: [PATCH 899/937] Bump actions/setup-java from 5.1.0 to 5.2.0 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5.1.0 to 5.2.0. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/f2beeb24e141e01a676f977032f5a29d81c9e27e...be666c2fcd27ec809703dec50e508c2fdc7f6654) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 5.2.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 3fc5cd317..c9d099126 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 - name: Set up JDK 17 - uses: actions/setup-java@f2beeb24e141e01a676f977032f5a29d81c9e27e # v5.1.0 + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 with: java-version: '17' distribution: 'temurin' From a46bec0fbae26383f10ab564a09cbe4e23509f81 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Jan 2026 05:51:10 +0000 Subject: [PATCH 900/937] Bump actions/checkout from 6.0.1 to 6.0.2 Bumps [actions/checkout](https://github.com/actions/checkout) from 6.0.1 to 6.0.2. - [Release notes](https://github.com/actions/checkout/releases) - [Commits](https://github.com/actions/checkout/compare/v6.0.1...v6.0.2) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: 6.0.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- .github/workflows/cmake-tests.yml | 10 +-- .github/workflows/commit.yml | 6 +- .github/workflows/dev-long-tests.yml | 54 ++++++------- .github/workflows/dev-short-tests.yml | 76 +++++++++---------- .github/workflows/nightly.yml | 2 +- .../workflows/publish-release-artifacts.yml | 2 +- .github/workflows/release_check.yml | 4 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 10 files changed, 80 insertions(+), 80 deletions(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 3fc5cd317..69dd551a5 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Set up JDK 17 uses: actions/setup-java@f2beeb24e141e01a676f977032f5a29d81c9e27e # v5.1.0 diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index a293e77cf..3660dcbcf 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -28,7 +28,7 @@ jobs: name: "CMake Root Build" runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Configure (Root) run: | cmake -S . -B cmake-build -DCMAKE_BUILD_TYPE=Release ${{ env.COMMON_CMAKE_FLAGS }} @@ -43,7 +43,7 @@ jobs: name: "CMake build using make wrapper" runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Install dependencies run: | sudo apt install liblzma-dev # Required for compression algorithms @@ -73,7 +73,7 @@ jobs: env: SRC_DIR: "source directory with spaces" steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 with: path: "${{ env.SRC_DIR }}" - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 @@ -131,7 +131,7 @@ jobs: runner: "windows-2022" cmake_extra_flags: "-DCMAKE_COMPILE_WARNING_AS_ERROR=ON -DZSTD_BUILD_TESTS=ON" steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 - name: "Configure CMake (${{ matrix.name }})" @@ -156,7 +156,7 @@ jobs: name: "CMake macOS ARM64 (Apple Silicon)" runs-on: macos-14 # ARM64 runner steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: "CMake build and test (ARM64)" run: | # Configure and build with ARM64-specific optimizations diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 98345206a..2dbbcc4a0 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -17,7 +17,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 - name: Install Dependencies run: | sudo apt-get update @@ -40,7 +40,7 @@ jobs: image: fbopensource/zstd-circleci-primary:0.0.1 options: --entrypoint /bin/bash steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 - name: Install Dependencies run: | sudo apt-get update @@ -73,7 +73,7 @@ jobs: env: CIRCLE_ARTIFACTS: "/tmp/circleci-artifacts" steps: - - uses: actions/checkout@v6.0.1 + - uses: actions/checkout@v6.0.2 - name: restore_cache uses: actions/cache@v5 with: diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index c606b3d45..dc4155f5a 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -16,7 +16,7 @@ jobs: make-all: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: make all run: make all @@ -27,7 +27,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: make test run: | make test @@ -38,7 +38,7 @@ jobs: make-test-macos: runs-on: macos-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: make test on macos run: make test @@ -49,7 +49,7 @@ jobs: DEVNULLRIGHTS: 1 READFROMBLOCKDEVICE: 1 steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: make test # note: `make -j test success` seems to require a clean state run: | sudo apt-get -qqq update @@ -61,7 +61,7 @@ jobs: test-largeDictionary: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: largeDictionary run: | CFLAGS="-Werror -O3" make -j -C tests test-largeDictionary @@ -70,7 +70,7 @@ jobs: no-intrinsics-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: no intrinsics fuzztest run: MOREFLAGS="-DZSTD_NO_INTRINSICS" make -C tests fuzztest @@ -78,14 +78,14 @@ jobs: tsan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: thread sanitizer zstreamtest run: CC=clang ZSTREAM_TESTTIME=-T3mn make tsan-test-zstream uasan-zstreamtest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: ub + address sanitizer on zstreamtest run: CC=clang make uasan-test-zstream @@ -93,14 +93,14 @@ jobs: tsan-fuzztest: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: thread sanitizer fuzztest run: CC=clang make tsan-fuzztest big-tests-zstreamtest32: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: zstream tests in 32bit mode, with big tests run: | sudo apt-get -qqq update @@ -111,7 +111,7 @@ jobs: gcc-8-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: gcc-8 + ASan + UBSan + Test Zstd # See https://askubuntu.com/a/1428822 run: | @@ -123,14 +123,14 @@ jobs: clang-asan-ubsan-testzstd: runs-on: ubuntu-latest steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # tag=v6.0.1 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: clang + ASan + UBSan + Test Zstd run: CC=clang make -j uasan-test-zstd Date: Mon, 26 Jan 2026 09:01:27 -0800 Subject: [PATCH 901/937] extend dependabot period to monthly --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5ace4600a..8ac6b8c49 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -3,4 +3,4 @@ updates: - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "weekly" + interval: "monthly" From a90d7e7689a4468e36247c8afe7c2643ad5c57a2 Mon Sep 17 00:00:00 2001 From: Briar Campbell Date: Thu, 5 Feb 2026 18:26:50 -0600 Subject: [PATCH 902/937] Fix formatting of lz4 option in README --- programs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/README.md b/programs/README.md index 2c2e94dc6..2a6978ac4 100644 --- a/programs/README.md +++ b/programs/README.md @@ -224,7 +224,7 @@ Advanced compression options: --format=gzip Compress files to the `.gz` format. --format=xz Compress files to the `.xz` format. --format=lzma Compress files to the `.lzma` format. - --format=lz4 Compress files to the `.lz4` format. + --format=lz4 Compress files to the `.lz4` format. Advanced decompression options: -l Print information about Zstandard-compressed files. From 117b0edfaee4d1a4af98a3074ea3b23833d47877 Mon Sep 17 00:00:00 2001 From: Briar Campbell Date: Thu, 5 Feb 2026 18:29:07 -0600 Subject: [PATCH 903/937] Fix formatting of lz4 option in zstdcli.c --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 01760ff8c..34db7bf51 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -264,7 +264,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT(" --format=lzma Compress files to the `.lzma` format.\n"); #endif #ifdef ZSTD_LZ4COMPRESS - DISPLAYOUT( " --format=lz4 Compress files to the `.lz4` format.\n"); + DISPLAYOUT( " --format=lz4 Compress files to the `.lz4` format.\n"); #endif #endif /* !ZSTD_NOCOMPRESS */ From 81cf153bce7c0ab41aeef574a70e32eaea7a8ba7 Mon Sep 17 00:00:00 2001 From: Cody <166262726+kowirth@users.noreply.github.com> Date: Thu, 19 Feb 2026 13:36:12 -0500 Subject: [PATCH 904/937] fix: adjust LDM params in estimate functions to prevent SIGFPE (issue #4590) --- lib/compress/zstd_compress.c | 12 ++++++++++-- tests/fuzzer.c | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/lib/compress/zstd_compress.c b/lib/compress/zstd_compress.c index 1d6f0fcae..c06f2e1bb 100644 --- a/lib/compress/zstd_compress.c +++ b/lib/compress/zstd_compress.c @@ -1771,15 +1771,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) @@ -1829,6 +1833,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 @@ -1838,8 +1843,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); } } diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 0bc160efa..472f8c8b3 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -2515,6 +2515,25 @@ static int basicUnitTests(U32 const seed, double compressibility) } } DISPLAYLEVEL(3, "OK \n"); + + DISPLAYLEVEL(3, "test%3i : estimation functions with LDM enabled (issue #4590) : ", testNb++); + { + /* ZSTD_estimateCCtxSize_usingCCtxParams must adjust zeroed-out + * LDM parameters when LDM is enabled, to avoid division by zero + * in ZSTD_ldm_getMaxNbSeq. */ + ZSTD_CCtx_params* params = ZSTD_createCCtxParams(); + size_t cctxSize; + CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_compressionLevel, 22)); + CHECK_Z(ZSTD_CCtxParams_setParameter(params, ZSTD_c_enableLongDistanceMatching, ZSTD_ps_enable)); + cctxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params); + if (ZSTD_isError(cctxSize)) goto _output_error; + if (cctxSize == 0) goto _output_error; + cctxSize = ZSTD_estimateCStreamSize_usingCCtxParams(params); + if (ZSTD_isError(cctxSize)) goto _output_error; + if (cctxSize == 0) goto _output_error; + ZSTD_freeCCtxParams(params); + } + DISPLAYLEVEL(3, "OK \n"); } free(staticCCtxBuffer); free(staticDCtxBuffer); From bce1ec6b0703c1b91c68daa13c763f46bf8d5199 Mon Sep 17 00:00:00 2001 From: Radek Zikmund Date: Fri, 16 Jan 2026 14:50:06 +0100 Subject: [PATCH 905/937] Make explicit ptrdiff_t to int casts in divsufsort.c to avoid compiler warnings. --- lib/dictBuilder/divsufsort.c | 154 +++++++++++++++++------------------ 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/lib/dictBuilder/divsufsort.c b/lib/dictBuilder/divsufsort.c index e5b117b29..b59781f01 100644 --- a/lib/dictBuilder/divsufsort.c +++ b/lib/dictBuilder/divsufsort.c @@ -25,23 +25,22 @@ */ /*- 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 #include "divsufsort.h" +#define PTRDIFF_TO_INT(x) (assert((x) <= INT_MAX && (x) >= INT_MIN), (int)(x)) + /*- Constants -*/ #if defined(INLINE) # undef INLINE @@ -354,7 +353,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) { @@ -409,7 +408,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 @@ -420,7 +419,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) { @@ -435,16 +434,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; @@ -481,9 +480,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); @@ -491,38 +490,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; } @@ -551,7 +550,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) { @@ -601,7 +601,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; @@ -640,7 +640,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); @@ -692,7 +692,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; } @@ -781,7 +781,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)), @@ -850,8 +850,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 { @@ -863,7 +863,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) { @@ -909,8 +909,8 @@ sssort(const unsigned char *T, const int *PA, static INLINE int tr_ilg(int n) { - return ((unsigned)n & 0xffff0000) ? - (((unsigned)n & 0xff000000) ? + return (n & 0xffff0000) ? + ((n & 0xff000000) ? 24 + lg_table[(n >> 24) & 0xff] : 16 + lg_table[(n >> 16) & 0xff]) : ((n & 0x0000ff00) ? @@ -1016,7 +1016,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) { @@ -1098,9 +1098,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); } @@ -1117,17 +1117,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); } } } @@ -1141,13 +1141,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; } } @@ -1155,7 +1155,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; } } @@ -1164,7 +1164,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; } } @@ -1180,23 +1180,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 */ @@ -1207,19 +1207,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); } @@ -1228,26 +1228,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; @@ -1281,7 +1281,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; } } @@ -1297,14 +1297,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)) { @@ -1381,8 +1381,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); @@ -1420,7 +1420,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; } @@ -1634,7 +1634,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); @@ -1658,7 +1658,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); @@ -1698,7 +1698,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); @@ -1726,7 +1726,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); @@ -1738,7 +1738,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 @@ -1776,13 +1776,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); @@ -1802,7 +1802,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 { @@ -1814,17 +1814,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; @@ -1835,7 +1835,7 @@ construct_BWT_indexes(const unsigned char *T, int *SA, } } - return orig - SA; + return PTRDIFF_TO_INT(orig - SA); } From 2107c8f189e8496b2c561cd15d3c90a7d1d82479 Mon Sep 17 00:00:00 2001 From: Alexander Moch Date: Thu, 1 Jan 2026 10:56:31 +0100 Subject: [PATCH 906/937] bitstream: fix `BIT_readBits` and `BIT_reloadDStream` prototypes Align the declarations of BIT_readBits() and BIT_reloadDStream() in bitstream.h with their FORCE_INLINE_TEMPLATE definitions. The previous MEM_STATIC declarations caused an attribute mismatch between the header and the definitions, which can lead to incorrect compiler assumptions under certain toolchains and optimization levels. Signed-off-by: Alexander Moch --- lib/common/bitstream.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/bitstream.h b/lib/common/bitstream.h index 3b7ad483d..6ff482a83 100644 --- a/lib/common/bitstream.h +++ b/lib/common/bitstream.h @@ -102,8 +102,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); From bb1eedcf866e0abdd34b157d83e19d76eb82a6f7 Mon Sep 17 00:00:00 2001 From: richardsonnick Date: Tue, 23 Dec 2025 16:40:02 -0500 Subject: [PATCH 907/937] correct mmap error check Update mmap error validation to check for MAP_FAILED instead of NULL. POSIX specifies that mmap returns MAP_FAILED (-1) on failure. --- programs/fileio.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/programs/fileio.c b/programs/fileio.c index 4000c5b62..a0dcad817 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -1050,7 +1050,9 @@ static size_t FIO_setDictBufferMMap(FIO_Dict_t* dict, const char* fileName, FIO_ } *bufferPtr = mmap(NULL, (size_t)fileSize, PROT_READ, MAP_PRIVATE, fileHandle, 0); - if (*bufferPtr==NULL) EXM_THROW(34, "%s", strerror(errno)); + if (*bufferPtr == MAP_FAILED) { + EXM_THROW(34, "%s", strerror(errno)) + } close(fileHandle); return (size_t)fileSize; From d9b10820f8b573e5cdcb343ae4884b4ce70ca156 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Mar 2026 05:32:41 +0000 Subject: [PATCH 908/937] Bump actions/upload-artifact from 6.0.0 to 7.0.0 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6.0.0 to 7.0.0. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: 7.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 2dbbcc4a0..af3028e3c 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -99,6 +99,6 @@ jobs: echo " are still good, copy it into the repo and commit it." echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv - - uses: actions/upload-artifact@v6.0.0 + - uses: actions/upload-artifact@v7.0.0 with: path: "/tmp/circleci-artifacts" diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index dc4155f5a..f72a99729 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -317,7 +317,7 @@ jobs: dry-run: false sanitizer: ${{ matrix.sanitizer }} - name: Upload Crash - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 if: failure() && steps.build.outcome == 'success' with: name: ${{ matrix.sanitizer }}-artifacts diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 8f808b745..31b3f731d 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -51,7 +51,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 with: name: SARIF file path: results.sarif diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 9095cc602..401441d12 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -93,7 +93,7 @@ jobs: mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # tag=v6.0.0 + uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 with: compression-level: 9 # maximum compression if-no-files-found: error # defaults to `warn` From 1c140a86a17957b37d14ce14b1c1ae909166b250 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Mar 2026 05:32:44 +0000 Subject: [PATCH 909/937] Bump cygwin/cygwin-install-action from 6.0 to 6.1 Bumps [cygwin/cygwin-install-action](https://github.com/cygwin/cygwin-install-action) from 6.0 to 6.1. - [Release notes](https://github.com/cygwin/cygwin-install-action/releases) - [Commits](https://github.com/cygwin/cygwin-install-action/compare/f2009323764960f80959895c7bc3bb30210afe4d...711d29f3da23c9f4a1798e369a6f01198c13b11a) --- updated-dependencies: - dependency-name: cygwin/cygwin-install-action dependency-version: '6.1' dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 4423a6dca..aef73157e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -544,7 +544,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: cygwin/cygwin-install-action@f2009323764960f80959895c7bc3bb30210afe4d # tag=v6 + - uses: cygwin/cygwin-install-action@711d29f3da23c9f4a1798e369a6f01198c13b11a # tag=v6 with: platform: x86_64 packages: >- From 6e1e545916eff6457e4b264f8813a7417510a57e Mon Sep 17 00:00:00 2001 From: "Sergey G. Brester (sebres)" Date: Sun, 1 Mar 2026 21:00:18 +0100 Subject: [PATCH 910/937] avoid potential RC on ctx->threadLimit, code review; closes gh-4547; replaces gh-4558 --- lib/common/pool.c | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/lib/common/pool.c b/lib/common/pool.c index 3adcefc9a..dd5fb0c4d 100644 --- a/lib/common/pool.c +++ b/lib/common/pool.c @@ -142,19 +142,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; } @@ -220,23 +218,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; } From 6a8715f8d43dcbaec8d33945a7cfdae06ef1be6d Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Wed, 4 Mar 2026 13:29:20 -0800 Subject: [PATCH 911/937] update man --- programs/zstd.1.md | 3 ++- programs/zstdcli.c | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index bb9258d57..49d9e5f88 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -131,6 +131,7 @@ the last one takes effect. In all cases, the nb of threads is capped to `ZSTDMT_NBWORKERS_MAX`, which is either 64 in 32-bit mode, or 256 for 64-bit environments. This modifier does nothing if `zstd` is compiled without multithread support. + Note that memory usage increases with each thread. * `--single-thread`: Use a single thread for both I/O and compression. As compression is serialized with I/O, this can be slightly slower. @@ -157,7 +158,7 @@ the last one takes effect. when combined with multiple worker threads (>=2). * `--long[=#]`: enables long distance matching with `#` `windowLog`, if `#` is not - present it defaults to `27`. + present it defaults to `27`. The highest possible value is 31 This increases the window size (`windowLog`) and memory usage for both the compressor and decompressor. This setting is designed to improve the compression ratio for files with diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 34db7bf51..7749b2908 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -1540,7 +1540,12 @@ int main(int argCount, const char* argv[]) /* check compression level limits */ { int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX; if (cLevel > maxCLevel) { - DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel); + DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i. ", maxCLevel); + DISPLAYLEVEL(2, "Specify --ultra to raise the limit to 22 and use " + "--long=31 for maximum compression. Note that this " + "requires high amounts of memory, and the resulting data " + "might be rejected by third-party decoders and is " + "therefore only recommended for archival purposes. \n"); cLevel = maxCLevel; } } #endif From 1bd8e553633bb1b51fae051bc6b7fa75cb135fc6 Mon Sep 17 00:00:00 2001 From: jlee303 Date: Thu, 5 Mar 2026 15:12:33 -0800 Subject: [PATCH 912/937] Update programs/zstd.1.md Co-authored-by: Nick Terrell --- programs/zstd.1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstd.1.md b/programs/zstd.1.md index 49d9e5f88..1721441df 100644 --- a/programs/zstd.1.md +++ b/programs/zstd.1.md @@ -158,7 +158,7 @@ the last one takes effect. when combined with multiple worker threads (>=2). * `--long[=#]`: enables long distance matching with `#` `windowLog`, if `#` is not - present it defaults to `27`. The highest possible value is 31 + present it defaults to `27`. The highest possible value is 31. This increases the window size (`windowLog`) and memory usage for both the compressor and decompressor. This setting is designed to improve the compression ratio for files with From d7ee3207cc0db53f78fc6a69babc80747b1b7658 Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 5 Mar 2026 18:44:12 -0500 Subject: [PATCH 913/937] Remove LICENSE file in build/ dir --- build/LICENSE | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 build/LICENSE diff --git a/build/LICENSE b/build/LICENSE deleted file mode 100644 index e69de29bb..000000000 From 7b04e6dd1e2385df0701e2c513db2478e5950d1b Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Fri, 6 Mar 2026 09:47:03 -0800 Subject: [PATCH 914/937] Retry CI From f1e77ab2ba96f8fe2b7139b76989f7cd7022d6c9 Mon Sep 17 00:00:00 2001 From: Integral Date: Fri, 6 Mar 2026 15:36:57 +0800 Subject: [PATCH 915/937] Accept G, GB and GiB suffixes for options --- programs/zstdcli.c | 60 ++++++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 34db7bf51..e0d7faa43 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -347,7 +347,7 @@ static void errorOut(const char* msg) /*! readU32FromCharChecked() : * @return 0 if success, and store the result in *value. - * allows and interprets K, KB, KiB, M, MB and MiB suffix. + * allows and interprets K, KB, KiB, M, MB, MiB, G, GB and GiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. * @return 1 if an overflow error occurs */ static int readU32FromCharChecked(const char** stringPtr, unsigned* value) @@ -362,15 +362,22 @@ static int readU32FromCharChecked(const char** stringPtr, unsigned* value) if (result < last) return 1; /* overflow error */ (*stringPtr)++ ; } - if ((**stringPtr=='K') || (**stringPtr=='M')) { - unsigned const maxK = ((unsigned)(-1)) >> 10; - if (result > maxK) return 1; /* overflow error */ - result <<= 10; - if (**stringPtr=='M') { - if (result > maxK) return 1; /* overflow error */ - result <<= 10; + if ((**stringPtr=='K') || (**stringPtr=='M') || (**stringPtr=='G')) { + switch (**stringPtr) { + case 'K': + if (result > (((unsigned)-1) >> 10)) return 1; /* overflow error */ + result <<= 10; + break; + case 'M': + if (result > (((unsigned)-1) >> 20)) return 1; /* overflow error */ + result <<= 20; + break; + case 'G': + if (result > (((unsigned)-1) >> 30)) return 1; /* overflow error */ + result <<= 30; + break; } - (*stringPtr)++; /* skip `K` or `M` */ + (*stringPtr)++; /* skip `K`, `M` or `G` */ if (**stringPtr=='i') (*stringPtr)++; if (**stringPtr=='B') (*stringPtr)++; } @@ -380,7 +387,7 @@ static int readU32FromCharChecked(const char** stringPtr, unsigned* value) /*! readU32FromChar() : * @return : unsigned integer value read from input in `char` format. - * allows and interprets K, KB, KiB, M, MB and MiB suffix. + * allows and interprets K, KB, KiB, M, MB, MiB, G, GB and GiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. * Note : function will exit() program if digit sequence overflows */ static unsigned readU32FromChar(const char** stringPtr) { @@ -392,7 +399,7 @@ static unsigned readU32FromChar(const char** stringPtr) { /*! readIntFromChar() : * @return : signed integer value read from input in `char` format. - * allows and interprets K, KB, KiB, M, MB and MiB suffix. + * allows and interprets K, KB, KiB, M, MB, MiB, G, GB and GiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. * Note : function will exit() program if digit sequence overflows */ static int readIntFromChar(const char** stringPtr) { @@ -409,7 +416,7 @@ static int readIntFromChar(const char** stringPtr) { /*! readSizeTFromCharChecked() : * @return 0 if success, and store the result in *value. - * allows and interprets K, KB, KiB, M, MB and MiB suffix. + * allows and interprets K, KB, KiB, M, MB, MiB, G, GB and GiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. * @return 1 if an overflow error occurs */ static int readSizeTFromCharChecked(const char** stringPtr, size_t* value) @@ -424,15 +431,22 @@ static int readSizeTFromCharChecked(const char** stringPtr, size_t* value) if (result < last) return 1; /* overflow error */ (*stringPtr)++ ; } - if ((**stringPtr=='K') || (**stringPtr=='M')) { - size_t const maxK = ((size_t)(-1)) >> 10; - if (result > maxK) return 1; /* overflow error */ - result <<= 10; - if (**stringPtr=='M') { - if (result > maxK) return 1; /* overflow error */ - result <<= 10; + if ((**stringPtr=='K') || (**stringPtr=='M') || (**stringPtr=='G')) { + switch (**stringPtr) { + case 'K': + if (result > (((size_t)-1) >> 10)) return 1; /* overflow error */ + result <<= 10; + break; + case 'M': + if (result > (((size_t)-1) >> 20)) return 1; /* overflow error */ + result <<= 20; + break; + case 'G': + if (result > (((size_t)-1) >> 30)) return 1; /* overflow error */ + result <<= 30; + break; } - (*stringPtr)++; /* skip `K` or `M` */ + (*stringPtr)++; /* skip `K`, `M` or `G` */ if (**stringPtr=='i') (*stringPtr)++; if (**stringPtr=='B') (*stringPtr)++; } @@ -442,7 +456,7 @@ static int readSizeTFromCharChecked(const char** stringPtr, size_t* value) /*! readSizeTFromChar() : * @return : size_t value read from input in `char` format. - * allows and interprets K, KB, KiB, M, MB and MiB suffix. + * allows and interprets K, KB, KiB, M, MB, MiB, G, GB and GiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. * Note : function will exit() program if digit sequence overflows */ static size_t readSizeTFromChar(const char** stringPtr) { @@ -830,7 +844,7 @@ static unsigned init_nbWorkers(unsigned defaultNbWorkers) { NEXT_FIELD(__nb); \ _varu32 = readU32FromChar(&__nb); \ if(*__nb != 0) { \ - errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ + errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed"); \ } \ } @@ -839,7 +853,7 @@ static unsigned init_nbWorkers(unsigned defaultNbWorkers) { NEXT_FIELD(__nb); \ _varTsize = readSizeTFromChar(&__nb); \ if(*__nb != 0) { \ - errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \ + errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed"); \ } \ } From 3f8f9b3f89244638f10bca664c120fd28cb14efe Mon Sep 17 00:00:00 2001 From: NiDU-NINJA Date: Sat, 7 Mar 2026 08:27:15 +0000 Subject: [PATCH 916/937] Fix potential NULL pointer dereference in ZSTD_customCalloc when custom allocator fails --- lib/common/allocations.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/common/allocations.h b/lib/common/allocations.h index 5e8995501..d4d392998 100644 --- a/lib/common/allocations.h +++ b/lib/common/allocations.h @@ -33,9 +33,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; } From 043426b3e226a6f4b7325cfbdd21da90f702a892 Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Mon, 9 Mar 2026 16:30:41 -0700 Subject: [PATCH 917/937] Promote flag --- programs/zstdcli.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 34db7bf51..19c6cae89 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -147,6 +147,7 @@ static void usage(FILE* f, const char* programName) DISPLAY_F(f, "Usage: %s [OPTIONS...] [INPUT... | -] [-o OUTPUT]\n\n", programName); DISPLAY_F(f, "Options:\n"); DISPLAY_F(f, " -o OUTPUT Write output to a single file, OUTPUT.\n"); + DISPLAY_F(f, " -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s).\n"); DISPLAY_F(f, " -k, --keep Preserve INPUT file(s). [Default] \n"); DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression to file.\n"); #ifdef ZSTD_GZCOMPRESS @@ -167,7 +168,8 @@ static void usage(FILE* f, const char* programName) DISPLAY_F(f, " -f, --force Disable input and output checks. Allows overwriting existing files,\n"); DISPLAY_F(f, " receiving input from the console, printing output to STDOUT, and\n"); DISPLAY_F(f, " operating on links, block devices, etc. Unrecognized formats will be\n"); - DISPLAY_F(f, " passed-through through as-is.\n\n"); + DISPLAY_F(f, " passed-through through as-is.\n"); + DISPLAY_F(f, " -q, --quiet Suppress warnings; pass twice to suppress errors.\n\n"); DISPLAY_F(f, " -h Display short usage and exit.\n"); DISPLAY_F(f, " -H, --help Display full help and exit.\n"); @@ -181,10 +183,8 @@ static void usageAdvanced(const char* programName) DISPLAYOUT("\n"); usage(stdout, programName); DISPLAYOUT("Advanced options:\n"); - DISPLAYOUT(" -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s).\n\n"); DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n"); - DISPLAYOUT(" -q, --quiet Suppress warnings; pass twice to suppress errors.\n"); #ifndef ZSTD_NOTRACE DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n"); #endif From 13ea076d3b8df315cb6731971f594b8bb4f4e401 Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Mon, 9 Mar 2026 16:40:42 -0700 Subject: [PATCH 918/937] Update tests --- tests/cli-tests/basic/help.sh.stdout.glob | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/cli-tests/basic/help.sh.stdout.glob b/tests/cli-tests/basic/help.sh.stdout.glob index 66c6906cf..eb249bf2b 100644 --- a/tests/cli-tests/basic/help.sh.stdout.glob +++ b/tests/cli-tests/basic/help.sh.stdout.glob @@ -5,6 +5,7 @@ Usage: zstd *OPTIONS...* *INPUT... | -* *-o OUTPUT* Options: -o OUTPUT Write output to a single file, OUTPUT. + -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s). -k, --keep Preserve INPUT file(s). *Default* --rm Remove INPUT file(s) after successful (de)compression to file. @@ -19,11 +20,12 @@ Options: receiving input from the console, printing output to STDOUT, and operating on links, block devices, etc. Unrecognized formats will be passed-through through as-is. + -q, --quiet Suppress warnings; pass twice to suppress errors. -h Display short usage and exit. -H, --help Display full help and exit. -V, --version Display the program version and exit. - + + zstd -H ... Advanced options: From 2293e9601f89904061e468796c0613f1088ec7a2 Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Mon, 9 Mar 2026 17:17:13 -0700 Subject: [PATCH 919/937] init commit --- contrib/largeNbDicts/largeNbDicts.c | 6 ++++-- programs/README.md | 7 +++++++ programs/fileio.c | 4 +++- programs/zstdcli.c | 8 +++++--- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/contrib/largeNbDicts/largeNbDicts.c b/contrib/largeNbDicts/largeNbDicts.c index 6b6cc34ca..f7496930b 100644 --- a/contrib/largeNbDicts/largeNbDicts.c +++ b/contrib/largeNbDicts/largeNbDicts.c @@ -45,7 +45,9 @@ #define RUN_TIME_DEFAULT_MS 1000 #define BENCH_TIME_DEFAULT_MS (BENCH_TIME_DEFAULT_S * RUN_TIME_DEFAULT_MS) -#define DISPLAY_LEVEL_DEFAULT 3 +#ifndef ZSTD_DISPLAY_LEVEL_DEFAULT +#define ZSTD_DISPLAY_LEVEL_DEFAULT 3 +#endif #define BENCH_SIZE_MAX (1200 MB) @@ -61,7 +63,7 @@ #define DISPLAY(...) fprintf(stdout, __VA_ARGS__) #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } } -static int g_displayLevel = DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */ +static int g_displayLevel = ZSTD_DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */ /*--- buffer_t ---*/ diff --git a/programs/README.md b/programs/README.md index 2a6978ac4..6522b647d 100644 --- a/programs/README.md +++ b/programs/README.md @@ -79,6 +79,13 @@ There are however other Makefile targets that create different variations of CLI This can be useful to produce smaller binaries. A corresponding `Makefile` target using this ability is `zstd-compress`. +- __ZSTD_DISPLAY_LEVEL_DEFAULT__ : Controls the default verbosity level of `zstd` output. + The default value is `2`. Lower values (e.g., `1`) reduce output verbosity, + while higher values (e.g., `3`) increase it. + This allows setting preferred verbosity at compile time, + rather than passing `-q` or `-v` flags at runtime. + Example : `CPPFLAGS="-DZSTD_DISPLAY_LEVEL_DEFAULT=1" make` + - __BACKTRACE__ : `zstd` can display a stack backtrace when execution generates a runtime exception. By default, this feature may be degraded/disabled on some platforms unless additional compiler directives are diff --git a/programs/fileio.c b/programs/fileio.c index a0dcad817..3b2f9b636 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -2401,7 +2401,9 @@ int FIO_compressFilename(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, const cRess_t ress = FIO_createCResources(prefs, dictFileName, UTIL_getFileSize(srcFileName), compressionLevel, comprParams); int const result = FIO_compressFilename_srcFile(fCtx, prefs, &ress, dstFileName, srcFileName, compressionLevel); -#define DISPLAY_LEVEL_DEFAULT 2 +#ifndef ZSTD_DISPLAY_LEVEL_DEFAULT +#define ZSTD_DISPLAY_LEVEL_DEFAULT 2 +#endif FIO_freeCResources(&ress); return result; diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 34db7bf51..70e170c47 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -77,7 +77,9 @@ static unsigned init_nbWorkers(unsigned defaultNbWorkers); #define MB *(1 <<20) #define GB *(1U<<30) -#define DISPLAY_LEVEL_DEFAULT 2 +#ifndef ZSTD_DISPLAY_LEVEL_DEFAULT +#define ZSTD_DISPLAY_LEVEL_DEFAULT 2 +#endif static const char* g_defaultDictName = "dictionary"; static const unsigned g_defaultMaxDictSize = 110 KB; @@ -104,7 +106,7 @@ typedef enum { cover, fastCover, legacy } dictType; **************************************/ #undef DISPLAYLEVEL #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } } -static int g_displayLevel = DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */ +static int g_displayLevel = ZSTD_DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */ /*-************************************ @@ -660,7 +662,7 @@ static void setMaxCompression(ZSTD_compressionParameters* params) static void printVersion(void) { - if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) { + if (g_displayLevel < ZSTD_DISPLAY_LEVEL_DEFAULT) { DISPLAYOUT("%s\n", ZSTD_VERSION_STRING); return; } From 488b3a7e37a0325a6115e2aef89708a4c41bdb33 Mon Sep 17 00:00:00 2001 From: Integral Date: Fri, 6 Mar 2026 16:50:05 +0800 Subject: [PATCH 920/937] Add tests for options with G, GB and GiB suffixes --- tests/cli-tests/basic/memlimit.sh | 24 +++++++++++++++++++ .../cli-tests/basic/memlimit.sh.stderr.exact | 21 +++++++++++----- .../cli-tests/basic/memlimit.sh.stdout.exact | 9 +++++++ tests/playTests.sh | 10 +++++++- 4 files changed, 57 insertions(+), 7 deletions(-) diff --git a/tests/cli-tests/basic/memlimit.sh b/tests/cli-tests/basic/memlimit.sh index 88d734d0d..ec7f93a10 100755 --- a/tests/cli-tests/basic/memlimit.sh +++ b/tests/cli-tests/basic/memlimit.sh @@ -35,6 +35,30 @@ rm file.zst println "+ zstd --memory=1MiB file" zstd -q --memory=1MiB file && die "Should allow numeric parameter with expected suffix" rm file.zst +println "+ zstd --memory=1G file" +zstd -q --memory=1G file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=1GB file" +zstd -q --memory=1GB file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=1GiB file" +zstd -q --memory=1GiB file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=3G file" +zstd -q --memory=3G file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=3GB file" +zstd -q --memory=3GB file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=3GiB file" +zstd -q --memory=3GiB file && die "Should allow numeric parameter with expected suffix" +rm file.zst +println "+ zstd --memory=4G file" +zstd --memory=4G file && die "Should not allow out-of-bound numeric parameter" +println "+ zstd --memory=4GB file" +zstd --memory=4GB file && die "Should not allow out-of-bound numeric parameter" +println "+ zstd --memory=4GiB file" +zstd --memory=4GiB file && die "Should not allow out-of-bound numeric parameter" rm file exit 0 diff --git a/tests/cli-tests/basic/memlimit.sh.stderr.exact b/tests/cli-tests/basic/memlimit.sh.stderr.exact index 3785b0f92..28784a1e6 100644 --- a/tests/cli-tests/basic/memlimit.sh.stderr.exact +++ b/tests/cli-tests/basic/memlimit.sh.stderr.exact @@ -1,9 +1,9 @@ -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed -error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed +error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB, G, GB, GiB are allowed Should allow numeric parameter without suffix Should allow numeric parameter with expected suffix Should allow numeric parameter with expected suffix @@ -11,3 +11,12 @@ Should allow numeric parameter with expected suffix Should allow numeric parameter with expected suffix Should allow numeric parameter with expected suffix Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +Should allow numeric parameter with expected suffix +error: numeric value overflows 32-bit unsigned int +error: numeric value overflows 32-bit unsigned int +error: numeric value overflows 32-bit unsigned int diff --git a/tests/cli-tests/basic/memlimit.sh.stdout.exact b/tests/cli-tests/basic/memlimit.sh.stdout.exact index 1821648e4..a1a5520e7 100644 --- a/tests/cli-tests/basic/memlimit.sh.stdout.exact +++ b/tests/cli-tests/basic/memlimit.sh.stdout.exact @@ -11,3 +11,12 @@ + zstd --memory=1M file + zstd --memory=1MB file + zstd --memory=1MiB file ++ zstd --memory=1G file ++ zstd --memory=1GB file ++ zstd --memory=1GiB file ++ zstd --memory=3G file ++ zstd --memory=3GB file ++ zstd --memory=3GiB file ++ zstd --memory=4G file ++ zstd --memory=4GB file ++ zstd --memory=4GiB file diff --git a/tests/playTests.sh b/tests/playTests.sh index d3ce39846..d8ea0c3da 100755 --- a/tests/playTests.sh +++ b/tests/playTests.sh @@ -1075,13 +1075,19 @@ cat tmp | zstd -14 -f --size-hint=11050 | zstd -t # slightly too high cat tmp | zstd -14 -f --size-hint=10950 | zstd -t # slightly too low cat tmp | zstd -14 -f --size-hint=22000 | zstd -t # considerably too high cat tmp | zstd -14 -f --size-hint=5500 | zstd -t # considerably too low -println "test : allows and interprets K,KB,KiB,M,MB and MiB suffix" +println "test : allows and interprets K,KB,KiB,M,MB,MiB,G,GB and GiB suffix" cat tmp | zstd -14 -f --size-hint=11K | zstd -t cat tmp | zstd -14 -f --size-hint=11KB | zstd -t cat tmp | zstd -14 -f --size-hint=11KiB | zstd -t cat tmp | zstd -14 -f --size-hint=1M | zstd -t cat tmp | zstd -14 -f --size-hint=1MB | zstd -t cat tmp | zstd -14 -f --size-hint=1MiB | zstd -t +cat tmp | zstd -14 -f --size-hint=1G | zstd -t +cat tmp | zstd -14 -f --size-hint=1GB | zstd -t +cat tmp | zstd -14 -f --size-hint=1GiB | zstd -t +cat tmp | zstd -14 -f --size-hint=3G | zstd -t +cat tmp | zstd -14 -f --size-hint=3GB | zstd -t +cat tmp | zstd -14 -f --size-hint=3GiB | zstd -t println "\n===> dictionary tests " @@ -1684,6 +1690,8 @@ roundTripTest -g1M -P50 "1 --single-thread --long=29" " --memory=512MB" roundTripTest -g1M -P50 "1 --single-thread --long=29 --zstd=wlog=28" " --memory=256MB" roundTripTest -g1M -P50 "1 --single-thread --long=29" " --long=28 --memory=512MB" roundTripTest -g1M -P50 "1 --single-thread --long=29" " --zstd=wlog=28 --memory=512MB" +roundTripTest -g1M -P50 "1 --single-thread --long=30" " --memory=1GB" +roundTripTest -g1M -P50 "1 --single-thread --long=30" " --zstd=wlog=29 --memory=1GB" if [ "$ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP" -ne "1" ]; then From 3041c8e539b6027381939690ff12600ef01ade6d Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Wed, 11 Mar 2026 08:29:06 -0700 Subject: [PATCH 921/937] Update #define format --- contrib/largeNbDicts/largeNbDicts.c | 2 +- programs/fileio.c | 2 +- programs/zstdcli.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/largeNbDicts/largeNbDicts.c b/contrib/largeNbDicts/largeNbDicts.c index f7496930b..30c1396ec 100644 --- a/contrib/largeNbDicts/largeNbDicts.c +++ b/contrib/largeNbDicts/largeNbDicts.c @@ -46,7 +46,7 @@ #define BENCH_TIME_DEFAULT_MS (BENCH_TIME_DEFAULT_S * RUN_TIME_DEFAULT_MS) #ifndef ZSTD_DISPLAY_LEVEL_DEFAULT -#define ZSTD_DISPLAY_LEVEL_DEFAULT 3 +# define ZSTD_DISPLAY_LEVEL_DEFAULT 3 #endif #define BENCH_SIZE_MAX (1200 MB) diff --git a/programs/fileio.c b/programs/fileio.c index 3b2f9b636..78a906d53 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -2402,7 +2402,7 @@ int FIO_compressFilename(FIO_ctx_t* const fCtx, FIO_prefs_t* const prefs, const int const result = FIO_compressFilename_srcFile(fCtx, prefs, &ress, dstFileName, srcFileName, compressionLevel); #ifndef ZSTD_DISPLAY_LEVEL_DEFAULT -#define ZSTD_DISPLAY_LEVEL_DEFAULT 2 +# define ZSTD_DISPLAY_LEVEL_DEFAULT 2 #endif FIO_freeCResources(&ress); diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 70e170c47..1be8fc26b 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -78,7 +78,7 @@ static unsigned init_nbWorkers(unsigned defaultNbWorkers); #define GB *(1U<<30) #ifndef ZSTD_DISPLAY_LEVEL_DEFAULT -#define ZSTD_DISPLAY_LEVEL_DEFAULT 2 +# define ZSTD_DISPLAY_LEVEL_DEFAULT 2 #endif static const char* g_defaultDictName = "dictionary"; From 3f565b731e65b48800e2a8da31825b5b2af15c26 Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Thu, 12 Mar 2026 11:32:48 -0700 Subject: [PATCH 922/937] rever -q --- programs/zstdcli.c | 4 ++-- tests/cli-tests/basic/help.sh.stdout.glob | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 19c6cae89..b3c7a9900 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -168,8 +168,7 @@ static void usage(FILE* f, const char* programName) DISPLAY_F(f, " -f, --force Disable input and output checks. Allows overwriting existing files,\n"); DISPLAY_F(f, " receiving input from the console, printing output to STDOUT, and\n"); DISPLAY_F(f, " operating on links, block devices, etc. Unrecognized formats will be\n"); - DISPLAY_F(f, " passed-through through as-is.\n"); - DISPLAY_F(f, " -q, --quiet Suppress warnings; pass twice to suppress errors.\n\n"); + DISPLAY_F(f, " passed-through through as-is.\n\n"); DISPLAY_F(f, " -h Display short usage and exit.\n"); DISPLAY_F(f, " -H, --help Display full help and exit.\n"); @@ -185,6 +184,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT("Advanced options:\n"); DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n"); + DISPLAY_F(f, " -q, --quiet Suppress warnings; pass twice to suppress errors.\n"); #ifndef ZSTD_NOTRACE DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n"); #endif diff --git a/tests/cli-tests/basic/help.sh.stdout.glob b/tests/cli-tests/basic/help.sh.stdout.glob index eb249bf2b..08cfdb1b3 100644 --- a/tests/cli-tests/basic/help.sh.stdout.glob +++ b/tests/cli-tests/basic/help.sh.stdout.glob @@ -20,12 +20,11 @@ Options: receiving input from the console, printing output to STDOUT, and operating on links, block devices, etc. Unrecognized formats will be passed-through through as-is. - -q, --quiet Suppress warnings; pass twice to suppress errors. -h Display short usage and exit. -H, --help Display full help and exit. -V, --version Display the program version and exit. - + + zstd -H ... Advanced options: From e374fc76fe48d394d9265641a3e1dbbcf5050bac Mon Sep 17 00:00:00 2001 From: Jennifer Lee Date: Thu, 12 Mar 2026 11:34:43 -0700 Subject: [PATCH 923/937] fix display format --- programs/zstdcli.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index b3c7a9900..0cb4f3ba2 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -184,7 +184,7 @@ static void usageAdvanced(const char* programName) DISPLAYOUT("Advanced options:\n"); DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n"); - DISPLAY_F(f, " -q, --quiet Suppress warnings; pass twice to suppress errors.\n"); + DISPLAYOUT(" -q, --quiet Suppress warnings; pass twice to suppress errors.\n"); #ifndef ZSTD_NOTRACE DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n"); #endif From cef5a5611a3792cf9eaab5826f48e92c7c287f0a Mon Sep 17 00:00:00 2001 From: Kevin Zhang Date: Tue, 17 Mar 2026 13:08:14 -0700 Subject: [PATCH 924/937] Fix unintended high memory usage --- lib/compress/zstd_ldm.c | 6 +++++- tests/fuzzer.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/compress/zstd_ldm.c b/lib/compress/zstd_ldm.c index 070551cad..7bf36cd86 100644 --- a/lib/compress/zstd_ldm.c +++ b/lib/compress/zstd_ldm.c @@ -152,7 +152,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; diff --git a/tests/fuzzer.c b/tests/fuzzer.c index 472f8c8b3..7b7c9d666 100644 --- a/tests/fuzzer.c +++ b/tests/fuzzer.c @@ -1414,6 +1414,37 @@ static int basicUnitTests(U32 const seed, double compressibility) } DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : ldm hashRateLog > windowLog underflow check : ", testNb++); + { + /* Test that when windowLog < hashRateLog, we don't get excessive memory usage + * due to underflow in hashLog calculation (windowLog - hashRateLog). */ + ZSTD_CCtx* const cctx = ZSTD_createCCtx(); + + size_t const size = (1U << 10); // 1 KB + size_t const dstCapacity = ZSTD_compressBound(size); + void* src = (void*)malloc(size); + void* dst = (void*)malloc(dstCapacity); + + RDG_genBuffer(src, size, 0.5, 0.5, seed); + + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, ZSTD_ps_enable)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_ldmHashLog, 0)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 12)); + CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_ldmHashRateLog, 13)); + + CHECK_Z(ZSTD_compress2(cctx, dst, dstCapacity, src, size)); + + { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx); + DISPLAYLEVEL(3, "CCtx size: %u bytes ", (unsigned)cctxSize); + CHECK_LT(cctxSize, 50 MB); + } + + ZSTD_freeCCtx(cctx); + free(src); + free(dst); + } + DISPLAYLEVEL(3, "OK \n"); + DISPLAYLEVEL(3, "test%3i : testing dict compression with enableLdm and forceMaxWindow : ", testNb++); { ZSTD_CCtx* const cctx = ZSTD_createCCtx(); From 5fc4931c04de9d2c21b41a99cda546b369506508 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Apr 2026 05:50:27 +0000 Subject: [PATCH 925/937] Bump microsoft/setup-msbuild from 2.0.0 to 3.0.0 Bumps [microsoft/setup-msbuild](https://github.com/microsoft/setup-msbuild) from 2.0.0 to 3.0.0. - [Release notes](https://github.com/microsoft/setup-msbuild/releases) - [Commits](https://github.com/microsoft/setup-msbuild/compare/6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce...30375c66a4eea26614e0d39710365f22f8b0af57) --- updated-dependencies: - dependency-name: microsoft/setup-msbuild dependency-version: 3.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/cmake-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cmake-tests.yml b/.github/workflows/cmake-tests.yml index 3660dcbcf..47817a659 100644 --- a/.github/workflows/cmake-tests.yml +++ b/.github/workflows/cmake-tests.yml @@ -133,7 +133,7 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 + uses: microsoft/setup-msbuild@30375c66a4eea26614e0d39710365f22f8b0af57 # tag=v3.0.0 - name: "Configure CMake (${{ matrix.name }})" run: | cd build\cmake diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index aef73157e..5031d107b 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -321,7 +321,7 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 + uses: microsoft/setup-msbuild@30375c66a4eea26614e0d39710365f22f8b0af57 # tag=v3.0.0 - name: Build ${{matrix.name}} working-directory: ${{env.GITHUB_WORKSPACE}} # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference @@ -524,7 +524,7 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Add MSBuild to PATH - uses: microsoft/setup-msbuild@6fb02220983dee41ce7ae257b6f4d8f9bf5ed4ce # tag=v2.0.0 + uses: microsoft/setup-msbuild@30375c66a4eea26614e0d39710365f22f8b0af57 # tag=v3.0.0 - name: Build and run tests working-directory: ${{env.GITHUB_WORKSPACE}} env: From 497a433e0141ddde8f7c84aebd3ff343ed3f960a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Apr 2026 05:50:32 +0000 Subject: [PATCH 926/937] Bump android-actions/setup-android from 3.2.2 to 4.0.0 Bumps [android-actions/setup-android](https://github.com/android-actions/setup-android) from 3.2.2 to 4.0.0. - [Release notes](https://github.com/android-actions/setup-android/releases) - [Commits](https://github.com/android-actions/setup-android/compare/9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407...651bceb6f9ca583f16b8d75b62c36ded2ae6fc9c) --- updated-dependencies: - dependency-name: android-actions/setup-android dependency-version: 4.0.0 dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index 890d6fb7c..bd4aa6fde 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -22,7 +22,7 @@ jobs: distribution: 'temurin' - name: Setup Android SDK - uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3.2.2 + uses: android-actions/setup-android@651bceb6f9ca583f16b8d75b62c36ded2ae6fc9c # v4.0.0 - name: Install Android NDK run: | From a23bf84362c3f751cdc11b3b2709c03c677378ef Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Apr 2026 05:50:38 +0000 Subject: [PATCH 927/937] Bump msys2/setup-msys2 from 2.30.0 to 2.31.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.30.0 to 2.31.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/4f806de0a5a7294ffabaff804b38a9b435a73bda...cafece8e6baf9247cf9b1bf95097b0b983cc558d) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.31.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index f72a99729..447a865c5 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 + - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index aef73157e..13f929b20 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -487,7 +487,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 + - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 401441d12..cb659e5fb 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 # MSYS2 setup - - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # tag=v2.30.0 + - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 if: matrix.shell == 'msys2' with: msystem: ${{ matrix.msystem }} From 0d815ad877b43b7d2e05e18cb51673b66d0afade Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Apr 2026 05:50:47 +0000 Subject: [PATCH 928/937] Bump github/codeql-action from 4.31.2 to 4.35.1 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.31.2 to 4.35.1. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/0499de31b99561a6d14a36a5f662c2a54f91beee...c10b8064de6f491fea524254123dbe5e09572f13) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 4.35.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 31b3f731d..1e372f63a 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@0499de31b99561a6d14a36a5f662c2a54f91beee # tag=v4.31.2 + uses: github/codeql-action/upload-sarif@c10b8064de6f491fea524254123dbe5e09572f13 # tag=v4.35.1 with: sarif_file: results.sarif From 44ebbde6a3178b53e4da5a28426fbf82d1fbb6f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ey=C3=BCp=20Can=20Akman?= Date: Sun, 19 Apr 2026 20:11:15 +0300 Subject: [PATCH 929/937] Fake console stdin in valgrindTest to force failure --- build/meson/tests/valgrindTest.py | 2 +- tests/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build/meson/tests/valgrindTest.py b/build/meson/tests/valgrindTest.py index 05d84878b..8bf840704 100644 --- a/build/meson/tests/valgrindTest.py +++ b/build/meson/tests/valgrindTest.py @@ -19,7 +19,7 @@ def valgrindTest(valgrind, datagen, fuzzer, zstd, fullbench): subprocess.check_call([*VALGRIND_ARGS, datagen, '-g50M'], stdout=subprocess.DEVNULL) - if subprocess.call([*VALGRIND_ARGS, zstd], + if subprocess.call([*VALGRIND_ARGS, zstd, '--fake-stdin-is-console'], stdout=subprocess.DEVNULL) == 0: raise subprocess.SubprocessError('zstd without argument should have failed') diff --git a/tests/Makefile b/tests/Makefile index c74c219dc..bfa796ba0 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -281,7 +281,7 @@ test-valgrind: VALGRIND = valgrind --leak-check=full --show-leak-kinds=all --err test-valgrind: zstd datagen fuzzer fullbench @echo "\n ---- valgrind tests : memory analyzer ----" $(VALGRIND) ./datagen -g50M > $(VOID) - $(VALGRIND) $(PRGDIR)/zstd ; if [ $$? -eq 0 ] ; then echo "zstd without argument should have failed"; false; fi + $(VALGRIND) $(PRGDIR)/zstd --fake-stdin-is-console ; if [ $$? -eq 0 ] ; then echo "zstd without argument should have failed"; false; fi ./datagen -g80 | $(VALGRIND) $(PRGDIR)/zstd - -c > $(VOID) ./datagen -g16KB | $(VALGRIND) $(PRGDIR)/zstd -vf - -c > $(VOID) ./datagen -g2930KB | $(VALGRIND) $(PRGDIR)/zstd -5 -vf - -o tmp From c770d993fbed02b2fdc53f5534f076327a53ee23 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 May 2026 06:18:32 +0000 Subject: [PATCH 930/937] Bump msys2/setup-msys2 from 2.31.0 to 2.31.1 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.31.0 to 2.31.1. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/cafece8e6baf9247cf9b1bf95097b0b983cc558d...e9898307ac31d1a803454791be09ab9973336e1c) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.31.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 447a865c5..64360cbd5 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 + - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index 179d49e00..acd55584e 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -487,7 +487,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 + - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index cb659e5fb..fcd79b89f 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 # MSYS2 setup - - uses: msys2/setup-msys2@cafece8e6baf9247cf9b1bf95097b0b983cc558d # tag=v2.31.0 + - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 if: matrix.shell == 'msys2' with: msystem: ${{ matrix.msystem }} From cb6b844cb5f708e34f4bdcec956f26dfb80105de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 May 2026 06:18:35 +0000 Subject: [PATCH 931/937] Bump actions/upload-artifact from 7.0.0 to 7.0.1 Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 7.0.0 to 7.0.1. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v7...v7.0.1) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: 7.0.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index af3028e3c..8b8bb0f57 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -99,6 +99,6 @@ jobs: echo " are still good, copy it into the repo and commit it." echo "> diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv" diff tests/regression/results.csv $CIRCLE_ARTIFACTS/results.csv - - uses: actions/upload-artifact@v7.0.0 + - uses: actions/upload-artifact@v7.0.1 with: path: "/tmp/circleci-artifacts" diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index 447a865c5..441cd2683 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -317,7 +317,7 @@ jobs: dry-run: false sanitizer: ${{ matrix.sanitizer }} - name: Upload Crash - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # tag=v7.0.1 if: failure() && steps.build.outcome == 'success' with: name: ${{ matrix.sanitizer }}-artifacts diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 1e372f63a..caa862ca3 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -51,7 +51,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # tag=v7.0.1 with: name: SARIF file path: results.sarif diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index cb659e5fb..cd1ef23de 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -93,7 +93,7 @@ jobs: mv bin/ zstd-${{ github.ref_name }}-${{matrix.ziparch}}/ - name: Publish zstd-$VERSION-${{matrix.ziparch}}.zip for manual inspection - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # tag=v7.0.0 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # tag=v7.0.1 with: compression-level: 9 # maximum compression if-no-files-found: error # defaults to `warn` From 5233c58e6ca0b1c4c6b353ad79649191ed195bdc Mon Sep 17 00:00:00 2001 From: Nick Terrell Date: Thu, 14 May 2026 13:55:54 -0400 Subject: [PATCH 932/937] [doc] Clarify requirements around Block_Maximum_Size in spec Clarify that it is legal to send compressed blocks that are larger than the uncompressed size so long as their `Block_Content` is no larger than `Block_Maximum_Size`. See https://github.com/facebook/zstd/issues/4667 --- doc/zstd_compression_format.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/doc/zstd_compression_format.md b/doc/zstd_compression_format.md index 7700c472d..cdad14f58 100644 --- a/doc/zstd_compression_format.md +++ b/doc/zstd_compression_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -0.4.4 (2025-03-22) +0.4.5 (2026-05-14) Introduction @@ -387,20 +387,24 @@ When `Block_Type` is `RLE_Block`, since `Block_Content`’s size is always 1, __`Block_Content`__ and __`Block_Maximum_Size`__ -The size of `Block_Content` is limited by `Block_Maximum_Size`, -which is the smallest of: +The size of `Block_Content` is limited by `Block_Maximum_Size`, which is +determined once for a given frame and is the smallest of: - `Window_Size` - 128 KiB (131.072 bytes) -`Block_Maximum_Size` is constant for a given frame. -This maximum is applicable to both the decompressed size -and the compressed size of any block in the frame. +Both the `Block_Content` and the decompressed size of any block in the frame must +be no larger than `Block_Maximum_Size`. The reasoning for this limit is that a decoder can read this information at the beginning of a frame and use it to allocate buffers. The guarantees on the size of blocks ensure that the buffers will be large enough for any following block of the valid frame. +If a compressed block is larger than its uncompressed content, it is recommended +to send it uncompressed (i.e., a `Raw_Block`). However, as long as +`Block_Content` is no larger than `Block_Maximum_Size`, it is legal to send such +a compressed block, even if it's larger than its uncompressed content. + Compressed Blocks ----------------- @@ -1742,6 +1746,7 @@ or at least provide a meaningful error code explaining for which reason it canno Version changes --------------- +- 0.4.5 : minor clarification regarding Block_Maximum_Size - 0.4.4 : minor clarification for block size - 0.4.3 : clarifications for Huffman prefix code assignment example - 0.4.2 : refactor FSE table construction process, inspired by Donald Pian From a20ab7436fcb947c7322655c7cf03710cefdf1c1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Jul 2026 05:32:43 +0000 Subject: [PATCH 933/937] Bump github/codeql-action/upload-sarif from 4.35.1 to 4.36.2 Bumps [github/codeql-action/upload-sarif](https://github.com/github/codeql-action) from 4.35.1 to 4.36.2. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/c10b8064de6f491fea524254123dbe5e09572f13...8aad20d150bbac5944a9f9d289da16a4b0d87c1e) --- updated-dependencies: - dependency-name: github/codeql-action/upload-sarif dependency-version: 4.36.2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/scorecards.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index caa862ca3..fb678cf68 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -59,6 +59,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@c10b8064de6f491fea524254123dbe5e09572f13 # tag=v4.35.1 + uses: github/codeql-action/upload-sarif@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # tag=v4.36.2 with: sarif_file: results.sarif From 61b9912eec9d703248a96fdf0e9ec5bd14bf7e5c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 1 Jul 2026 05:32:46 +0000 Subject: [PATCH 934/937] Bump cygwin/cygwin-install-action from 6.0.1 to 6.0.2 Bumps [cygwin/cygwin-install-action](https://github.com/cygwin/cygwin-install-action) from 6.0.1 to 6.0.2. - [Release notes](https://github.com/cygwin/cygwin-install-action/releases) - [Commits](https://github.com/cygwin/cygwin-install-action/compare/711d29f3da23c9f4a1798e369a6f01198c13b11a...3f0a3f9f988f7e96b8c18098ae05eaec175f5b52) --- updated-dependencies: - dependency-name: cygwin/cygwin-install-action dependency-version: 6.0.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-short-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index acd55584e..cfd0294ca 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -544,7 +544,7 @@ jobs: steps: - run: git config --global core.autocrlf input - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: cygwin/cygwin-install-action@711d29f3da23c9f4a1798e369a6f01198c13b11a # tag=v6 + - uses: cygwin/cygwin-install-action@3f0a3f9f988f7e96b8c18098ae05eaec175f5b52 # tag=v6 with: platform: x86_64 packages: >- From a1ddcdae2d8a81668d4d8aa38b15e2e17bed1efc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 05:32:35 +0000 Subject: [PATCH 935/937] Bump actions/cache from 5 to 6 Bumps [actions/cache](https://github.com/actions/cache) from 5 to 6. - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v5...v6) --- updated-dependencies: - dependency-name: actions/cache dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml index 8b8bb0f57..a66818409 100644 --- a/.github/workflows/commit.yml +++ b/.github/workflows/commit.yml @@ -75,7 +75,7 @@ jobs: steps: - uses: actions/checkout@v6.0.2 - name: restore_cache - uses: actions/cache@v5 + uses: actions/cache@v6 with: key: regression-cache-{{ checksum "tests/regression/data.c" }}-v0 path: tests/regression/cache From e0764492056386c0d4334bff26d53efccc08e01a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 05:32:52 +0000 Subject: [PATCH 936/937] Bump actions/setup-java from 5.2.0 to 5.6.0 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5.2.0 to 5.6.0. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/be666c2fcd27ec809703dec50e508c2fdc7f6654...03ad4de0992f5dab5e18fcb136590ce7c4a0ac95) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 5.6.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/android-ndk-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/android-ndk-build.yml b/.github/workflows/android-ndk-build.yml index bd4aa6fde..1e9e23e08 100644 --- a/.github/workflows/android-ndk-build.yml +++ b/.github/workflows/android-ndk-build.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - name: Set up JDK 17 - uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0 + uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5.6.0 with: java-version: '17' distribution: 'temurin' From af48fb967f65fd4d70ede433fc2562b114c66264 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Aug 2026 05:32:58 +0000 Subject: [PATCH 937/937] Bump msys2/setup-msys2 from 2.31.1 to 2.32.0 Bumps [msys2/setup-msys2](https://github.com/msys2/setup-msys2) from 2.31.1 to 2.32.0. - [Release notes](https://github.com/msys2/setup-msys2/releases) - [Changelog](https://github.com/msys2/setup-msys2/blob/main/CHANGELOG.md) - [Commits](https://github.com/msys2/setup-msys2/compare/e9898307ac31d1a803454791be09ab9973336e1c...66cd2cce69caa17b53920067426061ca1de3a884) --- updated-dependencies: - dependency-name: msys2/setup-msys2 dependency-version: 2.32.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/dev-long-tests.yml | 2 +- .github/workflows/dev-short-tests.yml | 2 +- .github/workflows/windows-artifacts.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/dev-long-tests.yml b/.github/workflows/dev-long-tests.yml index da607543e..c5b1e22d5 100644 --- a/.github/workflows/dev-long-tests.yml +++ b/.github/workflows/dev-long-tests.yml @@ -274,7 +274,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 + - uses: msys2/setup-msys2@66cd2cce69caa17b53920067426061ca1de3a884 # tag=v2.32.0 with: msystem: MINGW64 install: make diff --git a/.github/workflows/dev-short-tests.yml b/.github/workflows/dev-short-tests.yml index cfd0294ca..4b8a95d18 100644 --- a/.github/workflows/dev-short-tests.yml +++ b/.github/workflows/dev-short-tests.yml @@ -487,7 +487,7 @@ jobs: shell: msys2 {0} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 - - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 + - uses: msys2/setup-msys2@66cd2cce69caa17b53920067426061ca1de3a884 # tag=v2.32.0 with: msystem: ${{ matrix.msystem }} install: make diffutils diff --git a/.github/workflows/windows-artifacts.yml b/.github/workflows/windows-artifacts.yml index 9998584d9..97454beb2 100644 --- a/.github/workflows/windows-artifacts.yml +++ b/.github/workflows/windows-artifacts.yml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # tag=v6.0.2 # MSYS2 setup - - uses: msys2/setup-msys2@e9898307ac31d1a803454791be09ab9973336e1c # tag=v2.31.1 + - uses: msys2/setup-msys2@66cd2cce69caa17b53920067426061ca1de3a884 # tag=v2.32.0 if: matrix.shell == 'msys2' with: msystem: ${{ matrix.msystem }}