The Labs \ Source Viewer \ SSCLI \ Microsoft.Win32 \ Win32Native

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*============================================================
  16. **
  17. ** Class:  Microsoft.Win32.Win32Native
  18. **
  19. **
  20. ** Purpose: The CLR wrapper for all Win32 (Win2000, NT4, Win9x,
  21. **          as well as ROTOR-style Unix PAL, etc.) native operations
  22. **
  23. **
  24. ===========================================================*/
  25. /**
  26. * Notes to PInvoke users:  Getting the syntax exactly correct is crucial, and
  27. * more than a little confusing.  Here's some guidelines.
  28. *
  29. * For handles, you should use a SafeHandle subclass specific to your handle
  30. * type.  For files, we have the following set of interesting definitions:
  31. *
  32. *  [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
  33. *  private static extern SafeFileHandle CreateFile(...);
  34. *
  35. *  [DllImport(KERNEL32, SetLastError=true)]
  36. *  unsafe internal static extern int ReadFile(SafeFileHandle handle, ...);
  37. *
  38. *  [DllImport(KERNEL32, SetLastError=true)]
  39. *  internal static extern bool CloseHandle(IntPtr handle);
  40. *
  41. * P/Invoke will create the SafeFileHandle instance for you and assign the
  42. * return value from CreateFile into the handle atomically.  When we call
  43. * ReadFile, P/Invoke will increment a ref count, make the call, then decrement
  44. * it (preventing handle recycling vulnerabilities).  Then SafeFileHandle's
  45. * ReleaseHandle method will call CloseHandle, passing in the handle field
  46. * as an IntPtr.
  47. *
  48. * If for some reason you cannot use a SafeHandle subclass for your handles,
  49. * then use IntPtr as the handle type (or possibly HandleRef - understand when
  50. * to use GC.KeepAlive).  If your code will run in SQL Server (or any other
  51. * long-running process that can't be recycled easily), use a constrained
  52. * execution region to prevent thread aborts while allocating your
  53. * handle, and consider making your handle wrapper subclass
  54. * CriticalFinalizerObject to ensure you can free the handle.  As you can
  55. * probably guess, SafeHandle  will save you a lot of headaches if your code
  56. * needs to be robust to thread aborts and OOM.
  57. *
  58. *
  59. * If you have a method that takes a native struct, you have two options for
  60. * declaring that struct.  You can make it a value type ('struct' in CSharp),
  61. * or a reference type ('class').  This choice doesn't seem very interesting,
  62. * but your function prototype must use different syntax depending on your
  63. * choice.  For example, if your native method is prototyped as such:
  64. *
  65. *    bool GetVersionEx(OSVERSIONINFO & lposvi);
  66. *
  67. *
  68. * you must use EITHER THIS OR THE NEXT syntax:
  69. *
  70. *    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
  71. *    internal struct OSVERSIONINFO {  ...  }
  72. *
  73. *    [DllImport(KERNEL32, CharSet=CharSet.Auto)]
  74. *    internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi);
  75. *
  76. * OR:
  77. *
  78. *    [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
  79. *    internal class OSVERSIONINFO {  ...  }
  80. *
  81. *    [DllImport(KERNEL32, CharSet=CharSet.Auto)]
  82. *    internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi);
  83. *
  84. * Note that classes require being marked as [In, Out] while value types must
  85. * be passed as ref parameters.
  86. *
  87. * Also note the CharSet.Auto on GetVersionEx - while it does not take a String
  88. * as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so
  89. * the size of the struct varies on different platforms, and there's a
  90. * GetVersionExA & a GetVersionExW.  Also, the OSVERSIONINFO struct has a sizeof
  91. * field so the OS can ensure you've passed in the correctly-sized copy of an
  92. * OSVERSIONINFO.  You must explicitly set this using Marshal.SizeOf(Object);
  93. *
  94. * For security reasons, if you're making a P/Invoke method to a Win32 method
  95. * that takes an ANSI String (or will be ANSI on Win9x) and that String is the
  96. * name of some resource you've done a security check on (such as a file name),
  97. * you want to disable best fit mapping in WideCharToMultiByte.  Do this by
  98. * setting BestFitMapping=false in your DllImportAttribute.
  99. */
  100. namespace Microsoft.Win32
  101. {
  102.     using System;
  103.     using System.Security;
  104.     using System.Security.Principal;
  105.     using System.Text;
  106.     using System.Configuration.Assemblies;
  107.     using System.Runtime.Remoting;
  108.     using System.Runtime.InteropServices;
  109.     using System.Threading;
  110.     using Microsoft.Win32.SafeHandles;
  111.     using System.Runtime.ConstrainedExecution;
  112.     using System.Runtime.Versioning;
  113.    
  114.     using BOOL = System.Int32;
  115.     using DWORD = System.UInt32;
  116.     using ULONG = System.UInt32;
  117.    
  118. /**
  119.     * Win32 encapsulation for MSCORLIB.
  120.     */   
  121.     // Remove the default demands for all N/Direct methods with this
  122.     // global declaration on the class.
  123.     //
  124.     [SuppressUnmanagedCodeSecurityAttribute()]
  125.     static internal class Win32Native
  126.     {
  127.        
  128.        
  129.         // Win32 ACL-related constants:
  130.         internal const int READ_CONTROL = 131072;
  131.         internal const int SYNCHRONIZE = 1048576;
  132.        
  133.         internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
  134.         internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
  135.        
  136.         // STANDARD_RIGHTS_REQUIRED (0x000F0000L)
  137.         // SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
  138.        
  139.         // SEMAPHORE and Event both use 0x0002
  140.         // MUTEX uses 0x001 (MUTANT_QUERY_STATE)
  141.        
  142.         // Note that you may need to specify the SYNCHRONIZE bit as well
  143.         // to be able to open a synchronization primitive.
  144.         internal const int SEMAPHORE_MODIFY_STATE = 2;
  145.         internal const int EVENT_MODIFY_STATE = 2;
  146.         internal const int MUTEX_MODIFY_STATE = 1;
  147.         internal const int MUTEX_ALL_ACCESS = 2031617;
  148.        
  149.        
  150.         internal const int LMEM_FIXED = 0;
  151.         internal const int LMEM_ZEROINIT = 64;
  152.         internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
  153.        
  154.         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  155.         internal class OSVERSIONINFO
  156.         {
  157.             internal OSVERSIONINFO()
  158.             {
  159.                 OSVersionInfoSize = (int)Marshal.SizeOf(this);
  160.             }
  161.            
  162.             // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
  163.             internal int OSVersionInfoSize = 0;
  164.             internal int MajorVersion = 0;
  165.             internal int MinorVersion = 0;
  166.             internal int BuildNumber = 0;
  167.             internal int PlatformId = 0;
  168.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
  169.             internal string CSDVersion = null;
  170.         }
  171.        
  172.         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  173.         internal class OSVERSIONINFOEX
  174.         {
  175.            
  176.             public OSVERSIONINFOEX()
  177.             {
  178.                 OSVersionInfoSize = (int)Marshal.SizeOf(this);
  179.             }
  180.            
  181.             // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
  182.             internal int OSVersionInfoSize = 0;
  183.             internal int MajorVersion = 0;
  184.             internal int MinorVersion = 0;
  185.             internal int BuildNumber = 0;
  186.             internal int PlatformId = 0;
  187.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
  188.             internal string CSDVersion = null;
  189.             internal ushort ServicePackMajor = 0;
  190.             internal ushort ServicePackMinor = 0;
  191.             internal short SuiteMask = 0;
  192.             internal byte ProductType = 0;
  193.             internal byte Reserved = 0;
  194.         }
  195.        
  196.         [StructLayout(LayoutKind.Sequential)]
  197.         internal struct SYSTEM_INFO
  198.         {
  199.             internal int dwOemId;
  200.             // This is a union of a DWORD and a struct containing 2 WORDs.
  201.             internal int dwPageSize;
  202.             internal IntPtr lpMinimumApplicationAddress;
  203.             internal IntPtr lpMaximumApplicationAddress;
  204.             internal IntPtr dwActiveProcessorMask;
  205.             internal int dwNumberOfProcessors;
  206.             internal int dwProcessorType;
  207.             internal int dwAllocationGranularity;
  208.             internal short wProcessorLevel;
  209.             internal short wProcessorRevision;
  210.         }
  211.        
  212.         [StructLayout(LayoutKind.Sequential)]
  213.         internal class SECURITY_ATTRIBUTES
  214.         {
  215.             internal int nLength = 0;
  216.             unsafe internal byte* pSecurityDescriptor = null;
  217.             internal int bInheritHandle = 0;
  218.         }
  219.        
  220.         [StructLayout(LayoutKind.Sequential), Serializable()]
  221.         internal struct WIN32_FILE_ATTRIBUTE_DATA
  222.         {
  223.             internal int fileAttributes;
  224.             internal uint ftCreationTimeLow;
  225.             internal uint ftCreationTimeHigh;
  226.             internal uint ftLastAccessTimeLow;
  227.             internal uint ftLastAccessTimeHigh;
  228.             internal uint ftLastWriteTimeLow;
  229.             internal uint ftLastWriteTimeHigh;
  230.             internal int fileSizeHigh;
  231.             internal int fileSizeLow;
  232.         }
  233.        
  234.         [StructLayout(LayoutKind.Sequential)]
  235.         internal struct FILE_TIME
  236.         {
  237.             public FILE_TIME(long fileTime)
  238.             {
  239.                 ftTimeLow = (uint)fileTime;
  240.                 ftTimeHigh = (uint)(fileTime >> 32);
  241.             }
  242.            
  243.             public long ToTicks()
  244.             {
  245.                 return ((long)ftTimeHigh << 32) + ftTimeLow;
  246.             }
  247.            
  248.             internal uint ftTimeLow;
  249.             internal uint ftTimeHigh;
  250.         }
  251.        
  252.        
  253.        
  254.         #if !PLATFORM_UNIX
  255.         internal const string DLLPREFIX = "";
  256.         internal const string DLLSUFFIX = ".dll";
  257.         #else // !PLATFORM_UNIX
  258.         #if __APPLE__
  259.         internal const string DLLPREFIX = "lib";
  260.         internal const string DLLSUFFIX = ".dylib";
  261.         #else
  262.         internal const string DLLPREFIX = "lib";
  263.         internal const string DLLSUFFIX = ".so";
  264.         #endif
  265.         #endif // !PLATFORM_UNIX
  266.        
  267.         internal const string KERNEL32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
  268.         internal const string USER32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
  269.         internal const string ADVAPI32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
  270.         internal const string OLE32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
  271.         internal const string OLEAUT32 = DLLPREFIX + "rotor_palrt" + DLLSUFFIX;
  272.         internal const string SHIM = DLLPREFIX + "sscoree" + DLLSUFFIX;
  273.         internal const string MSCORWKS = DLLPREFIX + "mscorwks" + DLLSUFFIX;
  274.        
  275.        
  276.         internal const string LSTRCPY = "lstrcpy";
  277.         internal const string LSTRCPYN = "lstrcpyn";
  278.         internal const string LSTRLEN = "lstrlen";
  279.         internal const string LSTRLENA = "lstrlenA";
  280.         internal const string LSTRLENW = "lstrlenW";
  281.         internal const string MOVEMEMORY = "RtlMoveMemory";
  282.        
  283.        
  284.         // From WinBase.h
  285.         internal const int SEM_FAILCRITICALERRORS = 1;
  286.        
  287.         [DllImport(KERNEL32, SetLastError = true)]
  288.         [ResourceExposure(ResourceScope.None)]
  289.         static internal extern void SetLastError(int errorCode);
  290.        
  291.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  292.         [ResourceExposure(ResourceScope.None)]
  293.         static internal extern bool GetVersionEx(        [In(), Out()]
  294. OSVERSIONINFO ver);
  295.        
  296.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  297.         [ResourceExposure(ResourceScope.None)]
  298.         static internal extern bool GetVersionEx(        [In(), Out()]
  299. OSVERSIONINFOEX ver);
  300.        
  301.         [DllImport(KERNEL32, SetLastError = true)]
  302.         [ResourceExposure(ResourceScope.None)]
  303.         static internal extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
  304.        
  305.         [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)]
  306.         [ResourceExposure(ResourceScope.None)]
  307.         static internal extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments);
  308.        
  309.         // Gets an error message for a Win32 error code.
  310.         static internal string GetMessage(int errorCode)
  311.         {
  312.             StringBuilder sb = new StringBuilder(512);
  313.             int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, Win32Native.NULL, errorCode, 0, sb, sb.Capacity, Win32Native.NULL);
  314.             if (result != 0) {
  315.                 // result is the # of characters copied to the StringBuilder on NT,
  316.                 // but on Win9x, it appears to be the number of MBCS bytes.
  317.                 // Just give up and return the String as-is...
  318.                 string s = sb.ToString();
  319.                 return s;
  320.             }
  321.             else {
  322.                 return Environment.GetResourceString("UnknownError_Num", errorCode);
  323.             }
  324.         }
  325.        
  326.         [DllImport(KERNEL32, EntryPoint = "LocalAlloc")]
  327.         [ResourceExposure(ResourceScope.None)]
  328.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  329.         static internal extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, IntPtr sizetdwBytes);
  330.        
  331.        
  332.         [DllImport(KERNEL32, SetLastError = true)]
  333.         [ResourceExposure(ResourceScope.None)]
  334.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  335.         static internal extern IntPtr LocalFree(IntPtr handle);
  336.        
  337.         [DllImport(KERNEL32, SetLastError = true)]
  338.         [ResourceExposure(ResourceScope.None)]
  339.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  340.         static internal extern void ZeroMemory(IntPtr handle, uint length);
  341.        
  342.        
  343.         [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)]
  344.         [ResourceExposure(ResourceScope.Machine)]
  345.         static internal extern uint GetTempPath(int bufferLen, StringBuilder buffer);
  346.        
  347.         [DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRCPY, BestFitMapping = false)]
  348.         [ResourceExposure(ResourceScope.None)]
  349.         static internal extern IntPtr lstrcpy(IntPtr dst, string src);
  350.        
  351.         [DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRCPY, BestFitMapping = false)]
  352.         [ResourceExposure(ResourceScope.None)]
  353.         static internal extern IntPtr lstrcpy(StringBuilder dst, IntPtr src);
  354.        
  355.         [DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRLEN)]
  356.         [ResourceExposure(ResourceScope.None)]
  357.         static internal extern int lstrlen(sbyte[] ptr);
  358.        
  359.         [DllImport(KERNEL32, CharSet = CharSet.Auto, EntryPoint = LSTRLEN)]
  360.         [ResourceExposure(ResourceScope.None)]
  361.         static internal extern int lstrlen(IntPtr ptr);
  362.        
  363.         [DllImport(KERNEL32, CharSet = CharSet.Ansi, EntryPoint = LSTRLENA)]
  364.         [ResourceExposure(ResourceScope.None)]
  365.         static internal extern int lstrlenA(IntPtr ptr);
  366.        
  367.         [DllImport(KERNEL32, CharSet = CharSet.Unicode, EntryPoint = LSTRLENW)]
  368.         [ResourceExposure(ResourceScope.None)]
  369.         static internal extern int lstrlenW(IntPtr ptr);
  370.        
  371.         [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
  372.         [ResourceExposure(ResourceScope.None)]
  373.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  374.         static internal extern IntPtr SysAllocStringLen(string src, int len);
  375.         // BSTR
  376.         [DllImport(Win32Native.OLEAUT32)]
  377.         [ResourceExposure(ResourceScope.None)]
  378.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  379.         static internal extern int SysStringLen(IntPtr bstr);
  380.        
  381.         [DllImport(Win32Native.OLEAUT32)]
  382.         [ResourceExposure(ResourceScope.None)]
  383.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  384.         static internal extern void SysFreeString(IntPtr bstr);
  385.        
  386.         [DllImport(KERNEL32, CharSet = CharSet.Unicode, EntryPoint = MOVEMEMORY)]
  387.         [ResourceExposure(ResourceScope.None)]
  388.         static internal extern void CopyMemoryUni(IntPtr pdst, string psrc, IntPtr sizetcb);
  389.        
  390.         [DllImport(KERNEL32, CharSet = CharSet.Unicode, EntryPoint = MOVEMEMORY)]
  391.         [ResourceExposure(ResourceScope.None)]
  392.         static internal extern void CopyMemoryUni(StringBuilder pdst, IntPtr psrc, IntPtr sizetcb);
  393.        
  394.         [DllImport(KERNEL32, CharSet = CharSet.Ansi, EntryPoint = MOVEMEMORY, BestFitMapping = false)]
  395.         [ResourceExposure(ResourceScope.None)]
  396.         static internal extern void CopyMemoryAnsi(IntPtr pdst, string psrc, IntPtr sizetcb);
  397.        
  398.         [DllImport(KERNEL32, CharSet = CharSet.Ansi, EntryPoint = MOVEMEMORY, BestFitMapping = false)]
  399.         [ResourceExposure(ResourceScope.None)]
  400.         static internal extern void CopyMemoryAnsi(StringBuilder pdst, IntPtr psrc, IntPtr sizetcb);
  401.        
  402.        
  403.         [DllImport(KERNEL32)]
  404.         [ResourceExposure(ResourceScope.None)]
  405.         static internal extern int GetACP();
  406.        
  407.         [DllImport(KERNEL32, SetLastError = true)]
  408.         [ResourceExposure(ResourceScope.None)]
  409.         static internal extern bool SetEvent(SafeWaitHandle handle);
  410.        
  411.         [DllImport(KERNEL32, SetLastError = true)]
  412.         [ResourceExposure(ResourceScope.None)]
  413.         static internal extern bool ResetEvent(SafeWaitHandle handle);
  414.        
  415.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  416.         [ResourceExposure(ResourceScope.Machine)]
  417.         // Machine or none based on the value of "name"
  418.         static internal extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, string name);
  419.        
  420.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  421.         [ResourceExposure(ResourceScope.Machine)]
  422.             /* DWORD */        static internal extern SafeWaitHandle OpenEvent(int desiredAccess, bool inheritHandle, string name);
  423.        
  424.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  425.         [ResourceExposure(ResourceScope.Machine)]
  426.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  427.         static internal extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, string name);
  428.        
  429.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  430.         [ResourceExposure(ResourceScope.Machine)]
  431.             /* DWORD */        static internal extern SafeWaitHandle OpenMutex(int desiredAccess, bool inheritHandle, string name);
  432.        
  433.         [DllImport(KERNEL32, SetLastError = true)]
  434.         [ResourceExposure(ResourceScope.None)]
  435.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  436.         static internal extern bool ReleaseMutex(SafeWaitHandle handle);
  437.        
  438.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  439.         [ResourceExposure(ResourceScope.Machine)]
  440.         static internal extern int GetFullPathName(        [In()]
  441. char[] path, int numBufferChars,         [Out()]
  442. char[] buffer, IntPtr mustBeZero);
  443.        
  444.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  445.         [ResourceExposure(ResourceScope.Machine)]
  446.         unsafe static internal extern int GetFullPathName(char* path, int numBufferChars, char* buffer, IntPtr mustBeZero);
  447.        
  448.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  449.         [ResourceExposure(ResourceScope.Machine)]
  450.         static internal extern int GetLongPathName(string path, StringBuilder longPathBuffer, int bufferLength);
  451.        
  452.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  453.         [ResourceExposure(ResourceScope.Machine)]
  454.         static internal extern int GetLongPathName(        [In()]
  455. char[] path,         [Out()]
  456. char[] longPathBuffer, int bufferLength);
  457.        
  458.        
  459.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  460.         [ResourceExposure(ResourceScope.Machine)]
  461.         unsafe static internal extern int GetLongPathName(char* path, char* longPathBuffer, int bufferLength);
  462.        
  463.         // Disallow access to all non-file devices from methods that take
  464.         // a String. This disallows DOS devices like "con:", "com1:",
  465.         // "lpt1:", etc. Use this to avoid security problems, like allowing
  466.         // a web client asking a server for "http://server/com1.aspx" and
  467.         // then causing a worker process to hang.
  468.         [ResourceExposure(ResourceScope.Machine)]
  469.         [ResourceConsumption(ResourceScope.Machine)]
  470.         static internal SafeFileHandle SafeCreateFile(string lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
  471.         {
  472.             SafeFileHandle handle = CreateFile(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
  473.            
  474.             if (!handle.IsInvalid) {
  475.                 int fileType = Win32Native.GetFileType(handle);
  476.                 if (fileType != Win32Native.FILE_TYPE_DISK) {
  477.                     handle.Dispose();
  478.                     throw new NotSupportedException(Environment.GetResourceString("NotSupported_FileStreamOnNonFiles"));
  479.                 }
  480.             }
  481.            
  482.             return handle;
  483.         }
  484.        
  485.         [ResourceExposure(ResourceScope.Machine)]
  486.         [ResourceConsumption(ResourceScope.Machine)]
  487.         static internal SafeFileHandle UnsafeCreateFile(string lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
  488.         {
  489.             SafeFileHandle handle = CreateFile(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
  490.            
  491.             return handle;
  492.         }
  493.        
  494.         // Do not use these directly, use the safe or unsafe versions above.
  495.         // The safe version does not support devices (aka if will only open
  496.         // files on disk), while the unsafe version give you the full semantic
  497.         // of the native version.
  498.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  499.         [ResourceExposure(ResourceScope.Machine)]
  500.         private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, System.IO.FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
  501.        
  502.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  503.         [ResourceExposure(ResourceScope.Machine)]
  504.         static internal extern SafeFileMappingHandle CreateFileMapping(SafeFileHandle hFile, IntPtr lpAttributes, uint fProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
  505.        
  506.         [DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
  507.         [ResourceExposure(ResourceScope.Machine)]
  508.         static internal extern SafeViewOfFileHandle MapViewOfFile(SafeFileMappingHandle handle, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, UIntPtr dwNumerOfBytesToMap);
  509.        
  510.         [DllImport(KERNEL32, ExactSpelling = true)]
  511.         [ResourceExposure(ResourceScope.Machine)]
  512.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  513.         static internal extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
  514.        
  515.         [DllImport(KERNEL32, SetLastError = true)]
  516.         [ResourceExposure(ResourceScope.Machine)]
  517.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  518.         static internal extern bool CloseHandle(IntPtr handle);
  519.        
  520.         [DllImport(KERNEL32)]
  521.         [ResourceExposure(ResourceScope.None)]
  522.         static internal extern int GetFileType(SafeFileHandle handle);
  523.        
  524.         [DllImport(KERNEL32, SetLastError = true)]
  525.         [ResourceExposure(ResourceScope.None)]
  526.         static internal extern bool SetEndOfFile(SafeFileHandle hFile);
  527.        
  528.         [DllImport(KERNEL32, SetLastError = true, EntryPoint = "SetFilePointer")]
  529.         [ResourceExposure(ResourceScope.None)]
  530.         unsafe private static extern int SetFilePointerWin32(SafeFileHandle handle, int lo, int* hi, int origin);
  531.        
  532.         [ResourceExposure(ResourceScope.None)]
  533.         unsafe static internal long SetFilePointer(SafeFileHandle handle, long offset, System.IO.SeekOrigin origin, out int hr)
  534.         {
  535.             hr = 0;
  536.             int lo = (int)offset;
  537.             int hi = (int)(offset >> 32);
  538.             lo = SetFilePointerWin32(handle, lo, &hi, (int)origin);
  539.            
  540.             if (lo == -1 && ((hr = Marshal.GetLastWin32Error()) != 0))
  541.                 return -1;
  542.             return (long)(((ulong)((uint)hi)) << 32) | ((uint)lo);
  543.         }
  544.        
  545.         // Note there are two different ReadFile prototypes - this is to use
  546.         // the type system to force you to not trip across a "feature" in
  547.         // Win32's async IO support. You can't do the following three things
  548.         // simultaneously: overlapped IO, free the memory for the overlapped
  549.         // struct in a callback (or an EndRead method called by that callback),
  550.         // and pass in an address for the numBytesRead parameter.
  551.        
  552.         [DllImport(KERNEL32, SetLastError = true)]
  553.         [ResourceExposure(ResourceScope.None)]
  554.         unsafe static internal extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
  555.        
  556.         [DllImport(KERNEL32, SetLastError = true)]
  557.         [ResourceExposure(ResourceScope.None)]
  558.         unsafe static internal extern int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
  559.        
  560.         // Note there are two different WriteFile prototypes - this is to use
  561.         // the type system to force you to not trip across a "feature" in
  562.         // Win32's async IO support. You can't do the following three things
  563.         // simultaneously: overlapped IO, free the memory for the overlapped
  564.         // struct in a callback (or an EndWrite method called by that callback),
  565.         // and pass in an address for the numBytesRead parameter.
  566.        
  567.         [DllImport(KERNEL32, SetLastError = true)]
  568.         [ResourceExposure(ResourceScope.None)]
  569.         unsafe static internal extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
  570.        
  571.         [DllImport(KERNEL32, SetLastError = true)]
  572.         [ResourceExposure(ResourceScope.None)]
  573.         unsafe static internal extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
  574.        
  575.        
  576.         // NOTE: The out parameters are PULARGE_INTEGERs and may require
  577.         // some byte munging magic.
  578.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  579.         [ResourceExposure(ResourceScope.None)]
  580.         static internal extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
  581.        
  582.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  583.         [ResourceExposure(ResourceScope.None)]
  584.         static internal extern int GetDriveType(string drive);
  585.        
  586.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  587.         [ResourceExposure(ResourceScope.None)]
  588.         static internal extern bool GetVolumeInformation(string drive, StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, StringBuilder fileSystemName, int fileSystemNameBufLen);
  589.        
  590.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  591.         [ResourceExposure(ResourceScope.None)]
  592.         static internal extern bool SetVolumeLabel(string driveLetter, string volumeName);
  593.        
  594.        
  595.         [DllImport(KERNEL32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "PAL_GetPALDirectoryW", BestFitMapping = false)]
  596.         [ResourceExposure(ResourceScope.Machine)]
  597.         static internal extern int GetSystemDirectory(StringBuilder sb, int length);
  598.        
  599.         [DllImport(OLEAUT32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "PAL_FetchConfigurationStringW")]
  600.         [ResourceExposure(ResourceScope.Machine)]
  601.         static internal extern bool FetchConfigurationString(bool perMachine, string parameterName, StringBuilder parameterValue, int parameterValueLength);
  602.        
  603.         [DllImport(KERNEL32, SetLastError = true)]
  604.         [ResourceExposure(ResourceScope.None)]
  605.         unsafe static internal extern bool SetFileTime(SafeFileHandle hFile, FILE_TIME* creationTime, FILE_TIME* lastAccessTime, FILE_TIME* lastWriteTime);
  606.        
  607.         [DllImport(KERNEL32, SetLastError = true)]
  608.         [ResourceExposure(ResourceScope.None)]
  609.         static internal extern int GetFileSize(SafeFileHandle hFile, out int highSize);
  610.        
  611.         [DllImport(KERNEL32, SetLastError = true)]
  612.         [ResourceExposure(ResourceScope.None)]
  613.         static internal extern bool LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
  614.        
  615.         [DllImport(KERNEL32, SetLastError = true)]
  616.         [ResourceExposure(ResourceScope.None)]
  617.         static internal extern bool UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
  618.        
  619.         static internal readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
  620.         // WinBase.h
  621.         static internal readonly IntPtr NULL = IntPtr.Zero;
  622.        
  623.         // Note, these are #defines used to extract handles, and are NOT handles.
  624.         internal const int STD_INPUT_HANDLE = -10;
  625.         internal const int STD_OUTPUT_HANDLE = -11;
  626.         internal const int STD_ERROR_HANDLE = -12;
  627.        
  628.         [DllImport(KERNEL32, SetLastError = true)]
  629.         [ResourceExposure(ResourceScope.Process)]
  630.         static internal extern IntPtr GetStdHandle(int nStdHandle);
  631.         // param is NOT a handle, but it returns one!
  632.         // From wincon.h
  633.         internal const int CTRL_C_EVENT = 0;
  634.         internal const int CTRL_BREAK_EVENT = 1;
  635.         internal const int CTRL_CLOSE_EVENT = 2;
  636.         internal const int CTRL_LOGOFF_EVENT = 5;
  637.         internal const int CTRL_SHUTDOWN_EVENT = 6;
  638.         internal const short KEY_EVENT = 1;
  639.        
  640.         // From WinBase.h
  641.         internal const int FILE_TYPE_DISK = 1;
  642.         internal const int FILE_TYPE_CHAR = 2;
  643.         internal const int FILE_TYPE_PIPE = 3;
  644.        
  645.         internal const int REPLACEFILE_WRITE_THROUGH = 1;
  646.         internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 2;
  647.        
  648.         private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512;
  649.         private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096;
  650.         private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192;
  651.        
  652.         // Constants from WinNT.h
  653.         internal const int FILE_ATTRIBUTE_READONLY = 1;
  654.         internal const int FILE_ATTRIBUTE_DIRECTORY = 16;
  655.         internal const int FILE_ATTRIBUTE_REPARSE_POINT = 1024;
  656.        
  657.         internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)2684354563u);
  658.        
  659.         internal const int PAGE_READWRITE = 4;
  660.        
  661.         internal const int MEM_COMMIT = 4096;
  662.         internal const int MEM_RESERVE = 8192;
  663.         internal const int MEM_RELEASE = 32768;
  664.         internal const int MEM_FREE = 65536;
  665.        
  666.         // Error codes from WinError.h
  667.         internal const int ERROR_SUCCESS = 0;
  668.         internal const int ERROR_INVALID_FUNCTION = 1;
  669.         internal const int ERROR_FILE_NOT_FOUND = 2;
  670.         internal const int ERROR_PATH_NOT_FOUND = 3;
  671.         internal const int ERROR_ACCESS_DENIED = 5;
  672.         internal const int ERROR_INVALID_HANDLE = 6;
  673.         internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
  674.         internal const int ERROR_INVALID_DATA = 13;
  675.         internal const int ERROR_INVALID_DRIVE = 15;
  676.         internal const int ERROR_NO_MORE_FILES = 18;
  677.         internal const int ERROR_NOT_READY = 21;
  678.         internal const int ERROR_BAD_LENGTH = 24;
  679.         internal const int ERROR_SHARING_VIOLATION = 32;
  680.         internal const int ERROR_NOT_SUPPORTED = 50;
  681.         internal const int ERROR_FILE_EXISTS = 80;
  682.         internal const int ERROR_INVALID_PARAMETER = 87;
  683.         internal const int ERROR_CALL_NOT_IMPLEMENTED = 120;
  684.         internal const int ERROR_INSUFFICIENT_BUFFER = 122;
  685.         internal const int ERROR_INVALID_NAME = 123;
  686.         internal const int ERROR_BAD_PATHNAME = 161;
  687.         internal const int ERROR_ALREADY_EXISTS = 183;
  688.         internal const int ERROR_ENVVAR_NOT_FOUND = 203;
  689.         internal const int ERROR_FILENAME_EXCED_RANGE = 206;
  690.         // filename too long.
  691.         internal const int ERROR_NO_DATA = 232;
  692.         internal const int ERROR_PIPE_NOT_CONNECTED = 233;
  693.         internal const int ERROR_MORE_DATA = 234;
  694.         internal const int ERROR_OPERATION_ABORTED = 995;
  695.         // 995; For IO Cancellation
  696.         internal const int ERROR_NO_TOKEN = 1008;
  697.         internal const int ERROR_DLL_INIT_FAILED = 1114;
  698.         internal const int ERROR_NON_ACCOUNT_SID = 1257;
  699.         internal const int ERROR_NOT_ALL_ASSIGNED = 1300;
  700.         internal const int ERROR_UNKNOWN_REVISION = 1305;
  701.         internal const int ERROR_INVALID_OWNER = 1307;
  702.         internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;
  703.         internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;
  704.         internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;
  705.         internal const int ERROR_NONE_MAPPED = 1332;
  706.         internal const int ERROR_INVALID_ACL = 1336;
  707.         internal const int ERROR_INVALID_SID = 1337;
  708.         internal const int ERROR_INVALID_SECURITY_DESCR = 1338;
  709.         internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;
  710.         internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;
  711.         internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;
  712.         internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;
  713.        
  714.         // Error codes from ntstatus.h
  715.         internal const uint STATUS_SOME_NOT_MAPPED = 263;
  716.         internal const uint STATUS_NO_MEMORY = 3221225495u;
  717.         internal const uint STATUS_NONE_MAPPED = 3221225587u;
  718.         internal const uint STATUS_INSUFFICIENT_RESOURCES = 3221225626u;
  719.         internal const uint STATUS_ACCESS_DENIED = 3221225506u;
  720.        
  721.         internal const int INVALID_FILE_SIZE = -1;
  722.        
  723.         // From WinStatus.h
  724.         internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int)3221225582u);
  725.        
  726.         // Use this to translate error codes like the above into HRESULTs like
  727.         // 0x80070006 for ERROR_INVALID_HANDLE
  728.         static internal int MakeHRFromErrorCode(int errorCode)
  729.         {
  730.             BCLDebug.Assert((4294901760u & errorCode) == 0, "This is an HRESULT, not an error code!");
  731.             return unchecked(((int)2147942400u) | errorCode);
  732.         }
  733.        
  734.         // Win32 Structs in N/Direct style
  735.         [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto), Serializable()]
  736.         [BestFitMapping(false)]
  737.         internal class WIN32_FIND_DATA
  738.         {
  739.             internal int dwFileAttributes = 0;
  740.             // ftCreationTime was a by-value FILETIME structure
  741.             internal int ftCreationTime_dwLowDateTime = 0;
  742.             internal int ftCreationTime_dwHighDateTime = 0;
  743.             // ftLastAccessTime was a by-value FILETIME structure
  744.             internal int ftLastAccessTime_dwLowDateTime = 0;
  745.             internal int ftLastAccessTime_dwHighDateTime = 0;
  746.             // ftLastWriteTime was a by-value FILETIME structure
  747.             internal int ftLastWriteTime_dwLowDateTime = 0;
  748.             internal int ftLastWriteTime_dwHighDateTime = 0;
  749.             internal int nFileSizeHigh = 0;
  750.             internal int nFileSizeLow = 0;
  751.             // If the file attributes' reparse point flag is set, then
  752.             // dwReserved0 is the file tag (aka reparse tag) for the
  753.             // reparse point. Use this to figure out whether something is
  754.             // a volume mount point or a symbolic link.
  755.             internal int dwReserved0 = 0;
  756.             internal int dwReserved1 = 0;
  757.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  758.             internal string cFileName = null;
  759.             [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
  760.             internal string cAlternateFileName = null;
  761.         }
  762.        
  763.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  764.         [ResourceExposure(ResourceScope.Machine)]
  765.         static internal extern bool CopyFile(string src, string dst, bool failIfExists);
  766.        
  767.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  768.         [ResourceExposure(ResourceScope.Machine)]
  769.         static internal extern bool CreateDirectory(string path, SECURITY_ATTRIBUTES lpSecurityAttributes);
  770.        
  771.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  772.         [ResourceExposure(ResourceScope.Machine)]
  773.         static internal extern bool DeleteFile(string path);
  774.        
  775.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  776.         [ResourceExposure(ResourceScope.Machine)]
  777.         static internal extern bool ReplaceFile(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);
  778.        
  779.         [DllImport(ADVAPI32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  780.         [ResourceExposure(ResourceScope.Machine)]
  781.         static internal extern bool DecryptFile(string path, int reservedMustBeZero);
  782.        
  783.         [DllImport(ADVAPI32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  784.         [ResourceExposure(ResourceScope.Machine)]
  785.         static internal extern bool EncryptFile(string path);
  786.        
  787.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  788.         [ResourceExposure(ResourceScope.None)]
  789.         static internal extern SafeFindHandle FindFirstFile(string fileName,         [In(), Out()]
  790. Win32Native.WIN32_FIND_DATA data);
  791.        
  792.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  793.         [ResourceExposure(ResourceScope.None)]
  794.         static internal extern bool FindNextFile(SafeFindHandle hndFindFile,         [In(), Out(), MarshalAs(UnmanagedType.LPStruct)]
  795. WIN32_FIND_DATA lpFindFileData);
  796.        
  797.         [DllImport(KERNEL32)]
  798.         [ResourceExposure(ResourceScope.None)]
  799.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  800.         static internal extern bool FindClose(IntPtr handle);
  801.        
  802.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  803.         [ResourceExposure(ResourceScope.Machine)]
  804.         static internal extern int GetCurrentDirectory(int nBufferLength, StringBuilder lpBuffer);
  805.        
  806.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  807.         [ResourceExposure(ResourceScope.None)]
  808.         static internal extern bool GetFileAttributesEx(string name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
  809.        
  810.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  811.         [ResourceExposure(ResourceScope.None)]
  812.         static internal extern bool SetFileAttributes(string name, int attr);
  813.        
  814.         #if !PLATFORM_UNIX
  815.         [DllImport(KERNEL32, SetLastError = true)]
  816.         [ResourceExposure(ResourceScope.None)]
  817.         static internal extern int GetLogicalDrives();
  818.         #endif // !PLATFORM_UNIX
  819.        
  820.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  821.         [ResourceExposure(ResourceScope.None)]
  822.         static internal extern uint GetTempFileName(string tmpPath, string prefix, uint uniqueIdOrZero, StringBuilder tmpFileName);
  823.        
  824.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  825.         [ResourceExposure(ResourceScope.Machine)]
  826.         static internal extern bool MoveFile(string src, string dst);
  827.        
  828.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  829.         [ResourceExposure(ResourceScope.Machine)]
  830.         static internal extern bool DeleteVolumeMountPoint(string mountPoint);
  831.        
  832.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  833.         [ResourceExposure(ResourceScope.Machine)]
  834.         static internal extern bool RemoveDirectory(string path);
  835.        
  836.         [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
  837.         [ResourceExposure(ResourceScope.Machine)]
  838.         static internal extern bool SetCurrentDirectory(string path);
  839.        
  840.         [DllImport(KERNEL32, SetLastError = false)]
  841.         [ResourceExposure(ResourceScope.Process)]
  842.         static internal extern int SetErrorMode(int newMode);
  843.        
  844.         internal const int LCID_SUPPORTED = 2;
  845.         // supported locale ids
  846.         [DllImport(KERNEL32)]
  847.         [ResourceExposure(ResourceScope.None)]
  848.         unsafe static internal extern int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2);
  849.        
  850.         // A Win32 HandlerRoutine
  851.         internal delegate bool ConsoleCtrlHandlerRoutine(int controlType);
  852.        
  853.         [DllImport(KERNEL32, SetLastError = true)]
  854.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  855.         [ResourceExposure(ResourceScope.Process)]
  856.         static internal extern bool SetConsoleCtrlHandler(ConsoleCtrlHandlerRoutine handler, bool addOrRemove);
  857.        
  858.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  859.         [ResourceExposure(ResourceScope.Process)]
  860.         static internal extern bool SetEnvironmentVariable(string lpName, string lpValue);
  861.        
  862.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
  863.         [ResourceExposure(ResourceScope.Machine)]
  864.         static internal extern int GetEnvironmentVariable(string lpName, StringBuilder lpValue, int size);
  865.        
  866.         [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
  867.         [ResourceExposure(ResourceScope.Process)]
  868.         static internal extern uint GetCurrentProcessId();
  869.        
  870.         [DllImport(ADVAPI32, CharSet = CharSet.Auto)]
  871.         [ResourceExposure(ResourceScope.None)]
  872.         static internal extern bool GetUserName(StringBuilder lpBuffer, ref int nSize);
  873.        
  874.         [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)]
  875.         static internal extern int GetComputerName(StringBuilder nameBuffer, ref int bufferSize);
  876.        
  877.        
  878.        
  879.         [DllImport(KERNEL32, SetLastError = false)]
  880.         [ResourceExposure(ResourceScope.None)]
  881.         static internal extern uint GetConsoleCP();
  882.        
  883.         [DllImport(KERNEL32, SetLastError = true)]
  884.         [ResourceExposure(ResourceScope.Process)]
  885.         static internal extern bool SetConsoleCP(uint codePage);
  886.        
  887.         [DllImport(KERNEL32, SetLastError = false)]
  888.         [ResourceExposure(ResourceScope.None)]
  889.         static internal extern uint GetConsoleOutputCP();
  890.        
  891.         [DllImport(KERNEL32, SetLastError = true)]
  892.         [ResourceExposure(ResourceScope.Process)]
  893.         static internal extern bool SetConsoleOutputCP(uint codePage);
  894.        
  895.        
  896.         // managed cryptography wrapper around the PALRT cryptography api
  897.         internal const int PAL_HCRYPTPROV = 123;
  898.        
  899.         internal const int CALG_MD2 = ((4 << 13) | 1);
  900.         internal const int CALG_MD4 = ((4 << 13) | 2);
  901.         internal const int CALG_MD5 = ((4 << 13) | 3);
  902.         internal const int CALG_SHA = ((4 << 13) | 4);
  903.         internal const int CALG_SHA1 = ((4 << 13) | 4);
  904.         internal const int CALG_MAC = ((4 << 13) | 5);
  905.         internal const int CALG_SSL3_SHAMD5 = ((4 << 13) | 8);
  906.         internal const int CALG_HMAC = ((4 << 13) | 9);
  907.        
  908.         internal const int HP_ALGID = 1;
  909.         internal const int HP_HASHVAL = 2;
  910.         internal const int HP_HASHSIZE = 4;
  911.        
  912.         [DllImport(OLEAUT32, CharSet = CharSet.Unicode, EntryPoint = "CryptAcquireContextW")]
  913.         [ResourceExposure(ResourceScope.Machine)]
  914.         static internal extern bool CryptAcquireContext(out IntPtr hProv,         [MarshalAs(UnmanagedType.LPWStr)]
  915. string container,         [MarshalAs(UnmanagedType.LPWStr)]
  916. string provider, int provType, int flags);
  917.        
  918.         [DllImport(OLEAUT32, SetLastError = true)]
  919.         [ResourceExposure(ResourceScope.None)]
  920.         static internal extern bool CryptReleaseContext(IntPtr hProv, int flags);
  921.        
  922.         [DllImport(OLEAUT32, SetLastError = true)]
  923.         [ResourceExposure(ResourceScope.None)]
  924.         static internal extern bool CryptCreateHash(IntPtr hProv, int Algid, IntPtr hKey, int flags, out IntPtr hHash);
  925.        
  926.         [DllImport(OLEAUT32, SetLastError = true)]
  927.         [ResourceExposure(ResourceScope.None)]
  928.         static internal extern bool CryptDestroyHash(IntPtr hHash);
  929.        
  930.         [DllImport(OLEAUT32, SetLastError = true)]
  931.         [ResourceExposure(ResourceScope.None)]
  932.         static internal extern bool CryptHashData(IntPtr hHash,         [In(), MarshalAs(UnmanagedType.LPArray)]
  933. byte[] data, int length, int flags);
  934.        
  935.         [DllImport(OLEAUT32, SetLastError = true)]
  936.         [ResourceExposure(ResourceScope.None)]
  937.         static internal extern bool CryptGetHashParam(IntPtr hHash, int param,         [Out(), MarshalAs(UnmanagedType.LPArray)]
  938. byte[] digest, ref int length, int flags);
  939.        
  940.         [DllImport(OLEAUT32, SetLastError = true)]
  941.         [ResourceExposure(ResourceScope.None)]
  942.         static internal extern bool CryptGetHashParam(IntPtr hHash, int param, out int data, ref int length, int flags);
  943.        
  944.         [DllImport(KERNEL32, EntryPoint = "PAL_Random")]
  945.         [ResourceExposure(ResourceScope.None)]
  946.         static internal extern bool Random(bool bStrong,         [Out(), MarshalAs(UnmanagedType.LPArray)]
  947. byte[] buffer, int length);
  948.        
  949.         // Fusion APIs
  950.        
  951.         [DllImport(MSCORWKS, CharSet = CharSet.Unicode)]
  952.         [ResourceExposure(ResourceScope.None)]
  953.         static internal extern int CreateAssemblyNameObject(out SafeFusionHandle ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved);
  954.        
  955.         [DllImport(MSCORWKS, CharSet = CharSet.Auto)]
  956.         [ResourceExposure(ResourceScope.None)]
  957.         static internal extern int CreateAssemblyEnum(out SafeFusionHandle ppEnum, SafeFusionHandle pAppCtx, SafeFusionHandle pName, uint dwFlags, IntPtr pvReserved);
  958.        
  959.         // Globalization APIs
  960.         [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)]
  961.         [ResourceExposure(ResourceScope.None)]
  962.             // locale
  963.             // calendar identifier
  964.             // calendar type
  965.             // information buffer
  966.             // information buffer size
  967.             // data
  968.         static internal extern int GetCalendarInfo(int Locale, int Calendar, int CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue);
  969.     }
  970. }

Developer Fusion