Repository navigation
Expand file tree
/
Copy pathProcessMemoryPriorityNativeMethods.cs
More file actions
339 lines (292 loc) Β· 12.2 KB
/
Copy pathProcessMemoryPriorityNativeMethods.cs
File metadata and controls
339 lines (292 loc) Β· 12.2 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* ThreadPilot - Windows process memory priority P/Invoke declarations.
*/
namespace ThreadPilot.Platforms.Windows
{
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class ProcessMemoryPriorityNativeMethods
{
internal const int ProcessIoPriority = 33;
internal const string SeIncreaseBasePriorityPrivilege = "SeIncreaseBasePriorityPrivilege";
private const uint TokenAdjustPrivileges = 0x0020;
private const uint TokenQuery = 0x0008;
private const uint SePrivilegeEnabled = 0x00000002;
private const uint TokenPrivilegesInformationClass = 3;
private static readonly object PrivilegeLock = new();
private static readonly System.Collections.Generic.Dictionary<string, PrivilegeState> ActivePrivileges = new(StringComparer.OrdinalIgnoreCase);
[StructLayout(LayoutKind.Sequential)]
internal struct Luid
{
public uint LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LuidAndAttributes
{
public Luid Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TokenPrivileges
{
public uint PrivilegeCount;
public Luid Luid;
public uint Attributes;
}
[LibraryImport("kernel32.dll", SetLastError = true)]
public static partial SafeProcessHandle OpenProcess(
ProcessAccessFlags access,
[MarshalAs(UnmanagedType.Bool)] bool inheritHandle,
uint processId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool GetProcessInformation(
SafeProcessHandle process,
ProcessInformationClass processInformationClass,
ref MemoryPriorityInformation processInformation,
uint processInformationSize);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SetProcessInformation(
SafeProcessHandle process,
ProcessInformationClass processInformationClass,
ref MemoryPriorityInformation processInformation,
uint processInformationSize);
[LibraryImport("ntdll.dll")]
public static partial int NtQueryInformationProcess(
SafeProcessHandle process,
int processInformationClass,
ref int processInformation,
int processInformationLength,
out uint returnLength);
[LibraryImport("ntdll.dll")]
public static partial int NtSetInformationProcess(
SafeProcessHandle process,
int processInformationClass,
ref int processInformation,
int processInformationLength);
[LibraryImport("kernel32.dll")]
public static partial IntPtr GetCurrentProcess();
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool OpenProcessToken(
IntPtr processHandle,
uint desiredAccess,
out SafeAccessTokenHandle tokenHandle);
[LibraryImport("advapi32.dll", EntryPoint = "LookupPrivilegeValueW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool LookupPrivilegeValue(
string? lpSystemName,
string lpName,
out Luid lpLuid);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool AdjustTokenPrivileges(
SafeAccessTokenHandle tokenHandle,
[MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
ref TokenPrivileges newState,
uint bufferLength,
out TokenPrivileges previousState,
out uint returnLength);
[LibraryImport("advapi32.dll", EntryPoint = "AdjustTokenPrivileges", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool AdjustTokenPrivileges(
SafeAccessTokenHandle tokenHandle,
[MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
ref TokenPrivileges newState,
uint bufferLength,
IntPtr previousState,
IntPtr returnLength);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool GetTokenInformation(
SafeAccessTokenHandle tokenHandle,
uint tokenInformationClass,
IntPtr tokenInformation,
uint tokenInformationLength,
out uint returnLength);
internal static IDisposable AcquirePrivilegeScope(string privilegeName)
{
if (string.IsNullOrWhiteSpace(privilegeName))
{
return EmptyDisposable.Instance;
}
lock (PrivilegeLock)
{
if (ActivePrivileges.TryGetValue(privilegeName, out var existingState))
{
existingState.RefCount++;
return new ScopedPrivilege(existingState);
}
if (!OpenProcessToken(GetCurrentProcess(), TokenAdjustPrivileges | TokenQuery, out var tokenHandle))
{
return EmptyDisposable.Instance;
}
using (tokenHandle)
{
if (tokenHandle.IsInvalid)
{
return EmptyDisposable.Instance;
}
if (!LookupPrivilegeValue(null, privilegeName, out var luid))
{
return EmptyDisposable.Instance;
}
var tp = new TokenPrivileges
{
PrivilegeCount = 1,
Luid = luid,
Attributes = SePrivilegeEnabled,
};
bool adjusted = AdjustTokenPrivileges(
tokenHandle,
false,
ref tp,
(uint)Marshal.SizeOf<TokenPrivileges>(),
out var previousState,
out _);
int lastError = Marshal.GetLastWin32Error();
if (!adjusted || lastError != 0)
{
return EmptyDisposable.Instance;
}
var newState = new PrivilegeState(privilegeName, previousState);
ActivePrivileges[privilegeName] = newState;
return new ScopedPrivilege(newState);
}
}
}
internal static bool TryGetPrivilegeState(string privilegeName, out bool isPresent, out bool isEnabled)
{
isPresent = false;
isEnabled = false;
if (string.IsNullOrWhiteSpace(privilegeName))
{
return false;
}
if (!OpenProcessToken(GetCurrentProcess(), TokenQuery, out var tokenHandle))
{
return false;
}
using (tokenHandle)
{
if (tokenHandle.IsInvalid)
{
return false;
}
if (!LookupPrivilegeValue(null, privilegeName, out var targetLuid))
{
return false;
}
GetTokenInformation(tokenHandle, TokenPrivilegesInformationClass, IntPtr.Zero, 0, out uint requiredLength);
if (requiredLength == 0)
{
return false;
}
IntPtr buffer = Marshal.AllocHGlobal((int)requiredLength);
try
{
if (!GetTokenInformation(tokenHandle, TokenPrivilegesInformationClass, buffer, requiredLength, out _))
{
return false;
}
int count = Marshal.ReadInt32(buffer);
int offset = 4;
for (int i = 0; i < count; i++)
{
var item = Marshal.PtrToStructure<LuidAndAttributes>(IntPtr.Add(buffer, offset));
if (item.Luid.LowPart == targetLuid.LowPart && item.Luid.HighPart == targetLuid.HighPart)
{
isPresent = true;
isEnabled = (item.Attributes & SePrivilegeEnabled) != 0;
return true;
}
offset += Marshal.SizeOf<LuidAndAttributes>();
}
return false;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}
internal static bool IsPrivilegeEnabled(string privilegeName)
{
return TryGetPrivilegeState(privilegeName, out var isPresent, out var isEnabled) && isPresent && isEnabled;
}
internal static bool IsPrivilegePresent(string privilegeName)
{
return TryGetPrivilegeState(privilegeName, out var isPresent, out _) && isPresent;
}
private sealed class PrivilegeState
{
public PrivilegeState(string privilegeName, TokenPrivileges previousState)
{
this.PrivilegeName = privilegeName;
this.PreviousState = previousState;
this.RefCount = 1;
}
public string PrivilegeName { get; }
public TokenPrivileges PreviousState { get; }
public int RefCount { get; set; }
public void Restore()
{
if (this.PreviousState.PrivilegeCount > 0)
{
if (OpenProcessToken(GetCurrentProcess(), TokenAdjustPrivileges | TokenQuery, out var tokenHandle))
{
using (tokenHandle)
{
if (!tokenHandle.IsInvalid)
{
var previous = this.PreviousState;
AdjustTokenPrivileges(
tokenHandle,
false,
ref previous,
0,
IntPtr.Zero,
IntPtr.Zero);
}
}
}
}
}
}
private sealed class ScopedPrivilege : IDisposable
{
private readonly PrivilegeState state;
private int disposed;
public ScopedPrivilege(PrivilegeState state)
{
this.state = state;
}
public void Dispose()
{
if (Interlocked.Exchange(ref this.disposed, 1) != 0)
{
return;
}
lock (PrivilegeLock)
{
this.state.RefCount--;
if (this.state.RefCount <= 0)
{
ActivePrivileges.Remove(this.state.PrivilegeName);
this.state.Restore();
}
}
}
}
private sealed class EmptyDisposable : IDisposable
{
public static EmptyDisposable Instance { get; } = new();
public void Dispose()
{
}
}
}
}