Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.FreeHGlobal(System.IntPtr) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2064 Examples
19
Source : PInvokeHooks.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static void CallHooks(Messages Msg, IntPtr wParam, Message lParamMsg, bool global = true, bool window = true, bool allWindows = false) {
IntPtr lParam = Marshal.AllocHGlobal(MessageSize);
Marshal.StructureToPtr(lParamMsg, lParam, false);
CallHooks(Msg, wParam, lParam, lParamMsg: ref lParamMsg, global: global, window: window, allWindows: allWindows);
Marshal.FreeHGlobal(lParam);
}
19
Source : MetadataCustomMarshaler.cs
with MIT License
from 0xC0000054
with MIT License
from 0xC0000054
public void CleanUpNativeData(IntPtr pNativeData)
{
unsafe
{
if (pNativeData != IntPtr.Zero)
{
NativeMetadataParams* metadata = (NativeMetadataParams*)pNativeData;
if (metadata->iccProfile != IntPtr.Zero)
{
Marshal.FreeHGlobal(metadata->iccProfile);
}
if (metadata->exif != IntPtr.Zero)
{
Marshal.FreeHGlobal(metadata->exif);
}
if (metadata->xmp != IntPtr.Zero)
{
Marshal.FreeHGlobal(metadata->xmp);
}
Marshal.FreeHGlobal(pNativeData);
}
}
}
19
Source : AesGcm.cs
with GNU General Public License v3.0
from 0xfd3
with GNU General Public License v3.0
from 0xfd3
public byte[] Decrypt(byte[] key, byte[] iv, byte[] aad, byte[] cipherText, byte[] authTag)
{
IntPtr hAlg = OpenAlgorithmProvider(BCrypt.BCRYPT_AES_ALGORITHM, BCrypt.MS_PRIMITIVE_PROVIDER, BCrypt.BCRYPT_CHAIN_MODE_GCM);
IntPtr hKey, keyDataBuffer = ImportKey(hAlg, key, out hKey);
byte[] plainText;
var authInfo = new BCrypt.BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO(iv, aad, authTag);
using (authInfo)
{
byte[] ivData = new byte[MaxAuthTagSize(hAlg)];
int plainTextSize = 0;
uint status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, null, 0, ref plainTextSize, 0x0);
if (status != BCrypt.ERROR_SUCCESS)
throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() (get size) failed with status code: {0}", status));
plainText = new byte[plainTextSize];
status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, plainText, plainText.Length, ref plainTextSize, 0x0);
if (status == BCrypt.STATUS_AUTH_TAG_MISMATCH)
throw new CryptographicException("BCrypt.BCryptDecrypt(): authentication tag mismatch");
if (status != BCrypt.ERROR_SUCCESS)
throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() failed with status code:{0}", status));
}
BCrypt.BCryptDestroyKey(hKey);
Marshal.FreeHGlobal(keyDataBuffer);
BCrypt.BCryptCloseAlgorithmProvider(hAlg, 0x0);
return plainText;
}
19
Source : BCrypt.cs
with GNU General Public License v3.0
from 0xfd3
with GNU General Public License v3.0
from 0xfd3
public void Dispose()
{
if (pbNonce != IntPtr.Zero) Marshal.FreeHGlobal(pbNonce);
if (pbTag != IntPtr.Zero) Marshal.FreeHGlobal(pbTag);
if (pbAuthData != IntPtr.Zero) Marshal.FreeHGlobal(pbAuthData);
if (pbMacContext != IntPtr.Zero) Marshal.FreeHGlobal(pbMacContext);
}
19
Source : AreaForm.cs
with MIT License
from 1CM69
with MIT License
from 1CM69
public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
{
var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
var iconImage = IntPtr.Zero;
var cursorHandle = IntPtr.Zero;
try
{
var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));
if (imageIndex >= header.count)
throw new ArgumentOutOfRangeException("imageIndex");
var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));
iconImage = Marshal.AllocHGlobal(info.size + 4);
Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);
cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
return new Cursor(cursorHandle);
}
finally
{
if (cursorHandle != IntPtr.Zero)
NativeMethods.DestroyIcon(cursorHandle);
if (iconImage != IntPtr.Zero)
Marshal.FreeHGlobal(iconImage);
if (resourceHandle.IsAllocated)
resourceHandle.Free();
}
}
19
Source : UacHelper.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
public static bool IsProcessElevated()
{
if (IsUacEnabled())
{
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
{
throw new ApplicationException("Could not get process token. Win32 Error Code: " + Marshal.GetLastWin32Error());
}
try
{
TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;
int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
uint returnedSize = 0;
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
try
{
bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
if (success)
{
elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
return isProcessAdmin;
}
else
{
throw new ApplicationException("Unable to determine the current elevation.");
}
}
finally
{
if (elevationTypePtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(elevationTypePtr);
}
}
}
finally
{
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
else
{
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new(idenreplacedy);
bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
return result;
}
}
19
Source : DellSmbiosBzh.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static bool RemoveDriver()
{
IntPtr serviceManagerHandle;
IntPtr serviceHandle;
bool result;
StopDriver();
serviceManagerHandle = ServiceMethods.OpenSCManager(null, null, ServiceAccess.ServiceManagerAllAccess);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
serviceHandle = ServiceMethods.OpenService(serviceManagerHandle, DriverName, ServiceAccess.AllAccess);
ServiceMethods.CloseServiceHandle(serviceManagerHandle);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
result = ServiceMethods.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out int bytesNeeded);
if ((ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.InsufficientBuffer)
{
IntPtr serviceConfigurationPtr = Marshal.AllocHGlobal(bytesNeeded);
result = ServiceMethods.QueryServiceConfig(serviceHandle, serviceConfigurationPtr, bytesNeeded, out _);
QueryServiceConfig serviceConfiguration = (QueryServiceConfig) Marshal.PtrToStructure(serviceConfigurationPtr, typeof(QueryServiceConfig));
if (!result)
{
Marshal.FreeHGlobal(serviceConfigurationPtr);
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
// If service is set to load automatically, don't delete it!
if (serviceConfigurationPtr != IntPtr.Zero && serviceConfiguration.startType == ServiceStartType.DemandStart)
{
result = ServiceMethods.DeleteService(serviceHandle);
}
Marshal.FreeHGlobal(serviceConfigurationPtr);
}
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
19
Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static uint? GetSecurityKeyNew(SmiPreplacedword which, string preplacedword, PreplacedwordProperties properties)
{
// NOTE – Non-functional, need to figure out the string pointer before it will work.
if (GetPreplacedwordFormat(which, properties) == SmiPreplacedwordFormat.Scancode)
{
throw new NotImplementedException("BIOS wants scancode-encoded preplacedwords, but only ASCII-encoded preplacedwords are supported at this time.");
}
SmiObject message = new SmiObject
{
Clreplaced = (Clreplaced)which,
Selector = Selector.VerifyPreplacedwordNew
};
// Allocate a buffer for the preplacedword.
int bufferSize = properties.MaximumLength * 2;
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
// Zero out the buffer.
for (byte index = 0; index < bufferSize; index++)
{
Marshal.WriteByte(buffer, index, 0);
}
// Copy preplacedword into the buffer (ASCII-encoded).
byte[] preplacedwordBytes = ASCIIEncoding.ASCII.GetBytes(preplacedword);
Marshal.Copy(preplacedwordBytes, 0, buffer, Math.Min(preplacedword.Length, bufferSize));
message.Input1 = (uint)buffer.ToInt32();
ExecuteCommand(ref message);
Marshal.FreeHGlobal(buffer);
if (message.Input1 == (uint)SmiPreplacedwordCheckResult.Correct)
{
return message.Input2;
}
else
{
return null;
}
}
19
Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static byte[] StructToByteArray(SmiObject message)
{
int size = Marshal.SizeOf(message);
byte[] array = new byte[size];
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(message, pointer, true);
Marshal.Copy(pointer, array, 0, size);
Marshal.FreeHGlobal(pointer);
return array;
}
19
Source : DellSmbiosSmi.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static SmiObject ByteArrayToStruct(byte[] array)
{
SmiObject message = new SmiObject();
int size = Marshal.SizeOf(message);
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.Copy(array, 0, pointer, size);
message = (SmiObject)Marshal.PtrToStructure(pointer, message.GetType());
Marshal.FreeHGlobal(pointer);
return message;
}
19
Source : SafeHeapHandle.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
protected override bool ReleaseHandle()
{
var handleCopy = handle;
handle = IntPtr.Zero;
if (handleCopy != IntPtr.Zero)
Marshal.FreeHGlobal(handleCopy);
return true;
}
19
Source : OVRCommon.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private void Release()
{
if (m_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_ptr);
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public byte[] ToBytes()
{
int size = Marshal.SizeOf(this);
Trace.replacedert(size == StructSize);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(this, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
19
Source : OVRNetwork.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static FrameHeader FromBytes(byte[] arr)
{
FrameHeader header = new FrameHeader();
int size = Marshal.SizeOf(header);
Trace.replacedert(size == StructSize);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(arr, 0, ptr, size);
header = (FrameHeader)Marshal.PtrToStructure(ptr, header.GetType());
Marshal.FreeHGlobal(ptr);
return header;
}
19
Source : PowerManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private Guid GetActiveGuid()
{
Guid ActiveScheme = Guid.Empty;
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));
if (PowerGetActiveScheme((IntPtr)null, out ptr) == 0)
{
ActiveScheme = (Guid)Marshal.PtrToStructure(ptr, typeof(Guid));
if (ptr != null)
{
Marshal.FreeHGlobal(ptr);
}
}
return ActiveScheme;
}
19
Source : PowerManager.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static string GetPowerPlanName(Guid guid)
{
string name = string.Empty;
IntPtr lpszName = (IntPtr)null;
uint dwSize = 0;
PowerReadFriendlyName((IntPtr)null, ref guid, (IntPtr)null, (IntPtr)null, lpszName, ref dwSize);
if (dwSize > 0)
{
lpszName = Marshal.AllocHGlobal((int)dwSize);
if (0 == PowerReadFriendlyName((IntPtr)null, ref guid, (IntPtr)null, (IntPtr)null, lpszName, ref dwSize))
{
name = Marshal.PtrToStringUni(lpszName);
}
if (lpszName != IntPtr.Zero)
Marshal.FreeHGlobal(lpszName);
}
return name;
}
19
Source : FileHandle.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
private static string GetNameFromHandle(SafeGenericHandle handle)
{
uint length;
NativeMethods.NtQueryObject(
handle,
OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
IntPtr.Zero, 0, out length);
IntPtr ptr = IntPtr.Zero;
try
{
try { }
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
if (NativeMethods.NtQueryObject(
handle,
OBJECT_INFORMATION_CLreplaced.ObjectNameInformation,
ptr, length, out length) != NTSTATUS.STATUS_SUCCESS)
{
return null;
}
var unicodeStringName = (UNICODE_STRING)Marshal.PtrToStructure(ptr, typeof(UNICODE_STRING));
return unicodeStringName.ToString();
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
19
Source : NativeMethods.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public void Dispose()
{
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
}
19
Source : FileHandle.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
private static string GetTypeFromHandle(SafeGenericHandle handle)
{
uint length;
NativeMethods.NtQueryObject(handle,
OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
IntPtr.Zero,
0,
out length);
IntPtr ptr = IntPtr.Zero;
try
{
try
{
}
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
if (NativeMethods.NtQueryObject(handle,
OBJECT_INFORMATION_CLreplaced.ObjectTypeInformation,
ptr,
length,
out length) != NTSTATUS.STATUS_SUCCESS)
{
return null;
}
var typeInformation =
(PUBLIC_OBJECT_TYPE_INFORMATION)
Marshal.PtrToStructure(ptr, typeof(PUBLIC_OBJECT_TYPE_INFORMATION));
return typeInformation.TypeName.ToString();
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
19
Source : SystemUtility.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public static IEnumerable<FileHandle> GetHandles(int[] processIds)
{
var longProcIds = processIds.Select(Convert.ToUInt64).OrderBy(x => x).ToArray();
uint length = 0x10000;
IntPtr ptr = IntPtr.Zero;
try
{
try { }
finally
{
ptr = Marshal.AllocHGlobal((int)length);
}
uint returnLength;
NTSTATUS result;
while ((result = NativeMethods.NtQuerySystemInformation(
SYSTEM_INFORMATION_CLreplaced.SystemHandleInformation, ptr, length, out returnLength)) ==
NTSTATUS.STATUS_INFO_LENGTH_MISMATCH)
{
length = ((returnLength + 0xffff) & ~(uint)0xffff);
try { }
finally
{
Marshal.FreeHGlobal(ptr);
ptr = Marshal.AllocHGlobal((int)length);
}
}
if (result != NTSTATUS.STATUS_SUCCESS)
yield break;
long handleCount = Marshal.ReadInt64(ptr);
int offset = sizeof(long) + sizeof(long);
int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
for (int i = 0; i < handleCount; i++)
{
var handleEntry =
(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX)Marshal.PtrToStructure(
IntPtr.Add(ptr, offset), typeof(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX));
if (Array.BinarySearch(longProcIds, handleEntry.UniqueProcessId) > -1
&& FileHandle.TryCreate(handleEntry.UniqueProcessId, handleEntry.HandleValue, handleEntry.ObjectTypeIndex, out var fileHandle))
{
yield return fileHandle;
}
offset += size;
}
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
}
19
Source : AcrylicBlur.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public void EnableBlur()
{
var accent = new AccentPolicy
{
AccentFlags = (0x20 | 0x40 | 0x80 | 0x100),
AccentState = AccentState.ACCENT_ENABLE_ACRYLICBLURBEHIND,
GradientColor = (_blurOpacity << 24) | (_blurBackgroundColor & 0xFFFFFF)
};
var accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
SetWindowCompositionAttribute(WindowHandle, ref data);
Marshal.FreeHGlobal(accentPtr);
}
19
Source : NativeMethods.cs
with GNU General Public License v2.0
from ADeltaX
with GNU General Public License v2.0
from ADeltaX
public static bool TryStartService(string svcName)
{
bool wasDisabled = false;
QUERY_SERVICE_CONFIG SvcConfig = new QUERY_SERVICE_CONFIG();
IntPtr hSvcMgr = OpenSCManager(null, null, SC_MANAGER_CONNECT);
IntPtr hSvc = OpenService(hSvcMgr, "TrustedInstaller",
SERVICE_CHANGE_CONFIG | SERVICE_QUERY_CONFIG | SERVICE_START);
// Check if the service was disabled
uint dummy = 0;
IntPtr ptr = Marshal.AllocHGlobal(4096);
if (!QueryServiceConfig(hSvc, ptr, 4096, out dummy)) return false;
Marshal.PtrToStructure(ptr, SvcConfig);
Marshal.FreeHGlobal(ptr);
wasDisabled = (SvcConfig.dwStartType == SvcStartupType.Disabled);
// If it was disabled, set it as manual temporary
if (wasDisabled)
{
if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
SvcStartupType.Manual, SERVICE_NO_CHANGE,
null, null, IntPtr.Zero, null, null, null, null)) return false;
}
// Start the service
StartService(hSvc, 0, null);
// If it was disabled, set it back to disabled
if (wasDisabled)
{
if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE,
SvcStartupType.Disabled, SERVICE_NO_CHANGE,
null, null, IntPtr.Zero, null, null, null, null)) return false;
}
// Clean up
CloseServiceHandle(hSvc);
CloseServiceHandle(hSvcMgr);
return true;
}
19
Source : DarksVMStack.cs
with GNU General Public License v3.0
from Aekras1a
with GNU General Public License v3.0
from Aekras1a
public LocallocNode Free()
{
if(Memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(Memory);
Memory = IntPtr.Zero;
}
return Next;
}
19
Source : DiscordRPC.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
internal void FreeMem()
{
for (var i = _buffers.Count - 1; i >= 0; i--)
{
Marshal.FreeHGlobal(_buffers[i]);
_buffers.RemoveAt(i);
}
}
19
Source : UnmanagedBuffer.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
public bool Resize(int size)
{
if (size < 0)
{
return this.SetLastError(new ArgumentException("Attempting to resize to less than zero bytes of memory", "size"));
}
if (size == this.Size)
{
return true;
}
if (size > this.Size)
{
return this.Alloc(size);
}
try
{
if (size == 0)
{
Marshal.FreeHGlobal(this.Pointer);
this.Pointer = IntPtr.Zero;
}
else if (size > 0)
{
this.Pointer = Marshal.ReAllocHGlobal(this.Pointer, new IntPtr(size));
}
this.Size = size;
return true;
}
catch (Exception exception)
{
return this.SetLastError(exception);
}
}
19
Source : utils.cs
with GNU General Public License v3.0
from Aeroblast
with GNU General Public License v3.0
from Aeroblast
public static T GetStructBE<T>(byte[] data, int offset)
{
int size = Marshal.SizeOf(typeof(T));
Byte[] data_trimed = SubArray(data, offset, size);
Array.Reverse(data_trimed);
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(data_trimed, 0, structPtr, size);
T r = (T)Marshal.PtrToStructure(structPtr, typeof(T));
Marshal.FreeHGlobal(structPtr);
return r;
}
19
Source : Platform.Posix.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private static void MonoDllMapInsert(string libraryName, string libraryPath)
{
IntPtr libraryNamePtr = Marshal.StringToHGlobalAnsi(libraryName);
IntPtr pathPtr = Marshal.StringToHGlobalAnsi(libraryPath);
mono_dllmap_insert(IntPtr.Zero, libraryNamePtr, IntPtr.Zero, pathPtr, IntPtr.Zero);
Marshal.FreeHGlobal(libraryNamePtr);
Marshal.FreeHGlobal(pathPtr);
}
19
Source : ZFrame.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public string GetOption(string property, out ZError error)
{
error = ZError.None;
string result = null;
using (var propertyPtr = DispoIntPtr.AllocString(property))
{
IntPtr resultPtr;
if (IntPtr.Zero == (resultPtr = zmq.msg_gets(framePtr, propertyPtr)))
{
error = ZError.GetLastErr();
return null;
}
else
{
Marshal.FreeHGlobal(resultPtr);
result = Marshal.PtrToStringAnsi(resultPtr);
}
}
return result;
}
19
Source : DispoIntPtr.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
protected override void DoDispose()
{
Marshal.FreeHGlobal(Ptr);
Ptr = IntPtr.Zero;
}
19
Source : Platform.Posix.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static SafeLibraryHandle OpenHandle(string fileName)
{
IntPtr fileNamePtr = Marshal.StringToHGlobalAnsi(fileName);
SafeLibraryHandle libHandle = dlopen(fileNamePtr, RTLD_LAZY | RTLD_GLOBAL);
Marshal.FreeHGlobal(fileNamePtr);
return libHandle;
}
19
Source : Platform.Posix.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
{
IntPtr functionNamePtr = Marshal.StringToHGlobalAnsi(functionName);
IntPtr procHandle = dlsym(libHandle, functionNamePtr);
Marshal.FreeHGlobal(functionNamePtr);
return procHandle;
}
19
Source : CustomAudioSinkSample.cs
with MIT License
from AgoraIO
with MIT License
from AgoraIO
private void PullAudioFrameThread()
{
var avsync_type = 0;
var bytesPerSample = 2;
var type = AUDIO_FRAME_TYPE.FRAME_TYPE_PCM16;
var channels = CHANNEL;
var samples = SAMPLE_RATE / PULL_FREQ_PER_SEC * CHANNEL;
var samplesPerSec = SAMPLE_RATE;
var buffer = Marshal.AllocHGlobal(samples * bytesPerSample);
var freq = 1000 / PULL_FREQ_PER_SEC;
var tic = new TimeSpan(DateTime.Now.Ticks);
while (_pullAudioFrameThreadSignal)
{
var toc = new TimeSpan(DateTime.Now.Ticks);
if (toc.Subtract(tic).Duration().Milliseconds >= freq)
{
tic = new TimeSpan(DateTime.Now.Ticks);
_audioRawDataManager.PullAudioFrame(buffer, (int) type, samples, bytesPerSample, channels,
samplesPerSec, 0, avsync_type);
var byteArray = new byte[samples * bytesPerSample];
Marshal.Copy(buffer, byteArray, 0, samples * bytesPerSample);
var floatArray = ConvertByteToFloat16(byteArray);
lock (audioBuffer)
{
audioBuffer.Put(floatArray);
}
writeCount += floatArray.Length;
count += 1;
}
if (count == 100)
{
_startSignal = true;
}
}
Marshal.FreeHGlobal(buffer);
}
19
Source : RawInputWnd.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void GetRawInputData(IntPtr hRawInput)
{
try
{
int bsCount = -1;
int blen = 0;
int hlen = Marshal.SizeOf(typeof(RAWINPUTHEADER));
//TraceLogger.Instance.WriteLineInfo("Get RawInput data.");
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, IntPtr.Zero, ref blen, hlen);
if ((bsCount == -1) || (blen < 1))
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer size."); }
else
{
IntPtr pBuffer = Marshal.AllocHGlobal(blen);
try
{
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, pBuffer, ref blen, hlen);
if (bsCount != blen)
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer data."); }
else
{
RawInput ri = (RawInput)Marshal.PtrToStructure(pBuffer, typeof(RawInput));
FireRawInputEvent(ref ri);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
finally
{
Marshal.FreeHGlobal(pBuffer);
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
19
Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : TcpEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static IEnumerable<MIB_TCPROW_OWNER_PID> EnumTcpConnectionsV4()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCPROW_OWNER_PID item = new MIB_TCPROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCPROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : TcpEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static IEnumerable<MIB_TCP6ROW_OWNER_PID> EnumTcpConnectionsV6()
{
int dwSize = sizeof(int) + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)) * 100;
IntPtr hTcpTable = IntPtr.Zero;
{
hTcpTable = Marshal.AllocHGlobal(dwSize);
int ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
// retry for new dwSize.
Marshal.FreeHGlobal(hTcpTable);
hTcpTable = Marshal.AllocHGlobal(dwSize);
ret = iphlpapi.GetExtendedTcpTable(hTcpTable, ref dwSize, true, util.AF_INET6, TCP_TABLE_CLreplaced.TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
if (ret != util.NO_ERROR)
{
Marshal.FreeHGlobal(hTcpTable);
throw new Exception("GetExtendedTcpTable return: " + ret);
}
}
}
{
MIB_TCP6ROW_OWNER_PID item = new MIB_TCP6ROW_OWNER_PID();
int dwNumEntries = Marshal.ReadInt32(hTcpTable);
IntPtr pItem = new IntPtr(hTcpTable.ToInt32() + sizeof(int));
for (int i = 0; i < dwNumEntries; ++i)
{
//var item = (MIB_TCP6ROW_OWNER_PID)Marshal.PtrToStructure(pItem, typeof(MIB_TCP6ROW_OWNER_PID));
Marshal.PtrToStructure(pItem, item);
pItem = new IntPtr(pItem.ToInt64() + Marshal.SizeOf(typeof(MIB_TCP6ROW_OWNER_PID)));
yield return item;
}
Marshal.FreeHGlobal(hTcpTable);
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24
with BSD 3-Clause "New" or "Revised" License
from airzero24
public static string ExecuteShellCommand(int PPID, bool BlockDLLs, string Command)
{
var saHandles = new SECURITY_ATTRIBUTES();
saHandles.nLength = Marshal.SizeOf(saHandles);
saHandles.bInheritHandle = true;
saHandles.lpSecurityDescriptor = IntPtr.Zero;
IntPtr hStdOutRead;
IntPtr hStdOutWrite;
IntPtr hDupStdOutWrite = IntPtr.Zero;
CreatePipe(
out hStdOutRead,
out hStdOutWrite,
ref saHandles,
0);
SetHandleInformation(
hStdOutRead,
HANDLE_FLAGS.INHERIT,
0);
var pInfo = new PROCESS_INFORMATION();
var siEx = new STARTUPINFOEX();
siEx.StartupInfo.cb = Marshal.SizeOf(siEx);
siEx.StartupInfo.hStdErr = hStdOutWrite;
siEx.StartupInfo.hStdOutput = hStdOutWrite;
string result = string.Empty;
try
{
var lpSize = IntPtr.Zero;
if (BlockDLLs)
{
InitializeProcThreadAttributeList(
IntPtr.Zero,
2,
0,
ref lpSize);
siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
InitializeProcThreadAttributeList(
siEx.lpAttributeList,
2,
0,
ref lpSize);
var lpMitigationPolicy = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteInt64(lpMitigationPolicy, (long)BINARY_SIGNATURE_POLICY.PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON);
UpdateProcThreadAttribute(
siEx.lpAttributeList,
0,
0x20007,
lpMitigationPolicy,
(IntPtr)IntPtr.Size,
IntPtr.Zero,
IntPtr.Zero);
}
else
{
InitializeProcThreadAttributeList(
IntPtr.Zero,
1,
0,
ref lpSize);
siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
InitializeProcThreadAttributeList(
siEx.lpAttributeList,
1,
0,
ref lpSize);
}
var parentHandle = OpenProcess(
0x0080 | 0x0040,
false,
PPID);
var lpParentProcess = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpParentProcess, parentHandle);
UpdateProcThreadAttribute(
siEx.lpAttributeList,
0,
0x00020000,
lpParentProcess,
(IntPtr)IntPtr.Size,
IntPtr.Zero,
IntPtr.Zero);
var hCurrent = Process.GetCurrentProcess().Handle;
DuplicateHandle(
hCurrent,
hStdOutWrite,
parentHandle,
ref hDupStdOutWrite,
0,
true,
0x00000001 | 0x00000002);
siEx.StartupInfo.hStdErr = hDupStdOutWrite;
siEx.StartupInfo.hStdOutput = hDupStdOutWrite;
siEx.StartupInfo.dwFlags = 0x00000001 | 0x00000100;
siEx.StartupInfo.wShowWindow = 0;
var ps = new SECURITY_ATTRIBUTES();
var ts = new SECURITY_ATTRIBUTES();
ps.nLength = Marshal.SizeOf(ps);
ts.nLength = Marshal.SizeOf(ts);
CreateProcess(
null,
Command,
ref ps,
ref ts,
true,
CREATION_FLAGS.CREATE_NO_WINDOW | CREATION_FLAGS.EXTENDED_STARTUPINFO_PRESENT,
IntPtr.Zero,
null,
ref siEx,
out pInfo);
var safeHandle = new SafeFileHandle(hStdOutRead, false);
var encoding = Encoding.GetEncoding(GetConsoleOutputCP());
var reader = new StreamReader(new FileStream(safeHandle, FileAccess.Read, 4096, false), encoding, true);
var exit = false;
try
{
do
{
if (WaitForSingleObject(pInfo.hProcess, 100) == 0)
exit = true;
char[] buf = null;
int bytesRead;
uint bytesToRead = 0;
var peekRet = PeekNamedPipe(
hStdOutRead,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
ref bytesToRead,
IntPtr.Zero);
if (peekRet == true && bytesToRead == 0)
if (exit == true)
break;
else
continue;
if (bytesToRead > 4096)
bytesToRead = 4096;
buf = new char[bytesToRead];
bytesRead = reader.Read(buf, 0, buf.Length);
if (bytesRead > 0)
result += new string(buf);
} while (true);
reader.Close();
}
catch { }
finally
{
safeHandle.Close();
}
CloseHandle(hStdOutRead);
}
catch { }
finally
{
DeleteProcThreadAttributeList(siEx.lpAttributeList);
Marshal.FreeHGlobal(siEx.lpAttributeList);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
}
return result;
}
19
Source : MemoryManager.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal byte[] ReadVirtualMemory(IntPtr baseAddress, int bytesToRead)
{
var bytesBuffer = Marshal.AllocHGlobal(bytesToRead);
if (!ReadProcessMemory(_processHandle, baseAddress, bytesBuffer, bytesToRead, IntPtr.Zero))
{
ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
}
var bytesRead = new byte[bytesToRead];
Marshal.Copy(bytesBuffer, bytesRead, 0, bytesToRead);
Marshal.FreeHGlobal(bytesBuffer);
return bytesRead;
}
19
Source : MemoryManager.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal TStructure ReadVirtualMemory<TStructure>(IntPtr baseAddress) where TStructure : struct
{
var structureSize = Marshal.SizeOf<TStructure>();
var structureBuffer = Marshal.AllocHGlobal(structureSize);
if (!ReadProcessMemory(_processHandle, baseAddress, structureBuffer, structureSize, IntPtr.Zero))
{
ExceptionHandler.ThrowWin32Exception("Failed to read from a region of virtual memory in the remote process");
}
try
{
return Marshal.PtrToStructure<TStructure>(structureBuffer);
}
finally
{
Marshal.FreeHGlobal(structureBuffer);
}
}
19
Source : CreateThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Create a suspended thread with a spoofed start address
var ntStatus = Ntdll.NtCreateThreadEx(out var threadHandle, AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, IntPtr.Zero, _process.SafeHandle, _process.MainModule.BaseAddress, IntPtr.Zero, ThreadCreationFlags.CreateSuspended | ThreadCreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);
if (ntStatus != NtStatus.Success)
{
throw new Win32Exception($"Failed to call NtCreateThreadEx with error code {ntStatus}");
}
if (callDescriptor.IsWow64Call)
{
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Integer};
if (!Kernel32.Wow64GetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Change the spoofed start address to the address of the shellcode
threadContext.Eax = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Integer};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Change the spoofed start address to the address of the shellcode
threadContext.Rcx = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Resume the thread
if (Kernel32.ResumeThread(threadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
if (Kernel32.WaitForSingleObject(threadHandle, int.MaxValue) == -1)
{
throw new Win32Exception($"Failed to call WaitForSingleObject with error code {Marshal.GetLastWin32Error()}");
}
threadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
}
19
Source : HijackThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
var completionFlagBuffer = _memory.AllocateBlock(IntPtr.Zero, sizeof(bool), ProtectionType.ReadWrite);
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor, completionFlagBuffer);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Open a handle to the first thread
var firstThreadHandle = Kernel32.OpenThread(AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, false, _process.Threads[0].Id);
if (firstThreadHandle.IsInvalid)
{
throw new Win32Exception($"Failed to call OpenThread with error code {Marshal.GetLastWin32Error()}");
}
if (callDescriptor.IsWow64Call)
{
// Suspend the thread
if (Kernel32.Wow64SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call Wow64SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Control};
if (!Kernel32.Wow64GetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Esp -= sizeof(int);
_memory.Write((IntPtr) threadContext.Esp, threadContext.Eip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Eip = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Suspend the thread
if (Kernel32.SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Control};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Rsp -= sizeof(long);
_memory.Write((IntPtr) threadContext.Rsp, threadContext.Rip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Rip = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Send a message to the thread to ensure it executes the shellcode
if (!User32.PostThreadMessage(_process.Threads[0].Id, MessageType.Null, IntPtr.Zero, IntPtr.Zero))
{
throw new Win32Exception($"Failed to call PostThreadMessage with error code {Marshal.GetLastWin32Error()}");
}
// Resume the thread
if (Kernel32.ResumeThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
while (!_memory.Read<bool>(completionFlagBuffer))
{
Thread.Sleep(1);
}
firstThreadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
_memory.FreeBlock(completionFlagBuffer);
}
19
Source : UnmanagedCollection.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void Dispose()
{
Marshal.FreeHGlobal((IntPtr)Data);
GC.SuppressFinalize(this);
}
19
Source : UnmanagedCollection.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void GrowMemoryBlock(int newElementCount)
{
var newDataSize = elementSize_ * newElementCount;
var newData = (T*)Marshal.AllocHGlobal(newDataSize);
Buffer.MemoryCopy(Data, newData, DataSizeInBytes, DataSizeInBytes);
Marshal.FreeHGlobal((IntPtr)Data);
dataSizeInElements_ = newElementCount;
Data = newData;
}
19
Source : UntypedBuffer.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private void UpdateBuffer(int newSizeInBytes)
{
var newAllocation = AlignedAlloc(newSizeInBytes);
if (unalignedPtr_ != IntPtr.Zero) //has old data
{
var copySize = Math.Min(bufferSizeInBytes_, newSizeInBytes); //grows or shrinks
Buffer.MemoryCopy((void*)buffer_, (void*)newAllocation.aligned, copySize, copySize);
Marshal.FreeHGlobal(unalignedPtr_);
}
bufferSizeInBytes_ = newSizeInBytes;
buffer_ = newAllocation.aligned;
unalignedPtr_ = newAllocation.unaligned;
}
19
Source : GvrAudio.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled) {
// Update the enabled rooms list.
if (roomEnabled) {
if (!enabledRooms.Contains(room)) {
enabledRooms.Add(room);
}
} else {
enabledRooms.Remove(room);
}
// Update the current room effects to be applied.
if(initialized) {
if (enabledRooms.Count > 0) {
GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1];
RoomProperties roomProperties = GetRoomProperties(currentRoom);
// Preplaced the room properties into a pointer.
IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties));
Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false);
SetRoomProperties(roomPropertiesPtr);
Marshal.FreeHGlobal(roomPropertiesPtr);
} else {
// Set the room properties to null, which will effectively disable the room effects.
SetRoomProperties(IntPtr.Zero);
}
}
}
19
Source : StructHelper.cs
with MIT License
from albyho
with MIT License
from albyho
public static byte[] StructToBytes<T>(T structObj) where T : struct
{
//得到结构体的大小
Int32 size = Marshal.SizeOf(structObj);
//创建byte数组
var bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
19
Source : StructHelper.cs
with MIT License
from albyho
with MIT License
from albyho
public static T BytesToStuct<T>(byte[] bytes, Int32 offset) where T : struct
{
Type type = typeof(T);
//得到结构体的大小
Int32 size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length - offset)
{
throw new ArgumentException("bytes 的长度不足", nameof(bytes));
//返回空
//return default(T);
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, offset, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return (T)obj;
}
19
Source : StructHelper.cs
with MIT License
from albyho
with MIT License
from albyho
public static T BytesToStuct<T>(byte[] bytes) where T : struct
{
Type type = typeof(T);
//得到结构体的大小
Int32 size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
throw new ArgumentException("bytes 的长度不足", nameof(bytes));
//返回空
//return default(T);
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return (T)obj;
}
19
Source : Window.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public void AeroGlreplacedForEightAndHigher(bool enable)
{
var accent = new AccentPolicy();
var accentStructSize = Marshal.SizeOf(accent);
accent.AccentState = enable ? AccentState.ACCENT_ENABLE_BLURBEHIND : AccentState.ACCENT_DISABLED;
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
try
{
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData();
data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
data.SizeOfData = accentStructSize;
data.Data = accentPtr;
NativeMethods.SetWindowCompositionAttribute(Handle, ref data);
}
finally
{
Marshal.FreeHGlobal(accentPtr);
}
}
See More Examples