public void TestMessage() { // skip escape sequence var res = OpenResource("capture.bin", 8); var marshal = new Marshal(res); var message = marshal.Read<Message>(); Assert.AreEqual(0xd6da, message.CRC16); }
internal static ValidateAuthTicketResponse_t Fill(IntPtr p) { return (ValidateAuthTicketResponse_t)Marshal.PtrToStructure(p, typeof(ValidateAuthTicketResponse_t)); }
public static void CreateDirectory(string fullPath) { // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) { return; } List <string> stackDir = new List <string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) { length--; } int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing { stackDir.Add(dir); } else { somepathexists = true; } while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) { i--; } i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default; bool r = true; int firstError = 0; string errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { string name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) { firstError = currentError; } else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) { throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); } return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) { throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } }
internal static IPHostEntry NativeToHostEntry(IntPtr nativePointer) { #endif // // marshal pointer to struct // hostent Host = (hostent)Marshal.PtrToStructure(nativePointer, typeof(hostent)); IPHostEntry HostEntry = new IPHostEntry(); if (Host.h_name != IntPtr.Zero) { HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name); GlobalLog.Print("HostEntry.HostName: " + HostEntry.HostName); } // decode h_addr_list to ArrayList of IP addresses. // The h_addr_list field is really a pointer to an array of pointers // to IP addresses. Loop through the array, and while the pointer // isn't NULL read the IP address, convert it to an IPAddress class, // and add it to the list. ArrayList TempList = new ArrayList(); int IPAddressToAdd; string AliasToAdd; IntPtr currentArrayElement; // // get the first pointer in the array // currentArrayElement = Host.h_addr_list; nativePointer = Marshal.ReadIntPtr(currentArrayElement); while (nativePointer != IntPtr.Zero) { // // if it's not null it points to an IPAddress, // read it... // IPAddressToAdd = Marshal.ReadInt32(nativePointer); #if BIGENDIAN // IP addresses from native code are always a byte array // converted to int. We need to convert the address into // a uniform integer value. IPAddressToAdd = (int)( ((uint)IPAddressToAdd << 24) | (((uint)IPAddressToAdd & 0x0000FF00) << 8) | (((uint)IPAddressToAdd >> 8) & 0x0000FF00) | ((uint)IPAddressToAdd >> 24) ); #endif GlobalLog.Print("currentArrayElement: " + currentArrayElement.ToString() + " nativePointer: " + nativePointer.ToString() + " IPAddressToAdd:" + IPAddressToAdd.ToString()); // // ...and add it to the list // TempList.Add(new IPAddress(IPAddressToAdd)); // // now get the next pointer in the array and start over // currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size); nativePointer = Marshal.ReadIntPtr(currentArrayElement); } HostEntry.AddressList = new IPAddress[TempList.Count]; TempList.CopyTo(HostEntry.AddressList, 0); // // Now do the same thing for the aliases. // TempList.Clear(); currentArrayElement = Host.h_aliases; nativePointer = Marshal.ReadIntPtr(currentArrayElement); while (nativePointer != IntPtr.Zero) { GlobalLog.Print("currentArrayElement: " + ((long)currentArrayElement).ToString() + "nativePointer: " + ((long)nativePointer).ToString()); // // if it's not null it points to an Alias, // read it... // AliasToAdd = Marshal.PtrToStringAnsi(nativePointer); // // ...and add it to the list // TempList.Add(AliasToAdd); // // now get the next pointer in the array and start over // currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size); nativePointer = Marshal.ReadIntPtr(currentArrayElement); } HostEntry.Aliases = new string[TempList.Count]; TempList.CopyTo(HostEntry.Aliases, 0); return HostEntry; } // NativeToHostEntry
private unsafe static SocketError TryGetAddrInfo(string name, AddressInfoHints flags, out IPHostEntry hostinfo) { // // Use SocketException here to show operation not supported // if, by some nefarious means, this method is called on an // unsupported platform. // #if FEATURE_PAL throw new SocketException(SocketError.OperationNotSupported); #else SafeFreeAddrInfo root = null; ArrayList addresses = new ArrayList(); string canonicalname = null; AddressInfo hints = new AddressInfo(); hints.ai_flags = flags; hints.ai_family = AddressFamily.Unspecified; // gets all address families // // Use try / finally so we always get a shot at freeaddrinfo // try { SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root); if (errorCode != SocketError.Success) { // Should not throw, return mostly blank hostentry hostinfo = new IPHostEntry(); hostinfo.HostName = name; hostinfo.Aliases = new string[0]; hostinfo.AddressList = new IPAddress[0]; return errorCode; } AddressInfo* pAddressInfo = (AddressInfo*)root.DangerousGetHandle(); // // Process the results // while (pAddressInfo!=null) { SocketAddress sockaddr; // // Retrieve the canonical name for the host - only appears in the first AddressInfo // entry in the returned array. // if (canonicalname==null && pAddressInfo->ai_canonname!=null) { canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname); } // // Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll // ever get any other address families, but better to be safe than sorry. // We also filter based on whether IPv6 is supported on the current // platform / machine. // if ( ( pAddressInfo->ai_family == AddressFamily.InterNetwork ) || // Never filter v4 (pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6)) { sockaddr = new SocketAddress(pAddressInfo->ai_family, pAddressInfo->ai_addrlen); // // Push address data into the socket address buffer // for (int d = 0; d < pAddressInfo->ai_addrlen; d++) { sockaddr.m_Buffer[d] = *(pAddressInfo->ai_addr + d); } // // NOTE: We need an IPAddress now, the only way to create it from a // SocketAddress is via IPEndPoint. This ought to be simpler. // if ( pAddressInfo->ai_family == AddressFamily.InterNetwork ) { addresses.Add( ((IPEndPoint)IPEndPoint.Any.Create(sockaddr)).Address ); } else { addresses.Add( ((IPEndPoint)IPEndPoint.IPv6Any.Create(sockaddr)).Address ); } } // // Next addressinfo entry // pAddressInfo = pAddressInfo->ai_next; } } finally { if (root != null) { root.Close(); } } // // Finally, put together the IPHostEntry // hostinfo = new IPHostEntry(); hostinfo.HostName = canonicalname!=null ? canonicalname : name; hostinfo.Aliases = new string[0]; hostinfo.AddressList = new IPAddress[addresses.Count]; addresses.CopyTo(hostinfo.AddressList); return SocketError.Success; #endif // FEATURE_PAL }
public void ReplyToHostCredentialRequest(byte[] message) { if (client == null) return; Console.WriteLine($"ReplyToHostCredentialRequest ThreadID = {Thread.CurrentThread.ManagedThreadId}"); Int32 Loc = 0; try { //We will assume to tell the host this is just an update of the //credentials we first sent during the application start. This //will be true if the 'message' argument is null, otherwise we //will change the packet type below to the 'TYPE_MyCredentials'. UInt16 PaketType = (UInt16)PACKETTYPES.TYPE_CredentialsUpdate; if (message != null) { int myOldServerID = 0; //The host server has past my ID. PACKET_DATA IncomingData = new PACKET_DATA(); IncomingData = (PACKET_DATA)PACKET_FUNCTIONS.ByteArrayToStructure(message, typeof(PACKET_DATA)); Loc = 10; if (MyHostServerID > 0) myOldServerID = MyHostServerID; Loc = 20; MyHostServerID = (int)IncomingData.idTo;//Hang onto this value Loc = 25; Console.WriteLine($"My Host Server ID is {MyHostServerID}"); string MyAddressAsSeenByTheHost = new string(IncomingData.szStringDataA).TrimEnd('\0');//My computer address SetSomeLabelInfoFromThread($"My Address As Seen By The Server: {MyAddressAsSeenByTheHost}, and my ID given by the server is: {MyHostServerID}"); ServerTime = IncomingData.DataLong1; PaketType = (UInt16)PACKETTYPES.TYPE_MyCredentials; } //ods.DebugOut("Send Host Server some info about myself"); PACKET_DATA xdata = new PACKET_DATA(); xdata.Packet_Type = PaketType; xdata.Data_Type = 0; xdata.Packet_Size = (UInt16)Marshal.SizeOf(typeof(PACKET_DATA)); xdata.maskTo = 0; xdata.idTo = 0; xdata.idFrom = 0; //Station Name string p = System.Environment.MachineName; if (p.Length > (xdata.szStringDataA.Length - 1)) p.CopyTo(0, xdata.szStringDataA, 0, (xdata.szStringDataA.Length - 1)); else p.CopyTo(0, xdata.szStringDataA, 0, p.Length); xdata.szStringDataA[(xdata.szStringDataA.Length - 1)] = '\0';//cap it off just incase //App and DLL Version string VersionNumber = string.Empty; VersionNumber = Assembly.GetEntryAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetEntryAssembly().GetName().Version.Minor.ToString() + "." + Assembly.GetEntryAssembly().GetName().Version.Build.ToString(); Loc = 30; VersionNumber.CopyTo(0, xdata.szStringDataB, 0, VersionNumber.Length); Loc = 40; //Station Name string L = textBoxClientName.Text; if (L.Length > (xdata.szStringData150.Length - 1)) L.CopyTo(0, xdata.szStringData150, 0, (xdata.szStringData150.Length - 1)); else L.CopyTo(0, xdata.szStringData150, 0, L.Length); xdata.szStringData150[(xdata.szStringData150.Length - 1)] = '\0';//cap it off just incase Loc = 50; //Application type xdata.nAppLevel = (UInt16)APPLEVEL.None; byte[] byData = PACKET_FUNCTIONS.StructureToByteArray(xdata); Loc = 60; SendMessageToServer(byData); Loc = 70; } catch (Exception ex) { string exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message; Console.WriteLine($"EXCEPTION at location {Loc}, IN: ReplyToHostCredentialRequest - {exceptionMessage}"); } }
private static unsafe MemoryInfoResult GetMemoryInfoWindows(Process process, bool extended) { // windows var memoryStatus = new MemoryStatusEx { dwLength = (uint)sizeof(MemoryStatusEx) }; if (GlobalMemoryStatusEx(&memoryStatus) == false) { if (Logger.IsInfoEnabled) { Logger.Info("Failure when trying to read memory info from Windows, error code is: " + Marshal.GetLastWin32Error()); } return(FailedResult); } // The amount of physical memory retrieved by the GetPhysicallyInstalledSystemMemory function // must be equal to or greater than the amount reported by the GlobalMemoryStatusEx function // if it is less, the SMBIOS data is malformed and the function fails with ERROR_INVALID_DATA. // Malformed SMBIOS data may indicate a problem with the user's computer. var fetchedInstalledMemory = GetPhysicallyInstalledSystemMemory(out var installedMemoryInKb); var sharedClean = GetSharedCleanInBytes(process); SetMemoryRecords((long)memoryStatus.ullAvailPhys); return(new MemoryInfoResult { TotalCommittableMemory = new Size((long)memoryStatus.ullTotalPageFile, SizeUnit.Bytes), CurrentCommitCharge = new Size((long)(memoryStatus.ullTotalPageFile - memoryStatus.ullAvailPageFile), SizeUnit.Bytes), AvailableMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes), AvailableWithoutTotalCleanMemory = new Size((long)memoryStatus.ullAvailPhys + sharedClean, SizeUnit.Bytes), SharedCleanMemory = new Size(sharedClean, SizeUnit.Bytes), TotalPhysicalMemory = new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes), InstalledMemory = fetchedInstalledMemory ? new Size(installedMemoryInKb, SizeUnit.Kilobytes) : new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes), WorkingSet = new Size(process?.WorkingSet64 ?? 0, SizeUnit.Bytes), IsExtended = extended }); }
private static void DownloadCompletedCallbackDelegate(IntPtr app, IntPtr version, IntPtr downloadedFile){ if(_mIRegisterUpdaterEventListener != null) _mIRegisterUpdaterEventListener.DownloadCompletedCallback(Marshal.PtrToStringAnsi(version), Marshal.PtrToStringAnsi(downloadedFile)); }
public static string GetJoystickName(Joystick joy) { var ptr = glfwGetJoystickName((int)joy); return Marshal.PtrToStringAnsi(ptr); }
public static void SetScrollCallback(Window window, CursorPosFunc callback) { var ptr = Marshal.GetFunctionPointerForDelegate(callback); glfwSetScrollCallback(window.Ptr, ptr); GC.KeepAlive(callback); }
public static void SetCharModsCallback(Window window, CharModFunc callback) { var ptr = Marshal.GetFunctionPointerForDelegate(callback); glfwSetCharModsCallback(window.Ptr, ptr); GC.KeepAlive(callback); }
/// <summary> /// Returns up to maxEncodings codepages that are assumed to be apropriate /// </summary> /// <param name="input">array containing the raw data</param> /// <param name="maxEncodings">maxiumum number of encodings to detect</param> /// <returns>an array of Encoding with assumed encodings</returns> public static Encoding[] DetectInputCodepages(byte[] input, int maxEncodings) { if (maxEncodings < 1) throw new ArgumentOutOfRangeException("maxEncodings", "at least one encoding must be returned"); if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return new Encoding[] { Encoding.ASCII }; // expand the string to be at least 256 bytes if (input.Length < 256) { byte[] newInput = new byte[256]; int steps = 256 / input.Length; for (int i = 0; i < steps; i++) Array.Copy(input, 0, newInput, input.Length * i, input.Length); int rest = 256 % input.Length; if (rest > 0) Array.Copy(input, 0, newInput, steps * input.Length, rest); input = newInput; } List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage" interface IMultiLanguage2 multilang2 = new CMultiLanguageClass(); if (multilang2 == null) throw new COMException("Failed to get IMultilang2"); try { DetectEncodingInfo[] detectedEncdings = new DetectEncodingInfo[maxEncodings]; int scores = detectedEncdings.Length; int srcLen = input.Length; // setup options (none) const MLDETECTCP options = MLDETECTCP.MLDETECTCP_NONE; // finally... call to DetectInputCodepage multilang2.DetectInputCodepage(options, 0, ref input[0], ref srcLen, ref detectedEncdings[0], ref scores); // get result if (scores > 0) { for (int i = 0; i < scores; i++) { // add the result result.Add(Encoding.GetEncoding((int)detectedEncdings[i].nCodePage)); } } } finally { Marshal.FinalReleaseComObject(multilang2); } // nothing found return result.ToArray(); }
public static Encoding[] DetectOutgoingEncodings(string input, int[] preferredEncodings, bool preserveOrder) { if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return new Encoding[] { Encoding.ASCII }; List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage3 interface IMultiLanguage3 multilang3 = new CMultiLanguageClass(); if (multilang3 == null) throw new COMException("Failed to get IMultilang3"); try { int[] resultCodePages = new int[preferredEncodings.Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = Marshal.AllocCoTaskMem(sizeof(uint) * preferredEncodings.Length); IntPtr pDetectedEncs = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { Marshal.Copy(preferredEncodings, 0, pPrefEncs, preferredEncodings.Length); Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MLCPF options = MLCPF.MLDETECTF_VALID_NLS | MLCPF.MLDETECTF_PREFERRED_ONLY; if (preserveOrder) options |= MLCPF.MLDETECTF_PRESERVE_ORDER; options |= MLCPF.MLDETECTF_PREFERRED_ONLY; // finally... call to DetectOutboundCodePage multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)preferredEncodings.Length, pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); // get the encodings for the codepages for (int i = 0; i < detectedCodepages; i++) result.Add(Encoding.GetEncoding(theResult[i])); } } finally { if (pPrefEncs != IntPtr.Zero) Marshal.FreeCoTaskMem(pPrefEncs); Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } // nothing found return result.ToArray(); }
private static Encoding DetectOutgoingEncoding(string input, int[] preferredEncodings, bool preserveOrder) { if (input == null) throw new ArgumentNullException("input"); // empty strings can always be encoded as ASCII if (input.Length == 0) return Encoding.ASCII; Encoding result = Encoding.ASCII; // get the IMultiLanguage3 interface IMultiLanguage3 multilang3 = new CMultiLanguageClass(); if (multilang3 == null) throw new COMException("Failed to get IMultilang3"); try { int[] resultCodePages = new int[preferredEncodings != null ? preferredEncodings.Length : Encoding.GetEncodings().Length]; uint detectedCodepages = (uint)resultCodePages.Length; ushort specialChar = (ushort)'?'; // get unmanaged arrays IntPtr pPrefEncs = preferredEncodings == null ? IntPtr.Zero : Marshal.AllocCoTaskMem(sizeof(uint) * preferredEncodings.Length); IntPtr pDetectedEncs = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (preferredEncodings != null) Marshal.Copy(preferredEncodings, 0, pPrefEncs, preferredEncodings.Length); Marshal.Copy(resultCodePages, 0, pDetectedEncs, resultCodePages.Length); MLCPF options = MLCPF.MLDETECTF_VALID_NLS; if (preserveOrder) options |= MLCPF.MLDETECTF_PRESERVE_ORDER; if (preferredEncodings != null) options |= MLCPF.MLDETECTF_PREFERRED_ONLY; multilang3.DetectOutboundCodePage(options, input, (uint)input.Length, pPrefEncs, (uint)(preferredEncodings == null ? 0 : preferredEncodings.Length), pDetectedEncs, ref detectedCodepages, ref specialChar); // get result if (detectedCodepages > 0) { int[] theResult = new int[detectedCodepages]; Marshal.Copy(pDetectedEncs, theResult, 0, theResult.Length); result = Encoding.GetEncoding(theResult[0]); } } finally { if (pPrefEncs != IntPtr.Zero) Marshal.FreeCoTaskMem(pPrefEncs); Marshal.FreeCoTaskMem(pDetectedEncs); } } finally { Marshal.FinalReleaseComObject(multilang3); } return result; }
//重设代理地址 public void RefreshIESettings(string strProxy) { const int INTERNET_OPTION_PROXY = 38; const int INTERNET_OPEN_TYPE_PROXY = 3; Struct_INTERNET_PROXY_INFO struct_IPI; // Filling in structure struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY; struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy); struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local"); // Allocating memory IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)); // Converting structure to IntPtr Marshal.StructureToPtr(struct_IPI, intptrStruct, true); bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI)); }
public OctetsStream unmarshal(Marshal m) { return m.unmarshal(this); }
// TODO: Support extended public bool Create(string path, MediaType mediaType, Dictionary<string, string> options, ulong sectors, uint sectorSize) { if(sectorSize != 512) { ErrorMessage = "Unsupported sector size"; return false; } if(!SupportedMediaTypes.Contains(mediaType)) { ErrorMessage = $"Unsupported media format {mediaType}"; return false; } if((sectors * sectorSize) / DEFAULT_CLUSTER_SIZE > uint.MaxValue) { ErrorMessage = "Too many sectors for selected cluster size"; return false; } _imageInfo = new ImageInfo { MediaType = mediaType, SectorSize = sectorSize, Sectors = sectors }; try { _writingStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch(IOException e) { ErrorMessage = $"Could not create new image file, exception {e.Message}"; return false; } uint batEntries = (uint)((sectors * sectorSize) / DEFAULT_CLUSTER_SIZE); if((sectors * sectorSize) % DEFAULT_CLUSTER_SIZE > 0) batEntries++; uint headerSectors = (uint)Marshal.SizeOf<Header>() + (batEntries * 4); if((uint)Marshal.SizeOf<Header>() + (batEntries % 4) > 0) headerSectors++; _pHdr = new Header { magic = _magic, version = PARALLELS_VERSION, sectors = sectors, in_use = PARALLELS_CLOSED, bat_entries = batEntries, data_off = headerSectors, cluster_size = DEFAULT_CLUSTER_SIZE / 512 }; _bat = new uint[batEntries]; _currentWritingPosition = headerSectors * 512; IsWriting = true; ErrorMessage = null; return true; }
public static string GetClipboardString(Window window) { var ptr = glfwGetClipboardString(window.Ptr); return Marshal.PtrToStringAnsi(ptr); }
private static unsafe MemoryInfoResult GetMemoryInfoMacOs(Process process, bool extended) { var mib = new[] { (int)TopLevelIdentifiers.CTL_HW, (int)CtkHwIdentifiers.HW_MEMSIZE }; ulong physicalMemory = 0; var len = sizeof(ulong); if (macSyscall.sysctl(mib, 2, &physicalMemory, &len, null, UIntPtr.Zero) != 0) { if (Logger.IsInfoEnabled) { Logger.Info("Failure when trying to read physical memory info from MacOS, error code was: " + Marshal.GetLastWin32Error()); } return(FailedResult); } uint pageSize; var vmStats = new vm_statistics64(); var machPort = macSyscall.mach_host_self(); var count = sizeof(vm_statistics64) / sizeof(uint); if (macSyscall.host_page_size(machPort, &pageSize) != 0 || macSyscall.host_statistics64(machPort, (int)Flavor.HOST_VM_INFO64, &vmStats, &count) != 0) { if (Logger.IsInfoEnabled) { Logger.Info("Failure when trying to get vm_stats from MacOS, error code was: " + Marshal.GetLastWin32Error()); } return(FailedResult); } // swap usage var swapu = new xsw_usage(); len = sizeof(xsw_usage); mib = new[] { (int)TopLevelIdentifiers.CTL_VM, (int)CtlVmIdentifiers.VM_SWAPUSAGE }; if (macSyscall.sysctl(mib, 2, &swapu, &len, null, UIntPtr.Zero) != 0) { if (Logger.IsInfoEnabled) { Logger.Info("Failure when trying to read swap info from MacOS, error code was: " + Marshal.GetLastWin32Error()); } return(FailedResult); } var totalPhysicalMemory = new Size((long)physicalMemory, SizeUnit.Bytes); /* Free memory: This is RAM that's not being used. * Wired memory: Information in this memory can't be moved to the hard disk, so it must stay in RAM. The amount of Wired memory depends on the applications you are using. * Active memory: This information is currently in memory, and has been recently used. * Inactive memory: This information in memory is not actively being used, but was recently used. */ var availableRamInBytes = new Size((vmStats.FreePagesCount + vmStats.InactivePagesCount) * pageSize, SizeUnit.Bytes); // there is no commited memory value in OSX, // this is an approximation: wired + active + swap used var commitedMemoryInBytes = (vmStats.WirePagesCount + vmStats.ActivePagesCount) * pageSize + (long)swapu.xsu_used; var commitedMemory = new Size(commitedMemoryInBytes, SizeUnit.Bytes); // commit limit: physical memory + swap var commitLimit = new Size((long)(physicalMemory + swapu.xsu_total), SizeUnit.Bytes); var availableWithoutTotalCleanMemory = availableRamInBytes; // mac (unlike other linux distros) does calculate accurate available memory var workingSet = new Size(process?.WorkingSet64 ?? 0, SizeUnit.Bytes); return(BuildPosixMemoryInfoResult(availableRamInBytes, totalPhysicalMemory, commitedMemory, commitLimit, availableWithoutTotalCleanMemory, Size.Zero, workingSet, extended)); }
public static unsafe string GetVersionString() { IntPtr version = glfwGetVersionString(); return Marshal.PtrToStringAnsi(version); }
private async Task <List <PdbSymbol> > GetPdbSymbols() { var pdbSymbols = new List <PdbSymbol>(); await DownloadPdb(); // Read the PDB header var pdbBufferHandle = GCHandle.Alloc(File.ReadAllBytes(_pdbPath), GCHandleType.Pinned); var pdbBuffer = pdbBufferHandle.AddrOfPinnedObject(); var pdbHeader = Marshal.PtrToStructure <PdbHeader>(pdbBuffer); // Determine the amount of streams in the PDB var rootPageNumber = Marshal.PtrToStructure <uint>(pdbBuffer.AddOffset(pdbHeader.PageSize * pdbHeader.RootStreamPageNumberListNumber)); var rootStream = Marshal.PtrToStructure <uint>(pdbBuffer.AddOffset(pdbHeader.PageSize * rootPageNumber)); var streams = new List <List <uint> >(); var pageNumber = 0; for (var streamIndex = 0; streamIndex < rootStream; streamIndex += 1) { // Calculate the amount of pages in the stream var streamSize = Marshal.PtrToStructure <uint>(pdbBuffer.AddOffset(pdbHeader.PageSize * rootPageNumber + sizeof(uint) + sizeof(uint) * streamIndex)); var pagesNeeded = streamSize / pdbHeader.PageSize; if (streamSize % pdbHeader.PageSize != 0) { pagesNeeded += 1; } var streamPages = new List <uint>(); for (var pageIndex = 0; pageIndex < pagesNeeded; pageIndex += 1) { // Read the page of the stream streamPages.Add(Marshal.PtrToStructure <uint>(pdbBuffer.AddOffset(pdbHeader.PageSize * rootPageNumber + sizeof(uint) + (rootStream + pageNumber) * sizeof(uint)))); pageNumber += 1; } streams.Add(streamPages); } // Read the DBI header var dbiStreamOffset = pdbHeader.PageSize * streams[3][0]; var dbiHeader = Marshal.PtrToStructure <DbiHeader>(pdbBuffer.AddOffset(dbiStreamOffset)); // Get the symbol stream var symbolStream = new byte[pdbHeader.PageSize * streams[dbiHeader.SymbolStreamIndex].Count]; for (var pageIndex = 0; pageIndex < streams[dbiHeader.SymbolStreamIndex].Count; pageIndex += 1) { Marshal.Copy(pdbBuffer.AddOffset(pdbHeader.PageSize * streams[dbiHeader.SymbolStreamIndex][pageIndex]), symbolStream, (int)pdbHeader.PageSize * pageIndex, (int)pdbHeader.PageSize); } pdbBufferHandle.Free(); var symbolStreamBufferHandle = GCHandle.Alloc(symbolStream, GCHandleType.Pinned); var symbolStreamBuffer = symbolStreamBufferHandle.AddrOfPinnedObject(); while (true) { // Read the name of the symbol var symbolData = Marshal.PtrToStructure <SymbolData>(symbolStreamBuffer); if (symbolData.Magic != SymbolMagic) { break; } var symbolName = Marshal.PtrToStringAnsi(symbolStreamBuffer.AddOffset(Marshal.SizeOf <SymbolData>())); pdbSymbols.Add(new PdbSymbol(symbolName, symbolData.Offset, symbolData.Section)); // Calculate the address of the next symbol symbolStreamBuffer += symbolData.Length + sizeof(ushort); } symbolStreamBufferHandle.Free(); return(pdbSymbols); }
public static void SetErrorCallback(ErrorFunc callback) { errorFunc = callback; glfwSetErrorCallback(Marshal.GetFunctionPointerForDelegate(callback)); GC.KeepAlive(callback); }
public static void IsBlittableTest() { Assert.That(Marshal.SizeOf <D3D12_PARAMETER_DESC>(), Is.EqualTo(sizeof(D3D12_PARAMETER_DESC))); }
public static unsafe string GetMonitortName(Monitor monitor) { IntPtr name = glfwGetMonitorName(monitor.Ptr); return Marshal.PtrToStringAnsi(name); }
} // GetHostByAddress // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). // Legacy methods do not include IPv6, unless configed to by Socket.LegacySupportsIPv6 and Socket.OSSupportsIPv6. internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString()); // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // SocketError errorCode = SocketError.Success; Exception exception = null; if ( Socket.LegacySupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. string name = TryGetNameInfo(address, out errorCode); if(errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = TryGetAddrInfo(name, out hostEntry); if (errorCode == SocketError.Success) return hostEntry; // Log failure if (Logging.On) Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", new SocketException(errorCode)); // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return hostEntry; } exception = new SocketException(errorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if ( address.AddressFamily == AddressFamily.InterNetworkV6 ) { // // Protocol not supported // throw new SocketException(SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // int addressAsInt = unchecked((int)address.m_Address); #if BIGENDIAN addressAsInt = (int)( ((uint)addressAsInt << 24) | (((uint)addressAsInt & 0x0000FF00) << 8) | (((uint)addressAsInt >> 8) & 0x0000FF00) | ((uint)addressAsInt >> 24) ); #endif IntPtr nativePointer = UnsafeNclNativeMethods.OSSOCK.gethostbyaddr( ref addressAsInt, Marshal.SizeOf(typeof(int)), ProtocolFamily.InterNetwork); if (nativePointer != IntPtr.Zero) { return NativeToHostEntry(nativePointer); } exception = new SocketException(); } if (Logging.On) Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", exception); throw exception; } // InternalGetHostByAddress
public static void SetMonitorCallback(MonitorFunc callback) { glfwSetMonitorCallback(Marshal.GetFunctionPointerForDelegate(callback)); GC.KeepAlive(callback); }
private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel32.WIN32_FIND_DATA findData, bool topLevel) { int errorCode; Exception exception = null; using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref findData)) { if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } do { if ((findData.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0) { // File string fileName = findData.cFileName.GetStringFromFixedBuffer(); if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); // We don't care if something else deleted the file first if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } else { // Directory, skip ".", "..". if (findData.cFileName.FixedBufferEqualsString(".") || findData.cFileName.FixedBufferEqualsString("..")) { continue; } string fileName = findData.cFileName.GetStringFromFixedBuffer(); if ((findData.dwFileAttributes & (int)FileAttributes.ReparsePoint) == 0) { // Not a reparse point, recurse. try { RemoveDirectoryRecursive( Path.Combine(fullPath, fileName), findData: ref findData, topLevel: false); } catch (Exception e) { if (exception == null) { exception = e; } } } else { // Reparse point, don't recurse, just remove. (dwReserved0 is documented for this flag) if (findData.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Mount point. Unmount using full path plus a trailing '\'. // (Note: This doesn't remove the underlying directory) string mountPoint = Path.Combine(fullPath, fileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } // Note that RemoveDirectory on a symbolic link will remove the link itself. if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } } } while (Interop.Kernel32.FindNextFile(handle, ref findData)); if (exception != null) { throw exception; } errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) { throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } // As we successfully removed all of the files we shouldn't care about the directory itself // not being empty. As file deletion is just a marker to remove the file when all handles // are closed we could still have contents hanging around. RemoveDirectoryInternal(fullPath, topLevel: topLevel, allowDirectoryNotEmpty: true); }
public static VideoMode GetVideoMode(Monitor monitor) { var ptr = glfwGetVideoMode(monitor.Ptr); return (VideoMode)Marshal.PtrToStructure(ptr, typeof(VideoMode)); }
static ValidateAuthTicketResponse_t() { ValidateAuthTicketResponse_t.StructSize = Marshal.SizeOf(typeof(ValidateAuthTicketResponse_t)); }
public static void SetWindowIconifyCallback(Window window, WindowBoolFunc callback) { var ptr = Marshal.GetFunctionPointerForDelegate(callback); glfwSetWindowIconifyCallback(window.Ptr, ptr); GC.KeepAlive(callback); }
private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed) { if (sourceSids == null) { throw new ArgumentNullException(nameof(sourceSids)); } if (sourceSids.Count == 0) { throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids)); } Contract.EndContractBlock(); IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count]; GCHandle[] HandleArray = new GCHandle[sourceSids.Count]; SafeLsaPolicyHandle LsaHandle = SafeLsaPolicyHandle.InvalidHandle; SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle; SafeLsaMemoryHandle NamesPtr = SafeLsaMemoryHandle.InvalidHandle; try { // // Pin all elements in the array of SIDs // int currentSid = 0; foreach (IdentityReference id in sourceSids) { SecurityIdentifier sid = id as SecurityIdentifier; if (sid == null) { throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids)); } HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned); SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject(); currentSid++; } // // Open LSA policy (for lookup requires it) // LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES); // // Perform the actual lookup // someFailed = false; uint ReturnCode; ReturnCode = Interop.mincore.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, ref ReferencedDomainsPtr, ref NamesPtr); // // Make a decision regarding whether it makes sense to proceed // based on the return code and the value of the forceSuccess argument // if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY || ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES) { throw new OutOfMemoryException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { someFailed = true; } else if (ReturnCode != 0) { int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode)); Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode)); throw new Win32Exception(win32ErrorCode); } NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>()); Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr); // // Interpret the results and generate NTAccount objects // IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count); if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED) { // // Interpret the results and generate NT Account objects // Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); string[] ReferencedDomains = new string[rdl.Entries]; for (int i = 0; i < rdl.Entries; i++) { Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>())); ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char)); } Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count]; NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length); for (int i = 0; i < sourceSids.Count; i++) { Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i]; switch ((SidNameUse)Ltn.Use) { case SidNameUse.User: case SidNameUse.Group: case SidNameUse.Alias: case SidNameUse.Computer: case SidNameUse.WellKnownGroup: string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ; string domain = ReferencedDomains[Ltn.DomainIndex]; Result.Add(new NTAccount(domain, account)); break; default: someFailed = true; Result.Add(sourceSids[i]); break; } } } else { for (int i = 0; i < sourceSids.Count; i++) { Result.Add(sourceSids[i]); } } return Result; } finally { for (int i = 0; i < sourceSids.Count; i++) { if (HandleArray[i].IsAllocated) { HandleArray[i].Free(); } } LsaHandle.Dispose(); ReferencedDomainsPtr.Dispose(); NamesPtr.Dispose(); } }
public static void SetFramebufferSizeCallback(Window window, WindowSizeFunc callback) { var ptr = Marshal.GetFunctionPointerForDelegate(callback); glfwSetFramebufferSizeCallback(window.Ptr, ptr); GC.KeepAlive(callback); }