Skip to content

Bounds-check NetDataReader Peek methods - #618

Merged
RevenantX merged 1 commit into
RevenantX:masterfrom
armadavalor:fix/peek-bounds-check
Oct 26, 2026
Merged

RevenantX merged 1 commit into
RevenantX:masterfrom
armadavalor:fix/peek-bounds-check

Conversation

@armadavalor

Copy link
Copy Markdown
Contributor

After the NetDataReader rework, the Get* methods call EnsureAvailable, but the Peek* ones do not:

  • PeekUnmanaged<T> (so PeekInt, PeekLong, etc.) reads sizeof(T) bytes with Unsafe.ReadUnaligned / a raw pointer. On a 2-byte buffer, PeekInt() reads past the end of the array instead of throwing.
  • PeekByte, PeekString and PeekString(int) only check against the array length, not _dataSize. A reader over a NetDataWriter whose backing array is larger than the data returns garbage. For example, a truncated string returns a run of null characters.
  • In the UNITY_ANDROID branch, PeekUnmanaged uses size, which is never declared. That branch fails with CS0103. I checked this by compiling with UNITY_ANDROID defined and a stub UnsafeUtility.

The fix adds EnsureAvailable to PeekByte, PeekUnmanaged (which also declares size) and both PeekString overloads. Peeking past the end now throws InvalidOperationException, the same as the matching Get* call.

There are two new tests in ReaderWriterSimpleDataTest. I only have the .NET 7 SDK, so I could not run the net8/net9 test project. I built the library for netstandard2.1 and ran the same assertions from a net7 console. Before the fix, 7 assertions fail; after it, all pass.

PeekByte, PeekString and PeekUnmanaged did not check against the data size,
so peeking near the end returned bytes past the packet (or past the array
via the unsafe read). PeekUnmanaged also referenced an undefined 'size' in
the UNITY_ANDROID branch, which broke that build.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants