-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathNativeMethods.cs
1736 lines (1510 loc) · 59.8 KB
/
NativeMethods.cs
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Build.Shared;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
#nullable disable
namespace Microsoft.Build.Framework;
internal static class NativeMethods
{
#region Constants
internal const uint ERROR_INSUFFICIENT_BUFFER = 0x8007007A;
internal const uint STARTUP_LOADER_SAFEMODE = 0x10;
internal const uint S_OK = 0x0;
internal const uint S_FALSE = 0x1;
internal const uint ERROR_ACCESS_DENIED = 0x5;
internal const uint ERROR_FILE_NOT_FOUND = 0x80070002;
internal const uint FUSION_E_PRIVATE_ASM_DISALLOWED = 0x80131044; // Tried to find unsigned assembly in GAC
internal const uint RUNTIME_INFO_DONT_SHOW_ERROR_DIALOG = 0x40;
internal const uint FILE_TYPE_CHAR = 0x0002;
internal const Int32 STD_OUTPUT_HANDLE = -11;
internal const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
internal const uint RPC_S_CALLPENDING = 0x80010115;
internal const uint E_ABORT = (uint)0x80004004;
internal const int FILE_ATTRIBUTE_READONLY = 0x00000001;
internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
/// <summary>
/// Default buffer size to use when dealing with the Windows API.
/// </summary>
internal const int MAX_PATH = 260;
private const string kernel32Dll = "kernel32.dll";
private const string WINDOWS_FILE_SYSTEM_REGISTRY_KEY = @"SYSTEM\CurrentControlSet\Control\FileSystem";
private const string WINDOWS_LONG_PATHS_ENABLED_VALUE_NAME = "LongPathsEnabled";
internal static DateTime MinFileDate { get; } = DateTime.FromFileTimeUtc(0);
internal static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
internal static IntPtr NullIntPtr = new IntPtr(0);
internal static IntPtr InvalidHandle = new IntPtr(-1);
// As defined in winnt.h:
internal const ushort PROCESSOR_ARCHITECTURE_INTEL = 0;
internal const ushort PROCESSOR_ARCHITECTURE_ARM = 5;
internal const ushort PROCESSOR_ARCHITECTURE_IA64 = 6;
internal const ushort PROCESSOR_ARCHITECTURE_AMD64 = 9;
internal const ushort PROCESSOR_ARCHITECTURE_ARM64 = 12;
internal const uint INFINITE = 0xFFFFFFFF;
internal const uint WAIT_ABANDONED_0 = 0x00000080;
internal const uint WAIT_OBJECT_0 = 0x00000000;
internal const uint WAIT_TIMEOUT = 0x00000102;
#endregion
#region Enums
private enum PROCESSINFOCLASS : int
{
ProcessBasicInformation = 0,
ProcessQuotaLimits,
ProcessIoCounters,
ProcessVmCounters,
ProcessTimes,
ProcessBasePriority,
ProcessRaisePriority,
ProcessDebugPort,
ProcessExceptionPort,
ProcessAccessToken,
ProcessLdtInformation,
ProcessLdtSize,
ProcessDefaultHardErrorMode,
ProcessIoPortHandlers, // Note: this is kernel mode only
ProcessPooledUsageAndLimits,
ProcessWorkingSetWatch,
ProcessUserModeIOPL,
ProcessEnableAlignmentFaultFixup,
ProcessPriorityClass,
ProcessWx86Information,
ProcessHandleCount,
ProcessAffinityMask,
ProcessPriorityBoost,
MaxProcessInfoClass
};
private enum eDesiredAccess : int
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_ALL = 0x001F0000,
PROCESS_TERMINATE = 0x0001,
PROCESS_CREATE_THREAD = 0x0002,
PROCESS_SET_SESSIONID = 0x0004,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020,
PROCESS_DUP_HANDLE = 0x0040,
PROCESS_CREATE_PROCESS = 0x0080,
PROCESS_SET_QUOTA = 0x0100,
PROCESS_SET_INFORMATION = 0x0200,
PROCESS_QUERY_INFORMATION = 0x0400,
PROCESS_ALL_ACCESS = SYNCHRONIZE | 0xFFF
}
#pragma warning disable 0649, 0169
internal enum LOGICAL_PROCESSOR_RELATIONSHIP
{
RelationProcessorCore,
RelationNumaNode,
RelationCache,
RelationProcessorPackage,
RelationGroup,
RelationAll = 0xffff
}
internal struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX
{
public LOGICAL_PROCESSOR_RELATIONSHIP Relationship;
public uint Size;
public PROCESSOR_RELATIONSHIP Processor;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct PROCESSOR_RELATIONSHIP
{
public byte Flags;
private byte EfficiencyClass;
private fixed byte Reserved[20];
public ushort GroupCount;
public IntPtr GroupInfo;
}
#pragma warning restore 0169, 0149
/// <summary>
/// Flags for CoWaitForMultipleHandles
/// </summary>
[Flags]
public enum COWAIT_FLAGS : int
{
/// <summary>
/// Exit when a handle is signaled.
/// </summary>
COWAIT_NONE = 0,
/// <summary>
/// Exit when all handles are signaled AND a message is received.
/// </summary>
COWAIT_WAITALL = 0x00000001,
/// <summary>
/// Exit when an RPC call is serviced.
/// </summary>
COWAIT_ALERTABLE = 0x00000002
}
/// <summary>
/// Processor architecture values
/// </summary>
internal enum ProcessorArchitectures
{
// Intel 32 bit
X86,
// AMD64 64 bit
X64,
// Itanium 64
IA64,
// ARM
ARM,
// ARM64
ARM64,
// Who knows
Unknown
}
internal enum SymbolicLink
{
File = 0,
Directory = 1,
AllowUnprivilegedCreate = 2,
}
#endregion
#region Structs
/// <summary>
/// Structure that contain information about the system on which we are running
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
// This is a union of a DWORD and a struct containing 2 WORDs.
internal ushort wProcessorArchitecture;
internal ushort wReserved;
internal uint dwPageSize;
internal IntPtr lpMinimumApplicationAddress;
internal IntPtr lpMaximumApplicationAddress;
internal IntPtr dwActiveProcessorMask;
internal uint dwNumberOfProcessors;
internal uint dwProcessorType;
internal uint dwAllocationGranularity;
internal ushort wProcessorLevel;
internal ushort wProcessorRevision;
}
/// <summary>
/// Wrap the intptr returned by OpenProcess in a safe handle.
/// </summary>
internal class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Create a SafeHandle, informing the base class
// that this SafeHandle instance "owns" the handle,
// and therefore SafeHandle should call
// our ReleaseHandle method when the SafeHandle
// is no longer in use
private SafeProcessHandle() : base(true)
{
}
[SupportedOSPlatform("windows")]
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
/// <summary>
/// Contains information about the current state of both physical and virtual memory, including extended memory
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class MemoryStatus
{
/// <summary>
/// Initializes a new instance of the <see cref="MemoryStatus"/> class.
/// </summary>
public MemoryStatus()
{
#if CLR2COMPATIBILITY
_length = (uint)Marshal.SizeOf(typeof(MemoryStatus));
#else
_length = (uint)Marshal.SizeOf<MemoryStatus>();
#endif
}
/// <summary>
/// Size of the structure, in bytes. You must set this member before calling GlobalMemoryStatusEx.
/// </summary>
private uint _length;
/// <summary>
/// Number between 0 and 100 that specifies the approximate percentage of physical
/// memory that is in use (0 indicates no memory use and 100 indicates full memory use).
/// </summary>
public uint MemoryLoad;
/// <summary>
/// Total size of physical memory, in bytes.
/// </summary>
public ulong TotalPhysical;
/// <summary>
/// Size of physical memory available, in bytes.
/// </summary>
public ulong AvailablePhysical;
/// <summary>
/// Size of the committed memory limit, in bytes. This is physical memory plus the
/// size of the page file, minus a small overhead.
/// </summary>
public ulong TotalPageFile;
/// <summary>
/// Size of available memory to commit, in bytes. The limit is ullTotalPageFile.
/// </summary>
public ulong AvailablePageFile;
/// <summary>
/// Total size of the user mode portion of the virtual address space of the calling process, in bytes.
/// </summary>
public ulong TotalVirtual;
/// <summary>
/// Size of unreserved and uncommitted memory in the user mode portion of the virtual
/// address space of the calling process, in bytes.
/// </summary>
public ulong AvailableVirtual;
/// <summary>
/// Size of unreserved and uncommitted memory in the extended portion of the virtual
/// address space of the calling process, in bytes.
/// </summary>
public ulong AvailableExtendedVirtual;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_BASIC_INFORMATION
{
public uint ExitStatus;
public IntPtr PebBaseAddress;
public UIntPtr AffinityMask;
public int BasePriority;
public UIntPtr UniqueProcessId;
public UIntPtr InheritedFromUniqueProcessId;
public uint Size
{
get
{
unsafe
{
return (uint)sizeof(PROCESS_BASIC_INFORMATION);
}
}
}
};
/// <summary>
/// Contains information about a file or directory; used by GetFileAttributesEx.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct WIN32_FILE_ATTRIBUTE_DATA
{
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
internal uint ftLastAccessTimeLow;
internal uint ftLastAccessTimeHigh;
internal uint ftLastWriteTimeLow;
internal uint ftLastWriteTimeHigh;
internal uint fileSizeHigh;
internal uint fileSizeLow;
}
/// <summary>
/// Contains the security descriptor for an object and specifies whether
/// the handle retrieved by specifying this structure is inheritable.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal class SecurityAttributes
{
public SecurityAttributes()
{
#if (CLR2COMPATIBILITY)
_nLength = (uint)Marshal.SizeOf(typeof(SecurityAttributes));
#else
_nLength = (uint)Marshal.SizeOf<SecurityAttributes>();
#endif
}
private uint _nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
private class SystemInformationData
{
/// <summary>
/// Architecture as far as the current process is concerned.
/// It's x86 in wow64 (native architecture is x64 in that case).
/// Otherwise it's the same as the native architecture.
/// </summary>
public readonly ProcessorArchitectures ProcessorArchitectureType;
/// <summary>
/// Actual architecture of the system.
/// </summary>
public readonly ProcessorArchitectures ProcessorArchitectureTypeNative;
/// <summary>
/// Convert SYSTEM_INFO architecture values to the internal enum
/// </summary>
/// <param name="arch"></param>
/// <returns></returns>
private static ProcessorArchitectures ConvertSystemArchitecture(ushort arch)
{
return arch switch
{
PROCESSOR_ARCHITECTURE_INTEL => ProcessorArchitectures.X86,
PROCESSOR_ARCHITECTURE_AMD64 => ProcessorArchitectures.X64,
PROCESSOR_ARCHITECTURE_ARM => ProcessorArchitectures.ARM,
PROCESSOR_ARCHITECTURE_IA64 => ProcessorArchitectures.IA64,
PROCESSOR_ARCHITECTURE_ARM64 => ProcessorArchitectures.ARM64,
_ => ProcessorArchitectures.Unknown,
};
}
/// <summary>
/// Read system info values
/// </summary>
public SystemInformationData()
{
ProcessorArchitectureType = ProcessorArchitectures.Unknown;
ProcessorArchitectureTypeNative = ProcessorArchitectures.Unknown;
if (IsWindows)
{
var systemInfo = new SYSTEM_INFO();
GetSystemInfo(ref systemInfo);
ProcessorArchitectureType = ConvertSystemArchitecture(systemInfo.wProcessorArchitecture);
GetNativeSystemInfo(ref systemInfo);
ProcessorArchitectureTypeNative = ConvertSystemArchitecture(systemInfo.wProcessorArchitecture);
}
else
{
ProcessorArchitectures processorArchitecture = ProcessorArchitectures.Unknown;
#if !NET35
// Get the architecture from the runtime.
processorArchitecture = RuntimeInformation.OSArchitecture switch
{
Architecture.Arm => ProcessorArchitectures.ARM,
Architecture.Arm64 => ProcessorArchitectures.ARM64,
Architecture.X64 => ProcessorArchitectures.X64,
Architecture.X86 => ProcessorArchitectures.X86,
_ => ProcessorArchitectures.Unknown,
};
#endif
// Fall back to 'uname -m' to get the architecture.
if (processorArchitecture == ProcessorArchitectures.Unknown)
{
try
{
// On Unix run 'uname -m' to get the architecture. It's common for Linux and Mac
using (
var proc =
Process.Start(
new ProcessStartInfo("uname")
{
Arguments = "-m",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}))
{
string arch = null;
if (proc != null)
{
arch = proc.StandardOutput.ReadLine();
proc.WaitForExit();
}
if (!string.IsNullOrEmpty(arch))
{
if (arch.StartsWith("x86_64", StringComparison.OrdinalIgnoreCase))
{
ProcessorArchitectureType = ProcessorArchitectures.X64;
}
else if (arch.StartsWith("ia64", StringComparison.OrdinalIgnoreCase))
{
ProcessorArchitectureType = ProcessorArchitectures.IA64;
}
else if (arch.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
{
ProcessorArchitectureType = ProcessorArchitectures.ARM;
}
else if (arch.StartsWith("aarch64", StringComparison.OrdinalIgnoreCase))
{
ProcessorArchitectureType = ProcessorArchitectures.ARM64;
}
else if (arch.StartsWith("i", StringComparison.OrdinalIgnoreCase)
&& arch.EndsWith("86", StringComparison.OrdinalIgnoreCase))
{
ProcessorArchitectureType = ProcessorArchitectures.X86;
}
}
}
}
catch
{
// Best effort: fall back to Unknown
}
}
ProcessorArchitectureTypeNative = ProcessorArchitectureType = processorArchitecture;
}
}
}
public static int GetLogicalCoreCount()
{
int numberOfCpus = Environment.ProcessorCount;
#if !MONO
// .NET on Windows returns a core count limited to the current NUMA node
// https://github.com/dotnet/runtime/issues/29686
// so always double-check it.
if (IsWindows)
{
var result = GetLogicalCoreCountOnWindows();
if (result != -1)
{
numberOfCpus = result;
}
}
#endif
return numberOfCpus;
}
/// <summary>
/// Get the exact physical core count on Windows
/// Useful for getting the exact core count in 32 bits processes,
/// as Environment.ProcessorCount has a 32-core limit in that case.
/// https://github.com/dotnet/runtime/blob/221ad5b728f93489655df290c1ea52956ad8f51c/src/libraries/System.Runtime.Extensions/src/System/Environment.Windows.cs#L171-L210
/// </summary>
[SupportedOSPlatform("windows")]
private unsafe static int GetLogicalCoreCountOnWindows()
{
uint len = 0;
const int ERROR_INSUFFICIENT_BUFFER = 122;
if (!GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore, IntPtr.Zero, ref len) &&
Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
{
// Allocate that much space
var buffer = new byte[len];
fixed (byte* bufferPtr = buffer)
{
// Call GetLogicalProcessorInformationEx with the allocated buffer
if (GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore, (IntPtr)bufferPtr, ref len))
{
// Walk each SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX in the buffer, where the Size of each dictates how
// much space it's consuming. For each group relation, count the number of active processors in each of its group infos.
int processorCount = 0;
byte* ptr = bufferPtr;
byte* endPtr = bufferPtr + len;
while (ptr < endPtr)
{
var current = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr;
if (current->Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore)
{
// Flags is 0 if the core has a single logical proc, LTP_PC_SMT if more than one
// for now, assume "more than 1" == 2, as it has historically been for hyperthreading
processorCount += (current->Processor.Flags == 0) ? 1 : 2;
}
ptr += current->Size;
}
return processorCount;
}
}
}
return -1;
}
#endregion
#region Member data
internal static bool HasMaxPath => MaxPath == MAX_PATH;
/// <summary>
/// Gets the max path limit of the current OS.
/// </summary>
internal static int MaxPath
{
get
{
if (!IsMaxPathSet)
{
SetMaxPath();
}
return _maxPath;
}
}
/// <summary>
/// Cached value for MaxPath.
/// </summary>
private static int _maxPath;
private static bool IsMaxPathSet { get; set; }
private static readonly object MaxPathLock = new object();
private static void SetMaxPath()
{
lock (MaxPathLock)
{
if (!IsMaxPathSet)
{
bool isMaxPathRestricted = Traits.Instance.EscapeHatches.DisableLongPaths || IsMaxPathLegacyWindows();
_maxPath = isMaxPathRestricted ? MAX_PATH : int.MaxValue;
IsMaxPathSet = true;
}
}
}
internal static bool IsMaxPathLegacyWindows()
{
try
{
return IsWindows && !IsLongPathsEnabledRegistry();
}
catch
{
return true;
}
}
[SupportedOSPlatform("windows")]
private static bool IsLongPathsEnabledRegistry()
{
using (RegistryKey fileSystemKey = Registry.LocalMachine.OpenSubKey(WINDOWS_FILE_SYSTEM_REGISTRY_KEY))
{
object longPathsEnabledValue = fileSystemKey?.GetValue(WINDOWS_LONG_PATHS_ENABLED_VALUE_NAME, 0);
return fileSystemKey != null && Convert.ToInt32(longPathsEnabledValue) == 1;
}
}
/// <summary>
/// Cached value for IsUnixLike (this method is called frequently during evaluation).
/// </summary>
private static readonly bool s_isUnixLike = IsLinux || IsOSX || IsBSD;
/// <summary>
/// Gets a flag indicating if we are running under a Unix-like system (Mac, Linux, etc.)
/// </summary>
internal static bool IsUnixLike
{
get { return s_isUnixLike; }
}
/// <summary>
/// Gets a flag indicating if we are running under Linux
/// </summary>
[SupportedOSPlatformGuard("linux")]
internal static bool IsLinux
{
#if CLR2COMPATIBILITY
get { return false; }
#else
get { return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); }
#endif
}
/// <summary>
/// Gets a flag indicating if we are running under flavor of BSD (NetBSD, OpenBSD, FreeBSD)
/// </summary>
internal static bool IsBSD
{
#if CLR2COMPATIBILITY
get { return false; }
#else
get
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")) ||
RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")) ||
RuntimeInformation.IsOSPlatform(OSPlatform.Create("OPENBSD"));
}
#endif
}
private static readonly object IsMonoLock = new object();
private static bool? _isMono;
/// <summary>
/// Gets a flag indicating if we are running under MONO
/// </summary>
internal static bool IsMono
{
get
{
if (_isMono != null) return _isMono.Value;
lock (IsMonoLock)
{
if (_isMono == null)
{
// There could be potentially expensive TypeResolve events, so cache IsMono.
// Also, VS does not host Mono runtimes, so turn IsMono off when msbuild is running under VS
_isMono = !BuildEnvironmentState.s_runningInVisualStudio &&
Type.GetType("Mono.Runtime") != null;
}
}
return _isMono.Value;
}
}
#if !CLR2COMPATIBILITY
private static bool? _isWindows;
#endif
/// <summary>
/// Gets a flag indicating if we are running under some version of Windows
/// </summary>
[SupportedOSPlatformGuard("windows")]
internal static bool IsWindows
{
#if CLR2COMPATIBILITY
get { return true; }
#else
get
{
_isWindows ??= RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
return _isWindows.Value;
}
#endif
}
#if !CLR2COMPATIBILITY
private static bool? _isOSX;
#endif
/// <summary>
/// Gets a flag indicating if we are running under Mac OSX
/// </summary>
internal static bool IsOSX
{
#if CLR2COMPATIBILITY
get { return false; }
#else
get
{
_isOSX ??= RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
return _isOSX.Value;
}
#endif
}
/// <summary>
/// Gets a string for the current OS. This matches the OS env variable
/// for Windows (Windows_NT).
/// </summary>
internal static string OSName
{
get { return IsWindows ? "Windows_NT" : "Unix"; }
}
/// <summary>
/// Framework named as presented to users (for example in version info).
/// </summary>
internal static string FrameworkName
{
get
{
#if RUNTIME_TYPE_NETCORE
const string frameworkName = ".NET";
#elif MONO
const string frameworkName = "Mono";
#else
const string frameworkName = ".NET Framework";
#endif
return frameworkName;
}
}
/// <summary>
/// OS name that can be used for the msbuildExtensionsPathSearchPaths element
/// for a toolset
/// </summary>
internal static string GetOSNameForExtensionsPath()
{
return IsOSX ? "osx" : IsUnixLike ? "unix" : "windows";
}
internal static bool OSUsesCaseSensitivePaths
{
get { return IsLinux; }
}
/// <summary>
/// The base directory for all framework paths in Mono
/// </summary>
private static string s_frameworkBasePath;
/// <summary>
/// The directory of the current framework
/// </summary>
private static string s_frameworkCurrentPath;
/// <summary>
/// Gets the currently running framework path
/// </summary>
internal static string FrameworkCurrentPath
{
get
{
if (s_frameworkCurrentPath == null)
{
var baseTypeLocation = AssemblyUtilities.GetAssemblyLocation(typeof(string).GetTypeInfo().Assembly);
s_frameworkCurrentPath =
Path.GetDirectoryName(baseTypeLocation)
?? string.Empty;
}
return s_frameworkCurrentPath;
}
}
/// <summary>
/// Gets the base directory of all Mono frameworks
/// </summary>
internal static string FrameworkBasePath
{
get
{
if (s_frameworkBasePath == null)
{
var dir = FrameworkCurrentPath;
if (dir != string.Empty)
{
dir = Path.GetDirectoryName(dir);
}
s_frameworkBasePath = dir ?? string.Empty;
}
return s_frameworkBasePath;
}
}
/// <summary>
/// System information, initialized when required.
/// </summary>
/// <remarks>
/// Initially implemented as <see cref="Lazy{SystemInformationData}"/>, but
/// that's .NET 4+, and this is used in MSBuildTaskHost.
/// </remarks>
private static SystemInformationData SystemInformation
{
get
{
if (!_systemInformationInitialized)
{
lock (SystemInformationLock)
{
if (!_systemInformationInitialized)
{
_systemInformation = new SystemInformationData();
_systemInformationInitialized = true;
}
}
}
return _systemInformation;
}
}
private static SystemInformationData _systemInformation;
private static bool _systemInformationInitialized;
private static readonly object SystemInformationLock = new object();
/// <summary>
/// Architecture getter
/// </summary>
internal static ProcessorArchitectures ProcessorArchitecture => SystemInformation.ProcessorArchitectureType;
/// <summary>
/// Native architecture getter
/// </summary>
internal static ProcessorArchitectures ProcessorArchitectureNative => SystemInformation.ProcessorArchitectureTypeNative;
#endregion
#region Wrapper methods
[DllImport("kernel32.dll", SetLastError = true)]
[SupportedOSPlatform("windows")]
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport("kernel32.dll", SetLastError = true)]
[SupportedOSPlatform("windows")]
internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo);
[DllImport("kernel32.dll", SetLastError = true)]
[SupportedOSPlatform("windows")]
internal static extern bool GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP RelationshipType, IntPtr Buffer, ref uint ReturnedLength);
/// <summary>
/// Get the last write time of the fullpath to a directory. If the pointed path is not a directory, or
/// if the directory does not exist, then false is returned and fileModifiedTimeUtc is set DateTime.MinValue.
/// </summary>
/// <param name="fullPath">Full path to the file in the filesystem</param>
/// <param name="fileModifiedTimeUtc">The UTC last write time for the directory</param>
internal static bool GetLastWriteDirectoryUtcTime(string fullPath, out DateTime fileModifiedTimeUtc)
{
// This code was copied from the reference manager, if there is a bug fix in that code, see if the same fix should also be made
// there
if (IsWindows)
{
fileModifiedTimeUtc = DateTime.MinValue;
WIN32_FILE_ATTRIBUTE_DATA data = new WIN32_FILE_ATTRIBUTE_DATA();
bool success = GetFileAttributesEx(fullPath, 0, ref data);
if (success)
{
if ((data.fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
long dt = ((long)(data.ftLastWriteTimeHigh) << 32) | ((long)data.ftLastWriteTimeLow);
fileModifiedTimeUtc = DateTime.FromFileTimeUtc(dt);
}
else
{
// Path does not point to a directory
success = false;
}
}
return success;
}
if (Directory.Exists(fullPath))
{
fileModifiedTimeUtc = Directory.GetLastWriteTimeUtc(fullPath);
return true;
}
else
{
fileModifiedTimeUtc = DateTime.MinValue;
return false;
}
}
/// <summary>
/// Takes the path and returns the short path
/// </summary>
internal static string GetShortFilePath(string path)
{
if (!IsWindows)
{
return path;
}
if (path != null)
{
int length = GetShortPathName(path, null, 0);
int errorCode = Marshal.GetLastWin32Error();
if (length > 0)
{
char[] fullPathBuffer = new char[length];
length = GetShortPathName(path, fullPathBuffer, length);
errorCode = Marshal.GetLastWin32Error();
if (length > 0)
{
string fullPath = new(fullPathBuffer, 0, length);
path = fullPath;
}
}
if (length == 0 && errorCode != 0)
{
ThrowExceptionForErrorCode(errorCode);
}
}
return path;
}
/// <summary>
/// Takes the path and returns a full path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
[SupportedOSPlatform("windows")]
internal static string GetLongFilePath(string path)
{
if (IsUnixLike)
{
return path;
}
if (path != null)
{
int length = GetLongPathName(path, null, 0);
int errorCode = Marshal.GetLastWin32Error();