public static byte[] WriteToNDB(WDBSheet sheet) { NDBHeader header = new NDBHeader(); header.fieldCount = sheet.FieldCount; header.lineCount = sheet.LineCount; int structSize = MarshalUtility.GetStructSize(typeof(NDBHeader)); header.fieldOffset = structSize; byte[] fieldBytes = GetFieldBytes(sheet, out var lineSize); header.lineSize = lineSize; header.lineOffset = structSize + fieldBytes.Length; byte[] strBytes = GetStringBytes(sheet, out var strOffsetDic); byte[] lineBytes = GetLineBytes(sheet, strOffsetDic); header.stringOffset = structSize + fieldBytes.Length + lineBytes.Length; MemoryStream stream = new MemoryStream(); byte[] headerBytes = MarshalUtility.StructToByte(header, structSize); stream.Write(headerBytes, 0, headerBytes.Length); stream.Write(fieldBytes, 0, fieldBytes.Length); stream.Write(lineBytes, 0, lineBytes.Length); stream.Write(strBytes, 0, strBytes.Length); return(stream.ToArray());; }
public PeerId[] GetConnectedPeers() { #if !UNITY_EDITOR || UNITY_EDITOR_OSX || UNITY_EDITOR_OVERRIDE IntPtr nativePeersArrayPtr = IntPtr.Zero; try { int nativePeerCount; IntPtr error; bool success = NativeMethods.UMCMediatorFacade.GetConnectedPeers( -1, out nativePeersArrayPtr, out nativePeerCount, out error); AssertNativeError(success, error); if (nativePeerCount == 0) { return(kEmptyPeerIdArray); } PeerId[] peers = MarshalUtility.MarshalNativeArray(nativePeersArrayPtr, nativePeerCount, ptr => new PeerId(ptr)); return(peers); } finally { NativeMethods.free(nativePeersArrayPtr); } #else return(kEmptyPeerIdArray); #endif }
public int GetConnectedPeers(PeerId[] results) { if (results == null) { throw new ArgumentNullException("results"); } #if !UNITY_EDITOR || UNITY_EDITOR_OSX || UNITY_EDITOR_OVERRIDE IntPtr nativePeersArrayPtr = IntPtr.Zero; try { int nativePeerCount; IntPtr error; bool success = NativeMethods.UMCMediatorFacade.GetConnectedPeers( results.Length, out nativePeersArrayPtr, out nativePeerCount, out error); AssertNativeError(success, error); if (nativePeerCount == 0) { return(0); } MarshalUtility.MarshalNativeArray(nativePeersArrayPtr, nativePeerCount, results, ptr => new PeerId(ptr)); return(nativePeerCount); } finally { NativeMethods.free(nativePeersArrayPtr); } #else return(0); #endif }
private void SetDataInternal(byte[] dataBytes) { this.dataBytes = dataBytes; int headerSize = MarshalUtility.GetStructSize(typeof(NDBHeader)); if (dataBytes == null || dataBytes.Length < headerSize) { throw new ArgumentNullException($"The databytes is empty. Name = {Name}"); } header = MarshalUtility.ByteToStruct <NDBHeader>(dataBytes, 0, headerSize); fields = new NDBField[header.fieldCount]; int fieldOffset = 0; int byteOffset = 0; for (int i = 0; i < header.fieldCount; ++i) { NDBField field = NDBByteUtility.ReadField(dataBytes, header.fieldOffset + byteOffset, out int offset); fields[i] = field; field.Offset = fieldOffset; fieldOffset += NDBFieldUtil.GetFieldOffset(field.FieldType); fieldNameToIndexDic.Add(field.Name, i); byteOffset += offset; } for (int i = 0; i < header.lineCount; ++i) { int id = ByteReader.ReadInt(dataBytes, header.lineOffset + header.lineSize * i, out int offset); dataIDToIndexDic.Add(id, i); } }
private static bool IsRepositoryCounterSignerInfo(CRYPT_ATTRIBUTE_STRING commitmentTypeIndicationAttribute) { int sizeOfCryptIntegerBlob = MarshalUtility.SizeOf <CRYPT_INTEGER_BLOB>(); for (var i = 0; i < commitmentTypeIndicationAttribute.cValue; ++i) { var attributeValuePointer = new IntPtr( (long)commitmentTypeIndicationAttribute.rgValue + (i * sizeOfCryptIntegerBlob)); var attributeValue = MarshalUtility.PtrToStructure <CRYPT_INTEGER_BLOB>(attributeValuePointer); var bytes = new byte[attributeValue.cbData]; Marshal.Copy(attributeValue.pbData, bytes, startIndex: 0, length: bytes.Length); var commitmentTypeIndication = CommitmentTypeIndication.Read(bytes); if (string.Equals( commitmentTypeIndication.CommitmentTypeId.Value, Oids.CommitmentTypeIdentifierProofOfReceipt, StringComparison.Ordinal)) { return(true); } } return(false); }
public ICollection <string> GetStringV(string key) { CheckKey(key); var originalPointer = PInvokes.GSettings.GetStrv(GSettingsPtr, key); var children = MarshalUtility.MarshalStringArray(originalPointer); return(children); }
void CreateInstance() { //LayerProperties[] available_layers = DelegateUtility.EnumerateToArray<LayerProperties> ( vk.EnumerateInstanceLayerProperties ); ExtensionProperties[] available_extensions = DelegateUtility.EnumerateToArray <ExtensionProperties> (vk.EnumerateInstanceExtensionProperties, IntPtr.Zero); List <string> extensions = new List <string> { KhrWin32Surface.EXTENSION_NAME, KhrSurface.EXTENSION_NAME }; for (int i = 0; i < extensions.Count; ++i) { if (!CheckExtensionAvailability(extensions[i], available_extensions)) { //std::cout << "Could not find instance extension named \"" << extensions[i] << "\"!" << std::endl; return; } } if (CheckExtensionAvailability(ExtDebugReport.EXTENSION_NAME, available_extensions)) { extensions.Add(ExtDebugReport.EXTENSION_NAME); supportDebugReport = true; } var exPtr = MarshalUtility.AllocateString(extensions); ApplicationInfo application_info = new ApplicationInfo { sType = StructureType.ApplicationInfo, pNext = IntPtr.Zero, pApplicationName = (byte *)Marshal.StringToHGlobalAnsi("Vulkan Window"), applicationVersion = new Version(1, 0, 0), pEngineName = (byte *)Marshal.StringToHGlobalAnsi("Vulkan Tutorial"), engineVersion = new Version(1, 0, 0), apiVersion = new Version(1, 0, 0), }; InstanceCreateInfo instance_create_info = new InstanceCreateInfo { sType = StructureType.InstanceCreateInfo, pNext = IntPtr.Zero, flags = 0, pApplicationInfo = &application_info, enabledLayerCount = 0, ppEnabledLayerNames = (byte *)0, enabledExtensionCount = (uint)extensions.Count, ppEnabledExtensionNames = (byte *)exPtr, }; vk.CreateInstance(ref instance_create_info, (AllocationCallbacks *)0, out vulkan.Instance).CheckError(); MarshalUtility.FreeString(exPtr, extensions.Count); Marshal.FreeHGlobal((IntPtr)application_info.pApplicationName); Marshal.FreeHGlobal((IntPtr)application_info.pEngineName); }
public int GetModuleSummaryList(int pid, out ModuleSummary[] result) { result = new ModuleSummary[0]; if (driverHandle != WinApi.INVALID_HANDLE_VALUE) { // Im lazy as f**k, so I just open a LARGE buffer int bufferSize = 1000 * 533; IntPtr bufferPointer = MarshalUtility.AllocZeroFilled(bufferSize); KERNEL_QUERY_PROCESS_INFO_OPERATION operation = new KERNEL_QUERY_PROCESS_INFO_OPERATION { targetProcessId = pid, bufferSize = bufferSize, bufferAddress = (ulong)bufferPointer.ToInt64() }; IntPtr operationPointer = MarshalUtility.CopyStructToMemory(operation); int operationSize = Marshal.SizeOf <KERNEL_QUERY_PROCESS_INFO_OPERATION>(); if (WinApi.DeviceIoControl(driverHandle, IO_QUERY_PROCESS_INFO, operationPointer, operationSize, operationPointer, operationSize, IntPtr.Zero, IntPtr.Zero)) { operation = MarshalUtility.GetStructFromMemory <KERNEL_QUERY_PROCESS_INFO_OPERATION>(operationPointer); if (operation.moduleCount > 0) { byte[] managedBuffer = new byte[bufferSize]; Marshal.Copy(bufferPointer, managedBuffer, 0, bufferSize); Marshal.FreeHGlobal(bufferPointer); result = new ModuleSummary[operation.moduleCount]; using (BinaryReader reader = new BinaryReader(new MemoryStream(managedBuffer))) { for (int i = 0; i < result.Length; i++) { result[i] = ModuleSummary.FromStream(reader); } } return(result.Length); } } else { int errCode = Marshal.GetLastWin32Error(); IntPtr tempptr = IntPtr.Zero; string msg = null; WinApi.FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr); MessageBox.Show(msg); } } return(0); }
/// <summary> /// Releases resources /// </summary> public void Dispose() { var element = MarshalUtility.InterlockedExchange(ref _element, IntPtr.Zero); if (ReferenceType == ElementRefType.Normal && element != IntPtr.Zero) { SciterDomApi.UnuseElement(element); } }
private T ReadProcessStruct <T>(int processId, IntPtr address) where T : struct { IntPtr buffer = MarshalUtility.AllocEmptyStruct <T>(); if (kernelDriver.CopyVirtualMemory(processId, address, buffer, Marshal.SizeOf <T>())) { return(MarshalUtility.GetStructFromMemory <T>(buffer)); } return(default(T)); }
public ICollection <string> ListChildren() { var originalPointer = PInvokes.GSettings.ListChildren(GSettingsPtr); var copyOriginalPointer = originalPointer; var children = MarshalUtility.MarshalStringArray(originalPointer); // You should free the return value with g_strfreev() when you are done with it. StringUtilityFunction.GStrFreeV(copyOriginalPointer); return(children); }
private byte[] ReadProcessBytes(int processId, IntPtr address, int size) { IntPtr unmanagedBytePointer = MarshalUtility.AllocZeroFilled(size); kernelDriver.CopyVirtualMemory(processId, address, unmanagedBytePointer, size); byte[] buffer = new byte[size]; Marshal.Copy(unmanagedBytePointer, buffer, 0, size); Marshal.FreeHGlobal(unmanagedBytePointer); return(buffer); }
private unsafe void SetDataInternal(byte[] dataBytes) { datas = dataBytes; int headerSize = Marshal.SizeOf(typeof(NDBHeader)); if (dataBytes == null || dataBytes.Length < headerSize) { throw new ArgumentNullException($"The databytes is empty. Name = {Name}"); } header = MarshalUtility.ByteToStruct <NDBHeader>(dataBytes, 0, headerSize); ReadFields(); }
public void StartAdvertising(IDictionary <string, string> discoveryInfo = null) { #if !UNITY_EDITOR || UNITY_EDITOR_OSX || UNITY_EDITOR_OVERRIDE NativeMethods.UMC_StringStringKeyValuePair[] keyValuePairs = null; int keyValuePairCount = 0; if (discoveryInfo != null) { keyValuePairs = MarshalUtility.StringStringDictionaryToPairArray(discoveryInfo); keyValuePairCount = keyValuePairs.Length; } IntPtr error; bool success = NativeMethods.UMCMediatorFacade.StartAdvertiserWithDiscoveryInfo(keyValuePairs, keyValuePairCount, out error); AssertNativeError(success, error); #endif }
private int GetProcessListRequiredBufferSize() { IntPtr operationPointer = MarshalUtility.AllocEmptyStruct <KERNEL_PROCESS_LIST_OPERATION>(); int operationSize = Marshal.SizeOf <KERNEL_PROCESS_LIST_OPERATION>(); if (WinApi.DeviceIoControl(driverHandle, IO_GET_PROCESS_LIST, operationPointer, operationSize, operationPointer, operationSize, IntPtr.Zero, IntPtr.Zero)) { KERNEL_PROCESS_LIST_OPERATION operation = MarshalUtility.GetStructFromMemory <KERNEL_PROCESS_LIST_OPERATION>(operationPointer); if (operation.processCount == 0 && operation.bufferSize > 0) { return(operation.bufferSize); } } return(0); }
// Reads native process info from a 64/32-bit process in the case where the target architecture // of this process is the same as that of the target process. private bool LoadProcessInfoNative(SafeProcessHandle handle, ProcessAccessFlags flags) { ProcessBasicInformation basicInfo = new ProcessBasicInformation(); int size; int status = NativeMethods.NtQueryInformationProcess( handle, ProcessInfoClass.BasicInformation, ref basicInfo, MarshalUtility.UnmanagedStructSize <ProcessBasicInformation>(), out size); _parentProcessId = basicInfo.ParentProcessId.ToInt32(); // If we can't load the ProcessBasicInfo, then we can't really do anything. if (status != NtStatus.Success || basicInfo.PebBaseAddress == IntPtr.Zero) { return(false); } if (flags.HasFlag(ProcessAccessFlags.VmRead)) { // Follows a pointer from the PROCESS_BASIC_INFORMATION structure in the target process's // address space to read the PEB. Peb peb = MarshalUtility.ReadUnmanagedStructFromProcess <Peb>( handle, basicInfo.PebBaseAddress); _isBeingDebugged = peb.IsBeingDebugged; if (peb.ProcessParameters != IntPtr.Zero) { // Follows a pointer from the PEB structure in the target process's address space to read // the RTL_USER_PROCESS_PARAMS. RtlUserProcessParameters processParameters = new RtlUserProcessParameters(); processParameters = MarshalUtility.ReadUnmanagedStructFromProcess <RtlUserProcessParameters>( handle, peb.ProcessParameters); _commandLine = MarshalUtility.ReadStringUniFromProcess( handle, processParameters.CommandLine.Buffer, processParameters.CommandLine.Length / 2); } } return(true); }
public bool GetProcessSummaryList(out ProcessSummary[] result) { result = new ProcessSummary[0]; if (driverHandle != WinApi.INVALID_HANDLE_VALUE) { int requiredBufferSize = GetProcessListRequiredBufferSize(); if (requiredBufferSize > 0) { IntPtr bufferPointer = MarshalUtility.AllocZeroFilled(requiredBufferSize); KERNEL_PROCESS_LIST_OPERATION operation = new KERNEL_PROCESS_LIST_OPERATION { bufferAddress = (ulong)bufferPointer.ToInt64(), bufferSize = requiredBufferSize }; IntPtr operationPointer = MarshalUtility.CopyStructToMemory(operation); int operationSize = Marshal.SizeOf <KERNEL_PROCESS_LIST_OPERATION>(); if (WinApi.DeviceIoControl(driverHandle, IO_GET_PROCESS_LIST, operationPointer, operationSize, operationPointer, operationSize, IntPtr.Zero, IntPtr.Zero)) { operation = MarshalUtility.GetStructFromMemory <KERNEL_PROCESS_LIST_OPERATION>(operationPointer); if (operation.processCount > 0) { byte[] managedBuffer = new byte[requiredBufferSize]; Marshal.Copy(bufferPointer, managedBuffer, 0, requiredBufferSize); Marshal.FreeHGlobal(bufferPointer); result = new ProcessSummary[operation.processCount]; using (BinaryReader reader = new BinaryReader(new MemoryStream(managedBuffer))) { for (int i = 0; i < result.Length; i++) { result[i] = ProcessSummary.FromStream(reader); } } return(true); } } } } return(false); }
private static bool IsRepositoryCounterSignerInfo(CMSG_SIGNER_INFO counterSignerInfo) { var signedAttributes = counterSignerInfo.AuthAttrs; int sizeOfCryptAttributeString = MarshalUtility.SizeOf <CRYPT_ATTRIBUTE_STRING>(); for (var i = 0; i < signedAttributes.cAttr; ++i) { var signedAttributePointer = new IntPtr( (long)signedAttributes.rgAttr + (i * sizeOfCryptAttributeString)); var signedAttribute = MarshalUtility.PtrToStructure <CRYPT_ATTRIBUTE_STRING>(signedAttributePointer); if (string.Equals(signedAttribute.pszObjId, Oids.CommitmentTypeIndication, StringComparison.Ordinal) && IsRepositoryCounterSignerInfo(signedAttribute)) { return(true); } } return(false); }
public bool CopyVirtualMemory(int targetProcessId, IntPtr targetAddress, IntPtr bufferAddress, int bufferSize) { if (driverHandle != WinApi.INVALID_HANDLE_VALUE) { KERNEL_COPY_MEMORY_OPERATION operation = new KERNEL_COPY_MEMORY_OPERATION { targetProcessId = targetProcessId, targetAddress = (ulong)targetAddress.ToInt64(), bufferAddress = (ulong)bufferAddress.ToInt64(), bufferSize = bufferSize }; IntPtr operationPointer = MarshalUtility.CopyStructToMemory(operation); bool result = WinApi.DeviceIoControl(driverHandle, IO_COPY_MEMORY, operationPointer, Marshal.SizeOf <KERNEL_COPY_MEMORY_OPERATION>(), IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero); Marshal.FreeHGlobal(operationPointer); return(result); } return(false); }
void createProcessTracer_OnFunctionExited( DkmStackWalkFrame frame, StackFrameAnalyzer frameAnalyzer) { try { ulong processInfoAddr = Convert.ToUInt64( frameAnalyzer.GetArgumentValue(frame, "lpProcessInformation")); // Check the return address first, it should be in EAX. CreateProcessAsUser and // CreateProcess both return 0 on failure. If the function failed, there is no child to // attach to. if (0 == frame.VscxGetRegisterValue32(CpuRegister.Eax)) { return; } // The process was successfully created. Extract the PID from the PROCESS_INFORMATION // output param. An attachment request must happend through the EnvDTE, which can only // be accessed from the VsPackage, so a request must be sent via a component message. DkmProcess process = frame.Process; int size = Marshal.SizeOf(typeof(PROCESS_INFORMATION)); byte[] buffer = new byte[size]; process.ReadMemory(processInfoAddr, DkmReadMemoryFlags.None, buffer); PROCESS_INFORMATION info = MarshalUtility.ByteArrayToStructure <PROCESS_INFORMATION>(buffer); DkmCustomMessage attachRequest = DkmCustomMessage.Create( process.Connection, process, PackageServices.VsPackageMessageGuid, (int)VsPackageMessage.AttachToChild, process.LivePart.Id, info.dwProcessId); attachRequest.SendToVsService(PackageServices.DkmComponentEventHandler, false); } catch (Exception exception) { Logger.LogError( exception, "An error occured handling the exit breakpoint. HR = 0x{0:X}", exception.HResult); } }
private static void MessageHandler(NativeMethods.Events.EventType eventType, IntPtr eventDataPtr) { lock (_nativeEvents) { switch (eventType) { // Session case NativeMethods.Events.EventType.SessionStarted: case NativeMethods.Events.EventType.SessionDisconnected: case NativeMethods.Events.EventType.SessionPeerStateChanged: // Advertiser case NativeMethods.Events.EventType.AdvertiserInvitationReceived: case NativeMethods.Events.EventType.AdvertiserStartFailed: // Advertiser assistant case NativeMethods.Events.EventType.AdvertiserAssistantInvitationDismissed: case NativeMethods.Events.EventType.AdvertiserAssistantInvitationPresenting: // Peer discovery case NativeMethods.Events.EventType.NearbyServiceBrowserPeerFound: case NativeMethods.Events.EventType.NearbyServiceBrowserPeerLost: case NativeMethods.Events.EventType.NearbyServiceBrowserStartFailed: // Peer discovery UI case NativeMethods.Events.EventType.BrowserViewControllerCancelled: case NativeMethods.Events.EventType.BrowserViewControllerFinished: // Just store the event data, the event marshalling and invocation are deferred until we are on the main Unity thread _nativeEvents.Push(new NativeEvent(eventType, eventDataPtr)); return; case NativeMethods.Events.EventType.BrowserViewControllerNearbyPeerPresenting: { // Special event, can not defer, must be processed immediately var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_BrowserViewControllerNearbyPeerPresentingEventData>(eventDataPtr); PeerId peerId = new PeerId(eventData.PeerId); Dictionary <string, string> discoveryInfo = eventData.DiscoveryInfoPairArray != IntPtr.Zero ? MarshalUtility.MarshalStringStringDictionary(eventData.DiscoveryInfoPairArray, eventData.DiscoveryInfoArrayPairCount) : null; NativeMethods.Events.UMC_BrowserViewControllerNearbyPeerPresentingResultEventData result; result.ShouldPresent = true; _peerDiscovery.OnNearbyPeerPresenting(peerId, discoveryInfo, ref result.ShouldPresent); // Copy from managed to native Marshal.StructureToPtr(result, eventData.Result, false); // Event data is freed on the native side automatically after this method returns return; } // Logs case NativeMethods.Events.EventType.Log: { // Special event, logs can be logged at any time var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_LogEventData>(eventDataPtr); switch (eventData.Type) { case NativeMethods.LogType.Log: Debug.Log("[ALM] " + eventData.Text); break; case NativeMethods.LogType.Warning: Debug.LogWarning("[ALM] " + eventData.Text); break; case NativeMethods.LogType.Error: Debug.LogError("[ALM] " + eventData.Text); break; default: throw new ArgumentOutOfRangeException("eventData.Type"); } NativeMethods.Events.UMC_FreeEventData(eventType, eventDataPtr); return; } default: throw new ArgumentOutOfRangeException("eventType", eventType, null); } } }
public ICollection <string> ListRelocatableSchemas() => MarshalUtility.MarshalStringArray(PInvokes.GSettings.ListRelocatableSchemas());
internal unsafe static CMSG_SIGNER_ENCODE_INFO CreateSignerInfo( CmsSigner cmsSigner, CngKey privateKey, HeapBlockRetainer hb) { var signerInfo = new CMSG_SIGNER_ENCODE_INFO(); signerInfo.cbSize = (uint)Marshal.SizeOf(signerInfo); signerInfo.pCertInfo = MarshalUtility.PtrToStructure <CERT_CONTEXT>(cmsSigner.Certificate.Handle).pCertInfo; signerInfo.hCryptProvOrhNCryptKey = privateKey.Handle.DangerousGetHandle(); signerInfo.HashAlgorithm.pszObjId = cmsSigner.DigestAlgorithm.Value; if (cmsSigner.SignerIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) { var certContextHandle = IntPtr.Zero; try { certContextHandle = NativeMethods.CertDuplicateCertificateContext(cmsSigner.Certificate.Handle); uint cbData = 0; var pbData = IntPtr.Zero; ThrowIfFailed(NativeMethods.CertGetCertificateContextProperty( certContextHandle, NativeMethods.CERT_KEY_IDENTIFIER_PROP_ID, pbData, ref cbData)); if (cbData > 0) { pbData = hb.Alloc((int)cbData); ThrowIfFailed(NativeMethods.CertGetCertificateContextProperty( certContextHandle, NativeMethods.CERT_KEY_IDENTIFIER_PROP_ID, pbData, ref cbData)); signerInfo.SignerId.dwIdChoice = NativeMethods.CERT_ID_KEY_IDENTIFIER; signerInfo.SignerId.KeyId.cbData = cbData; signerInfo.SignerId.KeyId.pbData = pbData; } } finally { if (certContextHandle != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(certContextHandle); } } } if (cmsSigner.SignedAttributes.Count != 0) { signerInfo.cAuthAttr = cmsSigner.SignedAttributes.Count; checked { int sizeOfCryptAttribute = MarshalUtility.SizeOf <CRYPT_ATTRIBUTE>(); int sizeOfCryptIntegerBlob = MarshalUtility.SizeOf <CRYPT_INTEGER_BLOB>(); var attributesArray = (CRYPT_ATTRIBUTE *)hb.Alloc(sizeOfCryptAttribute * cmsSigner.SignedAttributes.Count); var currentAttribute = attributesArray; foreach (var attribute in cmsSigner.SignedAttributes) { currentAttribute->pszObjId = hb.AllocAsciiString(attribute.Oid.Value); currentAttribute->cValue = (uint)attribute.Values.Count; currentAttribute->rgValue = hb.Alloc(sizeOfCryptIntegerBlob); foreach (var value in attribute.Values) { var attrData = value.RawData; if (attrData.Length > 0) { var blob = (CRYPT_INTEGER_BLOB *)currentAttribute->rgValue; blob->cbData = (uint)attrData.Length; blob->pbData = hb.Alloc(value.RawData.Length); Marshal.Copy(attrData, 0, blob->pbData, attrData.Length); } } currentAttribute++; } signerInfo.rgAuthAttr = new IntPtr(attributesArray); } } return(signerInfo); }
void CreateDevice() { PhysicalDevice[] physical_devices = DelegateUtility.EnumerateToArray <PhysicalDevice> (vk.EnumeratePhysicalDevices, (IntPtr)vulkan.Instance); if (physical_devices == null) { //std::cout << "Error occurred during physical devices enumeration!" << std::endl; return; } uint selected_graphics_queue_family_index = uint.MaxValue; uint selected_present_queue_family_index = uint.MaxValue; for (int i = 0; i < physical_devices.Length; ++i) { if (CheckPhysicalDeviceProperties(physical_devices[i], out selected_graphics_queue_family_index, out selected_present_queue_family_index)) { vulkan.PhysicalDevice = physical_devices[i]; } } if (vulkan.PhysicalDevice.IsZero || selected_graphics_queue_family_index == uint.MaxValue || selected_present_queue_family_index == uint.MaxValue) { //std::cout << "Could not select physical device based on the chosen properties!" << std::endl; return; } var queue_create_infos = stackalloc DeviceQueueCreateInfo[2]; uint count = 1; float *queue_priorities = stackalloc float[1]; queue_priorities[0] = 1.0f; queue_create_infos[0] = new DeviceQueueCreateInfo { sType = StructureType.DeviceQueueCreateInfo, // VkStructureType sType pNext = IntPtr.Zero, // const void *pNext flags = 0, // VkDeviceQueueCreateFlagBits flags queueFamilyIndex = selected_graphics_queue_family_index, // uint32_t queueFamilyIndex queueCount = 1, // uint32_t queueCount pQueuePriorities = queue_priorities // const float *pQueuePriorities }; if (selected_graphics_queue_family_index != selected_present_queue_family_index) { queue_create_infos[1] = new DeviceQueueCreateInfo { sType = StructureType.DeviceQueueCreateInfo, // VkStructureType sType pNext = IntPtr.Zero, // const void *pNext flags = 0, // VkDeviceQueueCreateFlagBits flags queueFamilyIndex = selected_present_queue_family_index, // uint32_t queueFamilyIndex queueCount = 1, // uint32_t queueCount pQueuePriorities = queue_priorities // const float *pQueuePriorities }; count++; } const uint exCount = 1; var exPtr = MarshalUtility.AllocateString(new string[] { KhrSwapchain.EXTENSION_NAME }); DeviceCreateInfo device_create_info = new DeviceCreateInfo { sType = StructureType.DeviceCreateInfo, // VkStructureType sType pNext = IntPtr.Zero, // const void *pNext flags = 0, // VkDeviceCreateFlagBits flags queueCreateInfoCount = count, // uint32_t queueCreateInfoCount pQueueCreateInfos = queue_create_infos, // const VkDeviceQueueCreateInfo *pQueueCreateInfos enabledLayerCount = 0, // uint32_t enabledLayerCount ppEnabledLayerNames = (byte *)0, // const char * const *ppEnabledLayerNames enabledExtensionCount = exCount, // uint32_t enabledExtensionCount ppEnabledExtensionNames = (byte *)exPtr, // const char * const *ppEnabledExtensionNames pEnabledFeatures = (PhysicalDeviceFeatures *)0 // const VkPhysicalDeviceFeatures *pEnabledFeatures }; vk.CreateDevice(vulkan.PhysicalDevice, ref device_create_info, (AllocationCallbacks *)0, out vulkan.Device).CheckError(); MarshalUtility.FreeString(exPtr, (int)exCount); }
internal static SignedCms NativeSign(CmsSigner cmsSigner, byte[] data, CngKey privateKey) { using (var hb = new HeapBlockRetainer()) { var certificateBlobs = new BLOB[cmsSigner.Certificates.Count]; for (var i = 0; i < cmsSigner.Certificates.Count; ++i) { var cert = cmsSigner.Certificates[i]; var context = MarshalUtility.PtrToStructure <CERT_CONTEXT>(cert.Handle); certificateBlobs[i] = new BLOB() { cbData = context.cbCertEncoded, pbData = context.pbCertEncoded }; } byte[] encodedData; var signerInfo = CreateSignerInfo(cmsSigner, privateKey, hb); var signedInfo = new CMSG_SIGNED_ENCODE_INFO(); signedInfo.cbSize = Marshal.SizeOf(signedInfo); signedInfo.cSigners = 1; using (var signerInfoHandle = new SafeLocalAllocHandle(Marshal.AllocHGlobal(Marshal.SizeOf(signerInfo)))) { Marshal.StructureToPtr(signerInfo, signerInfoHandle.DangerousGetHandle(), fDeleteOld: false); signedInfo.rgSigners = signerInfoHandle.DangerousGetHandle(); signedInfo.cCertEncoded = certificateBlobs.Length; using (var certificatesHandle = new SafeLocalAllocHandle(Marshal.AllocHGlobal(Marshal.SizeOf(certificateBlobs[0]) * certificateBlobs.Length))) { for (var i = 0; i < certificateBlobs.Length; ++i) { Marshal.StructureToPtr(certificateBlobs[i], new IntPtr(certificatesHandle.DangerousGetHandle().ToInt64() + Marshal.SizeOf(certificateBlobs[i]) * i), fDeleteOld: false); } signedInfo.rgCertEncoded = certificatesHandle.DangerousGetHandle(); var hMsg = NativeMethods.CryptMsgOpenToEncode( CMSG_ENCODING.Any, dwFlags: 0, dwMsgType: NativeMethods.CMSG_SIGNED, pvMsgEncodeInfo: ref signedInfo, pszInnerContentObjID: null, pStreamInfo: IntPtr.Zero); ThrowIfFailed(!hMsg.IsInvalid); ThrowIfFailed(NativeMethods.CryptMsgUpdate( hMsg, data, (uint)data.Length, fFinal: true)); uint valueLength = 0; ThrowIfFailed(NativeMethods.CryptMsgGetParam( hMsg, CMSG_GETPARAM_TYPE.CMSG_CONTENT_PARAM, dwIndex: 0, pvData: null, pcbData: ref valueLength)); encodedData = new byte[(int)valueLength]; ThrowIfFailed(NativeMethods.CryptMsgGetParam( hMsg, CMSG_GETPARAM_TYPE.CMSG_CONTENT_PARAM, dwIndex: 0, pvData: encodedData, pcbData: ref valueLength)); } } var cms = new SignedCms(); cms.Decode(encodedData); return(cms); } }
private static void DispatchNativeEvent(ref NativeEvent nativeEvent) { switch (nativeEvent.EventType) { // Session case NativeMethods.Events.EventType.SessionStarted: _session.OnStarted(); break; case NativeMethods.Events.EventType.SessionDisconnected: _session.OnStopped(); break; case NativeMethods.Events.EventType.SessionPeerStateChanged: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_SessionPeerStateChangedEventData>(nativeEvent.EventData); PeerId peerId = new PeerId(eventData.PeerId); _session.OnPeerStateChanged(peerId, eventData.NewPeerState); break; } // Advertiser case NativeMethods.Events.EventType.AdvertiserInvitationReceived: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_AdvertiserInvitationReceivedEventData>(nativeEvent.EventData); PeerId peerId = new PeerId(eventData.PeerId); // The block is wrapped into an NSObject wrapper so that it can be GC'd and eventually released NSObject invitationHandlerBlock = new NSObject(eventData.InvitationHandler); InvitationHandler invitationHandlerAction = accept => { NativeMethods.AdvertiserInvitationHandlerBlock.Invoke(invitationHandlerBlock.NativePointer, accept, IntPtr.Zero); }; _customServiceAdvertiser.OnInvitationReceived(peerId, invitationHandlerAction); break; } case NativeMethods.Events.EventType.AdvertiserStartFailed: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_ErrorStringEventData>(nativeEvent.EventData); _customServiceAdvertiser.OnStartFailed(eventData.Error); break; } // Advertiser assistant case NativeMethods.Events.EventType.AdvertiserAssistantInvitationDismissed: _serviceAdvertiser.OnInvitationDismissed(); break; case NativeMethods.Events.EventType.AdvertiserAssistantInvitationPresenting: _serviceAdvertiser.OnInvitationPresenting(); break; // Peer discovery case NativeMethods.Events.EventType.NearbyServiceBrowserPeerFound: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_PeerFoundEventData>(nativeEvent.EventData); PeerId peerId = new PeerId(eventData.PeerId); Dictionary <string, string> discoveryInfo = eventData.DiscoveryInfoPairArray != IntPtr.Zero ? MarshalUtility.MarshalStringStringDictionary(eventData.DiscoveryInfoPairArray, eventData.DiscoveryInfoArrayPairCount) : null; _customPeerDiscovery.OnPeerFound(peerId, discoveryInfo); break; } case NativeMethods.Events.EventType.NearbyServiceBrowserPeerLost: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_NearbyServiceBrowserPeerLostEventData>(nativeEvent.EventData); PeerId peerId = new PeerId(eventData.PeerId); _customPeerDiscovery.OnPeerLost(peerId); break; } case NativeMethods.Events.EventType.NearbyServiceBrowserStartFailed: { var eventData = MarshalUtility.PtrToStructure <NativeMethods.Events.UMC_ErrorStringEventData>(nativeEvent.EventData); _customPeerDiscovery.OnStartFailed(eventData.Error); break; } // Peer discovery UI case NativeMethods.Events.EventType.BrowserViewControllerCancelled: _peerDiscovery.OnCancelled(); break; case NativeMethods.Events.EventType.BrowserViewControllerFinished: _peerDiscovery.OnFinished(); break; default: throw new InvalidEnumArgumentException("nativeEvent.EventType", (int)nativeEvent.EventType, typeof(NativeMethods.Events.EventType)); } }
internal unsafe void AddTimestampToRepositoryCountersignature(SignedCms timestamp) { using (var hb = new HeapBlockRetainer()) { var repositoryCountersignature = GetRepositoryCountersignature(hb); if (repositoryCountersignature == null) { throw new SignatureException(Strings.Error_NotOneRepositoryCounterSignature); } // Remove repository countersignature from message var countersignatureDelAttr = new CMSG_CTRL_DEL_SIGNER_UNAUTH_ATTR_PARA() { dwSignerIndex = 0, dwUnauthAttrIndex = repositoryCountersignature.Value.dwUnauthAttrIndex }; countersignatureDelAttr.cbSize = (uint)Marshal.SizeOf(countersignatureDelAttr); var unmanagedCountersignatureDelAttr = hb.Alloc(Marshal.SizeOf(countersignatureDelAttr)); Marshal.StructureToPtr(countersignatureDelAttr, unmanagedCountersignatureDelAttr, fDeleteOld: false); if (!NativeMethods.CryptMsgControl( _handle, dwFlags: 0, dwCtrlType: CMSG_CONTROL_TYPE.CMSG_CTRL_DEL_SIGNER_UNAUTH_ATTR, pvCtrlPara: unmanagedCountersignatureDelAttr)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } // Add timestamp attribute to existing unsigned attributes var signerInfo = repositoryCountersignature.Value.SignerInfo; var unauthAttrCount = signerInfo.UnauthAttrs.cAttr + 1; var sizeOfCryptAttribute = MarshalUtility.SizeOf <CRYPT_ATTRIBUTE>(); var attributesArray = (CRYPT_ATTRIBUTE *)hb.Alloc((int)(sizeOfCryptAttribute * unauthAttrCount)); var currentAttribute = attributesArray; // Copy existing unsigned attributes for (var i = 0; i < unauthAttrCount - 1; ++i) { var existingAttributePointer = new IntPtr( (long)signerInfo.UnauthAttrs.rgAttr + (i * sizeOfCryptAttribute)); var existingAttribute = MarshalUtility.PtrToStructure <CRYPT_ATTRIBUTE>(existingAttributePointer); currentAttribute->pszObjId = existingAttribute.pszObjId; currentAttribute->cValue = existingAttribute.cValue; currentAttribute->rgValue = existingAttribute.rgValue; currentAttribute++; } // Add timestamp attribute *currentAttribute = GetCryptAttributeForData(timestamp.Encode(), Oids.SignatureTimeStampTokenAttribute, hb); signerInfo.UnauthAttrs = new CRYPT_ATTRIBUTES() { cAttr = unauthAttrCount, rgAttr = new IntPtr(attributesArray) }; // Encode signer info var unmanagedSignerInfo = hb.Alloc(Marshal.SizeOf(signerInfo)); Marshal.StructureToPtr(signerInfo, unmanagedSignerInfo, fDeleteOld: false); uint encodedLength = 0; if (!NativeMethods.CryptEncodeObjectEx( CMSG_ENCODING.Any, lpszStructType: new IntPtr(NativeMethods.PKCS7_SIGNER_INFO), pvStructInfo: unmanagedSignerInfo, dwFlags: 0, pEncodePara: IntPtr.Zero, pvEncoded: IntPtr.Zero, pcbEncoded: ref encodedLength)) { var err = Marshal.GetLastWin32Error(); if (err != NativeMethods.ERROR_MORE_DATA) { Marshal.ThrowExceptionForHR(NativeMethods.GetHRForWin32Error(err)); } } var unmanagedEncoded = hb.Alloc((int)encodedLength); if (!NativeMethods.CryptEncodeObjectEx( CMSG_ENCODING.Any, lpszStructType: new IntPtr(NativeMethods.PKCS7_SIGNER_INFO), pvStructInfo: unmanagedSignerInfo, dwFlags: 0, pEncodePara: IntPtr.Zero, pvEncoded: unmanagedEncoded, pcbEncoded: ref encodedLength)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } var encondedSignerBlob = new CRYPT_INTEGER_BLOB() { cbData = encodedLength, pbData = unmanagedEncoded }; var unmanagedBlob = hb.Alloc(Marshal.SizeOf(encondedSignerBlob)); Marshal.StructureToPtr(encondedSignerBlob, unmanagedBlob, fDeleteOld: false); var signerInfoAttr = new CRYPT_ATTRIBUTE() { pszObjId = hb.AllocAsciiString(Oids.Countersignature), cValue = 1, rgValue = unmanagedBlob }; // Create add unauth for signer info var signerInfoAddAttr = CreateUnsignedAddAttribute(signerInfoAttr, hb); // Add repository countersignature back to message signerInfoAddAttr.cbSize = (uint)Marshal.SizeOf(signerInfoAddAttr); var unmanagedSignerInfoAddAttr = hb.Alloc(Marshal.SizeOf(signerInfoAddAttr)); Marshal.StructureToPtr(signerInfoAddAttr, unmanagedSignerInfoAddAttr, fDeleteOld: false); if (!NativeMethods.CryptMsgControl( _handle, dwFlags: 0, dwCtrlType: CMSG_CONTROL_TYPE.CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR, pvCtrlPara: unmanagedSignerInfoAddAttr)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } } }
private unsafe RepositoryCounterSignerInfo?GetRepositoryCountersignature(HeapBlockRetainer retainer) { const uint primarySignerInfoIndex = 0; uint unsignedAttributeCount = 0; var pointer = IntPtr.Zero; NativeUtility.ThrowIfFailed(NativeMethods.CryptMsgGetParam( _handle, CMSG_GETPARAM_TYPE.CMSG_SIGNER_UNAUTH_ATTR_PARAM, primarySignerInfoIndex, pointer, ref unsignedAttributeCount)); if (unsignedAttributeCount == 0) { return(null); } pointer = retainer.Alloc((int)unsignedAttributeCount); NativeUtility.ThrowIfFailed(NativeMethods.CryptMsgGetParam( _handle, CMSG_GETPARAM_TYPE.CMSG_SIGNER_UNAUTH_ATTR_PARAM, primarySignerInfoIndex, pointer, ref unsignedAttributeCount)); var unsignedAttributes = MarshalUtility.PtrToStructure <CRYPT_ATTRIBUTES>(pointer); int sizeOfCryptAttributeString = MarshalUtility.SizeOf <CRYPT_ATTRIBUTE_STRING>(); int sizeOfCryptIntegerBlob = MarshalUtility.SizeOf <CRYPT_INTEGER_BLOB>(); for (uint i = 0; i < unsignedAttributes.cAttr; ++i) { var attributePointer = new IntPtr( (long)unsignedAttributes.rgAttr + (i * sizeOfCryptAttributeString)); var attribute = MarshalUtility.PtrToStructure <CRYPT_ATTRIBUTE_STRING>(attributePointer); if (!string.Equals(attribute.pszObjId, Oids.Countersignature, StringComparison.Ordinal)) { continue; } for (var j = 0; j < attribute.cValue; ++j) { var attributeValuePointer = new IntPtr( (long)attribute.rgValue + (j * sizeOfCryptIntegerBlob)); var attributeValue = MarshalUtility.PtrToStructure <CRYPT_INTEGER_BLOB>(attributeValuePointer); uint cbSignerInfo = 0; NativeUtility.ThrowIfFailed(NativeMethods.CryptDecodeObject( CMSG_ENCODING.Any, new IntPtr(NativeMethods.PKCS7_SIGNER_INFO), attributeValue.pbData, attributeValue.cbData, dwFlags: 0, pvStructInfo: IntPtr.Zero, pcbStructInfo: new IntPtr(&cbSignerInfo))); var counterSignerInfoPointer = retainer.Alloc((int)cbSignerInfo); NativeUtility.ThrowIfFailed(NativeMethods.CryptDecodeObject( CMSG_ENCODING.Any, new IntPtr(NativeMethods.PKCS7_SIGNER_INFO), attributeValue.pbData, attributeValue.cbData, dwFlags: 0, pvStructInfo: counterSignerInfoPointer, pcbStructInfo: new IntPtr(&cbSignerInfo))); var counterSignerInfo = MarshalUtility.PtrToStructure <CMSG_SIGNER_INFO>(counterSignerInfoPointer); if (IsRepositoryCounterSignerInfo(counterSignerInfo)) { return(new RepositoryCounterSignerInfo() { dwUnauthAttrIndex = i, UnauthAttr = attribute, SignerInfo = counterSignerInfo }); } } } return(null); }
// Reads native process info from a 64-bit process in the case where this function is executing // in a 32-bit process. private bool LoadProcessInfoWow64(SafeProcessHandle handle, ProcessAccessFlags flags) { ulong pebSize = (ulong)MarshalUtility.UnmanagedStructSize <PebWow64>(); ulong processParamsSize = (ulong)MarshalUtility.UnmanagedStructSize <RtlUserProcessParametersWow64>(); // Read PROCESS_BASIC_INFORMATION up to and including the pointer to PEB structure. int processInfoSize = MarshalUtility.UnmanagedStructSize <ProcessBasicInformationWow64>(); ProcessBasicInformationWow64 pbi = new ProcessBasicInformationWow64(); int result = NativeMethods.NtWow64QueryInformationProcess64( handle, ProcessInfoClass.BasicInformation, ref pbi, processInfoSize, out processInfoSize); if (result != 0) { return(false); } _parentProcessId = (int)pbi.ParentProcessId; Debug.Assert((int)pbi.UniqueProcessId == _processId); if (flags.HasFlag(ProcessAccessFlags.VmRead)) { IntPtr pebBuffer = IntPtr.Zero; IntPtr processParametersBuffer = IntPtr.Zero; IntPtr commandLineBuffer = IntPtr.Zero; try { pebBuffer = Marshal.AllocHGlobal((int)pebSize); // Read PEB up to and including the pointer to RTL_USER_PROCESS_PARAMETERS // structure. result = NativeMethods.NtWow64ReadVirtualMemory64( handle, pbi.PebBaseAddress, pebBuffer, pebSize, out pebSize); if (result != 0) { return(false); } PebWow64 peb = (PebWow64)Marshal.PtrToStructure(pebBuffer, typeof(PebWow64)); _isBeingDebugged = peb.IsBeingDebugged; processParametersBuffer = Marshal.AllocHGlobal((int)processParamsSize); result = NativeMethods.NtWow64ReadVirtualMemory64( handle, peb.ProcessParameters, processParametersBuffer, processParamsSize, out processParamsSize); if (result != 0) { return(false); } RtlUserProcessParametersWow64 processParameters = (RtlUserProcessParametersWow64) Marshal.PtrToStructure( processParametersBuffer, typeof(RtlUserProcessParametersWow64)); ulong commandLineBufferSize = (ulong)processParameters.CommandLine.MaximumLength; commandLineBuffer = Marshal.AllocHGlobal((int)commandLineBufferSize); result = NativeMethods.NtWow64ReadVirtualMemory64( handle, processParameters.CommandLine.Buffer, commandLineBuffer, commandLineBufferSize, out commandLineBufferSize); if (result != 0) { return(false); } _commandLine = Marshal.PtrToStringUni(commandLineBuffer); } finally { if (pebBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(pebBuffer); } if (commandLineBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(commandLineBuffer); } if (processParametersBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(processParametersBuffer); } } } return(true); }