Use GeneratedDllImport in System.DirectoryServices (#61975)
authorElinor Fung <elfung@microsoft.com>
Thu, 2 Dec 2021 05:52:02 +0000 (21:52 -0800)
committerGitHub <noreply@github.com>
Thu, 2 Dec 2021 05:52:02 +0000 (21:52 -0800)
23 files changed:
src/libraries/Common/src/Interop/Windows/Activeds/Interop.ADsOpenObject.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ConvertSidToStringSid.cs
src/libraries/Common/src/Interop/Windows/Advapi32/Interop.LogonUser.cs
src/libraries/Common/src/Interop/Windows/NtDll/Interop.NtStatus.cs
src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/interopt.cs
src/libraries/System.DirectoryServices/src/Interop/SafeNativeMethods.cs
src/libraries/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs
src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs
src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs

index 2ed72a6..ee31cd6 100644 (file)
@@ -9,6 +9,6 @@ internal static partial class Interop
     internal static partial class Activeds
     {
         [DllImport(Interop.Libraries.Activeds, CharSet = CharSet.Unicode, ExactSpelling = true)]
-        internal static extern int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
+        internal static extern int ADsOpenObject(string path, string? userName, string? password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
     }
 }
index 998f854..de48c70 100644 (file)
@@ -9,6 +9,6 @@ internal static partial class Interop
     internal static partial class Advapi32
     {
         [GeneratedDllImport(Libraries.Advapi32, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
-        internal static partial BOOL ConvertSidToStringSid(IntPtr sid, ref string stringSid);
+        internal static partial BOOL ConvertSidToStringSid(IntPtr sid, out string stringSid);
     }
 }
index 7e1155d..d15cad8 100644 (file)
@@ -11,8 +11,8 @@ internal static partial class Interop
         [GeneratedDllImport(Libraries.Advapi32, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
         internal static partial int LogonUser(
             string username,
-            string domain,
-            string password,
+            string? domain,
+            string? password,
             int logonType,
             int logonProvider,
             ref IntPtr token);
index 76715c8..4350898 100644 (file)
@@ -14,6 +14,7 @@ internal static partial class Interop
         internal const uint STATUS_NO_MEMORY              = 0xC0000017;
         internal const uint STATUS_ACCESS_DENIED          = 0xC0000022;
         internal const uint STATUS_OBJECT_NAME_NOT_FOUND  = 0xC0000034;
+        internal const uint STATUS_QUOTA_EXCEEDED         = 0xC0000044;
         internal const uint STATUS_ACCOUNT_RESTRICTION    = 0xC000006E;
         internal const uint STATUS_NONE_MAPPED            = 0xC0000073;
         internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A;
index f7a57d0..0ea2bf7 100644 (file)
@@ -1,12 +1,19 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
+using System;
+
 namespace Microsoft.Win32.SafeHandles
 {
     internal sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         public SafeLibraryHandle() : base(true) { }
 
+        internal SafeLibraryHandle(IntPtr value) : base(true)
+        {
+            SetHandle(value);
+        }
+
         protected override bool ReleaseHandle()
         {
             return Interop.Kernel32.FreeLibrary(handle);
index d631c7a..a18cdb6 100644 (file)
@@ -115,8 +115,6 @@ namespace System.DirectoryServices.AccountManagement
 
         internal static string ConvertSidToSDDL(byte[] sid)
         {
-            string sddlSid = null;
-
             // To put the byte[] SID into SDDL, we use ConvertSidToStringSid.
             // Calling that requires we first copy the SID into native memory.
             IntPtr pSid = IntPtr.Zero;
@@ -125,7 +123,7 @@ namespace System.DirectoryServices.AccountManagement
             {
                 pSid = ConvertByteArrayToIntPtr(sid);
 
-                if (Interop.Advapi32.ConvertSidToStringSid(pSid, ref sddlSid) != Interop.BOOL.FALSE)
+                if (Interop.Advapi32.ConvertSidToStringSid(pSid, out string sddlSid) != Interop.BOOL.FALSE)
                 {
                     return sddlSid;
                 }
@@ -502,12 +500,12 @@ namespace System.DirectoryServices.AccountManagement
                 UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)
                                     Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO));
 
-                Debug.Assert(Interop.Advapi32.IsValidSid(info.domainSid));
+                Debug.Assert(Interop.Advapi32.IsValidSid(info.DomainSid));
 
                 // Now we make a copy of the SID to return
-                int sidLength = Interop.Advapi32.GetLengthSid(info.domainSid);
+                int sidLength = Interop.Advapi32.GetLengthSid(info.DomainSid);
                 IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength);
-                bool success = Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.domainSid);
+                bool success = Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid);
                 if (!success)
                 {
                     int lastError = Marshal.GetLastWin32Error();
index d87879d..23ef181 100644 (file)
@@ -435,11 +435,11 @@ namespace System.DirectoryServices.AccountManagement
             public int wki100_ver_minor;
         };
 
-        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-        public sealed class POLICY_ACCOUNT_DOMAIN_INFO
+        [StructLayout(LayoutKind.Sequential)]
+        public struct POLICY_ACCOUNT_DOMAIN_INFO
         {
-            public Interop.UNICODE_INTPTR_STRING domainName;
-            public IntPtr domainSid = IntPtr.Zero;
+            public Interop.UNICODE_INTPTR_STRING DomainName;
+            public IntPtr DomainSid;
         }
     }
 }
index bbff66c..800f61e 100644 (file)
@@ -7,16 +7,13 @@ using System.Runtime.InteropServices;
 
 namespace System.DirectoryServices.Interop
 {
-    internal static class SafeNativeMethods
+    internal static partial class SafeNativeMethods
     {
-        [DllImport(global::Interop.Libraries.OleAut32, PreserveSig = false)]
-        public static extern void VariantClear(IntPtr pObject);
+        [GeneratedDllImport(global::Interop.Libraries.OleAut32)]
+        public static partial void VariantInit(IntPtr pObject);
 
-        [DllImport(global::Interop.Libraries.OleAut32)]
-        public static extern void VariantInit(IntPtr pObject);
-
-        [DllImport(global::Interop.Libraries.Activeds)]
-        public static extern bool FreeADsMem(IntPtr pVoid);
+        [GeneratedDllImport(global::Interop.Libraries.Activeds)]
+        public static partial bool FreeADsMem(IntPtr pVoid);
 
         public const int
             FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
@@ -25,11 +22,11 @@ namespace System.DirectoryServices.Interop
             ERROR_MORE_DATA = 234,
             ERROR_SUCCESS = 0;
 
-        [DllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)]
-        public static extern unsafe int ADsGetLastError(out int error, char* errorBuffer, int errorBufferLength, char* nameBuffer, int nameBufferLength);
+        [GeneratedDllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)]
+        public static unsafe partial int ADsGetLastError(out int error, char* errorBuffer, int errorBufferLength, char* nameBuffer, int nameBufferLength);
 
-        [DllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)]
-        public static extern int ADsSetLastError(int error, string? errorString, string? provider);
+        [GeneratedDllImport(global::Interop.Libraries.Activeds, CharSet = CharSet.Unicode)]
+        public static partial int ADsSetLastError(int error, string? errorString, string? provider);
 
         public class EnumVariant
         {
@@ -99,7 +96,7 @@ namespace System.DirectoryServices.Interop
                     }
                     finally
                     {
-                        VariantClear(addr);
+                        global::Interop.OleAut32.VariantClear(addr);
                     }
                 }
                 finally
