diff --git a/src/com/sheepit/client/os/windows/WinProcess.java b/src/com/sheepit/client/os/windows/WinProcess.java index 1bb976d..78ed2a8 100644 --- a/src/com/sheepit/client/os/windows/WinProcess.java +++ b/src/com/sheepit/client/os/windows/WinProcess.java @@ -21,6 +21,7 @@ package com.sheepit.client.os.windows; import java.io.IOException; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -61,35 +62,71 @@ public class WinProcess { } } - public WinProcess(Process process) { - this(); + private static boolean processHasGetPid() { try { - Field f = process.getClass().getDeclaredField("handle"); - f.setAccessible(true); - long val = f.getLong(process); - this.handle = new WinNT.HANDLE(); - this.handle.setPointer(Pointer.createConstant(val)); - this.pid = Kernel32.INSTANCE.GetProcessId(this.handle); + if (Process.class.getMethod("pid", null) != null) { + return true; + } } - catch (NoSuchFieldException e) { - } - catch (IllegalArgumentException e) { - } - catch (IllegalAccessException e) { + catch (NoSuchMethodException | SecurityException e) { } + return false; } - public WinProcess(int pid_) throws IOException { - this(); - this.handle = Kernel32.INSTANCE.OpenProcess(0x0400 | // PROCESS_QUERY_INFORMATION + private static long getPid(Process process) { + try { + return (long) Process.class.getMethod("pid", null).invoke(process, null); + } + catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + } + return 0; + } + + private static WinNT.HANDLE getHandleByPid(int pid_) throws IOException { + WinNT.HANDLE handle = Kernel32.INSTANCE.OpenProcess(0x0400 | // PROCESS_QUERY_INFORMATION 0x0800 | // PROCESS_SUSPEND_RESUME 0x0001 | // PROCESS_TERMINATE 0x0200 | // PROCESS_SET_INFORMATION 0x00100000, // SYNCHRONIZE false, pid_); - if (this.handle == null) { + if (handle == null) { throw new IOException("OpenProcess failed: " + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()) + " (pid: " + pid_ + ")"); } + return handle; + } + + public WinProcess(Process process) { + this(); + if (processHasGetPid()) { + int _pid = (int) getPid(process); + try { + this.handle = getHandleByPid(_pid); + } + catch (IOException e) { + } + this.pid = _pid; + } + else { + try { + Field f = process.getClass().getDeclaredField("handle"); + f.setAccessible(true); + long val = f.getLong(process); + this.handle = new WinNT.HANDLE(); + this.handle.setPointer(Pointer.createConstant(val)); + this.pid = Kernel32.INSTANCE.GetProcessId(this.handle); + } + catch (NoSuchFieldException e) { + } + catch (IllegalArgumentException e) { + } + catch (IllegalAccessException e) { + } + } + } + + public WinProcess(int pid_) throws IOException { + this(); + this.handle = getHandleByPid(pid_); this.pid = pid_; }