Skip to content

fix: prevent signed integer overflow in gzseek64 for SEEK_SET#1227

Open
SongTonyLi wants to merge 1 commit into
madler:developfrom
SongTonyLi:fix/issue-1222-gzseek64-overflow
Open

fix: prevent signed integer overflow in gzseek64 for SEEK_SET#1227
SongTonyLi wants to merge 1 commit into
madler:developfrom
SongTonyLi:fix/issue-1222-gzseek64-overflow

Conversation

@SongTonyLi
Copy link
Copy Markdown

@SongTonyLi SongTonyLi commented May 2, 2026

Summary

Fixes #1222. Generally agree with the issue's suggested fix, and I independently verified the patch's validity.

gzseek64() unconditionally subtracts state->x.pos from the user-supplied offset when whence == SEEK_SET. If offset is INT64_MIN and the stream position is non-zero, this overflows the signed z_off64_t type — undefined behavior flagged by UBSan.

Since a negative absolute position is always invalid for SEEK_SET, this patch rejects it early (returns -1) before the subtraction, eliminating the overflow without changing observable semantics.

Fix

Add if (offset < 0) return -1; guard inside the SEEK_SET branch, before offset -= state->x.pos.

Verification

Tested with UBSan-instrumented build:

  • Before: gzlib.c:389:16: runtime error: signed integer overflow: -9223372036854775808 - 1 cannot be represented in type 'off64_t'
  • After: No UBSan findings; clean exit

Reproducer:

gzFile gz = gzopen("any_file", "rb");
char buf[2]; gzread(gz, buf, 2);  // advance pos to 1
gzseek(gz, LONG_MIN, SEEK_SET);   // triggers overflow without fix
gzclose(gz);

Reject negative offsets early in the SEEK_SET branch of gzseek64()
before subtracting state->x.pos. Previously, passing INT64_MIN as
the offset with a non-zero stream position caused undefined behavior
via signed overflow (offset -= state->x.pos overflows z_off64_t).

Negative absolute positions are always invalid for SEEK_SET, so
returning -1 immediately is both safe and semantically correct.

Fixes madler#1222
@SongTonyLi SongTonyLi marked this pull request as ready for review May 2, 2026 02:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Signed Integer Overflow in gzseek64 when Normalizing a SEEK_SET Offset

1 participant