Prevent a mysterious crash in NBC

This commit is contained in:
Zahary Karadjov 2020-04-15 00:10:56 +03:00
commit 6ce0472ec0
No known key found for this signature in database
GPG key ID: C8936F8A3073D609
2 changed files with 14 additions and 1 deletions

View file

@ -59,6 +59,11 @@ proc close*(s: var InputStream) {.raises: [IOError, Defect].} =
s.vtable.closeSync(s) s.vtable.closeSync(s)
s = nil s = nil
proc preventFurtherReading(s: InputStream) =
s.vtable = nil
s.head = nil
s.bufferEnd = nil
proc `=destroy`*(h: var InputStreamHandle) {.raises: [Defect].} = proc `=destroy`*(h: var InputStreamHandle) {.raises: [Defect].} =
if h.s != nil: if h.s != nil:
if h.s.vtable != nil and h.s.vtable.closeSync != 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 # If the user wanted to handle the error, they would have called
# `close` manually. # `close` manually.
discard # TODO 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 = converter implicitDeref*(h: InputStreamHandle): InputStream =
h.s h.s

View file

@ -114,11 +114,13 @@ proc flipPage(s: OutputStream) =
s.endPos += s.pageSize s.endPos += s.pageSize
proc addPage(s: OutputStream) = proc addPage(s: OutputStream) =
doAssert s.pageSize > 0
s.pages.addLast OutputPage(buffer: newString(s.pageSize), s.pages.addLast OutputPage(buffer: newString(s.pageSize),
startOffset: 0) startOffset: 0)
s.flipPage s.flipPage
proc initWithSinglePage*(s: OutputStream) = proc initWithSinglePage*(s: OutputStream) =
s.pages = initDeque[OutputPage]()
s.addPage() s.addPage()
s.cursor.stream = s s.cursor.stream = s