public CLibrary() { switch (Platform.get()) { case LinuxIntel32: case LinuxIntel64: delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class); constants = new LinuxConstants(); break; case MacosIntel32: delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class); constants = new MacConstants(); break; case SolarisIntel32: case SolarisIntel64: case SolarisSparc32: case SolarisSparc64: delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class); constants = new SolarisConstants(); break; case WindowsIntel32: case Other: default: delegate = (GenericCLibrary) Native.loadLibrary("c", DefaultCLibrary.class); constants = new DefaultConstants(); break; } }
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; }
/** * Get a handle to the ServiceControlManager. * * @param machine * name of the machine or null for localhost * @param access * access flags * @return handle to ServiceControlManager or null when failed */ static private SC_HANDLE openServiceControlManager(String machine, int access) { SC_HANDLE handle = null; Advapi32 advapi32; advapi32 = Advapi32.INSTANCE; handle = advapi32.OpenSCManager(machine, null, access); if (handle == null) { int err = Native.getLastError(); lastWinError = err; System.out.println("Error in OpenSCManager: " + Integer.toHexString(err)); if (err == 5) System.out.println("Access denied: please check the user credentials"); } return (handle); }
public static void free(long peer) { long sizeInBytes = memTracker.get(peer); long totalSizeInBytes = ALLOCATED_SIZE.addAndGet(-1 * sizeInBytes); if (totalSizeInBytes < 0) { ALLOCATED_SIZE.set(0); totalSizeInBytes = 0; } LOGGER.info("Freeing off-heap memory block of " + (sizeInBytes/1048576) + "Mb and total allocated off-heap memory size is " + (totalSizeInBytes/1048576) + "Mb"); Native.free(peer); memTracker.remove(peer); }
/** * Make out own i/o be raw. */ private static void makeRaw() { String ttyName = "/dev/tty"; int ofd = Util.getFd(FileDescriptor.out); CLibrary.LinuxTermios termios = new CLibrary.LinuxTermios(); // check existing settings // If we don't do this tcssetattr() will return EINVAL. if (CLibrary.INSTANCE.tcgetattr(ofd, termios) == -1) { error("tcgetattr(\"" + ttyName + "\", <termios>) failed -- " + strerror(Native.getLastError())); } // System.out.printf("tcgetattr() gives %s\r\n", termios); // initialize values relevant for raw mode CLibrary.INSTANCE.cfmakeraw(termios); // System.out.printf("cfmakeraw() gives %s\r\n", termios); // apply them if (CLibrary.INSTANCE.tcsetattr(ofd, CLibrary.INSTANCE.TCSANOW(), termios) == -1) { error("tcsetattr(\"" + ttyName + "\", TCSANOW, <termios>) failed -- " + strerror(Native.getLastError())); } }
/** * @return the hostname the of the current machine */ public static String getHostname() { if (Platform.isWindows()) { return Kernel32Util.getComputerName(); } else { // For now, we'll consider anyhting other than Windows to be unix-ish enough to have gethostname // TODO - Consider http://stackoverflow.com/a/10543006 as a possibly better MacOS option byte[] hostnameBuffer = new byte[4097]; // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html suggests // the actual limit would be 255. int result = UnixCLibrary.INSTANCE.gethostname(hostnameBuffer, hostnameBuffer.length); if (result != 0) { throw new RuntimeException("gethostname call failed"); } return Native.toString(hostnameBuffer); } }
static void trySetMaxNumberOfThreads() { if (Constants.LINUX) { // this is only valid on Linux and the value *is* different on OS X // see /usr/include/sys/resource.h on OS X // on Linux the resource RLIMIT_NPROC means *the number of threads* // this is in opposition to BSD-derived OSes final int rlimit_nproc = 6; final JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit(); if (JNACLibrary.getrlimit(rlimit_nproc, rlimit) == 0) { MAX_NUMBER_OF_THREADS = rlimit.rlim_cur.longValue(); } else { logger.warn("unable to retrieve max number of threads [" + JNACLibrary.strerror(Native.getLastError()) + "]"); } } }
static void solarisImpl() { // first be defensive: we can give nice errors this way, at the very least. boolean supported = Constants.SUN_OS; if (supported == false) { throw new IllegalStateException("bug: should not be trying to initialize priv_set for an unsupported OS"); } // we couldn't link methods, could be some really ancient Solaris or some bug if (libc_solaris == null) { throw new UnsupportedOperationException("priv_set unavailable: could not link methods. requires Solaris 10+"); } // drop a null-terminated list of privileges if (libc_solaris.priv_set(PRIV_OFF, PRIV_ALLSETS, PRIV_PROC_FORK, PRIV_PROC_EXEC, null) != 0) { throw new UnsupportedOperationException("priv_set unavailable: priv_set(): " + JNACLibrary.strerror(Native.getLastError())); } logger.debug("Solaris priv_set initialization successful"); }
/** * Validates if the expression instance is valid * @return ValidationResult object */ public ValidationResult validate() { PointerByReference info = new PointerByReference(); PointerByReference error = new PointerByReference(); int hsResult = HyperscanLibrary.INSTANCE.hs_expression_info(this.expression, Util.bitEnumSetToInt(this.flags), info, error); String errorMessage = ""; boolean isValid = true; if(hsResult != 0) { isValid = false; CompileErrorStruct errorStruct = new CompileErrorStruct(error.getValue()); errorMessage = errorStruct.message; errorStruct.setAutoRead(false); HyperscanLibrary.INSTANCE.hs_free_compile_error(errorStruct); } else { Native.free(Pointer.nativeValue(info.getValue())); } return new ValidationResult(errorMessage, isValid); }
public static void main(String args[]) throws InterruptedException { Pointer pointer; System.out.println("running in " + System.getProperty("sun.arch.data.model")); System.out.println("Loading dll"); autoHotKeyDll lib = (autoHotKeyDll) Native.loadLibrary("AutoHotkey.dll", autoHotKeyDll.class); System.out.println("initialisation"); lib.ahktextdll(new WString(""), new WString(""), new WString("")); // Thread.sleep(100); // lib.addFile(new WString(System.getProperty("user.dir") + "\\lib.ahk"), 1); // Thread.sleep(1000); // System.out.println("function call"); // System.out.println("return:" + lib.ahkFunction(new WString("function"),new WString(""),new WString(""),new // WString(""),new WString(""),new WString(""),new WString(""),new WString(""),new WString(""),new // WString(""),new WString("")).getString(0)); Thread.sleep(1000); System.out.println("displaying cbBox"); lib.ahkExec(new WString("Send {Right}")); Thread.sleep(1000); }
public static void lockMemory() { int result = 0; try { Native.register(Platform.C_LIBRARY_NAME); result = mlockall(1); if (result == 0) { return; } } catch (Throwable t) { throw new IllegalStateException("Error trying to lock memory", t); } int errno = Native.getLastError(); String msg = "mlockall failed: " + errno; if (errno == 1 || errno == 12) { // EPERM || ENOMEM msg = "Unable to lock memory due to insufficient free space or privileges. " + "Please check the RLIMIT_MEMLOCK soft resource limit (ulimit -l) and " + "increase the available memory if needed"; } throw new IllegalStateException(msg); }
public static synchronized void start(HackRFSweepDataCallback dataCallback, int freq_min_MHz, int freq_max_MHz, int fft_bin_width, int num_samples, int lna_gain, int vga_gain, boolean antennaPowerEnable) { hackrf_sweep_lib_start__fft_power_callback_callback callback = new hackrf_sweep_lib_start__fft_power_callback_callback() { @Override public void apply(byte sweep_started, int bins, DoubleByReference freqStart, float fftBinWidth, FloatByReference powerdBm) { double[] freqStartArr = bins == 0 ? null : freqStart.getPointer().getDoubleArray(0, bins); float[] powerArr = bins == 0 ? null : powerdBm.getPointer().getFloatArray(0, bins); dataCallback.newSpectrumData(sweep_started==0 ? false : true, freqStartArr, fftBinWidth, powerArr); } }; Native.setCallbackThreadInitializer(callback, new CallbackThreadInitializer(true)); HackrfSweepLibrary.hackrf_sweep_lib_start(callback, freq_min_MHz, freq_max_MHz, fft_bin_width, num_samples, lna_gain, vga_gain, antennaPowerEnable ? 1 : 0); }
public static void main(String[] args) { final User32 user32 = User32.INSTANCE; user32.EnumWindows(new User32.WNDENUMPROC() { int count; public boolean callback(Pointer hWnd, Pointer userData) { byte[] windowText = new byte[512]; user32.GetWindowTextA(hWnd, windowText, 512); String wText = Native.toString(windowText); wText = (wText.isEmpty()) ? "" : "; text: " + wText; System.out.println("Found window " + hWnd + ", total " + ++count + wText); return true; } }, null); }
/** * 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; }
@Test public void test_getStyleName_Calls_getCurrentStyleName_From_Pattern() throws Exception { doAnswer(invocation -> { Object[] args = invocation.getArguments(); PointerByReference reference = (PointerByReference)args[0]; String value = "Hello"; Pointer pointer = new Memory(Native.WCHAR_SIZE * (value.length() +1)); pointer.setWideString(0, value); reference.setValue(pointer); return 0; }).when(rawPattern).getCurrentStyleName(any()); Styles pattern = new Styles(rawPattern); pattern.getStyleName(); verify(rawPattern, atLeastOnce()).getCurrentStyleName(any()); }
public long getUptime() { try { Sysinfo info = new Sysinfo(); if (0 != CLibrary.INSTANCE.sysinfo(info)) { if (_logger != null) _logger.severe("error getting uptime: " + Native.getLastError()); return 0L; } return info.uptime.longValue(); } catch (Exception ex) { if (_logger != null) _logger.severe("error getting uptime: " + ex); } return 0L; }
public void sendKey(final char key) { if (_pid <= 0) return; if (getActiveWindow() != null) { byte[] windowText = new byte[512]; MyUser32.INSTANCE.GetWindowTextA(lastActiveWindow, windowText, 512); String wText = Native.toString(windowText); wText = (wText.isEmpty()) ? "" : "; text: " + wText; System.out.println("sending key " + key + " to " + wText); MyUser32.INSTANCE.SendMessageW(lastActiveWindow, MyUser32.WM_KEYDOWN, key, 0); MyUser32.INSTANCE.SendMessageW(lastActiveWindow, MyUser32.WM_KEYUP, key, 0); } else System.out.println("no window found"); }
/** * Initialize the service, connect to the ServiceControlManager. */ public void init() { Advapi32 advapi32; // Advapi32.SERVICE_TABLE_ENTRY[] entries = new // Advapi32.SERVICE_TABLE_ENTRY[2]; Advapi32.SERVICE_TABLE_ENTRY entry; serviceMain = new ServiceMain(); advapi32 = Advapi32.INSTANCE; entry = new Advapi32.SERVICE_TABLE_ENTRY(); entry.size(); entry.lpServiceName = serviceName; entry.lpServiceProc = serviceMain; entry.write(); if (!advapi32.StartServiceCtrlDispatcher(entry.toArray(2))) { log("error in StartServiceCtrlDispatcher", 0); int err = Native.getLastError(); lastWinError = err; log(err + ":" + Kernel32Util.formatMessageFromLastErrorCode(err), 0); } }
@BeforeClass public static void initNotes() { NotesNativeAPI.initialize(); String notesProgramDir = System.getenv("Notes_ExecDirectory"); String notesIniPath = System.getenv("NotesINI"); if (notesProgramDir!=null && notesProgramDir.length()>0 && notesIniPath!=null && notesIniPath.length()>0) { NotesInitUtils.notesInitExtended(new String[] { notesProgramDir, "="+notesIniPath }); m_notesInitExtendedCalled = true; } NotesThread.sinitThread(); Native.setProtected(true); }
@Override public void lockCurrentMemory() { if (mlockall(MCL_CURRENT) == 0) { return; } final int errno = Native.getLastError(); final String msg, reason; if (errno == EPERM) { reason = "insufficient privileges"; } else if (errno == ENOMEM) { reason = "insufficient free space"; } else { reason = "errno=" + errno; } msg = "Unable to lock memory due to " + reason + ". Please check the RLIMIT_MEMLOCK soft resource limit " + "(ulimit -l) and increase the available memory if needed."; throw new IllegalStateException(msg); }
public static Process byName(String name) { if (Platform.isWindows()) { Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference(); Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0); try { while (Kernel32.Process32Next(snapshot, entry)) { String processName = Native.toString(entry.szExeFile); if (name.equals(processName)) { return byId(entry.th32ProcessID.intValue()); } } } finally { Kernel32.CloseHandle(snapshot); } } else if (Platform.isMac() || Platform.isLinux()) { return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'")); } else { throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")"); } throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?"); }
private String hashBytes(int iterations, int memory, int parallelism, byte[] pwd) { final byte[] salt = generateSalt(); final Uint32_t iterations_t = new Uint32_t(iterations); final Uint32_t memory_t = new Uint32_t(memory); final Uint32_t parallelism_t = new Uint32_t(parallelism); int len = argon2Library.argon2_encodedlen(iterations_t, memory_t, parallelism_t, new Uint32_t(salt.length), new Uint32_t(hashLen)).intValue(); final byte[] encoded = new byte[len]; int result = callLibraryHash(pwd, salt, iterations_t, memory_t, parallelism_t, encoded); if (result != Argon2Library.ARGON2_OK) { String errMsg = argon2Library.argon2_error_message(result); throw new IllegalStateException(String.format("%s (%d)", errMsg, result)); } return Native.toString(encoded, ASCII); }
private String hashBytes(int iterations, int memory, int parallelism, byte[] pwd) { final byte[] salt = generateSalt(); final JnaUint32 jnaIterations = new JnaUint32(iterations); final JnaUint32 jnaMemory = new JnaUint32(memory); final JnaUint32 jnaParallelism = new JnaUint32(parallelism); int len = Argon2Library.INSTANCE.argon2_encodedlen(jnaIterations, jnaMemory, jnaParallelism, new JnaUint32(salt.length), new JnaUint32(hashLen), getType().getJnaType()).intValue(); final byte[] encoded = new byte[len]; int result = callLibraryHash(pwd, salt, jnaIterations, jnaMemory, jnaParallelism, encoded); if (result != Argon2Library.ARGON2_OK) { String errMsg = Argon2Library.INSTANCE.argon2_error_message(result); throw new IllegalStateException(String.format("%s (%d)", errMsg, result)); } return Native.toString(encoded, ASCII); }
/** * Deploys WinDivert DLL and SYS files based upon Platform architecture (32/64bit). * * @param deployDirManager The TemporaryDirManager to create the temp directory where to store the files. * @return The {@link WinDivertDLL} instance to use. */ public static WinDivertDLL deploy(TemporaryDirManager deployDirManager) { String jnaLibraryPath = System.getProperty("jna.library.path"); try { File temp = deployDirManager.createTempDir(); if (temp != null && temp.delete() && temp.mkdir()) { System.setProperty("jna.library.path", deployInTempDir(temp)); return (WinDivertDLL) Native.loadLibrary(Platform.is64Bit() ? "WinDivert64" : "WinDivert32", WinDivertDLL.class); } else { throw new IOException("Could not create a proper temp dir"); } } catch (Exception e) { throw new ExceptionInInitializerError(new Exception("Unable to deploy WinDivert", e)); } finally { if (jnaLibraryPath != null) System.setProperty("jna.library.path", jnaLibraryPath); } }
private static void restartOnWindows(@NotNull final String... beforeRestart) throws IOException { Kernel32 kernel32 = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class); Shell32 shell32 = (Shell32)Native.loadLibrary("shell32", Shell32.class); final int pid = kernel32.GetCurrentProcessId(); final IntByReference argc = new IntByReference(); Pointer argv_ptr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc); final String[] argv = argv_ptr.getStringArray(0, argc.getValue(), true); kernel32.LocalFree(argv_ptr); doScheduleRestart(new File(PathManager.getBinPath(), "restarter.exe"), new Consumer<List<String>>() { @Override public void consume(List<String> commands) { Collections.addAll(commands, String.valueOf(pid), String.valueOf(beforeRestart.length)); Collections.addAll(commands, beforeRestart); Collections.addAll(commands, String.valueOf(argc.getValue())); Collections.addAll(commands, argv); } }); // Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter" // process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated // process which happened to have the same process ID. TimeoutUtil.sleep(500); }
public Capstone(int arch, int mode) { cs = (CS)Native.loadLibrary("capstone", CS.class); int version = cs.cs_version(null, null); if (version != (CS_API_MAJOR << 8) + CS_API_MINOR) { throw new RuntimeException("Different API version between core & binding (CS_ERR_VERSION)"); } this.arch = arch; this.mode = mode; ns = new NativeStruct(); ns.handleRef = new NativeLongByReference(); if (cs.cs_open(arch, mode, ns.handleRef) != CS_ERR_OK) { throw new RuntimeException("ERROR: Wrong arch or mode"); } ns.csh = ns.handleRef.getValue(); this.detail = CS_OPT_OFF; this.diet = cs.cs_support(CS_SUPPORT_DIET); }
public static void main(String[] args) { final User32 user32 = User32.INSTANCE; user32.EnumWindows(new WinUser.WNDENUMPROC() { int count = 0; @Override public boolean callback(WinDef.HWND hwnd, Pointer pointer) { byte[] windowText = new byte[512]; byte[] className = new byte[512]; user32.GetWindowTextA(hwnd, windowText, 512); user32.GetClassNameA(hwnd, className, 512); String title = Native.toString(windowText); String classN = Native.toString(className); // get rid of this if block if you want all windows regardless of whether // or not they have text if (title.isEmpty()) { return true; } System.out.println("Title: " + title + " Class name: " + classN); return true; } },null); }
private void gameToFront() { User32.INSTANCE.EnumWindows((hWnd, arg1) -> { char[] className = new char[512]; User32.INSTANCE.GetClassName(hWnd, className, 512); String wText = Native.toString(className); if (wText.isEmpty()) { return true; } if (wText.equals("POEWindowClass")) { User32.INSTANCE.SetForegroundWindow(hWnd); return false; } return true; }, null); }
private CSensors loadDynamicLibrary() { Object jnaProxy; try { jnaProxy = Native.loadLibrary("sensors", CSensors.class); } catch (UnsatisfiedLinkError err) { LOGGER.info("Cannot find library in system, using embedded one"); try { String libPath = SensorsUtils.generateLibTmpPath("/lib/linux/", "libsensors.so.4.4.0"); jnaProxy = Native.loadLibrary(libPath, CSensors.class); new File(libPath).delete(); } catch (UnsatisfiedLinkError err1) { jnaProxy = null; LOGGER.error("Cannot load sensors dinamic library", err1); } } return (CSensors) jnaProxy; }
@PostConstruct public void initialise() { log.info("Initialising NativeManager"); // Make sure the native directory exists File nativeDirectory = settingsManager.getFileFromConfigDirectory("native"); if (!nativeDirectory.exists()) { nativeDirectory.mkdirs(); } // Copy any native libraries to the config directory and load them if (settingsManager.getOsType() == OsType.OSX) { try { String userNotifications = "/native/NsUserNotificationsBridge.dylib"; File userNotificationsFile = settingsManager.getFileFromConfigDirectory(userNotifications); Files.copy(getClass().getResourceAsStream(userNotifications), userNotificationsFile.toPath(), StandardCopyOption.REPLACE_EXISTING); nsUserNotificationsBridge = (NsUserNotificationsBridge)Native .loadLibrary(userNotificationsFile.getAbsolutePath(), NsUserNotificationsBridge.class); } catch (Throwable t) { log.error("Error loading native notifications bridge", t); } } }
public static void main(String[] args) throws InterruptedException { //long lib = JTranscFFI.Loader.dlopen("kernel32.dll"); //System.out.println(lib); //long SleepAddr = JTranscFFI.Loader.dlsym(lib, "Sleep"); //System.out.println(SleepAddr); //SDL2 sdl2 = (SDL2) Native.loadLibrary("sdl2", SDL2.class); //sdl2.SDL_Init(SDL2.SDL_INIT_VIDEO); //sdl2.SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL2.SDL_WINDOW_SHOWN); ////Pointer.createConstant(10).getNativeLong() //Thread.sleep(1000L); if (JTranscSystem.isWindows()) { Kernel32 kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); User32 user32 = (User32) Native.loadLibrary("user32", User32.class); for (int n = 0; n < 6; n++) { kernel32.Beep(698 * (n + 1), 300); kernel32.Sleep(100); } user32.MessageBoxA(0, "done!", "done!", 0); } else { System.out.println("This demo just works on windows!"); } }
private LibNotifyWrapper() { myLibNotify = (LibNotify)Native.loadLibrary("libnotify.so.4", LibNotify.class); String appName = ApplicationNamesInfo.getInstance().getProductName(); if (myLibNotify.notify_init(appName) == 0) { throw new IllegalStateException("notify_init failed"); } String icon = AppUIUtil.findIcon(PathManager.getBinPath()); myIcon = icon != null ? icon : "dialog-information"; MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() { @Override public void appClosing() { synchronized (myLock) { myDisposed = true; myLibNotify.notify_uninit(); } } }); }
public static long allocate(long size) { long sizeInMb = size/1048576; long totalSizeInMb = ALLOCATED_SIZE.addAndGet(size)/1048576; LOGGER.info("Allocating off-heap memory block of " + sizeInMb + "Mb and total allocated off-heap memory size is " + totalSizeInMb + "Mb"); long retAddr = Native.malloc(size); memTracker.put(retAddr, size); return retAddr; }
/** * Returns the result of {@code gethostname()} function * from the standard Unix/Linux C Library. * * @return host name * @throws NativeException if there was an error executing the * system call. */ public static String cLibGetHostname() throws NativeException { byte[] buf = new byte[MAXHOSTNAMELEN]; int retCode = CLib.INSTANCE.gethostname(buf, buf.length); if (retCode == 0) { return Native.toString(buf); } throw new NativeException(retCode, "error calling 'gethostname()' function"); }
@SuppressWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME") private static Object load(Map<String,?> options) { try { return Native.loadLibrary(GENERIC, GnomeKeyringLibrary.class, options); } catch (UnsatisfiedLinkError x) { // #203735: on Oneiric, may have trouble finding right lib. // Precise is using multiarch (#211401) which should work automatically using JNA 3.4+ (#211403). // Unclear if this workaround is still needed for Oneiric with 3.4, but seems harmless to leave it in for now. if (new File(EXPLICIT_ONEIRIC).isFile()) { return Native.loadLibrary(EXPLICIT_ONEIRIC, GnomeKeyringLibrary.class, options); } else { throw x; } } }
public @Override byte[] encrypt(char[] cleartext) throws Exception { byte[] cleartextB = Utils.chars2Bytes(cleartext); CryptIntegerBlob input = new CryptIntegerBlob(); input.store(cleartextB); Arrays.fill(cleartextB, (byte) 0); CryptIntegerBlob output = new CryptIntegerBlob(); if (!CryptLib.INSTANCE.CryptProtectData(input, null, null, null, null, 0, output)) { throw new Exception("CryptProtectData failed: " + Native.getLastError()); } input.zero(); return output.load(); }
public @Override char[] decrypt(byte[] ciphertext) throws Exception { CryptIntegerBlob input = new CryptIntegerBlob(); input.store(ciphertext); CryptIntegerBlob output = new CryptIntegerBlob(); if (!CryptLib.INSTANCE.CryptUnprotectData(input, null, null, null, null, 0, output)) { throw new Exception("CryptUnprotectData failed: " + Native.getLastError()); } byte[] result = output.load(); // XXX gives CCE because not a Memory: output.zero(); char[] cleartext = Utils.bytes2Chars(result); Arrays.fill(result, (byte) 0); return cleartext; }
static void trySetMaxSizeVirtualMemory() { if (Constants.LINUX || Constants.MAC_OS_X) { final JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit(); if (JNACLibrary.getrlimit(JNACLibrary.RLIMIT_AS, rlimit) == 0) { MAX_SIZE_VIRTUAL_MEMORY = rlimit.rlim_cur.longValue(); } else { logger.warn("unable to retrieve max size virtual memory [" + JNACLibrary.strerror(Native.getLastError()) + "]"); } } }
static void tryVirtualLock() { JNAKernel32Library kernel = JNAKernel32Library.getInstance(); Pointer process = null; try { process = kernel.GetCurrentProcess(); // By default, Windows limits the number of pages that can be locked. // Thus, we need to first increase the working set size of the JVM by // the amount of memory we wish to lock, plus a small overhead (1MB). SizeT size = new SizeT(JvmInfo.jvmInfo().getMem().getHeapInit().getBytes() + (1024 * 1024)); if (!kernel.SetProcessWorkingSetSize(process, size, size)) { logger.warn("Unable to lock JVM memory. Failed to set working set size. Error code {}", Native.getLastError()); } else { JNAKernel32Library.MemoryBasicInformation memInfo = new JNAKernel32Library.MemoryBasicInformation(); long address = 0; while (kernel.VirtualQueryEx(process, new Pointer(address), memInfo, memInfo.size()) != 0) { boolean lockable = memInfo.State.longValue() == JNAKernel32Library.MEM_COMMIT && (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_NOACCESS) != JNAKernel32Library.PAGE_NOACCESS && (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_GUARD) != JNAKernel32Library.PAGE_GUARD; if (lockable) { kernel.VirtualLock(memInfo.BaseAddress, new SizeT(memInfo.RegionSize.longValue())); } // Move to the next region address += memInfo.RegionSize.longValue(); } LOCAL_MLOCKALL = true; } } catch (UnsatisfiedLinkError e) { // this will have already been logged by Kernel32Library, no need to repeat it } finally { if (process != null) { kernel.CloseHandle(process); } } }