runtime: AccessViolationException when calling Process.HandleCount
Description
Calling Process.HandleCount on a cached handle can cause an AccessViolationException on Linux (WSL)
Reproduction Steps
public sealed class DotNetStats
{
private readonly Process _process;
private Gauge _openHandles;
private DotNetStats(IMetricFactory metricFactory)
{
_process = Process.GetCurrentProcess();
_openHandles = metricFactory.CreateGauge("process_open_handles", "Number of open handles");
}
private readonly object _updateLock = new object();
public void UpdateMetrics()
{
try
{
lock (_updateLock)
{
_process.Refresh();
_openHandles.Set(_process.HandleCount);
}
}
catch (Exception)
{
}
}
}
Expected behavior
Calling UpdateMetrics sets the number of process handles
Actual behavior
Infrequent (about 6 hours of being called every 5 seconds)
Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.SpanHelpers.NonPackedIndexOfValueType[[System.Byte, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.SpanHelpers+DontNegate`1[[System.Byte, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](Byte ByRef, Byte, Int32)
at System.IO.Enumeration.FileSystemEntry.Initialize(System.IO.Enumeration.FileSystemEntry ByRef, DirectoryEntry, System.ReadOnlySpan`1<Char>, System.ReadOnlySpan`1<Char>, System.ReadOnlySpan`1<Char>, System.Span`1<Char>)
at System.IO.Enumeration.FileSystemEnumerator`1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
at System.Collections.Generic.List`1[[System.__Canon, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]..ctor(System.Collections.Generic.IEnumerable`1<System.__Canon>)
at System.Diagnostics.Process.EnsureHandleCountPopulated()
at Prometheus.DotNetStats.UpdateMetrics()
Regression?
Not sure as first time have run on WSL; haven’t had any issues on Windows or seen any complaints from Linux, macOS users
Known Workarounds
No workaround as AccessViolationException always bubbles through catches to crash process
Configuration
WSL on Windows 11 23H2 (OS Build 22631.4112)
.NET SDK:
Version: 8.0.108
Commit: 665a05cea7
Workload version: 8.0.100-manifests.109ff937
Runtime Environment:
OS Name: ubuntu
OS Version: 22.04
OS Platform: Linux
RID: ubuntu.22.04-x64
Base Path: /usr/lib/dotnet/sdk/8.0.108/
.NET workloads installed:
Workload version: 8.0.100-manifests.109ff937
There are no installed workloads to display.
Host:
Version: 8.0.8
Architecture: x64
Commit: 08338fcaa5
.NET SDKs installed:
8.0.108 [/usr/lib/dotnet/sdk]
.NET runtimes installed:
Microsoft.AspNetCore.App 8.0.8 [/usr/lib/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 8.0.8 [/usr/lib/dotnet/shared/Microsoft.NETCore.App]
Other information
Aside; creating all the strings for the filenames in /proc/{pid}/fd just to find the count of files doesn’t seem very efficient
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 2
- Comments: 25 (21 by maintainers)
On its own that could have high false positive rates. There’s nothing inherently wrong with using such vectorized helpers on unmanaged memory, issues only appear if you lie about the span’s length. So you could for example flag
new Span(ptr, int.MaxValue)as potentially problematic, but that wouldn’t have helped in this case.After #116639, we do not use
readdir_rnor callIndexOf<byte>(0)in file enumeration. File enumeration cannot crash with these exact symptoms anymore.In case we still see intermittent crashes during file enumeration, let’s open a new issue on it.
Yep, that’s what my guess was, which is resolvable by using
CreateReadOnlySpanFromNullTerminatedinstead which ensures that vector reads don’t cross page boundaries (or 16B). But the current logic that usesIndexOfwould only be problematic if the span length is incorrect (we’ll never read past the length). To Jan’s question, I’m not sure how that could happen yet, but should presumably be visible in a dump.@Vercidium
new Span(ptr, Int32.MaxValue).IndexOf<byte>(0)is not valid way to find the length of null terminated string. The vectorized implementation of IndexOf is free to read memory beyond the terminating null byte. This can lead to intermittent AccessViolationException like the one you are seeing.The correct way to find the length of null terminated string is using
CreateReadOnlySpanFromNullTerminatedAPI. I see that the current version of Silk.NET library uses this API: https://github.com/dotnet/Silk.NET/blob/c0dbe835702d01a9f6fe2b5b2ca34f5780d3450d/src/Core/Silk.NET.Core/Native/SilkMarshal.cs#L559 . Perhaps you just need to update to the current version of Silk.NET library to fix this crash in your application.How would that happen? Linux has
HAVE_READDIR_Rdefined and we should be allocating the buffer of sufficient size ourselves for it here: https://github.com/dotnet/runtime/blob/c9af66ccb24faea7538b682e4d928557276d7367/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs#L48-L49Hey! Sorry tried quite a few times to reproduce today enabling the dump generation and guess what, can’t reproduce, if I see it again I’ll share a dump asap 💯
just some extra details: seen it happen enumerating ~100k files order of magnitude, big host (ram/cores), lots of action happening => sounds like an extreme race condition
Given how commonly used the helper is (
NonPackedIndexOfValueTypeis the implementation forIndexOf(byte)), I find it suspicious that it’s only showing up fromSystem.IO.Enumeration.The only use of
IndexOf(byte)I see around those stacks is in the Unix InteropDirectoryEntryimplementation here: https://github.com/dotnet/runtime/blob/ff604c23939bc59f856ef67f1f3d18dd685ff7a2/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs#L29-L32 https://github.com/dotnet/runtime/blob/ff604c23939bc59f856ef67f1f3d18dd685ff7a2/src/libraries/Common/src/Interop/Unix/System.Native/Interop.ReadDir.cs#L42-L45I bet this should be using
MemoryMarshal.CreateReadOnlySpanFromNullTerminatedinstead, and we’re AVing because theNameisn’t a full 256 byte buffer.Looks like we were using
Marshal.PtrToStringAnsihere before https://github.com/dotnet/coreclr/pull/21622https://github.com/dotnet/runtime/blob/ff604c23939bc59f856ef67f1f3d18dd685ff7a2/src/native/libs/System.Native/pal_io.c#L478-L478
https://github.com/dotnet/runtime/blob/ff604c23939bc59f856ef67f1f3d18dd685ff7a2/src/native/libs/System.Native/pal_io.c#L494-L498
Though I suppose its more
Directory.GetFileson Linux (WSL) than necessarily Process; as that just determines the property of the directory being queried