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; }
/** * @param process NiFi Registry Process Reference * @param logger Logger Reference for Debug * @return Returns pid or null in-case pid could not be determined * This method takes {@link Process} and {@link Logger} and returns * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b> * In-case it fails to determine the pid, it will return Null. * Purpose for the Logger is to log any interaction for debugging. */ private static Long getWindowsProcessId(final Process process, final Logger logger) { /* determine the pid on windows plattforms */ try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handl = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handl)); int ret = kernel.GetProcessId(handle); logger.debug("Detected pid: {}", ret); return Long.valueOf(ret); } catch (final IllegalAccessException | NoSuchFieldException nsfe) { logger.debug("Could not find PID for child process due to {}", nsfe); } return null; }
/** * Gets the pattern * @return The pattern * @throws AutomationException Something went wrong getting the pattern */ private IUIAutomationInvokePattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }
/** * Gets the pointer * @return Underlying pointer * @throws AutomationException Automation has gone wrong */ private IUIAutomationSelectionPattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }
/** * Gets the pattern interface. * * @return The toggle pattern interface * @throws AutomationException Something went wrong with the automation library. */ private IUIAutomationTogglePattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }
/** * Gets the pattern. * @return The pattern * @throws AutomationException Something went wrong getting the pattern */ private IUIAutomationExpandCollapsePattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }
/** * Gets the selection container * @return The selection container * @throws AutomationException Something has gone wrong in automation */ public AutomationElement getSelectionContainer() throws AutomationException { PointerByReference pbr = new PointerByReference(); final int res = this.getPattern().getCurrentSelectionContainer(pbr); if (res != 0) { throw new AutomationException(res); } Unknown unkConditionA = makeUnknown(pbr.getValue()); PointerByReference pUnknownA = new PointerByReference(); WinNT.HRESULT resultA = unkConditionA.QueryInterface(new Guid.REFIID(IUIAutomationElement.IID), pUnknownA); if (COMUtils.SUCCEEDED(resultA)) { return new AutomationElement(convertPointerToElementInterface(pUnknownA)); } else { throw new AutomationException(resultA.intValue()); } }
/** * Gets the element associated with the grid cell * @param x X position * @param y Y position * @return The Element from the grid * @throws AutomationException Something amiss with automation */ public AutomationElement getItem(int x, int y) throws AutomationException { PointerByReference cell = this.getRawItem(x, y); Unknown uRoot = makeUnknown(cell.getValue()); PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = uRoot.QueryInterface(new Guid.REFIID(IUIAutomationElement.IID), pbr); if (COMUtils.SUCCEEDED(result0)) { return new AutomationElement(convertPointerToElementInterface(pbr)); } else { throw new AutomationException(result0.intValue()); } }
/** * 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; }
/** * Creates the wrapper. */ private void createWrapper() { CANALIZED_OLE32_INSTANCE = Canalizer.canalize(com.sun.jna.platform.win32.Ole32.INSTANCE); CANALIZED_OLE32_INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_APARTMENTTHREADED); PointerByReference pbr = new PointerByReference(); WinNT.HRESULT hr = CANALIZED_OLE32_INSTANCE.CoCreateInstance( IUIAutomation.CLSID, null, WTypes.CLSCTX_SERVER, IUIAutomation.IID, pbr); COMUtils.checkRC(hr); unknown = new Unknown(pbr.getValue()); }
/** * Gets the raw pattern from the given element. * @param item The Element * @return The raw collapse pattern * @throws AutomationException Failed to get pattern */ public IUIAutomationExpandCollapsePattern getExpandCollapsePatternFromItem(AutomationElement item) throws AutomationException { PointerByReference pElement = item.getPattern(PatternID.ExpandCollapse.getValue()); Unknown unkConditionA = makeUnknown(pElement.getValue()); PointerByReference pUnknownA = new PointerByReference(); WinNT.HRESULT resultA = unkConditionA.QueryInterface(new Guid.REFIID(IUIAutomationExpandCollapsePattern.IID), pUnknownA); if (COMUtils.SUCCEEDED(resultA)) { return IUIAutomationExpandCollapsePatternConverter.PointerToInterface(pUnknownA); } else { throw new AutomationException("QueryInterface failed"); } }
@Test @Ignore("Need to build up the mocking") public void test_getItem_Throws_Exception_When_Pattern_Returns_Error_From_GetItem() throws Exception { Grid pattern = new Grid(rawPattern); Grid spyPattern = Mockito.spy(pattern); doAnswer(invocation -> new WinNT.HRESULT(0)).when(mockUnknown).QueryInterface(any(Guid.REFIID.class), any(PointerByReference.class)); IUIAutomationGridPattern mockGrid = Mockito.mock(IUIAutomationGridPattern.class); doReturn(mockUnknown) .when(spyPattern) .makeUnknown(any()); AutomationElement element = spyPattern.getItem(0,0); }
@Test public void testCreateFalseCondtion() { UIAutomation instance = UIAutomation.getInstance(); try { PointerByReference condition = instance.createFalseCondition(); Unknown unk = new Unknown(condition.getValue()); PointerByReference pUnknown1 = new PointerByReference(); WinNT.HRESULT result = unk.QueryInterface(new Guid.REFIID(IUIAutomationCondition.IID), pUnknown1); assertTrue("Create FalseCondition:" + COMUtils.SUCCEEDED(result), COMUtils.SUCCEEDED(result)); } catch (AutomationException ex) { assertTrue("Ouch", false); } }
@Test public void testCreatePropertyCondition() { UIAutomation instance = UIAutomation.getInstance(); Variant.VARIANT.ByValue variant = new Variant.VARIANT.ByValue(); WTypes.BSTR sysAllocated = OleAuto.INSTANCE.SysAllocString("SOMETHING"); variant.setValue(Variant.VT_BSTR, sysAllocated); try { try { PointerByReference pCondition = instance.createPropertyCondition(PropertyID.AutomationId.getValue(), variant); Unknown unk = new Unknown(pCondition.getValue()); PointerByReference pUnknown1 = new PointerByReference(); WinNT.HRESULT result = unk.QueryInterface(new Guid.REFIID(IUIAutomationCondition.IID), pUnknown1); assertTrue("CreatePropertyCondition:" + COMUtils.SUCCEEDED(result), COMUtils.SUCCEEDED(result)); } catch (AutomationException ex) { assertTrue("Exception", false); } } finally { OleAuto.INSTANCE.SysFreeString(sysAllocated); } }
@Test public void testCreateTrueCondition() { UIAutomation instance = UIAutomation.getInstance(); try { PointerByReference pCondition = instance.createTrueCondition(); PointerByReference first = new PointerByReference(); // Check whether it is a condition Unknown unk = new Unknown(pCondition.getValue()); PointerByReference pUnk = new PointerByReference(); Guid.REFIID refiid3 = new Guid.REFIID(IUIAutomationCondition.IID); PointerByReference pUnknown1 = new PointerByReference(); WinNT.HRESULT result = unk.QueryInterface(refiid3, pUnknown1); assertTrue("Create TrueCondition:" + COMUtils.SUCCEEDED(result), COMUtils.SUCCEEDED(result)); } catch (AutomationException ex) { assertTrue("Exception", false); } }
public static long freeSpace(File file) { if (!file.isDirectory() || !file.exists()) return -2; WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfFreeBytes = new WinNT.LARGE_INTEGER.ByReference(); lpTotalNumberOfFreeBytes.clear(); boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(), null, null, lpTotalNumberOfFreeBytes); if (ret) return lpTotalNumberOfFreeBytes.getValue(); else { String s = Kernel32Util .formatMessageFromLastErrorCode(Kernel32.INSTANCE .GetLastError()); log.severe("error in File.freeSpace getting for \"" + file.getPath() + "\" " + s); } return -1; }
public static long totalSpace(File file) { if (!file.isDirectory() || !file.exists()) return -2; WinNT.LARGE_INTEGER.ByReference lpTotalNumberOfBytes = new WinNT.LARGE_INTEGER.ByReference(); lpTotalNumberOfBytes.clear(); boolean ret = Kernel32.INSTANCE.GetDiskFreeSpaceEx(file.getPath(), null, lpTotalNumberOfBytes, null); if (ret) return lpTotalNumberOfBytes.getValue(); else { String s = Kernel32Util .formatMessageFromLastErrorCode(Kernel32.INSTANCE .GetLastError()); log.severe("error in File.totalSpace getting for \"" + file.getPath() + "\" " + s); } return -1; }
/** * Delete a value. * * @param rootKey * root key * @param subKeyName * key name * @param name * value name * @return true on success */ public static boolean deleteValue(REGISTRY_ROOT_KEY rootKey, String subKeyName, String name) { Advapi32 advapi32; HKEY handle; boolean ret = true; advapi32 = Advapi32.INSTANCE; handle = openKey(rootKey, subKeyName, WinNT.KEY_READ | WinNT.KEY_WRITE); if (handle != null) { if (advapi32.RegDeleteValue(handle, name) == WINERROR.ERROR_SUCCESS) { ret = true; } advapi32.RegCloseKey(handle); } return (ret); }
/** * Writes a String value. * * @param rootKey * root key * @param subKeyName * key name * @param name * value name * @param value * value * @throws java.io.UnsupportedEncodingException * on error * @return true on success */ public static boolean setStringValue(REGISTRY_ROOT_KEY rootKey, String subKeyName, String name, String value) throws UnsupportedEncodingException { Advapi32 advapi32; HKEY handle; byte[] data; boolean ret = false; data = Arrays.copyOf(value.getBytes("UTF-16LE"), value.length() * 2 + 2); advapi32 = Advapi32.INSTANCE; handle = openKey(rootKey, subKeyName, WinNT.KEY_READ | WinNT.KEY_WRITE); if (handle != null) { if (advapi32.RegSetValueEx(handle, name, 0, WinNT.REG_SZ, data, data.length) == WINERROR.ERROR_SUCCESS) { ret = true; } advapi32.RegCloseKey(handle); } return (ret); }
/** * Delete a key. * * @param rootKey * root key * @param parent * name of parent key * @param name * key name * @return true on success */ public static boolean deleteKey(REGISTRY_ROOT_KEY rootKey, String parent, String name) { Advapi32 advapi32; HKEY handle = null; boolean ret = false; advapi32 = Advapi32.INSTANCE; handle = openKey(rootKey, parent, WinNT.KEY_READ); if (handle != null) { if (advapi32.RegDeleteKey(handle, name) == WINERROR.ERROR_SUCCESS) { ret = true; } else { ret = false; } advapi32.RegCloseKey(handle); } return (ret); }
private LRESULT processMessage(HWND hwnd, WPARAM wParam, LPARAM lParam) { WinBase.SECURITY_ATTRIBUTES psa = null; String mapname = readFileNameFromInput(lParam); sharedFile = libK.CreateFileMapping(WinBase.INVALID_HANDLE_VALUE, psa, WinNT.PAGE_READWRITE, 0, 8192, // AGENT_MAX_MSGLEN mapname); sharedMemory = Kernel32.INSTANCE.MapViewOfFile(sharedFile, WinNT.SECTION_MAP_WRITE, 0, 0, 0); int ret = answerIfDevicePresent(sharedMemory); disconnectFromSharedMemory(); return new LRESULT(ret); }
public boolean terminate() { Kernel32.HANDLE process = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_TERMINATE | WinNT.SYNCHRONIZE, false, pid); if (process.getPointer() == null) { Runner.logger.warn("Unable to find process " + name + "(" + pid + ")"); return false; } else { Kernel32.INSTANCE.TerminateProcess(process, 1); int wait = Kernel32.INSTANCE.WaitForSingleObject(process, 1000); if (wait != WinBase.WAIT_OBJECT_0) { Runner.logger.warn("Timed out while waiting for process " + name + "(" + pid + ") to end"); return false; } Kernel32.INSTANCE.CloseHandle(process); return true; } }
/** * Returns {@code pid} for Windows process * @param process Windows process * @return pid of the {@code process} */ public static int getProcessPid(Process process) { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { try { long handle = ReflectionUtil.getField(process.getClass(), process, long.class, "handle"); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE winHandle = new WinNT.HANDLE(); winHandle.setPointer(Pointer.createConstant(handle)); return kernel.GetProcessId(winHandle); } catch (Throwable e) { throw new IllegalStateException(e); } } else { throw new IllegalStateException("Unknown Process implementation"); } }
@Override protected void _openFile(String path) throws IOException { if (file != null) { throw new IllegalStateException("The file is already open!"); } file = Kernel32.INSTANCE.CreateFile( path, WinNT.GENERIC_WRITE + WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, null, WinNT.OPEN_ALWAYS, WinNT.FILE_ATTRIBUTE_NORMAL, null); if (WinNT.INVALID_HANDLE_VALUE.equals(file)) { throw new IOException("Unable to open file: " + getLastErrorAsString()); } }
@Override protected void _openMapping(long size) throws IOException { if (mapping != null) { throw new IllegalStateException("File is already mapped!"); } mapping = Kernel32.INSTANCE.CreateFileMapping( file, null, WinNT.PAGE_READWRITE, (int) (size >> 8 * 4), (int) (size & 0xFFFFFFFFL), null); if (mapping == null || WinNT.INVALID_HANDLE_VALUE.equals(mapping)) { throw new IOException("Unable to map file: " + getLastErrorAsString()); } else if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_ALREADY_EXISTS) { //File mapping already existing, TODO how to care about? throw new IOException("ERROR_ALREADY_EXISTS, don't know how to handle that!"); } }
/** * 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; } }
@Override public String findProcessId(Process process) throws NoSuchFieldException, IllegalAccessException { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long handleNumber = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(handleNumber)); int pid = kernel.GetProcessId(handle); log.debug("Found pid for managed process: {}", pid); return pid + ""; } return null; }
@Override protected void doApplySize(final Size size) throws BotConfigurationException { final int width = size.x(); final int height = size.y(); final HKEYByReference key = Advapi32Util.registryGetKey(WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\BlueStacks\\Guests\\Android\\FrameBuffer\\0", WinNT.KEY_READ | WinNT.KEY_WRITE); final int w1 = Advapi32Util.registryGetIntValue(key.getValue(), "WindowWidth"); final int h1 = Advapi32Util.registryGetIntValue(key.getValue(), "WindowHeight"); final int w2 = Advapi32Util.registryGetIntValue(key.getValue(), "GuestWidth"); final int h2 = Advapi32Util.registryGetIntValue(key.getValue(), "GuestHeight"); if (w1 != width || h1 != height || w2 != width || h2 != height) { Advapi32Util.registrySetIntValue(key.getValue(), "WindowWidth", width); Advapi32Util.registrySetIntValue(key.getValue(), "WindowHeight", height); Advapi32Util.registrySetIntValue(key.getValue(), "GuestWidth", width); Advapi32Util.registrySetIntValue(key.getValue(), "GuestHeight", height); Advapi32Util.registrySetIntValue(key.getValue(), "FullScreen", 0); } throw new BotConfigurationException(String.format("Please restart %s to fix resolution", BS_WINDOW_NAME)); }
/** * Get the dacl string from acl * * @param acl acl got from jna * @return dacl string */ private String getDaclString(final WinNT.ACL acl) { final WinNT.ACCESS_ACEStructure[] aceStructures = acl.getACEStructures(); final StringBuilder daclStringBuffer = new StringBuilder(); for (final WinNT.ACCESS_ACEStructure aceStructure : aceStructures) { daclStringBuffer.append("("); if (aceStructure.AceType == 0) { daclStringBuffer.append("A;"); } else if (aceStructure.AceType == 1) { daclStringBuffer.append("D;"); } else if (aceStructure.AceType == 2) { daclStringBuffer.append("AU;"); } daclStringBuffer.append("0x").append(Integer.toHexString(aceStructure.AceFlags)).append(";"); daclStringBuffer.append("0x").append(Integer.toHexString(aceStructure.Mask)).append(";;;"); daclStringBuffer.append(aceStructure.getSidString()).append(")"); } return daclStringBuffer.toString(); }
@Nullable private static String getUnityUserPath() { if(SystemInfo.isWinVistaOrNewer) { PointerByReference pointerByReference = new PointerByReference(); WinNT.HRESULT hresult = Shell32.INSTANCE.SHGetKnownFolderPath(Guid.GUID.fromString("{A520A1A4-1780-4FF6-BD18-167343C5AF16}"), 0, null, pointerByReference); if(hresult.longValue() != 0) { return null; } return pointerByReference.getValue().getWideString(0) + "\\Unity"; } else if(SystemInfo.isMac) { return SystemProperties.getUserHome() + "/Library/Unity"; } else if(SystemInfo.isLinux) { return SystemProperties.getUserHome() + "/.config/unity3d"; } return null; }
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; }
private List<WinProcess> getChildren() throws IOException { ArrayList<WinProcess> result = new ArrayList<WinProcess>(); WinNT.HANDLE hSnap = this.kernel32lib.CreateToolhelp32Snapshot(Kernel32Lib.TH32CS_SNAPPROCESS, new DWORD(0)); Kernel32Lib.PROCESSENTRY32.ByReference ent = new Kernel32Lib.PROCESSENTRY32.ByReference(); if (!this.kernel32lib.Process32First(hSnap, ent)) { return result; } do { if (ent.th32ParentProcessID.intValue() == this.pid) { try { result.add(new WinProcess(ent.th32ProcessID.intValue())); } catch (IOException e) { System.err.println("WinProcess::getChildren, IOException " + e); } } } while (this.kernel32lib.Process32Next(hSnap, ent)); Kernel32.INSTANCE.CloseHandle(hSnap); return result; }
private static int killWinProcess(Process process) { int exitValue; try { Field f = process.getClass().getDeclaredField("handle"); f.setAccessible(true); long hndl = f.getLong(process); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE handle = new WinNT.HANDLE(); handle.setPointer(Pointer.createConstant(hndl)); int pid = kernel.GetProcessId(handle); killPID("" + pid); exitValue = waitForProcessDeath(process, 10000); } catch (Exception ex) { LOG.log(Level.WARNING, "Process refused to die after 10 seconds, and couldn't taskkill it", ex); throw new RuntimeException( "Process refused to die after 10 seconds, and couldn't taskkill it: " + ex.getMessage(), ex); } return exitValue; }
@Nullable private Long windowsProcessId(Object process) { Class<?> clazz = process.getClass(); if (clazz.getName().equals("java.lang.Win32Process") || clazz.getName().equals("java.lang.ProcessImpl")) { try { Field f = clazz.getDeclaredField("handle"); f.setAccessible(true); long peer = f.getLong(process); Pointer pointer = Pointer.createConstant(peer); WinNT.HANDLE handle = new WinNT.HANDLE(pointer); return (long) Kernel32.INSTANCE.GetProcessId(handle); } catch (Exception e) { LOG.warn(e, "Cannot get process id!"); } } return null; }
/** 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()); }
public CygwinPtyProcess(String[] command, Map<String, String> environment, String workingDirectory, File logFile, boolean console) throws IOException { String pipePrefix = String.format("\\\\.\\pipe\\cygwinpty-%d-%d-", KERNEL32.GetCurrentProcessId(), processCounter.getAndIncrement()); String inPipeName = pipePrefix + "in"; String outPipeName = pipePrefix + "out"; String errPipeName = pipePrefix + "err"; myInputHandle = KERNEL32.CreateNamedPipeA(inPipeName, PIPE_ACCESS_OUTBOUND | WinNT.FILE_FLAG_OVERLAPPED, 0, 1, 0, 0, 0, null); myOutputHandle = KERNEL32.CreateNamedPipeA(outPipeName, PIPE_ACCESS_INBOUND | WinNT.FILE_FLAG_OVERLAPPED, 0, 1, 0, 0, 0, null); myErrorHandle = console ? KERNEL32.CreateNamedPipeA(errPipeName, PIPE_ACCESS_INBOUND | WinNT.FILE_FLAG_OVERLAPPED, 0, 1, 0, 0, 0, null) : null; if (myInputHandle == WinBase.INVALID_HANDLE_VALUE || myOutputHandle == WinBase.INVALID_HANDLE_VALUE || myErrorHandle == WinBase.INVALID_HANDLE_VALUE) { closeHandles(); throw new IOException("Unable to create a named pipe"); } myInputPipe = new NamedPipe(myInputHandle, false); myOutputPipe = new NamedPipe(myOutputHandle, false); myErrorPipe = myErrorHandle != null ? new NamedPipe(myErrorHandle, false) : null; myProcess = startProcess(inPipeName, outPipeName, errPipeName, workingDirectory, command, environment, logFile, console); }
public static int getProcessId(Process process) { String processClassName = process.getClass().getName(); if (processClassName.equals("java.lang.Win32Process") || processClassName.equals("java.lang.ProcessImpl")) { try { if (SystemInfo.IS_AT_LEAST_JAVA9) { //noinspection JavaReflectionMemberAccess return ((Long)Process.class.getMethod("pid").invoke(process)).intValue(); } long handle = assertNotNull(ReflectionUtil.getField(process.getClass(), process, long.class, "handle")); return Kernel32.INSTANCE.GetProcessId(new WinNT.HANDLE(Pointer.createConstant(handle))); } catch (Throwable t) { throw new IllegalStateException("Failed to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME, t); } } throw new IllegalStateException("Unable to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME); }
private IUIAutomationRangeValuePattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }
private IUIAutomationStylesPattern getPattern() throws AutomationException { if (this.rawPattern != null) { return this.rawPattern; } else { PointerByReference pbr = new PointerByReference(); WinNT.HRESULT result0 = this.getRawPatternPointer(pbr); if (COMUtils.SUCCEEDED(result0)) { return this.convertPointerToInterface(pbr); } else { throw new AutomationException(result0.intValue()); } } }