public static void GainMemoryAccess(IntPtr address, ulong len) { SYSTEM_INFO si = new SYSTEM_INFO(); GetSystemInfo(out si); MEMORY_BASIC_INFORMATION mbi; ulong currentAddress = RoundUpToPageBoundary((ulong)address, si.pageSize); ulong endAddress = currentAddress + len; uint ret; uint oldProtect = 0; while (currentAddress < endAddress) { mbi = new MEMORY_BASIC_INFORMATION(); ret = (uint)VirtualQuery((IntPtr)currentAddress, out mbi, (IntPtr)Marshal.SizeOf(mbi)); if (ret != 0) { if (mbi.state == MEM_COMMIT) { VirtualProtect(mbi.baseAddress, mbi.regionSize, PAGE_EXECUTE_READWRITE, out oldProtect); } if ((ulong)mbi.regionSize > 0) currentAddress += (ulong)mbi.regionSize; else currentAddress += si.pageSize; } else currentAddress += si.pageSize; } }
public static Platform GetOperationSystemPlatform() { var sysInfo = new SYSTEM_INFO(); // WinXP and older - use GetNativeSystemInfo if (Environment.OSVersion.Version.Major > 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1)) { GetNativeSystemInfo(ref sysInfo); } // else use GetSystemInfo else { GetSystemInfo(ref sysInfo); } switch (sysInfo.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_IA64: case PROCESSOR_ARCHITECTURE_AMD64: return Platform.X64; case PROCESSOR_ARCHITECTURE_INTEL: return Platform.X86; default: return Platform.Unknown; } }
public static string GetProcessorArchitecture() { try { SYSTEM_INFO systemInfo = new SYSTEM_INFO(); GetNativeSystemInfo(ref systemInfo); switch (systemInfo.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: case PROCESSOR_ARCHITECTURE_IA64: return "x64"; case PROCESSOR_ARCHITECTURE_ARM: return "ARM"; case PROCESSOR_ARCHITECTURE_INTEL: return "x86"; default: return "Unknown"; } } catch { return "Unknown"; } }
public Core() { SYSTEM_INFO info = new SYSTEM_INFO(); GetSystemInfo(ref info); PAGE_SIZE = info.pageSize; //dbg //mbd //CreateDataTypesXml(); }
// finally... public static void Main() { // getting minimum & maximum address SYSTEM_INFO sys_info = new SYSTEM_INFO(); GetSystemInfo(out sys_info); IntPtr proc_min_address = sys_info.minimumApplicationAddress; IntPtr proc_max_address = sys_info.maximumApplicationAddress; // saving the values as long ints so I won't have to do a lot of casts later long proc_min_address_l = (long)proc_min_address; long proc_max_address_l = (long)proc_max_address; // notepad better be runnin' Process process = Process.GetProcessesByName("tibia")[0]; // opening the process with desired access level IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id); StreamWriter sw = new StreamWriter("dump.txt"); // this will store any information we get from VirtualQueryEx() MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION(); int bytesRead = 0; // number of bytes read with ReadProcessMemory while (proc_min_address_l < proc_max_address_l) { // 28 = sizeof(MEMORY_BASIC_INFORMATION) VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28); // if this memory chunk is accessible if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT) { byte[] buffer = new byte[mem_basic_info.RegionSize]; // read everything in the buffer above ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead); // then output this in the file for (int i = 0; i < mem_basic_info.RegionSize; i++) sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]); } // move to the next memory chunk proc_min_address_l += mem_basic_info.RegionSize; proc_min_address = new IntPtr(proc_min_address_l); } sw.Flush(); sw.Close(); Console.ReadLine(); }
internal static new void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo) { if (MonoUtility.IsLinux) { throw new ApplicationException("This method is not supported in mono"); } else { NativeMethods.GetSystemInfo(ref lpSystemInfo); } }
bool VerifyProcessorCount() { SYSTEM_INFO sysInfo = new SYSTEM_INFO(); SYSTEM_INFO.GetSystemInfo(ref sysInfo); if (Environment.ProcessorCount != sysInfo.dwNumberOfProcessors) { TestFramework.LogError("001", @"ProcessorCount not as expected. Expected (from Win32): " + sysInfo.dwNumberOfProcessors.ToString() + ", Actual (from CLR): " + Environment.ProcessorCount.ToString()); return false; } return true; }
/// <summary> /// Abstracts the retrieval of a SYSTEM_INFO structure. /// </summary> /// <param name="lpSystemInfo">A reference to a SYSTEM_INFO structure that receives the information.</param> public static void GetSystemInfoAbstracted(ref SYSTEM_INFO lpSystemInfo) { if (System.Environment.OSVersion.Version.Major > 5 || (System.Environment.OSVersion.Version.Major == 5 && System.Environment.OSVersion.Version.Minor >= 1)) { GetNativeSystemInfo(ref lpSystemInfo); } else { GetSystemInfo(ref lpSystemInfo); } }
public void Windows_ProcessorCountTest() { //arrange SYSTEM_INFO sysInfo = new SYSTEM_INFO(); GetSystemInfo(ref sysInfo); int expected = sysInfo.dwNumberOfProcessors; //act int actual = Environment.ProcessorCount; //assert Assert.True(actual > 0); Assert.Equal(expected, actual); }
public static ProcessorType GetProcessorType() { SYSTEM_INFO sysInfo = new SYSTEM_INFO(); GetNativeSystemInfo(ref sysInfo); switch (sysInfo.wProcessorArchitecture) { case PROCESSOR_TYPE_INTEL_AMD64: return ProcessorType.X64; case PROCESSOR_TYPE_INTEL: return ProcessorType.X86; default: return ProcessorType.Unknown; } }
/// <summary> /// Try to preload the library. /// This is useful when we want to have AnyCPU .NET and CPU-specific native code. /// Only available on Windows for now. /// </summary> /// <param name="libraryName">Name of the library.</param> /// <exception cref="System.InvalidOperationException"></exception> public static void PreloadLibrary(string libraryName) { #if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP var systemInfo = new SYSTEM_INFO(); GetNativeSystemInfo(out systemInfo); string cpu; if (systemInfo.processorArchitecture == PROCESSOR_ARCHITECTURE.PROCESSOR_ARCHITECTURE_ARM) cpu = "ARM"; else cpu = IntPtr.Size == 8 ? "x64" : "x86"; var libraryFilename = Path.Combine(Path.GetDirectoryName(typeof(NativeLibrary).Assembly.Location), cpu, libraryName); var result = LoadLibrary(libraryFilename); if (result == IntPtr.Zero) throw new InvalidOperationException(string.Format("Could not load native library {0} using CPU architecture {1}.", libraryName, cpu)); #endif }
public static ProcessorArchitecture GetProcessorArchitecture() { SYSTEM_INFO si = new SYSTEM_INFO(); GetNativeSystemInfo(ref si); switch (si.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: return ProcessorArchitecture.Amd64; case PROCESSOR_ARCHITECTURE_IA64: return ProcessorArchitecture.IA64; case PROCESSOR_ARCHITECTURE_INTEL: return ProcessorArchitecture.X86; default: return ProcessorArchitecture.None; // that's weird :-) } }
/// <summary> /// Try to preload the library. /// This is useful when we want to have AnyCPU .NET and CPU-specific native code. /// Only available on Windows for now. /// </summary> /// <param name="libraryName">Name of the library.</param> /// <exception cref="System.InvalidOperationException"></exception> public static void PreloadLibrary(string libraryName) { #if SILICONSTUDIO_PLATFORM_WINDOWS_DESKTOP lock (LoadedLibraries) { // If already loaded, just exit as we want to load it just once var libraryNameNormalized = libraryName.ToLowerInvariant(); if (LoadedLibraries.ContainsKey(libraryNameNormalized)) { return; } var systemInfo = new SYSTEM_INFO(); GetNativeSystemInfo(out systemInfo); string cpu; if (systemInfo.processorArchitecture == PROCESSOR_ARCHITECTURE.PROCESSOR_ARCHITECTURE_ARM) cpu = "ARM"; else cpu = IntPtr.Size == 8 ? "x64" : "x86"; // We are trying to load the dll from a shadow path if it is already registered, otherwise we use it directly from the folder var dllFolder = NativeLibraryInternal.GetShadowPathForNativeDll(libraryName) ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cpu); var libraryFilename = Path.Combine(dllFolder, libraryName); var result = LoadLibrary(libraryFilename); if (result == IntPtr.Zero) { throw new InvalidOperationException(string.Format("Could not load native library {0} from path [{1}] using CPU architecture {2}.", libraryName, libraryFilename, cpu)); } else { LoadedLibraries.Add(libraryName.ToLowerInvariant(), result); } } #endif }
public IEnumerable<MEMORY_BASIC_INFORMATION> MemoryRegions() { // getting minimum & maximum address SYSTEM_INFO sys_info = new SYSTEM_INFO(); GetSystemInfo(out sys_info); IntPtr proc_min_address = sys_info.minimumApplicationAddress; IntPtr proc_max_address = sys_info.maximumApplicationAddress; // saving the values as long ints so I won't have to do a lot of casts later long proc_min_address_l = (long)proc_min_address; long proc_max_address_l = (long)proc_max_address; MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION(); long current = proc_min_address_l; while (current < proc_max_address_l) { var informationSize = VirtualQueryEx(processHandle, (IntPtr)current, out mem_basic_info, (uint)Marshal.SizeOf(mem_basic_info)); if (informationSize == 0) throw new Win32Exception(); yield return mem_basic_info; // move to the next memory chunk current += mem_basic_info.RegionSize; } }
private static extern void GetNativeSystemInfo(out SYSTEM_INFO info);
public int availCPUCore(string filename) { int num = 0; int cpuCore = 0; cpuCore = Environment.ProcessorCount; //ManagementClass c = new ManagementClass(new ManagementPath("Win32_Processor")); //// Get the properties in the class //ManagementObjectCollection moc = c.GetInstances(); //if (moc.Count > 0) //{ // cpuCore = moc.Count; //} //else if (cpuCore <= 0) { SYSTEM_INFO pSI = new SYSTEM_INFO(); GetSystemInfo(ref pSI); cpuCore = (int)pSI.dwNumberOfProcessors; } if (cpuCore <= 0) { cpuCore = getCpuCores(); } MEMORYSTATUS memSt = new MEMORYSTATUS(); GlobalMemoryStatus(ref memSt); long availMem = (long)memSt.dwAvailPhys; Bitmap curBitmap = (Bitmap)Image.FromFile(filename); GlobalMemoryStatus(ref memSt); long availMemUsed = (long)memSt.dwAvailPhys; long usedBytePerImage = availMem - availMemUsed; long usedByte = curBitmap.Width * curBitmap.Height * 3; if (usedBytePerImage < usedByte) { usedBytePerImage = Convert.ToInt64(usedByte * 1.05); } curBitmap.Dispose(); GC.Collect(); GlobalMemoryStatus(ref memSt); availMem = (long)memSt.dwAvailPhys; //if (Convert.ToInt32(usedBytePerImage / 1024 / 1024) >= 100) // cpuCore = 1; // 每张照片在 读入过程中, 其可能使用的内存为其本身所占内存大小的 8 位左右 // 故以 8 倍来检测可能并行的 核心数 if (cpuCore * (usedBytePerImage / 1024) * 10 < availMem / 1024) { num = cpuCore; } else { for (int i = cpuCore - 1; i > 0; i--) { if (i * (usedBytePerImage / 1024) * 10 < availMem / 1024) { num = i; break; } } } if (num == 0) { num = 8; } return(num); }
private static extern void GetSystemInfo(out SYSTEM_INFO input);
public static extern void GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo);
public static uint GetNumberOfProcessors() { SYSTEM_INFO info = GetSystemInfo(); return(info.dwNumberOfProcessors); }
private static string GetHDInfo(Action <string> logcall = null) { StringBuilder str = new StringBuilder(); str.Append("{"); using (var regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(REG_BIOS_PATH)) { if (regkey != null) { string v = regkey.GetValue("BIOSVendor", null) as string; str.AppendFormat(" BIOSVendor: \"{0}\",", v ?? ""); v = regkey.GetValue("SystemVersion", null) as string; str.AppendFormat(" BIOSSystemVersion: \"{0}\",", v ?? ""); v = regkey.GetValue("BIOSVersion", null) as string; str.AppendFormat(" BIOSVersion: \"{0}\",", v ?? ""); } } using (var regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(REG_PROC_PATH)) { if (regkey != null) { string v = regkey.GetValue("ProcessorNameString", null) as string; str.AppendFormat(" ProcessorName: \"{0}\",", v ?? ""); v = regkey.GetValue("Identifier", null) as string; str.AppendFormat(" ProcessorIdentifier: \"{0}\",", v ?? ""); } } var sys = new SYSTEM_INFO(); GetNativeSystemInfo(ref sys); str.AppendFormat(" ProcessorType: {0}, ProcessorLevel: {1}, ProcessorRevision: {2}, NumberOfProcessors: {3}, ActiveProcessorMask: {4}, ProcessorArchitecture: {5},", sys.dwProcessorType, sys.wProcessorLevel, sys.wProcessorRevision, sys.dwNumberOfProcessors, sys.dwActiveProcessorMask, sys.wProcessorArchitecture); string rootPathName = Path.GetPathRoot(Environment.SystemDirectory); str.AppendFormat(" RootPathName: \"{0}\",", rootPathName); var disk = GetDiskFreeSpace(rootPathName); if (disk != null) { str.AppendFormat(" TotalNumberOfBytes: {0},", disk.TotalSize); } var volumeInfo = GetVolumeInformation(rootPathName); if (volumeInfo != null) { str.AppendFormat(" VolumeSerialNumber: {0}, FileSystemFlags: {1}, FileSystemName: \"{2}\"", volumeInfo.SerialNumber, volumeInfo.FileSystemFlags, volumeInfo.FileSystemName ?? ""); } str.Append(" }"); OnLogcall(str.ToString(), logcall); string s = Md5Utils.GetMd5Hash(str.ToString()); if (string.IsNullOrEmpty(s)) { string error = "需要重启计算机!"; OnLogcall(error, logcall); throw new Exception(error); } else { OnLogcall("HDInfo: " + s, logcall); } return(s); }
private static string GetOSName(ref OSVERSIONINFOEX vm) { string name = null; switch (vm.dwMajorVersion) { case 10: if (vm.wProductType == VER_NT_WORKSTATION) { name = "Windows 10"; } else { name = "Windows Server 2016 Technical Preview"; } break; case 6: switch (vm.dwMinorVersion) { case 3: if (vm.wProductType == VER_NT_WORKSTATION) { name = "Windows 8.1"; } else { name = "Windows Server 2012 R2"; } break; case 2: if (vm.wProductType == VER_NT_WORKSTATION) { name = "Windows 8"; } else { name = "Windows Server 2012"; } break; case 1: if (vm.wProductType == VER_NT_WORKSTATION) { name = "Windows 7"; } else { name = "Windows Server 2008 R2"; } break; case 0: if (vm.wProductType == VER_NT_WORKSTATION) { name = "Windows Vista"; } else { name = "Windows Server 2008"; } break; } break; case 5: switch (vm.dwMinorVersion) { case 2: if (GetSystemMetrics(SM_SERVERR2) != 0) { name = "Windows Server 2003 R2"; } else if ((vm.wSuiteMask & VER_SUITE_WH_SERVER) != 0) { name = "Windows Home Server"; } else if (GetSystemMetrics(SM_SERVERR2) == 0) { name = "Windows Server 2003"; } else if (vm.wProductType == VER_NT_WORKSTATION) { SYSTEM_INFO info = new SYSTEM_INFO(); GetNativeSystemInfo(ref info); if (info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { name = "Windows XP Professional x64 Edition"; } } break; case 1: name = "Windows XP"; break; case 0: name = "Windows 2000"; break; } break; } if (name == null) { name = string.Format("{0}.{1}.{2}", vm.dwMajorVersion, vm.dwMinorVersion, vm.dwBuildNumber); } return(name); }
private static extern int GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
private void GetMemoryDump(IntPtr processHandle) { SYSTEM_INFO sysInfo = SystemInfoHelper.GetSysInfo(); IntPtr proc_min_address = sysInfo.MinimumApplicationAddress; IntPtr proc_max_address = sysInfo.MaximumApplicationAddress; // saving the values as long ints so I won't have to do a lot of casts later long proc_min_address_l = (long)proc_min_address; long proc_max_address_l = (long)(uint)proc_max_address; StreamWriter sw = new StreamWriter("dump.txt"); int bytesRead = 0; long lastminAddress = 0; bool IsWow64 = ProcessHelper.IsProcessWow64(processHandle); while (proc_min_address_l < proc_max_address_l) { uint Protect = 1; MEMORY_BASIC_INFORMATION64 memInfo; memInfo = IsWow64 ? SystemInfoHelper.GetMemInfo64(processHandle, proc_min_address) : SystemInfoHelper.GetMemInfo32(processHandle, proc_min_address); if ((memInfo.Protect == PAGE_READ || memInfo.Protect == PAGE_READWRITE) && memInfo.State == MEM_COMMIT) //if (memInfo.Protect == PAGE_READWRITE && memInfo.State == MEM_COMMIT) { int maxRowSize = 64; byte[] buffer = new byte[(int)memInfo.RegionSize]; ProcessHelper.ReadProcessMemory(processHandle, IsWow64 ? new IntPtr((long)memInfo.BaseAddress): new IntPtr((int)memInfo.BaseAddress), buffer, (int)memInfo.RegionSize, ref bytesRead); string resultRow = string.Empty; bool hasValues = false; for (int i = 0; i < (int)memInfo.RegionSize; i++) { if (i % 64 == 0) { if (hasValues) { sw.WriteLine(resultRow); } hasValues = false; resultRow = $"0x{((int)memInfo.BaseAddress + i).ToString("X")} : "; } if (buffer[i] != 0) { resultRow += ((char)buffer[i] + " "); hasValues = true; } } } if ((int)memInfo.RegionSize == 0) { break; } lastminAddress = proc_min_address_l; proc_min_address_l += (long)memInfo.RegionSize; if (proc_min_address_l < lastminAddress) { break; } try { proc_min_address = IsWow64 ? new IntPtr((long)proc_min_address_l) : new IntPtr((int)proc_min_address_l); } catch { break; } Debug.Print($"Progress {(double)proc_min_address_l / ((double)proc_max_address_l / 100.0)}%"); } sw.Close(); }
internal static extern void GetNativeSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo);
private static extern void GetSystemInfo( [Out] out SYSTEM_INFO Info);
private static extern void GetSystemInfo(out SYSTEM_INFO input);
internal static void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo) => throw new PlatformNotSupportedException();
public static extern void GetSystemInfo(out SYSTEM_INFO Info);
internal static extern void GetNativeSystemInfo(out SYSTEM_INFO info);
public static extern void GetNativeSystemInfo(ref SYSTEM_INFO systemInfo);
public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo);
public static extern void GetSystemInfo(ref SYSTEM_INFO lpSysInfo);
private static extern void GetSystemInfo(ref SYSTEM_INFO lpSysInfo);
MemoryBlock GetMemoryBlock(IntPtr origin) { IntPtr minAddr = IntPtr.Zero; IntPtr maxAddr = IntPtr.Zero; MemoryBlock result = null; SYSTEM_INFO si = new SYSTEM_INFO(); GetSystemInfo(ref si); if (IntPtr.Size == 8) { minAddr = si.lpMinimumApplicationAddress; maxAddr = si.lpMaximumApplicationAddress; if ((ulong)origin > MAX_MEMORY_RANGE && (ulong)minAddr < (ulong)origin - MAX_MEMORY_RANGE) { minAddr = (IntPtr)((ulong)origin - MAX_MEMORY_RANGE); } if ((ulong)maxAddr > (ulong)origin + MAX_MEMORY_RANGE) { maxAddr = (IntPtr)((ulong)origin + MAX_MEMORY_RANGE); } maxAddr = (IntPtr)((ulong)maxAddr - MEMORY_BLOCK_SIZE - 1); } foreach (var memoryBlock in memoryBlocks) { if (IntPtr.Size == 8 && ((ulong)memoryBlock.BaseAddress < (ulong)minAddr || (ulong)memoryBlock.BaseAddress >= (ulong)maxAddr)) { continue; } if (!memoryBlock.IsFull()) { return(memoryBlock); } } //Couldn't find a free block, lets allocate another if (IntPtr.Size == 8) { IntPtr alloc = origin; while ((ulong)alloc >= (ulong)minAddr) { alloc = FindPrevFreeRegion(alloc, minAddr, si.dwAllocationGranularity); if (alloc == IntPtr.Zero) { break; } IntPtr baseAddr = VirtualAlloc(alloc, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); if (baseAddr != IntPtr.Zero) { result = new MemoryBlock(baseAddr); break; } } if (result == null) { alloc = origin; while ((ulong)alloc <= (ulong)maxAddr) { alloc = FindNextFreeRegion(alloc, maxAddr, si.dwAllocationGranularity); if (alloc == IntPtr.Zero) { break; } IntPtr baseAddr = VirtualAlloc(alloc, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); if (baseAddr != IntPtr.Zero) { result = new MemoryBlock(baseAddr); break; } } } } else { IntPtr baseAddr = VirtualAlloc(IntPtr.Zero, (IntPtr)MEMORY_BLOCK_SIZE, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); if (baseAddr == IntPtr.Zero) { throw new OutOfMemoryException("Failed to allocate new block of memory"); } result = new MemoryBlock(baseAddr); } if (result == null) { throw new OutOfMemoryException("Failed to allocate new block of memory"); } memoryBlocks.Add(result); return(result); }
private static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
private ReadMemoryResults ReadMemory() { ReadMemoryResults results = null; SYSTEM_INFO sys_info = new SYSTEM_INFO(); GetSystemInfo(out sys_info); IntPtr proc_min_address = sys_info.minimumApplicationAddress; IntPtr proc_max_address = sys_info.maximumApplicationAddress; long proc_min_address_l = (long)proc_min_address; long proc_max_address_l = (long)proc_max_address; Process process = GetTibiaProcess(); if (process == null) { // Tibia process could not be found, wait for a bit and return Thread.Sleep(250); return null; } flashClient = TibiaClientName.ToLower().Contains("flash") || TibiaClientName.ToLower().Contains("chrome"); IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id); MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION(); int bytesRead = 0; // number of bytes read with ReadProcessMemory int scanSpeed = SettingsManager.getSettingInt("ScanSpeed"); try { results = new ReadMemoryResults(); while (proc_min_address_l < proc_max_address_l) { proc_min_address = new IntPtr(proc_min_address_l); // 28 = sizeof(MEMORY_BASIC_INFORMATION) VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28); // check if this memory chunk is accessible if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT) { if (!memorySegments.Contains(mem_basic_info.BaseAddress)) { byte[] buffer = new byte[mem_basic_info.RegionSize]; // read everything in the buffer above ReadProcessMemory((int)processHandle, mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead); // scan the memory for strings that start with timestamps and end with the null terminator ('\0') List<string> strings; if (!flashClient) { strings = FindTimestamps(buffer); } else { strings = FindTimestampsFlash(buffer); } if (strings.Count > 0) { // if any timestamp strings were found, scan the chunk for any messages SearchChunk(strings, results); } else { memorySegments.Add(mem_basic_info.BaseAddress); } // performance throttling sleep after every scan (depending on scanSpeed setting) if (scanSpeed > 0) { Thread.Sleep(scanSpeed); } } } // move to the next memory chunk proc_min_address_l += mem_basic_info.RegionSize; } } catch { return null; } if (memorySegments.Count > 10) { memorySegments.RemoveRange(0, 10); } else { memorySegments.Clear(); } process.Dispose(); FinalCleanup(results); return results; }
static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
internal static extern void GetNativeSystemInfo(ref SYSTEM_INFO system_INFO_0);
public static Dictionary <int, int> DoMemoryThing() { // getting minimum & maximum address Dictionary <int, int> regions = new Dictionary <int, int>(); SYSTEM_INFO sys_info = new SYSTEM_INFO(); GetSystemInfo(out sys_info); IntPtr proc_min_address = sys_info.minimumApplicationAddress; IntPtr proc_max_address = sys_info.maximumApplicationAddress; // saving the values as long ints so I won't have to do a lot of casts later long proc_min_address_l = (long)proc_min_address; long proc_max_address_l = (long)proc_max_address; // notepad better be runnin' Process process = Process.GetProcessesByName("rocketleague")[0]; // opening the process with desired access level IntPtr processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, process.Id); //StreamWriter sw = new StreamWriter("dump.txt"); // this will store any information we get from VirtualQueryEx() MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION(); int bytesRead = 0; // number of bytes read with ReadProcessMemory while (proc_min_address_l < proc_max_address_l) { // 28 = sizeof(MEMORY_BASIC_INFORMATION) VirtualQueryEx(processHandle, proc_min_address, out mem_basic_info, 28); // if this memory chunk is accessible if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT) { //byte[] buffer = new byte[mem_basic_info.RegionSize]; // read everything in the buffer above //ReadProcessMemory((int)processHandle, //mem_basic_info.BaseAddress, buffer, mem_basic_info.RegionSize, ref bytesRead); //// then output this in the file //var bytes = ReadMemory(mem_basic_info.BaseAddress, mem_basic_info.RegionSize); //for (int i = 0; i < bytes.Length; i += 4) //{ // var f = BitConverter.ToSingle(bytes, i); // if (f > 18.3562f && f < 18.3563f) // { // var z = 3; // } //} // sw.WriteLine("0x{0} : {1}", (mem_basic_info.BaseAddress + i).ToString("X"), (char)buffer[i]); if (mem_basic_info.lType == 0x20000) { regions.Add(mem_basic_info.BaseAddress, mem_basic_info.RegionSize); } } // move to the next memory chunk proc_min_address_l += mem_basic_info.RegionSize; proc_min_address = new IntPtr(proc_min_address_l); } //sw.Close(); return(regions); }
public int DumpProcMemory(int pid, string filename) { //打开进程 IntPtr handle = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VMOperation | ProcessAccessFlags.VMRead | ProcessAccessFlags.VMWrite, false, pid); SYSTEM_INFO systeminfo = new SYSTEM_INFO(); GetSystemInfo(out systeminfo); System.IO.FileStream stream = null; stream = new System.IO.FileStream(filename, System.IO.FileMode.Append); long MaxAddress = (long)systeminfo.lpMaximumApplicationAddress; long address = 0; int countcount = 0; do { MEMORY_BASIC_INFORMATION memory; int result = VirtualQueryEx(handle, (IntPtr)address, out memory, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); if (address == (long)memory.BaseAddress + (long)memory.RegionSize) break; //保存具有读写属性且已提交的虚存 if (memory.State == (uint)StateEnum.MEM_COMMIT) { switch (memory.AllocationProtect) { case (uint)AllocationProtect.PAGE_READWRITE: byte[] buffer = new byte[(int)memory.RegionSize]; IntPtr byteread; ReadProcessMemory(handle, memory.BaseAddress, buffer, (int)memory.RegionSize, out byteread); //写入文件 stream.Write(buffer, 0, buffer.Length); countcount++; break; default: break; } } address = (long)memory.BaseAddress + (long)memory.RegionSize; } while (address <= MaxAddress); stream.Close(); CloseHandle(handle); Console.WriteLine("read over!"); Console.WriteLine(countcount); return 0; }
private static int GetAllocationGranularityWorker() { SYSTEM_INFO info = new SYSTEM_INFO(); GetSystemInfo(ref info); return info.dwAllocationGranularity; }
void DetectAntidumpsShown(object sender, EventArgs e) { string buildedstring = "Finding anti-dumps on module: " + strmodulename + " address: " + baseaddress.ToString("X8") + " size: " + modulesize.ToString("X8") + "\r\n"; SYSTEM_INFO pSI = new SYSTEM_INFO(); pSI.dwPageSize = 0x1000; pSI.lpMaximumApplicationAddress = 0xF0000000; pSI.lpMinimumApplicationAddress = 0; try { GetSystemInfo(ref pSI); } catch { } uint i = 0; Dictionary <uint, uint> allmemory = new Dictionary <uint, uint>(); Dictionary <uint, uint> neededmemory = new Dictionary <uint, uint>(); uint firstaddress = 0; IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)procid); if (hProcess != IntPtr.Zero) { while (i < pSI.lpMaximumApplicationAddress) { if (VirtualQueryEx(hProcess, i, out mbi, (uint)System.Runtime.InteropServices.Marshal.SizeOf(mbi)) ) { if (firstaddress == 0) { firstaddress = (uint)mbi.BaseAddress; } i = (uint)mbi.BaseAddress + (uint)mbi.RegionSize; if (mbi.State == MemoryState.Commit) { if ((uint)mbi.BaseAddress < (uint)baseaddress || i > (uint)(baseaddress + modulesize)) { if (allmemory.ContainsKey((uint)mbi.AllocationBase)) { uint oldmaxim = 0; allmemory.TryGetValue((uint)mbi.AllocationBase, out oldmaxim); uint newmaxim = 0; if (oldmaxim > i) { newmaxim = oldmaxim; } else { newmaxim = i; } allmemory.Remove((uint)mbi.AllocationBase); allmemory.Add((uint)mbi.AllocationBase, newmaxim); } else { allmemory.Add((uint)mbi.AllocationBase, i); } } } } } // end of loop /* * Stack antidumps: * "MOV DWORD PTR SS:[EBP+xxx],value" * opcode C785 folowed by address * * "MOV register,DWORD PTR SS:[EBP+xxx]" * opcode 8B85/8B8D/8B95 folowed by address * * "CMP DWORD PTR SS:[EBP+xxx],value" * opcode 83BD/81BD folowed by address * */ bool isok; byte[] onepage = new byte[pSI.dwPageSize]; uint BytesRead = 0; byte[] infokeep = new byte[8]; isok = ReadProcessMemory(hProcess, (IntPtr)baseaddress, onepage, (uint)onepage.Length, ref BytesRead); if (isok) { if (ReadProcessMemory(hProcess, (IntPtr)(baseaddress + 0x03C), infokeep, 4, ref BytesRead)) { int PEOffset = BitConverter.ToInt32(infokeep, 0); if (PEOffset > 0 && (PEOffset + 0x0120) < onepage.Length) { if (ReadProcessMemory(hProcess, (IntPtr)(baseaddress + PEOffset), infokeep, 2, ref BytesRead)) { int nrofsection = (int)BitConverter.ToInt16(onepage, PEOffset + 0x06); if (nrofsection > 0) { int virtualsize = BitConverter.ToInt32(onepage, PEOffset + 0x0F8 + 0x28 * 0 + 08); int virtualAddress = BitConverter.ToInt32(onepage, PEOffset + 0x0F8 + 0x28 * 0 + 012); byte[] firstsection = new byte[virtualsize]; if (ReadProcessMemory(hProcess, (IntPtr)(baseaddress + virtualAddress), firstsection, (uint)firstsection.Length, ref BytesRead)) { for (int j = 0; j < firstsection.Length - 6; j++) { // Find ouside address: } textBox1.Text = buildedstring; } } } } } } } }
internal static extern void GetSystemInfo(out SYSTEM_INFO si);
private void Form1_Load(object sender, EventArgs e) { SYSTEM_INFO pSI = new SYSTEM_INFO(); GetSystemInfo(ref pSI); int processorNumber = (int)pSI.dwNumberOfProcessors; x264ThreadsComboBox.Items.Add("auto"); for (int i = 1; i <= 16; i++) { x264ThreadsComboBox.Items.Add(i.ToString()); } //Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-TW"); //use YAHEI in VistaOrNewer //if (IsWindowsVistaOrNewer) //{ // FontFamily myFontFamily = new FontFamily("微软雅黑"); //采用哪种字体 // Font myFont = new Font(myFontFamily, 9, FontStyle.Regular); //字是那种字体,显示的风格 // this.Font = myFont; //} //define workpath startpath = System.Windows.Forms.Application.StartupPath; workPath = startpath + "\\tools"; if (!Directory.Exists(workPath)) { MessageBox.Show("tools文件夹没有解压喔~ 工具箱里没有工具的话运行不起来的喔~", "(这只丸子)", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } //Directory.CreateDirectory(workPath); //string diskSymbol = startpath.Substring(0, 1); //string systemDisk = Environment.GetFolderPath(Environment.SpecialFolder.System).Substring(0, 3); //string systemTempPath = systemDisk + @"windows\temp"; string systemTempPath = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine); tempavspath = systemTempPath + "\\temp.avs"; tempPic = systemTempPath + "\\marukotemp.jpg"; tempfilepath = startpath + "\\temp"; //load x264 exe DirectoryInfo folder = new DirectoryInfo(workPath); List<string> x264exe = new List<string>(); try { bool usex265 = bool.Parse(ConfigurationManager.AppSettings["x265Enable"].ToString()); foreach (FileInfo FileName in folder.GetFiles()) { if ((FileName.Name.ToLower().Contains("x264") || FileName.Name.ToLower().Contains(usex265 ? "x265" : "xxxx")) && Path.GetExtension(FileName.Name) == ".exe") { x264exe.Add(FileName.Name); } } x264exe = x264exe.OrderByDescending(i => i.Substring(7)).ToList(); x264ExeComboBox.Items.AddRange(x264exe.ToArray()); } catch { } // avisynth未安装使用本地内置的avs if (string.IsNullOrEmpty(Util.CheckAviSynth())) { string sourceAviSynthdll = Path.Combine(workPath, @"avs\AviSynth.dll"); string sourceDevILdll = Path.Combine(workPath, @"avs\DevIL.dll"); if (File.Exists(sourceAviSynthdll) && File.Exists(sourceDevILdll)) { File.Copy(sourceAviSynthdll, Path.Combine(workPath, "AviSynth.dll"), true); File.Copy(sourceDevILdll, Path.Combine(workPath, "DevIL.dll"), true); LogRecord("未安装avisynth,使用本地内置avs."); } } else { File.Delete(Path.Combine(workPath, "AviSynth.dll")); File.Delete(Path.Combine(workPath, "DevIL.dll")); } //load AVS filter DirectoryInfo avspath = new DirectoryInfo(workPath + @"\avs\plugins"); List<string> avsfilters = new List<string>(); if (Directory.Exists(workPath + @"\avs\plugins")) { foreach (FileInfo FileName in avspath.GetFiles()) { if (Path.GetExtension(FileName.Name) == ".dll") { avsfilters.Add(FileName.Name); } } AVSFilterComboBox.Items.AddRange(avsfilters.ToArray()); } //ReleaseDate = System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location); //获得程序编译时间 ReleaseDatelabel.Text = ReleaseDate.ToString("yyyy-M-d"); // load Help Text if (File.Exists(startpath + "\\help.rtf")) { HelpTextBox.LoadFile(startpath + "\\help.rtf"); } PresetXml(); LoadVideoPreset(); LoadSettings(); }
private static DataSource GetFileChunk(uint start, int size, int dtIndex, out uint difference) { SYSTEM_INFO _info = new SYSTEM_INFO(); GetSystemInfo(ref _info); uint chunk_start = start; int chunk_len = size; difference = 0; if (start % _info.allocationGranularity != 0) { chunk_start = start.RoundDown((int)_info.allocationGranularity); difference = start - chunk_start; chunk_len = (int)difference + size; } return new DataSource(FileMap.FromFile(DtPaths[dtIndex], FileMapProtect.ReadWrite, chunk_start, (int)chunk_len)); }
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
internal extern static void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
bool SearchMemory() { // getting minimum & maximum address SYSTEM_INFO sys_info = new SYSTEM_INFO(); GetSystemInfo(out sys_info); IntPtr PROCS_min_address = sys_info.minimumApplicationAddress; IntPtr PROCS_max_address = sys_info.maximumApplicationAddress; // saving the values as long ints so I won't have to do a lot of casts later ulong PROCS_min_address_l = (ulong)PROCS_min_address; ulong PROCS_max_address_l = (ulong)PROCS_max_address; // opening the process with desired access level this.ProcessHandle = OpenProcess( PROCESS_QUERY_INFORMATION //メモリ一覧の取得権限 | PROCESS_VM_READ //読込権限 | PROCESS_VM_WRITE | PROCESS_VM_OPERATION //書き込み権限 , false, this.Process.Id); if (this.ProcessHandle == IntPtr.Zero) { this.ErrorMessage = R._("OpenProcess APIが失敗ました。"); return(false); } // this will store any information we get from VirtualQueryEx() MEMORY_BASIC_INFORMATION mem_basic_info = new MEMORY_BASIC_INFORMATION(); while (PROCS_min_address_l < PROCS_max_address_l) { // 28 = sizeof(MEMORY_BASIC_INFORMATION) int ret = VirtualQueryEx(this.ProcessHandle, PROCS_min_address, out mem_basic_info, 28); if (ret <= 0) { break; } // if this memory chunk is accessible if (mem_basic_info.Protect == PAGE_READWRITE && mem_basic_info.State == MEM_COMMIT && mem_basic_info.lType == MEM_PRIVATE ) { if (this.MemBasicInfo02.RegionSize <= 0) { Parse02(this.ProcessHandle, mem_basic_info); } if (this.MemBasicInfo03.RegionSize <= 0) { Parse03(this.ProcessHandle, mem_basic_info); } } // move to the next memory chunk PROCS_min_address_l += (ulong)mem_basic_info.RegionSize; PROCS_min_address = (IntPtr)PROCS_min_address_l; } if (!IsConnect()) { CloseHandle(ProcessHandle); ProcessHandle = IntPtr.Zero; if (MemBasicInfo02.RegionSize <= 0 || Memory02.Length <= 0) { if (MemBasicInfo03.RegionSize <= 0 || Memory03.Length <= 0) { this.ErrorMessage = R._("読込むメモリを特定できませんでした。(Page02,Page03)"); } else { this.ErrorMessage = R._("読込むメモリを特定できませんでした。(Page02)"); } } else { this.ErrorMessage = R._("読込むメモリを特定できませんでした。(Page03)"); } #if DEBUG // DebugDumpMemory(); #endif return(false); } return(true); }
public int ResumeProcState(int pid, string filename) { AllocConsole(); //建文件流 System.IO.FileStream stream = null; stream = new System.IO.FileStream(filename, System.IO.FileMode.Open); byte[] descriptioncount = new byte[1]; //读出exe文件路径长度 stream.Read(descriptioncount, 0, descriptioncount.Length); int descount = Convert.ToInt32(descriptioncount[0]); char[] procdescription = new char[descount]; byte[] bytedescription = new byte[descount]; //读出exe文件路径 stream.Read(bytedescription, 0, bytedescription.Length); for (int j = 0; j < descount; j++) { procdescription[j] = Convert.ToChar(bytedescription[j]); } string description = new string(procdescription); //新建进程 SECURITY_ATTRIBUTES process = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES thread = new SECURITY_ATTRIBUTES(); STARTUPINFO info = new STARTUPINFO(); PROCESS_INFORMATION proinfo = new PROCESS_INFORMATION(); if (CreateProcess( null, description, ref process, ref thread, false, (uint)CreateProcessFlags.NORMAL_PRIORITY_CLASS, (IntPtr)null, null, ref info, out proinfo)) { IntPtr prohandle = proinfo.hProcess; IntPtr thrhandle = proinfo.hThread; System.Threading.Thread.Sleep(5000); SuspendThread(thrhandle); //打印信息 CONTEXT tt = new CONTEXT(); tt.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; GetThreadContext(thrhandle, ref tt); Console.WriteLine(thrhandle); Console.WriteLine("Ebp : {0}", tt.Ebp); Console.WriteLine("Eip : {0}", tt.Eip); Console.WriteLine("SegCs : {0}", tt.SegCs); Console.WriteLine("EFlags : {0}", tt.EFlags); Console.WriteLine("Esp : {0}", tt.Esp); Console.WriteLine("SegSs : {0}", tt.SegSs); Console.WriteLine("Dr0 : {0}", tt.Dr0); Console.WriteLine("Dr1 : {0}", tt.Dr1); Console.WriteLine("Dr2 : {0}", tt.Dr2); Console.WriteLine("Dr3 : {0}", tt.Dr3); Console.WriteLine("Dr6 : {0}", tt.Dr6); Console.WriteLine("Dr7 : {0}", tt.Dr7); Console.WriteLine("SegGs : {0}", tt.SegGs); Console.WriteLine("SegFs : {0}", tt.SegFs); Console.WriteLine("Seges : {0}", tt.SegEs); Console.WriteLine("SegDs : {0}", tt.SegDs); Console.WriteLine("Edi : {0}", tt.Edi); Console.WriteLine("Esi : {0}", tt.Esi); Console.WriteLine("Ebx : {0}", tt.Ebx); Console.WriteLine("Edx : {0}", tt.Edx); Console.WriteLine("Ecx : {0}", tt.Ecx); Console.WriteLine("Eax : {0}", tt.Eax); ResumeThread(thrhandle); System.Threading.Thread.Sleep(5000); SuspendThread(thrhandle); CONTEXT ttt = new CONTEXT(); ttt.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; GetThreadContext(thrhandle, ref ttt); Console.WriteLine(thrhandle); Console.WriteLine("Ebp : {0}", ttt.Ebp); Console.WriteLine("Eip : {0}", ttt.Eip); Console.WriteLine("SegCs : {0}", ttt.SegCs); Console.WriteLine("EFlags : {0}", ttt.EFlags); Console.WriteLine("Esp : {0}", ttt.Esp); Console.WriteLine("SegSs : {0}", ttt.SegSs); Console.WriteLine("Dr0 : {0}", ttt.Dr0); Console.WriteLine("Dr1 : {0}", ttt.Dr1); Console.WriteLine("Dr2 : {0}", ttt.Dr2); Console.WriteLine("Dr3 : {0}", ttt.Dr3); Console.WriteLine("Dr6 : {0}", ttt.Dr6); Console.WriteLine("Dr7 : {0}", ttt.Dr7); Console.WriteLine("SegGs : {0}", ttt.SegGs); Console.WriteLine("SegFs : {0}", ttt.SegFs); Console.WriteLine("Seges : {0}", ttt.SegEs); Console.WriteLine("SegDs : {0}", ttt.SegDs); Console.WriteLine("Edi : {0}", ttt.Edi); Console.WriteLine("Esi : {0}", ttt.Esi); Console.WriteLine("Ebx : {0}", ttt.Ebx); Console.WriteLine("Edx : {0}", ttt.Edx); Console.WriteLine("Ecx : {0}", ttt.Ecx); Console.WriteLine("Eax : {0}", ttt.Eax); //读取线程数 byte[] bytecount = new byte[1]; stream.Read(bytecount, 0, bytecount.Length); int count = Convert.ToInt32(bytecount[0]); int threadid = proinfo.dwThreadId; CONTEXT[] context = new CONTEXT[count]; for (int i = 0; i < count; i++) { //读取原先的线程句柄 byte[] byteAgohandlecount = new byte[1]; stream.Read(byteAgohandlecount, 0, byteAgohandlecount.Length); int Agohandlecount = Convert.ToInt32(byteAgohandlecount[0]); Console.WriteLine(Agohandlecount); byte[] byteAgohandle = new byte[Agohandlecount]; stream.Read(byteAgohandle, 0, byteAgohandle.Length); char[] charAgohandle = new char[Agohandlecount]; for (int bi = 0; bi < Agohandlecount; bi++) { charAgohandle[bi] = Convert.ToChar(byteAgohandle[bi]); } string stringAgohandle = new string(charAgohandle); IntPtr Agohandle = (IntPtr)Convert.ToInt32(stringAgohandle); Console.WriteLine(Agohandle); //读上下文 byte[] bydata = new byte[Marshal.SizeOf(context[i])]; stream.Read(bydata, 0, bydata.Length); context[i] = Deserialize(bydata); Console.WriteLine("Ebp : {0}", context[i].Ebp); Console.WriteLine("Eip : {0}", context[i].Eip); Console.WriteLine("SegCs : {0}", context[i].SegCs); Console.WriteLine("EFlags : {0}", context[i].EFlags); Console.WriteLine("Esp : {0}", context[i].Esp); Console.WriteLine("SegSs : {0}", context[i].SegSs); Console.WriteLine("Dr0 : {0}", context[i].Dr0); Console.WriteLine("Dr1 : {0}", context[i].Dr1); Console.WriteLine("Dr2 : {0}", context[i].Dr2); Console.WriteLine("Dr3 : {0}", context[i].Dr3); Console.WriteLine("Dr6 : {0}", context[i].Dr6); Console.WriteLine("Dr7 : {0}", context[i].Dr7); Console.WriteLine("SegGs : {0}", context[i].SegGs); Console.WriteLine("SegFs : {0}", context[i].SegFs); Console.WriteLine("Seges : {0}", context[i].SegEs); Console.WriteLine("SegDs : {0}", context[i].SegDs); Console.WriteLine("Edi : {0}", context[i].Edi); Console.WriteLine("Esi : {0}", context[i].Esi); Console.WriteLine("Ebx : {0}", context[i].Ebx); Console.WriteLine("Edx : {0}", context[i].Edx); Console.WriteLine("Ecx : {0}", context[i].Ecx); Console.WriteLine("Eax : {0}", context[i].Eax); context[i].ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; IntPtr Nowhandle = OpenThread(ThreadAccess.SET_CONTEXT, false, (uint)threadid); // Console.WriteLine(Nowhandle); // context[i] = HandleToHandle(Agohandle, Nowhandle, context[i]); tt.Eax = context[i].Eax; tt.Ebx = context[i].Ebx; tt.Ecx = context[i].Ecx; tt.Edx = context[i].Edx; //tt.Ebp = context[i].Ebp; //tt.Esp = context[i].Esp; //tt.Esi = context[i].Esi; //SetThreadContext(Agohandle, ref tt); CloseHandle(Nowhandle); //建立新线程 if (i + 1 < count) { IntPtr lpThreadID = (IntPtr)0; StartThread threadfunc = null; ThreadStartDelegate threadFunc = null; unsafe { thrhandle = CreateRemoteThread(prohandle, (IntPtr)null, 0, threadFunc, (IntPtr)null, (uint)CreateProcessFlags.CREATE_SUSPENDED, lpThreadID); } threadid = (int)lpThreadID; } } // ResumeThread(thrhandle); //读入内存状态 SYSTEM_INFO systeminfo = new SYSTEM_INFO(); GetSystemInfo(out systeminfo); long MaxAddress = (long)systeminfo.lpMaximumApplicationAddress; long address = 0; int countcount = 0; do { MEMORY_BASIC_INFORMATION memory; int result = VirtualQueryEx(prohandle, (IntPtr)address, out memory, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); if (address == (long)memory.BaseAddress + (long)memory.RegionSize) break; if (memory.State == (uint)StateEnum.MEM_COMMIT) { switch (memory.AllocationProtect) { case (uint)AllocationProtect.PAGE_READWRITE: byte[] buffer = new byte[(int)memory.RegionSize]; Console.WriteLine("now"); Console.WriteLine(memory.BaseAddress); Console.WriteLine(memory.AllocationBase); Console.WriteLine(memory.RegionSize); Console.WriteLine(memory.Type); Console.WriteLine(memory.Protect); stream.Read(buffer, 0, buffer.Length); UIntPtr byteread; WriteProcessMemory(prohandle, memory.BaseAddress, buffer, (uint)memory.RegionSize, out byteread); Console.WriteLine("ago"); Console.WriteLine(memory.BaseAddress); Console.WriteLine(memory.AllocationBase); Console.WriteLine(memory.RegionSize); Console.WriteLine(memory.Type); Console.WriteLine(memory.Protect); countcount++; break; default: break; } } address = (long)memory.BaseAddress + (long)memory.RegionSize; } while (address <= MaxAddress); stream.Close(); CloseHandle(prohandle); Console.WriteLine("write over!"); Console.WriteLine(countcount); } //恢复线程运行 System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(proinfo.dwProcessId); System.Diagnostics.ProcessThread[] processthread = new System.Diagnostics.ProcessThread[500]; System.Diagnostics.ProcessThreadCollection threadcollection = new System.Diagnostics.ProcessThreadCollection(processthread); threadcollection = proc.Threads; for (int k = 0; k < threadcollection.Count; k++) { IntPtr ptrr = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)threadcollection[k].Id); ResumeThread(ptrr); CloseHandle(ptrr); } return 0; }
public (long, Dictionary <string, int>) Search(Process process) { //List<MemoryDumpChunk> memoryDumpChunks = new List<MemoryDumpChunk>(); Dictionary <string, int> memoryDumpChunks = new Dictionary <string, int>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Restart(); SYSTEM_INFO msi = new SYSTEM_INFO(); Kernel32.GetSystemInfo(ref msi); MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); long ProcMinAddress = (long)msi.lpMinimumApplicationAddress; IntPtr procMinPtr = msi.lpMinimumApplicationAddress; long ProcMaxAddress = (long)msi.lpMaximumApplicationAddress; IntPtr processHandle = process.Handle; int bytesRead = 0; using (StreamWriter swByte = new StreamWriter("RAM_Dump_Byte.txt")) { using (StreamWriter swChar = new StreamWriter("RAM_Dump_Char.txt")) { using (StreamWriter swSectors = new StreamWriter("RAM_Dump_Sectors.txt")) { using (StreamWriter swInt = new StreamWriter("RAM_Dump_Int.txt")) { swByte.WriteLine(DateTime.Now); swByte.WriteLine(""); int sector = 0; MemoryDumpChunk memoryDumpChunk = new MemoryDumpChunk(); while (ProcMinAddress < ProcMaxAddress) { Kernel32.VirtualQueryEx(processHandle, procMinPtr, out mbi, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); swByte.WriteLine("Sector done!" + "Address: " + string.Format("0x{0}", (procMinPtr).ToString("X16")) + " Number: " + sector); swChar.WriteLine("Sector done!" + "Address: " + string.Format("0x{0}", (procMinPtr).ToString("X16")) + " Number: " + sector); swSectors.WriteLine("Sector done!" + "Address: " + string.Format("0x{0}", (procMinPtr).ToString("X16")) + " Number: " + sector); if (mbi.Protect == Kernel32.PAGE_READWRITE && mbi.State == Kernel32.MEM_COMMIT) { byte[] buffer = new byte[mbi.RegionSize]; Kernel32.ReadProcessMemory((int)processHandle, mbi.BaseAddress, buffer, mbi.RegionSize, ref bytesRead); byte[] IntBufferValue = new byte[sizeof(int)]; int bufIter = 0; string intAddress = string.Format("0x{0}", (mbi.BaseAddress).ToString("X16")); if ((mbi.RegionSize % 4) != 0) { throw new Exception("x"); } for (int x = 0; x < mbi.RegionSize; x++) { string Address = string.Format("0x{0}", (mbi.BaseAddress + x).ToString("X16")); byte Value = buffer[x]; memoryDumpChunk.Address = Address; memoryDumpChunk.charValue = (char)Value; memoryDumpChunk.intValue = (int)Value; memoryDumpChunk.byteValue = Value; memoryDumpChunk.boolValue = Convert.ToBoolean(Value); memoryDumpChunk.shortValue = (short)Value; memoryDumpChunk.longValue = (long)Value; memoryDumpChunk.uintValue = (uint)Value; memoryDumpChunk.ulongValue = (uint)Value; //memoryDumpChunks.Add(memoryDumpChunk); swByte.WriteLine(Address + " : " + memoryDumpChunk.byteValue); swChar.WriteLine(Address + " : " + memoryDumpChunk.charValue); if (bufIter < 4) { IntBufferValue[bufIter] = memoryDumpChunk.byteValue; } if (bufIter == 4) { bufIter = 0; int value = BitConverter.ToInt32(IntBufferValue, 0); swInt.WriteLine(intAddress + " : Int32: " + value + " Hex: " + string.Format("0x{0}", BitConverter.ToInt32(IntBufferValue, 0).ToString("X16")) + " UInt32: " + BitConverter.ToUInt32(IntBufferValue, 0)); memoryDumpChunks.Add(intAddress, value); IntBufferValue[bufIter] = memoryDumpChunk.byteValue; intAddress = Address; } bufIter++; } } ProcMinAddress += mbi.RegionSize; procMinPtr = new IntPtr(ProcMinAddress); sector++; } } } } } stopwatch.Stop(); return(stopwatch.ElapsedMilliseconds, memoryDumpChunks); }
private static extern void GetSystemInfo(ref SYSTEM_INFO pSI);
internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
private static extern int GetSystemInfo(ref SYSTEM_INFO lpSystemInfo);
static extern void GetNativeSystemInfo(ref SYSTEM_INFO lpSystemInfo);
static extern void GetNativeSystemInfo(out SYSTEM_INFO lpSystemInfo);
private static partial void GetSystemInfo(out SYSTEM_INFO input);
static Win32Native() { SYSTEM_INFO lpSystemInfo = new SYSTEM_INFO(); GetSystemInfo(out lpSystemInfo); PAGE_SIZE = (int) lpSystemInfo.dwPageSize; }
public static extern void GetSystemInfo(ref SYSTEM_INFO pSI);
public static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
void DumpModule() { IntPtr hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)procid); if (hProcess == IntPtr.Zero) { IntPtr pDACL, pSecDesc; GetSecurityInfo((int)Process.GetCurrentProcess().Handle, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4, 0, 0, out pDACL, IntPtr.Zero, out pSecDesc); hProcess = OpenProcess(0x40000, 0, (uint)procid); SetSecurityInfo((int)hProcess, /*SE_KERNEL_OBJECT*/ 6, /*DACL_SECURITY_INFORMATION*/ 4 | /*UNPROTECTED_DACL_SECURITY_INFORMATION*/ 0x20000000, 0, 0, pDACL, IntPtr.Zero); ProcModule.CloseHandle(hProcess); hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_TERMINATE, 0, (uint)procid); } if (hProcess != IntPtr.Zero) { string newdirname = DirName; if (DirName.Length < 2 || !Directory.Exists(DirName)) { newdirname = "C:\\"; } newdirname = Path.Combine(DirName, "Dumps"); System.IO.Directory.CreateDirectory(newdirname); int ImageBase = System.Convert.ToInt32(lvmodules.Items[lvmodules.SelectedIndices[0]].SubItems[1].Text, 16); string moduleName = lvmodules.Items[lvmodules.SelectedIndices[0]].SubItems[0].Text; bool isok; uint speed = 0x1000; try { SYSTEM_INFO pSI = new SYSTEM_INFO(); GetSystemInfo(ref pSI); speed = pSI.dwPageSize; } catch { } byte[] bigMem = new byte[speed]; byte[] InfoKeep = new byte[8]; uint BytesRead = 0; int nrofsection = 0; byte[] Dump = null; byte[] Partkeep = null; int filealignment = 0; int rawaddress; int address = 0; int offset = 0; bool ShouldFixrawsize = false; isok = ReadProcessMemory(hProcess, (uint)(ImageBase + 0x03C), InfoKeep, 4, ref BytesRead); int PEOffset = BitConverter.ToInt32(InfoKeep, 0); try { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + PEOffset + 0x0F8 + 20), InfoKeep, 4, ref BytesRead); byte[] PeHeader = new byte[speed]; rawaddress = BitConverter.ToInt32(InfoKeep, 0); int sizetocopy = rawaddress; if (sizetocopy > speed) { sizetocopy = (int)speed; } isok = ReadProcessMemory(hProcess, (uint)(ImageBase), PeHeader, (uint)sizetocopy, ref BytesRead); offset = offset + rawaddress; nrofsection = (int)BitConverter.ToInt16(PeHeader, PEOffset + 0x06); int sectionalignment = BitConverter.ToInt32(PeHeader, PEOffset + 0x038); filealignment = BitConverter.ToInt32(PeHeader, PEOffset + 0x03C); int sizeofimage = BitConverter.ToInt32(PeHeader, PEOffset + 0x050); int calculatedimagesize = BitConverter.ToInt32(PeHeader, PEOffset + 0x0F8 + 012); for (int i = 0; i < nrofsection; i++) { int virtualsize = BitConverter.ToInt32(PeHeader, PEOffset + 0x0F8 + 0x28 * i + 08); int toadd = (virtualsize % sectionalignment); if (toadd != 0) { toadd = sectionalignment - toadd; } calculatedimagesize = calculatedimagesize + virtualsize + toadd; } if (calculatedimagesize > sizeofimage) { sizeofimage = calculatedimagesize; } Dump = new byte[sizeofimage]; Array.Copy(PeHeader, Dump, sizetocopy); Partkeep = new byte[sizeofimage]; } catch { } int calcrawsize = 0; for (int i = 0; i < nrofsection; i++) { int rawsize, virtualsize, virtualAddress; for (int l = 0; l < nrofsection; l++) { rawsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 16); virtualsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 08); virtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * l + 012); // RawSize = Virtual Size rounded on FileAlligment calcrawsize = 0; calcrawsize = virtualsize % filealignment; if (calcrawsize != 0) { calcrawsize = filealignment - calcrawsize; } calcrawsize = virtualsize + calcrawsize; if (calcrawsize != 0 && rawsize != calcrawsize && rawsize != virtualsize) { ShouldFixrawsize = true; break; } } rawsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 16); virtualsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 08); // RawSize = Virtual Size rounded on FileAlligment virtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 012); if (ShouldFixrawsize) { rawsize = virtualsize; BinaryWriter writer = new BinaryWriter(new MemoryStream(Dump)); writer.BaseStream.Position = PEOffset + 0x0F8 + 0x28 * i + 16; writer.Write(virtualsize); writer.BaseStream.Position = PEOffset + 0x0F8 + 0x28 * i + 20; writer.Write(virtualAddress); writer.Close(); } address = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 0x28 * i + 12); isok = ReadProcessMemory(hProcess, (uint)(ImageBase + address), Partkeep, (uint)rawsize, ref BytesRead); if (!isok) { byte[] onepage = new byte[512]; for (int c = 0; c < virtualsize; c = c + 512) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + virtualAddress + c), onepage, (uint)512, ref BytesRead); Array.Copy(onepage, 0, Partkeep, c, 512); } } if (ShouldFixrawsize) { Array.Copy(Partkeep, 0, Dump, virtualAddress, rawsize); offset = virtualAddress + rawsize; } else { Array.Copy(Partkeep, 0, Dump, offset, rawsize); offset = offset + rawsize; } } if (Dump != null && Dump.Length > 0 && Dump.Length >= offset) { int ImportDirectoryRva = BitConverter.ToInt32(Dump, PEOffset + 0x080); if (ImportDirectoryRva > 0 && ImportDirectoryRva < offset) { int current = 0; int ThunkToFix = 0; int ThunkData = 0; isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 12), Partkeep, 4, ref BytesRead); int NameOffset = BitConverter.ToInt32(Partkeep, 0); while (isok && NameOffset != 0) { byte[] mscoreeAscii = { 0x6D, 0x73, 0x63, 0x6F, 0x72, 0x65, 0x65, 0x2E, 0x64, 0x6C, 0x6C, 0x00 }; byte[] NameKeeper = new byte[mscoreeAscii.Length]; isok = ReadProcessMemory(hProcess, (uint)(ImageBase + NameOffset), NameKeeper, (uint)mscoreeAscii.Length, ref BytesRead); if (isok && BytesEqual(NameKeeper, mscoreeAscii)) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current), Partkeep, 4, ref BytesRead); int OriginalFirstThunk = BitConverter.ToInt32(Partkeep, 0); // OriginalFirstThunk; if (OriginalFirstThunk > 0 && OriginalFirstThunk < offset) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + OriginalFirstThunk), Partkeep, 4, ref BytesRead); ThunkData = BitConverter.ToInt32(Partkeep, 0); if (ThunkData > 0 && ThunkData < offset) { byte[] CorExeMain = { 0x5F, 0x43, 0x6F, 0x72, 0x45, 0x78, 0x65, 0x4D, 0x61, 0x69, 0x6E, 0x00 }; byte[] CorDllMain = { 0x5F, 0x43, 0x6F, 0x72, 0x44, 0x6C, 0x6C, 0x4D, 0x61, 0x69, 0x6E, 0x00 }; NameKeeper = new byte[CorExeMain.Length]; isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + 2), NameKeeper, (uint)CorExeMain.Length, ref BytesRead); if (isok && (BytesEqual(NameKeeper, CorExeMain) || BytesEqual(NameKeeper, CorDllMain))) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 16), Partkeep, 4, ref BytesRead); ThunkToFix = BitConverter.ToInt32(Partkeep, 0); // FirstThunk; break; } } } } current = current + 20; // 20 size of IMAGE_IMPORT_DESCRIPTOR isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ImportDirectoryRva + current + 12), Partkeep, 4, ref BytesRead); NameOffset = BitConverter.ToInt32(Partkeep, 0); } if (ThunkToFix > 0 && ThunkToFix < offset) { BinaryWriter writer = new BinaryWriter(new MemoryStream(Dump)); isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkToFix), Partkeep, 4, ref BytesRead); int ThunkValue = BitConverter.ToInt32(Partkeep, 0); if (isok && (ThunkValue < 0 || ThunkValue > offset)) { int fvirtualsize = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 08); int fvirtualAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 012); int frawAddress = BitConverter.ToInt32(Dump, PEOffset + 0x0F8 + 20); writer.BaseStream.Position = ThunkToFix - fvirtualAddress + frawAddress; writer.Write(ThunkData); } int EntryPoint = BitConverter.ToInt32(Dump, PEOffset + 0x028); if (EntryPoint <= 0 || EntryPoint > offset) { int ca = 0; do { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca), Partkeep, 1, ref BytesRead); if (isok && Partkeep[0] == 0x0FF) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca + 1), Partkeep, 1, ref BytesRead); if (isok && Partkeep[0] == 0x025) { isok = ReadProcessMemory(hProcess, (uint)(ImageBase + ThunkData + ca + 2), Partkeep, 4, ref BytesRead); if (isok) { int RealEntryPoint = ThunkData + ca; writer.BaseStream.Position = PEOffset + 0x028; writer.Write(RealEntryPoint); } } } ca++; }while (isok); } writer.Close(); } } } if (Dump != null && Dump.Length > 0 && Dump.Length >= offset) { FileStream fout; string filename = newdirname + "\\" + moduleName; fout = new FileStream(filename, FileMode.Create); fout.Write(Dump, 0, offset); fout.Close(); label2.ForeColor = Color.Blue; label2.Text = "Module saved in " + filename; } else { label2.ForeColor = Color.Red; label2.Text = "Failed to dump module!"; } } else { label2.ForeColor = Color.Red; label2.Text = "Failed to open process!"; } }