index bc8671e..7b4922c 100644 (file)
@@ -28,14 +28,11 @@ namespace System.DirectoryServices.Interop
 
     internal static class UnsafeNativeMethods
     {
-        [DllImport(global::Interop.Libraries.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
-        private static extern int IntADsOpenObject(string path, string? userName, string? password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
-
         public static int ADsOpenObject(string path, string? userName, string? password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
         {
             try
             {
-                return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
+                return global::Interop.Activeds.ADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
             }
             catch (EntryPointNotFoundException)
             {
index 39d6ef2..6384fde 100644 (file)
@@ -1,8 +1,12 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
     <IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
+    <!-- Suppressions to avoid ifdefs:
+        CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
+        CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
+    <NoWarn>$(NoWarn);CA1845;CA1846</NoWarn>
     <Nullable>enable</Nullable>
     <IsPackable>true</IsPackable>
     <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
@@ -149,9 +153,88 @@ System.DirectoryServices.ActiveDirectory.DomainController</PackageDescription>
     <Compile Include="Interop\NativeMethods.cs" />
     <Compile Include="Interop\SafeNativeMethods.cs" />
     <Compile Include="Interop\UnsafeNativeMethods.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOL.cs"
+             Link="Common\Interop\Windows\Interop.BOOL.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.BOOLEAN.cs"
+             Link="Common\Interop\Windows\Interop.BOOLEAN.cs" />
     <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
              Link="Common\Interop\Windows\Interop.Libraries.cs" />
-    <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="System\Obsoletions.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs"
+             Link="Common\Interop\Windows\Interop.OBJECT_ATTRIBUTES.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs"
+             Link="Common\Interop\Windows\Interop.SECURITY_QUALITY_OF_SERVICE.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Interop.UNICODE_STRING.cs"
+             Link="Common\Interop\Windows\Interop.UNICODE_STRING.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Activeds\Interop.ADsOpenObject.cs"
+             Link="Common\Interop\Windows\Activeds\Interop.ADsOpenObject.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ConvertSidToStringSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ConvertStringSidToSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CopySid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.CopySid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.EqualDomainSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.EqualDomainSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetLengthSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetLengthSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetSidIdentifierAuthority.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.GetTokenInformation.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.GetTokenInformation.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.ImpersonateLoggedOnUser_IntPtr.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.IsValidSid.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.IsValidSid.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LogonUser.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LogonUser.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaClose.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaClose.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaFreeMemory.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaNtStatusToWinError.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaOpenPolicy.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.LsaQueryInformationPolicy.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.OpenThreadToken_SafeTokenHandle.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenProcessToken.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.OpenProcessToken.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.RevertToSelf.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.RevertToSelf.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs"
+             Link="Common\Interop\Windows\Advapi32\Interop.TOKEN_INFORMATION_CLASS.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.FreeLibrary.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.FreeLibrary.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentProcess.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThread.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThread.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetCurrentThreadId.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.GetProcAddress.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.GetProcAddress.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LoadLibrary.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.LoadLibrary.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.LocalAlloc.cs"
+             Link="Common\Interop\Windows\Kernel32\Interop.LocalAlloc.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\OleAut32\Interop.VariantClear.cs"
+             Link="Common\Interop\Windows\OleAut32\Interop.VariantClear.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\NtDll\Interop.NtStatus.cs"
+             Link="Common\Interop\Windows\NtDll\Interop.NtStatus.cs" />
+    <Compile Include="$(CommonPath)Interop\Windows\SspiCli\Interop.TOKENS.cs"
+             Link="Common\Interop\Windows\SspiCli\Interop.TOKENS.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeLsaPolicyHandle.cs" />
+    <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeTokenHandle.cs"
+             Link="Common\Microsoft\Win32\SafeHandles\SafeTokenHandle.cs" />
+    <Compile Include="$(CommonPath)System\Obsoletions.cs"
+             Link="System\Obsoletions.cs" />
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" />
@@ -167,6 +250,7 @@ System.DirectoryServices.ActiveDirectory.DomainController</PackageDescription>
     <Reference Include="System.Diagnostics.Debug" />
     <Reference Include="System.IO.FileSystem" />
     <Reference Include="System.IO.FileSystem.AccessControl" />
+    <Reference Include="System.Memory" />
     <Reference Include="System.Net.NameResolution" />
     <Reference Include="System.Net.Primitives" />
     <Reference Include="System.Net.Security" />
@@ -174,6 +258,7 @@ System.DirectoryServices.ActiveDirectory.DomainController</PackageDescription>
     <Reference Include="System.Resources.ResourceManager" />
     <Reference Include="System.Runtime" />
     <Reference Include="System.Runtime.Extensions" />
+    <Reference Include="System.Runtime.CompilerServices.Unsafe" />
     <Reference Include="System.Runtime.InteropServices" />
     <Reference Include="System.Security.AccessControl" />
     <Reference Include="System.Security.Claims" />
index 48281bb..1307a7e 100644 (file)
@@ -1306,7 +1306,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
                 IntPtr info = (IntPtr)0;
                 // call DsReplicaSyncAllW
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -1348,7 +1348,7 @@ namespace System.DirectoryServices.ActiveDirectory
                 finally
                 {
                     // call DsFreeNameResultW
-                    functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+                    functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
                     if (functionPtr == (IntPtr)0)
                     {
                         throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
index 0ed4b80..021afb3 100644 (file)
@@ -9,6 +9,8 @@ using System.ComponentModel;
 using System.IO;
 using System.Diagnostics.CodeAnalysis;
 
+using Microsoft.Win32.SafeHandles;
+
 namespace System.DirectoryServices.ActiveDirectory
 {
     public enum DirectoryContextType
@@ -31,8 +33,8 @@ namespace System.DirectoryServices.ActiveDirectory
         private bool _validated;
         private bool _contextIsValid;
 
-        internal static LoadLibrarySafeHandle ADHandle;
-        internal static LoadLibrarySafeHandle ADAMHandle;
+        internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADHandle;
+        internal static Microsoft.Win32.SafeHandles.SafeLibraryHandle ADAMHandle;
 
         #region constructors
 
@@ -553,14 +555,14 @@ namespace System.DirectoryServices.ActiveDirectory
         {
             string? domainName = null;
 
-            NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest();
+            NegotiateCallerNameRequest requestBuffer = default;
             int requestBufferLength = (int)Marshal.SizeOf(requestBuffer);
 
             IntPtr pResponseBuffer = IntPtr.Zero;
             NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse();
             int responseBufferLength;
-            int protocolStatus;
-            int result;
+            uint protocolStatus;
+            uint result;
 
             LsaLogonProcessSafeHandle lsaHandle;
 
@@ -594,11 +596,11 @@ namespace System.DirectoryServices.ActiveDirectory
                     }
                     else
                     {
-                        if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
+                        if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED)
                         {
                             throw new OutOfMemoryException();
                         }
-                        else if ((result == 0) && (UnsafeNativeMethods.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION))
+                        else if ((result == 0) && (global::Interop.Advapi32.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION))
                         {
                             // If this is a directory user, extract domain info from username
                             if (!Utils.IsSamUser())
@@ -612,7 +614,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         }
                         else
                         {
-                            throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
                         }
                     }
                 }
@@ -624,13 +626,13 @@ namespace System.DirectoryServices.ActiveDirectory
                     }
                 }
             }
-            else if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
+            else if (result == global::Interop.StatusOptions.STATUS_QUOTA_EXCEEDED)
             {
                 throw new OutOfMemoryException();
             }
             else
             {
-                throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result));
+                throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result));
             }
 
             // If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.),
@@ -688,27 +690,27 @@ namespace System.DirectoryServices.ActiveDirectory
         {
             // first get AD handle
             string systemPath = Environment.SystemDirectory;
-            IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll");
+            IntPtr tempHandle = global::Interop.Kernel32.LoadLibrary(systemPath + "\\ntdsapi.dll");
             if (tempHandle == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
             }
             else
             {
-                ADHandle = new LoadLibrarySafeHandle(tempHandle);
+                ADHandle = new SafeLibraryHandle(tempHandle);
             }
 
             // not get the ADAM handle
             // got to the windows\adam directory
             DirectoryInfo windowsDirectory = Directory.GetParent(systemPath)!;
-            tempHandle = UnsafeNativeMethods.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
+            tempHandle = global::Interop.Kernel32.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
             if (tempHandle == (IntPtr)0)
             {
                 ADAMHandle = ADHandle;
             }
             else
             {
-                ADAMHandle = new LoadLibrarySafeHandle(tempHandle);
+                ADAMHandle = new SafeLibraryHandle(tempHandle);
             }
         }
 
index 24bc8ce..3ca3439 100644 (file)
@@ -2,10 +2,11 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System.Collections;
-using System.Globalization;
 using System.Runtime.InteropServices;
 using System.Diagnostics;
 
+using Microsoft.Win32.SafeHandles;
+
 namespace System.DirectoryServices.ActiveDirectory
 {
     public abstract class DirectoryServer : IDisposable
@@ -292,10 +293,10 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal DirectoryContext Context => context;
 
-        internal void CheckConsistencyHelper(IntPtr dsHandle, LoadLibrarySafeHandle libHandle)
+        internal void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle)
         {
             // call DsReplicaConsistencyCheck
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -308,7 +309,7 @@ namespace System.DirectoryServices.ActiveDirectory
                 throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
         }
 
-        internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string? partition, ref bool advanced, int context, LoadLibrarySafeHandle libHandle)
+        internal IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string? partition, ref bool advanced, int context, SafeLibraryHandle libHandle)
         {
             IntPtr info = (IntPtr)0;
             int result = 0;
@@ -317,11 +318,11 @@ namespace System.DirectoryServices.ActiveDirectory
 
             // first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
             // call DsReplicaGetInfo2W
-            functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
+            functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
             if (functionPtr == (IntPtr)0)
             {
                 // a win2k machine which does not have it.
-                functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
+                functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -341,7 +342,7 @@ namespace System.DirectoryServices.ActiveDirectory
             if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
             {
                 // this is the case that client is xp/win2k3, dc is win2k
-                functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaGetInfoW");
+                functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -390,7 +391,7 @@ namespace System.DirectoryServices.ActiveDirectory
             return info;
         }
 
-        internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, LoadLibrarySafeHandle libHandle)
+        internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, SafeLibraryHandle libHandle)
         {
             int context = 0;
             int count = 0;
@@ -455,7 +456,7 @@ namespace System.DirectoryServices.ActiveDirectory
             return collection;
         }
 
-        internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
+        internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
         {
             ReplicationOperationInformation replicationInfo = new ReplicationOperationInformation();
             ReplicationOperationCollection collection = new ReplicationOperationCollection(server);
@@ -484,7 +485,7 @@ namespace System.DirectoryServices.ActiveDirectory
             return replicationInfo;
         }
 
-        internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
+        internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
         {
             ReplicationNeighborCollection collection = new ReplicationNeighborCollection(server);
             int count = 0;
@@ -508,7 +509,7 @@ namespace System.DirectoryServices.ActiveDirectory
             return collection;
         }
 
-        internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
+        internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
         {
             ReplicationFailureCollection collection = new ReplicationFailureCollection(server);
             int count = 0;
@@ -531,7 +532,7 @@ namespace System.DirectoryServices.ActiveDirectory
             return collection;
         }
 
-        internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, LoadLibrarySafeHandle libHandle)
+        internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
         {
             ActiveDirectoryReplicationMetadata collection = new ActiveDirectoryReplicationMetadata(server);
             int count = 0;
@@ -633,7 +634,7 @@ namespace System.DirectoryServices.ActiveDirectory
             }
         }
 
-        internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllFunctionPointer, string partition, SyncFromAllServersOptions option, SyncUpdateCallback? callback, LoadLibrarySafeHandle libHandle)
+        internal void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllFunctionPointer, string partition, SyncFromAllServersOptions option, SyncUpdateCallback? callback, SafeLibraryHandle libHandle)
         {
             IntPtr errorInfo = (IntPtr)0;
 
@@ -642,7 +643,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
             // we want to return the dn instead of DNS guid
             // call DsReplicaSyncAllW
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncAllW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -673,16 +674,16 @@ namespace System.DirectoryServices.ActiveDirectory
             {
                 // release the memory
                 if (errorInfo != (IntPtr)0)
-                    UnsafeNativeMethods.LocalFree(errorInfo);
+                    global::Interop.Kernel32.LocalFree(errorInfo);
             }
         }
 
-        private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, LoadLibrarySafeHandle libHandle)
+        private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHandle libHandle)
         {
             if (value != (IntPtr)0)
             {
                 // call DsReplicaFreeInfo
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaFreeInfo");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -693,7 +694,7 @@ namespace System.DirectoryServices.ActiveDirectory
             }
         }
 
