zlib: properly clamp to uLong

On platforms where `unsigned long` and `size_t` differ in bit size, we want to clamp the buffers we pass to zlib to the former's size, as per d05d666977 (git-zlib: handle data streams larger than 4GB, 2026-05-08). The logic introduced in that commit performs a clamping to the bits, though, which fails to do what is needed here: If too many bytes are available in the buffers, we need to clamp to the maximum value of an `unsigned long`. Otherwise, we ask zlib to use too small buffers, in the worst case using 0 as the size (think: a value whose 32 lowest bits are all zero). Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Jun 18, 2026 at 13:50 UTC ab3810eb6fffd95d39e9579945e360e8247eeda8
1 file changed +9 -4
git-zlib.c
+9 -4
@@ -38,12 +38,17 @@ static inline uInt zlib_buf_cap(unsigned long len)
38 return (ZLIB_BUF_MAX < len) ? ZLIB_BUF_MAX : len;
39 }
40
41 +static inline uLong zlib_uLong_cap(size_t s)
42 +{
43 + return s < ULONG_MAX_VALUE ? (uLong)s : ULONG_MAX_VALUE;
44 +}
45 +
46 static void zlib_pre_call(git_zstream *s)
47 {
48 s->z.next_in = s->next_in;
49 s->z.next_out = s->next_out;
45 - s->z.total_in = (uLong)(s->total_in & ULONG_MAX_VALUE);
46 - s->z.total_out = (uLong)(s->total_out & ULONG_MAX_VALUE);
50 + s->z.total_in = zlib_uLong_cap(s->total_in);
51 + s->z.total_out = zlib_uLong_cap(s->total_out);
52 s->z.avail_in = zlib_buf_cap(s->avail_in);
53 s->z.avail_out = zlib_buf_cap(s->avail_out);
54 }
@@ -60,7 +65,7 @@ static void zlib_post_call(git_zstream *s, int status)
65 * We track our own totals and verify only the low bits match.
66 */
67 if ((s->z.total_out & ULONG_MAX_VALUE) !=
63 - ((s->total_out + bytes_produced) & ULONG_MAX_VALUE))
68 + ((zlib_uLong_cap(s->total_out) + bytes_produced) & ULONG_MAX_VALUE))
69 BUG("total_out mismatch");
70 /*
71 * zlib does not update total_in when it returns Z_NEED_DICT,
@@ -68,7 +73,7 @@ static void zlib_post_call(git_zstream *s, int status)
73 */
74 if (status != Z_NEED_DICT &&
75 (s->z.total_in & ULONG_MAX_VALUE) !=
71 - ((s->total_in + bytes_consumed) & ULONG_MAX_VALUE))
76 + ((zlib_uLong_cap(s->total_in) + bytes_consumed) & ULONG_MAX_VALUE))
77 BUG("total_in mismatch");
78
79 s->total_out += bytes_produced;