Skip to content

Commit 5e9de79

Browse files
mameclaude
andcommitted
Raise InProgressError from GzipFile methods while the stream is running
GzipFile methods did not check ZSTREAM_IN_PROGRESS either, so another thread could close the stream or replace its buffer while zlib was running without the GVL. gz = Zlib::GzipWriter.new(StringIO.new) q = Thread::Queue.new Thread.new { q.pop; gz.close } gz.write("x") q << true gz.write(Random.bytes(10_000_000)) #=> can't modify frozen NilClass: nil (FrozenError) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d5e96c9 commit 5e9de79

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎ext/zlib/zlib.c‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3358,6 +3358,7 @@ get_gzfile(VALUE obj)
33583358
if (!ZSTREAM_IS_READY(&gz->z)) {
33593359
rb_raise(cGzError, "closed gzip stream");
33603360
}
3361+
zstream_check_not_in_progress(&gz->z);
33613362
return gz;
33623363
}
33633364

@@ -3705,6 +3706,7 @@ rb_gzfile_close(VALUE obj)
37053706
if (!ZSTREAM_IS_READY(&gz->z)) {
37063707
return Qnil;
37073708
}
3709+
zstream_check_not_in_progress(&gz->z);
37083710
io = gz->io;
37093711
gzfile_close(gz, 1);
37103712
return io;
@@ -4251,6 +4253,7 @@ rb_gzreader_unused(VALUE obj)
42514253
{
42524254
struct gzfile *gz;
42534255
TypedData_Get_Struct(obj, struct gzfile, &gzfile_data_type, gz);
4256+
zstream_check_not_in_progress(&gz->z);
42544257
return gzfile_reader_get_unused(gz);
42554258
}
42564259

‎test/zlib/test_zlib.rb‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1966,6 +1966,27 @@ def test_thread_wakeup_interrupt
19661966
end
19671967

19681968
class TestZlibGzipWriter < Test::Unit::TestCase
1969+
def test_close_while_writing_in_another_thread
1970+
gz = Zlib::GzipWriter.new(StringIO.new(+""))
1971+
s = Random.new(0).bytes(1_000_000)
1972+
q = Thread::Queue.new
1973+
th = Thread.new do
1974+
gz.write(s)
1975+
q << true
1976+
10.times { gz.write(s) }
1977+
rescue Zlib::GzipFile::Error
1978+
end
1979+
q.pop
1980+
begin
1981+
gz.close
1982+
rescue Zlib::InProgressError
1983+
Thread.pass
1984+
retry
1985+
end
1986+
th.join
1987+
assert_predicate(gz, :closed?)
1988+
end
1989+
19691990
def test_invalid_new
19701991
assert_raise(NoMethodError, "[ruby-dev:23228]") { Zlib::GzipWriter.new(nil).close }
19711992
assert_raise(NoMethodError, "[ruby-dev:23344]") { Zlib::GzipWriter.new(true).close }

0 commit comments

Comments
 (0)