private long getDiskSize(Disk disk) { long result = -1l; Kernel32 kernel32 = Kernel32.INSTANCE; HANDLE diskHandle = kernel32.CreateFile(disk.path, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, null, WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null); if (WinBase.INVALID_HANDLE_VALUE.equals(diskHandle)) { return result; } try { Memory output = new Memory(Native.getNativeSize(LARGE_INTEGER.class)); IntByReference lpBytes = new IntByReference(); boolean success = kernel32.DeviceIoControl(diskHandle, WinioctlUtil.CTL_CODE(Winioctl.FILE_DEVICE_DISK, 0x17, Winioctl.METHOD_BUFFERED, Winioctl.FILE_READ_ACCESS), null, 0, output, Native.getNativeSize(LARGE_INTEGER.class), lpBytes, null); // TODO: Check success? result = output.getLong(0); } finally { Kernel32Util.closeHandle(diskHandle); } return result; }
public static void setProcessPriority(int pid, int priority) { HANDLE hProcess = null; try { hProcess = MyKernel32.INSTANCE.OpenProcess( MyKernel32.PROCESS_ALL_ACCESS, false, pid); if (hProcess == null) hProcess = MyKernel32.INSTANCE.OpenProcess( MyKernel32.PROCESS_QUERY_INFORMATION, false, pid); if (hProcess == null) return; MyKernel32.INSTANCE.SetPriorityClass(hProcess, getPriorityFlag(priority)); } catch (Throwable ex) { ex.printStackTrace(); } finally { if (hProcess != null) MyKernel32.INSTANCE.CloseHandle(hProcess); } }
/** * Retrieves the process ID (PID) for the specified {@link Process}. * * @param process the {@link Process} for whose PID to retrieve. * @return The PID or zero if the PID couldn't be retrieved. */ public static int getProcessId(@Nullable Process process) { if (process == null) { return 0; } try { Field field; if (Platform.isWindows()) { field = process.getClass().getDeclaredField("handle"); field.setAccessible(true); int pid = Kernel32.INSTANCE.GetProcessId(new HANDLE(new Pointer(field.getLong(process)))); if (pid == 0 && LOGGER.isDebugEnabled()) { int lastError = Kernel32.INSTANCE.GetLastError(); LOGGER.debug("KERNEL32.getProcessId() failed with error {}", lastError); } return pid; } field = process.getClass().getDeclaredField("pid"); field.setAccessible(true); return field.getInt(process); } catch (Exception e) { LOGGER.warn("Failed to get process id for process \"{}\": {}", process, e.getMessage()); LOGGER.trace("", e); return 0; } }
@Override public BufferedImage getScreenshot() { final HANDLE oldBitmap = GDI.SelectObject( blitDC, outputBitmap ); try { GDI.BitBlt( blitDC, 0, 0, screenArea.width, screenArea.height, windowDC, screenArea.x, screenArea.y, GDI32.SRCCOPY ); } finally { GDI.SelectObject( blitDC, oldBitmap ); } final boolean ok = GDI.GetDIBits( blitDC, outputBitmap, 0, screenArea.height, (byte[]) null, bi, WinGDI.DIB_RGB_COLORS ); if ( ok ) { final BITMAPINFOHEADER bih = bi.bmiHeader; bih.biHeight = -Math.abs( bih.biHeight ); bih.biCompression = 0; return bufferedImageFromBitmap( blitDC, outputBitmap ); } else return null; }
@Override public void close() { if (connectionClosed != null && Kernel32.INSTANCE.WaitForSingleObject(connectionClosed, 0) != 0) { /* Set close event if not yet set */ Kernel32.INSTANCE.SetEvent(connectionClosed); } HANDLE[] handles = {serverRead, serverWrote, clientRead, clientWrote, connectionClosed}; for (HANDLE h : handles) { if (h != null) { Kernel32.INSTANCE.CloseHandle(h); } } if (view != null) { Kernel32.INSTANCE.UnmapViewOfFile(view); } serverRead = null; serverWrote = null; clientRead = null; clientWrote = null; connectionClosed = null; view = null; }
@Override public int read(byte[] bytes, int off, int count) throws IOException { HANDLE[] handles = {serverWrote, connectionClosed}; if (bytesLeft == 0) { int index = Kernel32.INSTANCE.WaitForMultipleObjects(2, handles, false, timeout); if (index == -1) { throw new IOException("wait failed, timeout"); } else if (index == 1) { // Connection closed throw new IOException("Server closed connection"); } else if (index != 0) { throw new IOException("Unexpected return result from WaitForMultipleObjects : " + index); } bytesLeft = view.getInt(0); position = 4; } int len = Math.min(count, bytesLeft); view.read(position, bytes, off, len); position += len; bytesLeft -= len; if (bytesLeft == 0) { Kernel32.INSTANCE.SetEvent(clientRead); } return len; }
public static void highlightWindow(HWND hwnd, int x, int y, int x2, int y2){ //COLORREF i.e. 0x00804070 Red = 0x70 green = 0x40 blue = 0x80 //g_hRectanglePen = CreatePen (PS_SOLID, 3, RGB(256, 0, 0)); HPEN rectPen = Gdi32Ex.instance.CreatePen(PS_SOLID, 3, 0x00000099); //RGB(255, 0, 0) HDC dc = User32Ex.instance.GetWindowDC(hwnd); if (dc != null) { // Select our created pen into the DC and backup the previous pen. HANDLE prevPen = Gdi32Ex.instance.SelectObject(dc, rectPen); // Select a transparent brush into the DC and backup the previous brush. HANDLE prevBrush = Gdi32Ex.instance.SelectObject(dc, Gdi32Ex.instance.GetStockObject(HOLLOW_BRUSH)); // Draw a rectangle in the DC covering the entire window area of the found window. Gdi32Ex.instance.Rectangle (dc, x, y, x2, y2); // Reinsert the previous pen and brush into the found window's DC. Gdi32Ex.instance.SelectObject(dc, prevPen); Gdi32Ex.instance.SelectObject(dc, prevBrush); // Finally release the DC. User32Ex.instance.ReleaseDC(hwnd, dc); } }
public static List<MEMORY_BASIC_INFORMATION> getPageRanges(WinNT.HANDLE hOtherProcess) { List<MEMORY_BASIC_INFORMATION> ret = new ArrayList<>(); MEMORY_BASIC_INFORMATION mbi; WinBase.SYSTEM_INFO si = new WinBase.SYSTEM_INFO(); Kernel32.INSTANCE.GetSystemInfo(si); Pointer lpMem = si.lpMinimumApplicationAddress; while (pointerToAddress(lpMem) < pointerToAddress(si.lpMaximumApplicationAddress)) { mbi = new MEMORY_BASIC_INFORMATION(); BaseTSD.SIZE_T t = Kernel32.INSTANCE.VirtualQueryEx(hOtherProcess, lpMem, mbi, new BaseTSD.SIZE_T(mbi.size())); if (t.longValue() == 0) { Logger.getLogger(Win32ProcessTools.class.getName()).log(Level.SEVERE, "Cannot get page ranges. Last error:" + Kernel32.INSTANCE.GetLastError()); break; } ret.add(mbi); lpMem = new Pointer(pointerToAddress(mbi.baseAddress) + mbi.regionSize.longValue()); } return ret; }
/** * @param hPhysicalMonitor Handle to the physical monitor. * @param szPhysicalMonitorDescription */ public MonitorJna(HANDLE hPhysicalMonitor, String szPhysicalMonitorDescription) { this.handle = hPhysicalMonitor; this.name = szPhysicalMonitorDescription; DWORDByReference minBrightness = new DWORDByReference(); DWORDByReference curBrightness = new DWORDByReference(); DWORDByReference maxBrightness = new DWORDByReference(); check(Dxva2.INSTANCE.GetMonitorBrightness(handle, minBrightness, curBrightness, maxBrightness)); minBright = minBrightness.getValue().intValue(); maxBright = maxBrightness.getValue().intValue(); curBright = curBrightness.getValue().intValue(); }
/** Creates a Windows named pipe bound to a path */ public static WindowsNamedPipe createPipeWithPath(String path) throws IOException { HANDLE pipeHandle = api.CreateFile( path, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, 0, null, WinNT.OPEN_EXISTING, WinNT.FILE_FLAG_OVERLAPPED, null); if (WinNT.INVALID_HANDLE_VALUE.equals(pipeHandle)) { throw new IOException( "Failed to open a named pipe " + path + " error: " + api.GetLastError()); } return new WindowsNamedPipe(pipeHandle, createEvent(), createEvent()); }
/** * Kill a process from its PID. * * @param pid the PID * @param code the code * @return true, if successful */ public static boolean kill(final int pid, final int code) { if (pid <= 0) { return false; } final HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(MyKernel32.PROCESS_TERMINATE, false, pid); if (hProcess == null) { win32ErrorRuntime("OpenProcess"); } boolean result = false; try { result = Kernel32.INSTANCE.TerminateProcess(hProcess, code); if (!result) { win32ErrorRuntime("TerminateProcess"); } } finally { Kernel32.INSTANCE.CloseHandle(hProcess); } return result; }
public static String getAppUserModelId(HWND hwnd) { IntByReference processID = new IntByReference(); User32.INSTANCE.GetWindowThreadProcessId(hwnd, processID); HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processID.getValue()); UINTByReference length = new UINTByReference(); Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, null); char[] modelID = new char[length.getValue().intValue()]; Kernel32Ext.INSTANCE.GetApplicationUserModelId(hProcess, length, modelID); return new String(Native.toString(modelID)); }
/** * Kill. * * @param pid * the pid * @param code * the code * * @return true, if successful */ public static boolean kill(int pid, int code) { if (pid <= 0) return false; HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess( MyKernel32.PROCESS_TERMINATE, false, pid); boolean result = MyKernel32.INSTANCE.TerminateProcess(hProcess, code); Thread.yield(); if (!result) System.out.println("process kill failed: " + pid + " code=" + code); MyKernel32.INSTANCE.CloseHandle(hProcess); return result; }
/** * Performs {@code TerminateProcess} on the specified Windows * {@link Process}. * * @param processInfo the {@link ProcessInfo} referencing the * {@link Process} to terminate. * @return {@code true} if {@code TerminateProcess} was executed, * {@code false} otherwise. */ protected boolean stopWindowsProcessTerminateProcess(@Nonnull ProcessInfo processInfo) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Attempting to stop timed out process \"{}\" ({}) with TerminateProcess", processInfo.getName(), processInfo.getPID() ); } HANDLE hProc = Kernel32.INSTANCE.OpenProcess( Kernel32.PROCESS_TERMINATE, false, processInfo.getPID() ); if (hProc == null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Failed to get Windows handle for process \"{}\" ({}) during TerminateProcess", processInfo.getName(), processInfo.getPID() ); } return false; } boolean result = Kernel32.INSTANCE.TerminateProcess(hProc, 1); Kernel32.INSTANCE.CloseHandle(hProc); if (LOGGER.isTraceEnabled()) { if (result) { LOGGER.trace("TerminateProcess performed for process \"{}\" ({})", processInfo.getName(), processInfo.getPID()); } else { LOGGER.trace("TerminateProcess failed for process \"{}\" ({})", processInfo.getName(), processInfo.getPID()); } } return result; }
/** * 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; }
/** * Whether the given process is a 64-bit application or not. A 32-bit * application that runs in the WoW64 environment is not considered as * 64-bit application, since they are restricted to the 32-bit memory space. * * @param hProcess * Handle to the process in question * @return <tt>True</tt> if the given process is a 64-bit application, * <tt>false</tt> otherwise. * @throws Win32Exception * If the operation was not successful */ public static boolean is64Bit(final HANDLE hProcess) throws Win32Exception { if (System.getenv(SystemProperties.PRC_ARCH) == Masks.PRC_ARCH_32BIT) { return false; } final IntByReference isWow64 = new IntByReference(); final boolean success = Kernel32.INSTANCE.IsWow64Process(hProcess, isWow64); if (!success) { throw new Win32Exception(Native.getLastError()); } return isWow64.getValue() == 0; }
public BufferedImage capture(final HWND hWnd) { final HDC hdcWindow = User32.INSTANCE.GetDC(hWnd); final HDC hdcMemDC = GDI32.INSTANCE.CreateCompatibleDC(hdcWindow); final RECT bounds = new RECT(); User32Extra.INSTANCE.GetClientRect(hWnd, bounds); final int width = bounds.right - bounds.left; final int height = bounds.bottom - bounds.top; if (width * height <= 0) { return null; } final HBITMAP hBitmap = GDI32.INSTANCE.CreateCompatibleBitmap(hdcWindow, width, height); final HANDLE hOld = GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap); GDI32Extra.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcWindow, 0, 0, WinGDIExtra.SRCCOPY); GDI32.INSTANCE.SelectObject(hdcMemDC, hOld); GDI32.INSTANCE.DeleteDC(hdcMemDC); final BITMAPINFO bmi = new BITMAPINFO(); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = -height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = WinGDI.BI_RGB; final Memory buffer = new Memory(width * height * 4); GDI32.INSTANCE.GetDIBits(hdcWindow, hBitmap, 0, height, buffer, bmi, WinGDI.DIB_RGB_COLORS); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, width, height, buffer.getIntArray(0, width * height), 0, width); GDI32.INSTANCE.DeleteObject(hBitmap); User32.INSTANCE.ReleaseDC(hWnd, hdcWindow); return image; }
public static BufferedImage getIcon(final String path, final int num, final int width, final int height) throws FileNotFoundException { final HMODULE hinst = org.appwork.jna.winapi.kernel32.Kernel.I.LoadLibraryExA(path, null, org.appwork.jna.winapi.kernel32.Kernel.LOAD_LIBRARY_AS_DATAFILE); // Kernel32.INSTANCE.e // final HMODULE hinst = // final int err = Kernel32.INSTANCE.GetLastError(); if (hinst == null) { throw new FileNotFoundException(path + " could not be loaded"); } final HANDLE hicon = com.sun.jna.platform.win32.User32.INSTANCE.LoadImage(hinst, "IDR_MAINFRAME", 1, width, height, 0); if (hicon == null) { throw new FileNotFoundException(path + ": No icon #" + num); } return getImageByHICON(width, height, hicon); }
public static BufferedImage getScreenshot( final Rectangle bounds ) { HDC windowDC = GDI.GetDC( USER.GetDesktopWindow() ); HBITMAP outputBitmap = GDI.CreateCompatibleBitmap( windowDC, bounds.width, bounds.height ); try { HDC blitDC = GDI.CreateCompatibleDC( windowDC ); try { HANDLE oldBitmap = GDI.SelectObject( blitDC, outputBitmap ); try { GDI.BitBlt( blitDC, 0, 0, bounds.width, bounds.height, windowDC, bounds.x, bounds.y, GDI32.SRCCOPY ); } finally { GDI.SelectObject( blitDC, oldBitmap ); } BITMAPINFO bi = new BITMAPINFO( 40 ); bi.bmiHeader.biSize = 40; boolean ok = GDI.GetDIBits( blitDC, outputBitmap, 0, bounds.height, (byte[]) null, bi, WinGDI.DIB_RGB_COLORS ); if ( ok ) { BITMAPINFOHEADER bih = bi.bmiHeader; bih.biHeight = -Math.abs( bih.biHeight ); bi.bmiHeader.biCompression = 0; return bufferedImageFromBitmap( blitDC, outputBitmap, bi ); } else return null; } finally { GDI.DeleteObject( blitDC ); } } finally { GDI.DeleteObject( outputBitmap ); } }
private HANDLE lockMutex() throws IOException { PointerByReference securityDescriptor = new PointerByReference(); Advapi32.INSTANCE.ConvertStringSecurityDescriptorToSecurityDescriptor(EVERYONE_SYNCHRONIZE_SDDL, 1, securityDescriptor, null); Advapi32.SECURITY_ATTRIBUTES sa = new Advapi32.SECURITY_ATTRIBUTES(); sa.nLength = sa.size(); sa.lpSecurityDescriptor = securityDescriptor.getValue(); sa.bInheritHandle = false; HANDLE mutex = Kernel32.INSTANCE.CreateMutex(sa, false, memoryName + "_CONNECT_MUTEX"); Kernel32.INSTANCE.LocalFree(securityDescriptor.getValue()); if (Kernel32.INSTANCE.WaitForSingleObject(mutex, timeout) == -1) { Kernel32.INSTANCE.CloseHandle(mutex); throw new IOException("wait failed (timeout, last error = " + Kernel32.INSTANCE.GetLastError()); } return mutex; }
private int getConnectNumber() throws IOException { HANDLE connectRequest; try { connectRequest = openEvent(memoryName + "_CONNECT_REQUEST"); } catch (LastErrorException lee) { try { connectRequest = openEvent("Global\\" + memoryName + "_CONNECT_REQUEST"); memoryName = "Global\\" + memoryName; } catch (LastErrorException lee2) { throw new IOException("getConnectNumber() fails : " + lee2.getMessage() + " " + memoryName); } } HANDLE connectAnswer = openEvent(memoryName + "_CONNECT_ANSWER"); HANDLE mutex = lockMutex(); Pointer connectData = null; try { Kernel32.INSTANCE.SetEvent(connectRequest); connectData = mapMemory(memoryName + "_CONNECT_DATA", Kernel32.FILE_MAP_READ, 4); int ret = Kernel32.INSTANCE.WaitForSingleObject(connectAnswer, timeout); if (ret != 0) { throw new IOException("WaitForSingleObject returned " + ret + ", last error " + Kernel32.INSTANCE.GetLastError()); } return connectData.getInt(0); } finally { Kernel32.INSTANCE.ReleaseMutex(mutex); Kernel32.INSTANCE.CloseHandle(mutex); if (connectData != null) { Kernel32.INSTANCE.UnmapViewOfFile(connectData); } Kernel32.INSTANCE.CloseHandle(connectRequest); Kernel32.INSTANCE.CloseHandle(connectAnswer); } }
@Override public void write(byte[] bytes, int off, int count) throws IOException { int bytesToWrite = count; int buffPos = off; HANDLE[] handles = {serverRead, connectionClosed}; while (bytesToWrite > 0) { int index = Kernel32.INSTANCE.WaitForMultipleObjects(2, handles, false, timeout); if (index == -1) { // wait failed, probably timeout throw new IOException("WaitForMultipleObjects() failed, timeout"); } else if (index == 1) { // Connection closed throw new IOException("Server closed connection"); } else if (index != 0) { throw new IOException("Unexpected return result from WaitForMultipleObjects : " + index); } int chunk = Math.min(bytesToWrite, BUFFERLEN); view.setInt(0, chunk); view.write(4, bytes, buffPos, chunk); buffPos += chunk; bytesToWrite -= chunk; if (!Kernel32.INSTANCE.SetEvent(clientWrote)) { throw new IOException("SetEvent failed"); } } }
private void getProcessInfo() { if (pid == 0) return; char[] buffer = new char[1026]; Pointer process = Kernel32Ex.instance.OpenProcess(Api.PROCESS_QUERY_INFORMATION | Api.PROCESS_VM_READ, false, new Pointer(pid)); PsapiEx.instance.GetModuleBaseNameW(process, null, buffer, 512); processName = Native.toString(buffer); Kernel32Ex.instance.CloseHandle(new HANDLE(process)); is64bit = Api.isProcess64bit((int)pid); }
public static boolean isProcess64bit(int pid) { try { SYSTEM_INFO lpSystemInfo = new SYSTEM_INFO(); Kernel32Ex.instance.GetNativeSystemInfo(lpSystemInfo); if (lpSystemInfo.processorArchitecture.dwOemID.intValue() == 0) { System.out.println("intel x86"); //not a 64 bit os return false; } Pointer process = Kernel32Ex.instance.OpenProcess(Api.PROCESS_QUERY_INFORMATION | Api.PROCESS_VM_READ, false, new Pointer(pid)); IntByReference isWow64 = new IntByReference(0); if (!Kernel32Ex.instance.IsWow64Process(new HANDLE(process), isWow64)) { //handle error } //System.out.println("isProcess64bit " + pid + " = " + isWow64.getValue()); Kernel32Ex.instance.CloseHandle(new HANDLE(process)); if (isWow64.getValue() == 1) return false; return true; //CloseHandle() } catch(Exception ex) { ex.printStackTrace(); } return false; }
public static void SelectListViewItemByIndex(HWND listViewHwnd, int index) { /* HANDLE hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, 0x0000c130); LPVOID epLvi = VirtualAllocEx(hProcess, NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); LVITEM lvi; lvi.state = LVIS_FOCUSED | LVIS_SELECTED; lvi.stateMask = LVIS_FOCUSED | LVIS_SELECTED; SIZE_T cbWritten = 0; WriteProcessMemory(hProcess, epLvi, &lvi, sizeof(lvi), &cbWritten); DWORD dw = SendMessage((HWND)0x00020C4C, LVM_SETITEMSTATE, 1, (LPARAM)epLvi); VirtualFreeEx(hProcess, epLvi, 4096, MEM_DECOMMIT | MEM_RELEASE); CloseHandle(hProcess); */ PointerByReference pointer = new PointerByReference(); User32Ex.instance.GetWindowThreadProcessId(listViewHwnd, pointer); int pid = pointer.getPointer().getInt(0); Pointer process = Kernel32Ex.instance.OpenProcess(Api.PROCESS_VM_WRITE | Api.PROCESS_VM_OPERATION, false, new Pointer(pid)); IntByReference addr = new IntByReference(0); SIZE_T size = new SIZE_T(4096); IntByReference epLvi = Kernel32Ex.instance.VirtualAllocEx(new HANDLE(process), addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); LVITEM_VISTA lvitem = new LVITEM_VISTA(); lvitem.stateMask = LVIS_FOCUSED | LVIS_SELECTED; lvitem.state = LVIS_FOCUSED | LVIS_SELECTED; IntByReference bytesWritten = new IntByReference(); Api.Kernel32Ex.instance.WriteProcessMemory(new HANDLE(process), epLvi, lvitem.getPointer(), lvitem.size(),bytesWritten); Api.User32Ex.instance.SendMessage(listViewHwnd, LVM_SETITEMSTATE, new WPARAM(index), lvitem); Api.Kernel32Ex.instance.VirtualFreeEx(new HANDLE(process), epLvi, new SIZE_T(4096), new DWORD(MEM_DECOMMIT | MEM_RELEASE)); Api.Kernel32Ex.instance.CloseHandle(new HANDLE(process)); }
/** * Get the priority of a process. * * @param pid * The PID of the process to check. * @return Return the priority of the process if success, return null if * failed. */ public static ProcPriority getPriority(final int pid) { ProcPriority procPriority = null; if ((pid > 0) && exists(pid)) { HANDLE handle = Kernel32.INSTANCE.OpenProcess(0x0400, false, pid); if (handle != null) { int priority = Kernel32Ext.INSTANCE.GetPriorityClass(handle); switch (priority) { case IDLE_PRIORITY_CLASS: procPriority = ProcPriority.LOW; break; case BELOW_NORMAL_PRIORITY_CLASS: procPriority = ProcPriority.BELOW_NORMAL; break; case NORMAL_PRIORITY_CLASS: procPriority = ProcPriority.NORMAL; break; case ABOVE_NORMAL_PRIORITY_CLASS: procPriority = ProcPriority.ABOVE_NORMAL; break; case HIGH_PRIORITY_CLASS: procPriority = ProcPriority.HIGH; break; case REALTIME_PRIORITY_CLASS: procPriority = ProcPriority.REALTIME; break; } } } return procPriority; }
private static boolean unsetGuard(HANDLE hOtherProcess, MEMORY_BASIC_INFORMATION mbi) { if (!hasGuard(mbi)) { return true; } int oldProt = mbi.protect.intValue(); int newProt = oldProt - WinNT.PAGE_GUARD; IntByReference oldProtRef = new IntByReference(); boolean ok = Kernel32.INSTANCE.VirtualProtectEx(hOtherProcess, new WinDef.LPVOID(pointerToAddress(mbi.baseAddress)), mbi.regionSize, newProt, oldProtRef); if (ok) { mbi.protect = new NativeLong(newProt); return true; } return false; }
private static boolean setGuard(HANDLE hOtherProcess, MEMORY_BASIC_INFORMATION mbi) { if (hasGuard(mbi)) { return true; } int oldProt = mbi.protect.intValue(); int newProt = oldProt | WinNT.PAGE_GUARD; IntByReference oldProtRef = new IntByReference(); boolean ok = Kernel32.INSTANCE.VirtualProtectEx(hOtherProcess, new WinDef.LPVOID(pointerToAddress(mbi.baseAddress)), mbi.regionSize, newProt, oldProtRef); if (ok) { mbi.protect = new NativeLong(newProt); return true; } return false; }
public static boolean adjustPrivileges() { WinNT.TOKEN_PRIVILEGES tp = new WinNT.TOKEN_PRIVILEGES(1); WinNT.TOKEN_PRIVILEGES oldtp = new WinNT.TOKEN_PRIVILEGES(1); WinNT.LUID luid = new WinNT.LUID(); WinNT.HANDLEByReference hTokenRef = new WinNT.HANDLEByReference(); if (!Advapi32.INSTANCE.OpenProcessToken(Kernel32.INSTANCE.GetCurrentProcess(), WinNT.TOKEN_ADJUST_PRIVILEGES | WinNT.TOKEN_QUERY, hTokenRef)) { return false; } WinNT.HANDLE hToken = hTokenRef.getValue(); if (!Advapi32.INSTANCE.LookupPrivilegeValue(null, WinNT.SE_DEBUG_NAME, luid)) { Kernel32.INSTANCE.CloseHandle(hToken); return false; } tp.PrivilegeCount = new WinDef.DWORD(1); tp.Privileges = new WinNT.LUID_AND_ATTRIBUTES[1]; tp.Privileges[0] = new WinNT.LUID_AND_ATTRIBUTES(luid, new WinDef.DWORD(WinNT.SE_PRIVILEGE_ENABLED)); IntByReference retSize = new IntByReference(0); if (!Advapi32.INSTANCE.AdjustTokenPrivileges(hToken, false, tp, tp.size(), oldtp, retSize)) { Kernel32.INSTANCE.CloseHandle(hToken); return false; } Kernel32.INSTANCE.CloseHandle(hToken); privAdjusted = true; return true; }
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; }
static void enumerate(HMONITOR hMonitor) { System.out.println("Found HMONITOR: " + hMonitor.getPointer().toString()); MONITORINFOEX info = new MONITORINFOEX(); User32.INSTANCE.GetMonitorInfo(hMonitor, info); System.out.println("Screen " + info.rcMonitor); System.out.println("Work area " + info.rcWork); boolean isPrimary = (info.dwFlags & WinUser.MONITORINFOF_PRIMARY) != 0; System.out.println("Primary? " + (isPrimary ? "yes" : "no")); System.out.println("Device " + new String(info.szDevice)); DWORDByReference pdwNumberOfPhysicalMonitors = new DWORDByReference(); Dxva2.INSTANCE.GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, pdwNumberOfPhysicalMonitors); int monitorCount = pdwNumberOfPhysicalMonitors.getValue().intValue(); System.out.println("HMONITOR is linked to " + monitorCount + " physical monitors"); PHYSICAL_MONITOR[] physMons = new PHYSICAL_MONITOR[monitorCount]; Dxva2.INSTANCE.GetPhysicalMonitorsFromHMONITOR(hMonitor, monitorCount, physMons); for (int i = 0; i < monitorCount; i++) { HANDLE hPhysicalMonitor = physMons[0].hPhysicalMonitor; System.out.println("Monitor " + i + " - " + new String(physMons[i].szPhysicalMonitorDescription)); enumeratePhysicalMonitor(hPhysicalMonitor); } }
@Override public void setIcon (FileHandle iconCacheFolder, FileHandle icoFile, FileHandle pngFile) { //WinAPI can't read icon from JAR, needs copying to some other location FileHandle cachedIco = iconCacheFolder.child(icoFile.name()); if (cachedIco.exists() == false) icoFile.copyTo(cachedIco); try { HANDLE hImage = User32.INSTANCE.LoadImage(Kernel32.INSTANCE.GetModuleHandle(""), cachedIco.path(), WinUser.IMAGE_ICON, 0, 0, WinUser.LR_LOADFROMFILE); User32.INSTANCE.SendMessageW(User32.INSTANCE.GetActiveWindow(), User32.WM_SETICON, new WPARAM(User32.BIG_ICON), hImage); } catch (Exception e) { throw new IllegalStateException(e); } }
private WindowsNamedPipe(HANDLE pipeHandle, HANDLE readerWaitable, HANDLE writerWaitable) { this.pipeHandle = pipeHandle; this.readerWaitable = readerWaitable; this.writerWaitable = writerWaitable; this.in = new NamedPipeInputStream(); this.out = new NamedPipeOutputStream(); }
private static HANDLE createEvent() throws IOException { HANDLE event = api.CreateEvent(null, true, false, null); if (event == null) { throw new IOException("CreateEvent() failed. Error: " + api.GetLastError()); } return event; }
/** Sets the private field 'handle' of a field descriptor */ private void writefd(final FileDescriptor fd, final HANDLE pointer) { try { final Field handleField = FileDescriptor.class.getDeclaredField("handle"); handleField.setAccessible(true); handleField.setLong(fd, Pointer.nativeValue(pointer.getPointer())); } catch (Exception e) { e.printStackTrace(); } }
/** * Safely closes a handle. * @param ref handle by reference */ private static void closeSafely(final HANDLEByReference ref) { final HANDLE handle = ref.getValue(); if (handle != null) { Kernel32.INSTANCE.CloseHandle(handle); } }
public long GetApplicationUserModelId(HANDLE hProcess, UINTByReference applicationUserModelIdLength, char[] applicationUserModelId);
boolean OpenProcessToken(HANDLE ProcessHandle, int DesiredAccess, PointerByReference TokenHandle);
/** * Gets the process. * * @param pid * the pid * * @return the process */ public static Process getProcess(int pid) { WindowsXPProcess result = new WindowsXPProcess(); HANDLE hProcess = MyKernel32.INSTANCE.OpenProcess( MyKernel32.PROCESS_ALL_ACCESS, false, pid); if (hProcess == null) hProcess = MyKernel32.INSTANCE.OpenProcess( MyKernel32.PROCESS_QUERY_INFORMATION, false, pid); if (hProcess == null) return null; result._pid = pid; result._processInformation = new PROCESS_INFORMATION(); result._processInformation.dwProcessId = pid; result._processInformation.hProcess = hProcess; result._cmd = result.getCommandLineInternal(); // this does not always work (why ??), if so try again, then this // normally does // on win64 PEB of 64 bit cannot be accessed from wow -> use wmi if (result._cmd.equals("?")) result._cmd = result.getCommandLineInternalWMI(); if ("?".equals(result._cmd)) { System.err.println("Could not get commandline"); } // else // System.out.println("Command line of " + pid + ": " + result._cmd); PointerByReference hToken = new PointerByReference(); HANDLE hp = new HANDLE(); hp.setPointer(hProcess.getPointer()); if (MyAdvapi.INSTANCE.OpenProcessToken(hp, MyAdvapi.TOKEN_READ, hToken)) { IntByReference dwSize = new IntByReference(); MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, null, 0, dwSize); { Memory pTokenUser = new Memory(dwSize.getValue()); if (MyAdvapi.INSTANCE.GetTokenInformation(hToken.getValue(), MyAdvapi.TokenUser, pTokenUser, dwSize.getValue(), dwSize)) { MyAdvapi.TOKEN_USER tokenUser = new MyAdvapi.TOKEN_USER( pTokenUser); Pointer lpSid = tokenUser.User.Sid; Memory lpName = new Memory(256); IntByReference cchName = new IntByReference(); cchName.setValue(256); Memory lpReferencedDomainName = new Memory(256); IntByReference cchReferencedDomainName = new IntByReference(); cchReferencedDomainName.setValue(256); IntByReference peUse = new IntByReference(); if (MyAdvapi.INSTANCE.LookupAccountSidW(null, lpSid, lpName, cchName, lpReferencedDomainName, cchReferencedDomainName, peUse)) result._user = lpReferencedDomainName .getString(0, true) + "\\" + lpName.getString(0, true); ; // System.out.println(result._user); } } if (result._user == null) System.out.println("could not get user name OS error #" + MyKernel32.INSTANCE.GetLastError()); MyKernel32.INSTANCE.CloseHandle(hToken.getValue()); } return result; }