-        internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, LoadLibrarySafeHandle libHandle)
+        internal void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, SafeLibraryHandle libHandle)
         {
             int structSize = Marshal.SizeOf(typeof(Guid));
             IntPtr unmanagedGuid = (IntPtr)0;
@@ -722,7 +723,7 @@ namespace System.DirectoryServices.ActiveDirectory
                 }
 
                 // call DsReplicaSyncW
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsReplicaSyncW");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
index e002830..85591aa 100644 (file)
@@ -1087,7 +1087,7 @@ namespace System.DirectoryServices.ActiveDirectory
             GetDSHandle();
 
             // call DsGetDomainControllerInfo
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -1164,7 +1164,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     if (dcInfoPtr != IntPtr.Zero)
                     {
                         // call DsFreeDomainControllerInfo
-                        functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW");
+                        functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW");
                         if (functionPtr == (IntPtr)0)
                         {
                             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -1249,7 +1249,7 @@ namespace System.DirectoryServices.ActiveDirectory
             GetDSHandle();
             // Get the roles
             // call DsListRoles
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -1289,7 +1289,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     if (rolesPtr != IntPtr.Zero)
                     {
                         // call DsFreeNameResult
-                        functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+                        functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
                         if (functionPtr == (IntPtr)0)
                         {
                             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
index bee105b..0c393ab 100644 (file)
@@ -884,7 +884,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
                 // Get the sites within the forest
                 // call DsListSites
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsListSitesW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -921,7 +921,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         if (sitesPtr != IntPtr.Zero)
                         {
                             // call DsFreeNameResultW
-                            functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+                            functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
                             if (functionPtr == (IntPtr)0)
                             {
                                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
index 1b418b8..27498d2 100644 (file)
@@ -25,22 +25,15 @@ namespace System.DirectoryServices.ActiveDirectory
             _status = (ForestTrustDomainStatus)flag;
             DnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2);
             NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2);
-            IntPtr ptr = (IntPtr)0;
-            int result = UnsafeNativeMethods.ConvertSidToStringSidW(domainInfo.sid, ref ptr);
-            if (result == 0)
-            {
-                throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
-            }
 
-            try
+            string sidLocal;
+            global::Interop.BOOL result = global::Interop.Advapi32.ConvertSidToStringSid(domainInfo.sid, out sidLocal);
+            if (result == global::Interop.BOOL.FALSE)
             {
-                DomainSid = Marshal.PtrToStringUni(ptr)!;
-            }
-            finally
-            {
-                UnsafeNativeMethods.LocalFree(ptr);
+                throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
             }
 
+            DomainSid = sidLocal;
             this.time = time;
         }
 
index ae2ccd4..a209fc1 100644 (file)
@@ -5,6 +5,8 @@ using System.Runtime.InteropServices;
 using System.Collections;
 using System.Collections.Specialized;
 
+using Microsoft.Win32.SafeHandles;
+
 namespace System.DirectoryServices.ActiveDirectory
 {
     public class ForestTrustRelationshipInformation : TrustRelationshipInformation
@@ -82,8 +84,7 @@ namespace System.DirectoryServices.ActiveDirectory
             int currentCount = 0;
             IntPtr tmpPtr = (IntPtr)0;
             IntPtr forestInfo = (IntPtr)0;
-            PolicySafeHandle? handle = null;
-            LSA_UNICODE_STRING trustedDomainName;
+            SafeLsaPolicyHandle? handle = null;
             IntPtr collisionInfo = (IntPtr)0;
             ArrayList ptrList = new ArrayList();
             ArrayList sidList = new ArrayList();
@@ -135,10 +136,9 @@ namespace System.DirectoryServices.ActiveDirectory
                         record.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName;
                         TopLevelName TLN = _topLevelNames[i];
                         record.Time = TLN.time;
-                        record.TopLevelName = new LSA_UNICODE_STRING();
                         ptr = Marshal.StringToHGlobalUni(TLN.Name);
                         ptrList.Add(ptr);
-                        UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr);
+                        UnsafeNativeMethods.RtlInitUnicodeString(out record.TopLevelName, ptr);
 
                         tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
                         ptrList.Add(tmpPtr);
@@ -165,10 +165,10 @@ namespace System.DirectoryServices.ActiveDirectory
                             record.Time.lowPart = currentTime.lower;
                             record.Time.highPart = currentTime.higher;
                         }
-                        record.TopLevelName = new LSA_UNICODE_STRING();
+
                         ptr = Marshal.StringToHGlobalUni(_excludedNames[i]);
                         ptrList.Add(ptr);
-                        UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr);
+                        UnsafeNativeMethods.RtlInitUnicodeString(out record.TopLevelName, ptr);
                         tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
                         ptrList.Add(tmpPtr);
                         Marshal.StructureToPtr(record, tmpPtr, false);
@@ -187,11 +187,8 @@ namespace System.DirectoryServices.ActiveDirectory
                         ForestTrustDomainInformation tmp = _domainInfo[i];
                         record.Time = tmp.time;
                         IntPtr pSid = (IntPtr)0;
-                        IntPtr stringSid = (IntPtr)0;
-                        stringSid = Marshal.StringToHGlobalUni(tmp.DomainSid);
-                        ptrList.Add(stringSid);
-                        int result = UnsafeNativeMethods.ConvertStringSidToSidW(stringSid, ref pSid);
-                        if (result == 0)
+                        global::Interop.BOOL result = global::Interop.Advapi32.ConvertStringSidToSid(tmp.DomainSid, out pSid);
+                        if (result == global::Interop.BOOL.FALSE)
                         {
                             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
                         }
@@ -268,18 +265,18 @@ namespace System.DirectoryServices.ActiveDirectory
                     impersonated = Utils.Impersonate(context);
 
                     // get the policy handle
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(TargetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // call the unmanaged function
-                    int error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo);
+                    uint error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo);
                     if (error != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(error), serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(error), serverName);
                     }
 
                     // there is collision, throw proper exception so user can deal with it
@@ -292,7 +289,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 0, out collisionInfo);
                     if (error != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(error, serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)error, serverName);
                     }
 
                     // now next time property is invoked, we need to go to the server
@@ -311,7 +308,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
                     for (int i = 0; i < sidList.Count; i++)
                     {
-                        UnsafeNativeMethods.LocalFree((IntPtr)sidList[i]!);
+                        global::Interop.Kernel32.LocalFree((IntPtr)sidList[i]!);
                     }
 
                     if (records != (IntPtr)0)
@@ -325,7 +322,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     }
 
                     if (collisionInfo != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(collisionInfo);
+                        global::Interop.Advapi32.LsaFreeMemory(collisionInfo);
 
                     if (target != (IntPtr)0)
                         Marshal.FreeHGlobal(target);
@@ -340,8 +337,7 @@ namespace System.DirectoryServices.ActiveDirectory
         private void GetForestTrustInfoHelper()
         {
             IntPtr forestTrustInfo = (IntPtr)0;
-            PolicySafeHandle? handle = null;
-            LSA_UNICODE_STRING? tmpName = null;
+            SafeLsaPolicyHandle? handle = null;
             bool impersonated = false;
             IntPtr targetPtr = (IntPtr)0;
             string? serverName = null;
@@ -360,9 +356,9 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the target name
-                    tmpName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING tmpName;
                     targetPtr = Marshal.StringToHGlobalUni(TargetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(tmpName, targetPtr);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out tmpName, targetPtr);
 
                     serverName = Utils.GetPolicyServerName(context, true, false, source);
 
@@ -370,16 +366,16 @@ namespace System.DirectoryServices.ActiveDirectory
                     impersonated = Utils.Impersonate(context);
 
                     // get the policy handle
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
-                    int result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo);
+                    uint result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo);
                     // check the result
                     if (result != 0)
                     {
-                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         if (win32Error != 0)
                         {
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                         }
                     }
 
@@ -440,7 +436,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     }
                     finally
                     {
-                        UnsafeNativeMethods.LsaFreeMemory(forestTrustInfo);
+                        global::Interop.Advapi32.LsaFreeMemory(forestTrustInfo);
                     }
 
                     _topLevelNames = tmpTLNs;
index eba0046..aa2c349 100644 (file)
@@ -256,26 +256,15 @@ namespace System.DirectoryServices.ActiveDirectory
         public byte reserved;
     }
 
-    /*typedef struct _LUID {
-            DWORD LowPart;
-            LONG HighPart;
-    } LUID, *PLUID;*/
-    [StructLayout(LayoutKind.Sequential)]
-    internal sealed class LUID
-    {
-        public int LowPart;
-        public int HighPart;
-    }
-
     /*typedef struct _NEGOTIATE_CALLER_NAME_REQUEST {
             ULONG       MessageType ;
             LUID        LogonId ;
     } NEGOTIATE_CALLER_NAME_REQUEST, *PNEGOTIATE_CALLER_NAME_REQUEST ;*/
     [StructLayout(LayoutKind.Sequential)]
-    internal sealed class NegotiateCallerNameRequest
+    internal struct NegotiateCallerNameRequest
     {
         public int messageType;
-        public LUID? logonId;
+        public global::Interop.LUID logonId;
     }
 
     /*typedef struct _NEGOTIATE_CALLER_NAME_RESPONSE {
@@ -289,7 +278,7 @@ namespace System.DirectoryServices.ActiveDirectory
         public string? callerName;
     }
 
-    internal sealed class NativeMethods
+    internal sealed partial class NativeMethods
     {
         // disable public constructor
         private NativeMethods() { }
@@ -320,14 +309,14 @@ namespace System.DirectoryServices.ActiveDirectory
                 ULONG Flags,
                 PDOMAIN_CONTROLLER_INFO* DomainControllerInfo
                 );*/
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
-        internal static extern int DsGetDcName(
-            [In] string? computerName,
-            [In] string? domainName,
-            [In] IntPtr domainGuid,
-            [In] string? siteName,
-            [In] int flags,
-            [Out] out IntPtr domainControllerInfo);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
+        internal static partial int DsGetDcName(
+            string? computerName,
+            string? domainName,
+            IntPtr domainGuid,
+            string? siteName,
+            int flags,
+            out IntPtr domainControllerInfo);
 
         /* DWORD WINAPI DsGetDcOpen(
                          LPCTSTR DnsName,
@@ -338,15 +327,15 @@ namespace System.DirectoryServices.ActiveDirectory
                          ULONG DcFlags,
                          PHANDLE RetGetDcContext
                          );*/
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcOpenW", CharSet = CharSet.Unicode)]
-        internal static extern int DsGetDcOpen(
-            [In] string? dnsName,
-            [In] int optionFlags,
-            [In] string? siteName,
-            [In] IntPtr domainGuid,
-            [In] string? dnsForestName,
-            [In] int dcFlags,
-            [Out] out IntPtr retGetDcContext);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcOpenW", CharSet = CharSet.Unicode)]
+        internal static partial int DsGetDcOpen(
+            string? dnsName,
+            int optionFlags,
+            string? siteName,
+            IntPtr domainGuid,
+            string? dnsForestName,
+            int dcFlags,
+            out IntPtr retGetDcContext);
 
         /*DWORD WINAPI DsGetDcNext(
                         HANDLE GetDcContextHandle,
@@ -354,26 +343,26 @@ namespace System.DirectoryServices.ActiveDirectory
                         LPSOCKET_ADDRESS* SockAddresses,
                         LPTSTR* DnsHostName
                         );*/
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNextW", CharSet = CharSet.Unicode)]
-        internal static extern int DsGetDcNext(
-            [In] IntPtr getDcContextHandle,
-            [In, Out] ref IntPtr sockAddressCount,
-            [Out] out IntPtr sockAdresses,
-            [Out] out IntPtr dnsHostName);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcNextW", CharSet = CharSet.Unicode)]
+        internal static partial int DsGetDcNext(
+            IntPtr getDcContextHandle,
+            ref IntPtr sockAddressCount,
+            out IntPtr sockAdresses,
+            out IntPtr dnsHostName);
 
         /*void WINAPI DsGetDcClose(
                         HANDLE GetDcContextHandle
                         );*/
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcCloseW", CharSet = CharSet.Unicode)]
-        internal static extern void DsGetDcClose(
-            [In] IntPtr getDcContextHandle);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetDcCloseW", CharSet = CharSet.Unicode)]
+        internal static partial void DsGetDcClose(
+            IntPtr getDcContextHandle);
 
         /*NET_API_STATUS NetApiBufferFree(
                 LPVOID Buffer
                 );*/
-        [DllImport(global::Interop.Libraries.Netapi32)]
-        internal static extern int NetApiBufferFree(
-            [In] IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32)]
+        internal static partial int NetApiBufferFree(
+            IntPtr buffer);
 
         /*DWORD DsMakePasswordCredentials(
             LPTSTR User,
@@ -457,10 +446,6 @@ namespace System.DirectoryServices.ActiveDirectory
             [In] IntPtr dsHandle,
             [Out] out IntPtr roles);
 
-        /*DWORD GetLastError(VOID)*/
-        [DllImport(global::Interop.Libraries.Kernel32)]
-        internal static extern int GetLastError();
-
         internal const int DnsSrvData = 33;
         internal const int DnsQueryBypassCache = 8;
 
@@ -472,30 +457,23 @@ namespace System.DirectoryServices.ActiveDirectory
             PDNS_RECORD *ppQueryResultsSet,
             PVOID *pReserved
             );*/
-        [DllImport(global::Interop.Libraries.Dnsapi, EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode)]
-        internal static extern int DnsQuery(
-            [In] string recordName,
-            [In] short recordType,
-            [In] int options,
-            [In] IntPtr servers,
-            [Out] out IntPtr dnsResultList,
-            [Out] IntPtr reserved);
+        [GeneratedDllImport(global::Interop.Libraries.Dnsapi, EntryPoint = "DnsQuery_W", CharSet = CharSet.Unicode)]
+        internal static partial int DnsQuery(
+            string recordName,
+            short recordType,
+            int options,
+            IntPtr servers,
+            out IntPtr dnsResultList,
+            IntPtr reserved);
 
         /*VOID WINAPI DnsRecordListFree(
             PDNS_RECORD pRecordList,
             DNS_FREE_TYPE FreeType
             );*/
