From 09ff41d82cbc75cdb07b61bb3c35bfa07f897a8d Mon Sep 17 00:00:00 2001 From: Kaz Kylheku Date: Mon, 6 Jun 2022 07:07:51 -0700 Subject: string-out-stream: gc issue. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The problem being addressed here showed up for me when compiling with either gcc-7 or gcc-11 on Ubuntu 18, using -fsanitize-undefined. A few test test cases run under --gc-debug were crashing. I narrowed it down to this small test case, whose correct output would be "1": ./txr --gc-debug -p '(sys:fmt-simple 1 : : : :)' "\x6700ACB0缻\x6700ACB0缻 " The issue doesn't have anything to do with -fsanitize-undefined; that just how it got reproduced by chance. I'm reasonably certain that in builds for which "make tests" passes, and the above test case doesn't repro, this issue is absent: the code got generated in such a way that it the string_own call doesn't cause the stream object to be reclaimed. * stream.c (get_string_from_stream): change the order of operations in the ownership transfer of the string from the stream to the returned string object. We capture the string in a local variable, and null out so->buf before calling string_own. The problem is that get_string_from_stream is called in a way where the caller no longer has any use for the stream, and so the object is no longer live. It's possible for the string_own call to cause the stream object to be garbage collected. Therefore, the object must not still be hanging on to the wchar_t * string, which was already transferred to the string object. --- stream.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/stream.c b/stream.c index ca03cb7e..0b75c65a 100644 --- a/stream.c +++ b/stream.c @@ -2411,6 +2411,7 @@ val get_string_from_stream(val stream) if (stream->co.ops == &string_out_ops.cobj_ops) { val out = nil; + wchar_t *buf; if (!so->buf) return out; @@ -2419,10 +2420,10 @@ val get_string_from_stream(val stream) out = string_out_byte_flush(so, stream); /* Trim to actual size */ - so->buf = coerce(wchar_t *, chk_realloc(coerce(mem_t *, so->buf), - (so->fill + 1) * sizeof *so->buf)); - out = string_own(so->buf); + buf = coerce(wchar_t *, chk_realloc(coerce(mem_t *, so->buf), + (so->fill + 1) * sizeof *so->buf)); so->buf = 0; + out = string_own(buf); return out; } else { type_assert (stream->co.ops == &string_in_ops.cobj_ops, -- cgit v1.2.3