1 // ==++==
2 //
3 //   Copyright (c) Microsoft Corporation.  All rights reserved.
4 //
5 // ==--==
6 /*============================================================
7 **
8 ** Class:  Microsoft.Win32.Win32Native
9 **
10 **
11 ** Purpose: The CLR wrapper for all Win32 as well as
12 **          ROTOR-style Unix PAL, etc. native operations
13 **
14 **
15 ===========================================================*/
16 /**
17  * Notes to PInvoke users:  Getting the syntax exactly correct is crucial, and
18  * more than a little confusing.  Here's some guidelines.
19  *
20  * For handles, you should use a SafeHandle subclass specific to your handle
21  * type.  For files, we have the following set of interesting definitions:
22  *
23  *  [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
24  *  private static extern SafeFileHandle CreateFile(...);
25  *
26  *  [DllImport(KERNEL32, SetLastError=true)]
27  *  unsafe internal static extern int ReadFile(SafeFileHandle handle, ...);
28  *
29  *  [DllImport(KERNEL32, SetLastError=true)]
30  *  internal static extern bool CloseHandle(IntPtr handle);
31  *
32  * P/Invoke will create the SafeFileHandle instance for you and assign the
33  * return value from CreateFile into the handle atomically.  When we call
34  * ReadFile, P/Invoke will increment a ref count, make the call, then decrement
35  * it (preventing handle recycling vulnerabilities).  Then SafeFileHandle's
36  * ReleaseHandle method will call CloseHandle, passing in the handle field
37  * as an IntPtr.
38  *
39  * If for some reason you cannot use a SafeHandle subclass for your handles,
40  * then use IntPtr as the handle type (or possibly HandleRef - understand when
41  * to use GC.KeepAlive).  If your code will run in SQL Server (or any other
42  * long-running process that can't be recycled easily), use a constrained
43  * execution region to prevent thread aborts while allocating your
44  * handle, and consider making your handle wrapper subclass
45  * CriticalFinalizerObject to ensure you can free the handle.  As you can
46  * probably guess, SafeHandle  will save you a lot of headaches if your code
47  * needs to be robust to thread aborts and OOM.
48  *
49  *
50  * If you have a method that takes a native struct, you have two options for
51  * declaring that struct.  You can make it a value type ('struct' in CSharp),
52  * or a reference type ('class').  This choice doesn't seem very interesting,
53  * but your function prototype must use different syntax depending on your
54  * choice.  For example, if your native method is prototyped as such:
55  *
56  *    bool GetVersionEx(OSVERSIONINFO & lposvi);
57  *
58  *
59  * you must use EITHER THIS OR THE NEXT syntax:
60  *
61  *    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
62  *    internal struct OSVERSIONINFO {  ...  }
63  *
64  *    [DllImport(KERNEL32, CharSet=CharSet.Auto)]
65  *    internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi);
66  *
67  * OR:
68  *
69  *    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
70  *    internal class OSVERSIONINFO {  ...  }
71  *
72  *    [DllImport(KERNEL32, CharSet=CharSet.Auto)]
73  *    internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi);
74  *
75  * Note that classes require being marked as [In, Out] while value types must
76  * be passed as ref parameters.
77  *
78  * Also note the CharSet.Auto on GetVersionEx - while it does not take a String
79  * as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so
80  * the size of the struct varies on different platforms, and there's a
81  * GetVersionExA & a GetVersionExW.  Also, the OSVERSIONINFO struct has a sizeof
82  * field so the OS can ensure you've passed in the correctly-sized copy of an
83  * OSVERSIONINFO.  You must explicitly set this using Marshal.SizeOf(Object);
84  *
85  * For security reasons, if you're making a P/Invoke method to a Win32 method
86  * that takes an ANSI String and that String is the name of some resource you've
87  * done a security check on (such as a file name), you want to disable best fit
88  * mapping in WideCharToMultiByte.  Do this by setting BestFitMapping=false
89  * in your DllImportAttribute.
90  */
91 
92 namespace Microsoft.Win32 {
93     using System;
94     using System.Security;
95     using System.Security.Principal;
96     using System.Text;
97     using System.Configuration.Assemblies;
98     using System.Runtime.Remoting;
99     using System.Runtime.InteropServices;
100     using System.Threading;
101     using Microsoft.Win32.SafeHandles;
102     using System.Runtime.CompilerServices;
103     using System.Runtime.ConstrainedExecution;
104     using System.Runtime.Versioning;
105 
106     using BOOL = System.Int32;
107     using DWORD = System.UInt32;
108     using ULONG = System.UInt32;
109 
110     /**
111      * Win32 encapsulation for MSCORLIB.
112      */
113     // Remove the default demands for all P/Invoke methods with this
114     // global declaration on the class.
115     // <
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128     [System.Security.SecurityCritical]
129     [SuppressUnmanagedCodeSecurityAttribute()]
130     internal static class Win32Native {
131 
132 #if !FEATURE_PAL
133         internal const int KEY_QUERY_VALUE        = 0x0001;
134         internal const int KEY_SET_VALUE          = 0x0002;
135         internal const int KEY_CREATE_SUB_KEY     = 0x0004;
136         internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
137         internal const int KEY_NOTIFY             = 0x0010;
138         internal const int KEY_CREATE_LINK        = 0x0020;
139         internal const int KEY_READ               =((STANDARD_RIGHTS_READ       |
140                                                            KEY_QUERY_VALUE            |
141                                                            KEY_ENUMERATE_SUB_KEYS     |
142                                                            KEY_NOTIFY)
143                                                           &
144                                                           (~SYNCHRONIZE));
145 
146         internal const int KEY_WRITE              =((STANDARD_RIGHTS_WRITE      |
147                                                            KEY_SET_VALUE              |
148                                                            KEY_CREATE_SUB_KEY)
149                                                           &
150                                                           (~SYNCHRONIZE));
151         internal const int KEY_WOW64_64KEY        = 0x0100;     //
152         internal const int KEY_WOW64_32KEY        = 0x0200;     //
153         internal const int REG_OPTION_NON_VOLATILE= 0x0000;     // (default) keys are persisted beyond reboot/unload
154         internal const int REG_OPTION_VOLATILE    = 0x0001;     // All keys created by the function are volatile
155         internal const int REG_OPTION_CREATE_LINK = 0x0002;     // They key is a symbolic link
156         internal const int REG_OPTION_BACKUP_RESTORE = 0x0004;  // Use SE_BACKUP_NAME process special privileges
157         internal const int REG_NONE                    = 0;     // No value type
158         internal const int REG_SZ                      = 1;     // Unicode nul terminated string
159         internal const int REG_EXPAND_SZ               = 2;     // Unicode nul terminated string
160         // (with environment variable references)
161         internal const int REG_BINARY                  = 3;     // Free form binary
162         internal const int REG_DWORD                   = 4;     // 32-bit number
163         internal const int REG_DWORD_LITTLE_ENDIAN     = 4;     // 32-bit number (same as REG_DWORD)
164         internal const int REG_DWORD_BIG_ENDIAN        = 5;     // 32-bit number
165         internal const int REG_LINK                    = 6;     // Symbolic Link (unicode)
166         internal const int REG_MULTI_SZ                = 7;     // Multiple Unicode strings
167         internal const int REG_RESOURCE_LIST           = 8;     // Resource list in the resource map
168         internal const int REG_FULL_RESOURCE_DESCRIPTOR  = 9;   // Resource list in the hardware description
169         internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10;
170         internal const int REG_QWORD                   = 11;    // 64-bit number
171 
172         internal const int HWND_BROADCAST              = 0xffff;
173         internal const int WM_SETTINGCHANGE            = 0x001A;
174 
175         // CryptProtectMemory and CryptUnprotectMemory.
176         internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE    = 16;
177         internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS  = 0x00;
178         internal const uint CRYPTPROTECTMEMORY_CROSS_PROCESS = 0x01;
179         internal const uint CRYPTPROTECTMEMORY_SAME_LOGON    = 0x02;
180 
181         // Security Quality of Service flags
182         internal const int SECURITY_ANONYMOUS       = ((int)SECURITY_IMPERSONATION_LEVEL.Anonymous << 16);
183         internal const int SECURITY_SQOS_PRESENT    = 0x00100000;
184 
185         // Access Control library.
186         internal const string MICROSOFT_KERBEROS_NAME = "Kerberos";
187         internal const uint ANONYMOUS_LOGON_LUID = 0x3e6;
188 
189         internal const int SECURITY_ANONYMOUS_LOGON_RID    = 0x00000007;
190         internal const int SECURITY_AUTHENTICATED_USER_RID = 0x0000000B;
191         internal const int SECURITY_LOCAL_SYSTEM_RID       = 0x00000012;
192         internal const int SECURITY_BUILTIN_DOMAIN_RID     = 0x00000020;
193 
194         internal const uint SE_PRIVILEGE_DISABLED           = 0x00000000;
195         internal const uint SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001;
196         internal const uint SE_PRIVILEGE_ENABLED            = 0x00000002;
197         internal const uint SE_PRIVILEGE_USED_FOR_ACCESS    = 0x80000000;
198 
199         internal const uint SE_GROUP_MANDATORY          = 0x00000001;
200         internal const uint SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002;
201         internal const uint SE_GROUP_ENABLED            = 0x00000004;
202         internal const uint SE_GROUP_OWNER              = 0x00000008;
203         internal const uint SE_GROUP_USE_FOR_DENY_ONLY  = 0x00000010;
204         internal const uint SE_GROUP_LOGON_ID           = 0xC0000000;
205         internal const uint SE_GROUP_RESOURCE           = 0x20000000;
206 
207         internal const uint DUPLICATE_CLOSE_SOURCE      = 0x00000001;
208         internal const uint DUPLICATE_SAME_ACCESS       = 0x00000002;
209         internal const uint DUPLICATE_SAME_ATTRIBUTES   = 0x00000004;
210 #endif
211 
212         // TimeZone
213         internal const int TIME_ZONE_ID_INVALID = -1;
214         internal const int TIME_ZONE_ID_UNKNOWN = 0;
215         internal const int TIME_ZONE_ID_STANDARD = 1;
216         internal const int TIME_ZONE_ID_DAYLIGHT = 2;
217         internal const int MAX_PATH = 260;
218 
219         internal const int MUI_LANGUAGE_ID = 0x4;
220         internal const int MUI_LANGUAGE_NAME = 0x8;
221         internal const int MUI_PREFERRED_UI_LANGUAGES = 0x10;
222         internal const int MUI_INSTALLED_LANGUAGES = 0x20;
223         internal const int MUI_ALL_LANGUAGES = 0x40;
224         internal const int MUI_LANG_NEUTRAL_PE_FILE = 0x100;
225         internal const int MUI_NON_LANG_NEUTRAL_FILE = 0x200;
226 
227         internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
228         internal const int LOAD_STRING_MAX_LENGTH = 500;
229 
230         [StructLayout(LayoutKind.Sequential)]
231         internal struct SystemTime {
232             [MarshalAs(UnmanagedType.U2)]
233             public short Year;
234             [MarshalAs(UnmanagedType.U2)]
235             public short Month;
236             [MarshalAs(UnmanagedType.U2)]
237             public short DayOfWeek;
238             [MarshalAs(UnmanagedType.U2)]
239             public short Day;
240             [MarshalAs(UnmanagedType.U2)]
241             public short Hour;
242             [MarshalAs(UnmanagedType.U2)]
243             public short Minute;
244             [MarshalAs(UnmanagedType.U2)]
245             public short Second;
246             [MarshalAs(UnmanagedType.U2)]
247             public short Milliseconds;
248         }
249 
250         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
251         internal struct TimeZoneInformation {
252             [MarshalAs(UnmanagedType.I4)]
253             public Int32 Bias;
254             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
255             public string StandardName;
256             public SystemTime StandardDate;
257             [MarshalAs(UnmanagedType.I4)]
258             public Int32 StandardBias;
259             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
260             public string DaylightName;
261             public SystemTime DaylightDate;
262             [MarshalAs(UnmanagedType.I4)]
263             public Int32 DaylightBias;
264 
TimeZoneInformationMicrosoft.Win32.Win32Native.TimeZoneInformation265             public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) {
266                 Bias = dtzi.Bias;
267                 StandardName = dtzi.StandardName;
268                 StandardDate = dtzi.StandardDate;
269                 StandardBias = dtzi.StandardBias;
270                 DaylightName = dtzi.DaylightName;
271                 DaylightDate = dtzi.DaylightDate;
272                 DaylightBias = dtzi.DaylightBias;
273             }
274         }
275 
276 
277         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
278         internal struct DynamicTimeZoneInformation {
279             [MarshalAs(UnmanagedType.I4)]
280             public Int32 Bias;
281             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
282             public string StandardName;
283             public SystemTime StandardDate;
284             [MarshalAs(UnmanagedType.I4)]
285             public Int32 StandardBias;
286             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
287             public string DaylightName;
288             public SystemTime DaylightDate;
289             [MarshalAs(UnmanagedType.I4)]
290             public Int32 DaylightBias;
291             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
292             public string TimeZoneKeyName;
293             [MarshalAs(UnmanagedType.Bool)]
294             public bool DynamicDaylightTimeDisabled;
295         }
296 
297 
298         [StructLayout(LayoutKind.Sequential)]
299         internal struct RegistryTimeZoneInformation {
300             [MarshalAs(UnmanagedType.I4)]
301             public Int32 Bias;
302             [MarshalAs(UnmanagedType.I4)]
303             public Int32 StandardBias;
304             [MarshalAs(UnmanagedType.I4)]
305             public Int32 DaylightBias;
306             public SystemTime StandardDate;
307             public SystemTime DaylightDate;
308 
RegistryTimeZoneInformationMicrosoft.Win32.Win32Native.RegistryTimeZoneInformation309             public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) {
310                 Bias = tzi.Bias;
311                 StandardDate = tzi.StandardDate;
312                 StandardBias = tzi.StandardBias;
313                 DaylightDate = tzi.DaylightDate;
314                 DaylightBias = tzi.DaylightBias;
315             }
316 
RegistryTimeZoneInformationMicrosoft.Win32.Win32Native.RegistryTimeZoneInformation317             public RegistryTimeZoneInformation(Byte[] bytes) {
318                 //
319                 // typedef struct _REG_TZI_FORMAT {
320                 // [00-03]    LONG Bias;
321                 // [04-07]    LONG StandardBias;
322                 // [08-11]    LONG DaylightBias;
323                 // [12-27]    SYSTEMTIME StandardDate;
324                 // [12-13]        WORD wYear;
325                 // [14-15]        WORD wMonth;
326                 // [16-17]        WORD wDayOfWeek;
327                 // [18-19]        WORD wDay;
328                 // [20-21]        WORD wHour;
329                 // [22-23]        WORD wMinute;
330                 // [24-25]        WORD wSecond;
331                 // [26-27]        WORD wMilliseconds;
332                 // [28-43]    SYSTEMTIME DaylightDate;
333                 // [28-29]        WORD wYear;
334                 // [30-31]        WORD wMonth;
335                 // [32-33]        WORD wDayOfWeek;
336                 // [34-35]        WORD wDay;
337                 // [36-37]        WORD wHour;
338                 // [38-39]        WORD wMinute;
339                 // [40-41]        WORD wSecond;
340                 // [42-43]        WORD wMilliseconds;
341                 // } REG_TZI_FORMAT;
342                 //
343                 if (bytes == null || bytes.Length != 44) {
344                     throw new ArgumentException(Environment.GetResourceString("Argument_InvalidREG_TZI_FORMAT"), "bytes");
345                 }
346                 Bias = BitConverter.ToInt32(bytes, 0);
347                 StandardBias = BitConverter.ToInt32(bytes, 4);
348                 DaylightBias = BitConverter.ToInt32(bytes, 8);
349 
350                 StandardDate.Year = BitConverter.ToInt16(bytes, 12);
351                 StandardDate.Month = BitConverter.ToInt16(bytes, 14);
352                 StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 16);
353                 StandardDate.Day = BitConverter.ToInt16(bytes, 18);
354                 StandardDate.Hour = BitConverter.ToInt16(bytes, 20);
355                 StandardDate.Minute = BitConverter.ToInt16(bytes, 22);
356                 StandardDate.Second = BitConverter.ToInt16(bytes, 24);
357                 StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 26);
358 
359                 DaylightDate.Year = BitConverter.ToInt16(bytes, 28);
360                 DaylightDate.Month = BitConverter.ToInt16(bytes, 30);
361                 DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 32);
362                 DaylightDate.Day = BitConverter.ToInt16(bytes, 34);
363                 DaylightDate.Hour = BitConverter.ToInt16(bytes, 36);
364                 DaylightDate.Minute = BitConverter.ToInt16(bytes, 38);
365                 DaylightDate.Second = BitConverter.ToInt16(bytes, 40);
366                 DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 42);
367             }
368         }
369 
370         // end of TimeZone
371 
372 
373         // Win32 ACL-related constants:
374         internal const int READ_CONTROL                    = 0x00020000;
375         internal const int SYNCHRONIZE                     = 0x00100000;
376 
377         internal const int STANDARD_RIGHTS_READ            = READ_CONTROL;
378         internal const int STANDARD_RIGHTS_WRITE           = READ_CONTROL;
379 
380         // STANDARD_RIGHTS_REQUIRED  (0x000F0000L)
381         // SEMAPHORE_ALL_ACCESS          (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
382 
383         // SEMAPHORE and Event both use 0x0002
384         // MUTEX uses 0x001 (MUTANT_QUERY_STATE)
385 
386         // Note that you may need to specify the SYNCHRONIZE bit as well
387         // to be able to open a synchronization primitive.
388         internal const int SEMAPHORE_MODIFY_STATE = 0x00000002;
389         internal const int EVENT_MODIFY_STATE     = 0x00000002;
390         internal const int MUTEX_MODIFY_STATE     = 0x00000001;
391         internal const int MUTEX_ALL_ACCESS       = 0x001F0001;
392 
393 
394         internal const int LMEM_FIXED    = 0x0000;
395         internal const int LMEM_ZEROINIT = 0x0040;
396         internal const int LPTR          = (LMEM_FIXED | LMEM_ZEROINIT);
397 
398         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
399         internal class OSVERSIONINFO {
OSVERSIONINFO()400             internal OSVERSIONINFO() {
401                 OSVersionInfoSize = (int)Marshal.SizeOf(this);
402             }
403 
404             // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
405             internal int OSVersionInfoSize = 0;
406             internal int MajorVersion = 0;
407             internal int MinorVersion = 0;
408             internal int BuildNumber = 0;
409             internal int PlatformId = 0;
410             [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
411             internal String CSDVersion = null;
412         }
413 
414         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
415         internal class OSVERSIONINFOEX {
416 
OSVERSIONINFOEX()417             public OSVERSIONINFOEX() {
418                 OSVersionInfoSize = (int)Marshal.SizeOf(this);
419             }
420 
421             // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
422             internal int OSVersionInfoSize = 0;
423             internal int MajorVersion = 0;
424             internal int MinorVersion = 0;
425             internal int BuildNumber = 0;
426             internal int PlatformId = 0;
427             [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
428             internal string CSDVersion = null;
429             internal ushort ServicePackMajor = 0;
430             internal ushort ServicePackMinor = 0;
431             internal short SuiteMask = 0;
432             internal byte ProductType = 0;
433             internal byte Reserved = 0;
434         }
435 
436             [StructLayout(LayoutKind.Sequential)]
437             internal struct SYSTEM_INFO {
438             internal int dwOemId;    // This is a union of a DWORD and a struct containing 2 WORDs.
439             internal int dwPageSize;
440             internal IntPtr lpMinimumApplicationAddress;
441             internal IntPtr lpMaximumApplicationAddress;
442             internal IntPtr dwActiveProcessorMask;
443             internal int dwNumberOfProcessors;
444             internal int dwProcessorType;
445             internal int dwAllocationGranularity;
446             internal short wProcessorLevel;
447             internal short wProcessorRevision;
448         }
449 
450         [StructLayout(LayoutKind.Sequential)]
451         internal class SECURITY_ATTRIBUTES {
452             internal int nLength = 0;
453             // don't remove null, or this field will disappear in bcl.small
454             internal unsafe byte * pSecurityDescriptor = null;
455             internal int bInheritHandle = 0;
456         }
457 
458         [Serializable]
459         [StructLayout(LayoutKind.Sequential)]
460         internal struct WIN32_FILE_ATTRIBUTE_DATA {
461             internal int fileAttributes;
462             internal uint ftCreationTimeLow;
463             internal uint ftCreationTimeHigh;
464             internal uint ftLastAccessTimeLow;
465             internal uint ftLastAccessTimeHigh;
466             internal uint ftLastWriteTimeLow;
467             internal uint ftLastWriteTimeHigh;
468             internal int fileSizeHigh;
469             internal int fileSizeLow;
470 
471             [System.Security.SecurityCritical]
PopulateFromMicrosoft.Win32.Win32Native.WIN32_FILE_ATTRIBUTE_DATA472             internal void PopulateFrom(WIN32_FIND_DATA findData) {
473                 // Copy the information to data
474                 fileAttributes = findData.dwFileAttributes;
475                 ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime;
476                 ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime;
477                 ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime;
478                 ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime;
479                 ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime;
480                 ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime;
481                 fileSizeHigh = findData.nFileSizeHigh;
482                 fileSizeLow = findData.nFileSizeLow;
483             }
484         }
485 
486         [StructLayout(LayoutKind.Sequential)]
487         internal struct FILE_TIME {
FILE_TIMEMicrosoft.Win32.Win32Native.FILE_TIME488             public FILE_TIME(long fileTime) {
489                 ftTimeLow = (uint) fileTime;
490                 ftTimeHigh = (uint) (fileTime >> 32);
491             }
492 
ToTicksMicrosoft.Win32.Win32Native.FILE_TIME493             public long ToTicks() {
494                 return ((long) ftTimeHigh << 32) + ftTimeLow;
495             }
496 
497             internal uint ftTimeLow;
498             internal uint ftTimeHigh;
499         }
500 
501 #if !FEATURE_PAL
502 
503         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
504         internal struct KERB_S4U_LOGON {
505             internal uint                   MessageType;
506             internal uint                   Flags;
507             internal UNICODE_INTPTR_STRING  ClientUpn;   // REQUIRED: UPN for client
508             internal UNICODE_INTPTR_STRING  ClientRealm; // Optional: Client Realm, if known
509         }
510 
511         [StructLayoutAttribute(LayoutKind.Sequential)]
512         internal struct LSA_OBJECT_ATTRIBUTES {
513             internal int Length;
514             internal IntPtr RootDirectory;
515             internal IntPtr ObjectName;
516             internal int Attributes;
517             internal IntPtr SecurityDescriptor;
518             internal IntPtr SecurityQualityOfService;
519         }
520 
521         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
522         internal struct UNICODE_STRING {
523             internal ushort Length;
524             internal ushort MaximumLength;
525             [MarshalAs(UnmanagedType.LPWStr)] internal string Buffer;
526         }
527 
528         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
529         internal struct UNICODE_INTPTR_STRING {
530             /// <remarks>
531             ///     Note - this constructor extracts the raw pointer from the safe handle, so any
532             ///     strings created with this version of the constructor will be unsafe to use after the buffer
533             ///     has been freed.
534             /// </remarks>
535             [System.Security.SecurityCritical]  // auto-generated
UNICODE_INTPTR_STRINGMicrosoft.Win32.Win32Native.UNICODE_INTPTR_STRING536             internal UNICODE_INTPTR_STRING (int stringBytes, SafeLocalAllocHandle buffer) {
537                 BCLDebug.Assert(buffer == null || (stringBytes >= 0 && (ulong)stringBytes <= buffer.ByteLength),
538                                 "buffer == null || (stringBytes >= 0 && stringBytes <= buffer.ByteLength)");
539 
540                 this.Length = (ushort) stringBytes;
541                 this.MaxLength = (ushort) buffer.ByteLength;
542 
543                 // Marshaling with a SafePointer does not work correctly, so unfortunately we need to extract
544                 // the raw handle here.
545                 this.Buffer = buffer.DangerousGetHandle();
546             }
547 
548             /// <remarks>
549             ///     This constructor should be used for constructing UNICODE_STRING structures with pointers
550             ///     into a block of memory managed by a SafeHandle or the GC.  It shouldn't be used to own
551             ///     any memory on its own.
552             /// </remarks>
UNICODE_INTPTR_STRINGMicrosoft.Win32.Win32Native.UNICODE_INTPTR_STRING553             internal UNICODE_INTPTR_STRING(int stringBytes, IntPtr buffer) {
554                 BCLDebug.Assert((stringBytes == 0 && buffer == IntPtr.Zero) || (stringBytes > 0 && stringBytes <= UInt16.MaxValue && buffer != IntPtr.Zero),
555                                 "(stringBytes == 0 && buffer == IntPtr.Zero) || (stringBytes > 0 && stringBytes <= UInt16.MaxValue && buffer != IntPtr.Zero)");
556 
557                 this.Length = (ushort)stringBytes;
558                 this.MaxLength = (ushort)stringBytes;
559                 this.Buffer = buffer;
560             }
561 
562             internal ushort Length;
563             internal ushort MaxLength;
564             internal IntPtr Buffer;
565         }
566 
567         [StructLayout(LayoutKind.Sequential)]
568         internal struct LSA_TRANSLATED_NAME {
569             internal int Use;
570             internal UNICODE_INTPTR_STRING Name;
571             internal int DomainIndex;
572         }
573 
574         [StructLayoutAttribute(LayoutKind.Sequential)]
575         internal struct LSA_TRANSLATED_SID {
576             internal int Use;
577             internal uint Rid;
578             internal int DomainIndex;
579         }
580 
581         [StructLayoutAttribute(LayoutKind.Sequential)]
582         internal struct LSA_TRANSLATED_SID2 {
583             internal int Use;
584             internal IntPtr Sid;
585             internal int DomainIndex;
586             uint Flags;
587         }
588 
589         [StructLayout(LayoutKind.Sequential)]
590         internal struct LSA_TRUST_INFORMATION {
591             internal UNICODE_INTPTR_STRING Name;
592             internal IntPtr Sid;
593         }
594 
595         [StructLayout(LayoutKind.Sequential)]
596         internal struct LSA_REFERENCED_DOMAIN_LIST {
597             internal int Entries;
598             internal IntPtr Domains;
599         }
600 
601         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
602         internal struct LUID {
603             internal uint LowPart;
604             internal uint HighPart;
605         }
606 
607         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
608         internal struct LUID_AND_ATTRIBUTES {
609             internal LUID Luid;
610             internal uint Attributes;
611         }
612 
613         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
614         internal struct QUOTA_LIMITS {
615             internal IntPtr PagedPoolLimit;
616             internal IntPtr NonPagedPoolLimit;
617             internal IntPtr MinimumWorkingSetSize;
618             internal IntPtr MaximumWorkingSetSize;
619             internal IntPtr PagefileLimit;
620             internal IntPtr TimeLimit;
621         }
622 
623         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
624         internal struct SECURITY_LOGON_SESSION_DATA {
625             internal uint       Size;
626             internal LUID       LogonId;
627             internal UNICODE_INTPTR_STRING UserName;
628             internal UNICODE_INTPTR_STRING LogonDomain;
629             internal UNICODE_INTPTR_STRING AuthenticationPackage;
630             internal uint       LogonType;
631             internal uint       Session;
632             internal IntPtr     Sid;
633             internal long       LogonTime;
634         }
635 
636         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
637         internal struct SID_AND_ATTRIBUTES {
638             internal IntPtr Sid;
639             internal uint   Attributes;
640             internal static readonly long SizeOf = (long)Marshal.SizeOf(typeof(SID_AND_ATTRIBUTES));
641         }
642 
643         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
644         internal struct TOKEN_GROUPS {
645             internal uint GroupCount;
646             internal SID_AND_ATTRIBUTES Groups; // SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
647         }
648 
649         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
650         internal struct TOKEN_PRIMARY_GROUP
651         {
652             internal IntPtr PrimaryGroup;
653         }
654 
655         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
656         internal struct TOKEN_PRIVILEGE {
657             internal uint                PrivilegeCount;
658             internal LUID_AND_ATTRIBUTES Privilege;
659         }
660 
661         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
662         internal struct TOKEN_SOURCE {
663             private const int TOKEN_SOURCE_LENGTH = 8;
664 
665             [MarshalAs(UnmanagedType.ByValArray, SizeConst=TOKEN_SOURCE_LENGTH)]
666             internal char[] Name;
667             internal LUID   SourceIdentifier;
668         }
669 
670         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
671         internal struct TOKEN_STATISTICS {
672             internal LUID   TokenId;
673             internal LUID   AuthenticationId;
674             internal long   ExpirationTime;
675             internal uint   TokenType;
676             internal uint   ImpersonationLevel;
677             internal uint   DynamicCharged;
678             internal uint   DynamicAvailable;
679             internal uint   GroupCount;
680             internal uint   PrivilegeCount;
681             internal LUID   ModifiedId;
682         }
683 
684         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
685         internal struct TOKEN_USER {
686             internal SID_AND_ATTRIBUTES User;
687         }
688 
689         [StructLayout(LayoutKind.Sequential)]
690         internal struct MEMORYSTATUSEX {
691             // The length field must be set to the size of this data structure.
692             internal int length;
693             internal int memoryLoad;
694             internal ulong totalPhys;
695             internal ulong availPhys;
696             internal ulong totalPageFile;
697             internal ulong availPageFile;
698             internal ulong totalVirtual;
699             internal ulong availVirtual;
700             internal ulong availExtendedVirtual;
701         }
702 
703         [StructLayout(LayoutKind.Sequential)]
704         internal unsafe struct MEMORY_BASIC_INFORMATION {
705             internal void* BaseAddress;
706             internal void* AllocationBase;
707             internal uint AllocationProtect;
708             internal UIntPtr RegionSize;
709             internal uint State;
710             internal uint Protect;
711             internal uint Type;
712         }
713 #endif  // !FEATURE_PAL
714 
715         internal const String KERNEL32 = "kernel32.dll";
716         internal const String USER32   = "user32.dll";
717         internal const String ADVAPI32 = "advapi32.dll";
718         internal const String OLE32    = "ole32.dll";
719         internal const String OLEAUT32 = "oleaut32.dll";
720         internal const String SHELL32  = "shell32.dll";
721         internal const String SHIM     = "mscoree.dll";
722         internal const String CRYPT32  = "crypt32.dll";
723         internal const String SECUR32  = "secur32.dll";
724         internal const String NTDLL    = "ntdll.dll";
725 #if FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
726         internal const String MSCORWKS = "coreclr.dll";
727 #else //FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
728         internal const String MSCORWKS = "clr.dll";
729 #endif //FEATURE_MAIN_CLR_MODULE_USES_CORE_NAME
730 
731         // From WinBase.h
732         internal const int SEM_FAILCRITICALERRORS = 1;
733 
734         [DllImport(KERNEL32, SetLastError=true)]
735         [ResourceExposure(ResourceScope.None)]
GetSystemInfo(ref SYSTEM_INFO lpSystemInfo)736         internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
737 
738         [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=true)]
739         [ResourceExposure(ResourceScope.None)]
FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments)740         internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
741                     int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer,
742                     int nSize, IntPtr va_list_arguments);
743 
744         // Gets an error message for a Win32 error code.
GetMessage(int errorCode)745         internal static String GetMessage(int errorCode) {
746             StringBuilder sb = StringBuilderCache.Acquire(512);
747             int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
748                 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
749                 IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero);
750             if (result != 0) {
751                 // result is the # of characters copied to the StringBuilder.
752                 return StringBuilderCache.GetStringAndRelease(sb);
753             }
754             else {
755                 StringBuilderCache.Release(sb);
756                 return Environment.GetResourceString("UnknownError_Num", errorCode);
757             }
758         }
759 
760 #if FEATURE_PAL
761         [FriendAccessAllowed]  // Used by Silverlight networking stack in one place.
762 #endif // FEATURE_PAL
763         [DllImport(KERNEL32, EntryPoint="LocalAlloc")]
764         [ResourceExposure(ResourceScope.None)]
765         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes)766         internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes);
767 
768 #if !FEATURE_PAL
769         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
770         [ResourceExposure(ResourceScope.None)]
771         internal static extern
LocalAlloc( [In] int uFlags, [In] UIntPtr sizetdwBytes)772         SafeLocalAllocHandle LocalAlloc(
773             [In] int uFlags,
774             [In] UIntPtr sizetdwBytes);
775 #endif // !FEATURE_PAL
776 
777         [DllImport(KERNEL32, SetLastError=true)]
778         [ResourceExposure(ResourceScope.None)]
779         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
LocalFree(IntPtr handle)780         internal static extern IntPtr LocalFree(IntPtr handle);
781 
782         // MSDN says the length is a SIZE_T.
783         [DllImport(KERNEL32, EntryPoint = "RtlZeroMemory")]
784         [ResourceExposure(ResourceScope.None)]
785         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
ZeroMemory(IntPtr address, UIntPtr length)786         internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
787 
788 #if !FEATURE_PAL
GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)789         internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)
790         {
791             buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX));
792             return GlobalMemoryStatusExNative(ref buffer);
793         }
794 
795         [DllImport(KERNEL32, SetLastError=true, EntryPoint="GlobalMemoryStatusEx")]
796         [ResourceExposure(ResourceScope.None)]
GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer)797         private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer);
798 
799         [DllImport(KERNEL32, SetLastError=true)]
800         [ResourceExposure(ResourceScope.None)]
VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer)801         unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer);
802 
803         // VirtualAlloc should generally be avoided, but is needed in
804         // the MemoryFailPoint implementation (within a CER) to increase the
805         // size of the page file, ignoring any host memory allocators.
806         [DllImport(KERNEL32, SetLastError=true)]
807         [ResourceExposure(ResourceScope.Process)]
808         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode)809         unsafe internal static extern void * VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
810 
811         [DllImport(KERNEL32, SetLastError=true)]
812         [ResourceExposure(ResourceScope.Process)]
813         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode)814         unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode);
815 
816 
817 
818         // Note - do NOT use this to call methods.  Use P/Invoke, which will
819         // do much better things w.r.t. marshaling, pinning memory, security
820         // stuff, better interactions with thread aborts, etc.  This is used
821         // solely by DoesWin32MethodExist for avoiding try/catch EntryPointNotFoundException
822         // in scenarios where an OS Version check is insufficient
823         [DllImport(KERNEL32, CharSet=CharSet.Ansi, BestFitMapping=false, SetLastError=true, ExactSpelling=true)]
824         [ResourceExposure(ResourceScope.None)]
GetProcAddress(IntPtr hModule, String methodName)825         private static extern IntPtr GetProcAddress(IntPtr hModule, String methodName);
826 
827         [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)]
828         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
829         [ResourceExposure(ResourceScope.Process)]  // Is your module side-by-side?
GetModuleHandle(String moduleName)830         private static extern IntPtr GetModuleHandle(String moduleName);
831 
832         [System.Security.SecurityCritical]  // auto-generated
DoesWin32MethodExist(String moduleName, String methodName)833         internal static bool DoesWin32MethodExist(String moduleName, String methodName)
834         {
835             // GetModuleHandle does not increment the module's ref count, so we don't need to call FreeLibrary.
836             IntPtr hModule = Win32Native.GetModuleHandle(moduleName);
837             if (hModule == IntPtr.Zero) {
838                 BCLDebug.Assert(hModule != IntPtr.Zero, "GetModuleHandle failed.  Dll isn't loaded?");
839                 return false;
840             }
841             IntPtr functionPointer = Win32Native.GetProcAddress(hModule, methodName);
842             return (functionPointer != IntPtr.Zero);
843         }
844 #endif // !FEATURE_PAL
845 
846         // There is no need to call CloseProcess or to use a SafeHandle if you get the handle
847         // using GetCurrentProcess as it returns a pseudohandle
848         [DllImport(KERNEL32, SetLastError = true, CallingConvention = CallingConvention.Winapi)]
849         [return: MarshalAs(UnmanagedType.Bool)]
850         [ResourceExposure(ResourceScope.Machine)]
IsWow64Process( [In] IntPtr hSourceProcessHandle, [Out, MarshalAs(UnmanagedType.Bool)] out bool isWow64)851         internal static extern bool IsWow64Process(
852                    [In]
853                    IntPtr hSourceProcessHandle,
854                    [Out, MarshalAs(UnmanagedType.Bool)]
855                    out bool isWow64);
856 
857         [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false)]
858         [ResourceExposure(ResourceScope.Machine)]
GetTempPath(int bufferLen, [Out]StringBuilder buffer)859         internal static extern uint GetTempPath(int bufferLen, [Out]StringBuilder buffer);
860 
861         [DllImport(KERNEL32, CharSet=CharSet.Ansi, ExactSpelling=true, EntryPoint="lstrlenA")]
862         [ResourceExposure(ResourceScope.None)]
lstrlenA(IntPtr ptr)863         internal static extern int lstrlenA(IntPtr ptr);
864 
865         [DllImport(KERNEL32, CharSet=CharSet.Unicode, ExactSpelling=true, EntryPoint="lstrlenW")]
866         [ResourceExposure(ResourceScope.None)]
lstrlenW(IntPtr ptr)867         internal static extern int lstrlenW(IntPtr ptr);
868 
869         [DllImport(Win32Native.OLEAUT32, CharSet=CharSet.Unicode)]
870         [ResourceExposure(ResourceScope.None)]
871         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
SysAllocStringLen(String src, int len)872         internal static extern IntPtr SysAllocStringLen(String src, int len);  // BSTR
873 
874         [DllImport(Win32Native.OLEAUT32)]
875         [ResourceExposure(ResourceScope.None)]
876         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
SysAllocStringByteLen(byte[] str, uint len)877         internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len);  // BSTR
878 
879         [DllImport(Win32Native.OLEAUT32)]
880         [ResourceExposure(ResourceScope.None)]
881         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SysStringByteLen(IntPtr bstr)882         internal static extern uint SysStringByteLen(IntPtr bstr);
883 
884         [DllImport(Win32Native.OLEAUT32)]
885         [ResourceExposure(ResourceScope.None)]
886         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SysStringLen(IntPtr bstr)887         internal static extern uint SysStringLen(IntPtr bstr);
888 
889 #if !FEATURE_PAL
890         [DllImport(Win32Native.OLEAUT32)]
891         [ResourceExposure(ResourceScope.None)]
892         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SysStringLen(SafeBSTRHandle bstr)893         internal static extern uint SysStringLen(SafeBSTRHandle bstr);
894 #endif
895 
896         [DllImport(Win32Native.OLEAUT32)]
897         [ResourceExposure(ResourceScope.None)]
898         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
SysFreeString(IntPtr bstr)899         internal static extern void SysFreeString(IntPtr bstr);
900 
901 
902         [DllImport(KERNEL32)]
903         [ResourceExposure(ResourceScope.None)]
GetACP()904         internal static extern int GetACP();
905 
906         [DllImport(KERNEL32, SetLastError=true)]
907         [ResourceExposure(ResourceScope.None)]
SetEvent(SafeWaitHandle handle)908         internal static extern bool SetEvent(SafeWaitHandle handle);
909 
910         [DllImport(KERNEL32, SetLastError=true)]
911         [ResourceExposure(ResourceScope.None)]
ResetEvent(SafeWaitHandle handle)912         internal static extern bool ResetEvent(SafeWaitHandle handle);
913 
914         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
915         [ResourceExposure(ResourceScope.Machine)] // Machine or none based on the value of "name"
CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name)916         internal static extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name);
917 
918         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
919         [ResourceExposure(ResourceScope.Machine)]
OpenEvent( int desiredAccess, bool inheritHandle, String name)920         internal static extern SafeWaitHandle OpenEvent(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
921 
922         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
923         [ResourceExposure(ResourceScope.Machine)]
924         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name)925         internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name);
926 
927         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
928         [ResourceExposure(ResourceScope.Machine)]
OpenMutex( int desiredAccess, bool inheritHandle, String name)929         internal static extern SafeWaitHandle OpenMutex(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
930 
931         [DllImport(KERNEL32, SetLastError=true)]
932         [ResourceExposure(ResourceScope.None)]
933         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
ReleaseMutex(SafeWaitHandle handle)934         internal static extern bool ReleaseMutex(SafeWaitHandle handle);
935 
936         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
937         [ResourceExposure(ResourceScope.Machine)]
GetFullPathName(char* path, int numBufferChars, char* buffer, IntPtr mustBeZero)938         internal unsafe static extern int GetFullPathName(char* path, int numBufferChars, char* buffer, IntPtr mustBeZero);
939 
940         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
941         [ResourceExposure(ResourceScope.Machine)]
GetFullPathNameW(char* path, uint numBufferChars, SafeHandle buffer, IntPtr mustBeZero)942         internal unsafe static extern uint GetFullPathNameW(char* path, uint numBufferChars, SafeHandle buffer, IntPtr mustBeZero);
943 
944         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
945         [ResourceExposure(ResourceScope.Machine)]
GetFullPathName(String path, int numBufferChars, [Out]StringBuilder buffer, IntPtr mustBeZero)946         internal unsafe static extern int GetFullPathName(String path, int numBufferChars, [Out]StringBuilder buffer, IntPtr mustBeZero);
947 
948         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
949         [ResourceExposure(ResourceScope.Machine)]
GetLongPathName(char* path, char* longPathBuffer, int bufferLength)950         internal unsafe static extern int GetLongPathName(char* path, char* longPathBuffer, int bufferLength);
951 
952         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
953         [ResourceExposure(ResourceScope.Machine)]
GetLongPathName(String path, [Out]StringBuilder longPathBuffer, int bufferLength)954         internal static extern int GetLongPathName(String path, [Out]StringBuilder longPathBuffer, int bufferLength);
955 
956         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
957         [ResourceExposure(ResourceScope.Machine)]
GetLongPathNameW(SafeHandle lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer)958         internal static extern uint GetLongPathNameW(SafeHandle lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
959 
960         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
961         [ResourceExposure(ResourceScope.Machine)]
GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer)962         internal static extern uint GetLongPathNameW(string lpszShortPath, SafeHandle lpszLongPath, uint cchBuffer);
963 
964         // Disallow access to all non-file devices from methods that take
965         // a String.  This disallows DOS devices like "con:", "com1:",
966         // "lpt1:", etc.  Use this to avoid security problems, like allowing
967         // a web client asking a server for "http://server/com1.aspx" and
968         // then causing a worker process to hang.
969         [System.Security.SecurityCritical]  // auto-generated
970         [ResourceExposure(ResourceScope.Machine)]
971         [ResourceConsumption(ResourceScope.Machine)]
SafeCreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)972         internal static SafeFileHandle SafeCreateFile(String lpFileName,
973                     int dwDesiredAccess, System.IO.FileShare dwShareMode,
974                     SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
975                     int dwFlagsAndAttributes, IntPtr hTemplateFile)
976         {
977             SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
978                                 securityAttrs, dwCreationDisposition,
979                                 dwFlagsAndAttributes, hTemplateFile );
980 
981             if (!handle.IsInvalid)
982             {
983                 int fileType = Win32Native.GetFileType(handle);
984                 if (fileType != Win32Native.FILE_TYPE_DISK) {
985                     handle.Dispose();
986                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
987                 }
988             }
989 
990             return handle;
991         }
992 
993         [System.Security.SecurityCritical]  // auto-generated
994         [ResourceExposure(ResourceScope.Machine)]
995         [ResourceConsumption(ResourceScope.Machine)]
UnsafeCreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)996         internal static SafeFileHandle UnsafeCreateFile(String lpFileName,
997                     int dwDesiredAccess, System.IO.FileShare dwShareMode,
998                     SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
999                     int dwFlagsAndAttributes, IntPtr hTemplateFile)
1000         {
1001             SafeFileHandle handle = CreateFile( lpFileName, dwDesiredAccess, dwShareMode,
1002                                 securityAttrs, dwCreationDisposition,
1003                                 dwFlagsAndAttributes, hTemplateFile );
1004 
1005             return handle;
1006         }
1007 
1008         // Do not use these directly, use the safe or unsafe versions above.
1009         // The safe version does not support devices (aka if will only open
1010         // files on disk), while the unsafe version give you the full semantic
1011         // of the native version.
1012         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1013         [ResourceExposure(ResourceScope.Machine)]
CreateFile(String lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)1014         private static extern SafeFileHandle CreateFile(String lpFileName,
1015                     int dwDesiredAccess, System.IO.FileShare dwShareMode,
1016                     SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition,
1017                     int dwFlagsAndAttributes, IntPtr hTemplateFile);
1018 
1019         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1020         [ResourceExposure(ResourceScope.Machine)]
CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, String lpName)1021         internal static extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, String lpName);
1022 
1023         [DllImport(KERNEL32, SetLastError=true, ExactSpelling=true)]
1024         [ResourceExposure(ResourceScope.Machine)]
MapViewOfFile( SafeFileMappingHandle handle, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumerOfBytesToMap)1025         internal static extern IntPtr MapViewOfFile(
1026             SafeFileMappingHandle handle, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumerOfBytesToMap);
1027 
1028         [DllImport(KERNEL32, ExactSpelling=true)]
1029         [ResourceExposure(ResourceScope.Machine)]
1030         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
UnmapViewOfFile(IntPtr lpBaseAddress )1031         internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress );
1032 
1033         [DllImport(KERNEL32, SetLastError=true)]
1034         [ResourceExposure(ResourceScope.Machine)]
1035         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
CloseHandle(IntPtr handle)1036         internal static extern bool CloseHandle(IntPtr handle);
1037 
1038         [DllImport(KERNEL32)]
1039         [ResourceExposure(ResourceScope.None)]
GetFileType(SafeFileHandle handle)1040         internal static extern int GetFileType(SafeFileHandle handle);
1041 
1042         [DllImport(KERNEL32, SetLastError=true)]
1043         [ResourceExposure(ResourceScope.None)]
SetEndOfFile(SafeFileHandle hFile)1044         internal static extern bool SetEndOfFile(SafeFileHandle hFile);
1045 
1046         [DllImport(KERNEL32, SetLastError = true)]
1047         [ResourceExposure(ResourceScope.None)]
1048         [return: MarshalAs(UnmanagedType.Bool)]
FlushFileBuffers(SafeFileHandle hFile)1049         internal static extern bool FlushFileBuffers(SafeFileHandle hFile);
1050 
1051         [DllImport(KERNEL32, SetLastError=true, EntryPoint="SetFilePointer")]
1052         [ResourceExposure(ResourceScope.None)]
SetFilePointerWin32(SafeFileHandle handle, int lo, int * hi, int origin)1053         private unsafe static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int * hi, int origin);
1054 
1055         [System.Security.SecurityCritical]  // auto-generated
1056         [ResourceExposure(ResourceScope.None)]
SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr)1057         internal unsafe static long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr) {
1058             hr = 0;
1059             int lo = (int) offset;
1060             int hi = (int) (offset >> 32);
1061             lo = SetFilePointerWin32(handle, lo, &hi, (int) origin);
1062 
1063             if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0))
1064                 return -1;
1065             return (long) (((ulong) ((uint) hi)) << 32) | ((uint) lo);
1066         }
1067 
1068         // Note there are two different ReadFile prototypes - this is to use
1069         // the type system to force you to not trip across a "feature" in
1070         // Win32's async IO support.  You can't do the following three things
1071         // simultaneously: overlapped IO, free the memory for the overlapped
1072         // struct in a callback (or an EndRead method called by that callback),
1073         // and pass in an address for the numBytesRead parameter.
1074         // <
1075 
1076         [DllImport(KERNEL32, SetLastError=true)]
1077         [ResourceExposure(ResourceScope.None)]
ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped)1078         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
1079 
1080         [DllImport(KERNEL32, SetLastError=true)]
1081         [ResourceExposure(ResourceScope.None)]
ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero)1082         unsafe internal static extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
1083 
1084         // Note there are two different WriteFile prototypes - this is to use
1085         // the type system to force you to not trip across a "feature" in
1086         // Win32's async IO support.  You can't do the following three things
1087         // simultaneously: overlapped IO, free the memory for the overlapped
1088         // struct in a callback (or an EndWrite method called by that callback),
1089         // and pass in an address for the numBytesRead parameter.
1090         // <
1091 
1092         [DllImport(KERNEL32, SetLastError=true)]
1093         [ResourceExposure(ResourceScope.None)]
WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped)1094         internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
1095 
1096         [DllImport(KERNEL32, SetLastError=true)]
1097         [ResourceExposure(ResourceScope.None)]
WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero)1098         internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
1099 
1100         // This is only available on Vista or higher
1101         [DllImport(KERNEL32, SetLastError=true)]
1102         [ResourceExposure(ResourceScope.Process)]
CancelIoEx(SafeFileHandle handle, NativeOverlapped* lpOverlapped)1103         internal static unsafe extern bool CancelIoEx(SafeFileHandle handle, NativeOverlapped* lpOverlapped);
1104 
1105         // NOTE: The out parameters are PULARGE_INTEGERs and may require
1106         // some byte munging magic.
1107         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1108         [ResourceExposure(ResourceScope.None)]
GetDiskFreeSpaceEx(String drive, out long freeBytesForUser, out long totalBytes, out long freeBytes)1109         internal static extern bool GetDiskFreeSpaceEx(String drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
1110 
1111         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1112         [ResourceExposure(ResourceScope.None)]
GetDriveType(String drive)1113         internal static extern int GetDriveType(String drive);
1114 
1115         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1116         [ResourceExposure(ResourceScope.None)]
GetVolumeInformation(String drive, [Out]StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, [Out]StringBuilder fileSystemName, int fileSystemNameBufLen)1117         internal static extern bool GetVolumeInformation(String drive, [Out]StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, [Out]StringBuilder fileSystemName, int fileSystemNameBufLen);
1118 
1119         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1120         [ResourceExposure(ResourceScope.None)]
SetVolumeLabel(String driveLetter, String volumeName)1121         internal static extern bool SetVolumeLabel(String driveLetter, String volumeName);
1122 
1123         // The following 4 methods are used by Microsoft.WlcProfile
1124         [DllImport(KERNEL32)]
1125         [ResourceExposure(ResourceScope.None)]
1126         [return: MarshalAs(UnmanagedType.Bool)]
QueryPerformanceCounter(out long value)1127         internal static extern bool QueryPerformanceCounter(out long value);
1128 
1129         [DllImport(KERNEL32)]
1130         [ResourceExposure(ResourceScope.None)]
1131         [return: MarshalAs(UnmanagedType.Bool)]
QueryPerformanceFrequency(out long value)1132         internal static extern bool QueryPerformanceFrequency(out long value);
1133 
1134         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
1135         [ResourceExposure(ResourceScope.Machine)]
CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name)1136         internal static extern SafeWaitHandle CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name);
1137 
1138         [DllImport(KERNEL32, SetLastError = true)]
1139         [ResourceExposure(ResourceScope.Machine)]
1140         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
1141         [return: MarshalAs(UnmanagedType.Bool)]
ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount)1142         internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount);
1143 
1144         // Will be in winnls.h
1145         internal const int FIND_STARTSWITH  = 0x00100000; // see if value is at the beginning of source
1146         internal const int FIND_ENDSWITH    = 0x00200000; // see if value is at the end of source
1147         internal const int FIND_FROMSTART   = 0x00400000; // look for value in source, starting at the beginning
1148         internal const int FIND_FROMEND     = 0x00800000; // look for value in source, starting at the end
1149 
1150 #if !FEATURE_CORECLR
1151         [StructLayout(LayoutKind.Sequential)]
1152         internal struct NlsVersionInfoEx
1153         {
1154             internal int dwNLSVersionInfoSize;
1155             internal int dwNLSVersion;
1156             internal int dwDefinedVersion;
1157             internal int dwEffectiveId;
1158             internal Guid guidCustomVersion;
1159         }
1160 #endif
1161 
1162 #if !FEATURE_PAL
1163         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1164         [ResourceExposure(ResourceScope.Machine)]
GetWindowsDirectory([Out]StringBuilder sb, int length)1165         internal static extern int GetWindowsDirectory([Out]StringBuilder sb, int length);
1166 
1167         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1168         [ResourceExposure(ResourceScope.Machine)]
GetSystemDirectory([Out]StringBuilder sb, int length)1169         internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length);
1170 #else
1171 #if !FEATURE_CORECLR
1172         [DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true, EntryPoint="PAL_GetPALDirectoryW")]
1173         [ResourceExposure(ResourceScope.Machine)]
GetSystemDirectory([Out]StringBuilder sb, int length)1174         internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length);
1175 
1176         [DllImport(OLEAUT32, CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true, EntryPoint="PAL_FetchConfigurationStringW")]
1177         [ResourceExposure(ResourceScope.Machine)]
FetchConfigurationString(bool perMachine, String parameterName, [Out]StringBuilder parameterValue, int parameterValueLength)1178         internal static extern bool FetchConfigurationString(bool perMachine, String parameterName, [Out]StringBuilder parameterValue, int parameterValueLength);
1179 #endif // !FEATURE_CORECLR
1180 #endif // !FEATURE_PAL
1181 
1182         [DllImport(KERNEL32, SetLastError=true)]
1183         [ResourceExposure(ResourceScope.None)]
SetFileTime(SafeFileHandle hFile, FILE_TIME* creationTime, FILE_TIME* lastAccessTime, FILE_TIME* lastWriteTime)1184         internal unsafe static extern bool SetFileTime(SafeFileHandle hFile, FILE_TIME* creationTime,
1185                     FILE_TIME* lastAccessTime, FILE_TIME* lastWriteTime);
1186 
1187         [DllImport(KERNEL32, SetLastError=true)]
1188         [ResourceExposure(ResourceScope.None)]
GetFileSize(SafeFileHandle hFile, out int highSize)1189         internal static extern int GetFileSize(SafeFileHandle hFile, out int highSize);
1190 
1191         [DllImport(KERNEL32, SetLastError=true)]
1192         [ResourceExposure(ResourceScope.None)]
LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh)1193         internal static extern bool LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
1194 
1195         [DllImport(KERNEL32, SetLastError=true)]
1196         [ResourceExposure(ResourceScope.None)]
UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh)1197         internal static extern bool UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
1198 
1199         internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);  // WinBase.h
1200 
1201         // Note, these are #defines used to extract handles, and are NOT handles.
1202         internal const int STD_INPUT_HANDLE = -10;
1203         internal const int STD_OUTPUT_HANDLE = -11;
1204         internal const int STD_ERROR_HANDLE = -12;
1205 
1206         [DllImport(KERNEL32, SetLastError=true)]
1207         [ResourceExposure(ResourceScope.Process)]
GetStdHandle(int nStdHandle)1208         internal static extern IntPtr GetStdHandle(int nStdHandle);  // param is NOT a handle, but it returns one!
1209 
1210         // From wincon.h
1211         internal const int CTRL_C_EVENT = 0;
1212         internal const int CTRL_BREAK_EVENT = 1;
1213         internal const int CTRL_CLOSE_EVENT = 2;
1214         internal const int CTRL_LOGOFF_EVENT = 5;
1215         internal const int CTRL_SHUTDOWN_EVENT = 6;
1216         internal const short KEY_EVENT = 1;
1217 
1218         // From WinBase.h
1219         internal const int FILE_TYPE_DISK = 0x0001;
1220         internal const int FILE_TYPE_CHAR = 0x0002;
1221         internal const int FILE_TYPE_PIPE = 0x0003;
1222 
1223         internal const int REPLACEFILE_WRITE_THROUGH = 0x1;
1224         internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2;
1225 
1226         private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
1227         private const int FORMAT_MESSAGE_FROM_SYSTEM    = 0x00001000;
1228         private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
1229 
1230         internal const uint FILE_MAP_WRITE = 0x0002;
1231         internal const uint FILE_MAP_READ = 0x0004;
1232 
1233         // Constants from WinNT.h
1234         internal const int FILE_ATTRIBUTE_READONLY      = 0x00000001;
1235         internal const int FILE_ATTRIBUTE_DIRECTORY     = 0x00000010;
1236         internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
1237 
1238         internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)0xA0000003);
1239 
1240         internal const int PAGE_READWRITE = 0x04;
1241 
1242         internal const int MEM_COMMIT  =  0x1000;
1243         internal const int MEM_RESERVE =  0x2000;
1244         internal const int MEM_RELEASE =  0x8000;
1245         internal const int MEM_FREE    = 0x10000;
1246 
1247         // Error codes from WinError.h
1248         internal const int ERROR_SUCCESS = 0x0;
1249         internal const int ERROR_INVALID_FUNCTION = 0x1;
1250         internal const int ERROR_FILE_NOT_FOUND = 0x2;
1251         internal const int ERROR_PATH_NOT_FOUND = 0x3;
1252         internal const int ERROR_ACCESS_DENIED  = 0x5;
1253         internal const int ERROR_INVALID_HANDLE = 0x6;
1254         internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
1255         internal const int ERROR_INVALID_DATA = 0xd;
1256         internal const int ERROR_INVALID_DRIVE = 0xf;
1257         internal const int ERROR_NO_MORE_FILES = 0x12;
1258         internal const int ERROR_NOT_READY = 0x15;
1259         internal const int ERROR_BAD_LENGTH = 0x18;
1260         internal const int ERROR_SHARING_VIOLATION = 0x20;
1261         internal const int ERROR_NOT_SUPPORTED = 0x32;
1262         internal const int ERROR_FILE_EXISTS = 0x50;
1263         internal const int ERROR_INVALID_PARAMETER = 0x57;
1264         internal const int ERROR_BROKEN_PIPE = 0x6D;
1265         internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78;
1266         internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
1267         internal const int ERROR_INVALID_NAME = 0x7B;
1268         internal const int ERROR_BAD_PATHNAME = 0xA1;
1269         internal const int ERROR_ALREADY_EXISTS = 0xB7;
1270         internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
1271         internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE;  // filename too long.
1272         internal const int ERROR_NO_DATA = 0xE8;
1273         internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9;
1274         internal const int ERROR_MORE_DATA = 0xEA;
1275         internal const int ERROR_DIRECTORY = 0x10B;
1276         internal const int ERROR_OPERATION_ABORTED = 0x3E3;  // 995; For IO Cancellation
1277         internal const int ERROR_NOT_FOUND = 0x490;          // 1168; For IO Cancellation
1278         internal const int ERROR_NO_TOKEN = 0x3f0;
1279         internal const int ERROR_DLL_INIT_FAILED = 0x45A;
1280         internal const int ERROR_NON_ACCOUNT_SID = 0x4E9;
1281         internal const int ERROR_NOT_ALL_ASSIGNED = 0x514;
1282         internal const int ERROR_UNKNOWN_REVISION = 0x519;
1283         internal const int ERROR_INVALID_OWNER = 0x51B;
1284         internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C;
1285         internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521;
1286         internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522;
1287         internal const int ERROR_NONE_MAPPED = 0x534;
1288         internal const int ERROR_INVALID_ACL = 0x538;
1289         internal const int ERROR_INVALID_SID = 0x539;
1290         internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A;
1291         internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
1292         internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543;
1293         internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546;
1294         internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD;
1295 
1296         // Error codes from ntstatus.h
1297         internal const uint STATUS_SUCCESS = 0x00000000;
1298         internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107;
1299         internal const uint STATUS_NO_MEMORY = 0xC0000017;
1300         internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
1301         internal const uint STATUS_NONE_MAPPED = 0xC0000073;
1302         internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A;
1303         internal const uint STATUS_ACCESS_DENIED = 0xC0000022;
1304 
1305         internal const int INVALID_FILE_SIZE     = -1;
1306 
1307         // From WinStatus.h
1308         internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int) 0xC000006E);
1309 
1310         // Use this to translate error codes like the above into HRESULTs like
1311         // 0x80070006 for ERROR_INVALID_HANDLE
MakeHRFromErrorCode(int errorCode)1312         internal static int MakeHRFromErrorCode(int errorCode)
1313         {
1314             BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!");
1315             return unchecked(((int)0x80070000) | errorCode);
1316         }
1317 
1318         // Win32 Structs in N/Direct style
1319         [Serializable]
1320         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
1321         [BestFitMapping(false)]
1322         internal class WIN32_FIND_DATA {
1323             internal int  dwFileAttributes = 0;
1324             // ftCreationTime was a by-value FILETIME structure
1325             internal uint ftCreationTime_dwLowDateTime = 0 ;
1326             internal uint ftCreationTime_dwHighDateTime = 0;
1327             // ftLastAccessTime was a by-value FILETIME structure
1328             internal uint ftLastAccessTime_dwLowDateTime = 0;
1329             internal uint ftLastAccessTime_dwHighDateTime = 0;
1330             // ftLastWriteTime was a by-value FILETIME structure
1331             internal uint ftLastWriteTime_dwLowDateTime = 0;
1332             internal uint ftLastWriteTime_dwHighDateTime = 0;
1333             internal int  nFileSizeHigh = 0;
1334             internal int  nFileSizeLow = 0;
1335             // If the file attributes' reparse point flag is set, then
1336             // dwReserved0 is the file tag (aka reparse tag) for the
1337             // reparse point.  Use this to figure out whether something is
1338             // a volume mount point or a symbolic link.
1339             internal int  dwReserved0 = 0;
1340             internal int  dwReserved1 = 0;
1341             [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
1342             internal String   cFileName = null;
1343             [MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
1344             internal String   cAlternateFileName = null;
1345         }
1346 
1347 #if FEATURE_CORESYSTEM
1348         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1349         [ResourceExposure(ResourceScope.Machine)]
CopyFileEx(String src, String dst, IntPtr progressRoutine, IntPtr progressData, ref uint cancel, uint flags)1350         private static extern bool CopyFileEx(String src,
1351                                               String dst,
1352                                               IntPtr progressRoutine,
1353                                               IntPtr progressData,
1354                                               ref uint cancel,
1355                                               uint flags);
1356 
CopyFile(String src, String dst, bool failIfExists)1357         internal static bool CopyFile(String src, String dst, bool failIfExists)
1358         {
1359             uint cancel = 0;
1360             return CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, failIfExists ? 1U : 0U);
1361         }
1362 #else // FEATURE_CORESYSTEM
1363         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1364         [ResourceExposure(ResourceScope.Machine)]
CopyFile( String src, String dst, bool failIfExists)1365         internal static extern bool CopyFile(
1366                     String src, String dst, bool failIfExists);
1367 #endif // FEATURE_CORESYSTEM
1368 
1369         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1370         [ResourceExposure(ResourceScope.Machine)]
CreateDirectory( String path, SECURITY_ATTRIBUTES lpSecurityAttributes)1371         internal static extern bool CreateDirectory(
1372                     String path, SECURITY_ATTRIBUTES lpSecurityAttributes);
1373 
1374         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1375         [ResourceExposure(ResourceScope.Machine)]
DeleteFile(String path)1376         internal static extern bool DeleteFile(String path);
1377 
1378         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1379         [ResourceExposure(ResourceScope.Machine)]
ReplaceFile(String replacedFileName, String replacementFileName, String backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved)1380         internal static extern bool ReplaceFile(String replacedFileName, String replacementFileName, String backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);
1381 
1382         [DllImport(ADVAPI32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1383         [ResourceExposure(ResourceScope.Machine)]
DecryptFile(String path, int reservedMustBeZero)1384         internal static extern bool DecryptFile(String path, int reservedMustBeZero);
1385 
1386         [DllImport(ADVAPI32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1387         [ResourceExposure(ResourceScope.Machine)]
EncryptFile(String path)1388         internal static extern bool EncryptFile(String path);
1389 
1390         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1391         [ResourceExposure(ResourceScope.None)]
FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data)1392         internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);
1393 
1394         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1395         [ResourceExposure(ResourceScope.None)]
FindNextFile( SafeFindHandle hndFindFile, [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_DATA lpFindFileData)1396         internal static extern bool FindNextFile(
1397                     SafeFindHandle hndFindFile,
1398                     [In, Out, MarshalAs(UnmanagedType.LPStruct)]
1399                     WIN32_FIND_DATA lpFindFileData);
1400 
1401         [DllImport(KERNEL32)]
1402         [ResourceExposure(ResourceScope.None)]
1403         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
FindClose(IntPtr handle)1404         internal static extern bool FindClose(IntPtr handle);
1405 
1406         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1407         [ResourceExposure(ResourceScope.Machine)]
GetCurrentDirectory( int nBufferLength, [Out]StringBuilder lpBuffer)1408         internal static extern int GetCurrentDirectory(
1409                   int nBufferLength,
1410                   [Out]StringBuilder lpBuffer);
1411 
1412         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
1413         [ResourceExposure(ResourceScope.Machine)]
GetCurrentDirectoryW(uint nBufferLength, SafeHandle lpBuffer)1414         internal static extern uint GetCurrentDirectoryW(uint nBufferLength, SafeHandle lpBuffer);
1415 
1416         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1417         [ResourceExposure(ResourceScope.None)]
GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation)1418         internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
1419 
1420         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1421         [ResourceExposure(ResourceScope.None)]
SetFileAttributes(String name, int attr)1422         internal static extern bool SetFileAttributes(String name, int attr);
1423 
1424         [DllImport(KERNEL32, SetLastError=true)]
1425         [ResourceExposure(ResourceScope.None)]
GetLogicalDrives()1426         internal static extern int GetLogicalDrives();
1427 
1428         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1429         [ResourceExposure(ResourceScope.None)]
GetTempFileName(String tmpPath, String prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName)1430         internal static extern uint GetTempFileName(String tmpPath, String prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName);
1431 
1432 #if FEATURE_CORESYSTEM
1433         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1434         [ResourceExposure(ResourceScope.Machine)]
MoveFileEx(String src, String dst, uint flags)1435         private static extern bool MoveFileEx(String src, String dst, uint flags);
1436 
MoveFile(String src, String dst)1437         internal static bool MoveFile(String src, String dst)
1438         {
1439             return MoveFileEx(src, dst, 2 /* MOVEFILE_COPY_ALLOWED */);
1440         }
1441 #else // FEATURE_CORESYSTEM
1442         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1443         [ResourceExposure(ResourceScope.Machine)]
MoveFile(String src, String dst)1444         internal static extern bool MoveFile(String src, String dst);
1445 #endif // FEATURE_CORESYSTEM
1446 
1447         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1448         [ResourceExposure(ResourceScope.Machine)]
DeleteVolumeMountPoint(String mountPoint)1449         internal static extern bool DeleteVolumeMountPoint(String mountPoint);
1450 
1451         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1452         [ResourceExposure(ResourceScope.Machine)]
RemoveDirectory(String path)1453         internal static extern bool RemoveDirectory(String path);
1454 
1455         [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
1456         [ResourceExposure(ResourceScope.Machine)]
SetCurrentDirectory(String path)1457         internal static extern bool SetCurrentDirectory(String path);
1458 
1459         [DllImport(KERNEL32, SetLastError=false, EntryPoint="SetErrorMode", ExactSpelling=true)]
1460         [ResourceExposure(ResourceScope.Process)]
SetErrorMode_VistaAndOlder(int newMode)1461         private static extern int SetErrorMode_VistaAndOlder(int newMode);
1462 
1463         [DllImport(KERNEL32, SetLastError=true, EntryPoint="SetThreadErrorMode")]
1464         [ResourceExposure(ResourceScope.None)]
SetErrorMode_Win7AndNewer(int newMode, out int oldMode)1465         private static extern bool SetErrorMode_Win7AndNewer(int newMode, out int oldMode);
1466 
1467         // RTM versions of Win7 and Windows Server 2008 R2
1468         private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600);
1469 
1470         // this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems.
1471         //
1472         [ResourceExposure(ResourceScope.Process)]
1473         [ResourceConsumption(ResourceScope.Process)]
SetErrorMode(int newMode)1474         internal static int SetErrorMode(int newMode)
1475         {
1476 #if !FEATURE_CORESYSTEM // ARMSTUB
1477             if (Environment.OSVersion.Version >= ThreadErrorModeMinOsVersion)
1478             {
1479                 int oldMode;
1480                 SetErrorMode_Win7AndNewer(newMode, out oldMode);
1481                 return oldMode;
1482             }
1483 #endif
1484             return SetErrorMode_VistaAndOlder(newMode);
1485         }
1486 
1487         internal const int LCID_SUPPORTED = 0x00000002;  // supported locale ids
1488 
1489         [DllImport(KERNEL32)]
1490         [ResourceExposure(ResourceScope.None)]
WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2)1491         internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2);
1492 
1493         // A Win32 HandlerRoutine
ConsoleCtrlHandlerRoutine(int controlType)1494         internal delegate bool ConsoleCtrlHandlerRoutine(int controlType);
1495 
1496         [DllImport(KERNEL32, SetLastError=true)]
1497         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
1498         [ResourceExposure(ResourceScope.Process)]
SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove)1499         internal static extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove);
1500 
1501         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1502         [ResourceExposure(ResourceScope.Process)]
SetEnvironmentVariable(string lpName, string lpValue)1503         internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
1504 
1505         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1506         [ResourceExposure(ResourceScope.Machine)]
GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size)1507         internal static extern int GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size);
1508 
1509         [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
1510         [ResourceExposure(ResourceScope.Machine)]
GetEnvironmentStrings()1511         internal static unsafe extern char * GetEnvironmentStrings();
1512 
1513         [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
1514         [ResourceExposure(ResourceScope.Machine)]
FreeEnvironmentStrings(char * pStrings)1515         internal static unsafe extern bool FreeEnvironmentStrings(char * pStrings);
1516 
1517         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
1518         [ResourceExposure(ResourceScope.Process)]
GetCurrentProcessId()1519         internal static extern uint GetCurrentProcessId();
1520 
1521         [DllImport(ADVAPI32, CharSet=CharSet.Auto)]
1522         [ResourceExposure(ResourceScope.None)]
GetUserName([Out]StringBuilder lpBuffer, ref int nSize)1523         internal static extern bool GetUserName([Out]StringBuilder lpBuffer, ref int nSize);
1524 
1525         [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false)]
1526         [ResourceExposure(ResourceScope.None)]
GetComputerName([Out]StringBuilder nameBuffer, ref int bufferSize)1527         internal extern static int GetComputerName([Out]StringBuilder nameBuffer, ref int bufferSize);
1528 
1529         [DllImport(OLE32)]
1530         [ResourceExposure(ResourceScope.None)]
CoCreateGuid(out Guid guid)1531         internal extern static int CoCreateGuid(out Guid guid);
1532 
1533         [DllImport(Win32Native.OLE32)]
1534         [ResourceExposure(ResourceScope.None)]
CoTaskMemAlloc(UIntPtr cb)1535         internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb);
1536 
1537         [DllImport(Win32Native.OLE32)]
1538         [ResourceExposure(ResourceScope.None)]
CoTaskMemRealloc(IntPtr pv, UIntPtr cb)1539         internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb);
1540 
1541         [DllImport(Win32Native.OLE32)]
1542         [ResourceExposure(ResourceScope.None)]
CoTaskMemFree(IntPtr ptr)1543         internal static extern void CoTaskMemFree(IntPtr ptr);
1544 
1545 #if !FEATURE_PAL
1546         [StructLayoutAttribute(LayoutKind.Sequential)]
1547         internal struct COORD
1548         {
1549             internal short X;
1550             internal short Y;
1551         }
1552 
1553         [StructLayoutAttribute(LayoutKind.Sequential)]
1554         internal struct SMALL_RECT
1555         {
1556             internal short Left;
1557             internal short Top;
1558             internal short Right;
1559             internal short Bottom;
1560         }
1561 
1562         [StructLayoutAttribute(LayoutKind.Sequential)]
1563         internal struct CONSOLE_SCREEN_BUFFER_INFO
1564         {
1565             internal COORD      dwSize;
1566             internal COORD      dwCursorPosition;
1567             internal short      wAttributes;
1568             internal SMALL_RECT srWindow;
1569             internal COORD      dwMaximumWindowSize;
1570         }
1571 
1572         [StructLayoutAttribute(LayoutKind.Sequential)]
1573         internal struct CONSOLE_CURSOR_INFO
1574         {
1575             internal int dwSize;
1576             internal bool bVisible;
1577         }
1578 
1579         // Win32's KEY_EVENT_RECORD
1580         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
1581         internal struct KeyEventRecord
1582         {
1583             internal bool keyDown;
1584             internal short repeatCount;
1585             internal short virtualKeyCode;
1586             internal short virtualScanCode;
1587             internal char uChar; // Union between WCHAR and ASCII char
1588             internal int controlKeyState;
1589         }
1590 
1591         // Really, this is a union of KeyEventRecords and other types.
1592         [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
1593         internal struct InputRecord
1594         {
1595             internal short eventType;
1596             internal KeyEventRecord keyEvent;
1597             // This struct is a union!  Word alighment should take care of padding!
1598         }
1599 
1600 [Serializable]
1601         [Flags]
1602         internal enum Color : short
1603         {
1604             Black = 0,
1605             ForegroundBlue = 0x1,
1606             ForegroundGreen = 0x2,
1607             ForegroundRed = 0x4,
1608             ForegroundYellow = 0x6,
1609             ForegroundIntensity = 0x8,
1610             BackgroundBlue = 0x10,
1611             BackgroundGreen = 0x20,
1612             BackgroundRed = 0x40,
1613             BackgroundYellow = 0x60,
1614             BackgroundIntensity = 0x80,
1615 
1616             ForegroundMask = 0xf,
1617             BackgroundMask = 0xf0,
1618             ColorMask = 0xff
1619         }
1620 
1621         [StructLayout(LayoutKind.Sequential)]
1622         internal struct CHAR_INFO
1623         {
1624             ushort charData;  // Union between WCHAR and ASCII char
1625             short attributes;
1626         }
1627 
1628         internal const int ENABLE_PROCESSED_INPUT  = 0x0001;
1629         internal const int ENABLE_LINE_INPUT  = 0x0002;
1630         internal const int ENABLE_ECHO_INPUT  = 0x0004;
1631 
1632         [DllImport(KERNEL32, SetLastError=true)]
1633         [ResourceExposure(ResourceScope.Process)]
SetConsoleMode(IntPtr hConsoleHandle, int mode)1634         internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, int mode);
1635 
1636         [DllImport(KERNEL32, SetLastError=true)]
1637         [ResourceExposure(ResourceScope.Process)]
GetConsoleMode(IntPtr hConsoleHandle, out int mode)1638         internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int mode);
1639 
1640         [DllImport(KERNEL32, SetLastError=true)]
1641         [ResourceExposure(ResourceScope.None)]
Beep(int frequency, int duration)1642         internal static extern bool Beep(int frequency, int duration);
1643 
1644         [DllImport(KERNEL32, SetLastError=true)]
1645         [ResourceExposure(ResourceScope.None)]
GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo)1646         internal static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput,
1647             out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
1648 
1649         [DllImport(KERNEL32, SetLastError=true)]
1650         [ResourceExposure(ResourceScope.Process)]
SetConsoleScreenBufferSize(IntPtr hConsoleOutput, COORD size)1651         internal static extern bool SetConsoleScreenBufferSize(IntPtr hConsoleOutput, COORD size);
1652 
1653         [DllImport(KERNEL32, SetLastError=true)]
1654         [ResourceExposure(ResourceScope.None)]
GetLargestConsoleWindowSize(IntPtr hConsoleOutput)1655         internal static extern COORD GetLargestConsoleWindowSize(IntPtr hConsoleOutput);
1656 
1657         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
1658         [ResourceExposure(ResourceScope.Process)]
FillConsoleOutputCharacter(IntPtr hConsoleOutput, char character, int nLength, COORD dwWriteCoord, out int pNumCharsWritten)1659         internal static extern bool FillConsoleOutputCharacter(IntPtr hConsoleOutput,
1660             char character, int nLength, COORD dwWriteCoord, out int pNumCharsWritten);
1661 
1662         [DllImport(KERNEL32, SetLastError=true)]
1663         [ResourceExposure(ResourceScope.Process)]
FillConsoleOutputAttribute(IntPtr hConsoleOutput, short wColorAttribute, int numCells, COORD startCoord, out int pNumBytesWritten)1664         internal static extern bool FillConsoleOutputAttribute(IntPtr hConsoleOutput,
1665             short wColorAttribute, int numCells, COORD startCoord, out int pNumBytesWritten);
1666 
1667         [DllImport(KERNEL32, SetLastError=true)]
1668         [ResourceExposure(ResourceScope.Process)]
SetConsoleWindowInfo(IntPtr hConsoleOutput, bool absolute, SMALL_RECT* consoleWindow)1669         internal static unsafe extern bool SetConsoleWindowInfo(IntPtr hConsoleOutput,
1670             bool absolute, SMALL_RECT* consoleWindow);
1671 
1672         [DllImport(KERNEL32, SetLastError=true)]
1673         [ResourceExposure(ResourceScope.Process)]
SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes)1674         internal static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes);
1675 
1676         [DllImport(KERNEL32, SetLastError=true)]
1677         [ResourceExposure(ResourceScope.Process)]
SetConsoleCursorPosition(IntPtr hConsoleOutput, COORD cursorPosition)1678         internal static extern bool SetConsoleCursorPosition(IntPtr hConsoleOutput,
1679             COORD cursorPosition);
1680 
1681         [DllImport(KERNEL32, SetLastError=true)]
1682         [ResourceExposure(ResourceScope.None)]
GetConsoleCursorInfo(IntPtr hConsoleOutput, out CONSOLE_CURSOR_INFO cci)1683         internal static extern bool GetConsoleCursorInfo(IntPtr hConsoleOutput,
1684             out CONSOLE_CURSOR_INFO cci);
1685 
1686         [DllImport(KERNEL32, SetLastError=true)]
1687         [ResourceExposure(ResourceScope.Process)]
SetConsoleCursorInfo(IntPtr hConsoleOutput, ref CONSOLE_CURSOR_INFO cci)1688         internal static extern bool SetConsoleCursorInfo(IntPtr hConsoleOutput,
1689             ref CONSOLE_CURSOR_INFO cci);
1690 
1691         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=true)]
1692         [ResourceExposure(ResourceScope.Process)]
SetConsoleTitle(String title)1693         internal static extern bool SetConsoleTitle(String title);
1694 
1695         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
1696         [ResourceExposure(ResourceScope.Process)]
ReadConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead)1697         internal static extern bool ReadConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);
1698 
1699         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
1700         [ResourceExposure(ResourceScope.Process)]
PeekConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead)1701         internal static extern bool PeekConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);
1702 
1703         [DllImport(KERNEL32, SetLastError=true)]
1704         [ResourceExposure(ResourceScope.Process)]
ReadConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* pBuffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT readRegion)1705         internal static unsafe extern bool ReadConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* pBuffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT readRegion);
1706 
1707         [DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
1708         [ResourceExposure(ResourceScope.Process)]
1709         [return: MarshalAs(UnmanagedType.Bool)]
ReadConsoleW(SafeFileHandle hConsoleInput, Byte* lpBuffer, Int32 nNumberOfCharsToRead, out Int32 lpNumberOfCharsRead, IntPtr pInputControl)1710         internal static unsafe extern bool ReadConsoleW(SafeFileHandle hConsoleInput, Byte* lpBuffer, Int32 nNumberOfCharsToRead, out Int32 lpNumberOfCharsRead, IntPtr pInputControl);
1711 
1712         [DllImport(KERNEL32, SetLastError=true)]
1713         [ResourceExposure(ResourceScope.Process)]
WriteConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* buffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT writeRegion)1714         internal static unsafe extern bool WriteConsoleOutput(IntPtr hConsoleOutput, CHAR_INFO* buffer, COORD bufferSize, COORD bufferCoord, ref SMALL_RECT writeRegion);
1715 
1716         [DllImport(KERNEL32, CharSet=CharSet.Unicode, SetLastError=true)]
1717         [ResourceExposure(ResourceScope.Process)]
1718         [return: MarshalAs(UnmanagedType.Bool)]
WriteConsoleW(SafeFileHandle hConsoleOutput, Byte* lpBuffer, Int32 nNumberOfCharsToWrite, out Int32 lpNumberOfCharsWritten, IntPtr lpReservedMustBeNull)1719         internal static unsafe extern bool WriteConsoleW(SafeFileHandle hConsoleOutput, Byte* lpBuffer, Int32 nNumberOfCharsToWrite, out Int32 lpNumberOfCharsWritten, IntPtr lpReservedMustBeNull);
1720 
1721         [DllImport(USER32)]  // Appears to always succeed
1722         [ResourceExposure(ResourceScope.Process)]
GetKeyState(int virtualKeyCode)1723         internal static extern short GetKeyState(int virtualKeyCode);
1724 #endif // !FEATURE_PAL
1725 
1726         [DllImport(KERNEL32, SetLastError=false)]
1727         [ResourceExposure(ResourceScope.None)]
GetConsoleCP()1728         internal static extern uint GetConsoleCP();
1729 
1730         [DllImport(KERNEL32, SetLastError=true)]
1731         [ResourceExposure(ResourceScope.Process)]
SetConsoleCP(uint codePage)1732         internal static extern bool SetConsoleCP(uint codePage);
1733 
1734         [DllImport(KERNEL32, SetLastError=false)]
1735         [ResourceExposure(ResourceScope.None)]
GetConsoleOutputCP()1736         internal static extern uint GetConsoleOutputCP();
1737 
1738         [DllImport(KERNEL32, SetLastError=true)]
1739         [ResourceExposure(ResourceScope.Process)]
SetConsoleOutputCP(uint codePage)1740         internal static extern bool SetConsoleOutputCP(uint codePage);
1741 
1742 #if !FEATURE_PAL
1743         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1744         [ResourceExposure(ResourceScope.Machine)]
RegConnectRegistry(String machineName, SafeRegistryHandle key, out SafeRegistryHandle result)1745         internal static extern int RegConnectRegistry(String machineName,
1746                     SafeRegistryHandle key, out SafeRegistryHandle result);
1747 
1748         // Note: RegCreateKeyEx won't set the last error on failure - it returns
1749         // an error code if it fails.
1750         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1751         [ResourceExposure(ResourceScope.Machine)]
RegCreateKeyEx(SafeRegistryHandle hKey, String lpSubKey, int Reserved, String lpClass, int dwOptions, int samDesired, SECURITY_ATTRIBUTES lpSecurityAttributes, out SafeRegistryHandle hkResult, out int lpdwDisposition)1752         internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, String lpSubKey,
1753                     int Reserved, String lpClass, int dwOptions,
1754                     int samDesired, SECURITY_ATTRIBUTES lpSecurityAttributes,
1755                     out SafeRegistryHandle hkResult, out int lpdwDisposition);
1756 
1757         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1758         [ResourceExposure(ResourceScope.Machine)]
RegDeleteKey(SafeRegistryHandle hKey, String lpSubKey)1759         internal static extern int RegDeleteKey(SafeRegistryHandle hKey, String lpSubKey);
1760 
1761         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1762         [ResourceExposure(ResourceScope.Machine)]
RegDeleteKeyEx(SafeRegistryHandle hKey, String lpSubKey, int samDesired, int Reserved)1763         internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, String lpSubKey,
1764                     int samDesired, int Reserved);
1765 
1766         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1767         [ResourceExposure(ResourceScope.Machine)]
RegDeleteValue(SafeRegistryHandle hKey, String lpValueName)1768         internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName);
1769 
1770         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1771         [ResourceExposure(ResourceScope.None)]
RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char *lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime)1772         internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex,
1773                     char *lpName, ref int lpcbName, int[] lpReserved,
1774                     [Out]StringBuilder lpClass, int[] lpcbClass,
1775                     long[] lpftLastWriteTime);
1776 
1777         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1778         [ResourceExposure(ResourceScope.None)]
RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char *lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData)1779         internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex,
1780                     char *lpValueName, ref int lpcbValueName,
1781                     IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
1782                     int[] lpcbData);
1783 
1784 
1785         [DllImport(ADVAPI32)]
1786         [ResourceExposure(ResourceScope.None)]
RegFlushKey(SafeRegistryHandle hKey)1787         internal static extern int RegFlushKey(SafeRegistryHandle hKey);
1788 
1789         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1790         [ResourceExposure(ResourceScope.Machine)]
RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult)1791         internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey,
1792                     int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
1793 
1794         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1795         [ResourceExposure(ResourceScope.Machine)]
RegOpenKeyEx(IntPtr hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult)1796         internal static extern int RegOpenKeyEx(IntPtr hKey, String lpSubKey,
1797                     int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
1798 
1799         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1800         [ResourceExposure(ResourceScope.None)]
RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass, int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen, ref int lpcValues, int[] lpcbMaxValueNameLen, int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor, int[] lpftLastWriteTime)1801         internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass,
1802                     int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys,
1803                     int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen,
1804                     ref int lpcValues, int[] lpcbMaxValueNameLen,
1805                     int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor,
1806                     int[] lpftLastWriteTime);
1807 
1808         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1809         [ResourceExposure(ResourceScope.None)]
RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData)1810         internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
1811                     int[] lpReserved, ref int lpType, [Out] byte[] lpData,
1812                     ref int lpcbData);
1813 
1814         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1815         [ResourceExposure(ResourceScope.None)]
RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData)1816         internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
1817                     int[] lpReserved, ref int lpType, ref int lpData,
1818                     ref int lpcbData);
1819 
1820         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1821         [ResourceExposure(ResourceScope.None)]
RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData)1822         internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
1823                     int[] lpReserved, ref int lpType, ref long lpData,
1824                     ref int lpcbData);
1825 
1826         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1827         [ResourceExposure(ResourceScope.None)]
RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData)1828         internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
1829                      int[] lpReserved, ref int lpType, [Out] char[] lpData,
1830                      ref int lpcbData);
1831 
1832         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1833         [ResourceExposure(ResourceScope.None)]
RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out]StringBuilder lpData, ref int lpcbData)1834         internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
1835                     int[] lpReserved, ref int lpType, [Out]StringBuilder lpData,
1836                     ref int lpcbData);
1837 
1838         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1839         [ResourceExposure(ResourceScope.None)]
RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData)1840         internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
1841                     int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
1842 
1843         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1844         [ResourceExposure(ResourceScope.None)]
RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData)1845         internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
1846                     int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);
1847 
1848         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1849         [ResourceExposure(ResourceScope.None)]
RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData)1850         internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
1851                     int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);
1852 
1853         [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
1854         [ResourceExposure(ResourceScope.None)]
RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, String lpData, int cbData)1855         internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
1856                     int Reserved, RegistryValueKind dwType, String lpData, int cbData);
1857 
1858         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1859         [ResourceExposure(ResourceScope.None)]
ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize)1860         internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize);
1861 
1862         [DllImport(KERNEL32)]
1863         [ResourceExposure(ResourceScope.None)]
LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags)1864         internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags);
1865 #endif // !FEATURE_PAL
1866 
1867         internal const int SHGFP_TYPE_CURRENT               = 0;      // the current (user) folder path setting
1868         internal const int UOI_FLAGS                        = 1;
1869         internal const int WSF_VISIBLE                      = 1;
1870 
1871 //////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!////////
1872 //////!!!!!! Keep the following locations synchronized            !!!!!!////////
1873 //////!!!!!! 1) ndp\clr\src\BCL\Microsoft\Win32\Win32Native.cs    !!!!!!////////
1874 //////!!!!!! 2) ndp\clr\src\BCL\System\Environment.cs             !!!!!!////////
1875 //////!!!!!! 3) rotor\pal\inc\rotor_pal.h                         !!!!!!////////
1876 //////!!!!!! 4) rotor\pal\corunix\shfolder\shfolder.cpp           !!!!!!////////
1877 //////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!////////
1878 /*<
1879 
1880 
1881 
1882 
1883 
1884 
1885 
1886 
1887 
1888 
1889 
1890 
1891 
1892 
1893 
1894 
1895 
1896 
1897 
1898 
1899 
1900 
1901 
1902 
1903 */
1904         // .NET Framework 4.0 and newer - all versions of windows ||| \public\sdk\inc\shlobj.h
1905         internal const int CSIDL_FLAG_CREATE                = 0x8000; // force folder creation in SHGetFolderPath
1906         internal const int CSIDL_FLAG_DONT_VERIFY           = 0x4000; // return an unverified folder path
1907         internal const int CSIDL_ADMINTOOLS                 = 0x0030; // <user name>\Start Menu\Programs\Administrative Tools
1908         internal const int CSIDL_CDBURN_AREA                = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
1909         internal const int CSIDL_COMMON_ADMINTOOLS          = 0x002f; // All Users\Start Menu\Programs\Administrative Tools
1910         internal const int CSIDL_COMMON_DOCUMENTS           = 0x002e; // All Users\Documents
1911         internal const int CSIDL_COMMON_MUSIC               = 0x0035; // All Users\My Music
1912         internal const int CSIDL_COMMON_OEM_LINKS           = 0x003a; // Links to All Users OEM specific apps
1913         internal const int CSIDL_COMMON_PICTURES            = 0x0036; // All Users\My Pictures
1914         internal const int CSIDL_COMMON_STARTMENU           = 0x0016; // All Users\Start Menu
1915         internal const int CSIDL_COMMON_PROGRAMS            = 0X0017; // All Users\Start Menu\Programs
1916         internal const int CSIDL_COMMON_STARTUP             = 0x0018; // All Users\Startup
1917         internal const int CSIDL_COMMON_DESKTOPDIRECTORY    = 0x0019; // All Users\Desktop
1918         internal const int CSIDL_COMMON_TEMPLATES           = 0x002d; // All Users\Templates
1919         internal const int CSIDL_COMMON_VIDEO               = 0x0037; // All Users\My Video
1920         internal const int CSIDL_FONTS                      = 0x0014; // windows\fonts
1921         internal const int CSIDL_MYVIDEO                    = 0x000e; // "My Videos" folder
1922         internal const int CSIDL_NETHOOD                    = 0x0013; // %APPDATA%\Microsoft\Windows\Network Shortcuts
1923         internal const int CSIDL_PRINTHOOD                  = 0x001b; // %APPDATA%\Microsoft\Windows\Printer Shortcuts
1924         internal const int CSIDL_PROFILE                    = 0x0028; // %USERPROFILE% (%SystemDrive%\Users\%USERNAME%)
1925         internal const int CSIDL_PROGRAM_FILES_COMMONX86    = 0x002c; // x86 Program Files\Common on RISC
1926         internal const int CSIDL_PROGRAM_FILESX86           = 0x002a; // x86 C:\Program Files on RISC
1927         internal const int CSIDL_RESOURCES                  = 0x0038; // %windir%\Resources
1928         internal const int CSIDL_RESOURCES_LOCALIZED        = 0x0039; // %windir%\resources\0409 (code page)
1929         internal const int CSIDL_SYSTEMX86                  = 0x0029; // %windir%\system32
1930         internal const int CSIDL_WINDOWS                    = 0x0024; // GetWindowsDirectory()
1931 
1932         // .NET Framework 3.5 and earlier - all versions of windows
1933         internal const int CSIDL_APPDATA                    = 0x001a;
1934         internal const int CSIDL_COMMON_APPDATA             = 0x0023;
1935         internal const int CSIDL_LOCAL_APPDATA              = 0x001c;
1936         internal const int CSIDL_COOKIES                    = 0x0021;
1937         internal const int CSIDL_FAVORITES                  = 0x0006;
1938         internal const int CSIDL_HISTORY                    = 0x0022;
1939         internal const int CSIDL_INTERNET_CACHE             = 0x0020;
1940         internal const int CSIDL_PROGRAMS                   = 0x0002;
1941         internal const int CSIDL_RECENT                     = 0x0008;
1942         internal const int CSIDL_SENDTO                     = 0x0009;
1943         internal const int CSIDL_STARTMENU                  = 0x000b;
1944         internal const int CSIDL_STARTUP                    = 0x0007;
1945         internal const int CSIDL_SYSTEM                     = 0x0025;
1946         internal const int CSIDL_TEMPLATES                  = 0x0015;
1947         internal const int CSIDL_DESKTOPDIRECTORY           = 0x0010;
1948         internal const int CSIDL_PERSONAL                   = 0x0005;
1949         internal const int CSIDL_PROGRAM_FILES              = 0x0026;
1950         internal const int CSIDL_PROGRAM_FILES_COMMON       = 0x002b;
1951         internal const int CSIDL_DESKTOP                    = 0x0000;
1952         internal const int CSIDL_DRIVES                     = 0x0011;
1953         internal const int CSIDL_MYMUSIC                    = 0x000d;
1954         internal const int CSIDL_MYPICTURES                 = 0x0027;
1955 
1956         [DllImport(SHELL32, CharSet=CharSet.Auto, BestFitMapping=false)]
1957         [ResourceExposure(ResourceScope.Machine)]
SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, [Out]StringBuilder lpszPath)1958         internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, [Out]StringBuilder lpszPath);
1959 
1960 #if !FEATURE_PAL
1961         internal const int NameSamCompatible = 2;
1962 
1963         [ResourceExposure(ResourceScope.None)]
1964         [DllImport(SECUR32, CharSet=CharSet.Unicode, SetLastError=true)]
1965         // Win32 return type is BOOLEAN (which is 1 byte and not BOOL which is 4bytes)
GetUserNameEx(int format, [Out]StringBuilder domainName, ref uint domainNameLen)1966         internal static extern byte GetUserNameEx(int format, [Out]StringBuilder domainName, ref uint domainNameLen);
1967 
1968         [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
1969         [ResourceExposure(ResourceScope.None)]
LookupAccountName(string machineName, string accountName, byte[] sid, ref int sidLen, [Out]StringBuilder domainName, ref uint domainNameLen, out int peUse)1970         internal static extern bool LookupAccountName(string machineName, string accountName, byte[] sid,
1971                                  ref int sidLen, [Out]StringBuilder domainName, ref uint domainNameLen, out int peUse);
1972 
1973         // Note: This returns a handle, but it shouldn't be closed.  The Avalon
1974         // team says CloseWindowStation would ignore this handle.  So there
1975         // isn't a lot of value to switching to SafeHandle here.
1976         [DllImport(USER32, ExactSpelling=true)]
1977         [ResourceExposure(ResourceScope.Machine)]
GetProcessWindowStation()1978         internal static extern IntPtr GetProcessWindowStation();
1979 
1980         [DllImport(USER32, SetLastError=true)]
1981         [ResourceExposure(ResourceScope.None)]
GetUserObjectInformation(IntPtr hObj, int nIndex, [MarshalAs(UnmanagedType.LPStruct)] USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded)1982         internal static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex,
1983             [MarshalAs(UnmanagedType.LPStruct)] USEROBJECTFLAGS pvBuffer, int nLength, ref int lpnLengthNeeded);
1984 
1985         [DllImport(USER32, SetLastError=true, BestFitMapping=false)]
1986         [ResourceExposure(ResourceScope.Machine)]
SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult)1987         internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult);
1988 
1989         [StructLayout(LayoutKind.Sequential)]
1990         internal class USEROBJECTFLAGS {
1991             internal int fInherit = 0;
1992             internal int fReserved = 0;
1993             internal int dwFlags = 0;
1994         }
1995 
1996         //
1997         // DPAPI
1998         //
1999 
2000         //
2001         // RtlEncryptMemory and RtlDecryptMemory are declared in the internal header file crypt.h.
2002         // They were also recently declared in the public header file ntsecapi.h (in the Platform SDK as well as the current build of Server 2003).
2003         // We use them instead of CryptProtectMemory and CryptUnprotectMemory because
2004         // they are available in both WinXP and in Windows Server 2003.
2005         //
2006 
2007         [DllImport(Win32Native.ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2008         [ResourceExposure(ResourceScope.None)]
2009         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
2010         internal static extern
SystemFunction040( [In,Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlags)2011         int SystemFunction040 (
2012             [In,Out] SafeBSTRHandle     pDataIn,
2013             [In]     uint       cbDataIn,   // multiple of RTL_ENCRYPT_MEMORY_SIZE
2014             [In]     uint       dwFlags);
2015 
2016         [DllImport(Win32Native.ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2017         [ResourceExposure(ResourceScope.None)]
2018         internal static extern
SystemFunction041( [In,Out] SafeBSTRHandle pDataIn, [In] uint cbDataIn, [In] uint dwFlags)2019         int SystemFunction041 (
2020             [In,Out] SafeBSTRHandle     pDataIn,
2021             [In]     uint       cbDataIn,   // multiple of RTL_ENCRYPT_MEMORY_SIZE
2022             [In]     uint       dwFlags);
2023 
2024 #if FEATURE_CORECLR
2025         [DllImport(NTDLL, CharSet=CharSet.Unicode, SetLastError=true)]
2026         [ResourceExposure(ResourceScope.None)]
2027         internal static extern
RtlNtStatusToDosError( [In] int status)2028         int RtlNtStatusToDosError (
2029             [In]    int         status);
2030 #else
2031         // identical to RtlNtStatusToDosError, but we are in ask mode for desktop CLR
2032         [DllImport(ADVAPI32, CharSet = CharSet.Unicode, SetLastError = true)]
2033         [ResourceExposure(ResourceScope.None)]
2034         internal static extern
LsaNtStatusToWinError( [In] int status)2035         int LsaNtStatusToWinError (
2036             [In]    int         status);
2037 #endif
2038         // Get the current FIPS policy setting on Vista and above
2039         [DllImport("bcrypt.dll")]
2040         [ResourceExposure(ResourceScope.Machine)]
BCryptGetFipsAlgorithmMode( [MarshalAs(UnmanagedType.U1), Out]out bool pfEnabled)2041         internal static extern uint BCryptGetFipsAlgorithmMode(
2042                 [MarshalAs(UnmanagedType.U1), Out]out bool pfEnabled);
2043 
2044         //
2045         // Managed ACLs
2046         //
2047 
2048         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2049         [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2050         [ResourceExposure(ResourceScope.None)]
2051         internal static extern
AdjustTokenPrivileges( [In] SafeAccessTokenHandle TokenHandle, [In] bool DisableAllPrivileges, [In] ref TOKEN_PRIVILEGE NewState, [In] uint BufferLength, [In,Out] ref TOKEN_PRIVILEGE PreviousState, [In,Out] ref uint ReturnLength)2052         bool AdjustTokenPrivileges (
2053             [In]     SafeAccessTokenHandle TokenHandle,
2054             [In]     bool                  DisableAllPrivileges,
2055             [In]     ref TOKEN_PRIVILEGE   NewState,
2056             [In]     uint                  BufferLength,
2057             [In,Out] ref TOKEN_PRIVILEGE   PreviousState,
2058             [In,Out] ref uint              ReturnLength);
2059 
2060         [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2061         [ResourceExposure(ResourceScope.None)]
2062         internal static extern
AllocateLocallyUniqueId( [In,Out] ref LUID Luid)2063         bool AllocateLocallyUniqueId(
2064             [In,Out] ref LUID              Luid);
2065 
2066         [DllImport(ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2067         [ResourceExposure(ResourceScope.None)]
2068         internal static extern
CheckTokenMembership( [In] SafeAccessTokenHandle TokenHandle, [In] byte[] SidToCheck, [In,Out] ref bool IsMember)2069         bool CheckTokenMembership(
2070             [In]     SafeAccessTokenHandle  TokenHandle,
2071             [In]     byte[]                 SidToCheck,
2072             [In,Out] ref bool               IsMember);
2073 
2074         [DllImport(
2075              ADVAPI32,
2076              EntryPoint="ConvertSecurityDescriptorToStringSecurityDescriptorW",
2077              CallingConvention=CallingConvention.Winapi,
2078              SetLastError=true,
2079              ExactSpelling=true,
2080              CharSet=CharSet.Unicode)]
2081         [ResourceExposure(ResourceScope.None)]
ConvertSdToStringSd( byte[] securityDescriptor, uint requestedRevision, ULONG securityInformation, out IntPtr resultString, ref ULONG resultStringLength )2082         internal static extern BOOL ConvertSdToStringSd(
2083             byte[] securityDescriptor,
2084             /* DWORD */ uint requestedRevision,
2085             ULONG securityInformation,
2086             out IntPtr resultString,
2087             ref ULONG resultStringLength );
2088 
2089         [DllImport(
2090              ADVAPI32,
2091              EntryPoint="ConvertStringSecurityDescriptorToSecurityDescriptorW",
2092              CallingConvention=CallingConvention.Winapi,
2093              SetLastError=true,
2094              ExactSpelling=true,
2095              CharSet=CharSet.Unicode)]
2096         [ResourceExposure(ResourceScope.None)]
ConvertStringSdToSd( string stringSd, uint stringSdRevision, out IntPtr resultSd, ref ULONG resultSdLength )2097         internal static extern BOOL ConvertStringSdToSd(
2098             string stringSd,
2099             /* DWORD */ uint stringSdRevision,
2100             out IntPtr resultSd,
2101             ref ULONG resultSdLength );
2102 
2103         [DllImport(
2104              ADVAPI32,
2105              EntryPoint="ConvertStringSidToSidW",
2106              CallingConvention=CallingConvention.Winapi,
2107              SetLastError=true,
2108              ExactSpelling=true,
2109              CharSet=CharSet.Unicode)]
2110         [ResourceExposure(ResourceScope.None)]
ConvertStringSidToSid( string stringSid, out IntPtr ByteArray )2111         internal static extern BOOL ConvertStringSidToSid(
2112             string stringSid,
2113             out IntPtr ByteArray
2114             );
2115 
2116         [DllImport(
2117            ADVAPI32,
2118            EntryPoint = "ConvertSidToStringSidW",
2119            CallingConvention = CallingConvention.Winapi,
2120            SetLastError = true,
2121            ExactSpelling = true,
2122            CharSet = CharSet.Unicode)]
2123         [ResourceExposure(ResourceScope.None)]
2124         [return: MarshalAs(UnmanagedType.Bool)]
ConvertSidToStringSid( IntPtr Sid, ref IntPtr StringSid )2125         internal static extern bool ConvertSidToStringSid(
2126             IntPtr Sid,
2127             ref IntPtr StringSid
2128             );
2129 
2130 
2131         [DllImport(
2132              ADVAPI32,
2133              EntryPoint="CreateWellKnownSid",
2134              CallingConvention=CallingConvention.Winapi,
2135              SetLastError=true,
2136              ExactSpelling=true,
2137              CharSet=CharSet.Unicode)]
2138         [ResourceExposure(ResourceScope.None)]
CreateWellKnownSid( int sidType, byte[] domainSid, [Out] byte[] resultSid, ref uint resultSidLength )2139         internal static extern BOOL CreateWellKnownSid(
2140             int sidType,
2141             byte[] domainSid,
2142             [Out] byte[] resultSid,
2143             ref /*DWORD*/ uint resultSidLength );
2144 
2145         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
2146         [ResourceExposure(ResourceScope.Machine)]
2147         internal static extern
DuplicateHandle( [In] IntPtr hSourceProcessHandle, [In] IntPtr hSourceHandle, [In] IntPtr hTargetProcessHandle, [In,Out] ref SafeAccessTokenHandle lpTargetHandle, [In] uint dwDesiredAccess, [In] bool bInheritHandle, [In] uint dwOptions)2148         bool DuplicateHandle (
2149             [In]     IntPtr                     hSourceProcessHandle,
2150             [In]     IntPtr                     hSourceHandle,
2151             [In]     IntPtr                     hTargetProcessHandle,
2152             [In,Out] ref SafeAccessTokenHandle  lpTargetHandle,
2153             [In]     uint                       dwDesiredAccess,
2154             [In]     bool                       bInheritHandle,
2155             [In]     uint                       dwOptions);
2156 
2157         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2158         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
2159         [ResourceExposure(ResourceScope.Machine)]
2160         internal static extern
DuplicateHandle( [In] IntPtr hSourceProcessHandle, [In] SafeAccessTokenHandle hSourceHandle, [In] IntPtr hTargetProcessHandle, [In,Out] ref SafeAccessTokenHandle lpTargetHandle, [In] uint dwDesiredAccess, [In] bool bInheritHandle, [In] uint dwOptions)2161         bool DuplicateHandle (
2162             [In]     IntPtr                     hSourceProcessHandle,
2163             [In]     SafeAccessTokenHandle      hSourceHandle,
2164             [In]     IntPtr                     hTargetProcessHandle,
2165             [In,Out] ref SafeAccessTokenHandle  lpTargetHandle,
2166             [In]     uint                       dwDesiredAccess,
2167             [In]     bool                       bInheritHandle,
2168             [In]     uint                       dwOptions);
2169 
2170 #if FEATURE_IMPERSONATION
2171         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2172         [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
2173         [ResourceExposure(ResourceScope.None)]
2174         internal static extern
DuplicateTokenEx( [In] SafeAccessTokenHandle ExistingTokenHandle, [In] TokenAccessLevels DesiredAccess, [In] IntPtr TokenAttributes, [In] SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, [In] System.Security.Principal.TokenType TokenType, [In,Out] ref SafeAccessTokenHandle DuplicateTokenHandle )2175         bool DuplicateTokenEx (
2176             [In]     SafeAccessTokenHandle       ExistingTokenHandle,
2177             [In]     TokenAccessLevels           DesiredAccess,
2178             [In]     IntPtr                      TokenAttributes,
2179             [In]     SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
2180             [In]     System.Security.Principal.TokenType TokenType,
2181             [In,Out] ref SafeAccessTokenHandle   DuplicateTokenHandle );
2182 
2183         [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
2184         [ResourceExposure(ResourceScope.None)]
2185         internal static extern
DuplicateTokenEx( [In] SafeAccessTokenHandle hExistingToken, [In] uint dwDesiredAccess, [In] IntPtr lpTokenAttributes, [In] uint ImpersonationLevel, [In] uint TokenType, [In,Out] ref SafeAccessTokenHandle phNewToken)2186         bool DuplicateTokenEx (
2187             [In]     SafeAccessTokenHandle      hExistingToken,
2188             [In]     uint                       dwDesiredAccess,
2189             [In]     IntPtr                     lpTokenAttributes,   // LPSECURITY_ATTRIBUTES
2190             [In]     uint                       ImpersonationLevel,
2191             [In]     uint                       TokenType,
2192             [In,Out] ref SafeAccessTokenHandle  phNewToken);
2193 #endif
2194         [DllImport(
2195              ADVAPI32,
2196              EntryPoint="EqualDomainSid",
2197              CallingConvention=CallingConvention.Winapi,
2198              SetLastError=true,
2199              ExactSpelling=true,
2200              CharSet=CharSet.Unicode)]
2201         [ResourceExposure(ResourceScope.None)]
IsEqualDomainSid( byte[] sid1, byte[] sid2, out bool result)2202         internal static extern BOOL IsEqualDomainSid(
2203             byte[] sid1,
2204             byte[] sid2,
2205             out bool result);
2206 
2207         [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
2208         [ResourceExposure(ResourceScope.Process)]
GetCurrentProcess()2209         internal static extern IntPtr GetCurrentProcess();
2210 
2211         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
2212         [ResourceExposure(ResourceScope.Process)]
GetCurrentThread()2213         internal static extern IntPtr GetCurrentThread();
2214 
2215         [DllImport(
2216              ADVAPI32,
2217              EntryPoint="GetSecurityDescriptorLength",
2218              CallingConvention=CallingConvention.Winapi,
2219              SetLastError=true,
2220              ExactSpelling=true,
2221              CharSet=CharSet.Unicode)]
2222         [ResourceExposure(ResourceScope.None)]
GetSecurityDescriptorLength( IntPtr byteArray )2223         internal static extern /*DWORD*/ uint GetSecurityDescriptorLength(
2224             IntPtr byteArray );
2225 
2226         [DllImport(
2227              ADVAPI32,
2228              EntryPoint="GetSecurityInfo",
2229              CallingConvention=CallingConvention.Winapi,
2230              SetLastError=true,
2231              ExactSpelling=true,
2232              CharSet=CharSet.Unicode)]
2233         [ResourceExposure(ResourceScope.None)]
GetSecurityInfoByHandle( SafeHandle handle, uint objectType, uint securityInformation, out IntPtr sidOwner, out IntPtr sidGroup, out IntPtr dacl, out IntPtr sacl, out IntPtr securityDescriptor )2234         internal static extern /*DWORD*/ uint GetSecurityInfoByHandle(
2235             SafeHandle handle,
2236             /*DWORD*/ uint objectType,
2237             /*DWORD*/ uint securityInformation,
2238             out IntPtr sidOwner,
2239             out IntPtr sidGroup,
2240             out IntPtr dacl,
2241             out IntPtr sacl,
2242             out IntPtr securityDescriptor );
2243 
2244         [DllImport(
2245              ADVAPI32,
2246              EntryPoint="GetNamedSecurityInfoW",
2247              CallingConvention=CallingConvention.Winapi,
2248              SetLastError=true,
2249              ExactSpelling=true,
2250              CharSet=CharSet.Unicode)]
2251         [ResourceExposure(ResourceScope.None)]
GetSecurityInfoByName( string name, uint objectType, uint securityInformation, out IntPtr sidOwner, out IntPtr sidGroup, out IntPtr dacl, out IntPtr sacl, out IntPtr securityDescriptor )2252         internal static extern /*DWORD*/ uint GetSecurityInfoByName(
2253             string name,
2254             /*DWORD*/ uint objectType,
2255             /*DWORD*/ uint securityInformation,
2256             out IntPtr sidOwner,
2257             out IntPtr sidGroup,
2258             out IntPtr dacl,
2259             out IntPtr sacl,
2260             out IntPtr securityDescriptor );
2261 
2262         [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
2263         [ResourceExposure(ResourceScope.None)]
2264         internal static extern
GetTokenInformation( [In] IntPtr TokenHandle, [In] uint TokenInformationClass, [In] SafeLocalAllocHandle TokenInformation, [In] uint TokenInformationLength, [Out] out uint ReturnLength)2265         bool GetTokenInformation (
2266             [In]  IntPtr                TokenHandle,
2267             [In]  uint                  TokenInformationClass,
2268             [In]  SafeLocalAllocHandle  TokenInformation,
2269             [In]  uint                  TokenInformationLength,
2270             [Out] out uint              ReturnLength);
2271 
2272         [DllImport(ADVAPI32, CharSet=CharSet.Auto, SetLastError=true)]
2273         [ResourceExposure(ResourceScope.None)]
2274         internal static extern
GetTokenInformation( [In] SafeAccessTokenHandle TokenHandle, [In] uint TokenInformationClass, [In] SafeLocalAllocHandle TokenInformation, [In] uint TokenInformationLength, [Out] out uint ReturnLength)2275         bool GetTokenInformation (
2276             [In]  SafeAccessTokenHandle TokenHandle,
2277             [In]  uint                  TokenInformationClass,
2278             [In]  SafeLocalAllocHandle  TokenInformation,
2279             [In]  uint                  TokenInformationLength,
2280             [Out] out uint              ReturnLength);
2281 
2282         [DllImport(
2283              ADVAPI32,
2284              EntryPoint="GetWindowsAccountDomainSid",
2285              CallingConvention=CallingConvention.Winapi,
2286              SetLastError=true,
2287              ExactSpelling=true,
2288              CharSet=CharSet.Unicode)]
2289         [ResourceExposure(ResourceScope.None)]
GetWindowsAccountDomainSid( byte[] sid, [Out] byte[] resultSid, ref uint resultSidLength )2290         internal static extern BOOL GetWindowsAccountDomainSid(
2291             byte[] sid,
2292             [Out] byte[] resultSid,
2293             ref /*DWORD*/ uint  resultSidLength );
2294 
2295         internal enum SECURITY_IMPERSONATION_LEVEL
2296         {
2297             Anonymous = 0,
2298             Identification = 1,
2299             Impersonation = 2,
2300             Delegation = 3,
2301         }
2302 
2303         // Structures and definitions for Claims that are being introduced in Win8
2304         // inside the NTTOken - see winnt.h.  They will be surfaced through WindowsIdentity.Claims
2305 
2306         // CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID -> 0x00
2307         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID = 0;
2308 
2309         // CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64 -> 0x01
2310         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64 = 1;
2311 
2312         // CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64 -> 0x02
2313         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64 = 2;
2314 
2315         // CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING -> 0x03
2316         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING = 3;
2317 
2318         // CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN -> 0x04
2319         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN = 4;
2320 
2321         // CLAIM_SECURITY_ATTRIBUTE_TYPE_SID -> 0x05
2322         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_SID = 5;
2323 
2324         // CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN -> 0x06
2325         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN = 6;
2326 
2327         // CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING -> 0x10
2328         internal const int CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING = 16;
2329 
2330         // CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE -> 0x0001
2331         internal const int CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE = 1;
2332 
2333         // CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE -> 0x0002
2334         internal const int CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE = 2;
2335 
2336         // CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY -> 0x0004
2337         internal const int CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY = 4;
2338 
2339         // CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT -> 0x0008
2340         internal const int CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT = 8;
2341 
2342         // CLAIM_SECURITY_ATTRIBUTE_DISABLED -> 0x0010
2343         internal const int CLAIM_SECURITY_ATTRIBUTE_DISABLED = 16;
2344 
2345         // CLAIM_SECURITY_ATTRIBUTE_MANDATORY -> 0x0020
2346         internal const int CLAIM_SECURITY_ATTRIBUTE_MANDATORY = 32;
2347 
2348         internal const int CLAIM_SECURITY_ATTRIBUTE_VALID_FLAGS =
2349                       CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE
2350                     | CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE
2351                     | CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY
2352                     | CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT
2353                     | CLAIM_SECURITY_ATTRIBUTE_DISABLED
2354                     | CLAIM_SECURITY_ATTRIBUTE_MANDATORY;
2355 
2356 
2357         [StructLayoutAttribute( LayoutKind.Explicit )]
2358         internal struct CLAIM_SECURITY_ATTRIBUTE_INFORMATION_V1
2359         {
2360             // defined as union in CLAIM_SECURITY_ATTRIBUTES_INFORMATION
2361             [FieldOffsetAttribute( 0 )]
2362             public IntPtr pAttributeV1;
2363         }
2364 
2365         [StructLayoutAttribute( LayoutKind.Sequential )]
2366         internal struct CLAIM_SECURITY_ATTRIBUTES_INFORMATION
2367         {
2368             /// WORD->unsigned short
2369             public ushort Version;
2370 
2371             /// WORD->unsigned short
2372             public ushort Reserved;
2373 
2374             /// DWORD->unsigned int
2375             public uint AttributeCount;
2376 
2377             /// CLAIM_SECURITY_ATTRIBUTE_V1
2378             public CLAIM_SECURITY_ATTRIBUTE_INFORMATION_V1 Attribute;
2379         }
2380 
2381         //
2382         //  Fully-qualified binary name.
2383         //
2384         [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
2385         internal struct CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE
2386         {
2387             // DWORD64->unsigned __int64
2388             public ulong Version;
2389 
2390             // PWSTR->WCHAR*
2391             [MarshalAsAttribute( UnmanagedType.LPWStr )]
2392             public string Name;
2393         }
2394 
2395         [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
2396         internal struct CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE
2397         {
2398             /// PVOID->void*
2399             public IntPtr pValue;
2400 
2401             /// DWORD->unsigned int
2402             public uint ValueLength;
2403         }
2404 
2405         [StructLayoutAttribute( LayoutKind.Explicit, CharSet = CharSet.Unicode )]
2406         internal struct CLAIM_VALUES_ATTRIBUTE_V1
2407         {
2408             // PLONG64->__int64*
2409             [FieldOffsetAttribute( 0 )]
2410             public IntPtr pInt64;
2411 
2412             // PDWORD64->unsigned __int64*
2413             [FieldOffsetAttribute( 0 )]
2414             public IntPtr pUint64;
2415 
2416             // PWSTR*
2417             [FieldOffsetAttribute( 0 )]
2418             public IntPtr ppString;
2419 
2420             // PCLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE->_CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE*
2421             [FieldOffsetAttribute( 0 )]
2422             public IntPtr pFqbn;
2423 
2424             // PCLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE->_CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE*
2425             [FieldOffsetAttribute( 0 )]
2426             public IntPtr pOctetString;
2427         }
2428 
2429         [StructLayoutAttribute( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
2430         internal struct CLAIM_SECURITY_ATTRIBUTE_V1
2431         {
2432             // PWSTR->WCHAR*
2433             [MarshalAsAttribute( UnmanagedType.LPWStr )]
2434             public string Name;
2435 
2436             // WORD->unsigned short
2437             public ushort ValueType;
2438 
2439             // WORD->unsigned short
2440             public ushort Reserved;
2441 
2442             // DWORD->unsigned int
2443             public uint Flags;
2444 
2445             // DWORD->unsigned int
2446             public uint ValueCount;
2447 
2448             // struct CLAIM_VALUES - a union of 4 possible values
2449             public CLAIM_VALUES_ATTRIBUTE_V1 Values;
2450         }
2451 
2452         [DllImport(
2453              ADVAPI32,
2454              EntryPoint="IsWellKnownSid",
2455              CallingConvention=CallingConvention.Winapi,
2456              SetLastError=true,
2457              ExactSpelling=true,
2458              CharSet=CharSet.Unicode)]
2459         [ResourceExposure(ResourceScope.None)]
IsWellKnownSid( byte[] sid, int type )2460         internal static extern BOOL IsWellKnownSid(
2461             byte[] sid,
2462             int type );
2463 
2464         [DllImport(
2465             ADVAPI32,
2466             EntryPoint="LsaOpenPolicy",
2467             CallingConvention=CallingConvention.Winapi,
2468             SetLastError=true,
2469             ExactSpelling=true,
2470             CharSet=CharSet.Unicode)]
2471         [ResourceExposure(ResourceScope.None)]
LsaOpenPolicy( string systemName, ref LSA_OBJECT_ATTRIBUTES attributes, int accessMask, out SafeLsaPolicyHandle handle )2472         internal static extern /*DWORD*/ uint LsaOpenPolicy(
2473             string systemName,
2474             ref LSA_OBJECT_ATTRIBUTES attributes,
2475             int accessMask,
2476             out SafeLsaPolicyHandle handle
2477             );
2478 
2479         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
2480         [DllImport(
2481             ADVAPI32,
2482             EntryPoint="LookupPrivilegeValueW",
2483             CharSet=CharSet.Auto,
2484             SetLastError=true,
2485             ExactSpelling=true,
2486             BestFitMapping=false)]
2487         [ResourceExposure(ResourceScope.None)]
2488         internal static extern
LookupPrivilegeValue( [In] string lpSystemName, [In] string lpName, [In,Out] ref LUID Luid)2489         bool LookupPrivilegeValue (
2490             [In]     string             lpSystemName,
2491             [In]     string             lpName,
2492             [In,Out] ref LUID           Luid);
2493 
2494         [DllImport(
2495             ADVAPI32,
2496             EntryPoint="LsaLookupSids",
2497             CallingConvention=CallingConvention.Winapi,
2498             SetLastError=true,
2499             ExactSpelling=true,
2500             CharSet=CharSet.Unicode)]
2501         [ResourceExposure(ResourceScope.None)]
LsaLookupSids( SafeLsaPolicyHandle handle, int count, IntPtr[] sids, ref SafeLsaMemoryHandle referencedDomains, ref SafeLsaMemoryHandle names )2502         internal static extern /*DWORD*/ uint LsaLookupSids(
2503             SafeLsaPolicyHandle handle,
2504             int count,
2505             IntPtr[] sids,
2506             ref SafeLsaMemoryHandle referencedDomains,
2507             ref SafeLsaMemoryHandle names
2508             );
2509 
2510         [DllImport(ADVAPI32, SetLastError=true)]
2511         [ResourceExposure(ResourceScope.None)]
2512         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
LsaFreeMemory( IntPtr handle )2513         internal static extern int LsaFreeMemory( IntPtr handle );
2514 
2515         [DllImport(
2516             ADVAPI32,
2517             EntryPoint="LsaLookupNames",
2518             CallingConvention=CallingConvention.Winapi,
2519             SetLastError=true,
2520             ExactSpelling=true,
2521             CharSet=CharSet.Unicode)]
2522         [ResourceExposure(ResourceScope.None)]
LsaLookupNames( SafeLsaPolicyHandle handle, int count, UNICODE_STRING[] names, ref SafeLsaMemoryHandle referencedDomains, ref SafeLsaMemoryHandle sids )2523         internal static extern /*DWORD*/ uint LsaLookupNames(
2524             SafeLsaPolicyHandle handle,
2525             int count,
2526             UNICODE_STRING[] names,
2527             ref SafeLsaMemoryHandle referencedDomains,
2528             ref SafeLsaMemoryHandle sids
2529             );
2530 
2531         [DllImport(
2532             ADVAPI32,
2533             EntryPoint="LsaLookupNames2",
2534             CallingConvention=CallingConvention.Winapi,
2535             SetLastError=true,
2536             ExactSpelling=true,
2537             CharSet=CharSet.Unicode)]
2538         [ResourceExposure(ResourceScope.None)]
LsaLookupNames2( SafeLsaPolicyHandle handle, int flags, int count, UNICODE_STRING[] names, ref SafeLsaMemoryHandle referencedDomains, ref SafeLsaMemoryHandle sids )2539         internal static extern /*DWORD*/ uint LsaLookupNames2(
2540             SafeLsaPolicyHandle handle,
2541             int flags,
2542             int count,
2543             UNICODE_STRING[] names,
2544             ref SafeLsaMemoryHandle referencedDomains,
2545             ref SafeLsaMemoryHandle sids
2546             );
2547 
2548         [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
2549         [ResourceExposure(ResourceScope.None)]
2550         internal static extern
LsaConnectUntrusted( [In,Out] ref SafeLsaLogonProcessHandle LsaHandle)2551         int LsaConnectUntrusted (
2552             [In,Out] ref SafeLsaLogonProcessHandle LsaHandle);
2553 
2554         [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
2555         [ResourceExposure(ResourceScope.None)]
2556         internal static extern
LsaGetLogonSessionData( [In] ref LUID LogonId, [In,Out] ref SafeLsaReturnBufferHandle ppLogonSessionData)2557         int LsaGetLogonSessionData (
2558             [In]     ref LUID                      LogonId,
2559             [In,Out] ref SafeLsaReturnBufferHandle ppLogonSessionData);
2560 
2561         [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
2562         [ResourceExposure(ResourceScope.None)]
2563         internal static extern
LsaLogonUser( [In] SafeLsaLogonProcessHandle LsaHandle, [In] ref UNICODE_INTPTR_STRING OriginName, [In] uint LogonType, [In] uint AuthenticationPackage, [In] IntPtr AuthenticationInformation, [In] uint AuthenticationInformationLength, [In] IntPtr LocalGroups, [In] ref TOKEN_SOURCE SourceContext, [In,Out] ref SafeLsaReturnBufferHandle ProfileBuffer, [In,Out] ref uint ProfileBufferLength, [In,Out] ref LUID LogonId, [In,Out] ref SafeAccessTokenHandle Token, [In,Out] ref QUOTA_LIMITS Quotas, [In,Out] ref int SubStatus)2564         int LsaLogonUser (
2565             [In]     SafeLsaLogonProcessHandle      LsaHandle,
2566             [In]     ref UNICODE_INTPTR_STRING      OriginName,
2567             [In]     uint                           LogonType,
2568             [In]     uint                           AuthenticationPackage,
2569             [In]     IntPtr                         AuthenticationInformation,
2570             [In]     uint                           AuthenticationInformationLength,
2571             [In]     IntPtr                         LocalGroups,
2572             [In]     ref TOKEN_SOURCE               SourceContext,
2573             [In,Out] ref SafeLsaReturnBufferHandle  ProfileBuffer,
2574             [In,Out] ref uint                       ProfileBufferLength,
2575             [In,Out] ref LUID                       LogonId,
2576             [In,Out] ref SafeAccessTokenHandle      Token,
2577             [In,Out] ref QUOTA_LIMITS               Quotas,
2578             [In,Out] ref int                        SubStatus);
2579 
2580         [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
2581         [ResourceExposure(ResourceScope.None)]
2582         internal static extern
LsaLookupAuthenticationPackage( [In] SafeLsaLogonProcessHandle LsaHandle, [In] ref UNICODE_INTPTR_STRING PackageName, [In,Out] ref uint AuthenticationPackage)2583         int LsaLookupAuthenticationPackage (
2584             [In]     SafeLsaLogonProcessHandle LsaHandle,
2585             [In]     ref UNICODE_INTPTR_STRING PackageName,
2586             [In,Out] ref uint                  AuthenticationPackage);
2587 
2588         [DllImport(SECUR32, CharSet=CharSet.Auto, SetLastError=true)]
2589         [ResourceExposure(ResourceScope.None)]
2590         internal static extern
LsaRegisterLogonProcess( [In] ref UNICODE_INTPTR_STRING LogonProcessName, [In,Out] ref SafeLsaLogonProcessHandle LsaHandle, [In,Out] ref IntPtr SecurityMode)2591         int LsaRegisterLogonProcess (
2592             [In]     ref UNICODE_INTPTR_STRING     LogonProcessName,
2593             [In,Out] ref SafeLsaLogonProcessHandle LsaHandle,
2594             [In,Out] ref IntPtr                    SecurityMode);
2595 
2596         [DllImport(SECUR32, SetLastError=true)]
2597         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
2598         [ResourceExposure(ResourceScope.None)]
LsaDeregisterLogonProcess(IntPtr handle)2599         internal static extern int LsaDeregisterLogonProcess(IntPtr handle);
2600 
2601         [DllImport(ADVAPI32, SetLastError=true)]
2602         [ResourceExposure(ResourceScope.None)]
2603         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
LsaClose( IntPtr handle )2604         internal static extern int LsaClose( IntPtr handle );
2605 
2606         [DllImport(SECUR32, SetLastError=true)]
2607         [ResourceExposure(ResourceScope.None)]
2608         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
LsaFreeReturnBuffer(IntPtr handle)2609         internal static extern int LsaFreeReturnBuffer(IntPtr handle);
2610 
2611 #if FEATURE_IMPERSONATION || FEATURE_CORECLR
2612         [DllImport (ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2613         [ResourceExposure(ResourceScope.Process)]
2614         internal static extern
OpenProcessToken( [In] IntPtr ProcessToken, [In] TokenAccessLevels DesiredAccess, [Out] out SafeAccessTokenHandle TokenHandle)2615         bool OpenProcessToken (
2616             [In]     IntPtr                     ProcessToken,
2617             [In]     TokenAccessLevels          DesiredAccess,
2618             [Out]    out SafeAccessTokenHandle  TokenHandle);
2619 #endif
2620 
2621 #if FEATURE_CORECLR
2622         [DllImport (ADVAPI32, CharSet=CharSet.Unicode, SetLastError=true)]
2623         [ResourceExposure(ResourceScope.Process)]
2624         [return: MarshalAs(UnmanagedType.Bool)]
2625         internal static extern
OpenThreadToken( [In] IntPtr ThreadHandle, [In] TokenAccessLevels DesiredAccess, [In, MarshalAs(UnmanagedType.Bool)] bool OpenAsSelf, [Out] out SafeAccessTokenHandle TokenHandle)2626         bool OpenThreadToken (
2627             [In]     IntPtr                     ThreadHandle,
2628             [In]     TokenAccessLevels          DesiredAccess,
2629             [In, MarshalAs(UnmanagedType.Bool)]     bool OpenAsSelf,
2630             [Out]    out SafeAccessTokenHandle  TokenHandle);
2631 #endif
2632 
2633         [DllImport(
2634              ADVAPI32,
2635              EntryPoint="SetNamedSecurityInfoW",
2636              CallingConvention=CallingConvention.Winapi,
2637              SetLastError=true,
2638              ExactSpelling=true,
2639              CharSet=CharSet.Unicode)]
2640         [ResourceExposure(ResourceScope.Machine)]
SetSecurityInfoByName( string name, uint objectType, uint securityInformation, byte[] owner, byte[] group, byte[] dacl, byte[] sacl )2641         internal static extern /*DWORD*/ uint SetSecurityInfoByName(
2642             string name,
2643             /*DWORD*/ uint objectType,
2644             /*DWORD*/ uint securityInformation,
2645             byte[] owner,
2646             byte[] group,
2647             byte[] dacl,
2648             byte[] sacl );
2649 
2650         [DllImport(
2651              ADVAPI32,
2652              EntryPoint="SetSecurityInfo",
2653              CallingConvention=CallingConvention.Winapi,
2654              SetLastError=true,
2655              ExactSpelling=true,
2656              CharSet=CharSet.Unicode)]
2657         [ResourceExposure(ResourceScope.None)]
SetSecurityInfoByHandle( SafeHandle handle, uint objectType, uint securityInformation, byte[] owner, byte[] group, byte[] dacl, byte[] sacl )2658         internal static extern /*DWORD*/ uint SetSecurityInfoByHandle(
2659             SafeHandle handle,
2660             /*DWORD*/ uint objectType,
2661             /*DWORD*/ uint securityInformation,
2662             byte[] owner,
2663             byte[] group,
2664             byte[] dacl,
2665             byte[] sacl );
2666 
2667 #else // FEATURE_PAL
2668 
2669         // managed cryptography wrapper around the PALRT cryptography api
2670         internal const int PAL_HCRYPTPROV = 123;
2671 
2672         internal const int CALG_MD2         = ((4 << 13) | 1);
2673         internal const int CALG_MD4         = ((4 << 13) | 2);
2674         internal const int CALG_MD5         = ((4 << 13) | 3);
2675         internal const int CALG_SHA         = ((4 << 13) | 4);
2676         internal const int CALG_SHA1        = ((4 << 13) | 4);
2677         internal const int CALG_MAC         = ((4 << 13) | 5);
2678         internal const int CALG_SSL3_SHAMD5 = ((4 << 13) | 8);
2679         internal const int CALG_HMAC        = ((4 << 13) | 9);
2680 
2681         internal const int HP_ALGID         = 0x0001;
2682         internal const int HP_HASHVAL       = 0x0002;
2683         internal const int HP_HASHSIZE      = 0x0004;
2684 
2685         [DllImport(OLEAUT32, CharSet=CharSet.Unicode)]
2686         [ResourceExposure(ResourceScope.Machine)]
CryptAcquireContext(out IntPtr hProv, [MarshalAs(UnmanagedType.LPWStr)] string container, [MarshalAs(UnmanagedType.LPWStr)] string provider, int provType, int flags)2687         internal extern static bool CryptAcquireContext(out IntPtr hProv,
2688                            [MarshalAs(UnmanagedType.LPWStr)] string container,
2689                            [MarshalAs(UnmanagedType.LPWStr)] string provider,
2690                            int provType,
2691                            int flags);
2692 
2693         [DllImport(OLEAUT32, SetLastError=true)]
2694         [ResourceExposure(ResourceScope.None)]
CryptReleaseContext( IntPtr hProv, int flags)2695         internal extern static bool CryptReleaseContext( IntPtr hProv, int flags);
2696 
2697         [DllImport(OLEAUT32, SetLastError=true)]
2698         [ResourceExposure(ResourceScope.None)]
CryptCreateHash(IntPtr hProv, int Algid, IntPtr hKey, int flags, out IntPtr hHash)2699         internal extern static bool CryptCreateHash(IntPtr hProv, int Algid, IntPtr hKey, int flags, out IntPtr hHash);
2700 
2701         [DllImport(OLEAUT32, SetLastError=true)]
2702         [ResourceExposure(ResourceScope.None)]
CryptDestroyHash(IntPtr hHash)2703         internal extern static bool CryptDestroyHash(IntPtr hHash);
2704 
2705         [DllImport(OLEAUT32, SetLastError=true)]
2706         [ResourceExposure(ResourceScope.None)]
CryptHashData(IntPtr hHash, [In, MarshalAs(UnmanagedType.LPArray)] byte[] data, int length, int flags)2707         internal extern static bool CryptHashData(IntPtr hHash,
2708                            [In, MarshalAs(UnmanagedType.LPArray)] byte[] data,
2709                            int length,
2710                            int flags);
2711 
2712         [DllImport(OLEAUT32, SetLastError=true)]
2713         [ResourceExposure(ResourceScope.None)]
CryptGetHashParam(IntPtr hHash, int param, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] digest, ref int length, int flags)2714         internal extern static bool CryptGetHashParam(IntPtr hHash,
2715                            int param,
2716                            [Out, MarshalAs(UnmanagedType.LPArray)] byte[] digest,
2717                            ref int length,
2718                            int flags);
2719 
2720         [DllImport(OLEAUT32, SetLastError=true)]
2721         [ResourceExposure(ResourceScope.None)]
CryptGetHashParam(IntPtr hHash, int param, out int data, ref int length, int flags)2722         internal extern static bool CryptGetHashParam(IntPtr hHash,
2723                            int param,
2724                            out int data,
2725                            ref int length,
2726                            int flags);
2727 
2728         [DllImport(KERNEL32, EntryPoint="PAL_Random")]
2729         [ResourceExposure(ResourceScope.None)]
Random(bool bStrong, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, int length)2730         internal extern static bool Random(bool bStrong,
2731                            [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, int length);
2732 #endif // FEATURE_PAL
2733 
2734         // Fusion APIs
2735 #if FEATURE_FUSION
2736         [DllImport(MSCORWKS, CharSet=CharSet.Unicode)]
2737         [ResourceExposure(ResourceScope.None)]
CreateAssemblyNameObject(out IAssemblyName ppEnum, String szAssemblyName, uint dwFlags, IntPtr pvReserved)2738         internal static extern int CreateAssemblyNameObject(out IAssemblyName ppEnum, String szAssemblyName, uint dwFlags, IntPtr pvReserved);
2739 
2740         [DllImport(MSCORWKS, CharSet=CharSet.Auto)]
2741         [ResourceExposure(ResourceScope.None)]
CreateAssemblyEnum(out IAssemblyEnum ppEnum, IApplicationContext pAppCtx, IAssemblyName pName, uint dwFlags, IntPtr pvReserved)2742         internal static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, IApplicationContext pAppCtx, IAssemblyName pName, uint dwFlags, IntPtr pvReserved);
2743 #endif // FEATURE_FUSION
2744 #if FEATURE_CORECLR
2745         [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
2746         [SuppressUnmanagedCodeSecurityAttribute()]
WideCharToMultiByte( int CodePage, UInt32 dwFlags, char* lpWideCharStr, int cchWideChar, byte* lpMultiByteStr, int cchMultiByte, char* lpDefaultChar, bool* lpUsedDefaultChar)2747         internal  unsafe static extern int WideCharToMultiByte(
2748             int     CodePage,
2749             UInt32    dwFlags,
2750             char*  lpWideCharStr,
2751             int      cchWideChar,
2752             byte*    lpMultiByteStr,
2753             int      cchMultiByte,
2754             char*   lpDefaultChar,
2755             bool*   lpUsedDefaultChar);
2756 
2757         [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
2758         [SuppressUnmanagedCodeSecurityAttribute()]
MultiByteToWideChar( int CodePage, UInt32 dwFlags, byte* lpMultiByteStr, int cchMultiByte, char* lpWideCharStr, int cchWideChar)2759         internal unsafe static extern int MultiByteToWideChar(
2760             int     CodePage,
2761             UInt32    dwFlags,
2762             byte*    lpMultiByteStr,
2763             int      cchMultiByte,
2764             char*  lpWideCharStr,
2765             int      cchWideChar);
2766 #endif  // FEATURE_CORECLR
2767 
2768         [DllImport(KERNEL32, SetLastError = true)]
2769         [return: MarshalAs(UnmanagedType.Bool)]
QueryUnbiasedInterruptTime(out ulong UnbiasedTime)2770         internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
2771 
2772 // This is needed by the RuntimeInformation feature
2773         [DllImport(NTDLL)]
RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation)2774         internal static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation);
2775 
2776         [StructLayout(LayoutKind.Sequential)]
2777         internal struct RTL_OSVERSIONINFOEX
2778         {
2779             internal uint dwOSVersionInfoSize;
2780             internal uint dwMajorVersion;
2781             internal uint dwMinorVersion;
2782             internal uint dwBuildNumber;
2783             internal uint dwPlatformId;
2784             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
2785             internal string szCSDVersion;
2786         }
2787 
2788         [DllImport(KERNEL32)]
GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo)2789         internal extern static void GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo);
2790 
2791         internal enum ProcessorArchitecture : ushort
2792         {
2793             Processor_Architecture_INTEL = 0,
2794             Processor_Architecture_ARM = 5,
2795             Processor_Architecture_IA64 = 6,
2796             Processor_Architecture_AMD64 = 9,
2797             Processor_Architecture_ARM64 = 12,
2798             Processor_Architecture_UNKNOWN = 0xFFFF
2799         }
2800 // end RuntimeInformation
2801     }
2802 }
2803