com.sun.jna.platform.win32.WinNT Java Examples

The following examples show how to use com.sun.jna.platform.win32.WinNT. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringBootManagedContainer.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected static Integer windowsProcessId(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    /* 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);
      log.debug("Detected pid: {}", ret);
      return ret;
    } catch (Throwable ex) {
      throw new RuntimeException("Cannot fetch windows pid!", ex);
    }
  }
  return null;
}
 
Example #2
Source File: WinProcess.java    From sheepit-client with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: WindowsProcessExecutor.java    From Java-Auto-Update with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: OSUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #5
Source File: OSUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #6
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static List<WinNT.HANDLE> mockEventHandles(WEvtApi wEvtApi, Kernel32 kernel32, List<String> eventXmls) {
    List<WinNT.HANDLE> eventHandles = new ArrayList<>();
    for (String eventXml : eventXmls) {
        WinNT.HANDLE eventHandle = mock(WinNT.HANDLE.class);
        when(wEvtApi.EvtRender(isNull(), eq(eventHandle), eq(WEvtApi.EvtRenderFlags.EVENT_XML),
                anyInt(), any(Pointer.class), any(Pointer.class), any(Pointer.class))).thenAnswer(invocation -> {
            Object[] arguments = invocation.getArguments();
            Pointer bufferUsed = (Pointer) arguments[5];
            byte[] array = StandardCharsets.UTF_16LE.encode(eventXml).array();
            if (array.length > (int) arguments[3]) {
                when(kernel32.GetLastError()).thenReturn(W32Errors.ERROR_INSUFFICIENT_BUFFER).thenReturn(W32Errors.ERROR_SUCCESS);
            } else {
                ((Pointer) arguments[4]).write(0, array, 0, array.length);
            }
            bufferUsed.setInt(0, array.length);
            return false;
        });
        eventHandles.add(eventHandle);
    }
    return eventHandles;
}
 
Example #7
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduleError() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    evtSubscribe = new ConsumeWindowsEventLog(wEvtApi, kernel32);

    when(wEvtApi.EvtSubscribe(isNull(WinNT.HANDLE.class), isNull(WinNT.HANDLE.class), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
            isNull(WinNT.HANDLE.class), isNull(WinDef.PVOID.class), isA(EventSubscribeXmlRenderingCallback.class),
            eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT)))
            .thenReturn(null);

    when(kernel32.GetLastError()).thenReturn(WinError.ERROR_ACCESS_DENIED);

    testRunner = TestRunners.newTestRunner(evtSubscribe);

    testRunner.run(1);
    assertEquals(0, getCreatedSessions(testRunner).size());
    verify(wEvtApi, never()).EvtClose(any(WinNT.HANDLE.class));
}
 
Example #8
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopProcessesQueue() throws InvocationTargetException, IllegalAccessException {
    testRunner.run(1, false);

    List<String> eventXmls = Arrays.asList("one", "two", "three");
    for (WinNT.HANDLE eventHandle : mockEventHandles(wEvtApi, kernel32, eventXmls)) {
        getRenderingCallback().onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, eventHandle);
    }

    ReflectionUtils.invokeMethodsWithAnnotation(OnStopped.class, evtSubscribe, testRunner.getProcessContext());

    List<MockFlowFile> flowFilesForRelationship = testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS);
    assertEquals(eventXmls.size(), flowFilesForRelationship.size());
    for (int i = 0; i < eventXmls.size(); i++) {
        flowFilesForRelationship.get(i).assertContentEquals(eventXmls.get(i));
    }
}
 
Example #9
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStopProcessesQueue() throws InvocationTargetException, IllegalAccessException {
    testRunner.run(1, false);

    List<String> eventXmls = Arrays.asList("one", "two", "three");
    for (WinNT.HANDLE eventHandle : mockEventHandles(wEvtApi, kernel32, eventXmls)) {
        getRenderingCallback().onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, eventHandle);
    }

    ReflectionUtils.invokeMethodsWithAnnotation(OnStopped.class, evtSubscribe, testRunner.getProcessContext());

    List<MockFlowFile> flowFilesForRelationship = testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS);
    assertEquals(eventXmls.size(), flowFilesForRelationship.size());
    for (int i = 0; i < eventXmls.size(); i++) {
        flowFilesForRelationship.get(i).assertContentEquals(eventXmls.get(i));
    }
}
 
Example #10
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static List<WinNT.HANDLE> mockEventHandles(WEvtApi wEvtApi, Kernel32 kernel32, List<String> eventXmls) {
    List<WinNT.HANDLE> eventHandles = new ArrayList<>();
    for (String eventXml : eventXmls) {
        WinNT.HANDLE eventHandle = mock(WinNT.HANDLE.class);
        when(wEvtApi.EvtRender(isNull(WinNT.HANDLE.class), eq(eventHandle), eq(WEvtApi.EvtRenderFlags.EVENT_XML),
                anyInt(), any(Pointer.class), any(Pointer.class), any(Pointer.class))).thenAnswer(invocation -> {
            Object[] arguments = invocation.getArguments();
            Pointer bufferUsed = (Pointer) arguments[5];
            byte[] array = Charsets.UTF_16LE.encode(eventXml).array();
            if (array.length > (int) arguments[3]) {
                when(kernel32.GetLastError()).thenReturn(W32Errors.ERROR_INSUFFICIENT_BUFFER).thenReturn(W32Errors.ERROR_SUCCESS);
            } else {
                ((Pointer) arguments[4]).write(0, array, 0, array.length);
            }
            bufferUsed.setInt(0, array.length);
            return false;
        });
        eventHandles.add(eventHandle);
    }
    return eventHandles;
}
 
Example #11
Source File: ProcessHelper.java    From buck with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: WindowsNamedPipe.java    From buck with Apache License 2.0 6 votes vote down vote up
/** 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());
}
 
Example #13
Source File: WinProcessManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #14
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduleError() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    evtSubscribe = new ConsumeWindowsEventLog(wEvtApi, kernel32);

    when(wEvtApi.EvtSubscribe(isNull(), isNull(), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
            isNull(), isNull(), isA(EventSubscribeXmlRenderingCallback.class),
            eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT)))
            .thenReturn(null);

    when(kernel32.GetLastError()).thenReturn(WinError.ERROR_ACCESS_DENIED);

    testRunner = TestRunners.newTestRunner(evtSubscribe);

    testRunner.run(1);
    assertEquals(0, getCreatedSessions(testRunner).size());
    verify(wEvtApi, never()).EvtClose(any(WinNT.HANDLE.class));
}
 
Example #15
Source File: JKernel32.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static boolean openDeviceAsync() throws IOException {
       /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */
       int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE;
       int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ;
	HandleToDevice = Kernel32.INSTANCE.CreateFile(
               Devices.getConnectedDeviceWin32().getDevPath(), 
               Access, 
               shareMode, 
               null, 
               WinNT.OPEN_EXISTING, 
               WinNT.FILE_FLAG_OVERLAPPED, 
               (WinNT.HANDLE)null);
	if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError());
	return true;
}
 
