File size: 5,352 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#nullable enable

using System;
using System.Buffers;
using System.ComponentModel;
using System.Management.Automation;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal static partial class Windows
    {
        [LibraryImport(PinvokeDllNames.QueryDosDeviceDllName, EntryPoint = "QueryDosDeviceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)]
        internal static partial int QueryDosDevice(Span<char> lpDeviceName, Span<char> lpTargetPath, uint ucchMax);

        internal static string GetDosDeviceForNetworkPath(char deviceName)
        {
            // By default buffer size is set to 300 which would generally be sufficient in most of the cases.
            const int StartLength =
#if DEBUG
                // In debug, validate ArrayPool growth.
                1;
#else
                300;
#endif

            Span<char> buffer = stackalloc char[StartLength + 1];
            Span<char> fullDeviceName = [deviceName, ':', '\0'];
            char[]? rentedArray = null;

            try
            {
                while (true)
                {
                    uint length = (uint)buffer.Length;
                    int retValue = QueryDosDevice(fullDeviceName, buffer, length);
                    if (retValue > 0)
                    {
                        if (buffer.StartsWith("\\??\\"))
                        {
                            // QueryDosDevice always return array of NULL-terminating strings with additional final NULL
                            // so the buffer has always two NULL-s on end.
                            //
                            // "\\??\\UNC\\localhost\\c$\\tmp\0\0" -> "UNC\\localhost\\c$\\tmp\0\0"
                            Span<char> res = buffer.Slice(4);
                            if (res.StartsWith("UNC"))
                            {
                                // -> "C\\localhost\\c$\\tmp\0\0" -> "\\\\localhost\\c$\\tmp"
                                //
                                // We need to take only first null-terminated string as QueryDosDevice() docs say.
                                int i = 3;
                                for (; i < res.Length; i++)
                                {
                                    if (res[i] == '\0')
                                    {
                                        break;
                                    }
                                }

                                Diagnostics.Assert(i < res.Length, "Broken QueryDosDevice() buffer.");

                                res = res.Slice(2, i);
                                res[0] = '\\';

                                // If we want always to have terminating slash -> "\\\\localhost\\c$\\tmp\\"
                                // res = res.Slice(2, retValue - 3);
                                // res[0] = '\\';
                                // res[^1] = '\\';
                            }
                            // else if (res[^3] == ':')
                            // {
                            //     Diagnostics.Assert(false, "Really it is a dead code since GetDosDevice() is called only if PSDrive.DriveType == DriveType.Network");

                            //     // The substed path is the root path of a drive. For example: subst Y: C:\
                            //     // -> "C:\0\0" -> "C:\"
                            //     res = res.Slice(0, retValue - 1);
                            //     res[^1] = '\\';
                            // }
                            else
                            {
                                throw new Exception("GetDosDeviceForNetworkPath() can be called only if PSDrive.DriveType == DriveType.Network.");
                            }

                            return res.ToString();
                        }
                        else
                        {
                            Diagnostics.Assert(false, "Really it is a dead code since GetDosDevice() is called only if PSDrive.DriveType == DriveType.Network");

                            // The drive name is not a substed path, then we return the root path of the drive
                            // "C:\0" -> "C:\\"
                            fullDeviceName[^1] = '\\';
                            return fullDeviceName.ToString();
                        }
                    }

                    const int ERROR_INSUFFICIENT_BUFFER = 122;
                    int errorCode = Marshal.GetLastPInvokeError();
                    if (errorCode != ERROR_INSUFFICIENT_BUFFER)
                    {
                        throw new Win32Exception((int)errorCode);
                    }

                    char[]? toReturn = rentedArray;
                    buffer = rentedArray = ArrayPool<char>.Shared.Rent(buffer.Length * 2);
                    if (toReturn is not null)
                    {
                        ArrayPool<char>.Shared.Return(toReturn);
                    }
                }
            }
            finally
            {
                if (rentedArray is not null)
                {
                    ArrayPool<char>.Shared.Return(rentedArray);
                }
            }
        }
    }
}