diff --git a/ext/zlib/zlib.c b/ext/zlib/zlib.c index e279bb9..7143b3e 100644 --- a/ext/zlib/zlib.c +++ b/ext/zlib/zlib.c @@ -1063,9 +1063,6 @@ static VALUE zstream_run_once_begin(VALUE _arguments) { struct zstream_run_args *arguments = (struct zstream_run_args *)_arguments; - struct zstream *z = arguments->z; - - rb_str_locktmp(z->buf); #ifndef RB_NOGVL_UBF_ASYNC_SAFE return (VALUE)rb_thread_call_without_gvl(zstream_run_once, (void *)arguments, zstream_unblock_func, (void *)arguments); @@ -1096,6 +1093,15 @@ zstream_run_func(struct zstream_run_args *args) while (!args->interrupt) { n = z->stream.avail_out; + /* lock outside rb_ensure, so that a lock held by someone else is not + released when rb_str_locktmp fails, and raise the failure after + zstream_run_try has put back the pending input */ + rb_protect(rb_str_locktmp, z->buf, &state); + if (state) { + err = Z_OK; + args->jump_state = state; + break; + } err = (int)(VALUE)rb_ensure(zstream_run_once_begin, (VALUE)args, zstream_run_once_ensure, (VALUE)args); rb_str_set_len(z->buf, ZSTREAM_BUF_FILLED(z) + (n - z->stream.avail_out)); diff --git a/test/zlib/test_zlib.rb b/test/zlib/test_zlib.rb index afe9529..470dbf0 100644 --- a/test/zlib/test_zlib.rb +++ b/test/zlib/test_zlib.rb @@ -623,6 +623,35 @@ def test_inflate_buffer_modified_while_handling_need_dict assert_equal "A" * 12_000, z.inflate("", buffer: buf) end + def test_inflate_buffer_locked_by_another_thread + omit 'IO#read does not lock the buffer' if RUBY_ENGINE == 'truffleruby' + + dict = "dictionary-" * 4 + d = Zlib::Deflate.new + d.set_dictionary(dict) + deflated = d.deflate("A" * 12_000, Zlib::FINISH) + + # The buffer is kept across NeedDict, so the retry locks it without + # modifying it first. It is long enough that the first call keeps its + # capacity, and it gets a few bytes so that IO#read up to Ruby 3.1 + # does not resize it. + z = Zlib::Inflate.new + buf = "\0".b * (1 << 15) + assert_raise(Zlib::NeedDict) { z.inflate(deflated, buffer: buf) } + z.set_dictionary(dict) + buf << "...." + + IO.pipe do |r, w| + reader = Thread.new { r.read(3, buf) } + Thread.pass until reader.stop? + assert_raise(RuntimeError) { z.inflate("", buffer: buf) } + w.write("foo") + assert_equal "foo", reader.value + end + buf.clear + assert_equal "A" * 12_000, z.inflate("", buffer: buf) + end + def test_inflate_chunked_break # zeros = Zlib::Deflate.deflate("0" * 100_000) zeros = "x\234\355\3011\001\000\000\000\302\240J\353\237\316\032\036@" \