Skip to content

Commit fb3e614

Browse files
committed
(#239) DiskUtils: fix the incorrect file descriptor closure
1 parent 682b325 commit fb3e614

4 files changed

Lines changed: 62 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
2828
- The platform-default path comparers (`LocalPath.PlatformDefaultComparer`, `AbsolutePath.PlatformDefaultComparer`) are now case-insensitive on iOS and tvOS as well, matching the .NET runtime.
2929

3030
### Fixed
31+
- [#239](https://github.com/ForNeVeR/TruePath/issues/239): on Unix, `AbsolutePath.Canonicalize()` no longer closes the file descriptor 0 when the path doesn't exist. This used to close the standard input of the process, or any file or socket that later took this descriptor number. Also, it no longer leaks the memory allocated for the resolved path.
3132
- [#226](https://github.com/ForNeVeR/TruePath/issues/226): `LocalPath.IsPrefixOf` and `StartsWith` now take leading `..` references of relative paths into account instead of comparing them as strings. For example, `new LocalPath("..").IsPrefixOf(new LocalPath("foo"))` is now `true`, and `new LocalPath("..").IsPrefixOf(new LocalPath("../.."))` is now `false`.
3233
- [#225](https://github.com/ForNeVeR/TruePath/issues/225): Make path prefix checks use the same platform-default case sensitivity as path equality.
3334
- `LocalPath.IsPrefixOf` and `StartsWith` now compare path strings ordinally. Previously they used the current culture, which ignores collation-ignorable characters, so a path could be reported as a prefix of an unrelated one.

‎TruePath.Tests/DiskUtilsTests.cs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// SPDX-License-Identifier: MIT
44

55
using System.Text;
6+
using TruePath.SystemIo;
67
using RuntimeInformation = System.Runtime.InteropServices.RuntimeInformation;
78

89
namespace TruePath.Tests;
@@ -43,6 +44,42 @@ public void DiskUtils_OnCaseInsensitiveFs_PassNonCanonicalPath_ReturnCanonicalPa
4344
Assert.Equal(expected.Value, actual);
4445
}
4546

47+
[Fact]
48+
public void DiskUtils_PassNonExistentPath_KeepFileDescriptorZeroOpen()
49+
{
50+
// Arrange
51+
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return;
52+
53+
var placeholderPath = Temporary.CreateTempFile();
54+
try
55+
{
56+
// File descriptor 0 (normally the standard input) may be closed in the test process: then the next opened
57+
// file takes it.
58+
using var placeholder = IsFileDescriptorOpen(0) ? null : File.OpenHandle(placeholderPath.Value);
59+
Assert.True(IsFileDescriptorOpen(0), "File descriptor 0 should be open before the test.");
60+
var nonExistentPath = Temporary.SystemTempDirectory() / Guid.NewGuid().ToString() / "file.txt";
61+
62+
// Act
63+
var actual = DiskUtils.GetRealPath(nonExistentPath.Value);
64+
65+
// Assert
66+
Assert.Equal(nonExistentPath, new AbsolutePath(actual));
67+
Assert.True(IsFileDescriptorOpen(0), "File descriptor 0 should stay open.");
68+
}
69+
finally
70+
{
71+
placeholderPath.Delete();
72+
}
73+
}
74+
75+
// ReSharper disable once InconsistentNaming
76+
private const int F_GETFD = 1; // The same on Linux and macOS.
77+
78+
[DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
79+
private static extern int FCntl(int fd, int cmd);
80+
81+
private static bool IsFileDescriptorOpen(int fd) => FCntl(fd, F_GETFD) != -1;
82+
4683
private static string InvertCase(string path)
4784
{
4885
var builder = new StringBuilder();

‎TruePath/DiskUtils.cs‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// SPDX-FileCopyrightText: 2024 TruePath contributors <https://github.com/ForNeVeR/TruePath>
1+
// SPDX-FileCopyrightText: 2024-2026 TruePath contributors <https://github.com/ForNeVeR/TruePath>
22
//
33
// SPDX-License-Identifier: MIT
44

@@ -116,16 +116,21 @@ internal static string GetRealPath(string path)
116116
/// <returns>The resolved absolute path, or the original path if resolution fails.</returns>
117117
private static string GetPosixRealPath(string path)
118118
{
119-
using var ptr = Libc.RealPath(path, IntPtr.Zero);
119+
var ptr = Libc.RealPath(path, IntPtr.Zero);
120120

121-
if (ptr.DangerousGetHandle() == IntPtr.Zero)
121+
if (ptr == IntPtr.Zero)
122122
{
123123
return path;
124124
}
125125

126-
var result = Marshal.PtrToStringAnsi(ptr.DangerousGetHandle());
127-
128-
return result ?? path;
126+
try
127+
{
128+
return Marshal.PtrToStringAnsi(ptr)!; // never returns null since ptr is not zero here
129+
}
130+
finally
131+
{
132+
Libc.Free(ptr);
133+
}
129134
}
130135

131136
/// <summary>

‎TruePath/Libc.cs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
// SPDX-FileCopyrightText: 2024 TruePath contributors <https://github.com/ForNeVeR/TruePath>
1+
// SPDX-FileCopyrightText: 2024-2026 TruePath contributors <https://github.com/ForNeVeR/TruePath>
22
//
33
// SPDX-License-Identifier: MIT
44

55
using System.Runtime.InteropServices;
6-
using Microsoft.Win32.SafeHandles;
76

87
namespace TruePath;
98

@@ -17,13 +16,22 @@ internal static class Libc
1716
/// </summary>
1817
/// <param name="path">The file path to resolve.</param>
1918
/// <param name="buffer">A pointer to a buffer where the resolved absolute path will be stored.</param>
20-
/// <returns>A <see cref="SafeFileHandle"/> representing the resolved path, or an invalid handle if the function fails.</returns>
19+
/// <returns>
20+
/// A pointer to the resolved path, or <see cref="IntPtr.Zero"/> if the function fails. If <paramref name="buffer"/>
21+
/// is <see cref="IntPtr.Zero"/>, the result is allocated by libc and should be released with <see cref="Free"/>.
22+
/// </returns>
2123
/// <remarks>
22-
/// This method is an interop call to the 'realpath' function in the libc library. The <paramref name="buffer"/> should be allocated with enough space to hold the resolved path.
24+
/// This method is an interop call to the 'realpath' function in the libc library. The <paramref name="buffer"/>, if
25+
/// not <see cref="IntPtr.Zero"/>, should be allocated with enough space to hold the resolved path.
2326
/// </remarks>
2427
[DllImport("libc",
2528
EntryPoint = "realpath",
2629
SetLastError = true,
2730
CharSet = CharSet.Ansi)]
28-
internal static extern SafeFileHandle RealPath(string path, IntPtr buffer);
31+
internal static extern IntPtr RealPath(string path, IntPtr buffer);
32+
33+
/// <summary>Releases the memory allocated by libc.</summary>
34+
/// <param name="ptr">The pointer to the memory to release.</param>
35+
[DllImport("libc", EntryPoint = "free")]
36+
internal static extern void Free(IntPtr ptr);
2937
}

0 commit comments

Comments
 (0)