Refine search
public String getLastError() { int lastError = kernel32.GetLastError(); return Arrays.stream(WinError.class.getDeclaredFields()).filter(field -> { try { return Modifier.isStatic(field.getModifiers()) && field.getType() == int.class && field.getName().startsWith("ERROR") && (int) field.get(null) == lastError; } catch (IllegalAccessException e) { return false; } }).map(field -> field.getName() + "(" + lastError + ")") .findFirst() .orElse(Integer.toString(lastError)); } }
/** * @param process NiFi 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; }
public interface Psapi extends StdCallLibrary { Psapi INSTANCE = (Psapi) Native.loadLibrary("Psapi", Psapi.class); WinDef.DWORD GetModuleBaseNameW(Pointer hProcess, Pointer hModule, byte[] lpBaseName, int nSize); } if (Platform.isWindows()) { final int PROCESS_VM_READ=0x0010; final int PROCESS_QUERY_INFORMATION=0x0400; final User32 user32 = User32.INSTANCE; final Kernel32 kernel32=Kernel32.INSTANCE; final Psapi psapi = Psapi.INSTANCE; WinDef.HWND windowHandle=user32.GetForegroundWindow(); IntByReference pid= new IntByReference(); user32.GetWindowThreadProcessId(windowHandle, pid); WinNT.HANDLE processHandle=kernel32.OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, true, pid.getValue()); byte[] filename = new byte[512]; Psapi.INSTANCE.GetModuleBaseNameW(processHandle.getPointer(), Pointer.NULL, filename, filename.length); String name=new String(filename); System.out.println(name); if (name.endsWith("wwahost.exe")) { // Metro App // There is no stable API to get the current Metro app // But you can guestimate the name form the current directory of the process // To query this, see: // http://stackoverflow.com/questions/16110936/read-other-process-current-directory-in-c-sharp }
private Pointer queryServiceConfig2(int type) { IntByReference bufferSize = new IntByReference(); Advapi32.INSTANCE.QueryServiceConfig2(_handle, type, Pointer.NULL, 0, bufferSize); Pointer buffer = new Memory(bufferSize.getValue()); if (!Advapi32.INSTANCE.QueryServiceConfig2(_handle, type, buffer, bufferSize.getValue(), new IntByReference())) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } return buffer; }
/** * Gets the identifier of a provider from the enumerator. * * @param publisherEnum [in] A handle to the registered providers enumerator that * the {@link Wevtapi#EvtOpenPublisherEnum} function returns. * @return The name of the registered provider. */ public static String EvtNextPublisherId(EVT_HANDLE publisherEnum) { IntByReference publisherIdBufferUsed = new IntByReference(); boolean result = Wevtapi.INSTANCE.EvtNextPublisherId(publisherEnum, 0, null, publisherIdBufferUsed); int errorCode = Kernel32.INSTANCE.GetLastError(); if ((!result) && errorCode != Kernel32.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(errorCode); } char[] publisherIdBuffer = new char[publisherIdBufferUsed.getValue()]; result = Wevtapi.INSTANCE.EvtNextPublisherId(publisherEnum, publisherIdBuffer.length, publisherIdBuffer, publisherIdBufferUsed); if (!result) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } return Native.toString(publisherIdBuffer); }
@Override public String getProcessFilePath(final HWND hwnd) { final char[] filePath = new char[2048]; final IntByReference pid = new IntByReference(); User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid); final HANDLE process = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION | WinNT.PROCESS_VM_READ, false, pid.getValue()); if (process == null) { if(Kernel32.INSTANCE.GetLastError() != WinNT.ERROR_ACCESS_DENIED) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } else { null, filePath, filePath.length); if (length == 0) { if(Kernel32.INSTANCE.GetLastError() != WinNT.ERROR_INVALID_HANDLE) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } else { return Native.toString(filePath).trim(); } finally { Kernel32.INSTANCE.CloseHandle(process);
/** * Get current computer NetBIOS name. * * @return Netbios name. */ public static String getComputerName() { char buffer[] = new char[WinBase.MAX_COMPUTERNAME_LENGTH + 1]; IntByReference lpnSize = new IntByReference(buffer.length); if (!Kernel32.INSTANCE.GetComputerName(buffer, lpnSize)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } return Native.toString(buffer); }
/** * Invokes and parses the result of {@link Kernel32#GetVolumePathNamesForVolumeName(String, char[], int, IntByReference)} * @param lpszVolumeName The volume name * @return The parsed result * @throws Win32Exception If failed to retrieve the required information */ public static final List<String> getVolumePathNamesForVolumeName(String lpszVolumeName) { char[] lpszVolumePathNames = new char[WinDef.MAX_PATH + 1]; IntByReference lpcchReturnLength = new IntByReference(); if (!Kernel32.INSTANCE.GetVolumePathNamesForVolumeName(lpszVolumeName, lpszVolumePathNames, lpszVolumePathNames.length, lpcchReturnLength)) { int hr = Kernel32.INSTANCE.GetLastError(); if (hr != WinError.ERROR_MORE_DATA) { throw new Win32Exception(hr); } int required = lpcchReturnLength.getValue(); lpszVolumePathNames = new char[required]; // this time we MUST succeed if (!Kernel32.INSTANCE.GetVolumePathNamesForVolumeName(lpszVolumeName, lpszVolumePathNames, lpszVolumePathNames.length, lpcchReturnLength)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } int bufSize = lpcchReturnLength.getValue(); return Native.toStringList(lpszVolumePathNames, 0, bufSize); }
/** * * This function retrieves the full path of the executable file of a given process. * * @param hProcess * Handle for the running process * @param dwFlags * 0 - The name should use the Win32 path format. * 1(WinNT.PROCESS_NAME_NATIVE) - The name should use the native system path format. * * @return the full path of the process's executable file of null if failed. To get extended error information, * call GetLastError. */ public static final String QueryFullProcessImageName(HANDLE hProcess, int dwFlags) { char[] path = new char[WinDef.MAX_PATH]; IntByReference lpdwSize = new IntByReference(path.length); if (Kernel32.INSTANCE.QueryFullProcessImageName(hProcess, 0, path, lpdwSize)) return new String(path).substring(0, lpdwSize.getValue()); throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); }
import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.ptr.IntByReference; import com.sun.jna.win32.*; import com.sun.jna.examples.win32.Kernel32; ... public static boolean isLocalSession() { Kernel32 kernel32; IntByReference pSessionId; int consoleSessionId; Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); pSessionId = new IntByReference(); if (lib.ProcessIdToSessionId(lib.GetCurrentProcessId(), pSessionId)) { consoleSessionId = lib.WTSGetActiveConsoleSessionId(); return (consoleSessionId != 0xFFFFFFFF && consoleSessionId == pSessionId.getValue()); } else return false; }
/** * 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 kern32 = Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); WinNT.HANDLE snapshot = kern32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); boolean found = false; try { while (kern32.Process32Next(snapshot, processEntry)) { String fname = Native.toString(processEntry.szExeFile); if (fname != null && filenamePattern.matcher(fname).matches()) { found = true; break; } } } finally { kern32.CloseHandle(snapshot); } return found; }
IntByReference pid = new IntByReference(0); user32.GetWindowThreadProcessId(user32.FindWindowA(null, window), pid); Pointer process = kernel32.OpenProcess(permissions, true, pid); return process; kernel32.ReadProcessMemory(process, pointer, pTemp, size, null); kernel32.ReadProcessMemory(process, pointerAddress, pTemp, size, null); IntByReference read = new IntByReference(0); Memory output = new Memory(bytesToRead); kernel32.ReadProcessMemory(process, address, output, bytesToRead, read); return output; boolean b = kernel32.WriteProcessMemory(process, address, toWrite, size, null);
/** * Shut down the NamedPipe cleanly and quickly. Use an event to abort any * pending I/O, then acquire the locks to ensure that the I/O has ended. * Once everything has stopped, close all the native handles. * * Mark the function synchronized to ensure that a later call cannot return * earlier. */ public synchronized void close() throws IOException { if (!closeImpl()) { return; } if (!Kernel32.INSTANCE.CloseHandle(myHandle)) { throw new IOException("Close error:" + Native.getLastError()); } }
/** * Return the path designated for temporary files. * * @return Path. */ public static String getTempPath() { DWORD nBufferLength = new DWORD(WinDef.MAX_PATH); char[] buffer = new char[nBufferLength.intValue()]; if (Kernel32.INSTANCE.GetTempPath(nBufferLength, buffer).intValue() == 0) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } return Native.toString(buffer); }
/** * Get the value of an environment variable. * * @param name * Name of the environment variable. * @return Value of an environment variable. */ public static String getEnvironmentVariable(String name) { // obtain the buffer size int size = Kernel32.INSTANCE.GetEnvironmentVariable(name, null, 0); if (size == 0) { return null; } else if (size < 0) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } // obtain the value char[] buffer = new char[size]; size = Kernel32.INSTANCE.GetEnvironmentVariable(name, buffer, buffer.length); if (size <= 0) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } return Native.toString(buffer); }
/** * Retrieves the path of a special folder, identified by its CSIDL. * * @param csidl * A CSIDL that identifies the folder of interest. If a virtual folder is specified, this function will fail. * @param create * Indicates whether the folder should be created if it does not already exist. If this value is nonzero, the folder is created. If this value is * zero, the folder is not created. * @return The drive and path of the specified folder */ public static final String getSpecialFolderPath(final int csidl, final boolean create) { final char[] pszPath = new char[WinDef.MAX_PATH]; if (!Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, csidl, create)) throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); return Native.toString(pszPath); } }
public static NamedPipe connectToServer(String name, int desiredAccess) throws IOException { WinNT.HANDLE handle = Kernel32.INSTANCE.CreateFile( name, desiredAccess, 0, null, WinNT.OPEN_EXISTING, 0, null); if (handle == INVALID_HANDLE_VALUE) { throw new IOException("Error connecting to pipe '" + name + "': " + Native.getLastError()); } return new NamedPipe(handle, true); }
public boolean jambo_loco (int pid) { Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS); Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); try { int i = 0; int size = processEntry.dwSize.intValue(); while (kernel32.Process32Next(snapshot, processEntry) && i < size) { if (processEntry.th32ProcessID.intValue() == pid) return true; i++; } } finally { kernel32.CloseHandle(snapshot); } return false; }
int flags = WinNT.FILE_FLAG_BACKUP_SEMANTICS | WinNT.FILE_FLAG_OVERLAPPED; HANDLE handle = klib.CreateFile(file.getAbsolutePath(), WinNT.FILE_LIST_DIRECTORY, mask, null, WinNT.OPEN_EXISTING, if (WinBase.INVALID_HANDLE_VALUE.equals(handle)) { throw new IOException("Unable to open " + file + " (" + klib.GetLastError() + ")"); handleMap.put(handle, finfo); port = klib.CreateIoCompletionPort(handle, port, handle.getPointer(), 0); if (WinBase.INVALID_HANDLE_VALUE.equals(port)) { throw new IOException("Unable to create/use I/O Completion port " + "for " + file + " (" + klib.GetLastError() + ")"); if (!klib.ReadDirectoryChangesW(handle, finfo.info, finfo.info.size(), recursive, notifyMask, finfo.infoLength, finfo.overlapped, null)) { int err = klib.GetLastError(); throw new IOException("ReadDirectoryChangesW failed on " + finfo.file + ", handle " + handle
hFile = Kernel32.INSTANCE.CreateFile(fileName, WinNT.GENERIC_READ, WinNT.FILE_SHARE_READ, throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); int type = Kernel32.INSTANCE.GetFileType(hFile); switch(type) { case WinNT.FILE_TYPE_UNKNOWN: int err = Kernel32.INSTANCE.GetLastError(); switch(err) { case WinError.NO_ERROR: if (! Kernel32.INSTANCE.CloseHandle(hFile)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError());