multi_compress 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -0
  3. data/GET_STARTED.md +4 -2
  4. data/README.md +1 -1
  5. data/THIRD_PARTY_NOTICES.md +2 -2
  6. data/ext/multi_compress/exports.darwin +1 -0
  7. data/ext/multi_compress/exports.map +4 -0
  8. data/ext/multi_compress/extconf.rb +20 -0
  9. data/ext/multi_compress/multi_compress.c +123 -73
  10. data/ext/multi_compress/vendor/.vendored +1 -1
  11. data/ext/multi_compress/vendor/zstd/lib/BUCK +10 -5
  12. data/ext/multi_compress/vendor/zstd/lib/README.md +25 -5
  13. data/ext/multi_compress/vendor/zstd/lib/common/allocations.h +6 -2
  14. data/ext/multi_compress/vendor/zstd/lib/common/bits.h +1 -1
  15. data/ext/multi_compress/vendor/zstd/lib/common/bitstream.h +3 -3
  16. data/ext/multi_compress/vendor/zstd/lib/common/bmi2.h +40 -0
  17. data/ext/multi_compress/vendor/zstd/lib/common/compiler.h +37 -11
  18. data/ext/multi_compress/vendor/zstd/lib/common/entropy_common.c +7 -6
  19. data/ext/multi_compress/vendor/zstd/lib/common/fse_decompress.c +4 -3
  20. data/ext/multi_compress/vendor/zstd/lib/common/pool.c +16 -19
  21. data/ext/multi_compress/vendor/zstd/lib/common/portability_macros.h +31 -0
  22. data/ext/multi_compress/vendor/zstd/lib/common/threading.c +16 -2
  23. data/ext/multi_compress/vendor/zstd/lib/common/zstd_common.c +9 -0
  24. data/ext/multi_compress/vendor/zstd/lib/common/zstd_internal.h +4 -2
  25. data/ext/multi_compress/vendor/zstd/lib/compress/hist.c +300 -3
  26. data/ext/multi_compress/vendor/zstd/lib/compress/hist.h +4 -0
  27. data/ext/multi_compress/vendor/zstd/lib/compress/huf_compress.c +4 -1
  28. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress.c +775 -214
  29. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_internal.h +35 -6
  30. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_sequences.c +9 -5
  31. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_compress_superblock.c +14 -5
  32. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_double_fast.c +2 -2
  33. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_fast.c +2 -2
  34. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_lazy.c +49 -5
  35. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_ldm.c +11 -11
  36. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_ldm.h +11 -0
  37. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_opt.c +16 -18
  38. data/ext/multi_compress/vendor/zstd/lib/compress/zstd_preSplit.c +3 -3
  39. data/ext/multi_compress/vendor/zstd/lib/compress/zstdmt_compress.c +64 -39
  40. data/ext/multi_compress/vendor/zstd/lib/compress/zstdmt_compress.h +30 -2
  41. data/ext/multi_compress/vendor/zstd/lib/decompress/huf_decompress.c +78 -64
  42. data/ext/multi_compress/vendor/zstd/lib/decompress/huf_decompress_amd64.S +182 -18
  43. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_ddict.c +59 -27
  44. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_ddict.h +11 -0
  45. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress.c +194 -93
  46. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress_block.c +225 -85
  47. data/ext/multi_compress/vendor/zstd/lib/decompress/zstd_decompress_internal.h +19 -2
  48. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/cover.c +136 -91
  49. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/divsufsort.c +77 -77
  50. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/fastcover.c +48 -42
  51. data/ext/multi_compress/vendor/zstd/lib/dictBuilder/zdict.c +18 -14
  52. data/ext/multi_compress/vendor/zstd/lib/dll/example/build_package.bat +66 -20
  53. data/ext/multi_compress/vendor/zstd/lib/dll/example/fullbench-dll.vcxproj +10 -6
  54. data/ext/multi_compress/vendor/zstd/lib/install_oses.mk +17 -0
  55. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v01.c +10 -8
  56. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v02.c +5 -364
  57. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v03.c +4 -5
  58. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v04.c +7 -3
  59. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v05.c +8 -5
  60. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v06.c +3 -3
  61. data/ext/multi_compress/vendor/zstd/lib/legacy/zstd_v07.c +1 -0
  62. data/ext/multi_compress/vendor/zstd/lib/libzstd.mk +8 -7
  63. data/ext/multi_compress/vendor/zstd/lib/libzstd.pc.in +1 -0
  64. data/ext/multi_compress/vendor/zstd/lib/module.modulemap +0 -21
  65. data/ext/multi_compress/vendor/zstd/lib/zstd.h +209 -112
  66. data/lib/multi_compress/reader/read_operations.rb +2 -0
  67. data/lib/multi_compress/version.rb +1 -1
  68. data/multi_compress.gemspec +2 -0
  69. data/mysql_udf/Makefile +12 -5
  70. data/mysql_udf/multi_compress_mysql.exports +6 -0
  71. data/postgres_extension/Makefile +2 -1
  72. data/postgres_extension/test/run_e2e.sh +28 -10
  73. metadata +6 -5
  74. data/ext/multi_compress/vendor/lz4/lib/Makefile +0 -244
  75. data/ext/multi_compress/vendor/lz4/lib/dll/example/Makefile +0 -63
  76. data/ext/multi_compress/vendor/zstd/lib/Makefile +0 -389
  77. data/ext/multi_compress/vendor/zstd/lib/dll/example/Makefile +0 -48
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4cd5ef825dbbd3c13e3eac0d41eef32f086009a18f37418bdbfed70ba25e21f5
4
- data.tar.gz: 890a0635d3ea5022175d8bee00525b0fa40587a293df9c3dafe6e0467b5f36b2
3
+ metadata.gz: a5735160681919d2bd51ffde344dcd31aaf9ca08767c0939e9d657a4915e4432
4
+ data.tar.gz: 2454cd5e4ee3dd82e4dcb20af13e48adc44f8cb5fa487d6ddc4d74bf9e655848
5
5
  SHA512:
6
- metadata.gz: 7226cdc2c0b8e532087dbb85257323d842d2784f3686bca24ce0dfad01f0f8862941480b39c0c0e3155d646caa692b88f8ab5bcd9aac65470ae23cf074af0826
7
- data.tar.gz: 41ba902f053d2aacd5f4079ab8be9c2eda75987a896f18e352c59f642ee127b67fc53625816a0f6572598cb0968aa62d6c2701deba4bc39c6aaec830540a800f
6
+ metadata.gz: 82c35a0bd5623186ba2220689e3fdd17c6fb91c0b307973d1517750b6e2391645c78cf610f98c69198e58165652bdc0c426270ea12907cb3e1f520529738e069
7
+ data.tar.gz: db6f54a4b6731d0c1ceb35de2c6d28b19bb3b53dfb1dfcceef97a5230d84d0e945ac82e088d6fdf9bfb19e6be966c10a2c79846e71b31905585be00fc2c224d6
data/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.7.0]
4
+
5
+ ### Changed
6
+ - Update vendored zstd to 1.6.0, including upstream fixes for streaming
7
+ decompression, dictionary compression and dictionary training. Compressed
8
+ output and trained dictionaries were byte-identical to 1.5.7 in our tests, and
9
+ data stays compatible in both directions. Rebuild and redeploy the
10
+ PostgreSQL extension and the MySQL UDF to get the decoder fixes in the database.
11
+ - Streaming decoders reject truncated input: `Inflater#finish` and `Reader`
12
+ (`read`, `read(length)`, `gets`, `each_line`) raise `MultiCompress::DataError`
13
+ when a zstd, brotli or lz4 stream ends early. They used to return the partial
14
+ output as if it were complete.
15
+ - zstd input without a declared content size (written by `Deflater`/`Writer` or
16
+ other streaming encoders): `MultiCompress.decompress` now decodes every
17
+ concatenated frame and raises `DataError` for a truncated frame or for garbage
18
+ after a frame. It used to return partial output, only the first frame, or
19
+ ignore the garbage. The one-shot path for a first frame with a declared content
20
+ size still decodes only that frame and rejects concatenated frames. `Inflater#write`
21
+ no longer drops the rest of a chunk after a zstd frame ends.
22
+ - A frame compressed with a zstd dictionary always needs `dictionary:` to decode.
23
+ It could previously decode without one if the same thread had just decoded a
24
+ streaming frame with that dictionary.
25
+ - `Inflater` reports a corrupted zstd dictionary as `Dictionary is corrupted`
26
+ instead of `Allocation error` (zstd 1.6.0). `compress`/`decompress` still raise
27
+ `MemError` ("failed to create cdict/ddict") for such a dictionary.
28
+
29
+ ### Fixed
30
+ - Use-after-free of a zstd dictionary: decoding a frame without content size left
31
+ its `DDict` referenced on the thread-local decompression context, and a later
32
+ one-shot `decompress` on that thread read it after GC had freed the
33
+ `Dictionary`. One-shot decoding now passes the dictionary explicitly, and the
34
+ context is reset on every exit, including exceptions.
35
+ - Vendored codec symbols are private in the Ruby extension and the MySQL UDF
36
+ (the PostgreSQL extension already used an export map). A zstd already loaded in
37
+ the process, such as the system libzstd pulled in by `mysql2` or linked into
38
+ mysqld 8, can no longer replace the bundled implementation. zstd's weak
39
+ `ZSTD_trace_*` hooks are compiled out.
40
+ - `script/sanitize.sh` builds an ASAN/UBSAN-instrumented extension. mkmf ignores
41
+ `CFLAGS` from the environment, so the script used to run the suite on an
42
+ uninstrumented build.
43
+
3
44
  ## [0.6.1]
4
45
 
5
46
  ### Changed
data/GET_STARTED.md CHANGED
@@ -163,6 +163,8 @@ inflater.close
163
163
  original_data = decompressed_chunks.join
164
164
  ```
165
165
 
166
+ `Inflater#finish` (and `Reader` at end of input) raises `MultiCompress::DataError` when the compressed stream ends before its end marker, so a truncated file or upload is reported instead of returning partial data.
167
+
166
168
  ### Advanced Streaming Example
167
169
 
168
170
  ```ruby
@@ -402,7 +404,7 @@ end
402
404
 
403
405
  Dramatically improves compression on small, similar data (JSON APIs, configs, logs).
404
406
 
405
- **Important**: Dictionary training is available for **Zstd** in the current release (vendored zstd **1.5.7**). Brotli dictionaries can be used, but this gem does not expose Brotli training through `train_dictionary`.
407
+ **Important**: Dictionary training is available for **Zstd** in the current release (vendored zstd **1.6.0**). Brotli dictionaries can be used, but this gem does not expose Brotli training through `train_dictionary`.
406
408
 
407
409
  ### Training Dictionary (Zstd)
408
410
 
@@ -679,7 +681,7 @@ MultiCompress.available?(:zstd) # => true
679
681
  MultiCompress.available?(:fake) # => false
680
682
 
681
683
  # Get library versions
682
- MultiCompress.version(:zstd) # => "1.5.7"
684
+ MultiCompress.version(:zstd) # => "1.6.0"
683
685
  MultiCompress.version(:lz4) # => "1.10.0"
684
686
  MultiCompress.version(:brotli) # => "1.2.1"
685
687
  ```
data/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  Modern compression technology: **zstd**, **lz4**, **brotli** — unified compression platform with native C performance, **fiber-friendly** for modern async Ruby stacks.
8
8
 
9
9
  Bundled library versions in the current release:
10
- - **zstd 1.5.7**
10
+ - **zstd 1.6.0**
11
11
  - **lz4 1.10.0**
12
12
  - **brotli 1.2.1**
13
13
 
@@ -6,7 +6,7 @@ MultiCompress vendors C sources from upstream compression libraries so the gem c
6
6
 
7
7
  | Library | Vendored version | Vendored source scope | Upstream license used by MultiCompress |
8
8
  |---|---:|---|---|
9
- | Zstandard (`zstd`) | 1.5.7 | `lib/` | BSD side of upstream BSD OR GPLv2 licensing |
9
+ | Zstandard (`zstd`) | 1.6.0 | `lib/` | BSD side of upstream BSD OR GPLv2 licensing |
10
10
  | LZ4 | 1.10.0 | `lib/` | BSD 2-Clause |
11
11
  | Brotli | 1.2.1 | `c/common`, `c/enc`, `c/dec`, `c/include` | MIT |
12
12
 
@@ -19,6 +19,6 @@ MultiCompress vendors C sources from upstream compression libraries so the gem c
19
19
 
20
20
  ## Upstream projects
21
21
 
22
- - Zstandard: https://github.com/facebook/zstd
22
+ - Zstandard: https://github.com/meta/zstd
23
23
  - LZ4: https://github.com/lz4/lz4
24
24
  - Brotli: https://github.com/google/brotli
@@ -0,0 +1 @@
1
+ _Init_multi_compress
@@ -0,0 +1,4 @@
1
+ {
2
+ global: Init_multi_compress;
3
+ local: *;
4
+ };
@@ -253,6 +253,26 @@ end
253
253
  $CFLAGS += " -O3"
254
254
  $CFLAGS += " -DXXH_NAMESPACE=MULTICOMPRESS_"
255
255
 
256
+ if vpath_dirs
257
+ if RbConfig::CONFIG["GCC"] == "yes" && try_cflags("-fvisibility=hidden", werror: false)
258
+ $CFLAGS += " -fvisibility=hidden"
259
+ puts " vendored codec symbols: hidden"
260
+ elsif RUBY_PLATFORM.match?(/darwin|linux/)
261
+ puts " WARNING: -fvisibility=hidden unavailable; relying on the linker export list"
262
+ else
263
+ puts " WARNING: -fvisibility=hidden unavailable; vendored codec symbols may be exported"
264
+ end
265
+ $CPPFLAGS += " -DZSTDLIB_VISIBLE= -DZSTDERRORLIB_VISIBLE= -DZDICTLIB_VISIBLE=" \
266
+ " -DLZ4LIB_VISIBILITY= -DLZ4FLIB_VISIBILITY="
267
+ $CPPFLAGS += " -DZSTD_TRACE=0"
268
+
269
+ if RUBY_PLATFORM.include?("darwin")
270
+ $DLDFLAGS += " -Wl,-exported_symbols_list,#{File.join(__dir__, 'exports.darwin')}"
271
+ elsif RUBY_PLATFORM.include?("linux")
272
+ $DLDFLAGS += " -Wl,--version-script=#{File.join(__dir__, 'exports.map')}"
273
+ end
274
+ end
275
+
256
276
  if RUBY_PLATFORM.include?("darwin") && try_cflags("-Wno-default-const-init-field-unsafe")
257
277
  $CFLAGS += " -Wno-default-const-init-field-unsafe"
258
278
  end
@@ -184,10 +184,7 @@ static size_t zstd_decompress_cached(void *dst, size_t dst_cap, const void *src,
184
184
  return 0;
185
185
  }
186
186
 
187
- if (ddict)
188
- return ZSTD_decompress_usingDDict(dctx, dst, dst_cap, src, src_len, ddict);
189
-
190
- return ZSTD_decompressDCtx(dctx, dst, dst_cap, src, src_len);
187
+ return ZSTD_decompress_usingDDict(dctx, dst, dst_cap, src, src_len, ddict);
191
188
  }
192
189
 
193
190
  _Static_assert(ALGO_BROTLI == MC_NUM_ALGOS - 1,
@@ -1618,6 +1615,75 @@ static VALUE zstd_single_frame_info(VALUE self, VALUE data) {
1618
1615
  return result;
1619
1616
  }
1620
1617
 
1618
+ typedef struct {
1619
+ ZSTD_DCtx *dctx;
1620
+ ZSTD_DDict *ddict;
1621
+ const char *src;
1622
+ size_t src_len;
1623
+ limits_config_t limits;
1624
+ } zstd_unknown_size_args_t;
1625
+
1626
+ static VALUE zstd_decompress_unknown_size_body(VALUE arg) {
1627
+ zstd_unknown_size_args_t *a = (zstd_unknown_size_args_t *)arg;
1628
+ ZSTD_DCtx *dctx = a->dctx;
1629
+ const size_t max_out = a->limits.max_output_size;
1630
+ const size_t hard_cap = max_out == SIZE_MAX ? SIZE_MAX : max_out + 1;
1631
+
1632
+ size_t r = ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1633
+ if (ZSTD_isError(r))
1634
+ rb_raise(eError, "zstd dctx reset: %s", ZSTD_getErrorName(r));
1635
+ if (a->ddict) {
1636
+ r = ZSTD_DCtx_refDDict(dctx, a->ddict);
1637
+ if (ZSTD_isError(r))
1638
+ rb_raise(eError, "zstd dict ref: %s", ZSTD_getErrorName(r));
1639
+ }
1640
+
1641
+ size_t alloc_size = (a->src_len > max_out / 8) ? max_out : a->src_len * 8;
1642
+ if (alloc_size < 4096)
1643
+ alloc_size = 4096;
1644
+ if (alloc_size > hard_cap)
1645
+ alloc_size = hard_cap;
1646
+
1647
+ VALUE dst = rb_binary_str_buf_reserve(alloc_size);
1648
+ size_t total_out = 0;
1649
+ ZSTD_inBuffer input = {a->src, a->src_len, 0};
1650
+
1651
+ for (;;) {
1652
+ if (total_out >= alloc_size) {
1653
+ if (alloc_size >= hard_cap)
1654
+ rb_raise(eDataError, "decompressed output exceeds limit (%zu bytes)", max_out);
1655
+ alloc_size = alloc_size > hard_cap / 2 ? hard_cap : alloc_size * 2;
1656
+ grow_binary_str(dst, total_out, alloc_size);
1657
+ }
1658
+
1659
+ size_t out_cap = alloc_size - total_out;
1660
+ ZSTD_outBuffer output = {RSTRING_PTR(dst) + total_out, out_cap, 0};
1661
+ size_t ret = ZSTD_decompressStream(dctx, &output, &input);
1662
+ if (ZSTD_isError(ret))
1663
+ rb_raise(eDataError, "zstd decompress: %s", ZSTD_getErrorName(ret));
1664
+ total_out = checked_add_size(total_out, output.pos,
1665
+ "decompressed output exceeds representable size");
1666
+ enforce_output_and_ratio_limits(total_out, a->src_len, max_out,
1667
+ a->limits.max_ratio_enabled, a->limits.max_ratio);
1668
+
1669
+ if (ret == 0) {
1670
+ if (input.pos == input.size)
1671
+ break;
1672
+ continue;
1673
+ }
1674
+ if (input.pos == input.size && output.pos < out_cap)
1675
+ rb_raise(eDataError, "zstd decompress: truncated input (incomplete frame)");
1676
+ }
1677
+
1678
+ rb_binary_str_set_len(dst, total_out);
1679
+ return dst;
1680
+ }
1681
+
1682
+ static VALUE zstd_tls_dctx_release(VALUE arg) {
1683
+ ZSTD_DCtx_reset((ZSTD_DCtx *)(uintptr_t)arg, ZSTD_reset_session_and_parameters);
1684
+ return Qnil;
1685
+ }
1686
+
1621
1687
  static VALUE compress_decompress(int argc, VALUE *argv, VALUE self) {
1622
1688
  VALUE data, opts;
1623
1689
  scan_one_required_keywords(argc, argv, &data, &opts);
@@ -1740,69 +1806,21 @@ static VALUE compress_decompress(int argc, VALUE *argv, VALUE self) {
1740
1806
  if (!dctx)
1741
1807
  rb_raise(eMemError, "zstd: failed to create dctx");
1742
1808
 
1743
- {
1744
- size_t r = ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1745
- if (ZSTD_isError(r))
1746
- rb_raise(eError, "zstd dctx reset: %s", ZSTD_getErrorName(r));
1747
- }
1748
-
1809
+ zstd_unknown_size_args_t uargs = {
1810
+ .dctx = dctx,
1811
+ .ddict = NULL,
1812
+ .src = src,
1813
+ .src_len = slen,
1814
+ .limits = limits,
1815
+ };
1749
1816
  if (dict) {
1750
- ZSTD_DDict *ddict = dict_get_ddict(dict);
1751
- if (ddict) {
1752
- size_t r = ZSTD_DCtx_refDDict(dctx, ddict);
1753
- if (ZSTD_isError(r)) {
1754
- rb_raise(eError, "zstd dict ref: %s", ZSTD_getErrorName(r));
1755
- }
1756
- }
1817
+ uargs.ddict = dict_get_ddict(dict);
1818
+ if (!uargs.ddict)
1819
+ rb_raise(eMemError, "zstd: failed to create ddict");
1757
1820
  }
1758
1821
 
1759
- size_t alloc_size = (slen > limits.max_output_size / 8) ? limits.max_output_size : slen * 8;
1760
- if (alloc_size < 4096)
1761
- alloc_size = limits.max_output_size < 4096 ? limits.max_output_size : 4096;
1762
- if (alloc_size == 0)
1763
- alloc_size = limits.max_output_size;
1764
-
1765
- VALUE dst = rb_binary_str_buf_reserve(alloc_size);
1766
- size_t total_out = 0;
1767
-
1768
- ZSTD_inBuffer input = {src, slen, 0};
1769
- while (input.pos < input.size) {
1770
- if (total_out >= alloc_size) {
1771
- if (alloc_size >= limits.max_output_size) {
1772
- rb_raise(eDataError, "decompressed output exceeds limit (%zu bytes)",
1773
- limits.max_output_size);
1774
- }
1775
- size_t next_cap = alloc_size * 2;
1776
- if (next_cap > limits.max_output_size)
1777
- next_cap = limits.max_output_size;
1778
- alloc_size = next_cap;
1779
- grow_binary_str(dst, total_out, alloc_size);
1780
- }
1781
-
1782
- size_t remaining_budget = limits.max_output_size - total_out;
1783
- if (remaining_budget == 0) {
1784
- rb_raise(eDataError, "decompressed output exceeds limit (%zu bytes)",
1785
- limits.max_output_size);
1786
- }
1787
-
1788
- size_t out_cap = alloc_size - total_out;
1789
- if (out_cap > remaining_budget)
1790
- out_cap = remaining_budget;
1791
-
1792
- ZSTD_outBuffer output = {RSTRING_PTR(dst) + total_out, out_cap, 0};
1793
- size_t ret = ZSTD_decompressStream(dctx, &output, &input);
1794
- if (ZSTD_isError(ret)) {
1795
- rb_raise(eDataError, "zstd decompress: %s", ZSTD_getErrorName(ret));
1796
- }
1797
- total_out = checked_add_size(total_out, output.pos,
1798
- "decompressed output exceeds representable size");
1799
- enforce_output_and_ratio_limits(total_out, slen, limits.max_output_size,
1800
- limits.max_ratio_enabled, limits.max_ratio);
1801
- if (ret == 0)
1802
- break;
1803
- }
1804
-
1805
- rb_binary_str_set_len(dst, total_out);
1822
+ VALUE dst = rb_ensure(zstd_decompress_unknown_size_body, (VALUE)&uargs,
1823
+ zstd_tls_dctx_release, (VALUE)(uintptr_t)dctx);
1806
1824
  RB_GC_GUARD(data);
1807
1825
  RB_GC_GUARD(dict_val);
1808
1826
  return dst;
@@ -2879,6 +2897,8 @@ typedef struct {
2879
2897
  int closed;
2880
2898
  int finished;
2881
2899
  int operation_active;
2900
+ int stream_open;
2901
+ int lz4_ended;
2882
2902
  size_t max_output_size;
2883
2903
  size_t total_output;
2884
2904
  size_t total_input;
@@ -3042,8 +3062,10 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3042
3062
  ZSTD_inBuffer input = {src, slen, 0};
3043
3063
  size_t out_cap = ZSTD_DStreamOutSize();
3044
3064
  size_t result_cap = out_cap > slen * 2 ? out_cap : slen * 2;
3065
+ size_t hard_limit =
3066
+ inf->max_output_size == SIZE_MAX ? SIZE_MAX : inf->max_output_size + 1;
3045
3067
  size_t remaining_total_budget =
3046
- inf->max_output_size > inf->total_output ? inf->max_output_size - inf->total_output : 0;
3068
+ hard_limit > inf->total_output ? hard_limit - inf->total_output : 0;
3047
3069
  if (remaining_total_budget == 0)
3048
3070
  rb_raise(eDataError, "decompressed output exceeds limit (%zu bytes)",
3049
3071
  inf->max_output_size);
@@ -3052,17 +3074,19 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3052
3074
  VALUE result = rb_binary_str_buf_reserve(result_cap);
3053
3075
  size_t result_len = 0;
3054
3076
  VALUE scheduler = current_fiber_scheduler();
3077
+ size_t ret = 0;
3078
+ int drain = 0;
3055
3079
 
3056
- while (input.pos < input.size) {
3057
- size_t remaining_budget = inf->max_output_size - inf->total_output - result_len;
3080
+ while (input.pos < input.size || drain) {
3081
+ size_t remaining_budget = remaining_total_budget - result_len;
3058
3082
  if (remaining_budget == 0)
3059
3083
  rb_raise(eDataError, "decompressed output exceeds limit (%zu bytes)",
3060
3084
  inf->max_output_size);
3061
3085
 
3062
3086
  if (result_len + out_cap > result_cap) {
3063
3087
  size_t next_cap = result_cap * 2;
3064
- if (next_cap > inf->max_output_size - inf->total_output)
3065
- next_cap = inf->max_output_size - inf->total_output;
3088
+ if (next_cap > remaining_total_budget)
3089
+ next_cap = remaining_total_budget;
3066
3090
  result_cap = next_cap;
3067
3091
  rb_str_resize(result, result_cap);
3068
3092
  }
@@ -3072,7 +3096,6 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3072
3096
  current_out_cap = remaining_budget;
3073
3097
 
3074
3098
  ZSTD_outBuffer output = {RSTRING_PTR(result) + result_len, current_out_cap, 0};
3075
- size_t ret;
3076
3099
 
3077
3100
  if (select_fiber_or_direct_mode(scheduler, input.size - input.pos,
3078
3101
  policy->fiber_stream_threshold) == WORK_EXEC_FIBER) {
@@ -3100,9 +3123,9 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3100
3123
  "compressed input exceeds representable size");
3101
3124
  enforce_output_and_ratio_limits(total_output, total_input, inf->max_output_size,
3102
3125
  inf->max_ratio_enabled, inf->max_ratio);
3103
- if (ret == 0)
3104
- break;
3126
+ drain = ret != 0 && output.pos == current_out_cap;
3105
3127
  }
3128
+ inf->stream_open = ret != 0;
3106
3129
  inf->total_input = checked_add_size(input_accounted_before, input.pos,
3107
3130
  "compressed input exceeds representable size");
3108
3131
  inf->total_output = checked_add_size(inf->total_output, result_len,
@@ -3237,12 +3260,17 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3237
3260
  int use_fiber = has_fiber_scheduler();
3238
3261
  size_t fiber_counter = 0;
3239
3262
 
3263
+ if (!inf->lz4_ended)
3264
+ inf->stream_open = 1;
3265
+
3240
3266
  size_t pos = inf->lz4_buf.offset;
3241
3267
  while (pos + 4 <= inf->lz4_buf.len) {
3242
3268
  const uint8_t *p = (const uint8_t *)(inf->lz4_buf.buf + pos);
3243
3269
  uint32_t orig_size = read_le_u32(p);
3244
3270
  if (orig_size == 0) {
3245
3271
  inf->finished = 1;
3272
+ inf->lz4_ended = 1;
3273
+ inf->stream_open = 0;
3246
3274
  pos += 4;
3247
3275
  break;
3248
3276
  }
@@ -3278,6 +3306,8 @@ static VALUE inflater_write_impl(VALUE self, VALUE chunk) {
3278
3306
 
3279
3307
  result_len += dsize;
3280
3308
  pos += 8 + comp_size;
3309
+ inf->lz4_ended = 0;
3310
+ inf->stream_open = 1;
3281
3311
  if (use_fiber) {
3282
3312
  int did_yield = 0;
3283
3313
  fiber_counter = fiber_maybe_yield(fiber_counter, (size_t)dsize,
@@ -3305,12 +3335,30 @@ static VALUE inflater_write(VALUE self, VALUE chunk) {
3305
3335
  return stream_operation_call(&inf->operation_active, self, chunk, inflater_write_impl);
3306
3336
  }
3307
3337
 
3338
+ static void inflater_ensure_complete(inflater_t *inf) {
3339
+ switch (inf->algo) {
3340
+ case ALGO_ZSTD:
3341
+ if (inf->stream_open)
3342
+ rb_raise(eDataError, "zstd stream is truncated (incomplete frame)");
3343
+ break;
3344
+ case ALGO_BROTLI:
3345
+ if (inf->total_input > 0 && !BrotliDecoderIsFinished(inf->ctx.brotli))
3346
+ rb_raise(eDataError, "brotli stream is truncated (incomplete stream)");
3347
+ break;
3348
+ case ALGO_LZ4:
3349
+ if (inf->stream_open)
3350
+ rb_raise(eDataError, "lz4 stream is truncated (missing end marker)");
3351
+ break;
3352
+ }
3353
+ }
3354
+
3308
3355
  static VALUE inflater_finish_impl(VALUE self, VALUE unused) {
3309
3356
  (void)unused;
3310
3357
  inflater_t *inf;
3311
3358
  TypedData_Get_Struct(self, inflater_t, &inflater_type, inf);
3312
3359
  if (inf->closed)
3313
3360
  rb_raise(eStreamError, "stream is closed");
3361
+ inflater_ensure_complete(inf);
3314
3362
  inf->finished = 1;
3315
3363
  return rb_binary_str_new("", 0);
3316
3364
  }
@@ -3362,6 +3410,8 @@ static VALUE inflater_reset_impl(VALUE self, VALUE unused) {
3362
3410
  }
3363
3411
  inf->closed = 0;
3364
3412
  inf->finished = 0;
3413
+ inf->stream_open = 0;
3414
+ inf->lz4_ended = 0;
3365
3415
  inf->total_output = 0;
3366
3416
  inf->total_input = 0;
3367
3417
  return self;
@@ -3658,7 +3708,7 @@ static VALUE dict_size(VALUE self) {
3658
3708
  return SIZET2NUM(d->size);
3659
3709
  }
3660
3710
 
3661
- void Init_multi_compress(void) {
3711
+ RUBY_FUNC_EXPORTED void Init_multi_compress(void) {
3662
3712
  binary_encoding = rb_ascii8bit_encoding();
3663
3713
  init_id_cache();
3664
3714
  crc32_init_tables();
@@ -1,3 +1,3 @@
1
- zstd=1.5.7
1
+ zstd=1.6.0
2
2
  lz4=1.10.0
3
3
  brotli=1.2.1
@@ -32,7 +32,6 @@ cxx_library(
32
32
  srcs=glob(['decompress/zstd*.c']),
33
33
  deps=[
34
34
  ':common',
35
- ':legacy',
36
35
  ],
37
36
  )
38
37
 
@@ -47,6 +46,14 @@ cxx_library(
47
46
  deps=[':common'],
48
47
  )
49
48
 
49
+ # Decoders for formats older than v0.8. Not a dependency of :decompress,
50
+ # because ZSTD_LEGACY_SUPPORT is 0 (see .buckconfig), which makes them
51
+ # unreachable.
52
+ # Enabling legacy formats means two edits, which only make sense together :
53
+ # raise the level in .buckconfig, AND add ':legacy' to :decompress deps.
54
+ # Raising the level alone fails to link, which is easy to notice. Adding the
55
+ # dep alone is silent : these decoders get compiled back in, while
56
+ # ZSTD_isLegacy() remains compiled out, so legacy frames are still rejected.
50
57
  cxx_library(
51
58
  name='legacy',
52
59
  header_namespace='',
@@ -56,9 +63,6 @@ cxx_library(
56
63
  ]),
57
64
  srcs=glob(['legacy/*.c']),
58
65
  deps=[':common'],
59
- exported_preprocessor_flags=[
60
- '-DZSTD_LEGACY_SUPPORT=4',
61
- ],
62
66
  )
63
67
 
64
68
  cxx_library(
@@ -79,6 +83,7 @@ cxx_library(
79
83
  header_namespace='',
80
84
  visibility=['PUBLIC'],
81
85
  exported_headers=subdir_glob([
86
+ ('common', 'bmi2.h'),
82
87
  ('common', 'compiler.h'),
83
88
  ]),
84
89
  )
@@ -132,7 +137,7 @@ cxx_library(
132
137
  exported_headers=[
133
138
  'zstd_errors.h',
134
139
  'common/error_private.h',
135
- ]
140
+ ],
136
141
  srcs=['common/error_private.c'],
137
142
  )
138
143
 
@@ -7,15 +7,30 @@ in order to make it easier to select or exclude features.
7
7
 
8
8
  #### Building
9
9
 
10
- `Makefile` script is provided, supporting [Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html#Makefile-Conventions),
10
+ A `Makefile` script is provided, supporting [Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html#Makefile-Conventions),
11
11
  including commands variables, staged install, directory variables and standard targets.
12
12
  - `make` : generates both static and dynamic libraries
13
- - `make install` : install libraries and headers in target system directories
13
+ - `make install` : install libraries, headers and pkg-config in local system directories
14
14
 
15
- `libzstd` default scope is pretty large, including compression, decompression, dictionary builder,
16
- and support for decoding legacy formats >= v0.5.0.
15
+ `libzstd` default scope includes compression, decompression, and dictionary builder.
16
+ Note: starting v1.6.0, support for decoding legacy formats is disabled by default.
17
+ See _modular build_ below to learn how to enable it.
17
18
  The scope can be reduced on demand (see paragraph _modular build_).
18
19
 
20
+ #### Multiarch Support
21
+
22
+ For multiarch systems (like Debian/Ubuntu), libraries should be installed to architecture-specific directories.
23
+ When creating packages for such systems, use the `LIBDIR` variable to specify the correct multiarch path:
24
+
25
+ ```bash
26
+ # For x86_64 systems on Ubuntu/Debian:
27
+ make install PREFIX=/usr LIBDIR=/usr/lib/x86_64-linux-gnu
28
+
29
+ # For ARM64 systems on Ubuntu/Debian:
30
+ make install PREFIX=/usr LIBDIR=/usr/lib/aarch64-linux-gnu
31
+ ```
32
+
33
+ This will not only install the files in the correct directories, but also generate the correct paths for `pkg-config`.
19
34
 
20
35
  #### Multithreading support
21
36
 
@@ -85,7 +100,7 @@ The file structure is designed to make this selection manually achievable for an
85
100
  Specifying a number limits versions supported to that version onward.
86
101
  For example, `ZSTD_LEGACY_SUPPORT=2` means : "support legacy formats >= v0.2.0".
87
102
  Conversely, `ZSTD_LEGACY_SUPPORT=0` means "do __not__ support legacy formats".
88
- By default, this build macro is set as `ZSTD_LEGACY_SUPPORT=5`.
103
+ By default, this build macro is set as `ZSTD_LEGACY_SUPPORT=0` (disabled).
89
104
  Decoding supported legacy format is a transparent capability triggered within decompression functions.
90
105
  It's also allowed to invoke legacy API directly, exposed in `lib/legacy/zstd_legacy.h`.
91
106
  Each version does also provide its own set of advanced API.
@@ -193,6 +208,11 @@ The file structure is designed to make this selection manually achievable for an
193
208
  and assembly decoding loops. You may want to use this macro if these loops are
194
209
  slower on your platform.
195
210
 
211
+ - The macro `ZDICT_QSORT` can enforce selection of a specific sorting variant,
212
+ which is useful when autodetection fails, for example with older versions of `musl`.
213
+ For this scenario, it can be set as `ZDICT_QSORT=ZDICT_QSORT_C90`.
214
+ Other selectable suffixes are `_GNU`, `_APPLE`, `_MSVC` and `_C11`.
215
+
196
216
  #### Windows : using MinGW+MSYS to create DLL
197
217
 
198
218
  DLL can be created using MinGW+MSYS with the `make libzstd` command.
@@ -33,9 +33,13 @@ MEM_STATIC void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem)
33
33
  MEM_STATIC void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem)
34
34
  {
35
35
  if (customMem.customAlloc) {
36
- /* calloc implemented as malloc+memset;
37
- * not as efficient as calloc, but next best guess for custom malloc */
36
+ /* calloc implemented as malloc+memset */
38
37
  void* const ptr = customMem.customAlloc(customMem.opaque, size);
38
+
39
+ if (ptr == NULL) {
40
+ return NULL;
41
+ }
42
+
39
43
  ZSTD_memset(ptr, 0, size);
40
44
  return ptr;
41
45
  }
@@ -21,7 +21,7 @@ MEM_STATIC unsigned ZSTD_countTrailingZeros32_fallback(U32 val)
21
21
  30, 22, 20, 15, 25, 17, 4, 8,
22
22
  31, 27, 13, 23, 21, 19, 16, 7,
23
23
  26, 12, 18, 6, 11, 5, 10, 9};
24
- return DeBruijnBytePos[((U32) ((val & -(S32) val) * 0x077CB531U)) >> 27];
24
+ return DeBruijnBytePos[((U32) ((val & (0-val)) * 0x077CB531U)) >> 27];
25
25
  }
26
26
  }
27
27
 
@@ -102,8 +102,8 @@ typedef enum { BIT_DStream_unfinished = 0, /* fully refilled */
102
102
  } BIT_DStream_status; /* result of BIT_reloadDStream() */
103
103
 
104
104
  MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
105
- MEM_STATIC BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
106
- MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
105
+ FORCE_INLINE_TEMPLATE BitContainerType BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
106
+ FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
107
107
  MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
108
108
 
109
109
 
@@ -432,7 +432,7 @@ FORCE_INLINE_TEMPLATE BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
432
432
  /* start < ptr < limitPtr => cautious update */
433
433
  { U32 nbBytes = bitD->bitsConsumed >> 3;
434
434
  BIT_DStream_status result = BIT_DStream_unfinished;
435
- if (bitD->ptr - nbBytes < bitD->start) {
435
+ if (nbBytes > (size_t)(bitD->ptr - bitD->start)) {
436
436
  nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
437
437
  result = BIT_DStream_endOfBuffer;
438
438
  }
@@ -0,0 +1,40 @@
1
+ /*
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under both the BSD-style license (found in the
6
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7
+ * in the COPYING file in the root directory of this source tree).
8
+ * You may select, at your option, one of the above-listed licenses.
9
+ */
10
+
11
+ #ifndef ZSTD_BMI2_H
12
+ #define ZSTD_BMI2_H
13
+
14
+ #include "portability_macros.h"
15
+
16
+ #if defined(ZSTD_USE_KERNEL_CPU_FEATURES)
17
+ # include <asm/cpufeature.h>
18
+ #endif
19
+
20
+ /*
21
+ * Select between the BMI2 and default implementations at the final dispatch
22
+ * site. Integrations may ignore the caller-provided hint and consult their own
23
+ * CPU-feature policy instead.
24
+ *
25
+ * ZSTD_USE_BMI2() may not evaluate its argument. ZSTD_SET_BMI2() may not
26
+ * evaluate its value argument, which avoids executing the userspace CPUID
27
+ * probe when the integration supplies the dispatch decision.
28
+ */
29
+ #if !DYNAMIC_BMI2
30
+ # define ZSTD_USE_BMI2(bmi2) 0
31
+ # define ZSTD_SET_BMI2(state, value) do { } while (0)
32
+ #elif defined(ZSTD_USE_KERNEL_CPU_FEATURES)
33
+ # define ZSTD_USE_BMI2(bmi2) cpu_feature_enabled(X86_FEATURE_BMI2)
34
+ # define ZSTD_SET_BMI2(state, value) do { (state) = 0; } while (0)
35
+ #else
36
+ # define ZSTD_USE_BMI2(bmi2) (bmi2)
37
+ # define ZSTD_SET_BMI2(state, value) do { (state) = (value); } while (0)
38
+ #endif
39
+
40
+ #endif /* ZSTD_BMI2_H */