-        [DllImport(global::Interop.Libraries.Dnsapi, CharSet = CharSet.Unicode)]
-        internal static extern void DnsRecordListFree(
-            [In] IntPtr dnsResultList,
-            [In] bool dnsFreeType);
-
-        /*BOOL GetVersionEx(
-              LPOSVERSIONINFO lpVersionInfo
-            );*/
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetVersionExW", CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern bool GetVersionEx(
-                [In, Out] OSVersionInfoEx ver);
+        [GeneratedDllImport(global::Interop.Libraries.Dnsapi, CharSet = CharSet.Unicode)]
+        internal static partial void DnsRecordListFree(
+            IntPtr dnsResultList,
+            bool dnsFreeType);
 
         /*DWORD DsCrackNames(
             HANDLE hDS,
@@ -518,9 +496,9 @@ namespace System.DirectoryServices.ActiveDirectory
         /*NTSTATUS LsaConnectUntrusted(
               PHANDLE LsaHandle
             );*/
-        [DllImport(global::Interop.Libraries.Secur32)]
-        internal static extern int LsaConnectUntrusted(
-             [Out] out LsaLogonProcessSafeHandle lsaHandle);
+        [GeneratedDllImport(global::Interop.Libraries.Secur32)]
+        internal static partial uint LsaConnectUntrusted(
+             out LsaLogonProcessSafeHandle lsaHandle);
 
         internal const int NegGetCallerName = 1;
 
@@ -533,29 +511,29 @@ namespace System.DirectoryServices.ActiveDirectory
               PULONG ReturnBufferLength,
               PNTSTATUS ProtocolStatus
             );*/
-        [DllImport(global::Interop.Libraries.Secur32)]
-        internal static extern int LsaCallAuthenticationPackage(
-            [In] LsaLogonProcessSafeHandle lsaHandle,
-            [In] int authenticationPackage,
-            [In] NegotiateCallerNameRequest protocolSubmitBuffer,
-            [In] int submitBufferLength,
-            [Out] out IntPtr protocolReturnBuffer,
-            [Out] out int returnBufferLength,
-            [Out] out int protocolStatus);
+        [GeneratedDllImport(global::Interop.Libraries.Secur32)]
+        internal static partial uint LsaCallAuthenticationPackage(
+            LsaLogonProcessSafeHandle lsaHandle,
+            int authenticationPackage,
+            in NegotiateCallerNameRequest protocolSubmitBuffer,
+            int submitBufferLength,
+            out IntPtr protocolReturnBuffer,
+            out int returnBufferLength,
+            out uint protocolStatus);
 
         /*NTSTATUS LsaFreeReturnBuffer(
               PVOID Buffer
             );*/
-        [DllImport(global::Interop.Libraries.Secur32)]
-        internal static extern uint LsaFreeReturnBuffer(
-            [In] IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Secur32)]
+        internal static partial uint LsaFreeReturnBuffer(
+            IntPtr buffer);
 
         /*NTSTATUS LsaDeregisterLogonProcess(
               HANDLE LsaHandle
             );*/
