From 35e124832e29b65c84d4e0e4e434616859f9bdf5 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Mon, 30 Sep 2024 22:49:09 +0900 Subject: [PATCH] [Bug #20755] Frozen string should not be writable via IO::Buffer --- io_buffer.c | 3 ++- test/ruby/test_io_buffer.rb | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/io_buffer.c b/io_buffer.c index 2e789abe0f..cc76f12ecc 100644 --- a/io_buffer.c +++ b/io_buffer.c @@ -843,7 +843,8 @@ rb_io_buffer_get_bytes(VALUE self, void **base, size_t *size) static inline void io_buffer_get_bytes_for_writing(struct rb_io_buffer *buffer, void **base, size_t *size) { - if (buffer->flags & RB_IO_BUFFER_READONLY) { + if (buffer->flags & RB_IO_BUFFER_READONLY || + (!NIL_P(buffer->source) && OBJ_FROZEN(buffer->source))) { rb_raise(rb_eIOBufferAccessError, "Buffer is not writable!"); } diff --git a/test/ruby/test_io_buffer.rb b/test/ruby/test_io_buffer.rb index 7087a2b957..98cf45d0c3 100644 --- a/test/ruby/test_io_buffer.rb +++ b/test/ruby/test_io_buffer.rb @@ -248,6 +248,31 @@ class TestIOBuffer < Test::Unit::TestCase assert_equal "Hello World", hello end + def test_transfer + hello = %w"Hello World".join(" ") + buffer = IO::Buffer.for(hello) + transferred = buffer.transfer + assert_equal "Hello World", transferred.get_string + assert_predicate buffer, :null? + assert_raise IO::Buffer::AccessError do + transferred.set_string("Goodbye") + end + assert_equal "Hello World", hello + end + + def test_transfer_in_block + hello = %w"Hello World".join(" ") + buffer = IO::Buffer.for(hello, &:transfer) + assert_equal "Hello World", buffer.get_string + buffer.set_string("Ciao!") + assert_equal "Ciao! World", hello + hello.freeze + assert_raise IO::Buffer::AccessError do + buffer.set_string("Hola") + end + assert_equal "Ciao! World", hello + end + def test_locked buffer = IO::Buffer.new(128, IO::Buffer::INTERNAL|IO::Buffer::LOCKED)