Java Native Access Platform provides cross-platform mappings and utilities for commonly used platform functions across Windows, macOS, and Linux systems.
—
POSIX-compliant system calls and Linux-specific functionality including X11 graphics, device management, file system operations, and platform-specific utilities for AIX and Solaris systems.
Standard C library functions providing essential POSIX system calls for file operations, process management, and system interaction.
/**
* Standard C library functions (POSIX)
*/
public interface LibC extends Library {
LibC INSTANCE = Native.load("c", LibC.class);
/**
* Open file or device
* @param path File path to open
* @param flags Open flags (O_RDONLY, O_WRONLY, O_RDWR, etc.)
* @return File descriptor, or -1 if failed
*/
int open(String path, int flags);
/**
* Open file with mode specification
* @param path File path to open
* @param flags Open flags
* @param mode File permission mode (for O_CREAT)
* @return File descriptor, or -1 if failed
*/
int open(String path, int flags, int mode);
/**
* Close file descriptor
* @param fd File descriptor to close
* @return 0 if successful, -1 if failed
*/
int close(int fd);
/**
* Read from file descriptor
* @param fd File descriptor to read from
* @param buf Buffer to read into
* @param count Maximum bytes to read
* @return Number of bytes read, or -1 if failed
*/
NativeLong read(int fd, Pointer buf, NativeLong count);
/**
* Write to file descriptor
* @param fd File descriptor to write to
* @param buf Buffer containing data to write
* @param count Number of bytes to write
* @return Number of bytes written, or -1 if failed
*/
NativeLong write(int fd, Pointer buf, NativeLong count);
/**
* Change file permissions
* @param path File path
* @param mode New permission mode
* @return 0 if successful, -1 if failed
*/
int chmod(String path, int mode);
/**
* Change file ownership
* @param path File path
* @param owner New owner user ID
* @param group New group ID
* @return 0 if successful, -1 if failed
*/
int chown(String path, int owner, int group);
/**
* Get process ID
* @return Current process ID
*/
int getpid();
/**
* Get parent process ID
* @return Parent process ID
*/
int getppid();
/**
* Get user ID
* @return Current user ID
*/
int getuid();
/**
* Get effective user ID
* @return Effective user ID
*/
int geteuid();
}Usage Examples:
import com.sun.jna.platform.unix.LibC;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
// Open a file for reading
int fd = LibC.INSTANCE.open("/etc/passwd", LibC.O_RDONLY);
if (fd != -1) {
// Read from file
Memory buffer = new Memory(1024);
NativeLong bytesRead = LibC.INSTANCE.read(fd, buffer, new NativeLong(1024));
if (bytesRead.longValue() > 0) {
String content = buffer.getString(0);
System.out.println("Read " + bytesRead.longValue() + " bytes:");
System.out.println(content);
}
// Close file
LibC.INSTANCE.close(fd);
} else {
System.err.println("Failed to open file");
}
// Get process information
System.out.println("PID: " + LibC.INSTANCE.getpid());
System.out.println("Parent PID: " + LibC.INSTANCE.getppid());
System.out.println("UID: " + LibC.INSTANCE.getuid());X11 protocol bindings for graphics operations, window management, and event handling in Unix/Linux desktop environments.
/**
* X Window System functions
*/
public interface X11 extends Library {
X11 INSTANCE = Native.load("X11", X11.class);
/**
* Open connection to X server
* @param display_name Display name (can be null for default)
* @return Display pointer, or null if failed
*/
Display XOpenDisplay(String display_name);
/**
* Close connection to X server
* @param display Display to close
* @return 0 if successful
*/
int XCloseDisplay(Display display);
/**
* Create simple window
* @param display X display
* @param parent Parent window
* @param x X coordinate
* @param y Y coordinate
* @param width Window width
* @param height Window height
* @param border_width Border width
* @param border Border color
* @param background Background color
* @return Window ID
*/
Window XCreateSimpleWindow(Display display, Window parent, int x, int y,
int width, int height, int border_width,
NativeLong border, NativeLong background);
/**
* Map window (make visible)
* @param display X display
* @param window Window to map
* @return status code
*/
int XMapWindow(Display display, Window window);
/**
* Unmap window (hide)
* @param display X display
* @param window Window to unmap
* @return status code
*/
int XUnmapWindow(Display display, Window window);
/**
* Destroy window
* @param display X display
* @param window Window to destroy
* @return status code
*/
int XDestroyWindow(Display display, Window window);
/**
* Get next event from queue
* @param display X display
* @param event_return Event structure to fill
* @return status code
*/
int XNextEvent(Display display, XEvent event_return);
/**
* Check if events are pending
* @param display X display
* @return number of pending events
*/
int XPending(Display display);
}
/**
* X11 Display structure
*/
public static class Display extends PointerType {
public Display() { }
public Display(Pointer p) { super(p); }
}
/**
* X11 Window ID
*/
public static class Window extends NativeLong {
public Window() { }
public Window(long value) { super(value); }
}
/**
* X11 Event structure
*/
public static class XEvent extends Union {
public int type;
public XKeyEvent xkey;
public XButtonEvent xbutton;
public XMotionEvent xmotion;
// ... other event types
}Linux-specific system functions and interfaces not available on other Unix systems.
/**
* Linux udev device management
*/
public interface Udev extends Library {
Udev INSTANCE = Native.load("udev", Udev.class);
/**
* Create udev context
* @return udev context, or null if failed
*/
UdevContext udev_new();
/**
* Free udev context
* @param udev udev context to free
*/
void udev_unref(UdevContext udev);
/**
* Create device enumerator
* @param udev udev context
* @return device enumerator, or null if failed
*/
UdevEnumerate udev_enumerate_new(UdevContext udev);
/**
* Scan devices matching current filter
* @param enumerate device enumerator
* @return 0 if successful
*/
int udev_enumerate_scan_devices(UdevEnumerate enumerate);
/**
* Get list of device paths
* @param enumerate device enumerator
* @return linked list of device entries
*/
UdevListEntry udev_enumerate_get_list_entry(UdevEnumerate enumerate);
}/**
* Linux extended file attributes
*/
public interface XAttr extends Library {
XAttr INSTANCE = Native.load("c", XAttr.class);
/**
* Set extended attribute
* @param path File path
* @param name Attribute name
* @param value Attribute value
* @param size Value size
* @param flags Operation flags
* @return 0 if successful, -1 if failed
*/
int setxattr(String path, String name, Pointer value, NativeLong size, int flags);
/**
* Get extended attribute
* @param path File path
* @param name Attribute name
* @param value Buffer for attribute value
* @param size Buffer size
* @return Size of attribute value, or -1 if failed
*/
NativeLong getxattr(String path, String name, Pointer value, NativeLong size);
/**
* Remove extended attribute
* @param path File path
* @param name Attribute name to remove
* @return 0 if successful, -1 if failed
*/
int removexattr(String path, String name);
/**
* List extended attributes
* @param path File path
* @param list Buffer for attribute names
* @param size Buffer size
* @return Size of attribute list, or -1 if failed
*/
NativeLong listxattr(String path, Pointer list, NativeLong size);
}
/**
* Extended attribute utilities
*/
public class XAttrUtil {
/**
* Set string extended attribute
* @param path File path
* @param name Attribute name
* @param value String value to set
* @throws IOException if operation fails
*/
public static void setXAttr(String path, String name, String value) throws IOException;
/**
* Get string extended attribute
* @param path File path
* @param name Attribute name
* @return String value, or null if not found
* @throws IOException if operation fails
*/
public static String getXAttr(String path, String name) throws IOException;
/**
* List all extended attributes
* @param path File path
* @return Array of attribute names
* @throws IOException if operation fails
*/
public static String[] listXAttrs(String path) throws IOException;
}/**
* POSIX real-time extensions
*/
public interface LibRT extends Library {
LibRT INSTANCE = Native.load("rt", LibRT.class);
/**
* Create shared memory object
* @param name Shared memory name
* @param oflag Open flags
* @param mode Permission mode
* @return File descriptor, or -1 if failed
*/
int shm_open(String name, int oflag, int mode);
/**
* Remove shared memory object
* @param name Shared memory name to remove
* @return 0 if successful, -1 if failed
*/
int shm_unlink(String name);
/**
* Get current time with nanosecond precision
* @param clk_id Clock identifier
* @param tp Timespec structure to fill
* @return 0 if successful, -1 if failed
*/
int clock_gettime(int clk_id, TimeSpec tp);
/**
* Sleep for specified time with nanosecond precision
* @param req Requested sleep time
* @param rem Remaining time if interrupted
* @return 0 if successful, -1 if failed
*/
int nanosleep(TimeSpec req, TimeSpec rem);
}
/**
* Time specification structure
*/
public static class TimeSpec extends Structure {
public NativeLong tv_sec; // seconds
public NativeLong tv_nsec; // nanoseconds
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("tv_sec", "tv_nsec");
}
}/**
* Memory mapping operations
*/
public interface Mman extends Library {
Mman INSTANCE = Native.load("c", Mman.class);
// Memory protection flags
int PROT_READ = 0x1;
int PROT_WRITE = 0x2;
int PROT_EXEC = 0x4;
int PROT_NONE = 0x0;
// Memory mapping flags
int MAP_SHARED = 0x01;
int MAP_PRIVATE = 0x02;
int MAP_ANONYMOUS = 0x20;
/**
* Map memory
* @param addr Preferred address (can be null)
* @param len Length to map
* @param prot Protection flags
* @param flags Mapping flags
* @param fd File descriptor (-1 for anonymous)
* @param offset File offset
* @return Mapped address, or MAP_FAILED if failed
*/
Pointer mmap(Pointer addr, NativeLong len, int prot, int flags, int fd, NativeLong offset);
/**
* Unmap memory
* @param addr Address to unmap
* @param len Length to unmap
* @return 0 if successful, -1 if failed
*/
int munmap(Pointer addr, NativeLong len);
/**
* Change memory protection
* @param addr Address to change
* @param len Length to change
* @param prot New protection flags
* @return 0 if successful, -1 if failed
*/
int mprotect(Pointer addr, NativeLong len, int prot);
/**
* Synchronize memory mapping with file
* @param addr Address to sync
* @param len Length to sync
* @param flags Sync flags
* @return 0 if successful, -1 if failed
*/
int msync(Pointer addr, NativeLong len, int flags);
}/**
* AIX performance statistics
*/
public interface Perfstat extends Library {
Perfstat INSTANCE = Native.load("perfstat", Perfstat.class);
/**
* Get CPU statistics
* @param name CPU identifier (can be null for total)
* @param userbuff Buffer for CPU stats
* @param sizeof_userbuff Buffer size
* @param desired_number Number of entries requested
* @return Number of entries returned, or -1 if failed
*/
int perfstat_cpu_total(PerfstatId name, PerfstatCpuTotal userbuff,
int sizeof_userbuff, int desired_number);
/**
* Get memory statistics
* @param name Memory identifier (can be null for total)
* @param userbuff Buffer for memory stats
* @param sizeof_userbuff Buffer size
* @param desired_number Number of entries requested
* @return Number of entries returned, or -1 if failed
*/
int perfstat_memory_total(PerfstatId name, PerfstatMemoryTotal userbuff,
int sizeof_userbuff, int desired_number);
}/**
* Solaris kernel statistics
*/
public interface LibKstat extends Library {
LibKstat INSTANCE = Native.load("kstat", LibKstat.class);
/**
* Open kstat library
* @return kstat control structure, or null if failed
*/
KstatCtl kstat_open();
/**
* Close kstat library
* @param kc kstat control structure
* @return 0 if successful
*/
int kstat_close(KstatCtl kc);
/**
* Look up kstat by name
* @param kc kstat control structure
* @param module Module name (can be null)
* @param instance Instance number (-1 for any)
* @param name Statistic name (can be null)
* @return kstat structure, or null if not found
*/
Kstat kstat_lookup(KstatCtl kc, String module, int instance, String name);
/**
* Read kstat data
* @param kc kstat control structure
* @param ksp kstat structure
* @param buf Buffer to read into (can be null)
* @return 0 if successful, -1 if failed
*/
int kstat_read(KstatCtl kc, Kstat ksp, Pointer buf);
}/**
* High-level C library utilities
*/
public class LibCUtil {
/**
* Get last system error message
* @return Error message string
*/
public static String getLastErrorMessage();
/**
* Get current working directory
* @return Current directory path
* @throws IOException if operation fails
*/
public static String getCwd() throws IOException;
/**
* Change current working directory
* @param path New directory path
* @throws IOException if operation fails
*/
public static void chdir(String path) throws IOException;
/**
* Get environment variable
* @param name Variable name
* @return Variable value, or null if not found
*/
public static String getenv(String name);
/**
* Set environment variable
* @param name Variable name
* @param value Variable value
* @param overwrite Whether to overwrite existing value
* @throws IOException if operation fails
*/
public static void setenv(String name, String value, boolean overwrite) throws IOException;
}Usage Examples:
import com.sun.jna.platform.unix.X11;
import com.sun.jna.platform.unix.LibCUtil;
import com.sun.jna.platform.linux.XAttrUtil;
// X11 window creation
X11.Display display = X11.INSTANCE.XOpenDisplay(null);
if (display != null) {
X11.Window rootWindow = new X11.Window(1); // Root window is typically 1
X11.Window window = X11.INSTANCE.XCreateSimpleWindow(
display, rootWindow,
100, 100, // x, y
640, 480, // width, height
1, // border width
new NativeLong(0), // border color
new NativeLong(0) // background color
);
X11.INSTANCE.XMapWindow(display, window);
// Event loop would go here...
X11.INSTANCE.XDestroyWindow(display, window);
X11.INSTANCE.XCloseDisplay(display);
}
// Extended attributes (Linux)
try {
XAttrUtil.setXAttr("/tmp/testfile", "user.comment", "My test file");
String comment = XAttrUtil.getXAttr("/tmp/testfile", "user.comment");
System.out.println("File comment: " + comment);
} catch (IOException e) {
System.err.println("Extended attribute operation failed: " + e.getMessage());
}Advanced Linux system information gathering beyond basic POSIX functionality.
/**
* Linux-specific LibC extensions
*/
public interface LibC extends com.sun.jna.platform.unix.LibC {
LibC INSTANCE = Native.load("c", LibC.class);
/**
* Get system information (Linux-specific)
* @param info Structure to fill with system information
* @return 0 if successful, -1 if failed
*/
int sysinfo(Sysinfo info);
/**
* Get file system statistics
* @param path Path to file system
* @param statvfs Structure to fill with file system information
* @return 0 if successful, -1 if failed
*/
int statvfs(String path, Statvfs statvfs);
}
/**
* System information structure (Linux)
*/
public static class Sysinfo extends Structure {
public NativeLong uptime; // Seconds since boot
public NativeLong[] loads = new NativeLong[3]; // 1, 5, and 15 minute load averages
public NativeLong totalram; // Total usable main memory size
public NativeLong freeram; // Available memory size
public NativeLong sharedram; // Amount of shared memory
public NativeLong bufferram; // Memory used by buffers
public NativeLong totalswap; // Total swap space size
public NativeLong freeswap; // Available swap space
public short procs; // Number of current processes
public NativeLong totalhigh; // Total high memory size
public NativeLong freehigh; // Available high memory size
public int mem_unit; // Memory unit size in bytes
}
/**
* File system statistics structure
*/
public static class Statvfs extends Structure {
public NativeLong f_bsize; // File system block size
public NativeLong f_frsize; // Fragment size
public NativeLong f_blocks; // Size of file system in f_frsize units
public NativeLong f_bfree; // Number of free blocks
public NativeLong f_bavail; // Number of free blocks for unprivileged users
public NativeLong f_files; // Number of inodes
public NativeLong f_ffree; // Number of free inodes
public NativeLong f_favail; // Number of free inodes for unprivileged users
public NativeLong f_fsid; // File system ID
public NativeLong f_flag; // Mount flags
public NativeLong f_namemax; // Maximum filename length
}Comprehensive error code definitions for Linux system calls.
/**
* Linux errno constants
*/
public interface ErrNo {
int EPERM = 1; // Operation not permitted
int ENOENT = 2; // No such file or directory
int ESRCH = 3; // No such process
int EINTR = 4; // Interrupted system call
int EIO = 5; // Input/output error
int ENXIO = 6; // No such device or address
int E2BIG = 7; // Argument list too long
int ENOEXEC = 8; // Exec format error
int EBADF = 9; // Bad file descriptor
int ECHILD = 10; // No child processes
int EAGAIN = 11; // Resource temporarily unavailable
int ENOMEM = 12; // Cannot allocate memory
int EACCES = 13; // Permission denied
int EFAULT = 14; // Bad address
int ENOTBLK = 15; // Block device required
int EBUSY = 16; // Device or resource busy
int EEXIST = 17; // File exists
int EXDEV = 18; // Invalid cross-device link
int ENODEV = 19; // No such device
int ENOTDIR = 20; // Not a directory
int EISDIR = 21; // Is a directory
int EINVAL = 22; // Invalid argument
int ENFILE = 23; // Too many open files in system
int EMFILE = 24; // Too many open files
int ENOTTY = 25; // Inappropriate ioctl for device
int ETXTBSY = 26; // Text file busy
int EFBIG = 27; // File too large
int ENOSPC = 28; // No space left on device
int ESPIPE = 29; // Illegal seek
int EROFS = 30; // Read-only file system
int EMLINK = 31; // Too many links
int EPIPE = 32; // Broken pipe
int EDOM = 33; // Numerical argument out of domain
int ERANGE = 34; // Numerical result out of range
// ... many more error codes available
}System resource limit management and control.
/**
* Resource limit management
*/
public interface Resource extends Library {
Resource INSTANCE = Native.load("c", Resource.class);
// Resource limit constants
int RLIMIT_CPU = 0; // CPU time in seconds
int RLIMIT_FSIZE = 1; // Maximum file size
int RLIMIT_DATA = 2; // Data segment size
int RLIMIT_STACK = 3; // Stack size
int RLIMIT_CORE = 4; // Core file size
int RLIMIT_RSS = 5; // Resident set size
int RLIMIT_NPROC = 6; // Number of processes
int RLIMIT_NOFILE = 7; // Number of open files
int RLIMIT_MEMLOCK = 8; // Locked memory
int RLIMIT_AS = 9; // Address space size
/**
* Get resource limits
* @param resource Resource type (RLIMIT_*)
* @param rlim Structure to fill with current limits
* @return 0 if successful, -1 if failed
*/
int getrlimit(int resource, Rlimit rlim);
/**
* Set resource limits
* @param resource Resource type (RLIMIT_*)
* @param rlim New resource limits
* @return 0 if successful, -1 if failed
*/
int setrlimit(int resource, Rlimit rlim);
}
/**
* Resource limit structure
*/
public static class Rlimit extends Structure {
public NativeLong rlim_cur; // Current (soft) limit
public NativeLong rlim_max; // Maximum (hard) limit
}BSD-specific functionality including extended attributes support.
/**
* BSD extended attributes interface
*/
public interface ExtAttr extends Library {
ExtAttr INSTANCE = Native.load("c", ExtAttr.class);
// Namespace constants
int EXTATTR_NAMESPACE_USER = 1;
int EXTATTR_NAMESPACE_SYSTEM = 2;
/**
* Get extended attribute value
* @param path File path
* @param attrnamespace Attribute namespace
* @param attrname Attribute name
* @param data Buffer to store attribute value
* @param nbytes Buffer size
* @return Number of bytes retrieved, or -1 if failed
*/
NativeLong extattr_get_file(String path, int attrnamespace, String attrname,
Pointer data, NativeLong nbytes);
/**
* Set extended attribute value
* @param path File path
* @param attrnamespace Attribute namespace
* @param attrname Attribute name
* @param data Attribute value data
* @param nbytes Size of attribute value
* @return Number of bytes stored, or -1 if failed
*/
NativeLong extattr_set_file(String path, int attrnamespace, String attrname,
Pointer data, NativeLong nbytes);
/**
* Delete extended attribute
* @param path File path
* @param attrnamespace Attribute namespace
* @param attrname Attribute name
* @return 0 if successful, -1 if failed
*/
int extattr_delete_file(String path, int attrnamespace, String attrname);
/**
* List extended attributes
* @param path File path
* @param attrnamespace Attribute namespace
* @param data Buffer to store attribute list
* @param nbytes Buffer size
* @return Number of bytes retrieved, or -1 if failed
*/
NativeLong extattr_list_file(String path, int attrnamespace,
Pointer data, NativeLong nbytes);
}
/**
* High-level BSD extended attributes utilities
*/
public class ExtAttrUtil {
/**
* List all extended attributes for a file
* @param path File path
* @param namespace Attribute namespace
* @return List of attribute names
* @throws IOException if operation fails
*/
public static List<String> list(String path, int namespace) throws IOException;
/**
* Get extended attribute value as string
* @param path File path
* @param namespace Attribute namespace
* @param name Attribute name
* @return Attribute value, or null if not found
* @throws IOException if operation fails
*/
public static String get(String path, int namespace, String name) throws IOException;
/**
* Set extended attribute value from string
* @param path File path
* @param namespace Attribute namespace
* @param name Attribute name
* @param value Attribute value
* @throws IOException if operation fails
*/
public static void set(String path, int namespace, String name, String value) throws IOException;
/**
* Delete extended attribute
* @param path File path
* @param namespace Attribute namespace
* @param name Attribute name
* @throws IOException if operation fails
*/
public static void delete(String path, int namespace, String name) throws IOException;
}System reboot and shutdown control functionality.
/**
* System control interface for reboot/shutdown operations
*/
public interface Reboot extends Library {
Reboot INSTANCE = Native.load("c", Reboot.class);
// Reboot command constants
int RB_AUTOBOOT = 0x01234567; // Restart system
int RB_HALT_SYSTEM = 0xcdef0123; // Halt system
int RB_ENABLE_CAD = 0x89abcdef; // Enable Ctrl-Alt-Del
int RB_DISABLE_CAD = 0x00000000; // Disable Ctrl-Alt-Del
int RB_POWER_OFF = 0x4321fedc; // Power off system
int RB_SW_SUSPEND = 0xd000fce2; // Suspend system
int RB_KEXEC = 0x45584543; // Restart with kexec
/**
* Reboot or control system
* @param cmd Reboot command (RB_*)
* @return 0 if successful, -1 if failed
*/
int reboot(int cmd);
}Beyond the basic examples, AIX Perfstat provides comprehensive system statistics including CPU, memory, disk, network, and partition information.
Solaris 11.4+ includes the modern Kstat2 API for system statistics, providing improved performance and functionality over the legacy Kstat interface.
// Linux system information
LibC.Sysinfo sysinfo = new LibC.Sysinfo();
if (LibC.INSTANCE.sysinfo(sysinfo) == 0) {
System.out.println("Uptime: " + sysinfo.uptime + " seconds");
System.out.println("Total RAM: " + sysinfo.totalram.longValue() * sysinfo.mem_unit + " bytes");
System.out.println("Free RAM: " + sysinfo.freeram.longValue() * sysinfo.mem_unit + " bytes");
}
// BSD extended attributes
try {
ExtAttrUtil.set("/tmp/testfile", ExtAttr.EXTATTR_NAMESPACE_USER, "comment", "My test file");
String comment = ExtAttrUtil.get("/tmp/testfile", ExtAttr.EXTATTR_NAMESPACE_USER, "comment");
System.out.println("File comment: " + comment);
} catch (IOException e) {
System.err.println("Extended attribute operation failed: " + e.getMessage());
}
// Resource limits
Resource.Rlimit limits = new Resource.Rlimit();
if (Resource.INSTANCE.getrlimit(Resource.RLIMIT_NOFILE, limits) == 0) {
System.out.println("Current file descriptor limit: " + limits.rlim_cur);
System.out.println("Maximum file descriptor limit: " + limits.rlim_max);
}Install with Tessl CLI
npx tessl i tessl/maven-net-java-dev-jna--jna-platform