From 6ce0472ec0d857bb5a3615574580f631f29a4931 Mon Sep 17 00:00:00 2001 From: Zahary Karadjov Date: Wed, 15 Apr 2020 00:10:56 +0300 Subject: [PATCH] Prevent a mysterious crash in NBC --- faststreams/input_stream.nim | 13 ++++++++++++- faststreams/output_stream.nim | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/faststreams/input_stream.nim b/faststreams/input_stream.nim index 81236ff..1278c65 100644 --- a/faststreams/input_stream.nim +++ b/faststreams/input_stream.nim @@ -59,6 +59,11 @@ proc close*(s: var InputStream) {.raises: [IOError, Defect].} = s.vtable.closeSync(s) s = nil +proc preventFurtherReading(s: InputStream) = + s.vtable = nil + s.head = nil + s.bufferEnd = nil + proc `=destroy`*(h: var InputStreamHandle) {.raises: [Defect].} = if h.s != nil: if h.s.vtable != nil and h.s.vtable.closeSync != nil: @@ -69,7 +74,13 @@ proc `=destroy`*(h: var InputStreamHandle) {.raises: [Defect].} = # If the user wanted to handle the error, they would have called # `close` manually. discard # TODO - h.s = nil + # TODO ATTENTION! + # Uncommenting the following line will lead to a GC heap corruption. + # Most likely this leads to Nim collecting some object prematurely. + # h.s = nil + # We work-around the problem through more indirect incapacitatation + # of the stream object: + h.s.preventFurtherReading() converter implicitDeref*(h: InputStreamHandle): InputStream = h.s diff --git a/faststreams/output_stream.nim b/faststreams/output_stream.nim index 94de7f2..4b30438 100644 --- a/faststreams/output_stream.nim +++ b/faststreams/output_stream.nim @@ -114,11 +114,13 @@ proc flipPage(s: OutputStream) = s.endPos += s.pageSize proc addPage(s: OutputStream) = + doAssert s.pageSize > 0 s.pages.addLast OutputPage(buffer: newString(s.pageSize), startOffset: 0) s.flipPage proc initWithSinglePage*(s: OutputStream) = + s.pages = initDeque[OutputPage]() s.addPage() s.cursor.stream = s