diff --git a/.editorconfig b/.editorconfig
index 80d276422cb3..c532bc0d1f63 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 52fd7178f093..54a443530efc 100644
--- a/eng/tools/HelixTestRunner/HelixTestRunner.csproj
+++ b/eng/tools/HelixTestRunner/HelixTestRunner.csproj
@@ -13,6 +13,7 @@
Exe
$(NoWarn);CA2007;NU5104
false
+ true
true
diff --git a/eng/tools/HelixTestRunner/ProcessUtil.cs b/eng/tools/HelixTestRunner/ProcessUtil.cs
index 067850c4468e..b895fa86f548 100644
--- a/eng/tools/HelixTestRunner/ProcessUtil.cs
+++ b/eng/tools/HelixTestRunner/ProcessUtil.cs
@@ -15,10 +15,10 @@
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 09c943878688..98e70e084c4d 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;
///
/// Represents a handle to a Windows module (DLL).
///
-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 @@ protected override bool ReleaseHandle()
}
[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 @@ [In] IntPtr Arguments
#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 07ce968f0691..f943d6706866 100644
--- a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
+++ b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
@@ -15,7 +15,7 @@
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 1cd3b5f9cacc..ae213a62ca83 100644
--- a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
+++ b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
@@ -91,7 +91,7 @@ internal static byte[] ProtectWithDpapiCore(byte* pbSecret, uint cbSecret, byte*
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 Secret UnprotectWithDpapiCore(byte* pbProtectedData, uint cbProt
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 8501fa4083b6..1582c1217524 100644
--- a/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/HttpApi.cs
@@ -8,76 +8,77 @@
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 7b99862f05e3..13e78e2dd43d 100644
--- a/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs
+++ b/src/Servers/HttpSys/src/NativeInterop/RequestQueue.cs
@@ -44,7 +44,7 @@ private RequestQueue(string? requestQueueName, RequestQueueMode mode, ILogger lo
var statusCode = HttpApi.HttpCreateRequestQueue(
HttpApi.Version,
requestQueueName,
- null,
+ IntPtr.Zero,
flags,
out var requestQueueHandle);
@@ -56,7 +56,7 @@ private RequestQueue(string? requestQueueName, RequestQueueMode mode, ILogger lo
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 8949d77de4a9..1f90207dee9e 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;
///
/// Represents a handle to a Windows module (DLL).
///
-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 @@ protected override bool ReleaseHandle()
}
[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 c4ae575303fe..932a398acea8 100644
--- a/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs
+++ b/src/Servers/HttpSys/test/FunctionalTests/Listener/ServerOnExistingQueueTests.cs
@@ -243,7 +243,7 @@ public async Task Server_CreateOrAttach_NoUrlPrefix_NewUrlPrefixWorks()
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 ff897a01e564..2731b109e35b 100644
--- a/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs
+++ b/src/Servers/HttpSys/test/FunctionalTests/ServerTests.cs
@@ -49,7 +49,7 @@ public async Task Server_ConnectExistingQueueName_Success(RequestQueueMode queue
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 b138541d7a9d..612c2072c4d0 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 da8b7f7eebed..79ed2bf696a2 100644
--- a/src/Servers/IIS/IIS/src/NativeMethods.cs
+++ b/src/Servers/IIS/IIS/src/NativeMethods.cs
@@ -7,7 +7,7 @@
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 @@ public enum REQUEST_NOTIFICATION_STATUS
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 requestCallback,
delegate* unmanaged shutdownCallback,
delegate* unmanaged disconnectCallback,
@@ -57,101 +57,101 @@ private static extern unsafe int register_callbacks(NativeSafeHandle pInProcessA
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 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 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 @@ public static void HttpSetManagedContext(NativeSafeHandle pInProcessHandler, Int
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 777aaae856ea..605656b95560 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 @@
$(DefaultNetCoreTargetFramework)
true
+ true
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 a4bd602edce1..1d3be52275cd 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 @@
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 void Dispose()
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 5ec39f6e7a0f..2acbf0a49b2e 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 @@
-
+
@@ -7,6 +7,7 @@
FORWARDCOMPAT
false
disable
+ true
diff --git a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/InProcessWebSite.csproj
index eb727d52c5eb..be69b71e9217 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 @@
$(DefaultNetCoreTargetFramework)
true
+ true
diff --git a/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs b/src/Servers/IIS/IIS/test/testassets/InProcessWebSite/Startup.cs
index de9ddf614f4a..584cb898791e 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.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 void CompressedData(IApplicationBuilder builder)
});
}
- [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 e24c14fc1bb2..df927ded80dc 100644
--- a/src/Servers/IIS/IISIntegration/src/NativeMethods.cs
+++ b/src/Servers/IIS/IISIntegration/src/NativeMethods.cs
@@ -5,11 +5,11 @@
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 924690410d98..82e10049729a 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;
///
/// Deployment helper for IISExpress.
///
-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 override void Dispose(bool gracefulShutdown)
}
}
- 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 633601649a49..e6c3f4276dbd 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 @@
-
+
$(DefaultNetCoreTargetFramework)
@@ -20,6 +20,7 @@
$(NoWarn);NU5100
$(NoWarn);CA1416
+ true
diff --git a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs
index 3fdf0025dd75..616f40bfc17b 100644
--- a/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs
+++ b/src/Servers/IIS/IntegrationTesting.IIS/src/ProcessTracker.cs
@@ -8,7 +8,7 @@
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 @@ public static void Add(Process process)
}
}
- [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 e2cda1101997..748e4e94a7b3 100644
--- a/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs
+++ b/src/Servers/Kestrel/test/Interop.FunctionalTests/H2SpecCommands.cs
@@ -14,7 +14,7 @@
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 358a06a38f8c..404aeebc0a09 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 @@
false
true
+ true
diff --git a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs
index 0a44886086e2..7fed60b434b1 100644
--- a/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs
+++ b/src/Shared/HttpSys/NativeInterop/UnsafeNativeMethods.cs
@@ -7,7 +7,7 @@
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 class ErrorCodes
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 enum FileCompletionNotificationModes : byte
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 unsafe struct TOKENBINDING_RESULT_LIST
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 65d9579c012f..cbc2b9b15cd4 100644
--- a/src/Testing/src/DumpCollector/DumpCollector.Windows.cs
+++ b/src/Testing/src/DumpCollector/DumpCollector.Windows.cs
@@ -31,7 +31,9 @@ internal static void Collect(Process process, string outputFile)
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