-        [DllImport(global::Interop.Libraries.Secur32)]
-        internal static extern int LsaDeregisterLogonProcess(
-            [In] IntPtr lsaHandle);
+        [GeneratedDllImport(global::Interop.Libraries.Secur32)]
+        internal static partial int LsaDeregisterLogonProcess(
+            IntPtr lsaHandle);
 
         /*int CompareString(LCID Locale,
             DWORD dwCmpFlags,
@@ -564,17 +542,14 @@ namespace System.DirectoryServices.ActiveDirectory
             DWORD lpString2,
             DWORD cchCount2
             );*/
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CompareStringW", CharSet = CharSet.Unicode, SetLastError = true)]
-        internal static extern int CompareString(
-            [In] uint locale,
-            [In] uint dwCmpFlags,
-            [In] IntPtr lpString1,
-            [In] int cchCount1,
-            [In] IntPtr lpString2,
-            [In] int cchCount2);
-
-        [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
-        internal static extern int LsaNtStatusToWinError(int ntStatus);
+        [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CompareStringW", CharSet = CharSet.Unicode, SetLastError = true)]
+        internal static partial int CompareString(
+            uint locale,
+            uint dwCmpFlags,
+            IntPtr lpString1,
+            int cchCount1,
+            IntPtr lpString2,
+            int cchCount2);
     }
 
     internal sealed class NativeComInterfaces
index af0b098..62ac4f1 100644 (file)
@@ -1,23 +1,10 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
 
-using System.Security;
 using Microsoft.Win32.SafeHandles;
 
 namespace System.DirectoryServices.ActiveDirectory
 {
-    internal sealed class PolicySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
-    {
-        public PolicySafeHandle() : base(true) { }
-
-        internal PolicySafeHandle(IntPtr value) : base(true)
-        {
-            SetHandle(value);
-        }
-
-        protected override bool ReleaseHandle() => UnsafeNativeMethods.LsaClose(handle) == 0;
-    }
-
     internal sealed class LsaLogonProcessSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
     {
         public LsaLogonProcessSafeHandle() : base(true) { }
@@ -29,16 +16,4 @@ namespace System.DirectoryServices.ActiveDirectory
 
         protected override bool ReleaseHandle() => NativeMethods.LsaDeregisterLogonProcess(handle) == 0;
     }
-
-    internal sealed class LoadLibrarySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
-    {
-        public LoadLibrarySafeHandle() : base(true) { }
-
-        internal LoadLibrarySafeHandle(IntPtr value) : base(true)
-        {
-            SetHandle(value);
-        }
-
-        protected override bool ReleaseHandle() => UnsafeNativeMethods.FreeLibrary(handle) != 0;
-    }
 }
index a9eaeac..f55e081 100644 (file)
@@ -19,7 +19,7 @@ namespace System.DirectoryServices.ActiveDirectory
         private TopLevelNameStatus _status;
         internal readonly LARGE_INTEGER time;
 
-        internal TopLevelName(int flag, LSA_UNICODE_STRING val, LARGE_INTEGER time)
+        internal TopLevelName(int flag, global::Interop.UNICODE_STRING val, LARGE_INTEGER time)
         {
             _status = (TopLevelNameStatus)flag;
             Name = Marshal.PtrToStringUni(val.Buffer, val.Length / 2);
index f03d5a4..170c757 100644 (file)
@@ -5,6 +5,8 @@ using System.Runtime.InteropServices;
 using System.Diagnostics;
 using System.Security.Cryptography;
 
+using Microsoft.Win32.SafeHandles;
+
 namespace System.DirectoryServices.ActiveDirectory
 {
     internal enum TRUSTED_INFORMATION_CLASS
@@ -57,9 +59,8 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static bool GetTrustedDomainInfoStatus(DirectoryContext context, string? sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool isForest)
         {
-            PolicySafeHandle? handle = null;
+            SafeLsaPolicyHandle? handle = null;
             IntPtr buffer = (IntPtr)0;
-            LSA_UNICODE_STRING? trustedDomainName = null;
             bool impersonated = false;
             IntPtr target = (IntPtr)0;
             string? serverName = null;
@@ -74,17 +75,17 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle first
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
-                    int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
+                    uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
                     if (result != 0)
                     {
-                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                         if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                         {
@@ -94,12 +95,12 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                     }
 
                     Debug.Assert(buffer != (IntPtr)0);
 
-                    TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
+                    TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default;
                     Marshal.PtrToStructure(buffer, domainInfo);
 
                     // validate this is the trust that the user refers to
@@ -146,7 +147,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         Marshal.FreeHGlobal(target);
 
                     if (buffer != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(buffer);
+                        global::Interop.Advapi32.LsaFreeMemory(buffer);
                 }
             }
             catch { throw; }
@@ -154,10 +155,9 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static void SetTrustedDomainInfoStatus(DirectoryContext context, string? sourceName, string targetName, TRUST_ATTRIBUTE attribute, bool status, bool isForest)
         {
-            PolicySafeHandle? handle = null;
+            SafeLsaPolicyHandle? handle = null;
             IntPtr buffer = (IntPtr)0;
             IntPtr newInfo = (IntPtr)0;
-            LSA_UNICODE_STRING? trustedDomainName = null;
             bool impersonated = false;
             IntPtr target = (IntPtr)0;
             string? serverName = null;
@@ -171,18 +171,18 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle first
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // get the trusted domain information
-                    int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
+                    uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
                     if (result != 0)
                     {
-                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                         if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                         {
@@ -192,12 +192,12 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                     }
                     Debug.Assert(buffer != (IntPtr)0);
 
                     // get the managed structre representation
-                    TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
+                    TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default;
                     Marshal.PtrToStructure(buffer, domainInfo);
 
                     // validate this is the trust that the user refers to
@@ -259,7 +259,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, newInfo);
                     if (result != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
                     }
 
                     return;
@@ -273,7 +273,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         Marshal.FreeHGlobal(target);
 
                     if (buffer != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(buffer);
+                        global::Interop.Advapi32.LsaFreeMemory(buffer);
 
                     if (newInfo != (IntPtr)0)
                         Marshal.FreeHGlobal(newInfo);
@@ -284,9 +284,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static void DeleteTrust(DirectoryContext sourceContext, string? sourceName, string? targetName, bool isForest)
         {
-            PolicySafeHandle? policyHandle = null;
-            LSA_UNICODE_STRING? trustedDomainName = null;
-            int win32Error = 0;
+            SafeLsaPolicyHandle? policyHandle = null;
             bool impersonated = false;
             IntPtr target = (IntPtr)0;
             string? serverName = null;
@@ -301,18 +299,18 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle
-                    policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    policyHandle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // get trust information
-                    int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
+                    uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(policyHandle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
                     if (result != 0)
                     {
-                        win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint  win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                         if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                         {
@@ -322,14 +320,14 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                     }
 
                     Debug.Assert(buffer != (IntPtr)0);
 
                     try
                     {
-                        TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
+                        TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default;
                         Marshal.PtrToStructure(buffer, domainInfo);
 
                         // validate this is the trust that the user refers to
@@ -339,14 +337,14 @@ namespace System.DirectoryServices.ActiveDirectory
                         result = UnsafeNativeMethods.LsaDeleteTrustedDomain(policyHandle, domainInfo.Sid);
                         if (result != 0)
                         {
-                            win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                         }
                     }
                     finally
                     {
                         if (buffer != (IntPtr)0)
-                            UnsafeNativeMethods.LsaFreeMemory(buffer);
+                            global::Interop.Advapi32.LsaFreeMemory(buffer);
                     }
                 }
                 finally
@@ -363,8 +361,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static void VerifyTrust(DirectoryContext context, string? sourceName, string? targetName, bool isForest, TrustDirection direction, bool forceSecureChannelReset, string? preferredTargetServer)
         {
-            PolicySafeHandle? policyHandle = null;
-            LSA_UNICODE_STRING? trustedDomainName = null;
+            SafeLsaPolicyHandle? policyHandle = null;
             int win32Error = 0;
             IntPtr data = (IntPtr)0;
             IntPtr ptr = (IntPtr)0;
@@ -383,12 +380,12 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle
-                    policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(policyServerName));
+                    policyHandle = Utils.GetPolicyHandle(policyServerName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // validate the trust existence
                     ValidateTrust(policyHandle, trustedDomainName, sourceName, targetName, isForest, (int)direction, policyServerName);  // need to verify direction
@@ -479,13 +476,11 @@ namespace System.DirectoryServices.ActiveDirectory
         internal static void CreateTrust(DirectoryContext sourceContext, string? sourceName, DirectoryContext targetContext, string? targetName, bool isForest, TrustDirection direction, string password)
         {
             LSA_AUTH_INFORMATION? AuthData = null;
-            TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null;
-            TRUSTED_DOMAIN_INFORMATION_EX? tdi = null;
             IntPtr fileTime = (IntPtr)0;
             IntPtr unmanagedPassword = (IntPtr)0;
             IntPtr info = (IntPtr)0;
             IntPtr domainHandle = (IntPtr)0;
-            PolicySafeHandle? policyHandle = null;
+            SafeLsaPolicyHandle? policyHandle = null;
             IntPtr unmanagedAuthData = (IntPtr)0;
             bool impersonated = false;
             string? serverName = null;
@@ -519,7 +514,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
                     Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
 
-                    AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
+                    TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default;
                     if ((direction & TrustDirection.Inbound) != 0)
                     {
                         AuthInfoEx.IncomingAuthInfos = 1;
@@ -534,12 +529,14 @@ namespace System.DirectoryServices.ActiveDirectory
                         AuthInfoEx.OutgoingPreviousAuthenticationInformation = (IntPtr)0;
                     }
 
-                    tdi = new TRUSTED_DOMAIN_INFORMATION_EX();
-                    tdi.FlatName = domainInfo.Name;
-                    tdi.Name = domainInfo.DnsDomainName;
-                    tdi.Sid = domainInfo.Sid;
-                    tdi.TrustType = TRUST_TYPE_UPLEVEL;
-                    tdi.TrustDirection = (int)direction;
+                    TRUSTED_DOMAIN_INFORMATION_EX tdi = new TRUSTED_DOMAIN_INFORMATION_EX()
+                    {
+                        FlatName = domainInfo.Name,
+                        Name = domainInfo.DnsDomainName,
+                        Sid = domainInfo.Sid,
+                        TrustType = TRUST_TYPE_UPLEVEL,
+                        TrustDirection = (int)direction
+                    };
                     if (isForest)
                     {
                         tdi.TrustAttributes = TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE;
@@ -554,12 +551,12 @@ namespace System.DirectoryServices.ActiveDirectory
 
                     // do impersonation and get policy handle
                     impersonated = Utils.Impersonate(sourceContext);
-                    policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    policyHandle = Utils.GetPolicyHandle(serverName);
 
-                    int result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle);
+                    uint result = UnsafeNativeMethods.LsaCreateTrustedDomainEx(policyHandle, tdi, AuthInfoEx, TRUSTED_SET_POSIX | TRUSTED_SET_AUTH, out domainHandle);
                     if (result != 0)
                     {
-                        result = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        result = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         if (result == ERROR_ALREADY_EXISTS)
                         {
                             if (isForest)
@@ -568,7 +565,7 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingDomainTrust, sourceName, targetName));
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)result, serverName);
                     }
                 }
                 finally
@@ -580,10 +577,10 @@ namespace System.DirectoryServices.ActiveDirectory
                         Marshal.FreeHGlobal(fileTime);
 
                     if (domainHandle != (IntPtr)0)
-                        UnsafeNativeMethods.LsaClose(domainHandle);
+                        global::Interop.Advapi32.LsaClose(domainHandle);
 
                     if (info != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(info);
+                        global::Interop.Advapi32.LsaFreeMemory(info);
 
                     if (unmanagedPassword != (IntPtr)0)
                         Marshal.FreeHGlobal(unmanagedPassword);
@@ -597,16 +594,14 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static string UpdateTrust(DirectoryContext context, string? sourceName, string? targetName, string password, bool isForest)
         {
-            PolicySafeHandle? handle = null;
+            SafeLsaPolicyHandle? handle = null;
             IntPtr buffer = (IntPtr)0;
-            LSA_UNICODE_STRING? trustedDomainName = null;
             IntPtr newBuffer = (IntPtr)0;
             bool impersonated = false;
             LSA_AUTH_INFORMATION? AuthData = null;
             IntPtr fileTime = (IntPtr)0;
             IntPtr unmanagedPassword = (IntPtr)0;
             IntPtr unmanagedAuthData = (IntPtr)0;
-            TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null;
             TrustDirection direction;
             IntPtr target = (IntPtr)0;
             string? serverName = null;
@@ -620,18 +615,18 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle first
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // get the trusted domain information
-                    int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
+                    uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
                     if (result != 0)
                     {
-                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                         if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                         {
@@ -641,7 +636,7 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                     }
 
                     // get the managed structre representation
@@ -674,7 +669,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
                     Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
 
-                    AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
+                    TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx = default;
                     if ((direction & TrustDirection.Inbound) != 0)
                     {
                         AuthInfoEx.IncomingAuthInfos = 1;
@@ -697,7 +692,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
                     if (result != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
                     }
 
                     return serverName;
@@ -711,7 +706,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         Marshal.FreeHGlobal(target);
 
                     if (buffer != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(buffer);
+                        global::Interop.Advapi32.LsaFreeMemory(buffer);
 
                     if (newBuffer != (IntPtr)0)
                         Marshal.FreeHGlobal(newBuffer);
@@ -731,16 +726,14 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static void UpdateTrustDirection(DirectoryContext context, string? sourceName, string? targetName, string password, bool isForest, TrustDirection newTrustDirection)
         {
-            PolicySafeHandle? handle = null;
+            SafeLsaPolicyHandle? handle = null;
             IntPtr buffer = (IntPtr)0;
-            LSA_UNICODE_STRING? trustedDomainName = null;
             IntPtr newBuffer = (IntPtr)0;
             bool impersonated = false;
             LSA_AUTH_INFORMATION? AuthData = null;
             IntPtr fileTime = (IntPtr)0;
             IntPtr unmanagedPassword = (IntPtr)0;
             IntPtr unmanagedAuthData = (IntPtr)0;
-            TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInfoEx = null;
             IntPtr target = (IntPtr)0;
             string? serverName = null;
 
@@ -753,18 +746,18 @@ namespace System.DirectoryServices.ActiveDirectory
                 try
                 {
                     // get the policy handle first
-                    handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                    handle = Utils.GetPolicyHandle(serverName);
 
                     // get the target name
-                    trustedDomainName = new LSA_UNICODE_STRING();
+                    global::Interop.UNICODE_STRING trustedDomainName;
                     target = Marshal.StringToHGlobalUni(targetName);
-                    UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
+                    UnsafeNativeMethods.RtlInitUnicodeString(out trustedDomainName, target);
 
                     // get the trusted domain information
-                    int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
+                    uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, ref buffer);
                     if (result != 0)
                     {
-                        int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                        uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                         // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                         if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                         {
@@ -774,7 +767,7 @@ namespace System.DirectoryServices.ActiveDirectory
                                 throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                         }
                         else
-                            throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                            throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
                     }
 
                     // get the managed structre representation
@@ -804,7 +797,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     unmanagedAuthData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_AUTH_INFORMATION)));
                     Marshal.StructureToPtr(AuthData, unmanagedAuthData, false);
 
-                    AuthInfoEx = new TRUSTED_DOMAIN_AUTH_INFORMATION();
+                    TRUSTED_DOMAIN_AUTH_INFORMATION AuthInfoEx;
                     if ((newTrustDirection & TrustDirection.Inbound) != 0)
                     {
                         AuthInfoEx.IncomingAuthInfos = 1;
@@ -842,7 +835,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     result = UnsafeNativeMethods.LsaSetTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainFullInformation, newBuffer);
                     if (result != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
                     }
 
                     return;
@@ -856,7 +849,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         Marshal.FreeHGlobal(target);
 
                     if (buffer != (IntPtr)0)
-                        UnsafeNativeMethods.LsaFreeMemory(buffer);
+                        global::Interop.Advapi32.LsaFreeMemory(buffer);
 
                     if (newBuffer != (IntPtr)0)
                         Marshal.FreeHGlobal(newBuffer);
@@ -874,15 +867,15 @@ namespace System.DirectoryServices.ActiveDirectory
             catch { throw; }
         }
 
-        private static void ValidateTrust(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName)
+        private static void ValidateTrust(SafeLsaPolicyHandle handle, global::Interop.UNICODE_STRING trustedDomainName, string? sourceName, string? targetName, bool isForest, int direction, string serverName)
         {
             IntPtr buffer = (IntPtr)0;
 
             // get trust information
-            int result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
+            uint result = UnsafeNativeMethods.LsaQueryTrustedDomainInfoByName(handle, trustedDomainName, TRUSTED_INFORMATION_CLASS.TrustedDomainInformationEx, ref buffer);
             if (result != 0)
             {
-                int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
+                uint win32Error = global::Interop.Advapi32.LsaNtStatusToWinError(result);
                 // 2 ERROR_FILE_NOT_FOUND <--> 0xc0000034 STATUS_OBJECT_NAME_NOT_FOUND
                 if (win32Error == STATUS_OBJECT_NAME_NOT_FOUND)
                 {
@@ -892,14 +885,14 @@ namespace System.DirectoryServices.ActiveDirectory
                         throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist, sourceName, targetName), typeof(TrustRelationshipInformation), null);
                 }
                 else
-                    throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
+                    throw ExceptionHelper.GetExceptionFromErrorCode((int)win32Error, serverName);
             }
 
             Debug.Assert(buffer != (IntPtr)0);
 
             try
             {
-                TRUSTED_DOMAIN_INFORMATION_EX domainInfo = new TRUSTED_DOMAIN_INFORMATION_EX();
+                TRUSTED_DOMAIN_INFORMATION_EX domainInfo = default;
                 Marshal.PtrToStructure(buffer, domainInfo);
 
                 // validate this is the trust that the user refers to
@@ -920,7 +913,7 @@ namespace System.DirectoryServices.ActiveDirectory
             finally
             {
                 if (buffer != (IntPtr)0)
-                    UnsafeNativeMethods.LsaFreeMemory(buffer);
+                    global::Interop.Advapi32.LsaFreeMemory(buffer);
             }
         }
 
@@ -982,7 +975,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
         private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, string? targetName, bool isForest)
         {
-            PolicySafeHandle? policyHandle = null;
+            SafeLsaPolicyHandle? policyHandle = null;
             IntPtr buffer = (IntPtr)0;
             bool impersonated = false;
             string? serverName = null;
@@ -995,7 +988,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     impersonated = Utils.Impersonate(targetContext);
                     try
                     {
-                        policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                        policyHandle = Utils.GetPolicyHandle(serverName);
                     }
                     catch (ActiveDirectoryOperationException)
                     {
@@ -1007,7 +1000,7 @@ namespace System.DirectoryServices.ActiveDirectory
                         // try anonymous
                         Utils.ImpersonateAnonymous();
                         impersonated = true;
-                        policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                        policyHandle = Utils.GetPolicyHandle(serverName);
                     }
                     catch (UnauthorizedAccessException)
                     {
@@ -1019,13 +1012,13 @@ namespace System.DirectoryServices.ActiveDirectory
                         // try anonymous
                         Utils.ImpersonateAnonymous();
                         impersonated = true;
-                        policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
+                        policyHandle = Utils.GetPolicyHandle(serverName);
                     }
 
-                    int result = UnsafeNativeMethods.LsaQueryInformationPolicy(policyHandle, policyDnsDomainInformation, out buffer);
+                    uint result = global::Interop.Advapi32.LsaQueryInformationPolicy(policyHandle.DangerousGetHandle(), policyDnsDomainInformation, ref buffer);
                     if (result != 0)
                     {
-                        throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
+                        throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
                     }
 
                     return buffer;
index 3596b1a..84a9ab0 100644 (file)
@@ -25,8 +25,8 @@
 //}
 
 using System.Runtime.InteropServices;
-using System.Security;
-using System.Text;
+
+using Microsoft.Win32.SafeHandles;
 
 namespace System.DirectoryServices.ActiveDirectory
 {
@@ -412,7 +412,7 @@ namespace System.DirectoryServices.ActiveDirectory
         [FieldOffset(8)]
         public LARGE_INTEGER Time = null!;
         [FieldOffset(16)]
-        public LSA_UNICODE_STRING TopLevelName = null!;
+        public global::Interop.UNICODE_STRING TopLevelName;
         [FieldOffset(16)]
         public LSA_FOREST_TRUST_BINARY_DATA Data = null!;
         [FieldOffset(16)]
@@ -433,14 +433,6 @@ namespace System.DirectoryServices.ActiveDirectory
     }
 
     [StructLayout(LayoutKind.Sequential)]
-    internal sealed class LSA_UNICODE_STRING
-    {
-        public short Length;
-        public short MaximumLength;
-        public IntPtr Buffer;
-    }
-
-    [StructLayout(LayoutKind.Sequential)]
     internal sealed class LSA_FOREST_TRUST_DOMAIN_INFO
     {
         public IntPtr sid;
@@ -460,31 +452,10 @@ namespace System.DirectoryServices.ActiveDirectory
     }
 
     [StructLayout(LayoutKind.Sequential)]
-    internal sealed class LSA_OBJECT_ATTRIBUTES
-    {
-        internal int Length;
-        private readonly IntPtr _rootDirectory;
-        private readonly IntPtr _objectName;
-        internal int Attributes;
-        private readonly IntPtr _securityDescriptor;
-        private readonly IntPtr _securityQualityOfService;
-
-        public LSA_OBJECT_ATTRIBUTES()
-        {
-            Length = 0;
-            _rootDirectory = (IntPtr)0;
-            _objectName = (IntPtr)0;
-            Attributes = 0;
-            _securityDescriptor = (IntPtr)0;
-            _securityQualityOfService = (IntPtr)0;
-        }
-    }
-
-    [StructLayout(LayoutKind.Sequential)]
-    internal sealed class TRUSTED_DOMAIN_INFORMATION_EX
+    internal struct TRUSTED_DOMAIN_INFORMATION_EX
     {
-        public LSA_UNICODE_STRING? Name;
-        public LSA_UNICODE_STRING? FlatName;
+        public global::Interop.UNICODE_STRING Name;
+        public global::Interop.UNICODE_STRING FlatName;
         public IntPtr Sid;
         public int TrustDirection;
         public int TrustType;
@@ -504,7 +475,7 @@ namespace System.DirectoryServices.ActiveDirectory
         public int Index;
         public ForestTrustCollisionType Type;
         public int Flags;
-        public LSA_UNICODE_STRING Name = null!;
+        public global::Interop.UNICODE_STRING Name;
     }
 
     [StructLayout(LayoutKind.Sequential)]
@@ -526,7 +497,7 @@ namespace System.DirectoryServices.ActiveDirectory
     }
 
     [StructLayout(LayoutKind.Sequential)]
-    internal sealed class TRUSTED_DOMAIN_AUTH_INFORMATION
+    internal struct TRUSTED_DOMAIN_AUTH_INFORMATION
     {
         public int IncomingAuthInfos;
         public IntPtr IncomingAuthenticationInformation;
@@ -548,9 +519,9 @@ namespace System.DirectoryServices.ActiveDirectory
     [StructLayout(LayoutKind.Sequential)]
     internal sealed class POLICY_DNS_DOMAIN_INFO
     {
-        public LSA_UNICODE_STRING? Name;
-        public LSA_UNICODE_STRING? DnsDomainName;
-        public LSA_UNICODE_STRING? DnsForestName;
+        public global::Interop.UNICODE_STRING Name;
+        public global::Interop.UNICODE_STRING DnsDomainName;
+        public global::Interop.UNICODE_STRING DnsForestName;
         public Guid DomainGuid;
         public IntPtr Sid;
     }
@@ -564,7 +535,7 @@ namespace System.DirectoryServices.ActiveDirectory
     [StructLayout(LayoutKind.Sequential)]
     internal sealed class TRUSTED_DOMAIN_FULL_INFORMATION
     {
-        public TRUSTED_DOMAIN_INFORMATION_EX? Information;
+        public TRUSTED_DOMAIN_INFORMATION_EX Information;
         internal TRUSTED_POSIX_OFFSET_INFO? PosixOffset;
         public TRUSTED_DOMAIN_AUTH_INFORMATION? AuthInformation;
     }
@@ -595,37 +566,13 @@ namespace System.DirectoryServices.ActiveDirectory
     }
 
     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-    internal sealed class SID_AND_ATTR
-    {
-        public IntPtr pSid = IntPtr.Zero;
-        public int attrs;
-    }
-
-    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-    internal sealed class TOKEN_USER
-    {
-        public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR();
-    }
-
-    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-    internal sealed class SID_IDENTIFIER_AUTHORITY
-    {
-        public byte b1;
-        public byte b2;
-        public byte b3;
-        public byte b4;
-        public byte b5;
-        public byte b6;
-    }
-
-    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
-    internal sealed class POLICY_ACCOUNT_DOMAIN_INFO
+    internal struct POLICY_ACCOUNT_DOMAIN_INFO
     {
-        public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
-        public IntPtr domainSid = IntPtr.Zero;
+        public global::Interop.UNICODE_STRING DomainName;
+        public IntPtr DomainSid;
     }
 
-    internal static class UnsafeNativeMethods
+    internal static partial class UnsafeNativeMethods
     {
         public delegate int DsReplicaConsistencyCheck([In]IntPtr handle, int taskID, int flags);
 
@@ -639,108 +586,57 @@ namespace System.DirectoryServices.ActiveDirectory
 
         public delegate int DsReplicaSyncAllW(IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string partition, int flags, SyncReplicaFromAllServersCallback callback, IntPtr data, ref IntPtr error);
 
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "LocalFree")]
-        public static extern int LocalFree(IntPtr mem);
-
-        [DllImport(global::Interop.Libraries.Activeds, EntryPoint = "ADsEncodeBinaryData", CharSet = CharSet.Unicode)]
-        public static extern int ADsEncodeBinaryData(byte[] data, int length, ref IntPtr result);
+        [GeneratedDllImport(global::Interop.Libraries.Activeds, EntryPoint = "ADsEncodeBinaryData", CharSet = CharSet.Unicode)]
+        public static partial int ADsEncodeBinaryData(byte[] data, int length, ref IntPtr result);
 
-        [DllImport(global::Interop.Libraries.Activeds, EntryPoint = "FreeADsMem")]
-        public static extern bool FreeADsMem(IntPtr pVoid);
+        [GeneratedDllImport(global::Interop.Libraries.Activeds, EntryPoint = "FreeADsMem")]
+        public static partial bool FreeADsMem(IntPtr pVoid);
 
-        [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetSiteNameW", CharSet = CharSet.Unicode)]
-        public static extern int DsGetSiteName(string? dcName, ref IntPtr ptr);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsGetSiteNameW", CharSet = CharSet.Unicode)]
+        public static partial int DsGetSiteName(string? dcName, ref IntPtr ptr);
 
         public delegate int DsListDomainsInSiteW(IntPtr handle, [MarshalAs(UnmanagedType.LPWStr)] string site, ref IntPtr info);
 
         public delegate void DsFreeNameResultW(IntPtr result);
 
-        [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsEnumerateDomainTrustsW", CharSet = CharSet.Unicode)]
-        public static extern int DsEnumerateDomainTrustsW(string serverName, int flags, out IntPtr domains, out int count);
-
-        [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")]
-        public static extern int NetApiBufferFree(IntPtr buffer);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern int LogonUserW(string? lpszUsername, string? lpszDomain, string? lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateLoggedOnUser", SetLastError = true)]
-        public static extern int ImpersonateLoggedOnUser(IntPtr hToken);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "RevertToSelf", SetLastError = true)]
-        public static extern int RevertToSelf();
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern int ConvertSidToStringSidW(IntPtr pSid, ref IntPtr stringSid);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern int ConvertStringSidToSidW(IntPtr stringSid, ref IntPtr pSid);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsEnumerateDomainTrustsW", CharSet = CharSet.Unicode)]
+        public static partial int DsEnumerateDomainTrustsW(string serverName, int flags, out IntPtr domains, out int count);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")]
-        public static extern int LsaSetForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "NetApiBufferFree")]
+        public static partial int NetApiBufferFree(IntPtr buffer);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenPolicy")]
-        public static extern int LsaOpenPolicy(LSA_UNICODE_STRING target, LSA_OBJECT_ATTRIBUTES objectAttributes, int access, out IntPtr handle);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetForestTrustInformation")]
+        public static partial uint LsaSetForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, IntPtr forestTrustInfo, int checkOnly, out IntPtr collisionInfo);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaClose")]
-        public static extern int LsaClose(IntPtr handle);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")]
+        public static partial uint LsaQueryForestTrustInformation(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING target, ref IntPtr ForestTrustInfo);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryForestTrustInformation")]
-        public static extern int LsaQueryForestTrustInformation(PolicySafeHandle handle, LSA_UNICODE_STRING target, ref IntPtr ForestTrustInfo);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")]
+        public static partial uint LsaQueryTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryTrustedDomainInfoByName")]
-        public static extern int LsaQueryTrustedDomainInfoByName(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, ref IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")]
+        public static partial uint LsaSetTrustedDomainInfoByName(SafeLsaPolicyHandle handle, in global::Interop.UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaNtStatusToWinError")]
-        public static extern int LsaNtStatusToWinError(int status);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")]
+        public static partial uint LsaDeleteTrustedDomain(SafeLsaPolicyHandle handle, IntPtr pSid);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaFreeMemory")]
-        public static extern int LsaFreeMemory(IntPtr ptr);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "I_NetLogonControl2", CharSet = CharSet.Unicode)]
+        public static partial int I_NetLogonControl2(string serverName, int FunctionCode, int QueryLevel, IntPtr data, out IntPtr buffer);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaSetTrustedDomainInfoByName")]
-        public static extern int LsaSetTrustedDomainInfoByName(PolicySafeHandle handle, LSA_UNICODE_STRING trustedDomain, TRUSTED_INFORMATION_CLASS infoClass, IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")]
+        public static partial void GetSystemTimeAsFileTime(IntPtr fileTime);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaOpenTrustedDomainByName")]
-        public static extern int LsaOpenTrustedDomainByName(PolicySafeHandle policyHandle, LSA_UNICODE_STRING trustedDomain, int access, ref IntPtr trustedDomainHandle);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaCreateTrustedDomainEx")]
+        public static partial uint LsaCreateTrustedDomainEx(SafeLsaPolicyHandle handle, in TRUSTED_DOMAIN_INFORMATION_EX domainEx, in TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle);
 
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaDeleteTrustedDomain")]
-        public static extern int LsaDeleteTrustedDomain(PolicySafeHandle handle, IntPtr pSid);
+        [GeneratedDllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)]
+        public static partial IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID);
 
-        [DllImport(global::Interop.Libraries.Netapi32, EntryPoint = "I_NetLogonControl2", CharSet = CharSet.Unicode)]
-        public static extern int I_NetLogonControl2(string serverName, int FunctionCode, int QueryLevel, IntPtr data, out IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)]
+        public static partial int ImpersonateAnonymousToken(IntPtr token);
 
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetSystemTimeAsFileTime")]
-        public static extern void GetSystemTimeAsFileTime(IntPtr fileTime);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaQueryInformationPolicy")]
-        public static extern int LsaQueryInformationPolicy(PolicySafeHandle handle, int infoClass, out IntPtr buffer);
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "LsaCreateTrustedDomainEx")]
-        public static extern int LsaCreateTrustedDomainEx(PolicySafeHandle handle, TRUSTED_DOMAIN_INFORMATION_EX domainEx, TRUSTED_DOMAIN_AUTH_INFORMATION authInfo, int classInfo, out IntPtr domainHandle);
-
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "OpenThread", SetLastError = true)]
-        public static extern IntPtr OpenThread(uint desiredAccess, bool inheirted, int threadID);
-
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetCurrentThreadId")]
-        public static extern int GetCurrentThreadId();
-
-        [DllImport(global::Interop.Libraries.Advapi32, EntryPoint = "ImpersonateAnonymousToken", SetLastError = true)]
-        public static extern int ImpersonateAnonymousToken(IntPtr token);
-
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "CloseHandle")]
-        public static extern int CloseHandle(IntPtr handle);
-
-        [DllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")]
-        public static extern int RtlInitUnicodeString(LSA_UNICODE_STRING result, IntPtr s);
-
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "LoadLibraryW", CharSet = CharSet.Unicode, SetLastError = true)]
-        public static extern IntPtr LoadLibrary(string name);
-
-        [DllImport(global::Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)]
-        public static extern uint FreeLibrary(IntPtr libName);
-
-        [DllImport(global::Interop.Libraries.Kernel32, EntryPoint = "GetProcAddress", SetLastError = true, BestFitMapping = false)]
-        public static extern IntPtr GetProcAddress(LoadLibrarySafeHandle hModule, string entryPoint);
+        [GeneratedDllImport(global::Interop.Libraries.NtDll, EntryPoint = "RtlInitUnicodeString")]
+        public static partial int RtlInitUnicodeString(out global::Interop.UNICODE_STRING result, IntPtr s);
 
         /*
         DWORD DsRoleGetPrimaryDomainInformation(
@@ -749,99 +645,25 @@ namespace System.DirectoryServices.ActiveDirectory
           PBYTE* Buffer
         ); */
 
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
-        public static extern int DsRoleGetPrimaryDomainInformation(
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
+        public static partial int DsRoleGetPrimaryDomainInformation(
             [MarshalAs(UnmanagedType.LPTStr)] string lpServer,
-            [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
+            DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
             out IntPtr Buffer);
 
-        [DllImport(global::Interop.Libraries.Netapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
-        public static extern int DsRoleGetPrimaryDomainInformation(
-            [In] IntPtr lpServer,
-            [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
+        public static partial int DsRoleGetPrimaryDomainInformation(
+            IntPtr lpServer,
+            DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
             out IntPtr Buffer);
 
-        [DllImport(global::Interop.Libraries.Advapi32)]
-        public static extern int GetLengthSid(IntPtr sid);
-
-        [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true)]
-        public static extern bool IsValidSid(IntPtr sid);
-
-        [DllImport(global::Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid);
-
-        [DllImport(global::Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index);
-
-        [DllImport(global::Interop.Libraries.Advapi32)]
-        public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
-
-        [DllImport(global::Interop.Libraries.Advapi32)]
-        public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
-
-        [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true)]
-        public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
-
-        [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)]
-        public static extern bool OpenThreadToken(
-                                        IntPtr threadHandle,
-                                        int desiredAccess,
-                                        bool openAsSelf,
-                                        ref IntPtr tokenHandle
-                                        );
-
-        [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)]
-        public static extern bool OpenProcessToken(
-                                        IntPtr processHandle,
-                                        int desiredAccess,
-                                        ref IntPtr tokenHandle
-                                        );
-
-        [DllImport(global::Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)]
-        public static extern IntPtr GetCurrentThread();
-
-        [DllImport(global::Interop.Libraries.Kernel32, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)]
-        public static extern IntPtr GetCurrentProcess();
-
-        [DllImport(global::Interop.Libraries.Advapi32, SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)]
-        public static extern bool GetTokenInformation(
-                                        IntPtr tokenHandle,
-                                        int tokenInformationClass,
-                                        IntPtr buffer,
-                                        int bufferSize,
-                                        ref int returnLength
-                                        );
-
-        [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)]
-        public static extern int LsaOpenPolicy(
-                                        IntPtr lsaUnicodeString,
-                                        IntPtr lsaObjectAttributes,
-                                        int desiredAccess,
-                                        ref IntPtr policyHandle);
-
-        [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)]
-        public static extern int LsaQueryInformationPolicy(
-                                        IntPtr policyHandle,
-                                        int policyInformationClass,
-                                        ref IntPtr buffer
-                                        );
-
-        [DllImport(global::Interop.Libraries.Advapi32, CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)]
-        public static extern int LsaLookupSids(
-                                        IntPtr policyHandle,
-                                        int count,
-                                        IntPtr[] sids,
-                                        out IntPtr referencedDomains,
-                                        out IntPtr names
-                                        );
-
         /*
         void DsRoleFreeMemory(
           PVOID Buffer
         );
         */
-        [DllImport(global::Interop.Libraries.Netapi32)]
-        public static extern int DsRoleFreeMemory(
-            [In] IntPtr buffer);
+        [GeneratedDllImport(global::Interop.Libraries.Netapi32)]
+        public static partial int DsRoleFreeMemory(
+            IntPtr buffer);
     }
 }
