Enable C# 15 memory safety rules and annotate unsafe code
Merged
BR
18d ago+1037+1037+0123456789012345678901234567890123456789-503-503-012345678901234567890123456789
Summary
Enables the C# 15 preview memory safety rules (updated-memory-safety-rules) and annotates all unsafe code in Snappier so the compiler enforces where safety obligations are taken on and discharged.
Changes
- Build
LangVersionispreview, and theupdated-memory-safety-rulesfeature is on.AllowUnsafeBlocksis set, and anet11.0target is added to Snappier so the .NET 11 BCL's requires-unsafe APIs (Unsafe.*,MemoryMarshal.*,Vector128.LoadUnsafe/StoreUnsafe) are checked.- CI runs the test matrix on
net11.0as well.
- Contracts: each member that passes a safety obligation to its callers is marked
unsafeand documents the obligation in a/// <safety>comment. - Narrow unsafe regions: unsafe blocks and
unsafe(expr)expressions cover only the operations that need them.- Each has exactly one
// SAFETY:comment saying why the obligation holds at that point. - A blank line precedes each new
unsafeblock unless the line before is{or a comment.
- Each has exactly one
UnsafeReadonly:ByteOffset,IsAddressGreaterThanandIsAddressLessThanstay safe because they only compare addresses, as in the .NET 11 BCL. The other helpers forward theUnsafecontract and document it.- Benchmarks and tests were updated where they call members that are now requires-unsafe.
Notes for reviewers
- Rebased onto #156. The safety comments in
SnappyDecompressorreflect its two changes:- Output is now bounded by
ExpectedLength. - A long literal length that overflowed
ninton 32-bit platforms is now rejected, so every length passed toAppendis non-negative.
- Output is now bounded by
- Known limitations are documented in the contracts, not fixed. These are existing behaviors, not regressions:
UnalignedCopy64/UnalignedCopy128andUnsafeReadonly.Asuse typed loads that may fault on misaligned addresses on ARM32.- Some references computed only for comparison (
bufferEnd - N,nextIp) can point outside their buffer on short inputs. The runtime doesn't formally allow that even for comparisons. - When
RefillTagcopies within scratch, the source and destination can overlap.
- Preview dependency: this relies on a C# preview feature, so the annotation syntax may change before it ships.
Testing
- The Release build of
Snappier.slnxhas 0 warnings and 0 errors. dotnet test --project Snappier.Tests: 1,544 passed, 0 failed.
š¤ Generated with Claude Code