public void testCustomStringEncoding() throws Exception { final String ENCODING = System.getProperty("file.encoding"); // Keep stuff within the extended ASCII range so we work with more // limited native encodings String UNICODE = "Un \u00e9l\u00e9ment gr\u00e2ce \u00e0 l'index"; if (!UNICODE.equals(new String(UNICODE.getBytes()))) { // If the extended characters aren't encodable in the default // encoding, punt and use straight ASCII UNICODE = ""; for (char ch = 1; ch < 128; ch++) { UNICODE += ch; } } final String UNICODEZ = UNICODE + "\0more stuff"; byte[] customEncoded = Native.getBytes(UNICODE, ENCODING); byte[] expected = UNICODE.getBytes(ENCODING); for (int i = 0; i < Math.min(customEncoded.length, expected.length); i++) { assertEquals( "Improperly encoded (" + ENCODING + ") from Java at " + i, expected[i], customEncoded[i]); } assertEquals( "Wrong number of encoded characters (" + ENCODING + ")", expected.length, customEncoded.length); String result = Native.toString(customEncoded, ENCODING); assertEquals("Improperly decoded from native bytes (" + ENCODING + ")", UNICODE, result); assertEquals( "Should truncate bytes at NUL terminator", UNICODE, Native.toString(UNICODEZ.getBytes(ENCODING), ENCODING)); }
public void testSynchronizedAccess() throws Exception { final boolean[] lockHeld = {false}; final NativeLibrary nlib = NativeLibrary.getInstance("testlib", TestLib.class.getClassLoader()); final TestLib lib = (TestLib) Native.loadLibrary("testlib", TestLib.class); final TestLib synchlib = (TestLib) Native.synchronizedLibrary(lib); final TestLib.VoidCallback cb = new TestLib.VoidCallback() { public void callback() { lockHeld[0] = Thread.holdsLock(nlib); } }; Thread t0 = new Thread() { public void run() { lib.callVoidCallback(cb); } }; t0.start(); t0.join(); assertFalse( "NativeLibrary lock should not be held during native call to normal library", lockHeld[0]); Thread t1 = new Thread() { public void run() { synchlib.callVoidCallback(cb); } }; t1.start(); t1.join(); assertTrue( "NativeLibrary lock should be held during native call to synchronized library", lockHeld[0]); }
static { Throwable cause = null; FileDescriptor epollFd = null; FileDescriptor eventFd = null; try { epollFd = Native.newEpollCreate(); eventFd = Native.newEventFd(); } catch (Throwable t) { cause = t; } finally { if (epollFd != null) { try { epollFd.close(); } catch (Exception ignore) { // ignore } } if (eventFd != null) { try { eventFd.close(); } catch (Exception ignore) { // ignore } } } if (cause != null) { UNAVAILABILITY_CAUSE = cause; } else { UNAVAILABILITY_CAUSE = null; } }
public void testUseSingleLibraryInstance() { TestLibrary lib = (TestLibrary) Native.loadLibrary("testlib", TestLibrary.class); int count = lib.callCount(); TestLibrary lib2 = (TestLibrary) Native.loadLibrary("testlib", TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Interfaces should share a library instance", count + 1, count2); }
/** Returns the bounds of the given window, in absolute coordinates */ static Rectangle getWindowGeometry(long window) { XToolkit.awtLock(); try { int res = XlibWrapper.XGetGeometry( XToolkit.getDisplay(), window, XlibWrapper.larg1, // root_return XlibWrapper.larg2, // x_return XlibWrapper.larg3, // y_return XlibWrapper.larg4, // width_return XlibWrapper.larg5, // height_return XlibWrapper.larg6, // border_width_return XlibWrapper.larg7); // depth_return if (res == 0) { return null; } int x = Native.getInt(XlibWrapper.larg2); int y = Native.getInt(XlibWrapper.larg3); long width = Native.getUInt(XlibWrapper.larg4); long height = Native.getUInt(XlibWrapper.larg5); return new Rectangle(x, y, (int) width, (int) height); } finally { XToolkit.awtUnlock(); } }
@Override public int send(ByteBuffer src, SocketAddress target) throws IOException { UnixSocketAddress remote = null; if (null == target) { if (isConnected()) { remote = remoteAddress; } else { throw new IllegalArgumentException( "Destination address cannot be null on unconnected datagram sockets"); } } else { if (!(target instanceof UnixSocketAddress)) { throw new UnsupportedAddressTypeException(); } remote = (UnixSocketAddress) target; } SockAddrUnix sa = (null == remote) ? null : remote.getStruct(); int addrlen = (null == sa) ? 0 : sa.length(); int n = Native.sendto(getFD(), src, sa, addrlen); if (n < 0) { throw new IOException(Native.getLastErrorString()); } return n; }
public void testAliasLibraryFilename() { TestLibrary lib = (TestLibrary) Native.loadLibrary("testlib", TestLibrary.class); int count = lib.callCount(); NativeLibrary nl = NativeLibrary.getInstance("testlib"); TestLibrary lib2 = (TestLibrary) Native.loadLibrary(nl.getFile().getName(), TestLibrary.class); int count2 = lib2.callCount(); assertEquals("Simple filename load not aliased", count + 1, count2); }
EpollSocketChannel(Channel parent, int fd) { super(parent, fd, Native.EPOLLIN, true); config = new EpollSocketChannelConfig(this); // Directly cache the remote and local addresses // See https://github.com/netty/netty/issues/2359 remote = Native.remoteAddress(fd); local = Native.localAddress(fd); }
public static int[] makeHWArray(int len, int address, int idx, int cp) { int p = Native.rdMem(cp - 1); p = Native.rdMem(p + 1); p += idx * 2; Native.wrMem(address, p); Native.wrMem(len, p + 1); return Native.toIntArray(p); }
/** Invoked on a hardware generated exception. */ static void except() { saved_sp = Native.getSP(); if (Native.rdMem(Const.IO_EXCPT) == Const.EXC_SPOV) { // reset stack pointer Native.setSP(Const.STACK_OFF); } // we have more stack available now for the stack overflow handleException(); }
@Override public UnixSocketAddress receive(ByteBuffer src) throws IOException { UnixSocketAddress remote = new UnixSocketAddress(); int n = Native.recvfrom(getFD(), src, remote.getStruct()); if (n < 0) { throw new IOException(Native.getLastErrorString()); } return remote; }
protected void createCursor( byte[] xorMask, byte[] andMask, int width, int height, int fcolor, int bcolor, int xHotSpot, int yHotSpot) { XToolkit.awtLock(); try { long display = XToolkit.getDisplay(); long root_window = XlibWrapper.RootWindow(display, XlibWrapper.DefaultScreen(display)); long colormap = XToolkit.getDefaultXColormap(); XColor fore_color = new XColor(); fore_color.set_flags((byte) (XlibWrapper.DoRed | XlibWrapper.DoGreen | XlibWrapper.DoBlue)); fore_color.set_red((short) (((fcolor >> 16) & 0x000000ff) << 8)); fore_color.set_green((short) (((fcolor >> 8) & 0x000000ff) << 8)); fore_color.set_blue((short) (((fcolor >> 0) & 0x000000ff) << 8)); XlibWrapper.XAllocColor(display, colormap, fore_color.pData); XColor back_color = new XColor(); back_color.set_flags((byte) (XlibWrapper.DoRed | XlibWrapper.DoGreen | XlibWrapper.DoBlue)); back_color.set_red((short) (((bcolor >> 16) & 0x000000ff) << 8)); back_color.set_green((short) (((bcolor >> 8) & 0x000000ff) << 8)); back_color.set_blue((short) (((bcolor >> 0) & 0x000000ff) << 8)); XlibWrapper.XAllocColor(display, colormap, back_color.pData); long nativeXorMask = Native.toData(xorMask); long source = XlibWrapper.XCreateBitmapFromData(display, root_window, nativeXorMask, width, height); long nativeAndMask = Native.toData(andMask); long mask = XlibWrapper.XCreateBitmapFromData(display, root_window, nativeAndMask, width, height); long cursor = XlibWrapper.XCreatePixmapCursor( display, source, mask, fore_color.pData, back_color.pData, xHotSpot, yHotSpot); XlibWrapper.unsafe.freeMemory(nativeXorMask); XlibWrapper.unsafe.freeMemory(nativeAndMask); XlibWrapper.XFreePixmap(display, source); XlibWrapper.XFreePixmap(display, mask); back_color.dispose(); fore_color.dispose(); XGlobalCursorManager.setPData(this, cursor); } finally { XToolkit.awtUnlock(); } }
public void testOptionsInferenceFromEncodingField() { assertEquals( "Wrong encoding found for interface which provides STRING_ENCODING", TestInterfaceWithEncoding.STRING_ENCODING, Native.getStringEncoding(TestInterfaceWithEncoding.class)); assertEquals( "Wrong encoding found for structure from interface which provides STRING_ENCODING", TestInterfaceWithEncoding.STRING_ENCODING, Native.getStringEncoding(TestInterfaceWithEncoding.TestStructure.class)); }
public void testOptionsInferenceFromTypeMapperField() { assertEquals( "Wrong type mapper found for interface which provides TYPE_MAPPER", TestInterfaceWithTypeMapper.TEST_MAPPER, Native.getTypeMapper(TestInterfaceWithTypeMapper.class)); assertEquals( "Wrong type mapper found for structure from interface which provides TYPE_MAPPER", TestInterfaceWithTypeMapper.TEST_MAPPER, Native.getTypeMapper(TestInterfaceWithTypeMapper.TestStructure.class)); }
public void testOptionsInferenceFromAlignmentField() { assertEquals( "Wrong alignment found for interface which provides STRUCTURE_ALIGNMENT", Structure.ALIGN_NONE, Native.getStructureAlignment(TestInterfaceWithAlignment.class)); assertEquals( "Wrong alignment found for structure from interface which provides STRUCTURE_ALIGNMENT", Structure.ALIGN_NONE, Native.getStructureAlignment(TestInterfaceWithAlignment.TestStructure.class)); }
/** * Retrieves the Handle object associated with a {@link RubyObject}. Retrieval is either done * through the {@link GC} for Handles that have already been created, or depending on the object's * native class index.<br> * Fixnum's and Symbol's native Handles are created through bit-shifting on their values, File and * Float Handles are created using special JNI methods. All other objects are passed to the * generic {@link Native#newHandle} method.<br> * Once a Handle has been created, it is registered with the {@link GC} to prevent * garbage-collection during native method runs. */ static Handle valueOf(IRubyObject obj) { Handle h = GC.lookup(obj); if (h != null) { return h; } Ruby runtime = obj.getRuntime(); long nativeHandle; if (obj instanceof RubyObject) { int type = ((RubyObject) obj).getNativeTypeIndex(); switch (type) { case ClassIndex.FIXNUM: { final long val = ((RubyFixnum) obj).getLongValue(); nativeHandle = (val <= FIXNUM_MAX && val >= FIXNUM_MIN) ? ((val << FIXNUM_SHIFT) | FIXNUM_FLAG) : Native.getInstance(runtime).newFixnumHandle(obj, val); } break; case ClassIndex.FLOAT: nativeHandle = Native.getInstance(runtime).newFloatHandle(obj, ((RubyNumeric) obj).getDoubleValue()); break; case ClassIndex.SYMBOL: nativeHandle = ((long) ((RubySymbol) obj).getId() << SYMBOL_SHIFT) | SYMBOL_FLAG; break; case ClassIndex.FILE: // RubyIO uses FILE as type index, matching MRI's T_FILE nativeHandle = Native.getInstance(runtime) .newIOHandle( obj, (int) ((RubyIO) obj).fileno(runtime.getCurrentContext()).getLongValue(), ((RubyIO) obj).getOpenFile().getMode()); break; default: nativeHandle = Native.getInstance(runtime).newHandle(obj, type); break; } } else { nativeHandle = Native.getInstance(runtime).newHandle(obj, ClassIndex.OBJECT); } Handle handle = newHandle(runtime, obj, nativeHandle); GC.register(obj, handle); return handle; }
/** * Dispatch an interrupt to the handler according to the core and the interrupt number. Interrupt * 0 is the scheduler. */ static void interrupt() { // the clean way // ih[sys.cpuId][sys.intNr].run(); // a little bit faster ih[Native.rd(Const.IO_CPU_ID)][Native.rd(Const.IO_INTNR)].run(); // Enable interrupts again - we could have invoked a dummy handler Native.wr(1, Const.IO_INT_ENA); // wr('!'); // wr('0'+nr); }
public void testRemoveTemporaries() throws Exception { File dir = Native.getTempDir(); File tmp = new File(dir, Native.JNA_TMPLIB_PREFIX); tmp.delete(); try { assertTrue("Couldn't create temporary file " + tmp, tmp.createNewFile()); assertTrue("File isn't recognized as unpacked", Native.isUnpacked(tmp)); Native.markTemporaryFile(tmp); Native.removeTemporaryFiles(); assertFalse("Temporary file still exists", tmp.exists()); } finally { tmp.delete(); } }
/** Read bytes into the given {@link ByteBuf} and return the amount. */ private int doReadBytes(ByteBuf byteBuf) throws Exception { int writerIndex = byteBuf.writerIndex(); int localReadAmount; if (byteBuf.hasMemoryAddress()) { localReadAmount = Native.readAddress(fd, byteBuf.memoryAddress(), writerIndex, byteBuf.capacity()); } else { ByteBuffer buf = byteBuf.internalNioBuffer(writerIndex, byteBuf.writableBytes()); localReadAmount = Native.read(fd, buf, buf.position(), buf.limit()); } if (localReadAmount > 0) { byteBuf.writerIndex(writerIndex + localReadAmount); } return localReadAmount; }
public void testGetBytesBadEncoding() throws Exception { byte[] buf = Native.getBytes(getName(), "unsupported"); assertEquals( "Incorrect fallback bytes with bad encoding", getName(), new String(buf, System.getProperty("file.encoding"))); }
public void testStructureConversion() throws Exception { DefaultTypeMapper mapper = new DefaultTypeMapper(); TypeConverter converter = new TypeConverter() { public Object toNative(Object value, ToNativeContext ctx) { return new Integer(Boolean.TRUE.equals(value) ? 1 : 0); } public Object fromNative(Object value, FromNativeContext context) { return new Boolean(((Integer) value).intValue() == 1); } public Class nativeType() { return Integer.class; } }; mapper.addTypeConverter(Boolean.class, converter); Map options = new HashMap(); options.put(Library.OPTION_TYPE_MAPPER, mapper); StructureTestLibrary lib = (StructureTestLibrary) Native.loadLibrary("testlib", StructureTestLibrary.class, options); StructureTestLibrary.TestStructure s = new StructureTestLibrary.TestStructure(mapper); assertEquals("Wrong native size", 4, s.size()); s.data = true; s.write(); assertEquals("Wrong value written", 1, s.getPointer().getInt(0)); s.getPointer().setInt(0, 0); s.read(); assertFalse("Wrong value read", s.data); }
/*@Includes({"<sys/select.h>"})*/ public interface Select extends Library { Select INSTANCE = (Select) Native.loadLibrary("RTLD", Select.class); /** The maximum number of file descriptors that a fd_set object can hold information about. */ public static final int FD_SETSIZE = INSTANCE.initConstInt(0); /** The maximum number of file descriptors that a fd_set object can hold information about. */ public static final int fd_set_SIZEOF = INSTANCE.initConstInt(1); /** * Select() examines the I/O descriptor sets whose addresses are passed in readfds, writefds, and * errorfds to see if some of their descriptors are ready for reading, are ready for writ- ing, or * have an exceptional condition pending, respectively. * * <p>On return, select() replaces the given descriptor sets with subsets consisting of those * descriptors that are ready for the requested operation. * * @param nfds The first nfds descriptors are checked in each set * @param readfds * @param writefds * @param errorfds * @param timeout if timout is nill, wait forever, if a pointer to a zero'd timeval, then does NOT * wait. * @return the total number of ready descriptors in all the sets */ // int select(int nfds, Pointer readfds, // Pointer writefds, // Pointer errorfds, // Pointer timeout); /** * removes fd from fdset * * @param fd * @param fd_set */ /*@NativeName("sysFD_CLR")*/ // wrapper for macro FD_CLR void FD_CLR(int fd, Pointer fd_set); /** * includes a particular descriptor fd in fdset. * * @param fd * @param fd_set */ /*@NativeName("sysFD_SET")*/ // wrapper for macro FD_SET void FD_SET(int fd, Pointer fd_set); /** * is non-zero if fd is a member of fd_set, zero otherwise. * * @param fd * @param fd_set * @return */ /*@NativeName("sysFD_ISSET")*/ // wrapper for macro FD_ISSET boolean FD_ISSET(int fd, Pointer fd_set); }
static { OS os = Native.load("/", "jnotify"); String clsName = null; String overrideClass = System.getProperty("jnotify.impl.override"); if (overrideClass != null) { clsName = overrideClass; } else { switch (os) { case WINDOWS: clsName = "net.contentobjects.jnotify.win32.JNotifyAdapterWin32"; break; case LINUX: case SOLARIS: clsName = "net.contentobjects.jnotify.linux.JNotifyAdapterLinux"; break; case MAC: clsName = "net.contentobjects.jnotify.macosx.JNotifyAdapterMacOSX"; break; } } try { _instance = (IJNotify) Class.forName(clsName).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }
private void parseCmdLineAndEnvVars() { String s = Native.getCmdLineAndEnvVars(pid); if (s == null) throw new WinpException("Failed to obtain for PID=" + pid); int sep = s.indexOf('\0'); commandline = s.substring(0, sep); envVars = new TreeMap<String, String>(CASE_INSENSITIVE_COMPARATOR); s = s.substring(sep + 1); while (s.length() > 0) { sep = s.indexOf('\0'); if (sep == 0) return; String t; if (sep == -1) { t = s; s = ""; } else { t = s.substring(0, sep); s = s.substring(sep + 1); } sep = t.indexOf('='); if (sep != -1) // be defensive. not exactly sure when this happens, but see HUDSON-4034 envVars.put(t.substring(0, sep), t.substring(sep + 1)); } }
public void testVersion() { String[] INPUTS = {"1.0", "1.0.1", "2.1.3"}; float[] EXPECTED = {1.0f, 1.0f, 2.1f}; for (int i = 0; i < INPUTS.length; i++) { assertEquals("Incorrectly parsed version", EXPECTED[i], Native.parseVersion(INPUTS[i])); } }
/** Simple example of native library declaration and usage. */ public interface User32 extends Library { User32 INSTANCE = (User32) Native.loadLibrary(null, User32.class); void system(String command); void printf(String text, Object... obj); void WriteConsoleOutputCharacterA(int hwnd, String content, int size, int coord, Object bytes); int GetStdHandle(int ok); int CreateConsoleScreenBuffer(int access, int shareMode, Object security, int flags, Object data); int SetConsoleActiveScreenBuffer(int hwnd); int SetConsoleCursorInfo(int hwnd); // int cursorInfo); int GetConsoleCursorInfo(int hwnd); int SetConsoleScreenBufferSize(int hwnd, int size); int WriteConsoleA(int hwnd, String text, int size, int lpNumberOfCharsWritten, Object flags); int ReadConsoleA(int hwnd, String text, int size, String out, Object smg); int FlushConsoleInputBuffer(int hwnd); int ReadConsoleOutputCharacterA(int hwnd, String text, int size, int coord, Object smg); int SetConsoleTitleA(String title); }
public void testToByteArray() { final String VALUE = getName(); byte[] buf = Native.toByteArray(VALUE); assertEquals("Wrong byte array length", VALUE.getBytes().length + 1, buf.length); assertEquals("Missing NUL terminator", (byte) 0, buf[buf.length - 1]); assertEquals("Wrong byte array contents", VALUE, new String(buf, 0, buf.length - 1)); }
public static void testEncode(String input, String encoding) throws XcodeException { String inputdecoded = null; String output = null; String variant = null; if (input == null) { Debug.pass(""); return; } input = input.trim(); if (input.length() == 0 || input.charAt(0) == '#') { Debug.pass(input); return; } try { inputdecoded = new String(Hex.decodeChars(input)); output = Native.encode(inputdecoded, encoding); } catch (XcodeException x) { Debug.fail(input + " ERROR:" + x.getCode() + " " + x.getMessage()); return; } System.out.println(Hex.encode(output.toCharArray())); }
/** * Returns an instance of NativeLibrary for the specified name. The library is loaded if not * already loaded. If already loaded, the existing instance is returned. * * <p>More than one name may map to the same NativeLibrary instance; only a single instance will * be provided for any given unique file path. * * @param libraryName The library name to load. This can be short form (e.g. "c"), an explicit * version (e.g. "libc.so.6" or "QuickTime.framework/Versions/Current/QuickTime"), or the full * (absolute) path to the library (e.g. "/lib/libc.so.6"). * @param options native library options for the given library (see {@link Library}). */ public static final NativeLibrary getInstance(String libraryName, Map options) { options = new HashMap(options); if (options.get(Library.OPTION_CALLING_CONVENTION) == null) { options.put(Library.OPTION_CALLING_CONVENTION, new Integer(Function.C_CONVENTION)); } // Use current process to load libraries we know are already // loaded by the VM to ensure we get the correct version if ((Platform.isLinux() || Platform.isAIX()) && Platform.C_LIBRARY_NAME.equals(libraryName)) { libraryName = null; } synchronized (libraries) { WeakReference ref = (WeakReference) libraries.get(libraryName + options); NativeLibrary library = ref != null ? (NativeLibrary) ref.get() : null; if (library == null) { if (libraryName == null) { library = new NativeLibrary("<process>", null, Native.open(null, openFlags(options)), options); } else { library = loadLibrary(libraryName, options); } ref = new WeakReference(library); libraries.put(library.getName() + options, ref); File file = library.getFile(); if (file != null) { libraries.put(file.getAbsolutePath() + options, ref); libraries.put(file.getName() + options, ref); } } return library; } }
public void testFindDirectMappedClassFailure() { try { Native.findDirectMappedClass(NativeTest.class); fail("Expect an exception if native-mapped class can't be found"); } catch (IllegalArgumentException e) { } }