index 69cd0a8..6898e76 100644 (file)
@@ -7,7 +7,8 @@ using System.Collections;
 using System.Security.Principal;
 using System.Runtime.InteropServices;
 using System.Diagnostics;
-using System.Globalization;
+
+using Microsoft.Win32.SafeHandles;
 
 namespace System.DirectoryServices.ActiveDirectory
 {
@@ -42,7 +43,7 @@ namespace System.DirectoryServices.ActiveDirectory
     {
         private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
         private const int LOGON32_PROVIDER_WINNT50 = 3;
-        private const int POLICY_VIEW_LOCAL_INFORMATION = 0x00000001;
+
         private const uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
         private const uint SYNCHRONIZE = 0x00100000;
         private const uint THREAD_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF;
@@ -107,7 +108,7 @@ namespace System.DirectoryServices.ActiveDirectory
             Debug.Assert(distinguishedName != null);
 
             // call DsCrackNamesW
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -163,7 +164,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     if (results != IntPtr.Zero)
                     {
                         // call DsFreeNameResultW
-                        functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+                        functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
                         if (functionPtr == (IntPtr)0)
                         {
                             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -195,7 +196,7 @@ namespace System.DirectoryServices.ActiveDirectory
             Debug.Assert(dnsName != null);
 
             // call DsCrackNamesW
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsCrackNamesW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -231,7 +232,7 @@ namespace System.DirectoryServices.ActiveDirectory
                     if (results != IntPtr.Zero)
                     {
                         // call DsFreeNameResultW
-                        functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
+                        functionPtr = global::Interop.Kernel32.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
                         if (functionPtr == (IntPtr)0)
                         {
                             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -606,7 +607,7 @@ namespace System.DirectoryServices.ActiveDirectory
             }
         }
 
-        internal static IntPtr GetAuthIdentity(DirectoryContext context, LoadLibrarySafeHandle libHandle)
+        internal static IntPtr GetAuthIdentity(DirectoryContext context, SafeLibraryHandle libHandle)
         {
             IntPtr authIdentity;
             int result = 0;
@@ -619,7 +620,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
             // create the credentials
             // call DsMakePasswordCredentialsW
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsMakePasswordCredentialsW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsMakePasswordCredentialsW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -638,13 +639,13 @@ namespace System.DirectoryServices.ActiveDirectory
             return authIdentity;
         }
 
-        internal static void FreeAuthIdentity(IntPtr authIdentity, LoadLibrarySafeHandle libHandle)
+        internal static void FreeAuthIdentity(IntPtr authIdentity, SafeLibraryHandle libHandle)
         {
             // free the credentials object
             if (authIdentity != IntPtr.Zero)
             {
                 // call DsMakePasswordCredentialsW
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsFreePasswordCredentials");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsFreePasswordCredentials");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -654,14 +655,14 @@ namespace System.DirectoryServices.ActiveDirectory
             }
         }
 
-        internal static IntPtr GetDSHandle(string? domainControllerName, string? domainName, IntPtr authIdentity, LoadLibrarySafeHandle libHandle)
+        internal static IntPtr GetDSHandle(string? domainControllerName, string? domainName, IntPtr authIdentity, SafeLibraryHandle libHandle)
         {
             int result = 0;
             IntPtr handle;
 
             // call DsBindWithCred
             Debug.Assert((domainControllerName != null && domainName == null) || (domainName != null && domainControllerName == null));
-            IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsBindWithCredW");
+            IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsBindWithCredW");
             if (functionPtr == (IntPtr)0)
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -676,13 +677,13 @@ namespace System.DirectoryServices.ActiveDirectory
             return handle;
         }
 
-        internal static void FreeDSHandle(IntPtr dsHandle, LoadLibrarySafeHandle libHandle)
+        internal static void FreeDSHandle(IntPtr dsHandle, SafeLibraryHandle libHandle)
         {
             // DsUnbind
             if (dsHandle != IntPtr.Zero)
             {
                 // call DsUnbind
-                IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(libHandle, "DsUnBindW");
+                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsUnBindW");
                 if (functionPtr == (IntPtr)0)
                 {
                     throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
@@ -928,14 +929,14 @@ namespace System.DirectoryServices.ActiveDirectory
 
             Utils.GetDomainAndUsername(context, out userName, out domainName);
 
-            int result = UnsafeNativeMethods.LogonUserW(userName, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken);
+            int result = global::Interop.Advapi32.LogonUser(userName!, domainName, context.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref hToken);
             // check the result
             if (result == 0)
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
 
             try
             {
-                result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken);
+                result = global::Interop.Advapi32.ImpersonateLoggedOnUser(hToken);
                 if (result == 0)
                 {
                     result = Marshal.GetLastWin32Error();
@@ -945,7 +946,7 @@ namespace System.DirectoryServices.ActiveDirectory
             finally
             {
                 if (hToken != (IntPtr)0)
-                    UnsafeNativeMethods.CloseHandle(hToken);
+                    global::Interop.Kernel32.CloseHandle(hToken);
             }
 
             return true;
@@ -953,8 +954,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static void ImpersonateAnonymous()
         {
-            IntPtr hThread = (IntPtr)0;
-            hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, UnsafeNativeMethods.GetCurrentThreadId());
+            IntPtr hThread = UnsafeNativeMethods.OpenThread(THREAD_ALL_ACCESS, false, global::Interop.Kernel32.GetCurrentThreadId());
             if (hThread == (IntPtr)0)
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
 
@@ -967,15 +967,13 @@ namespace System.DirectoryServices.ActiveDirectory
             finally
             {
                 if (hThread != (IntPtr)0)
-                    UnsafeNativeMethods.CloseHandle(hThread);
+                    global::Interop.Kernel32.CloseHandle(hThread);
             }
         }
 
         internal static void Revert()
         {
-            int error = UnsafeNativeMethods.RevertToSelf();
-            // function failed
-            if (error == 0)
+            if (!global::Interop.Advapi32.RevertToSelf())
             {
                 throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
             }
@@ -1038,34 +1036,18 @@ namespace System.DirectoryServices.ActiveDirectory
             return serverName;
         }
 
-        internal static IntPtr GetPolicyHandle(string serverName)
+        internal static SafeLsaPolicyHandle GetPolicyHandle(string serverName)
         {
-            IntPtr handle = (IntPtr)0;
-            LSA_UNICODE_STRING systemName;
-            LSA_OBJECT_ATTRIBUTES objectAttribute = new LSA_OBJECT_ATTRIBUTES();
-            IntPtr target = (IntPtr)0;
-
-            int mask = POLICY_VIEW_LOCAL_INFORMATION;
-
-            systemName = new LSA_UNICODE_STRING();
-            target = Marshal.StringToHGlobalUni(serverName);
-            UnsafeNativeMethods.RtlInitUnicodeString(systemName, target);
-
-            try
-            {
-                int result = UnsafeNativeMethods.LsaOpenPolicy(systemName, objectAttribute, mask, out handle);
-                if (result != 0)
-                {
-                    throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName);
-                }
+            SafeLsaPolicyHandle handle;
+            global::Interop.OBJECT_ATTRIBUTES objectAttribute = default;
 
-                return handle;
-            }
-            finally
+            uint result = global::Interop.Advapi32.LsaOpenPolicy(serverName, ref objectAttribute, (int)global::Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION, out handle);
+            if (result != 0)
             {
-                if (target != (IntPtr)0)
-                    Marshal.FreeHGlobal(target);
+                throw ExceptionHelper.GetExceptionFromErrorCode((int)global::Interop.Advapi32.LsaNtStatusToWinError(result), serverName);
             }
+
+            return handle;
         }
 
         //
@@ -2029,7 +2011,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
                     // Does the user SID have the same domain as the machine SID?
                     bool sameDomain = false;
-                    bool success = UnsafeNativeMethods.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain);
+                    bool success = global::Interop.Advapi32.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain);
 
                     // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs
                     Debug.Assert(success == true);
@@ -2056,7 +2038,7 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static IntPtr GetCurrentUserSid()
         {
-            IntPtr pTokenHandle = IntPtr.Zero;
+            SafeTokenHandle? tokenHandle = null;
             IntPtr pBuffer = IntPtr.Zero;
 
             try
@@ -2067,22 +2049,22 @@ namespace System.DirectoryServices.ActiveDirectory
                 int error = 0;
 
                 // Get the current thread's token
-                if (!UnsafeNativeMethods.OpenThreadToken(
-                                UnsafeNativeMethods.GetCurrentThread(),
-                                0x8, // TOKEN_QUERY
+                if (!global::Interop.Advapi32.OpenThreadToken(
+                                global::Interop.Kernel32.GetCurrentThread(),
+                                TokenAccessLevels.Query, // TOKEN_QUERY
                                 true,
-                                ref pTokenHandle
+                                out tokenHandle
                                 ))
                 {
                     if ((error = Marshal.GetLastWin32Error()) == 1008) // ERROR_NO_TOKEN
                     {
-                        Debug.Assert(pTokenHandle == IntPtr.Zero);
+                        Debug.Assert(tokenHandle.IsInvalid);
 
                         // Current thread doesn't have a token, try the process
-                        if (!UnsafeNativeMethods.OpenProcessToken(
-                                        UnsafeNativeMethods.GetCurrentProcess(),
-                                        0x8, // TOKEN_QUERY
-                                        ref pTokenHandle
+                        if (!global::Interop.Advapi32.OpenProcessToken(
+                                        global::Interop.Kernel32.GetCurrentProcess(),
+                                        (int)TokenAccessLevels.Query,
+                                        out tokenHandle
                                         ))
                         {
                             int lastError = Marshal.GetLastWin32Error();
@@ -2095,18 +2077,18 @@ namespace System.DirectoryServices.ActiveDirectory
                     }
                 }
 
-                Debug.Assert(pTokenHandle != IntPtr.Zero);
+                Debug.Assert(!tokenHandle.IsInvalid);
 
-                int neededBufferSize = 0;
+                uint neededBufferSize = 0;
 
                 // Retrieve the user info from the current thread's token
                 // First, determine how big a buffer we need.
-                bool success = UnsafeNativeMethods.GetTokenInformation(
-                                        pTokenHandle,
-                                        1,   // TokenUser
+                bool success = global::Interop.Advapi32.GetTokenInformation(
+                                        tokenHandle.DangerousGetHandle(),
+                                        (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
                                         IntPtr.Zero,
                                         0,
-                                        ref neededBufferSize);
+                                        out neededBufferSize);
 
                 int getTokenInfoError = 0;
                 if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER
@@ -2117,15 +2099,15 @@ namespace System.DirectoryServices.ActiveDirectory
 
                 // Allocate the necessary buffer.
                 Debug.Assert(neededBufferSize > 0);
-                pBuffer = Marshal.AllocHGlobal(neededBufferSize);
+                pBuffer = Marshal.AllocHGlobal((int)neededBufferSize);
 
                 // Load the user info into the buffer
-                success = UnsafeNativeMethods.GetTokenInformation(
-                                        pTokenHandle,
-                                        1,   // TokenUser
+                success = global::Interop.Advapi32.GetTokenInformation(
+                                        tokenHandle.DangerousGetHandle(),
+                                        (uint)global::Interop.Advapi32.TOKEN_INFORMATION_CLASS.TokenUser,
                                         pBuffer,
                                         neededBufferSize,
-                                        ref neededBufferSize);
+                                        out neededBufferSize);
 
                 if (!success)
                 {
@@ -2135,15 +2117,15 @@ namespace System.DirectoryServices.ActiveDirectory
                 }
 
                 // Retrieve the user's SID from the user info
-                TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(TOKEN_USER))!;
-                IntPtr pUserSid = tokenUser.sidAndAttributes.pSid;   // this is a reference into the NATIVE memory (into pBuffer)
+                global::Interop.TOKEN_USER tokenUser = (global::Interop.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(global::Interop.TOKEN_USER))!;
+                IntPtr pUserSid = tokenUser.sidAndAttributes.Sid;   // this is a reference into the NATIVE memory (into pBuffer)
 
-                Debug.Assert(UnsafeNativeMethods.IsValidSid(pUserSid));
+                Debug.Assert(global::Interop.Advapi32.IsValidSid(pUserSid));
 
                 // Now we make a copy of the SID to return
-                int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid);
+                int userSidLength = global::Interop.Advapi32.GetLengthSid(pUserSid);
                 IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength);
-                success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
+                success = global::Interop.Advapi32.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
                 if (!success)
                 {
                     int lastError = Marshal.GetLastWin32Error();
@@ -2155,8 +2137,8 @@ namespace System.DirectoryServices.ActiveDirectory
             }
             finally
             {
-                if (pTokenHandle != IntPtr.Zero)
-                    UnsafeNativeMethods.CloseHandle(pTokenHandle);
+                if (tokenHandle != null)
+                    tokenHandle.Dispose();
 
                 if (pBuffer != IntPtr.Zero)
                     Marshal.FreeHGlobal(pBuffer);
@@ -2165,48 +2147,44 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static IntPtr GetMachineDomainSid()
         {
-            IntPtr pPolicyHandle = IntPtr.Zero;
+            SafeLsaPolicyHandle? policyHandle = null;
             IntPtr pBuffer = IntPtr.Zero;
-            IntPtr pOA = IntPtr.Zero;
 
             try
             {
-                LSA_OBJECT_ATTRIBUTES oa = new LSA_OBJECT_ATTRIBUTES();
-
-                pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES)));
-                Marshal.StructureToPtr(oa, pOA, false);
-                int err = UnsafeNativeMethods.LsaOpenPolicy(
-                                IntPtr.Zero,
-                                pOA,
-                                1,          // POLICY_VIEW_LOCAL_INFORMATION
-                                ref pPolicyHandle);
+                global::Interop.OBJECT_ATTRIBUTES oa = default;
+                uint err = global::Interop.Advapi32.LsaOpenPolicy(
+                                SystemName: null,
+                                ref oa,
+                                (int)global::Interop.Advapi32.PolicyRights.POLICY_VIEW_LOCAL_INFORMATION,
+                                out policyHandle);
 
                 if (err != 0)
                 {
-                    throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err)));
+                    throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, global::Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
-                Debug.Assert(pPolicyHandle != IntPtr.Zero);
-                err = UnsafeNativeMethods.LsaQueryInformationPolicy(
-                                pPolicyHandle,
+                Debug.Assert(!policyHandle.IsInvalid);
+                err = global::Interop.Advapi32.LsaQueryInformationPolicy(
+                                policyHandle.DangerousGetHandle(),
                                 5,              // PolicyAccountDomainInformation
                                 ref pBuffer);
 
                 if (err != 0)
                 {
-                    throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err)));
+                    throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, global::Interop.Advapi32.LsaNtStatusToWinError(err)));
                 }
 
                 Debug.Assert(pBuffer != IntPtr.Zero);
                 POLICY_ACCOUNT_DOMAIN_INFO info = (POLICY_ACCOUNT_DOMAIN_INFO)
                                     Marshal.PtrToStructure(pBuffer, typeof(POLICY_ACCOUNT_DOMAIN_INFO))!;
 
-                Debug.Assert(UnsafeNativeMethods.IsValidSid(info.domainSid));
+                Debug.Assert(global::Interop.Advapi32.IsValidSid(info.DomainSid));
 
                 // Now we make a copy of the SID to return
-                int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid);
+                int sidLength = global::Interop.Advapi32.GetLengthSid(info.DomainSid);
                 IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength);
