Skip to content

Commit cedbd74

Browse files
authored
Merge pull request #190 from aristocratte/fix-gzipreader-outbuf-shared
Do not write through a shared buffer in GzipReader#read and #readpartial
2 parents 505a222 + 144466a commit cedbd74

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

‎ext/zlib/zlib.c‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -855,6 +855,9 @@ zstream_shift_buffer(struct zstream *z, rb_len_t len, VALUE dst)
855855
} else {
856856
bufptr = RSTRING_PTR(z->buf);
857857
rb_str_resize(dst, buflen);
858+
/* dst may still share its memory with other strings, and
859+
* its coderange describes the old contents */
860+
rb_str_modify(dst);
858861
memcpy(RSTRING_PTR(dst), bufptr, buflen);
859862
}
860863
buflen = 0;
@@ -864,6 +867,7 @@ zstream_shift_buffer(struct zstream *z, rb_len_t len, VALUE dst)
864867
dst = rb_str_new(bufptr, len);
865868
} else {
866869
rb_str_resize(dst, len);
870+
rb_str_modify(dst);
867871
memcpy(RSTRING_PTR(dst), bufptr, len);
868872
}
869873
buflen -= len;

‎test/zlib/test_zlib.rb‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,6 +1520,41 @@ def test_readpartial
15201520
}
15211521
end
15221522

1523+
def test_outbuf_shared
1524+
# A copy of a long string shares its memory with the original
1525+
# until one of them is modified. Reading into the buffer again
1526+
# must not write through that shared memory.
1527+
a = "A" * 1000
1528+
b = "B" * 1000
1529+
gz = Zlib.gzip(a + b)
1530+
%i[read readpartial].each do |m|
1531+
Zlib::GzipReader.wrap(StringIO.new(gz)) do |f|
1532+
buf = "".dup
1533+
copy = f.__send__(m, 1000, buf).dup
1534+
frozen = copy.dup.freeze
1535+
key = {buf => true}.keys.first
1536+
assert_same buf, f.__send__(m, 1000, buf)
1537+
assert_equal b, buf, m
1538+
assert_equal a, copy, m
1539+
assert_equal a, frozen, m
1540+
assert_equal a, key, m
1541+
end
1542+
end
1543+
end
1544+
1545+
def test_outbuf_coderange
1546+
gz = Zlib.gzip("\xFF".b * 10)
1547+
%i[read readpartial].each do |m|
1548+
Zlib::GzipReader.wrap(StringIO.new(gz)) do |f|
1549+
buf = "".dup
1550+
assert_predicate buf, :ascii_only?
1551+
f.__send__(m, 10, buf)
1552+
assert_equal "\xFF".b * 10, buf.b, m
1553+
assert_not_predicate buf, :ascii_only?, m
1554+
end
1555+
end
1556+
end
1557+
15231558
def test_getc
15241559
Tempfile.create("test_zlib_gzip_reader_getc") {|t|
15251560
t.close

0 commit comments

Comments
 (0)