Example #16
Source File: Unity3dPackageWatcher.java    From consulo-unity3d with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<String> getUnityUserPaths()
{
	List<String> paths = new SmartList<>();
	if(SystemInfo.isWinVistaOrNewer)
	{
		paths.add(Shell32Util.getFolderPath(ShlObj.CSIDL_LOCAL_APPDATA) + "\\Unity");

		PointerByReference pointerByReference = new PointerByReference();
		// LocalLow
		WinNT.HRESULT hresult = Shell32.INSTANCE.SHGetKnownFolderPath(Guid.GUID.fromString("{A520A1A4-1780-4FF6-BD18-167343C5AF16}"), 0, null, pointerByReference);

		if(hresult.longValue() == 0)
		{
			paths.add(pointerByReference.getValue().getWideString(0) + "\\Unity");
		}
	}
	else if(SystemInfo.isMac)
	{
		paths.add(SystemProperties.getUserHome() + "/Library/Unity");
	}
	else if(SystemInfo.isLinux)
	{
		paths.add(SystemProperties.getUserHome() + "/.config/unity3d");
	}

	return paths;
}
 
Example #17
Source File: Win32ProcessTools.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: Jna.java    From ipc-eventbus with Apache License 2.0 5 votes vote down vote up
static long getWindowsPid(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    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));
      return kernel.GetProcessId(handle);
    } catch (Throwable ignored) {
    }
  }
  return -1;
}
 
Example #19
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public List<EventSubscribeXmlRenderingCallback> getRenderingCallbacks(int times) {
    ArgumentCaptor<EventSubscribeXmlRenderingCallback> callbackArgumentCaptor = ArgumentCaptor.forClass(EventSubscribeXmlRenderingCallback.class);
    verify(wEvtApi, times(times)).EvtSubscribe(isNull(WinNT.HANDLE.class), isNull(WinNT.HANDLE.class), eq(ConsumeWindowsEventLog.DEFAULT_CHANNEL), eq(ConsumeWindowsEventLog.DEFAULT_XPATH),
            isNull(WinNT.HANDLE.class), isNull(WinDef.PVOID.class), callbackArgumentCaptor.capture(),
            eq(WEvtApi.EvtSubscribeFlags.SUBSCRIBE_TO_FUTURE | WEvtApi.EvtSubscribeFlags.EVT_SUBSCRIBE_STRICT));
    return callbackArgumentCaptor.getAllValues();
}
 
Example #20
Source File: SystemService.java    From winthing with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("DM_CONVERT_CASE")
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;
}
 
Example #21
Source File: Win32ProcessTools.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: Win32ProcessTools.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
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;
    }
 
