I am running a c# app (.Net v3.5 compiled as x64) registered as a COM dll on Windows Server 2008 R2.
The dll appears to have a memory management issue because I am getting the “Attempted to read or write protected memory” exception (see below for details). The program does have some unmanaged code (see below).
The problem is that the program isn’t throwing the exception when the unmanaged code is executing. It throws the exception when it attempts to perform an LDAP bind. I checked the logs on the LDAP server, and the bind is failing before any events are logged there.
Also, the program works fine in running on an ESX VM. The error happens when it runs on physical hardware.
I am at a loss as to how to debug this as I can’t easily debug interactively. Any suggestions would be greatly appreciated.
EXCEPTION
Message: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
InnerException:
Source: System.DirectoryServices.Protocols
StackTrace: at System.DirectoryServices.Protocols.Wldap32.ldap_connect(IntPtr ldapHandle, LDAP_TIMEVAL timeout)
at System.DirectoryServices.Protocols.LdapConnection.Connect()
at System.DirectoryServices.Protocols.LdapConnection.BindHelper(NetworkCredential newCredential, Boolean needSetCredential)
at LDAPDatabase.openLDAPConnection()
at LDAPDatabase.DeleteAttributeValue(String attributeName, String distinguisedName, Object[] values)
TargetSite: Int32 ldap_connect(IntPtr, System.DirectoryServices.Protocols.LDAP_TIMEVAL)
Data: System.Collections.ListDictionaryInternal
UNMANAGED CODE
int pointerSize = int.Parse(applicationKey.GetValue(Support.RegistryKeys.CertificatePointerSize).ToString());
IntPtr objectPointer = Marshal.AllocHGlobal(pointerSize);
module.GetCertificateProperty(Support.CertificateProperties.RawCertificate, (int)Support.PropertyType.PROPTYPE_BINARY, objectPointer);
IntPtr bstrPtr = Marshal.ReadIntPtr(objectPointer, 8);
int bstrLen = Marshal.ReadInt32(bstrPtr, -4);
byte[] certBytes = new byte[bstrLen];
Marshal.Copy(bstrPtr, certBytes, 0, bstrLen);
cert = new X509Certificate(certBytes);
Marshal.FreeHGlobal(objectPointer);