[C#] Fix repeated group buffer overflow by j4b6ski · Pull Request #823 · aeron-io/simple-binary-encoding (original) (raw)

This actually broke code I was working on in a very nasty way when the buffer size was too small - I was trying to use the DirectBuffer's bufferOverflow delegate and some bytes were getting eaten when expanding the buffer.

Explanation in the commit msg:

On a repeated group in the WrapForEncode, the parentMessage.Limit has two purposes:

  1. It is used as a buffer offset for the _dimensions helper Wrap method
  2. The assignment to it has a side effect of checking that we do not exceed the underlying DirectBuffer's capacity

However notice that currently this assignment happens after writing to the _dimensions helper properties BlockLength and NumInGroup,
i.e. the writes are done before we check for buffer overflow.
Underneath these are direct writes to the byte* managed by the DirectBuffer, resulting in an unchecked, unsafe buffer overflow.
To fix this the Limit has to be increased right after the call to the _dimensions.Wrap, before writes to BlockLength and NumInGroup

The same occurs in the Decode method, only reading unsafe, invalid memory instead of writing to it.
Also fixed _actingVersion was being used before it's assigned in the Encode