/// <summary> /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (!_memoryBlock.IsInvalid) { _memoryBlock.Dispose(); _memoryBlock = _invalidBlock; } }
public void Ctor_NullPointerIsZero() { //Act using (var target = new SafeHGlobalHandle(IntPtr.Zero)) { //Assert target.Pointer.Should().BeZero(); target.IsInvalid.Should().BeTrue(); }; }
public void StringToUnicode_NullStringWorks() { //Act using (var target = SafeHGlobalHandle.StringToUnicode(null)) { //Assert target.IsInvalid.Should().BeTrue(); target.Pointer.Should().BeZero(); }; }
public void ResizeTest() { var h = new SafeHGlobalHandle(5); Assert.That(!h.IsClosed && !h.IsInvalid && h.Size == 5); var ptr = (IntPtr)h; h.Size = 50; Assert.That(!h.IsClosed && !h.IsInvalid && h.Size == 50 && (IntPtr)h != ptr); }
public void FromNativeVariantTest() { using (var pVar = new SafeHGlobalHandle(100)) { Marshal.GetNativeVariantForObject(0xFFFFFFFF, (IntPtr)pVar); var pv = PROPVARIANT.FromNativeVariant((IntPtr)pVar); Assert.That(pv.vt, Is.EqualTo(VARTYPE.VT_UI4)); VariantClear((IntPtr)pVar); } }
public void SetLengthTest() { using (var m = new SafeHGlobalHandle(1000)) using (var ms = new NativeMemoryStream((IntPtr)m, m.Size)) { Assert.That(() => ms.SetLength(-1), Throws.TypeOf <ArgumentOutOfRangeException>()); Assert.That(() => ms.SetLength(1001), Throws.Exception); Assert.That(() => ms.SetLength(100), Throws.Nothing); } }
public void SeekTest() { using SafeHGlobalHandle m = new SafeHGlobalHandle(1000); using MarshalingStream ms = new MarshalingStream(m, m.Size); Assert.That(ms.Seek(20, SeekOrigin.Begin), Is.EqualTo(20)); Assert.That(ms.Seek(20, SeekOrigin.Current), Is.EqualTo(40)); Assert.That(ms.Seek(-100, SeekOrigin.End), Is.EqualTo(900)); Assert.That(() => ms.Seek(-1, SeekOrigin.Begin), Throws.ArgumentException); Assert.That(() => ms.Seek(1, SeekOrigin.End), Throws.ArgumentException); }
static SafeHGlobalHandle CopyOidsToUnmanagedMemory(OidCollection oids) { SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle; if (oids == null || oids.Count == 0) { return(safeAllocHandle); } // Copy the oid strings to a local list to prevent a security race condition where // the OidCollection or individual oids can be modified by another thread and // potentially cause a buffer overflow List <string> oidStrs = new List <string>(); foreach (Oid oid in oids) { oidStrs.Add(oid.Value); } IntPtr pOid = IntPtr.Zero; IntPtr pNullTerminator = IntPtr.Zero; // Needs to be checked to avoid having large sets of oids overflow the sizes and allow // a potential buffer overflow checked { int ptrSize = oidStrs.Count * Marshal.SizeOf(typeof(IntPtr)); int oidSize = 0; foreach (string oidStr in oidStrs) { oidSize += (oidStr.Length + 1); } safeAllocHandle = SafeHGlobalHandle.AllocHGlobal(ptrSize + oidSize); pOid = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + ptrSize); } for (int index = 0; index < oidStrs.Count; index++) { Marshal.WriteIntPtr(new IntPtr((long)safeAllocHandle.DangerousGetHandle() + index * Marshal.SizeOf(typeof(IntPtr))), pOid); byte[] ansiOid = Encoding.ASCII.GetBytes(oidStrs[index]); if (ansiOid.Length != oidStrs[index].Length) { // We assumed single byte characters, fail if this is not the case. The exception is not ideal. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CollectionWasModified))); } Marshal.Copy(ansiOid, 0, pOid, ansiOid.Length); pNullTerminator = new IntPtr((long)pOid + ansiOid.Length); Marshal.WriteByte(pNullTerminator, 0); pOid = new IntPtr((long)pOid + oidStrs[index].Length + 1); } return(safeAllocHandle); }
public void PropTest() { using (var m = new SafeHGlobalHandle(1000)) using (var ms = new MarshalingStream((IntPtr)m, m.Size)) { Assert.That(ms.Length, Is.EqualTo(1000)); Assert.That(ms.CanWrite, Is.True); Assert.That(ms.CanSeek, Is.True); Assert.That(ms.CanRead, Is.True); } }
public AsciiCompiledTextSearchNative( NativeMethods.SearchAlgorithmKind kind, string pattern, NativeMethods.SearchOptions searchOptions) { _patternHandle = new SafeHGlobalHandle(Marshal.StringToHGlobalAnsi(pattern)); var patternLength = pattern.Length; _handle = CreateSearchHandle(kind, _patternHandle, patternLength, searchOptions); _searchBufferSize = NativeMethods.AsciiSearchAlgorithm_GetSearchBufferSize(_handle); }
public void RECTTest() { using (var h = SafeHGlobalHandle.CreateFromStructure(new RECT(1, 2, 3, 4))) { var r = h.ToStructure <RECT>(); Assert.That(r.left == 1); Assert.That(r.top == 2); Assert.That(r.right == 3); Assert.That(r.bottom == 4); } }
public void SecureStringToUnicode_ZeroesMemoryWhenClosed() { var str = CreateSecureString("Hello"); var target = SafeHGlobalHandle.SecureStringToUnicode(str); //Act target.Close(); //Assert - All we can do is verify it doesn't blow up target.IsClosed.Should().BeTrue(); }
public void GetSetDefaultCommConfigTest() { using (var mem = new SafeHGlobalHandle(2048)) { var sz = (uint)mem.Size; Assert.That(GetDefaultCommConfig(pcCommPort, mem, ref sz), ResultIs.Successful); var cc = mem.ToStructure <COMMCONFIG>(); cc.WriteValues(); Assert.That(SetDefaultCommConfig(pcCommPort, mem, (uint)mem.Size), ResultIs.Successful); } }
public void Dispose_NullPointerWorks() { //Act var target = new SafeHGlobalHandle(); target.Dispose(); //Assert - No real way to confirm the memory was released target.Pointer.Should().BeZero(); target.IsInvalid.Should().BeTrue(); }
private void WriteIndexedImage(GLTexture texture, GLTexture palette) { byte[] palettesPixels = palette.GetManagedPixelsArray(PixelFormat.Format32bppArgb); TexHeader header = CreateHeader(texture, palette, palettesPixels[3] == 0); _output.WriteStruct(header); _output.Write(palettesPixels, 0, palettesPixels.Length); using (SafeHGlobalHandle pixels = texture.GetUnmanagedPixelsArray(PixelFormat.Format8bppIndexed)) using (UnmanagedMemoryStream input = pixels.OpenStream(FileAccess.Read)) input.CopyTo(_output); }
public void GetPrivateObjectSecurityTest() { using (var pSD = GetSD(fn)) { var b = GetPrivateObjectSecurity(pSD, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, IntPtr.Zero, 0, out uint rightSize); Assert.That(rightSize, Is.GreaterThan(0)); var sdo = new SafeHGlobalHandle((int)rightSize); b = GetPrivateObjectSecurity(pSD, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, (IntPtr)sdo, (uint)sdo.Size, out rightSize); Assert.That(b); Assert.That(!sdo.IsInvalid); } }
public void Ctor_ValidPointerIsSet() { var expected = AllocateMemory(200); //Act using (var target = new SafeHGlobalHandle(expected)) { //Assert target.Pointer.Should().Be(expected); target.IsInvalid.Should().BeFalse(); }; }
public void RegisterEventSourceTest() { using (var hES = RegisterEventSource(null, "TestSource")) { Assert.That(hES, ResultIs.ValidHandle); using (var mem = SafeHGlobalHandle.CreateFromStructure <EVENTLOG_FULL_INFORMATION>()) { Assert.That(GetEventLogInformation(hES, 0, mem, mem.Size, out var req), ResultIs.Successful); mem.ToStructure <EVENTLOG_FULL_INFORMATION>().WriteValues(); } } }
public void StringToUnicode_ValidStringWorks() { string str = "Hello"; //Act using (var target = SafeHGlobalHandle.StringToUnicode(str)) { //Assert target.IsInvalid.Should().BeFalse(); AssertMemory(target.Pointer, Encoding.Unicode.GetBytes("Hello")); }; }
public void Attach_NullPointerWorks() { //Act using (var target = new SafeHGlobalHandle()) { target.Attach(IntPtr.Zero); //Assert target.Pointer.Should().BeZero(); target.IsInvalid.Should().BeTrue(); }; }
public void SecureStringToAnsi_ValidStringWorks() { var str = CreateSecureString("Hello"); //Act using (var target = SafeHGlobalHandle.SecureStringToAnsi(str)) { //Assert target.IsInvalid.Should().BeFalse(); AssertMemory(target.Pointer, Encoding.ASCII.GetBytes("Hello")); }; }
public void ToArrayTest() { var rs = new[] { 10, 11, 12, 13, 14 }; var h = SafeHGlobalHandle.CreateFromList(rs, rs.Length, i); var ro = ((IntPtr)h).ToArray <int>(4, i); Assert.That(ro.Length, Is.EqualTo(4)); Assert.That(ro[2], Is.EqualTo(rs[2])); Assert.That(((IntPtr)h).ToArray <int>(0, i), Is.Empty); Assert.That(IntPtr.Zero.ToArray <int>(3, i), Is.Null); }
public void FiberTest() { TestContext.WriteLine($"IsFiber:{IsThreadAFiber()}"); var id = FlsAlloc(Callback); var mem = new SafeHGlobalHandle(64); mem.Fill(1); Assert.That(FlsSetValue(id, (IntPtr)mem), Is.True); Assert.That(FlsGetValue(id), Is.EqualTo((IntPtr)mem)); Assert.That(FlsFree(id), Is.True); mem.Dispose(); }
public void RtlMoveMemoryTest() { var strings = new[] { "One", "Two", "Three" }; using (var src = SafeHGlobalHandle.CreateFromStringList(strings)) using (var dest = new SafeHGlobalHandle(src.Size)) { Assert.That(() => RtlZeroMemory(dest, dest.Size), Throws.Nothing); Assert.That(() => RtlMoveMemory(dest, src, src.Size), Throws.Nothing); Assert.That(dest.ToStringEnum(), Is.EquivalentTo(strings)); } }
private string UnprotectSecretv3(ProtectedSecret data) { byte[] rawProtectedData = Convert.FromBase64String(data.Data); using SafeHGlobalHandle f = new SafeHGlobalHandle(rawProtectedData); var result = NCrypt.NCryptUnprotectSecret(out _, NCrypt.UnprotectSecretFlags.NCRYPT_SILENT_FLAG, f.DangerousGetHandle(), f.Size, IntPtr.Zero, IntPtr.Zero, out IntPtr unprotectedData, out uint unprotectedDataSize); result.ThrowIfFailed(); using SafeHGlobalHandle d = new SafeHGlobalHandle(unprotectedData, unprotectedDataSize, true); return(Encoding.Unicode.GetString(d.GetBytes(0, (int)unprotectedDataSize))); }
public void PRECTTest() { Assert.That(Marshal.SizeOf(typeof(RECT)) == Marshal.SizeOf(typeof(PRECT))); using (var h = SafeHGlobalHandle.CreateFromStructure(new PRECT(1, 2, 3, 4))) { var r = h.ToStructure <RECT>(); Assert.That(r.left == 1); Assert.That(r.top == 2); Assert.That(r.right == 3); Assert.That(r.bottom == 4); } }
public void SeekTest() { using (var m = new SafeHGlobalHandle(1000)) using (var ms = new NativeMemoryStream((IntPtr)m, m.Size)) { Assert.That(ms.Seek(20, SeekOrigin.Begin), Is.EqualTo(20)); Assert.That(ms.Seek(20, SeekOrigin.Current), Is.EqualTo(40)); Assert.That(ms.Seek(-100, SeekOrigin.End), Is.EqualTo(900)); Assert.That(() => ms.Seek(-1, SeekOrigin.Begin), Throws.ArgumentException); Assert.That(() => ms.Seek(1, SeekOrigin.End), Throws.ArgumentException); } }
/// <summary> /// Ensures that there is sufficient memory allocated. /// </summary> /// <param name="capacity"> /// The required capacity of the block, in bytes. /// </param> /// <exception cref="OutOfMemoryException"> /// There is insufficient memory to satisfy the request. /// </exception> public void EnsureCapacity(int capacity) { int currentSize = _memoryBlock.IsInvalid ? 0 : _memoryBlock.Size; if (capacity > currentSize) { if (0 != currentSize) currentSize <<= 1; if (capacity > currentSize) currentSize = capacity; if (!_memoryBlock.IsInvalid) _memoryBlock.Dispose(); _memoryBlock = SafeHGlobalHandle.Allocate(currentSize); } }
//******************************************************************************************** // Function: GetPreferredAddress // // Description: This function sorts a list of Ipv4 & Ipv6 addresses, and returns the "best" address that stack determines // //******************************************************************************************** static Win32Error GetPreferredAddress(SOCKADDR_IN6[] pAddrList, out SOCKADDR_STORAGE pPreferredAddr) { Win32Error dwErr = Win32Error.ERROR_SUCCESS; pPreferredAddr = default; // Initialize WinSock using var wsa = SafeWSA.Initialize(); // create socket var socketIoctl = WSASocket(ADDRESS_FAMILY.AF_INET6, SOCK.SOCK_DGRAM, 0, IntPtr.Zero, 0, WSA_FLAG.WSA_FLAG_OVERLAPPED); if (socketIoctl == SOCKET.INVALID_SOCKET) { dwErr = WSAGetLastError(); Console.Write("WSASocket failed, (dwErr = {0}).", dwErr); return(dwErr); } var numElement = pAddrList.Length; var pSockAddrList = Array.ConvertAll(pAddrList, v6 => new SOCKADDR(v6)); var pSocketAddrList = new SOCKET_ADDRESS_LIST { iAddressCount = numElement, Address = Array.ConvertAll(pSockAddrList, sa => new SOCKET_ADDRESS { iSockaddrLength = sa.Size, lpSockaddr = sa.DangerousGetHandle() }) }; // sort addresses using var ppSocketAddrList = SafeHGlobalHandle.CreateFromStructure(pSocketAddrList); uint dwSize = 4U + (uint)(Marshal.SizeOf <SOCKET_ADDRESS>() * pSocketAddrList.iAddressCount); dwErr = WSAIoctl(socketIoctl, WinSockIOControlCode.SIO_ADDRESS_LIST_SORT, ppSocketAddrList, dwSize, ppSocketAddrList, dwSize, out var dwBytes); pSocketAddrList = ppSocketAddrList.ToStructure <SOCKET_ADDRESS_LIST>(); if (dwErr == SOCKET_ERROR) { dwErr = WSAGetLastError(); Console.Write("WSAIoctl sort address failed, (dwErr = {0}).", dwErr); return(dwErr); } var pBestAddress = new IPAddress(pSocketAddrList.Address[0].lpSockaddr.ToArray <byte>(pSocketAddrList.Address[0].iSockaddrLength)); pPreferredAddr = (SOCKADDR_STORAGE)(pBestAddress.IsIPv4MappedToIPv6 ? pBestAddress.MapToIPv4() : pBestAddress); if (socketIoctl != SOCKET.INVALID_SOCKET) { closesocket(socketIoctl); socketIoctl = SOCKET.INVALID_SOCKET; } return(dwErr); }
public void IsBadPtrTest() { using (var mem = new SafeHGlobalHandle(8)) { #pragma warning disable CS0618 // Type or member is obsolete Assert.That(IsBadCodePtr(mem), ResultIs.Successful); Assert.That(IsBadReadPtr(mem, 8), ResultIs.Successful); Assert.That(IsBadStringPtr("string", 4), ResultIs.Successful); Assert.That(IsBadWritePtr(mem, 8), ResultIs.Successful); #pragma warning restore CS0618 // Type or member is obsolete } }
public void Detach_NullPointerWorks() { //Act using (var target = new SafeHGlobalHandle()) { var actual = target.Detach(); //Assert actual.Should().BeZero(); target.Pointer.Should().BeZero(); target.IsInvalid.Should().BeTrue(); }; }
public void OpenProcessCloseTraceTest() { var callbackCount = 0; Assert.That(() => { var logFile = new EventLogFile(logfilePath); logFile.EventCallback = EvtCallback; using (var log = new EventTraceSingleLog(logFile)) { using (var mem = SafeHGlobalHandle.CreateFromStructure <ETW_TRACE_PARTITION_INFORMATION>()) { Assert.That(QueryTraceProcessingHandle(log.Handle, ETW_PROCESS_HANDLE_INFO_TYPE.EtwQueryPartitionInformation, default, 0, mem, mem.Size, out var retLen), ResultIs.Successful);
private static extern bool BackupRead( SafeFileHandle hFile, SafeHGlobalHandle pBuffer, int numberOfBytesToRead, out int numberOfBytesRead, [MarshalAs(UnmanagedType.Bool)] bool abort, [MarshalAs(UnmanagedType.Bool)] bool processSecurity, ref IntPtr context);