Example #23
Source File: WinProcess.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
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 (handle == null) {
		throw new IOException(
				"OpenProcess failed: " + Kernel32Util.formatMessageFromLastErrorCode(Kernel32.INSTANCE.GetLastError()) + " (pid: " + pid_ + ")");
	}
	return handle;
}
 
Example #24
Source File: CobaltStrike.java    From R9000 with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean checkIfProcessIsWow64( Pointer hOpenedProcess )
{
    IntByReference ref = new IntByReference();
    WinNT.HANDLE handleToProcess = new WinNT.HANDLE( hOpenedProcess );

    if ( !kernel32.IsWow64Process( handleToProcess, ref ) )
    {
        System.exit( 0 );
    }

    return ref.getValue() == 0;
}
 
Example #25
Source File: JKernel32.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static boolean openDevice() throws IOException {
       /* Kernel32RW.GENERIC_READ | Kernel32RW.GENERIC_WRITE not used in dwDesiredAccess field for system devices such a keyboard or mouse */
       int shareMode = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE;
       int Access = WinNT.GENERIC_WRITE | WinNT.GENERIC_READ;
	HandleToDevice = Kernel32.INSTANCE.CreateFile(
               Devices.getConnectedDeviceWin32().getDevPath(), 
               Access, 
               shareMode, 
               null, 
               WinNT.OPEN_EXISTING, 
               0,//WinNT.FILE_FLAG_OVERLAPPED, 
               (WinNT.HANDLE)null);
	if (HandleToDevice == WinBase.INVALID_HANDLE_VALUE) throw new IOException(getLastError());
	return true;
}
 
Example #26
Source File: JKernel32.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public static WinNT.HANDLE createEvent() throws IOException {
	WinNT.HANDLE hevent = kernel32.CreateEvent(null, false, false, null);
	int res = kernel32.GetLastError();
	if (hevent == WinBase.INVALID_HANDLE_VALUE || res!=0)
			throw new IOException(JKernel32.getLastError());
	return hevent;
}
 
Example #27
Source File: DwmApi.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @return 0 - color in format 0xAARRGGBB, 1 - opaque
 */
public static int[] DwmGetColorizationColor() {
  IntByReference colorRef = new IntByReference();
  IntByReference opaqueRef = new IntByReference();
  WinNT.HRESULT hresult = DwmApi.INSTANCE.DwmGetColorizationColor(colorRef, opaqueRef);
  if(W32Errors.S_OK.equals(hresult)) {
    return new int[] {colorRef.getValue(), opaqueRef.getValue()};
  }
  return new int[2];
}
 
Example #28
Source File: WindowsNamedPipeLibrary.java    From buck with Apache License 2.0 5 votes vote down vote up
WinNT.HANDLE CreateFile(
String lpFileName,
int dwDesiredAccess,
int dwShareMode,
WinBase.SECURITY_ATTRIBUTES lpSecurityAttributes,
int dwCreationDisposition,
int dwFlagsAndAttributes,
WinNT.HANDLE hTemplateFile);
 
Example #29
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10 * 1000)
public void testProcessesBlockedEvents() throws UnsupportedEncodingException {
    testRunner.setProperty(ConsumeWindowsEventLog.MAX_EVENT_QUEUE_SIZE, "1");
    testRunner.run(1, false, true);
    EventSubscribeXmlRenderingCallback renderingCallback = getRenderingCallback();

    List<String> eventXmls = Arrays.asList("one", "two", "three", "four", "five", "six");
    List<WinNT.HANDLE> eventHandles = mockEventHandles(wEvtApi, kernel32, eventXmls);
    AtomicBoolean done = new AtomicBoolean(false);
    new Thread(() -> {
        for (WinNT.HANDLE eventHandle : eventHandles) {
            renderingCallback.onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, eventHandle);
        }
        done.set(true);
    }).start();

    // Wait until the thread has really started
    while (testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS).size() == 0) {
        testRunner.run(1, false, false);
    }

    // Process rest of events
    while (!done.get()) {
        testRunner.run(1, false, false);
    }

    testRunner.run(1, true, false);

    List<MockFlowFile> flowFilesForRelationship = testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS);
    assertEquals(eventXmls.size(), flowFilesForRelationship.size());
    for (int i = 0; i < eventXmls.size(); i++) {
        flowFilesForRelationship.get(i).assertContentEquals(eventXmls.get(i));
    }
}
 
Example #30
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(expected = ProcessException.class)
public void testScheduleQueueStopThrowsException() throws Throwable {
    ReflectionUtils.invokeMethodsWithAnnotation(OnScheduled.class, evtSubscribe, testRunner.getProcessContext());

    WinNT.HANDLE handle = mockEventHandles(wEvtApi, kernel32, Arrays.asList("test")).get(0);
    getRenderingCallback().onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, handle);

    try {
        ReflectionUtils.invokeMethodsWithAnnotation(OnStopped.class, evtSubscribe, testRunner.getProcessContext());
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}