Fix possible memory confusion in unsafe slice cast #204
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description:
I found an incorrect cast from
string
to[]byte
inbytes_unsafe.go
. The problem is that whenreflect.SliceHeader
is created as a composite literal (instead of deriving it from an actual slice by cast), then the Go garbage collector will not treat itsData
field as a reference. If the GC runs just between creating theSliceHeader
and casting it into the final, real[]byte
slice, then the underlying data might have been collected already, effectively making the returned[]byte
slice a dangling pointer.This has a low probability to occur, but projects that import this library might still use it in a code path that gets executed a lot, thus increasing the probability to happen. Depending on the memory layout at the time of the GC run, this could potentially create an information leak vulnerability.
This PR changes the function to create the
reflect.SliceHeader
from an actual slice by first instantiating the return value.Benchmark before change: n/a
Benchmark after change: n/a
For running benchmarks use:
Both failed for me, therefore I skipped running the benchmark, sorry about that!