-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessCap.cs
More file actions
826 lines (723 loc) · 32 KB
/
Copy pathProcessCap.cs
File metadata and controls
826 lines (723 loc) · 32 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
namespace ProcessCap
{
public static class Program
{
private const ulong BytesPerMebibyte = 1024 * 1024;
public static int Main()
{
try
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
throw new PlatformNotSupportedException("ProcessCap requires Windows.");
}
WindowsVersionInfo windowsVersion = NativeMethods.GetWindowsVersionInfo();
if (windowsVersion.Major < 10)
{
throw new PlatformNotSupportedException("ProcessCap requires Windows 10 or later.");
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\nProcessCap");
Console.WriteLine("----------------------------------------");
Console.ResetColor();
WriteColored("Checking operating system and machine resources...", ConsoleColor.Gray);
SystemResourceInfo resources = NativeMethods.GetSystemResourceInfo(windowsVersion);
int totalMemoryMb = checked((int)(resources.TotalPhysicalMemoryBytes / BytesPerMebibyte));
int freeMemoryMb = checked((int)(resources.AvailablePhysicalMemoryBytes / BytesPerMebibyte));
int logicalProcessorCount = Environment.ProcessorCount;
int processBitness = IntPtr.Size * 8;
int maximumAffinityProcessorCount = Math.Min(logicalProcessorCount, processBitness);
int maximumMemoryLimitMb = GetMaximumMemoryLimitMb(totalMemoryMb);
Console.WriteLine("OS: {0} build {1}", resources.Caption, resources.BuildNumber);
Console.WriteLine("Launcher architecture: {0}-bit", processBitness);
Console.WriteLine("Logical processors: {0}", logicalProcessorCount);
Console.WriteLine("Usable CPU affinity range: 1-{0} logical processor(s)", maximumAffinityProcessorCount);
Console.WriteLine("Physical memory: {0} MB total, {1} MB currently free\n", totalMemoryMb, freeMemoryMb);
WriteColored("CPU limiting uses processor affinity; it is not an exact percentage throttle.", ConsoleColor.DarkYellow);
WriteColored("Memory limiting is a hard total job-memory limit inherited by child processes.\n", ConsoleColor.DarkYellow);
WriteColored("Input required. Press Enter to accept values shown in brackets.\n", ConsoleColor.Cyan);
string applicationPath = ReadExistingExecutable("Application executable path");
Console.Write("Application arguments (optional): ");
string arguments = Console.ReadLine() ?? string.Empty;
string defaultDirectory = Path.GetDirectoryName(applicationPath);
string workingDirectory = ReadDirectory("Working directory", defaultDirectory);
int cpuLimit = ReadInt32("Logical processors to allow", 1, maximumAffinityProcessorCount, maximumAffinityProcessorCount);
int defaultMemoryLimitMb = Math.Min(maximumMemoryLimitMb, Math.Max(256, Math.Min(freeMemoryMb, totalMemoryMb)));
int memoryLimitMb = ReadInt32("Total memory limit in MB", 1, maximumMemoryLimitMb, defaultMemoryLimitMb);
if (memoryLimitMb > freeMemoryMb)
{
WriteColored(string.Format("Warning: the limit exceeds currently free memory ({0} MB).", freeMemoryMb), ConsoleColor.Yellow);
}
ulong affinityMask = cpuLimit == 64 ? ulong.MaxValue : (1UL << cpuLimit) - 1;
ulong memoryLimitBytes = checked((ulong)memoryLimitMb * BytesPerMebibyte);
string jobName = "ProcessCap." + Guid.NewGuid().ToString("N");
using (RestrictedJob job = new RestrictedJob(jobName, memoryLimitBytes))
{
WriteColored("\nStarting restricted process...", ConsoleColor.Cyan);
Console.WriteLine("Executable: {0}", applicationPath);
Console.WriteLine("Arguments: {0}", arguments);
Console.WriteLine("Working directory: {0}", workingDirectory);
Console.WriteLine("CPU affinity logical processors: {0} of {1}", cpuLimit, logicalProcessorCount);
Console.WriteLine("Memory limit: {0} MB", memoryLimitMb);
using (LaunchedProcess process = job.StartProcess(applicationPath, arguments, workingDirectory, affinityMask))
{
int processId = process.Id;
WriteColored(string.Format("Started process ID {0}. Keep this launcher running to keep the restricted job alive.", processId), ConsoleColor.Green);
Thread.Sleep(250);
try
{
RestrictionVerification result = job.Verify(process.Handle, memoryLimitBytes, affinityMask);
WriteColored(
result.AllApplied ? "Restrictions verified successfully." : "Restrictions could not be fully verified.",
result.AllApplied ? ConsoleColor.Green : ConsoleColor.Yellow);
Console.WriteLine(" Job membership: {0}", result.IsAssignedToJob ? "applied" : "not applied");
Console.WriteLine(
" Job memory limit: {0} (expected {1} MB, actual {2:F2} MB, flags 0x{3:X})",
result.MemoryLimitApplied ? "applied" : "not applied",
memoryLimitMb,
result.ActualJobMemoryLimitBytes / (double)BytesPerMebibyte,
result.JobLimitFlags);
Console.WriteLine(
" CPU affinity: {0} (expected 0x{1:X}, actual 0x{2:X})",
result.AffinityApplied ? "applied" : "not applied",
result.ExpectedAffinityMask,
result.ActualAffinityMask);
}
catch (Exception ex)
{
WriteColored("Unable to verify restrictions after startup: " + ex.Message, ConsoleColor.Yellow);
}
process.WaitForExit();
WriteColored(string.Format("Process {0} exited.", processId), ConsoleColor.Green);
}
}
return 0;
}
catch (Exception ex)
{
WriteColored("Error: " + ex.Message, ConsoleColor.Red);
return 1;
}
}
private static string Normalize(string value)
{
return (value ?? string.Empty).Trim().Trim('"', '\'');
}
private static string ReadExistingExecutable(string prompt)
{
while (true)
{
Console.Write("{0}: ", prompt);
string value = Normalize(Console.ReadLine());
if (string.IsNullOrWhiteSpace(value))
{
WriteColored("A path is required.", ConsoleColor.Yellow);
continue;
}
string fullPath;
if (!TryGetFullPath(value, out fullPath))
{
continue;
}
if (!File.Exists(fullPath))
{
WriteColored("The file does not exist.", ConsoleColor.Yellow);
continue;
}
if (!string.Equals(Path.GetExtension(fullPath), ".exe", StringComparison.OrdinalIgnoreCase))
{
WriteColored("The selected file must be an .exe.", ConsoleColor.Yellow);
continue;
}
return fullPath;
}
}
private static string ReadDirectory(string prompt, string defaultPath)
{
while (true)
{
Console.Write("{0} [{1}]: ", prompt, defaultPath);
string value = Normalize(Console.ReadLine());
if (string.IsNullOrWhiteSpace(value))
{
return defaultPath;
}
string fullPath;
if (!TryGetFullPath(value, out fullPath))
{
continue;
}
if (Directory.Exists(fullPath))
{
return fullPath;
}
WriteColored("The directory does not exist.", ConsoleColor.Yellow);
}
}
private static int ReadInt32(string prompt, int minimum, int maximum, int defaultValue)
{
while (true)
{
Console.Write("{0} [{1}]: ", prompt, defaultValue);
string value = Console.ReadLine();
if (string.IsNullOrWhiteSpace(value))
{
return defaultValue;
}
int parsed;
if (!int.TryParse(value, out parsed))
{
WriteColored("Enter a whole number.", ConsoleColor.Yellow);
continue;
}
if (parsed >= minimum && parsed <= maximum)
{
return parsed;
}
WriteColored(string.Format("Enter a value from {0} to {1}.", minimum, maximum), ConsoleColor.Yellow);
}
}
private static int GetMaximumMemoryLimitMb(int totalMemoryMb)
{
if (IntPtr.Size == 4)
{
// JOBOBJECT_EXTENDED_LIMIT_INFORMATION uses SIZE_T for memory limits.
// A 32-bit launcher therefore cannot represent a value of 4 GiB or more.
int maximum32BitMb = (int)(uint.MaxValue / BytesPerMebibyte);
return Math.Min(totalMemoryMb, maximum32BitMb);
}
return totalMemoryMb;
}
private static void WriteColored(string text, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
private static bool TryGetFullPath(string value, out string fullPath)
{
try
{
fullPath = Path.GetFullPath(value);
return true;
}
catch (Exception ex)
{
if (!(ex is ArgumentException) && !(ex is NotSupportedException) && !(ex is PathTooLongException))
{
throw;
}
WriteColored("The path is invalid: " + ex.Message, ConsoleColor.Yellow);
fullPath = string.Empty;
return false;
}
}
}
internal sealed class RestrictedJob : IDisposable
{
private const uint CreateSuspended = 0x00000004;
private const uint JobObjectLimitJobMemory = 0x00000200;
private const uint JobObjectLimitKillOnJobClose = 0x00002000;
private const int JobObjectExtendedLimitInformation = 9;
private readonly SafeJobHandle jobHandle;
public RestrictedJob(string name, ulong memoryLimit)
{
jobHandle = NativeMethods.CreateJobObject(IntPtr.Zero, name);
if (jobHandle.IsInvalid)
{
throw NativeMethods.Error("Unable to create the Windows job object.");
}
JobObjectExtendedLimitInformation info = new JobObjectExtendedLimitInformation();
info.BasicLimitInformation.LimitFlags = JobObjectLimitKillOnJobClose | JobObjectLimitJobMemory;
info.JobMemoryLimit = new UIntPtr(memoryLimit);
WithStructure(
info,
delegate(IntPtr pointer, uint size)
{
return NativeMethods.SetInformationJobObject(jobHandle, JobObjectExtendedLimitInformation, pointer, size);
},
"Unable to configure the Windows job object memory limit.");
}
public LaunchedProcess StartProcess(string fileName, string arguments, string workingDirectory, ulong affinityMask)
{
StringBuilder commandLine = new StringBuilder(
QuoteWindowsArgument(fileName) + (string.IsNullOrWhiteSpace(arguments) ? string.Empty : " " + arguments));
StartupInfo startup = new StartupInfo();
startup.Size = Marshal.SizeOf(typeof(StartupInfo));
ProcessInformation process;
if (!NativeMethods.CreateProcess(
fileName,
commandLine,
IntPtr.Zero,
IntPtr.Zero,
false,
CreateSuspended,
IntPtr.Zero,
workingDirectory,
ref startup,
out process))
{
throw NativeMethods.Error("Unable to create the process.");
}
using (SafeKernelHandle threadHandle = new SafeKernelHandle(process.Thread, true))
{
SafeProcessHandle processHandle = new SafeProcessHandle(process.Process, true);
try
{
if (!NativeMethods.AssignProcessToJobObject(jobHandle, processHandle))
{
throw NativeMethods.Error("Unable to assign the process to the job.");
}
if (!NativeMethods.SetProcessAffinityMask(processHandle, new UIntPtr(affinityMask)))
{
throw NativeMethods.Error("Unable to apply processor affinity.");
}
if (NativeMethods.ResumeThread(threadHandle) == uint.MaxValue)
{
throw NativeMethods.Error("Unable to resume the process.");
}
return new LaunchedProcess(process.ProcessId, processHandle);
}
catch
{
NativeMethods.TerminateProcess(processHandle, 1);
processHandle.Dispose();
throw;
}
}
}
public RestrictionVerification Verify(SafeProcessHandle process, ulong expectedMemory, ulong expectedAffinity)
{
bool inJob;
if (!NativeMethods.IsProcessInJob(process, jobHandle, out inJob))
{
throw NativeMethods.Error("Unable to verify job membership.");
}
UIntPtr affinity;
UIntPtr systemAffinity;
if (!NativeMethods.GetProcessAffinityMask(process, out affinity, out systemAffinity))
{
throw NativeMethods.Error("Unable to verify affinity.");
}
JobObjectExtendedLimitInformation info = QueryInfo();
ulong memory = info.JobMemoryLimit.ToUInt64();
ulong actualAffinity = affinity.ToUInt64();
return new RestrictionVerification(
inJob,
(info.BasicLimitInformation.LimitFlags & JobObjectLimitJobMemory) != 0 && memory == expectedMemory,
actualAffinity == expectedAffinity,
expectedMemory,
memory,
expectedAffinity,
actualAffinity,
info.BasicLimitInformation.LimitFlags);
}
private JobObjectExtendedLimitInformation QueryInfo()
{
int size = Marshal.SizeOf(typeof(JobObjectExtendedLimitInformation));
IntPtr pointer = Marshal.AllocHGlobal(size);
try
{
if (!NativeMethods.QueryInformationJobObject(
jobHandle,
JobObjectExtendedLimitInformation,
pointer,
(uint)size,
IntPtr.Zero))
{
throw NativeMethods.Error("Unable to query job limits.");
}
return (JobObjectExtendedLimitInformation)Marshal.PtrToStructure(
pointer,
typeof(JobObjectExtendedLimitInformation));
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
private static void WithStructure<T>(T value, Func<IntPtr, uint, bool> operation, string error)
where T : struct
{
int size = Marshal.SizeOf(typeof(T));
IntPtr pointer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(value, pointer, false);
if (!operation(pointer, (uint)size))
{
throw NativeMethods.Error(error);
}
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
private static string QuoteWindowsArgument(string value)
{
StringBuilder result = new StringBuilder(value.Length + 2).Append('"');
int backslashCount = 0;
foreach (char character in value)
{
if (character == '\\')
{
backslashCount++;
continue;
}
if (character == '"')
{
result.Append('\\', backslashCount * 2 + 1).Append(character);
backslashCount = 0;
continue;
}
result.Append('\\', backslashCount).Append(character);
backslashCount = 0;
}
return result.Append('\\', backslashCount * 2).Append('"').ToString();
}
public void Dispose()
{
jobHandle.Dispose();
}
}
internal sealed class LaunchedProcess : IDisposable
{
public LaunchedProcess(int id, SafeProcessHandle handle)
{
Id = id;
Handle = handle;
}
public int Id { get; private set; }
public SafeProcessHandle Handle { get; private set; }
public void WaitForExit()
{
uint result = NativeMethods.WaitForSingleObject(Handle, NativeMethods.Infinite);
if (result == NativeMethods.WaitFailed)
{
throw NativeMethods.Error("Unable to wait for the launched process.");
}
}
public void Dispose()
{
Handle.Dispose();
}
}
internal sealed class RestrictionVerification
{
public RestrictionVerification(
bool isAssignedToJob,
bool memoryLimitApplied,
bool affinityApplied,
ulong expectedJobMemoryLimitBytes,
ulong actualJobMemoryLimitBytes,
ulong expectedAffinityMask,
ulong actualAffinityMask,
uint jobLimitFlags)
{
IsAssignedToJob = isAssignedToJob;
MemoryLimitApplied = memoryLimitApplied;
AffinityApplied = affinityApplied;
ExpectedJobMemoryLimitBytes = expectedJobMemoryLimitBytes;
ActualJobMemoryLimitBytes = actualJobMemoryLimitBytes;
ExpectedAffinityMask = expectedAffinityMask;
ActualAffinityMask = actualAffinityMask;
JobLimitFlags = jobLimitFlags;
}
public bool IsAssignedToJob { get; private set; }
public bool MemoryLimitApplied { get; private set; }
public bool AffinityApplied { get; private set; }
public ulong ExpectedJobMemoryLimitBytes { get; private set; }
public ulong ActualJobMemoryLimitBytes { get; private set; }
public ulong ExpectedAffinityMask { get; private set; }
public ulong ActualAffinityMask { get; private set; }
public uint JobLimitFlags { get; private set; }
public bool AllApplied { get { return IsAssignedToJob && MemoryLimitApplied && AffinityApplied; } }
}
internal sealed class SystemResourceInfo
{
public SystemResourceInfo(string caption, int buildNumber, ulong totalPhysicalMemoryBytes, ulong availablePhysicalMemoryBytes)
{
Caption = caption;
BuildNumber = buildNumber;
TotalPhysicalMemoryBytes = totalPhysicalMemoryBytes;
AvailablePhysicalMemoryBytes = availablePhysicalMemoryBytes;
}
public string Caption { get; private set; }
public int BuildNumber { get; private set; }
public ulong TotalPhysicalMemoryBytes { get; private set; }
public ulong AvailablePhysicalMemoryBytes { get; private set; }
}
internal sealed class WindowsVersionInfo
{
public WindowsVersionInfo(int major, int minor, int build, int revision)
{
Major = major;
Minor = minor;
Build = build;
Revision = revision;
}
public int Major { get; private set; }
public int Minor { get; private set; }
public int Build { get; private set; }
public int Revision { get; private set; }
}
[StructLayout(LayoutKind.Sequential)]
internal struct MemoryStatusEx
{
public uint Length;
public uint MemoryLoad;
public ulong TotalPhys;
public ulong AvailPhys;
public ulong TotalPageFile;
public ulong AvailPageFile;
public ulong TotalVirtual;
public ulong AvailVirtual;
public ulong AvailExtendedVirtual;
}
[StructLayout(LayoutKind.Sequential)]
internal struct IoCounters
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
internal struct JobObjectBasicLimitInformation
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
internal struct JobObjectExtendedLimitInformation
{
public JobObjectBasicLimitInformation BasicLimitInformation;
public IoCounters IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct StartupInfo
{
public int Size;
public IntPtr Reserved;
public IntPtr Desktop;
public IntPtr Title;
public uint X;
public uint Y;
public uint XSize;
public uint YSize;
public uint XCountChars;
public uint YCountChars;
public uint FillAttribute;
public uint Flags;
public ushort ShowWindow;
public ushort ReservedSize;
public IntPtr ReservedPointer;
public IntPtr StandardInput;
public IntPtr StandardOutput;
public IntPtr StandardError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct ProcessInformation
{
public IntPtr Process;
public IntPtr Thread;
public int ProcessId;
public int ThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct OsVersionInfo
{
public uint Size;
public uint Major;
public uint Minor;
public uint Build;
public uint PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string ServicePack;
}
internal static class NativeMethods
{
internal const uint Infinite = 0xFFFFFFFF;
internal const uint WaitFailed = 0xFFFFFFFF;
internal static WindowsVersionInfo GetWindowsVersionInfo()
{
try
{
return GetWindowsVersionInfoFromWinRt();
}
catch (Exception ex)
{
if (!(ex is FileNotFoundException) && !(ex is FileLoadException) && !(ex is TypeLoadException))
{
throw;
}
return GetWindowsVersionInfoFromNativeApi();
}
}
private static WindowsVersionInfo GetWindowsVersionInfoFromWinRt()
{
const string AnalyticsInfoTypeName =
"Windows.System.Profile.AnalyticsInfo, Windows.System.Profile, ContentType=WindowsRuntime";
Type analyticsInfoType = Type.GetType(AnalyticsInfoTypeName, true);
PropertyInfo versionInfoProperty = analyticsInfoType.GetProperty("VersionInfo", BindingFlags.Public | BindingFlags.Static);
if (versionInfoProperty == null)
{
throw new InvalidOperationException("Unable to locate the WinRT AnalyticsInfo.VersionInfo property.");
}
object versionInfo = versionInfoProperty.GetValue(null, null);
if (versionInfo == null)
{
throw new InvalidOperationException("WinRT AnalyticsInfo.VersionInfo returned no value.");
}
PropertyInfo deviceFamilyVersionProperty = versionInfo.GetType().GetProperty("DeviceFamilyVersion");
if (deviceFamilyVersionProperty == null)
{
throw new InvalidOperationException("Unable to locate the WinRT DeviceFamilyVersion property.");
}
object rawValue = deviceFamilyVersionProperty.GetValue(versionInfo, null);
ulong encodedVersion;
if (rawValue == null || !ulong.TryParse(rawValue.ToString(), out encodedVersion))
{
throw new InvalidOperationException("WinRT returned an invalid DeviceFamilyVersion value.");
}
return new WindowsVersionInfo(
(int)((encodedVersion >> 48) & 0xFFFF),
(int)((encodedVersion >> 32) & 0xFFFF),
(int)((encodedVersion >> 16) & 0xFFFF),
(int)(encodedVersion & 0xFFFF));
}
private static WindowsVersionInfo GetWindowsVersionInfoFromNativeApi()
{
OsVersionInfo version = new OsVersionInfo();
version.Size = (uint)Marshal.SizeOf(typeof(OsVersionInfo));
version.ServicePack = string.Empty;
int status = RtlGetVersion(ref version);
if (status < 0)
{
throw new InvalidOperationException(
string.Format("Unable to query the native Windows version. NTSTATUS: 0x{0:X8}.", status));
}
return new WindowsVersionInfo(
checked((int)version.Major),
checked((int)version.Minor),
checked((int)version.Build),
0);
}
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "ProcessCap validates Windows before calling this method.")]
internal static SystemResourceInfo GetSystemResourceInfo(WindowsVersionInfo windowsVersion)
{
MemoryStatusEx memory = new MemoryStatusEx();
memory.Length = (uint)Marshal.SizeOf(typeof(MemoryStatusEx));
if (!GlobalMemoryStatusEx(ref memory))
{
throw Error("Unable to query physical memory status.");
}
string caption = "Windows";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
if (key != null)
{
object productName = key.GetValue("ProductName");
if (productName != null && !string.IsNullOrWhiteSpace(productName.ToString()))
{
caption = productName.ToString();
}
}
}
if (windowsVersion.Build >= 22000 && caption.StartsWith("Windows 10", StringComparison.Ordinal))
{
caption = "Windows 11" + caption.Substring(10);
}
return new SystemResourceInfo(caption, windowsVersion.Build, memory.TotalPhys, memory.AvailPhys);
}
internal static Win32Exception Error(string message)
{
return new Win32Exception(Marshal.GetLastWin32Error(), message);
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GlobalMemoryStatusEx(ref MemoryStatusEx status);
[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
private static extern int RtlGetVersion(ref OsVersionInfo versionInformation);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern SafeJobHandle CreateJobObject(IntPtr attributes, string name);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetInformationJobObject(SafeJobHandle job, int type, IntPtr info, uint length);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool QueryInformationJobObject(SafeJobHandle job, int type, IntPtr info, uint length, IntPtr returned);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool AssignProcessToJobObject(SafeJobHandle job, SafeProcessHandle process);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool IsProcessInJob(SafeProcessHandle process, SafeJobHandle job, out bool result);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetProcessAffinityMask(SafeProcessHandle process, out UIntPtr processMask, out UIntPtr systemMask);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetProcessAffinityMask(SafeProcessHandle process, UIntPtr mask);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool TerminateProcess(SafeProcessHandle process, uint exitCode);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern uint ResumeThread(SafeKernelHandle thread);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern uint WaitForSingleObject(SafeProcessHandle handle, uint milliseconds);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool CreateProcess(
string applicationName,
StringBuilder commandLine,
IntPtr processAttributes,
IntPtr threadAttributes,
bool inheritHandles,
uint creationFlags,
IntPtr environment,
string currentDirectory,
ref StartupInfo startupInfo,
out ProcessInformation processInformation);
}
internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeJobHandle()
: base(true)
{
}
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(handle);
}
}
internal sealed class SafeKernelHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeKernelHandle(IntPtr handle, bool ownsHandle)
: base(ownsHandle)
{
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
return NativeMethods.CloseHandle(handle);
}
}
}