/** * Gets the handle of a process from the process entry. * * @param processEntry The processEntry to use * @return The handle * @throws AutomationException Thrown if the handle cannot be determined */ public static WinNT.HANDLE getHandleFromProcessEntry (final Tlhelp32.PROCESSENTRY32.ByReference processEntry) throws AutomationException { ensureWinApiInstances(); WinNT.HANDLE handle = kernel32.OpenProcess ( 0x0400 | /* PROCESS_QUERY_INFORMATION */ 0x0800 | /* PROCESS_SUSPEND_RESUME */ 0x0001 | /* PROCESS_TERMINATE */ 0x00100000 /* SYNCHRONIZE */, false, processEntry.th32ProcessID.intValue()); if (handle == null) { throw new AutomationException("OpenProcess failed"); } return handle; }
/** * Finds the given process in the process list. * * @param processEntry The process entry. * @param filenamePattern pattern matching the filename of the process. * @return The found process entry. */ public static boolean findProcessEntry (final Tlhelp32.PROCESSENTRY32.ByReference processEntry, final Pattern filenamePattern) { Kernel32 kernel32 = Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); boolean found = false; try { while (kernel32.Process32Next(snapshot, processEntry)) { String fname = Native.toString(processEntry.szExeFile); if (fname != null && filenamePattern.matcher(fname).matches()) { found = true; break; } } } finally { kernel32.CloseHandle(snapshot); } return found; }
public static Process byName(String name) { if (Platform.isWindows()) { Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference(); Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0); try { while (Kernel32.Process32Next(snapshot, entry)) { String processName = Native.toString(entry.szExeFile); if (name.equals(processName)) { return byId(entry.th32ProcessID.intValue()); } } } finally { Kernel32.CloseHandle(snapshot); } } else if (Platform.isMac() || Platform.isLinux()) { return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'")); } else { throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")"); } throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?"); }
/** * Checks if MassEffect3.exe is currently running. Uses native code. * * @return */ public static boolean isMassEffect3Running() { try { Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); boolean result = false; WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); try { while (kernel32.Process32Next(snapshot, processEntry)) { if ("MassEffect3.exe".toUpperCase().equals(Native.toString(processEntry.szExeFile).toUpperCase())) { result = true; break; } } } finally { kernel32.CloseHandle(snapshot); } ModManager.debugLogger.writeMessage("Mass Effect 3 is " + (result ? "" : "not ") + "currently running."); return result; } catch (Throwable t) { ModManager.debugLogger.writeErrorWithException("Critical native access exception: ", t); ModManager.debugLogger.writeError("Mod Manager will report that the game is not running to continue normal operations."); return false; } }
/** * Finds the given process in the process list. * * @param processEntry The process entry. * @param command Command. * @return The found process entry. */ public static boolean findProcessEntry (final Tlhelp32.PROCESSENTRY32.ByReference processEntry, final String... command) { File file = new File(command[0]); String filename = file.getName(); return findProcessEntry(processEntry,Pattern.compile(filename, Pattern.LITERAL)); }
@Test public void testFindProcessEntry_When_Not_found() { final Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); boolean found = Utils.findProcessEntry(processEntry, "notepad99.exe"); assertFalse(found); }
@Override public void initModules() { Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPMODULE32.intValue() | Tlhelp32.TH32CS_SNAPMODULE.intValue(), id()); Tlhelp32.MODULEENTRY32W entry = new Tlhelp32.MODULEENTRY32W.ByReference(); try { while (Kernel32.Module32NextW(snapshot, entry)) { String name = entry.szModule(); modules.put(name, new Module(this, name, entry.hModule.getPointer(), entry.modBaseSize.intValue())); } } finally { Kernel32.CloseHandle(snapshot); } }
/** * Gets a list of currently active processes by creating a snapshot. * * @return List of currently active processes * @throws Win32Exception * If the operation was not successful */ public static ProcessList getProcessList() throws Win32Exception { final ProcessList plist = new ProcessList(); final List<PROCESSENTRY32> list = new LinkedList<>(); final HANDLE hProcessSnap = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new DWORD(0)); PROCESSENTRY32 pe32 = new PROCESSENTRY32(); if (!Kernel32.INSTANCE.Process32First(hProcessSnap, pe32)) { throw new Win32Exception(Native.getLastError()); } do { if (pe32.th32ProcessID.intValue() != 0) { list.add(pe32); } pe32 = new PROCESSENTRY32(); } while (Kernel32.INSTANCE.Process32Next(hProcessSnap, pe32)); for (final PROCESSENTRY32 pe : list) { plist.add(new Process(pe)); } Kernel32.INSTANCE.CloseHandle(hProcessSnap); final List<DesktopWindow> windows = WindowUtils.getAllWindows(false); final IntByReference lpdwProcessId = new IntByReference(); int pid = 0; for (final DesktopWindow window : windows) { User32.INSTANCE.GetWindowThreadProcessId(window.getHWND(), lpdwProcessId); pid = lpdwProcessId.getValue(); plist.add(pid, window.getHWND()); } return plist; }
public Map<Integer, String> findProcesses(final String nameFragment) { Objects.requireNonNull(nameFragment); final String lowercaseNameFragment = nameFragment.toLowerCase(); final Map<Integer, String> processIds = new HashMap<>(); final WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot( Tlhelp32.TH32CS_SNAPPROCESS, null ); try { final Tlhelp32.PROCESSENTRY32.ByReference entryReference = new Tlhelp32.PROCESSENTRY32.ByReference(); if (kernel32.Process32First(snapshot, entryReference)) { while (kernel32.Process32Next(snapshot, entryReference)) { final String processName = new String(entryReference.szExeFile).trim(); if (processName.toLowerCase().contains(lowercaseNameFragment)) { processIds.put(entryReference.th32ProcessID.intValue(), processName); } } } } finally { kernel32.CloseHandle(snapshot); } return processIds; }
private static Map<String, Integer> findProcessPIDs(Kernel32 kernel32) { Map<String, Integer> processes = new HashMap<String, Integer>(); String matlabExe = "matlab.exe"; Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); // gets all current running processes WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); if (kernel32.Process32First(snapshot, processEntry)) { while (kernel32.Process32Next(snapshot, processEntry)) { String exePath = Native.toString(processEntry.szExeFile); exePath = exePath.toLowerCase(); // check if its a matlab process if (!exePath.equalsIgnoreCase(matlabExe)) { continue; } WinNT.HANDLE hProcess = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, processEntry.th32ProcessID.intValue()); // gets process path if (hProcess != null && hProcess.getPointer() != null) { char[] filePath = new char[1024]; Psapi32.INSTANCE.GetModuleFileNameExW(hProcess.getPointer(), null, filePath, 256); String processPath = Native.toString(filePath); int pid = kernel32.GetProcessId(hProcess); processes.put(processPath, pid); } } } return processes; }
/** * Gets the list of processes on this machine. * * @return The list of processes on this machine. */ public static List<ProcessInfo> getProcessList() throws Exception { /* Initialize the empty process list. */ List<ProcessInfo> processList = new ArrayList<ProcessInfo>(); /* Create the process snapshot. */ HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot( Tlhelp32.TH32CS_SNAPPROCESS, new DWORD(0)); Tlhelp32.PROCESSENTRY32.ByReference pe = new Tlhelp32.PROCESSENTRY32.ByReference(); for (boolean more = Kernel32.INSTANCE.Process32First(snapshot, pe); more; more = Kernel32.INSTANCE.Process32Next(snapshot, pe)) { /* Open this process; ignore processes that we cannot open. */ HANDLE hProcess = Kernel32.INSTANCE.OpenProcess( 0x1000, /* PROCESS_QUERY_LIMITED_INFORMATION */ false, pe.th32ProcessID.intValue()); if (hProcess == null) { continue; } /* Get the image name. */ char[] imageNameChars = new char[1024]; IntByReference imageNameLen = new IntByReference(imageNameChars.length); if (!Kernel32.INSTANCE.QueryFullProcessImageName( hProcess, new DWORD(0), imageNameChars, imageNameLen)) { throw new Exception("Couldn't get process image name for " + pe.th32ProcessID.intValue()); } /* Add the process info to our list. */ processList.add(new ProcessInfo( pe.th32ProcessID.intValue(), pe.th32ParentProcessID.intValue(), new String(imageNameChars, 0, imageNameLen.getValue()))); /* Close the process handle. */ Kernel32.INSTANCE.CloseHandle(hProcess); } /* Close the process snapshot. */ Kernel32.INSTANCE.CloseHandle(snapshot); /* Return the process list. */ return processList; }
@Test public void testFindProcessEntry_When_found() throws IOException { final Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); Utils.startProcess("notepad.exe"); this.andRest(); boolean found = Utils.findProcessEntry(processEntry, "notepad.exe"); assertTrue(found); }
public static native boolean Process32Next(Pointer pointer, Tlhelp32.PROCESSENTRY32 entry);
public static native boolean Module32NextW(Pointer pointer, Tlhelp32.MODULEENTRY32W entry);