Skip to content

Commit 6efa784

Browse files
committed
Fixed potential access violation with faulty MemoryManager<T>-s
1 parent 045aeb7 commit 6efa784

File tree

2 files changed

+7
-9
lines changed

2 files changed

+7
-9
lines changed

Microsoft.Toolkit.HighPerformance/Streams/Sources/ArrayOwner.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44

55
using System;
66
using System.Runtime.CompilerServices;
7+
#if SPAN_RUNTIME_SUPPORT
78
using System.Runtime.InteropServices;
89
using Microsoft.Toolkit.HighPerformance.Extensions;
10+
#endif
911

1012
namespace Microsoft.Toolkit.HighPerformance.Streams
1113
{

Microsoft.Toolkit.HighPerformance/Streams/Sources/MemoryManagerOwner.cs

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
using System;
66
using System.Buffers;
77
using System.Runtime.CompilerServices;
8-
using System.Runtime.InteropServices;
9-
using Microsoft.Toolkit.HighPerformance.Extensions;
108

119
namespace Microsoft.Toolkit.HighPerformance.Streams
1210
{
@@ -56,13 +54,11 @@ public Span<byte> Span
5654
[MethodImpl(MethodImplOptions.AggressiveInlining)]
5755
get
5856
{
59-
#if SPAN_RUNTIME_SUPPORT
60-
ref byte r0 = ref this.memoryManager.GetSpan().DangerousGetReferenceAt(this.offset);
61-
62-
return MemoryMarshal.CreateSpan(ref r0, this.length);
63-
#else
64-
return this.memoryManager.GetSpan();
65-
#endif
57+
// We can't use the same trick we use for arrays to optimize the creation of
58+
// the offset span, as otherwise a bugged MemoryManager<T> instance returning
59+
// a span of an incorrect size could cause an access violation. Instead, we just
60+
// get the span and then slice it, which will validate both offset and length.
61+
return this.memoryManager.GetSpan().Slice(this.offset, this.length);
6662
}
6763
}
6864
}

0 commit comments

Comments
 (0)