diff --git a/.editorconfig b/.editorconfig index 80d276422cb39a8165c1331d128d0ac7cb9d5d7e..c532bc0d1f63e2a0dd5a633c9d3294b510fef198 100644 --- a/.editorconfig +++ b/.editorconfig @@ -77,6 +77,9 @@ charset = utf-8-bom [*.{cs,vb}] +# SYSLIB1054: Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time +dotnet_diagnostic.SYSLIB1054.severity = warning + # CA1018: Mark attributes with AttributeUsageAttribute dotnet_diagnostic.CA1018.severity = warning diff --git a/eng/tools/HelixTestRunner/HelixTestRunner.csproj b/eng/tools/HelixTestRunner/HelixTestRunner.csproj index 52fd7178f093afd7ee28649dbdd730bf32f3fc48..54a443530efc155143581bc77905c2d49242a7d6 100644 --- a/eng/tools/HelixTestRunner/HelixTestRunner.csproj +++ b/eng/tools/HelixTestRunner/HelixTestRunner.csproj @@ -13,6 +13,7 @@ <OutputType>Exe</OutputType> <NoWarn>$(NoWarn);CA2007;NU5104</NoWarn> <IsPackable>false</IsPackable> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- We don't need this unless building for tests. --> <ExcludeFromBuild Condition=" '$(DotNetBuildFromSource)' == 'true' OR '$(SkipTestBuild)' == 'true' ">true</ExcludeFromBuild> diff --git a/eng/tools/HelixTestRunner/ProcessUtil.cs b/eng/tools/HelixTestRunner/ProcessUtil.cs index 067850c4468e00623f0947f95c310961090d06df..b895fa86f5485863ba6552ac6e10eb937bf48696 100644 --- a/eng/tools/HelixTestRunner/ProcessUtil.cs +++ b/eng/tools/HelixTestRunner/ProcessUtil.cs @@ -15,10 +15,10 @@ using System.Threading.Tasks; namespace HelixTestRunner; -public static class ProcessUtil +public static partial class ProcessUtil { - [DllImport("libc", SetLastError = true, EntryPoint = "kill")] - private static extern int sys_kill(int pid, int sig); + [LibraryImport("libc", SetLastError = true, EntryPoint = "kill")] + private static partial int sys_kill(int pid, int sig); public static Task CaptureDumpAsync() { diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs index 09c943878688147bfb7bfdf6efcca49d814abe88..98e70e084c4d1860ce63b090aecf244345162ea0 100644 --- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs +++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs @@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles; /// <summary> /// Represents a handle to a Windows module (DLL). /// </summary> -internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid +internal sealed unsafe partial class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { // Called by P/Invoke when returning SafeHandles private SafeLibraryHandle() @@ -125,18 +125,23 @@ internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInval } [SuppressUnmanagedCodeSecurity] - private static class UnsafeNativeMethods + private static partial class UnsafeNativeMethods { // http://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx - [DllImport("kernel32.dll", EntryPoint = "FormatMessageW", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)] +#if NET7_0_OR_GREATER + [LibraryImport("kernel32.dll", EntryPoint = "FormatMessageW", SetLastError = true)] + public static partial int FormatMessage( +#else + [DllImport("kernel32.dll", EntryPoint = "FormatMessageW", SetLastError = true)] public static extern int FormatMessage( - [In] uint dwFlags, - [In] SafeLibraryHandle lpSource, - [In] uint dwMessageId, - [In] uint dwLanguageId, - [Out] out LocalAllocHandle lpBuffer, - [In] uint nSize, - [In] IntPtr Arguments +#endif + uint dwFlags, + SafeLibraryHandle lpSource, + uint dwMessageId, + uint dwLanguageId, + out LocalAllocHandle lpBuffer, + uint nSize, + IntPtr Arguments ); // http://msdn.microsoft.com/en-us/library/ms683152(v=vs.85).aspx @@ -144,29 +149,50 @@ internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInval #if NETSTANDARD2_0 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)] - internal static extern bool FreeLibrary(IntPtr hModule); +#if NET7_0_OR_GREATER + [LibraryImport("kernel32.dll")] + internal static partial bool FreeLibrary( +#else + [DllImport("kernel32.dll")] + internal static extern bool FreeLibrary( +#endif + IntPtr hModule); // http://msdn.microsoft.com/en-us/library/ms683200(v=vs.85).aspx [return: MarshalAs(UnmanagedType.Bool)] - [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleExW", CallingConvention = CallingConvention.Winapi, SetLastError = true)] +#if NET7_0_OR_GREATER + [LibraryImport("kernel32.dll", EntryPoint = "GetModuleHandleExW", SetLastError = true)] + internal static partial bool GetModuleHandleEx( +#else + [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleExW", SetLastError = true)] internal static extern bool GetModuleHandleEx( - [In] uint dwFlags, - [In] SafeLibraryHandle lpModuleName, // can point to a location within the module if GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS is set - [Out] out IntPtr phModule); +#endif + uint dwFlags, + SafeLibraryHandle lpModuleName, // can point to a location within the module if GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS is set + out IntPtr phModule); // http://msdn.microsoft.com/en-us/library/ms683212(v=vs.85).aspx - [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)] +#if NET7_0_OR_GREATER + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial IntPtr GetProcAddress( +#else + [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcAddress( - [In] SafeLibraryHandle hModule, - [In, MarshalAs(UnmanagedType.LPStr)] string lpProcName); +#endif + SafeLibraryHandle hModule, + [MarshalAs(UnmanagedType.LPStr)] string lpProcName); // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx - [DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CallingConvention = CallingConvention.Winapi, SetLastError = true)] +#if NET7_0_OR_GREATER + [LibraryImport("kernel32.dll", EntryPoint = "LoadLibraryExW", SetLastError = true)] + internal static partial SafeLibraryHandle LoadLibraryEx( +#else + [DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", SetLastError = true)] internal static extern SafeLibraryHandle LoadLibraryEx( - [In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - [In] IntPtr hFile, - [In] uint dwFlags); +#endif + [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, + IntPtr hFile, + uint dwFlags); #pragma warning disable CS8763 // A method marked [DoesNotReturn] should not return. [DoesNotReturn] diff --git a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs index 07ce968f069136544be9269315006847ec1cc504..f943d6706866e8190fd900f747e2d86f907e1315 100644 --- a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs +++ b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs @@ -15,7 +15,7 @@ using Microsoft.AspNetCore.Cryptography.SafeHandles; namespace Microsoft.AspNetCore.Cryptography; [SuppressUnmanagedCodeSecurity] -internal static unsafe class UnsafeNativeMethods +internal static unsafe partial class UnsafeNativeMethods { internal const string BCRYPT_LIB = "bcrypt.dll"; private static SafeLibraryHandle? _lazyBCryptLibHandle; @@ -29,271 +29,410 @@ internal static unsafe class UnsafeNativeMethods /* * BCRYPT.DLL */ - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375377(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptCloseAlgorithmProvider( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptCloseAlgorithmProvider( - [In] IntPtr hAlgorithm, - [In] uint dwFlags); +#endif + IntPtr hAlgorithm, + uint dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375383(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptCreateHash( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptCreateHash( - [In] BCryptAlgorithmHandle hAlgorithm, - [Out] out BCryptHashHandle phHash, - [In] IntPtr pbHashObject, - [In] uint cbHashObject, - [In] byte* pbSecret, - [In] uint cbSecret, - [In] uint dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptAlgorithmHandle hAlgorithm, + out BCryptHashHandle phHash, + IntPtr pbHashObject, + uint cbHashObject, + byte* pbSecret, + uint cbSecret, + uint dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375391(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptDecrypt( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptDecrypt( - [In] BCryptKeyHandle hKey, - [In] byte* pbInput, - [In] uint cbInput, - [In] void* pPaddingInfo, - [In] byte* pbIV, - [In] uint cbIV, - [In] byte* pbOutput, - [In] uint cbOutput, - [Out] out uint pcbResult, - [In] BCryptEncryptFlags dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptKeyHandle hKey, + byte* pbInput, + uint cbInput, + void* pPaddingInfo, + byte* pbIV, + uint cbIV, + byte* pbOutput, + uint cbOutput, + out uint pcbResult, + BCryptEncryptFlags dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/dd433795(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptDeriveKeyPBKDF2( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptDeriveKeyPBKDF2( - [In] BCryptAlgorithmHandle hPrf, - [In] byte* pbPassword, - [In] uint cbPassword, - [In] byte* pbSalt, - [In] uint cbSalt, - [In] ulong cIterations, - [In] byte* pbDerivedKey, - [In] uint cbDerivedKey, - [In] uint dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptAlgorithmHandle hPrf, + byte* pbPassword, + uint cbPassword, + byte* pbSalt, + uint cbSalt, + ulong cIterations, + byte* pbDerivedKey, + uint cbDerivedKey, + uint dwFlags); + + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375399(v=vs.85).aspx #if NETSTANDARD2_0 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375399(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptDestroyHash( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptDestroyHash( - [In] IntPtr hHash); +#endif + IntPtr hHash); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375404(v=vs.85).aspx #if NETSTANDARD2_0 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375404(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptDestroyKey( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptDestroyKey( - [In] IntPtr hKey); +#endif + IntPtr hKey); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375413(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptDuplicateHash( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptDuplicateHash( - [In] BCryptHashHandle hHash, - [Out] out BCryptHashHandle phNewHash, - [In] IntPtr pbHashObject, - [In] uint cbHashObject, - [In] uint dwFlags); +#endif + BCryptHashHandle hHash, + out BCryptHashHandle phNewHash, + IntPtr pbHashObject, + uint cbHashObject, + uint dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375421(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptEncrypt( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptEncrypt( - [In] BCryptKeyHandle hKey, - [In] byte* pbInput, - [In] uint cbInput, - [In] void* pPaddingInfo, - [In] byte* pbIV, - [In] uint cbIV, - [In] byte* pbOutput, - [In] uint cbOutput, - [Out] out uint pcbResult, - [In] BCryptEncryptFlags dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptKeyHandle hKey, + byte* pbInput, + uint cbInput, + void* pPaddingInfo, + byte* pbIV, + uint cbIV, + byte* pbOutput, + uint cbOutput, + out uint pcbResult, + BCryptEncryptFlags dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375443(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptFinishHash( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptFinishHash( - [In] BCryptHashHandle hHash, - [In] byte* pbOutput, - [In] uint cbOutput, - [In] uint dwFlags); +#endif + BCryptHashHandle hHash, + byte* pbOutput, + uint cbOutput, + uint dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375453(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptGenerateSymmetricKey( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptGenerateSymmetricKey( - [In] BCryptAlgorithmHandle hAlgorithm, - [Out] out BCryptKeyHandle phKey, - [In] IntPtr pbKeyObject, - [In] uint cbKeyObject, - [In] byte* pbSecret, - [In] uint cbSecret, - [In] uint dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptAlgorithmHandle hAlgorithm, + out BCryptKeyHandle phKey, + IntPtr pbKeyObject, + uint cbKeyObject, + byte* pbSecret, + uint cbSecret, + uint dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375458(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptGenRandom( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptGenRandom( - [In] IntPtr hAlgorithm, - [In] byte* pbBuffer, - [In] uint cbBuffer, - [In] BCryptGenRandomFlags dwFlags); +#endif + IntPtr hAlgorithm, + byte* pbBuffer, + uint cbBuffer, + BCryptGenRandomFlags dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375464(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptGetProperty( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptGetProperty( - [In] BCryptHandle hObject, - [In, MarshalAs(UnmanagedType.LPWStr)] string pszProperty, - [In] void* pbOutput, - [In] uint cbOutput, - [Out] out uint pcbResult, - [In] uint dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptHandle hObject, + [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, + void* pbOutput, + uint cbOutput, + out uint pcbResult, + uint dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375468(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptHashData( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptHashData( - [In] BCryptHashHandle hHash, - [In] byte* pbInput, - [In] uint cbInput, - [In] uint dwFlags); +#endif + BCryptHashHandle hHash, + byte* pbInput, + uint cbInput, + uint dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/hh448506(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptKeyDerivation( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptKeyDerivation( - [In] BCryptKeyHandle hKey, - [In] BCryptBufferDesc* pParameterList, - [In] byte* pbDerivedKey, - [In] uint cbDerivedKey, - [Out] out uint pcbResult, - [In] uint dwFlags); - - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + BCryptKeyHandle hKey, + BCryptBufferDesc* pParameterList, + byte* pbDerivedKey, + uint cbDerivedKey, + out uint pcbResult, + uint dwFlags); + // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375479(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptOpenAlgorithmProvider( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptOpenAlgorithmProvider( - [Out] out BCryptAlgorithmHandle phAlgorithm, - [In, MarshalAs(UnmanagedType.LPWStr)] string pszAlgId, - [In, MarshalAs(UnmanagedType.LPWStr)] string? pszImplementation, - [In] uint dwFlags); +#endif + out BCryptAlgorithmHandle phAlgorithm, + [MarshalAs(UnmanagedType.LPWStr)] string pszAlgId, + [MarshalAs(UnmanagedType.LPWStr)] string? pszImplementation, + uint dwFlags); - [DllImport(BCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375504(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(BCRYPT_LIB)] + internal static partial int BCryptSetProperty( +#else + [DllImport(BCRYPT_LIB)] internal static extern int BCryptSetProperty( - [In] BCryptHandle hObject, - [In, MarshalAs(UnmanagedType.LPWStr)] string pszProperty, - [In] void* pbInput, - [In] uint cbInput, - [In] uint dwFlags); +#endif + BCryptHandle hObject, + [MarshalAs(UnmanagedType.LPWStr)] string pszProperty, + void* pbInput, + uint cbInput, + uint dwFlags); /* * CRYPT32.DLL */ - [DllImport(CRYPT32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(CRYPT32_LIB, SetLastError = true)] + internal static partial bool CryptProtectData( +#else + [DllImport(CRYPT32_LIB, SetLastError = true)] internal static extern bool CryptProtectData( - [In] DATA_BLOB* pDataIn, - [In] IntPtr szDataDescr, - [In] DATA_BLOB* pOptionalEntropy, - [In] IntPtr pvReserved, - [In] IntPtr pPromptStruct, - [In] uint dwFlags, - [Out] out DATA_BLOB pDataOut); +#endif + DATA_BLOB* pDataIn, + IntPtr szDataDescr, + DATA_BLOB* pOptionalEntropy, + IntPtr pvReserved, + IntPtr pPromptStruct, + uint dwFlags, + DATA_BLOB* pDataOut); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380262(v=vs.85).aspx - [DllImport(CRYPT32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] +#if NET7_0_OR_GREATER + [LibraryImport(CRYPT32_LIB, SetLastError = true)] + public static partial bool CryptProtectMemory( +#else + [DllImport(CRYPT32_LIB, SetLastError = true)] public static extern bool CryptProtectMemory( - [In] SafeHandle pData, - [In] uint cbData, - [In] uint dwFlags); +#endif + SafeHandle pData, + uint cbData, + uint dwFlags); - [DllImport(CRYPT32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380882(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(CRYPT32_LIB, SetLastError = true)] + internal static partial bool CryptUnprotectData( +#else + [DllImport(CRYPT32_LIB, SetLastError = true)] internal static extern bool CryptUnprotectData( - [In] DATA_BLOB* pDataIn, - [In] IntPtr ppszDataDescr, - [In] DATA_BLOB* pOptionalEntropy, - [In] IntPtr pvReserved, - [In] IntPtr pPromptStruct, - [In] uint dwFlags, - [Out] out DATA_BLOB pDataOut); +#endif + DATA_BLOB* pDataIn, + IntPtr ppszDataDescr, + DATA_BLOB* pOptionalEntropy, + IntPtr pvReserved, + IntPtr pPromptStruct, + uint dwFlags, + DATA_BLOB* pDataOut); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380890(v=vs.85).aspx - [DllImport(CRYPT32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] +#if NET7_0_OR_GREATER + [LibraryImport(CRYPT32_LIB, SetLastError = true)] + public static partial bool CryptUnprotectMemory( +#else + [DllImport(CRYPT32_LIB, SetLastError = true)] public static extern bool CryptUnprotectMemory( - [In] byte* pData, - [In] uint cbData, - [In] uint dwFlags); +#endif + byte* pData, + uint cbData, + uint dwFlags); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380890(v=vs.85).aspx - [DllImport(CRYPT32_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] +#if NET7_0_OR_GREATER + [LibraryImport(CRYPT32_LIB, SetLastError = true)] + public static partial bool CryptUnprotectMemory( +#else + [DllImport(CRYPT32_LIB, SetLastError = true)] public static extern bool CryptUnprotectMemory( - [In] SafeHandle pData, - [In] uint cbData, - [In] uint dwFlags); +#endif + SafeHandle pData, + uint cbData, + uint dwFlags); /* * NCRYPT.DLL */ - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] + // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706799(v=vs.85).aspx #if NETSTANDARD2_0 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706799(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptCloseProtectionDescriptor( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptCloseProtectionDescriptor( - [In] IntPtr hDescriptor); +#endif + IntPtr hDescriptor); - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706800(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptCreateProtectionDescriptor( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptCreateProtectionDescriptor( - [In, MarshalAs(UnmanagedType.LPWStr)] string pwszDescriptorString, - [In] uint dwFlags, - [Out] out NCryptDescriptorHandle phDescriptor); +#endif + [MarshalAs(UnmanagedType.LPWStr)] string pwszDescriptorString, + uint dwFlags, + out NCryptDescriptorHandle phDescriptor); - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // https://msdn.microsoft.com/en-us/library/windows/desktop/hh706801(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptGetProtectionDescriptorInfo( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptGetProtectionDescriptorInfo( - [In] NCryptDescriptorHandle hDescriptor, - [In] IntPtr pMemPara, - [In] uint dwInfoType, - [Out] out LocalAllocHandle ppvInfo); +#endif + NCryptDescriptorHandle hDescriptor, + IntPtr pMemPara, + uint dwInfoType, + out LocalAllocHandle ppvInfo); - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706802(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptProtectSecret( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptProtectSecret( - [In] NCryptDescriptorHandle hDescriptor, - [In] uint dwFlags, - [In] byte* pbData, - [In] uint cbData, - [In] IntPtr pMemPara, - [In] IntPtr hWnd, - [Out] out LocalAllocHandle ppbProtectedBlob, - [Out] out uint pcbProtectedBlob); - - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + NCryptDescriptorHandle hDescriptor, + uint dwFlags, + byte* pbData, + uint cbData, + IntPtr pMemPara, + IntPtr hWnd, + out LocalAllocHandle ppbProtectedBlob, + out uint pcbProtectedBlob); + // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706811(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptUnprotectSecret( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptUnprotectSecret( - [In] IntPtr phDescriptor, - [In] uint dwFlags, - [In] byte* pbProtectedBlob, - [In] uint cbProtectedBlob, - [In] IntPtr pMemPara, - [In] IntPtr hWnd, - [Out] out LocalAllocHandle ppbData, - [Out] out uint pcbData); - - [DllImport(NCRYPT_LIB, CallingConvention = CallingConvention.Winapi)] +#endif + IntPtr phDescriptor, + uint dwFlags, + byte* pbProtectedBlob, + uint cbProtectedBlob, + IntPtr pMemPara, + IntPtr hWnd, + out LocalAllocHandle ppbData, + out uint pcbData); + // http://msdn.microsoft.com/en-us/library/windows/desktop/hh706811(v=vs.85).aspx +#if NET7_0_OR_GREATER + [LibraryImport(NCRYPT_LIB)] + internal static partial int NCryptUnprotectSecret( +#else + [DllImport(NCRYPT_LIB)] internal static extern int NCryptUnprotectSecret( - [Out] out NCryptDescriptorHandle phDescriptor, - [In] uint dwFlags, - [In] byte* pbProtectedBlob, - [In] uint cbProtectedBlob, - [In] IntPtr pMemPara, - [In] IntPtr hWnd, - [Out] out LocalAllocHandle ppbData, - [Out] out uint pcbData); +#endif + out NCryptDescriptorHandle phDescriptor, + uint dwFlags, + byte* pbProtectedBlob, + uint cbProtectedBlob, + IntPtr pMemPara, + IntPtr hWnd, + out LocalAllocHandle ppbData, + out uint pcbData); /* * HELPER FUNCTIONS diff --git a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs index 1cd3b5f9cacc134383a434cb0254006417d459c7..ae213a62ca83a417747f9fe907be2a338d35e45f 100644 --- a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs +++ b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs @@ -91,7 +91,7 @@ internal static unsafe class DpapiSecretSerializerHelper pvReserved: IntPtr.Zero, pPromptStruct: IntPtr.Zero, dwFlags: CRYPTPROTECT_UI_FORBIDDEN | ((fLocalMachine) ? CRYPTPROTECT_LOCAL_MACHINE : 0), - pDataOut: out dataOut); + pDataOut: &dataOut); if (!success) { var errorCode = Marshal.GetLastWin32Error(); @@ -234,7 +234,7 @@ internal static unsafe class DpapiSecretSerializerHelper pvReserved: IntPtr.Zero, pPromptStruct: IntPtr.Zero, dwFlags: CRYPTPROTECT_UI_FORBIDDEN, - pDataOut: out dataOut); + pDataOut: &dataOut); if (!success) { var errorCode = Marshal.GetLastWin32Error(); diff --git a/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs b/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs index 8501fa4083b6d2ea3c3f1360a7efb3ddef5ed531..1582c1217524667f4a0f00f4439c2569c6ef7b12 100644 --- a/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs +++ b/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs @@ -8,76 +8,77 @@ using static Microsoft.AspNetCore.HttpSys.Internal.HttpApiTypes; namespace Microsoft.AspNetCore.Server.HttpSys; -internal static unsafe class HttpApi +internal static unsafe partial class HttpApi { private const string HTTPAPI = "httpapi.dll"; - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpInitialize(HTTPAPI_VERSION version, uint flags, void* pReserved); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpReceiveRequestEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, IntPtr pEntityBuffer, uint entityBufferLength, out uint bytesReturned, SafeNativeOverlapped pOverlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpReceiveRequestEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, IntPtr pEntityBuffer, uint entityBufferLength, out uint bytesReturned, SafeNativeOverlapped pOverlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, HTTP_SSL_CLIENT_CERT_INFO* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, SafeNativeOverlapped pOverlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_REQUEST* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpReceiveHttpRequest(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_REQUEST* pRequestBuffer, uint requestBufferLength, uint* pBytesReturned, NativeOverlapped* pOverlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_RESPONSE_V2* pHttpResponse, HTTP_CACHE_POLICY* pCachePolicy, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpSendHttpResponse(SafeHandle requestQueueHandle, ulong requestId, uint flags, HTTP_RESPONSE_V2* pHttpResponse, HTTP_CACHE_POLICY* pCachePolicy, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpSendResponseEntityBody(SafeHandle requestQueueHandle, ulong requestId, uint flags, ushort entityChunkCount, HTTP_DATA_CHUNK* pEntityChunks, uint* pBytesSent, IntPtr pReserved1, uint Reserved2, SafeNativeOverlapped pOverlapped, IntPtr pLogData); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpCancelHttpRequest(SafeHandle requestQueueHandle, ulong requestId, IntPtr pOverlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpWaitForDisconnectEx(SafeHandle requestQueueHandle, ulong connectionId, uint reserved, NativeOverlapped* overlapped); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpWaitForDisconnectEx(SafeHandle requestQueueHandle, ulong connectionId, uint reserved, NativeOverlapped* overlapped); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpCreateServerSession(HTTPAPI_VERSION version, ulong* serverSessionId, uint reserved); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpCreateServerSession(HTTPAPI_VERSION version, ulong* serverSessionId, uint reserved); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpCreateUrlGroup(ulong serverSessionId, ulong* urlGroupId, uint reserved); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpCreateUrlGroup(ulong serverSessionId, ulong* urlGroupId, uint reserved); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern uint HttpFindUrlGroupId(string pFullyQualifiedUrl, SafeHandle requestQueueHandle, ulong* urlGroupId); + [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial uint HttpFindUrlGroupId(string pFullyQualifiedUrl, SafeHandle requestQueueHandle, ulong* urlGroupId); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern uint HttpAddUrlToUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, ulong context, uint pReserved); + [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial uint HttpAddUrlToUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, ulong context, uint pReserved); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpSetUrlGroupProperty(ulong urlGroupId, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern uint HttpRemoveUrlFromUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, uint flags); + [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial uint HttpRemoveUrlFromUrlGroup(ulong urlGroupId, string pFullyQualifiedUrl, uint flags); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpCloseServerSession(ulong serverSessionId); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpCloseServerSession(ulong serverSessionId); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpCloseUrlGroup(ulong urlGroupId); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpCloseUrlGroup(ulong urlGroupId); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern uint HttpSetRequestQueueProperty(SafeHandle requestQueueHandle, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength, uint reserved, IntPtr pReserved); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static partial uint HttpSetRequestQueueProperty(SafeHandle requestQueueHandle, HTTP_SERVER_PROPERTY serverProperty, IntPtr pPropertyInfo, uint propertyInfoLength, uint reserved, IntPtr pReserved); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern unsafe uint HttpCreateRequestQueue(HTTPAPI_VERSION version, string? pName, - UnsafeNclNativeMethods.SECURITY_ATTRIBUTES? pSecurityAttributes, HTTP_CREATE_REQUEST_QUEUE_FLAG flags, out HttpRequestQueueV2Handle pReqQueueHandle); + [LibraryImport(HTTPAPI, SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static unsafe partial uint HttpCreateRequestQueue(HTTPAPI_VERSION version, string? pName, + IntPtr pSecurityAttributes, HTTP_CREATE_REQUEST_QUEUE_FLAG flags, out HttpRequestQueueV2Handle pReqQueueHandle); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern unsafe uint HttpCloseRequestQueue(IntPtr pReqQueueHandle); + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static unsafe partial uint HttpCloseRequestQueue(IntPtr pReqQueueHandle); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern bool HttpIsFeatureSupported(HTTP_FEATURE_ID feature); + [LibraryImport(HTTPAPI, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool HttpIsFeatureSupported(HTTP_FEATURE_ID feature); - [DllImport(HTTPAPI, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern unsafe uint HttpDelegateRequestEx(SafeHandle pReqQueueHandle, SafeHandle pDelegateQueueHandle, ulong requestId, + [LibraryImport(HTTPAPI, SetLastError = true)] + internal static unsafe partial uint HttpDelegateRequestEx(SafeHandle pReqQueueHandle, SafeHandle pDelegateQueueHandle, ulong requestId, ulong delegateUrlGroupId, ulong propertyInfoSetSize, HTTP_DELEGATE_REQUEST_PROPERTY_INFO* pRequestPropertyBuffer); internal delegate uint HttpSetRequestPropertyInvoker(SafeHandle requestQueueHandle, ulong requestId, HTTP_REQUEST_PROPERTY propertyId, void* input, uint inputSize, IntPtr overlapped); diff --git a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs index 7b99862f05e39768569c32d8620699347f395f32..13e78e2dd43d75cfe30612d11fe5b85c67237c7e 100644 --- a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs +++ b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs @@ -44,7 +44,7 @@ internal sealed partial class RequestQueue var statusCode = HttpApi.HttpCreateRequestQueue( HttpApi.Version, requestQueueName, - null, + IntPtr.Zero, flags, out var requestQueueHandle); @@ -56,7 +56,7 @@ internal sealed partial class RequestQueue statusCode = HttpApi.HttpCreateRequestQueue( HttpApi.Version, requestQueueName, - null, + IntPtr.Zero, flags, out requestQueueHandle); } diff --git a/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs b/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs index 8949d77de4a94c03ebb211265986fc248ed2af60..1f90207dee9ea421057c9d339145ae0473c18f3a 100644 --- a/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs +++ b/src/Servers/HttpSys/src/NativeInterop/SafeLibraryHandle.cs @@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Server.HttpSys; /// <summary> /// Represents a handle to a Windows module (DLL). /// </summary> -internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid +internal sealed unsafe partial class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid { // Called by P/Invoke when returning SafeHandles private SafeLibraryHandle() @@ -70,25 +70,25 @@ internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInval } [SuppressUnmanagedCodeSecurity] - private static class UnsafeNativeMethods + private static partial class UnsafeNativeMethods { // http://msdn.microsoft.com/en-us/library/ms683152(v=vs.85).aspx [return: MarshalAs(UnmanagedType.Bool)] - [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)] - internal static extern bool FreeLibrary(IntPtr hModule); + [LibraryImport("kernel32.dll")] + internal static partial bool FreeLibrary(IntPtr hModule); // http://msdn.microsoft.com/en-us/library/ms683212(v=vs.85).aspx - [DllImport("kernel32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)] - internal static extern IntPtr GetProcAddress( - [In] SafeLibraryHandle hModule, - [In, MarshalAs(UnmanagedType.LPStr)] string lpProcName); + [LibraryImport("kernel32.dll", SetLastError = true)] + internal static partial IntPtr GetProcAddress( + SafeLibraryHandle hModule, + [MarshalAs(UnmanagedType.LPStr)] string lpProcName); // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx - [DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CallingConvention = CallingConvention.Winapi, SetLastError = true)] - internal static extern SafeLibraryHandle LoadLibraryEx( - [In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - [In] IntPtr hFile, - [In] uint dwFlags); + [LibraryImport("kernel32.dll", EntryPoint = "LoadLibraryExW", SetLastError = true)] + internal static partial SafeLibraryHandle LoadLibraryEx( + [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, + IntPtr hFile, + uint dwFlags); internal static void ThrowExceptionForLastWin32Error() { diff --git a/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs b/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs index c4ae575303fed4d185541912b40491dd1f600e2c..932a398acea8ae0c6101afbba8af488374d7242b 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs @@ -243,7 +243,7 @@ public class ServerOnExistingQueueTests var statusCode = HttpApi.HttpCreateRequestQueue( HttpApi.Version, queueName, - null, + IntPtr.Zero, 0, out requestQueueHandle); diff --git a/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs b/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs index ff897a01e564d1ca8a3df252f5b712b856eae0b0..2731b109e35b10840ca24262bbf4472bca48c970 100644 --- a/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs +++ b/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs @@ -49,7 +49,7 @@ public class ServerTests var statusCode = HttpApi.HttpCreateRequestQueue( HttpApi.Version, queueName, - null, + IntPtr.Zero, 0, out requestQueueHandle); diff --git a/src/Servers/IIS/IIS/src/Core/IISConfigurationData.cs b/src/Servers/IIS/IIS/src/Core/IISConfigurationData.cs index b138541d7a9deff60286b8834b9dff57afb7aba6..612c2072c4d034ce7c0c4d70ae1194ef23670a62 100644 --- a/src/Servers/IIS/IIS/src/Core/IISConfigurationData.cs +++ b/src/Servers/IIS/IIS/src/Core/IISConfigurationData.cs @@ -2,21 +2,85 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; namespace Microsoft.AspNetCore.Server.IIS.Core; +[NativeMarshalling(typeof(Marshaller))] [StructLayout(LayoutKind.Sequential)] internal struct IISConfigurationData { public IntPtr pNativeApplication; - [MarshalAs(UnmanagedType.BStr)] public string pwzFullApplicationPath; - [MarshalAs(UnmanagedType.BStr)] public string pwzVirtualApplicationPath; public bool fWindowsAuthEnabled; public bool fBasicAuthEnabled; public bool fAnonymousAuthEnable; - [MarshalAs(UnmanagedType.BStr)] public string pwzBindings; public uint maxRequestBodySize; + + [CustomTypeMarshaller(typeof(IISConfigurationData), CustomTypeMarshallerKind.Value, Features = CustomTypeMarshallerFeatures.UnmanagedResources | CustomTypeMarshallerFeatures.TwoStageMarshalling)] + public unsafe ref struct Marshaller + { + public struct Native + { + public IntPtr pNativeApplication; + public IntPtr pwzFullApplicationPath; + public IntPtr pwzVirtualApplicationPath; + public int fWindowsAuthEnabled; + public int fBasicAuthEnabled; + public int fAnonymousAuthEnable; + public IntPtr pwzBindings; + public uint maxRequestBodySize; + } + + private Native _native; + + public Marshaller(IISConfigurationData managed) + { + _native.pNativeApplication = managed.pNativeApplication; + _native.pwzFullApplicationPath = managed.pwzFullApplicationPath is null ? IntPtr.Zero : Marshal.StringToBSTR(managed.pwzFullApplicationPath); + _native.pwzVirtualApplicationPath = managed.pwzVirtualApplicationPath is null ? IntPtr.Zero : Marshal.StringToBSTR(managed.pwzVirtualApplicationPath); + _native.fWindowsAuthEnabled = managed.fWindowsAuthEnabled ? 1 : 0; + _native.fBasicAuthEnabled = managed.fBasicAuthEnabled ? 1 : 0; + _native.fAnonymousAuthEnable = managed.fAnonymousAuthEnable ? 1 : 0; + _native.pwzBindings = managed.pwzBindings is null ? IntPtr.Zero : Marshal.StringToBSTR(managed.pwzBindings); + _native.maxRequestBodySize = managed.maxRequestBodySize; + } + + public Native ToNativeValue() => _native; + + public void FromNativeValue(Native value) => _native = value; + + public IISConfigurationData ToManaged() + { + return new() + { + pNativeApplication = _native.pNativeApplication, + pwzFullApplicationPath = _native.pwzFullApplicationPath == IntPtr.Zero ? string.Empty : Marshal.PtrToStringBSTR(_native.pwzFullApplicationPath), + pwzVirtualApplicationPath = _native.pwzVirtualApplicationPath == IntPtr.Zero ? string.Empty : Marshal.PtrToStringBSTR(_native.pwzVirtualApplicationPath), + fWindowsAuthEnabled = _native.fWindowsAuthEnabled != 0, + fBasicAuthEnabled = _native.fBasicAuthEnabled != 0, + fAnonymousAuthEnable = _native.fAnonymousAuthEnable != 0, + pwzBindings = _native.pwzBindings == IntPtr.Zero ? string.Empty : Marshal.PtrToStringBSTR(_native.pwzBindings), + maxRequestBodySize = _native.maxRequestBodySize + }; + } + + public void FreeNative() + { + if (_native.pwzFullApplicationPath != IntPtr.Zero) + { + Marshal.FreeBSTR(_native.pwzFullApplicationPath); + } + if (_native.pwzVirtualApplicationPath != IntPtr.Zero) + { + Marshal.FreeBSTR(_native.pwzVirtualApplicationPath); + } + if (_native.pwzBindings != IntPtr.Zero) + { + Marshal.FreeBSTR(_native.pwzBindings); + } + } + } } diff --git a/src/Servers/IIS/IIS/src/NativeMethods.cs b/src/Servers/IIS/IIS/src/NativeMethods.cs index da8b7f7eebeddbc0a7e0c1f68b882f5ac94334f1..79ed2bf696a251aa816d8d5cb51988d41fa7b3a0 100644 --- a/src/Servers/IIS/IIS/src/NativeMethods.cs +++ b/src/Servers/IIS/IIS/src/NativeMethods.cs @@ -7,7 +7,7 @@ using Microsoft.AspNetCore.Server.IIS.Core; namespace Microsoft.AspNetCore.Server.IIS; -internal static class NativeMethods +internal static partial class NativeMethods { internal const int HR_OK = 0; internal const int ERROR_NOT_FOUND = unchecked((int)0x80070490); @@ -19,12 +19,12 @@ internal static class NativeMethods internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll"; - [DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)] + [LibraryImport(KERNEL32, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool CloseHandle(IntPtr handle); - public static extern bool CloseHandle(IntPtr handle); - - [DllImport("kernel32.dll")] - private static extern IntPtr GetModuleHandle(string lpModuleName); + [LibraryImport(KERNEL32, EntryPoint = "GetModuleHandleW")] + private static partial IntPtr GetModuleHandle([MarshalAs(UnmanagedType.LPWStr)] string lpModuleName); public static bool IsAspNetCoreModuleLoaded() { @@ -38,17 +38,17 @@ internal static class NativeMethods RQ_NOTIFICATION_FINISH_REQUEST } - [DllImport(AspNetCoreModuleDll)] - private static extern int http_post_completion(NativeSafeHandle pInProcessHandler, int cbBytes); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_post_completion(NativeSafeHandle pInProcessHandler, int cbBytes); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_set_completion_status(NativeSafeHandle pInProcessHandler, REQUEST_NOTIFICATION_STATUS rquestNotificationStatus); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_set_completion_status(NativeSafeHandle pInProcessHandler, REQUEST_NOTIFICATION_STATUS rquestNotificationStatus); - [DllImport(AspNetCoreModuleDll)] - private static extern void http_indicate_completion(NativeSafeHandle pInProcessHandler, REQUEST_NOTIFICATION_STATUS notificationStatus); + [LibraryImport(AspNetCoreModuleDll)] + private static partial void http_indicate_completion(NativeSafeHandle pInProcessHandler, REQUEST_NOTIFICATION_STATUS notificationStatus); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int register_callbacks(NativeSafeHandle pInProcessApplication, + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int register_callbacks(NativeSafeHandle pInProcessApplication, delegate* unmanaged<IntPtr, IntPtr, REQUEST_NOTIFICATION_STATUS> requestCallback, delegate* unmanaged<IntPtr, int> shutdownCallback, delegate* unmanaged<IntPtr, void> disconnectCallback, @@ -57,101 +57,101 @@ internal static class NativeMethods IntPtr pvRequestContext, IntPtr pvShutdownContext); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_write_response_bytes(NativeSafeHandle pInProcessHandler, HttpApiTypes.HTTP_DATA_CHUNK* pDataChunks, int nChunks, out bool fCompletionExpected); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_write_response_bytes(NativeSafeHandle pInProcessHandler, HttpApiTypes.HTTP_DATA_CHUNK* pDataChunks, int nChunks, [MarshalAs(UnmanagedType.Bool)] out bool fCompletionExpected); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_flush_response_bytes(NativeSafeHandle pInProcessHandler, bool fMoreData, out bool fCompletionExpected); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_flush_response_bytes(NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.Bool)] bool fMoreData, [MarshalAs(UnmanagedType.Bool)] out bool fCompletionExpected); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe HttpApiTypes.HTTP_REQUEST_V2* http_get_raw_request(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial HttpApiTypes.HTTP_REQUEST_V2* http_get_raw_request(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_stop_calls_into_managed(NativeSafeHandle pInProcessApplication); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_stop_calls_into_managed(NativeSafeHandle pInProcessApplication); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_stop_incoming_requests(NativeSafeHandle pInProcessApplication); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_stop_incoming_requests(NativeSafeHandle pInProcessApplication); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_disable_buffering(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_disable_buffering(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll, CharSet = CharSet.Ansi)] - private static extern int http_set_response_status_code(NativeSafeHandle pInProcessHandler, ushort statusCode, string pszReason); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_set_response_status_code(NativeSafeHandle pInProcessHandler, ushort statusCode, [MarshalAs(UnmanagedType.LPStr)] string pszReason); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_read_request_bytes(NativeSafeHandle pInProcessHandler, byte* pvBuffer, int cbBuffer, out int dwBytesReceived, out bool fCompletionExpected); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_read_request_bytes(NativeSafeHandle pInProcessHandler, byte* pvBuffer, int cbBuffer, out int dwBytesReceived, [MarshalAs(UnmanagedType.Bool)] out bool fCompletionExpected); - [DllImport(AspNetCoreModuleDll)] - private static extern void http_get_completion_info(IntPtr pCompletionInfo, out int cbBytes, out int hr); + [LibraryImport(AspNetCoreModuleDll)] + private static partial void http_get_completion_info(IntPtr pCompletionInfo, out int cbBytes, out int hr); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_set_managed_context(NativeSafeHandle pInProcessHandler, IntPtr pvManagedContext); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_set_managed_context(NativeSafeHandle pInProcessHandler, IntPtr pvManagedContext); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_get_application_properties(out IISConfigurationData iiConfigData); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_get_server_variable( + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_get_server_variable( NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.LPStr)] string variableName, [MarshalAs(UnmanagedType.BStr)] out string value); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_set_server_variable( + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_set_server_variable( NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.LPStr)] string variableName, [MarshalAs(UnmanagedType.LPWStr)] string value); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_websockets_read_bytes( + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_websockets_read_bytes( NativeSafeHandle pInProcessHandler, byte* pvBuffer, int cbBuffer, delegate* unmanaged<IntPtr, IntPtr, IntPtr, REQUEST_NOTIFICATION_STATUS> pfnCompletionCallback, IntPtr pvCompletionContext, out int dwBytesReceived, - out bool fCompletionExpected); + [MarshalAs(UnmanagedType.Bool)] out bool fCompletionExpected); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_websockets_write_bytes( + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_websockets_write_bytes( NativeSafeHandle pInProcessHandler, HttpApiTypes.HTTP_DATA_CHUNK* pDataChunks, int nChunks, delegate* unmanaged<IntPtr, IntPtr, IntPtr, REQUEST_NOTIFICATION_STATUS> pfnCompletionCallback, IntPtr pvCompletionContext, - out bool fCompletionExpected); + [MarshalAs(UnmanagedType.Bool)] out bool fCompletionExpected); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_enable_websockets(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_enable_websockets(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_cancel_io(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_cancel_io(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_close_connection(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_close_connection(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_response_set_need_goaway(NativeSafeHandle pInProcessHandler); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_response_set_need_goaway(NativeSafeHandle pInProcessHandler); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_response_set_unknown_header(NativeSafeHandle pInProcessHandler, byte* pszHeaderName, byte* pszHeaderValue, ushort usHeaderValueLength, bool fReplace); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_response_set_unknown_header(NativeSafeHandle pInProcessHandler, byte* pszHeaderName, byte* pszHeaderValue, ushort usHeaderValueLength, [MarshalAs(UnmanagedType.Bool)] bool fReplace); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_has_response4(NativeSafeHandle pInProcessHandler, out bool isResponse4); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_response_set_trailer(NativeSafeHandle pInProcessHandler, byte* pszHeaderName, byte* pszHeaderValue, ushort usHeaderValueLength, bool replace); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_has_response4(NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.Bool)] out bool isResponse4); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_response_set_trailer(NativeSafeHandle pInProcessHandler, byte* pszHeaderName, byte* pszHeaderValue, ushort usHeaderValueLength, [MarshalAs(UnmanagedType.Bool)] bool replace); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_reset_stream(NativeSafeHandle pInProcessHandler, ulong errorCode); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_reset_stream(NativeSafeHandle pInProcessHandler, ulong errorCode); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_response_set_known_header(NativeSafeHandle pInProcessHandler, int headerId, byte* pHeaderValue, ushort length, bool fReplace); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_response_set_known_header(NativeSafeHandle pInProcessHandler, int headerId, byte* pHeaderValue, ushort length, [MarshalAs(UnmanagedType.Bool)] bool fReplace); - [DllImport(AspNetCoreModuleDll)] - private static extern int http_get_authentication_information(NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.BStr)] out string authType, out IntPtr token); + [LibraryImport(AspNetCoreModuleDll)] + private static partial int http_get_authentication_information(NativeSafeHandle pInProcessHandler, [MarshalAs(UnmanagedType.BStr)] out string authType, out IntPtr token); - [DllImport(AspNetCoreModuleDll)] - private static extern unsafe int http_set_startup_error_page_content(byte* content, int contentLength); + [LibraryImport(AspNetCoreModuleDll)] + private static unsafe partial int http_set_startup_error_page_content(byte* content, int contentLength); public static void HttpPostCompletion(NativeSafeHandle pInProcessHandler, int cbBytes) { @@ -227,8 +227,7 @@ internal static class NativeMethods internal static IISConfigurationData HttpGetApplicationProperties() { - var iisConfigurationData = new IISConfigurationData(); - Validate(http_get_application_properties(ref iisConfigurationData)); + Validate(http_get_application_properties(out IISConfigurationData iisConfigurationData)); return iisConfigurationData; } diff --git a/src/Servers/IIS/IIS/test/IIS.Tests/IIS.Tests.csproj b/src/Servers/IIS/IIS/test/IIS.Tests/IIS.Tests.csproj index 777aaae856eabbdcb095244d19d2e3caa04303fc..605656b95560878541fb6e002b3590b7fd29656a 100644 --- a/src/Servers/IIS/IIS/test/IIS.Tests/IIS.Tests.csproj +++ b/src/Servers/IIS/IIS/test/IIS.Tests/IIS.Tests.csproj @@ -5,6 +5,7 @@ <PropertyGroup> <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> <InProcessTestSite>true</InProcessTestSite> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <Import Project="../FunctionalTest.props" /> diff --git a/src/Servers/IIS/IIS/test/IIS.Tests/Utilities/TestServer.cs b/src/Servers/IIS/IIS/test/IIS.Tests/Utilities/TestServer.cs index a4bd602edce14730296a68e7297f568f156cec43..1d3be52275cd498b7a110f9fa1c5ca34aa33252f 100644 --- a/src/Servers/IIS/IIS/test/IIS.Tests/Utilities/TestServer.cs +++ b/src/Servers/IIS/IIS/test/IIS.Tests/Utilities/TestServer.cs @@ -23,7 +23,7 @@ using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests; -public class TestServer : IDisposable +public partial class TestServer : IDisposable { private const string InProcessHandlerDll = "aspnetcorev2_inprocess.dll"; private const string AspNetCoreModuleDll = "aspnetcorev2.dll"; @@ -178,23 +178,23 @@ public class TestServer : IDisposable private delegate int hostfxr_main_fn(IntPtr argc, IntPtr argv); - [DllImport(HWebCoreDll)] - private static extern int WebCoreActivate( - [In, MarshalAs(UnmanagedType.LPWStr)] + [LibraryImport(HWebCoreDll)] + private static partial int WebCoreActivate( + [MarshalAs(UnmanagedType.LPWStr)] string appHostConfigPath, - [In, MarshalAs(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] string rootWebConfigPath, - [In, MarshalAs(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] string instanceName); - [DllImport(HWebCoreDll)] - private static extern int WebCoreShutdown(bool immediate); + [LibraryImport(HWebCoreDll)] + private static partial int WebCoreShutdown([MarshalAs(UnmanagedType.Bool)] bool immediate); - [DllImport(InProcessHandlerDll)] - private static extern int set_main_handler(hostfxr_main_fn main); + [LibraryImport(InProcessHandlerDll)] + private static partial int set_main_handler(hostfxr_main_fn main); - [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)] - private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpFileName); + [LibraryImport("kernel32", EntryPoint = "LoadLibraryW", SetLastError = true)] + private static partial IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPWStr)] string lpFileName); private void Retry(Action func, int attempts) { diff --git a/src/Servers/IIS/IIS/test/testassets/InProcessNewShimWebSite/InProcessNewShimWebSite.csproj b/src/Servers/IIS/IIS/test/testassets/InProcessNewShimWebSite/InProcessNewShimWebSite.csproj index 5ec39f6e7a0f873506d5ad0bd47363fe819f97c2..2acbf0a49b2ee3b632ebe71db52cca56a3fe993e 100644 --- a/src/Servers/IIS/IIS/test/testassets/InProcessNewShimWebSite/InProcessNewShimWebSite.csproj +++ b/src/Servers/IIS/IIS/test/testassets/InProcessNewShimWebSite/InProcessNewShimWebSite.csproj @@ -1,4 +1,4 @@ -<Project Sdk="Microsoft.NET.Sdk.Web"> +<Project Sdk="Microsoft.NET.Sdk.Web"> <Import Project="..\..\..\..\build\testsite.props" /> <PropertyGroup> @@ -7,6 +7,7 @@ <DefineConstants>FORWARDCOMPAT</DefineConstants> <CompileUsingReferenceAssemblies>false</CompileUsingReferenceAssemblies> <ImplicitUsings>disable</ImplicitUsings> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> diff --git a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj index eb727d52c5ebad9c80bf952510f360aa5b701aa0..be69b71e9217c3aa78775b06af4474f907b16528 100644 --- a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj +++ b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj @@ -4,6 +4,7 @@ <PropertyGroup> <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> <InProcessTestSite>true</InProcessTestSite> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Condition="'$(OS)' == 'Windows_NT'"> diff --git a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs index de9ddf614f4a354592b201115e167b08c545683a..584cb898791e0c546dcd706c43e3b930a174c479 100644 --- a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs +++ b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs @@ -9,6 +9,7 @@ using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; using System.Security.Principal; using System.Text; using System.Threading; @@ -179,14 +180,14 @@ public partial class Startup }); } - [DllImport("kernel32.dll")] - static extern uint GetDllDirectory(uint nBufferLength, [Out] StringBuilder lpBuffer); + [LibraryImport("kernel32.dll")] + private static partial uint GetDllDirectory(uint nBufferLength, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2)] char[] lpBuffer); private async Task DllDirectory(HttpContext context) { - var builder = new StringBuilder(1024); - GetDllDirectory(1024, builder); - await context.Response.WriteAsync(builder.ToString()); + var buffer = new char[1024]; + GetDllDirectory(1024, buffer); + await context.Response.WriteAsync(buffer.ToString()); } private async Task GetEnvironmentVariable(HttpContext ctx) diff --git a/src/Servers/IIS/IISIntegration/src/NativeMethods.cs b/src/Servers/IIS/IISIntegration/src/NativeMethods.cs index e24c14fc1bb288e5add3418dccbc7417aa245d2b..df927ded80dc5604389cf6c03368fa29d2d96ff3 100644 --- a/src/Servers/IIS/IISIntegration/src/NativeMethods.cs +++ b/src/Servers/IIS/IISIntegration/src/NativeMethods.cs @@ -5,11 +5,11 @@ using System.Runtime.InteropServices; namespace Microsoft.AspNetCore.Server.IISIntegration; -internal static class NativeMethods +internal static partial class NativeMethods { private const string KERNEL32 = "kernel32.dll"; - [DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)] - - public static extern bool CloseHandle(IntPtr handle); + [LibraryImport(KERNEL32, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool CloseHandle(IntPtr handle); } diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/IISExpressDeployer.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/IISExpressDeployer.cs index 924690410d98d4e0721c72f7850c96e3a12604cf..82e10049729a2e3728a5f426d8b331f6447ab7ac 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/IISExpressDeployer.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/IISExpressDeployer.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; using System.Text.RegularExpressions; using System.Xml.Linq; using Microsoft.AspNetCore.Server.IntegrationTesting.Common; @@ -15,7 +16,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS; /// <summary> /// Deployment helper for IISExpress. /// </summary> -public class IISExpressDeployer : IISDeployerBase +public partial class IISExpressDeployer : IISDeployerBase { private const string IISExpressRunningMessage = "IIS Express is running."; private const string FailedToInitializeBindingsMessage = "Failed to initialize site bindings"; @@ -440,17 +441,34 @@ public class IISExpressDeployer : IISDeployerBase } } - private sealed class WindowsNativeMethods + private sealed partial class WindowsNativeMethods { internal delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam); - [DllImport("user32.dll")] - internal static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId); - [DllImport("user32.dll")] - internal static extern bool PostMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam); - [DllImport("user32.dll")] - internal static extern bool EnumWindows(EnumWindowProc callback, IntPtr lParam); - [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] - internal static extern int GetClassName(IntPtr hWnd, char[] lpClassName, int nMaxCount); + [LibraryImport("user32.dll")] + internal static partial uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId); + [LibraryImport("user32.dll", EntryPoint = "PostMessageW")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool PostMessage([MarshalUsing(typeof(HandleRefMarshaller))] HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool EnumWindows(EnumWindowProc callback, IntPtr lParam); + [LibraryImport("user32.dll", EntryPoint = "GetClassNameW", SetLastError = true)] + internal static partial int GetClassName(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2)] char[] lpClassName, int nMaxCount); + + [CustomTypeMarshaller(typeof(HandleRef), Direction = CustomTypeMarshallerDirection.In, Features = CustomTypeMarshallerFeatures.UnmanagedResources | CustomTypeMarshallerFeatures.TwoStageMarshalling)] + internal struct HandleRefMarshaller + { + private readonly HandleRef _handle; + + public HandleRefMarshaller(HandleRef handle) + { + _handle = handle; + } + + public IntPtr ToNativeValue() => _handle.Handle; + + public void FreeNative() => GC.KeepAlive(_handle.Wrapper); + } } private void SendStopMessageToProcess(int pid) diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/Microsoft.AspNetCore.Server.IntegrationTesting.IIS.csproj b/src/Servers/IIS/IntegrationTesting.IIS/src/Microsoft.AspNetCore.Server.IntegrationTesting.IIS.csproj index 633601649a49ce9a095d9a5364f7c95a5fcb745a..e6c3f4276dbd9c9c89681aaafbe413598ee052c0 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/Microsoft.AspNetCore.Server.IntegrationTesting.IIS.csproj +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/Microsoft.AspNetCore.Server.IntegrationTesting.IIS.csproj @@ -1,4 +1,4 @@ -<Project Sdk="Microsoft.NET.Sdk"> +<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework> @@ -20,6 +20,7 @@ <NoWarn>$(NoWarn);NU5100</NoWarn> <!-- Ignore platform compatibility analyzer warnings for test and test infrastructure --> <NoWarn>$(NoWarn);CA1416</NoWarn> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <Import Project="..\..\build\assets.props" /> diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs index 3fdf0025dd75f4dacf5f25d47f2971f85dcdde77..616f40bfc17b46018c4295d212d9273a626d0e31 100644 --- a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs +++ b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs @@ -8,7 +8,7 @@ using System.Runtime.InteropServices; namespace Microsoft.AspNetCore.Server.IntegrationTesting.IIS; // Uses Windows Job Objects to ensure external processes are killed if the current process is terminated non-gracefully. -internal static class ProcessTracker +internal static partial class ProcessTracker { private static readonly IntPtr _jobHandle = IntiailizeProcessTracker(); @@ -63,15 +63,17 @@ internal static class ProcessTracker } } - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string name); + [LibraryImport("kernel32.dll", EntryPoint = "CreateJobObjectW", StringMarshalling = StringMarshalling.Utf16)] + private static partial IntPtr CreateJobObject(IntPtr lpJobAttributes, string name); - [DllImport("kernel32.dll")] - static extern bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType, + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool SetInformationJobObject(IntPtr job, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength); - [DllImport("kernel32.dll", SetLastError = true)] - static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool AssignProcessToJobObject(IntPtr job, IntPtr process); private enum JobObjectInfoType { diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs index e2cda11019979669ebd1d55fcab57aad16f9e2bb..748e4e94a7b317234d033cde3dc6fed6cb7676d2 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs @@ -14,7 +14,7 @@ using Xunit; namespace Interop.FunctionalTests; -public static class H2SpecCommands +public static partial class H2SpecCommands { #region chmod // user permissions @@ -35,8 +35,8 @@ public static class H2SpecCommands | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; - [DllImport("libc", SetLastError = true)] - private static extern int chmod(string pathname, int mode); + [LibraryImport("libc", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + private static partial int chmod(string pathname, int mode); private static int chmod755(string pathname) => chmod(pathname, _0755); #endregion diff --git a/src/Servers/Kestrel/test/Interop.FunctionalTests/Interop.FunctionalTests.csproj b/src/Servers/Kestrel/test/Interop.FunctionalTests/Interop.FunctionalTests.csproj index 358a06a38f8c10ce656e3195988ede0ba99b2b2d..404aeebc0a097e9c493296286b26ca07c053f0de 100644 --- a/src/Servers/Kestrel/test/Interop.FunctionalTests/Interop.FunctionalTests.csproj +++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/Interop.FunctionalTests.csproj @@ -7,6 +7,7 @@ <!-- WebDriver is not strong named, so this test assembly cannot be strong-named either. --> <SignAssembly>false</SignAssembly> <SkipHelixAlpine>true</SkipHelixAlpine> + <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup> diff --git a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs index 0a44886086e271c88641af60910807a0cf1182ed..7fed60b434b180d7476699d06afe7ab619d0049e 100644 --- a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs +++ b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs @@ -7,7 +7,7 @@ using System.Runtime.InteropServices; namespace Microsoft.AspNetCore.HttpSys.Internal; -internal static unsafe class UnsafeNclNativeMethods +internal static unsafe partial class UnsafeNclNativeMethods { private const string sspicli_LIB = "sspicli.dll"; private const string api_ms_win_core_io_LIB = "api-ms-win-core-io-l1-1-0.dll"; @@ -37,11 +37,12 @@ internal static unsafe class UnsafeNclNativeMethods internal const uint ERROR_CONNECTION_INVALID = 1229; } - [DllImport(api_ms_win_core_io_LIB, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern unsafe uint CancelIoEx(SafeHandle handle, SafeNativeOverlapped overlapped); + [LibraryImport(api_ms_win_core_io_LIB, SetLastError = true)] + internal static unsafe partial uint CancelIoEx(SafeHandle handle, SafeNativeOverlapped overlapped); - [DllImport(api_ms_win_core_kernel32_legacy_LIB, ExactSpelling = true, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - internal static extern unsafe bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes modes); + [LibraryImport(api_ms_win_core_kernel32_legacy_LIB, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static unsafe partial bool SetFileCompletionNotificationModes(SafeHandle handle, FileCompletionNotificationModes modes); [Flags] internal enum FileCompletionNotificationModes : byte @@ -51,40 +52,42 @@ internal static unsafe class UnsafeNclNativeMethods SkipSetEventOnHandle = 2 } - [DllImport(TOKENBINDING, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] - public static extern int TokenBindingVerifyMessage( - [In] byte* tokenBindingMessage, - [In] uint tokenBindingMessageSize, - [In] char* keyType, - [In] byte* tlsUnique, - [In] uint tlsUniqueSize, - [Out] out HeapAllocHandle resultList); + [LibraryImport(TOKENBINDING)] + public static partial int TokenBindingVerifyMessage( + byte* tokenBindingMessage, + uint tokenBindingMessageSize, + char* keyType, + byte* tlsUnique, + uint tlsUniqueSize, + out HeapAllocHandle resultList); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa366569(v=vs.85).aspx - [DllImport(api_ms_win_core_heap_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] - internal static extern IntPtr GetProcessHeap(); + [LibraryImport(api_ms_win_core_heap_LIB, SetLastError = true)] + internal static partial IntPtr GetProcessHeap(); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa366701(v=vs.85).aspx - [DllImport(api_ms_win_core_heap_LIB, CallingConvention = CallingConvention.Winapi, SetLastError = true)] - internal static extern bool HeapFree( - [In] IntPtr hHeap, - [In] uint dwFlags, - [In] IntPtr lpMem); - - internal static class SafeNetHandles + [LibraryImport(api_ms_win_core_heap_LIB, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool HeapFree( + IntPtr hHeap, + uint dwFlags, + IntPtr lpMem); + + internal static partial class SafeNetHandles { - [DllImport(sspicli_LIB, ExactSpelling = true, SetLastError = true)] - internal static extern int FreeContextBuffer( - [In] IntPtr contextBuffer); + [LibraryImport(sspicli_LIB, SetLastError = true)] + internal static partial int FreeContextBuffer( + IntPtr contextBuffer); - [DllImport(api_ms_win_core_handle_LIB, ExactSpelling = true, SetLastError = true)] - internal static extern bool CloseHandle(IntPtr handle); + [LibraryImport(api_ms_win_core_handle_LIB, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseHandle(IntPtr handle); - [DllImport(api_ms_win_core_heap_obsolete_LIB, EntryPoint = "LocalAlloc", SetLastError = true)] - internal static extern SafeLocalFreeChannelBinding LocalAllocChannelBinding(int uFlags, UIntPtr sizetdwBytes); + [LibraryImport(api_ms_win_core_heap_obsolete_LIB, EntryPoint = "LocalAlloc", SetLastError = true)] + internal static partial SafeLocalFreeChannelBinding LocalAllocChannelBinding(int uFlags, UIntPtr sizetdwBytes); - [DllImport(api_ms_win_core_heap_obsolete_LIB, ExactSpelling = true, SetLastError = true)] - internal static extern IntPtr LocalFree(IntPtr handle); + [LibraryImport(api_ms_win_core_heap_obsolete_LIB, SetLastError = true)] + internal static partial IntPtr LocalFree(IntPtr handle); } // from tokenbinding.h @@ -140,17 +143,4 @@ internal static unsafe class UnsafeNclNativeMethods public TOKENBINDING_RESULT_DATA* resultData; } } - - // DACL related stuff - - [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Instantiated natively")] - [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", - Justification = "Does not own the resource.")] - [StructLayout(LayoutKind.Sequential)] - internal sealed class SECURITY_ATTRIBUTES - { - public int nLength = 12; - public SafeLocalMemHandle lpSecurityDescriptor = new SafeLocalMemHandle(IntPtr.Zero, false); - public bool bInheritHandle; - } } diff --git a/src/Testing/src/DumpCollector/DumpCollector.Windows.cs b/src/Testing/src/DumpCollector/DumpCollector.Windows.cs index 65d9579c012fb96038c27a5fc90e619fe01d6352..cbc2b9b15cd49c72c8b0a8b68961a298b54d8bce 100644 --- a/src/Testing/src/DumpCollector/DumpCollector.Windows.cs +++ b/src/Testing/src/DumpCollector/DumpCollector.Windows.cs @@ -31,7 +31,9 @@ public static partial class DumpCollector private static class NativeMethods { [DllImport("Dbghelp.dll")] +#pragma warning disable SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time public static extern bool MiniDumpWriteDump(IntPtr hProcess, uint ProcessId, SafeFileHandle hFile, MINIDUMP_TYPE DumpType, ref MINIDUMP_EXCEPTION_INFORMATION ExceptionParam, IntPtr UserStreamParam, IntPtr CallbackParam); +#pragma warning restore SYSLIB1054 // Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct MINIDUMP_EXCEPTION_INFORMATION