Java Code Examples for com.sun.jna.Native#getLastError()
The following examples show how to use
com.sun.jna.Native#getLastError() .
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: NativeCallsJNAImpl.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
@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); }
Example 2
Source File: NativeCallsJNAImpl.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
@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); }
Example 3
Source File: Win32Protect.java From netbeans with Apache License 2.0 | 5 votes |
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(); }
Example 4
Source File: BuckDaemon.java From buck with Apache License 2.0 | 5 votes |
private static void markFdCloseOnExec(int fd) { int fdFlags; fdFlags = Libc.INSTANCE.fcntl(fd, Libc.Constants.rFGETFD); if (fdFlags == -1) { throw new LastErrorException(Native.getLastError()); } fdFlags |= Libc.Constants.rFDCLOEXEC; if (Libc.INSTANCE.fcntl(fd, Libc.Constants.rFSETFD, fdFlags) == -1) { throw new LastErrorException(Native.getLastError()); } }
Example 5
Source File: Win32Process.java From Java-Memory-Manipulation with Apache License 2.0 | 5 votes |
@Override public Process write(Pointer address, MemoryBuffer buffer) { if (Kernel32.WriteProcessMemory(pointer(), address, buffer, buffer.size(), 0) == 0) { throw new Win32Exception(Native.getLastError()); } return this; }
Example 6
Source File: Win32Process.java From Java-Memory-Manipulation with Apache License 2.0 | 5 votes |
@Override public MemoryBuffer read(Pointer address, int size, MemoryBuffer buffer) { if (Kernel32.ReadProcessMemory(pointer(), address, buffer, size, 0) == 0) { throw new Win32Exception(Native.getLastError()); } return buffer; }
Example 7
Source File: Win32Process.java From Java-Memory-Manipulation with Apache License 2.0 | 5 votes |
@Override public Process write(Pointer address, MemoryBuffer buffer) { if (Kernel32.WriteProcessMemory(pointer(), address, buffer, buffer.size(), 0) == 0) { throw new Win32Exception(Native.getLastError()); } return this; }
Example 8
Source File: Win32Process.java From Java-Memory-Manipulation with Apache License 2.0 | 5 votes |
@Override public MemoryBuffer read(Pointer address, int size, MemoryBuffer buffer) { if (Kernel32.ReadProcessMemory(pointer(), address, buffer, size, 0) == 0) { throw new Win32Exception(Native.getLastError()); } return buffer; }
Example 9
Source File: Seccomp.java From Elasticsearch with Apache License 2.0 | 5 votes |
static void windowsImpl() { if (!Constants.WINDOWS) { throw new IllegalStateException("bug: should not be trying to initialize ActiveProcessLimit for an unsupported OS"); } JNAKernel32Library lib = JNAKernel32Library.getInstance(); // create a new Job Pointer job = lib.CreateJobObjectW(null, null); if (job == null) { throw new UnsupportedOperationException("CreateJobObject: " + Native.getLastError()); } try { // retrieve the current basic limits of the job int clazz = JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION_CLASS; JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION limits = new JNAKernel32Library.JOBOBJECT_BASIC_LIMIT_INFORMATION(); limits.write(); if (!lib.QueryInformationJobObject(job, clazz, limits.getPointer(), limits.size(), null)) { throw new UnsupportedOperationException("QueryInformationJobObject: " + Native.getLastError()); } limits.read(); // modify the number of active processes to be 1 (exactly the one process we will add to the job). limits.ActiveProcessLimit = 1; limits.LimitFlags = JNAKernel32Library.JOB_OBJECT_LIMIT_ACTIVE_PROCESS; limits.write(); if (!lib.SetInformationJobObject(job, clazz, limits.getPointer(), limits.size())) { throw new UnsupportedOperationException("SetInformationJobObject: " + Native.getLastError()); } // assign ourselves to the job if (!lib.AssignProcessToJobObject(job, lib.GetCurrentProcess())) { throw new UnsupportedOperationException("AssignProcessToJobObject: " + Native.getLastError()); } } finally { lib.CloseHandle(job); } logger.debug("Windows ActiveProcessLimit initialization successful"); }
Example 10
Source File: Win32Protect.java From netbeans with Apache License 2.0 | 5 votes |
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; }
Example 11
Source File: JNANatives.java From Elasticsearch with Apache License 2.0 | 4 votes |
static void tryMlockall() { int errno = Integer.MIN_VALUE; String errMsg = null; boolean rlimitSuccess = false; long softLimit = 0; long hardLimit = 0; try { int result = JNACLibrary.mlockall(JNACLibrary.MCL_CURRENT); if (result == 0) { LOCAL_MLOCKALL = true; return; } errno = Native.getLastError(); errMsg = JNACLibrary.strerror(errno); if (Constants.LINUX || Constants.MAC_OS_X) { // we only know RLIMIT_MEMLOCK for these two at the moment. JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit(); if (JNACLibrary.getrlimit(JNACLibrary.RLIMIT_MEMLOCK, rlimit) == 0) { rlimitSuccess = true; softLimit = rlimit.rlim_cur.longValue(); hardLimit = rlimit.rlim_max.longValue(); } else { logger.warn("Unable to retrieve resource limits: " + JNACLibrary.strerror(Native.getLastError())); } } } catch (UnsatisfiedLinkError e) { // this will have already been logged by CLibrary, no need to repeat it return; } // mlockall failed for some reason logger.warn("Unable to lock JVM Memory: error=" + errno + ",reason=" + errMsg); logger.warn("This can result in part of the JVM being swapped out."); if (errno == JNACLibrary.ENOMEM) { if (rlimitSuccess) { logger.warn("Increase RLIMIT_MEMLOCK, soft limit: " + rlimitToString(softLimit) + ", hard limit: " + rlimitToString(hardLimit)); if (Constants.LINUX) { // give specific instructions for the linux case to make it easy String user = System.getProperty("user.name"); logger.warn("These can be adjusted by modifying /etc/security/limits.conf, for example: \n" + "\t# allow user '" + user + "' mlockall\n" + "\t" + user + " soft memlock unlimited\n" + "\t" + user + " hard memlock unlimited" ); logger.warn("If you are logged in interactively, you will have to re-login for the new limits to take effect."); } } else { logger.warn("Increase RLIMIT_MEMLOCK (ulimit)."); } } }
Example 12
Source File: AlignedBuffersDirectFileIO.java From ignite with Apache License 2.0 | 4 votes |
/** * Creates Direct File IO. * * @param ioBlockSize FS/OS block size. * @param pageSize Durable memory Page size. * @param file File to open. * @param modes Open options (flags). * @param tlbOnePageAligned Thread local with buffers with capacity = one page {@code pageSize} and aligned using * {@code ioBlockSize}. * @param managedAlignedBuffers Managed aligned buffers map, used to check if buffer is known. * @param log Logger. * @throws IOException if file open failed. */ AlignedBuffersDirectFileIO( int ioBlockSize, int pageSize, File file, OpenOption[] modes, ThreadLocal<ByteBuffer> tlbOnePageAligned, ConcurrentHashMap<Long, Thread> managedAlignedBuffers, IgniteLogger log) throws IOException { this.log = log; this.ioBlockSize = ioBlockSize; this.pageSize = pageSize; this.file = file; this.tlbOnePageAligned = tlbOnePageAligned; this.managedAlignedBuffers = managedAlignedBuffers; String pathname = file.getAbsolutePath(); int openFlags = setupOpenFlags(modes, log, true); int mode = IgniteNativeIoLib.DEFAULT_OPEN_MODE; int fd = IgniteNativeIoLib.open(pathname, openFlags, mode); if (fd < 0) { int error = Native.getLastError(); String msg = "Error opening file [" + pathname + "] with flags [0x" + String.format("%2X", openFlags) + ": DIRECT & " + Arrays.asList(modes) + "], got error [" + error + ": " + getLastError() + "]"; if (error == IgniteNativeIoLib.E_INVAL) { openFlags = setupOpenFlags(modes, log, false); fd = IgniteNativeIoLib.open(pathname, openFlags, mode); if (fd > 0) { U.warn(log, "Disable Direct IO mode for path " + file.getParentFile() + "(probably incompatible file system selected, for example, tmpfs): " + msg); this.fd = fd; fsBlockSize = FileSystemUtils.getFileSystemBlockSize(fd); return; } } throw new IOException(msg); } this.fd = fd; fsBlockSize = FileSystemUtils.getFileSystemBlockSize(fd); }
Example 13
Source File: WindowsUtilities.java From libreveris with GNU Lesser General Public License v3.0 | 4 votes |
public static int runElevated (File exec, File pwd, String... args) throws IOException, InterruptedException { // Concatenate arguments into one string StringBuilder sb = new StringBuilder(); for (String arg : args) { sb.append(arg) .append(" "); } logger.debug("exec: {}", exec); logger.debug("pwd: {}", pwd); logger.debug("params: {}", sb); logger.debug("Calling ShellExecuteEx..."); // error code 740 is ERROR_ELEVATION_REQUIRED, indicating that // we run in UAC-enabled Windows and we need to run this in an elevated privilege SHELLEXECUTEINFO sei = new SHELLEXECUTEINFO(); sei.fMask = SHELLEXECUTEINFO.SEE_MASK_NOCLOSEPROCESS; sei.lpVerb = "runas"; sei.lpFile = exec.getAbsolutePath(); sei.lpParameters = sb.toString(); sei.lpDirectory = pwd.getAbsolutePath(); sei.nShow = SHELLEXECUTEINFO.SW_HIDE; if (!Shell32.INSTANCE.ShellExecuteEx(sei)) { throw new IOException( "Failed to shellExecute: " + Native.getLastError()); } try { int result = Kernel32Utils.waitForExitProcess(sei.hProcess); logger.debug("result: {}", result); return result; } finally { // TODO: need to print content of stdout/stderr // FileInputStream fin = new FileInputStream( // new File(pwd, "redirect.log")); // IOUtils.copy(fin, out.getLogger()); // fin.close(); } }
Example 14
Source File: MlockAll.java From Chronicle-Queue with Apache License 2.0 | 4 votes |
public static void doMlockall() throws IOException { if (mlockall(1) != 0) throw new IOException("mlockall failed: error code " + Native.getLastError()); }
Example 15
Source File: UartNative.java From arcusplatform with Apache License 2.0 | 4 votes |
@SuppressWarnings("deprecation") public void open() throws IOException { Native.setPreserveLastError(true); int ofd = IMPL.open(port, IMPL.constants().getOpenFlags()); if (ofd < 0) { throw new IOException("cannot open serial port: " + port); } try { int result; this.fd = ofd; this.filedesc = toFileDescriptor(fd); result = IMPL.fcntl(ofd, IMPL.constants().getfl()); result = IMPL.fcntl(ofd, IMPL.constants().setfl(), result & ~IMPL.constants().nonblock()); if (result < 0) { throw new IOException("cannot set serial port to non-blocking: " + Native.getLastError()); } result = IMPL.tcgetattr(ofd, oldtio); if (result < 0) { throw new IOException("cannot get current serial port settings: " + Native.getLastError()); } IMPL.cfmakeraw(newtio); result = IMPL.cfsetispeed(newtio, inputBaudRate); if (result < 0) { throw new IOException("cannot set serial port input speed: " + Native.getLastError()); } result = IMPL.cfsetospeed(newtio, outputBaudRate); if (result < 0) { throw new IOException("cannot set serial port output speed: " + Native.getLastError()); } IMPL.setTiosCc(newtio, IMPL.constants().vmin(), (byte)vmin); IMPL.setTiosCc(newtio, IMPL.constants().vtime(), (byte)vtime); IMPL.setTiosCc(newtio, IMPL.constants().vstart(), (byte)XON); IMPL.setTiosCc(newtio, IMPL.constants().vstop(), (byte)XOFF); long c_cflag = IMPL.getTiosCFlags(newtio); long c_iflag = IMPL.getTiosIFlags(newtio); c_cflag |= IMPL.constants().cread(); c_cflag |= IMPL.constants().clocal(); c_cflag &= ~IMPL.constants().csize(); c_iflag |= IMPL.constants().ignpar(); switch (data) { case DATA5: c_cflag |= IMPL.constants().cs5(); break; case DATA6: c_cflag |= IMPL.constants().cs6(); break; case DATA7: c_cflag |= IMPL.constants().cs7(); break; case DATA8: c_cflag |= IMPL.constants().cs8(); break; default: throw new IOException("unknown char size"); } switch (stop) { case STOP1: break; case STOP2: c_cflag |= IMPL.constants().cstopb(); break; default: throw new IOException("unknown number of stop bits"); } switch (parity) { case NONE: break; case EVEN: c_cflag |= IMPL.constants().parenb(); break; case ODD: c_cflag |= IMPL.constants().parenb() | IMPL.constants().parodd(); break; default: throw new IOException("unknown parity"); } switch (flow) { case NONE: break; case XONXOFF: c_iflag |= IMPL.constants().ixon() | IMPL.constants().ixoff(); break; case RTSCTS: c_cflag |= IMPL.constants().crtscts(); break; default: throw new IOException("unknown flow control"); } IMPL.setTiosCFlags(newtio, c_cflag); IMPL.setTiosIFlags(newtio, c_iflag); IMPL.tcflush(ofd, IMPL.constants().tciflush()); result = IMPL.tcsetattr(ofd, IMPL.constants().tcsanow(), newtio); if (result < 0) { throw new IOException("cannot setup serial port settings"); } } catch (Throwable th) { IMPL.close(ofd); this.fd = -1; this.filedesc = null; throw th; } }
Example 16
Source File: JNANatives.java From crate with Apache License 2.0 | 4 votes |
static void tryMlockall() { int errno = Integer.MIN_VALUE; String errMsg = null; boolean rlimitSuccess = false; long softLimit = 0; long hardLimit = 0; try { int result = JNACLibrary.mlockall(JNACLibrary.MCL_CURRENT); if (result == 0) { LOCAL_MLOCKALL = true; return; } errno = Native.getLastError(); errMsg = JNACLibrary.strerror(errno); if (Constants.LINUX || Constants.MAC_OS_X) { // we only know RLIMIT_MEMLOCK for these two at the moment. JNACLibrary.Rlimit rlimit = new JNACLibrary.Rlimit(); if (JNACLibrary.getrlimit(JNACLibrary.RLIMIT_MEMLOCK, rlimit) == 0) { rlimitSuccess = true; softLimit = rlimit.rlim_cur.longValue(); hardLimit = rlimit.rlim_max.longValue(); } else { LOGGER.warn("Unable to retrieve resource limits: {}", JNACLibrary.strerror(Native.getLastError())); } } } catch (UnsatisfiedLinkError e) { // this will have already been logged by CLibrary, no need to repeat it return; } // mlockall failed for some reason LOGGER.warn("Unable to lock JVM Memory: error={}, reason={}", errno , errMsg); LOGGER.warn("This can result in part of the JVM being swapped out."); if (errno == JNACLibrary.ENOMEM) { if (rlimitSuccess) { LOGGER.warn("Increase RLIMIT_MEMLOCK, soft limit: {}, hard limit: {}", rlimitToString(softLimit), rlimitToString(hardLimit)); if (Constants.LINUX) { // give specific instructions for the linux case to make it easy String user = System.getProperty("user.name"); LOGGER.warn("These can be adjusted by modifying /etc/security/limits.conf, for example: \n" + "\t# allow user '{}' mlockall\n" + "\t{} soft memlock unlimited\n" + "\t{} hard memlock unlimited", user, user, user ); LOGGER.warn("If you are logged in interactively, you will have to re-login for the new limits to take effect."); } } else { LOGGER.warn("Increase RLIMIT_MEMLOCK (ulimit)."); } } }
Example 17
Source File: errno.java From domino-jna with Apache License 2.0 | 2 votes |
/** * The <errno.h> header file defines the integer variable errno, which is * set by system calls and some library functions in the event of an error * to indicate what went wrong. Its value is significant only when the call * returned an error (usually -1), and a function that does succeed is * allowed to change errno. * * Sometimes, when -1 is also a valid successful return value one has to * zero errno before the call in order to detect possible errors. * * errno is defined by the ISO C standard to be a modifiable lvalue of type * int, and must not be explicitly declared; errno may be a macro. errno is * thread-local; setting it in one thread does not affect its value in any * other thread. * * Valid error numbers are all non-zero; errno is never set to zero by any * library function. All the error names specified by POSIX.1 must have * distinct values, with the exception of EAGAIN and EWOULDBLOCK, which may * be the same. * * Below is a list of the symbolic error names that are defined on Linux. * Some of these are marked POSIX.1, indicating that the name is defined by * POSIX.1-2001, or C99, indicating that the name is defined by C99. * * @return error number */ public static int errno() { return Native.getLastError(); }