-                bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid);
+                bool success = global::Interop.Advapi32.CopySid(sidLength, pCopyOfSid, info.DomainSid);
                 if (!success)
                 {
                     int lastError = Marshal.GetLastWin32Error();
@@ -2218,14 +2196,11 @@ namespace System.DirectoryServices.ActiveDirectory
             }
             finally
             {
-                if (pPolicyHandle != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaClose(pPolicyHandle);
+                if (policyHandle != null)
+                    policyHandle.Dispose();
 
                 if (pBuffer != IntPtr.Zero)
-                    UnsafeNativeMethods.LsaFreeMemory(pBuffer);
-
-                if (pOA != IntPtr.Zero)
-                    Marshal.FreeHGlobal(pOA);
+                    global::Interop.Advapi32.LsaFreeMemory(pBuffer);
             }
         }
 
@@ -2264,15 +2239,15 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static SidType ClassifySID(IntPtr pSid)
         {
-            Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid));
+            Debug.Assert(global::Interop.Advapi32.IsValidSid(pSid));
 
             // Get the issuing authority and the first RID
-            IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid);
+            IntPtr pIdentAuth = global::Interop.Advapi32.GetSidIdentifierAuthority(pSid);
 
-            SID_IDENTIFIER_AUTHORITY identAuth =
-                (SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(SID_IDENTIFIER_AUTHORITY))!;
+            global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY identAuth =
+                (global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(global::Interop.Advapi32.SID_IDENTIFIER_AUTHORITY))!;
 
-            IntPtr pRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, 0);
+            IntPtr pRid = global::Interop.Advapi32.GetSidSubAuthority(pSid, 0);
             int rid = Marshal.ReadInt32(pRid);
 
             // These bit signify that the sid was issued by ADAM.  If so then it can't be a fake sid.
@@ -2303,9 +2278,9 @@ namespace System.DirectoryServices.ActiveDirectory
 
         internal static int GetLastRidFromSid(IntPtr pSid)
         {
-            IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid);
+            IntPtr pRidCount = global::Interop.Advapi32.GetSidSubAuthorityCount(pSid);
             int ridCount = Marshal.ReadByte(pRidCount);
-            IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1);
+            IntPtr pLastRid = global::Interop.Advapi32.GetSidSubAuthority(pSid, ridCount - 1);
             int lastRid = Marshal.ReadInt32(pLastRid);
 
             return lastRid;