avoid UB writing nothing to outputs (#45)

* avoid UB writing nothing to outputs

* remove finalWrite version

* reference Nim issue
This commit is contained in:
tersec 2023-06-24 15:35:55 +02:00 committed by GitHub
parent f63bffa391
commit d78b9dcd68
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 0 deletions

View File

@ -737,6 +737,21 @@ when fsAsyncSupport:
writeAndWait(sp, memCopyToBytes(value))
proc writeBytesToCursor(c: var WriteCursor, bytes: openArray[byte]) =
# https://github.com/nim-lang/Nim/issues/22149
#
# Nim represents a zero-length openArray as a (NULL, 0) base+length tuple.
#
# https://gcc.gnu.org/gcc-4.9/porting_to.html
# "The pointers passed to memmove (and similar functions in <string.h>) must
# be non-null even when nbytes==0, so GCC can use that information to remove
# the check after the memmove call."
#
# https://en.cppreference.com/w/cpp/string/byte/memcpy
# "If either dest or src is an invalid or null pointer, the behavior is
# undefined, even if count is zero."
if bytes.len == 0:
return
var
runway = c.span.len
inputPos = baseAddr(bytes)
@ -788,6 +803,10 @@ proc finalWrite*(cursor: var WriteCursor, data: openArray[byte]) =
finalize cursor
proc finalWrite*(c: var VarSizeWriteCursor, data: openArray[byte]) =
# TODO ensure adding early-return for zero-length input is safe, or if not,
# what is. It can't make it all the way to copyMem, though, regardless, and
# remain non-UB.
template cursor: auto = WriteCursor(c)
let overestimatedBytes = cursor.span.len - data.len