It’s that time of the year again: Java Advent is back and this year we’re going outside the JVM. In previous years, we’ve generated Java bytecode, first with ProGuardCORE and then with the new Class-File API; then in 2025 we showed how to use the new FFM API to call out to LLVM to print “Hello, World!” via LLVM IR. This year, the task is simple: write a program to print “Hello, World!”. But our final program won’t use System.out.println, and no LLVM this time; instead we’ll directly write x86-64 machine instructions and use the FFM API to execute them.
What is machine code?
The x86-64 instruction set contains the instructions that Intel and AMD CPUs understand: things like moving a value into a register, adding two numbers or calling a function. Each instruction is encoded as a few bytes, and assembly is the readable version, so instead of B8 2A 00 00 00 we can write mov eax, 42. An assembler turns the text into bytes, and those bytes are the machine code that the CPU runs.
To follow along, you’ll need:
- an x86-64 machine: other CPUs, such as the ARM chips in Apple Silicon Macs, have their own instructions and encodings
- Linux, since our program asks the operating system to print the message, and each operating system handles that differently
- JDK 22 or newer
x86-64 assembly
There are two common ways of writing x86-64 assembly, AT&T syntax and Intel syntax. We’ll use Intel syntax, which puts the destination first (mov eax, 1 puts 1 into eax), and assemble it with the GNU assembler.
The x86-64 assembly for our “Hello, World!” looks like this:
.intel_syntax noprefix
.global _start
_start:
mov eax, 1 # system call 1: write
mov edi, 1 # to stdout
lea rsi, [rip + message] # the message
mov edx, 14 # 14 bytes long
syscall
mov eax, 60 # system call 60: exit
xor edi, edi # with status 0
syscall
message:
.ascii "Hello, World!\n"
Eventually, we’ll run instructions like these from Java but, for now, if you save this in a file called hello.s you can assemble it with as, link it with ld and run it:
$ as hello.s -o hello.o
$ ld hello.o -o hello
$ ./hello
Hello, World!
$ echo $?
0
There are a few parts to the hello.s example:
- Directives that tell the assembler to use Intel syntax and make
_start, where the program starts, visible to the linker - A
writesystem call that prints the message to stdout (file descriptor 1) - An
exitsystem call that ends the program with status 0 - The “Hello, World!\n” message itself, placed after the code
We’ll learn more about x86-64 soon, but first we need to see how we can execute such instructions directly from Java via the FFM API.
What is the Java FFM API?
The Foreign Function & Memory (FFM) API enables Java programs to interoperate with code and data outside the Java Virtual Machine. It replaces the older JNI as a safer way for Java programs to call native code and became final in Java 22 with JEP 454.
Much of the “safer” part comes from how the API models memory: each memory segment has a size and a lifetime, and the FFM API checks every access against them. Reading past the end of a segment, or using its memory after it’s been freed, throws an exception instead of crashing the JVM.
Some operations can’t be checked, though: for example, when we call a native function the FFM API has to trust our description of its parameters and return type. These operations are restricted methods, and calling one prints a warning unless you run Java with the --enable-native-access flag. We’ll use a few restricted methods in this post.
In the 2025 Java Advent, we used jextract to generate Java bindings for the whole LLVM C API. This time we only need a few system calls which we’ll call through their C library wrappers, so we’ll create the bindings ourselves.
A Linker creates downcall handles: method handles that call a native function, with a FunctionDescriptor describing its parameters and return type. As we’ll see, a downcall handle can call any address in memory, including the code that we’ll put there ourselves.
Running our first bytes
Before we print “Hello, World!”, let’s start with something simpler that requires only two x86-64 instructions: we’ll use mov and ret to put the constant 42 into a register and return it back to Java land.
A register is a small storage slot inside the CPU, a bit like a local variable. In x86-64 CPUs the registers are 64 bits wide, with names like rax, and smaller parts of each register have names of their own: eax is the low 32 bits of rax, ax the low 16 and al the low 8. An int fits in eax. Writing to eax also clears the top 32 bits of rax, so for small values like 42 we can use the shorter eax form. In assembly, our code looks like this:
mov eax, 42
ret
Which we can encode as bytes in a Java byte array as follows:
public class HelloWorld {
public static void main(String[] args) throws Throwable {
byte[] bytes = {
(byte) 0xB8, 42, 0, 0, 0, // mov eax, 42
(byte) 0xC3, // ret
};
}
}
We can’t run the byte array where it is, since Java’s heap memory isn’t executable. Instead, we’ll ask the operating system for a page of memory and copy our bytes into it. To allocate the page, we can use the mmap system call via its libc wrapper. We find mmap’s address with defaultLookup() and ask the Linker for a downcall handle to it. The Linker also needs a FunctionDescriptor describing the signature which lists the return type followed by the type of each parameter, using ValueLayouts such as ADDRESS for pointers, JAVA_LONG for 64-bit numbers and JAVA_INT for 32-bit ones.
Once we have the handle we can call the mmap function with the following parameters:
- the address:
MemorySegment.NULL, which means the kernel will choose the address for us - the length: the size of the instruction byte array
- the protection:
PROT_READ | PROT_WRITE(readable and writable) - the flags:
MAP_PRIVATE | MAP_ANONYMOUS: memory just for our process, and not backed by a file - the file descriptor:
-1, because there’s no file - the offset:
0L
Notice that we’re asking for memory that is readable and writable, but not executable: first we’ll write our bytes, then we’ll make it executable.
import java.lang.foreign.*;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = {
(byte) 0xB8, 42, 0, 0, 0, // mov eax, 42
(byte) 0xC3, // ret
};
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
// A new page of memory, readable and writable, holding our bytes.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size);
page.copyFrom(MemorySegment.ofArray(bytes));
}
}
The mmap function returns the memory address of our new page but we get back a zero-length MemorySegment, since an address only says where the memory starts, not how big it is. Memory segments are bounds-checked, so without a size the FFM API doesn’t let us access that memory.
We can use reinterpret to give the segment our known size (the instruction byte array length) and then copyFrom to copy our bytes into the page. reinterpret is a restricted method, because the FFM API has to trust that the size we give it is right.
If you don’t set the size of the memory segment then copying our bytes into it fails with an exception:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
Exception in thread "main" java.lang.IndexOutOfBoundsException: Out of bound access on segment MemorySegment{ kind: native, address: 0x775aaa875000, byteSize: 0 }; attempting to access an element of length 6 at offset 0 which is outside the valid range 0 <= offset+length < byteSize (=0)
at java.base/jdk.internal.foreign.AbstractMemorySegmentImpl.throwOutOfBounds(AbstractMemorySegmentImpl.java:435)
at java.base/jdk.internal.foreign.AbstractMemorySegmentImpl.checkAccessBounds(AbstractMemorySegmentImpl.java:415)
at java.base/jdk.internal.foreign.AbstractMemorySegmentImpl.checkAccess(AbstractMemorySegmentImpl.java:358)
at java.base/jdk.internal.foreign.SegmentBulkOperations.copy(SegmentBulkOperations.java:113)
at java.base/java.lang.foreign.MemorySegment.copy(MemorySegment.java:1592)
at java.base/jdk.internal.foreign.AbstractMemorySegmentImpl.copyFrom(AbstractMemorySegmentImpl.java:270)
at HelloWorld.main(HelloWorld.java:26)
Now that our bytes are in memory we need to execute them via a downcall handle that we get from the Linker with the address of our page. To the CPU, a function is just a sequence of instructions at some address: there’s no name, no list of parameters and no return type. A name like mmap only helps us find the address, which is what defaultLookup() did for us earlier, but here we already have the address of our page.
On the Java side we need to describe our function using a FunctionDescriptor: FunctionDescriptor.of(JAVA_INT) describes a function that takes no parameters and returns an int, which matches our mov eax, 42; ret. On Linux x86-64, a function returns an int in eax, so that’s where Java will look for it. We can call it with invokeExact and print the result:
import java.lang.foreign.*;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = {
(byte) 0xB8, 42, 0, 0, 0, // mov eax, 42
(byte) 0xC3, // ret
};
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
// A new page of memory, readable and writable, holding our bytes.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size);
page.copyFrom(MemorySegment.ofArray(bytes));
var function = linker.downcallHandle(page,
FunctionDescriptor.of(JAVA_INT));
int result = (int) function.invokeExact();
System.out.println(result);
}
}
But remember, the memory is not yet marked executable and here’s what happens if we try to execute our bytes now:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007153645df000, pid=543931, tid=543932
#
# JRE version: OpenJDK Runtime Environment (26.0.2+10) (build 26.0.2+10-55)
# Java VM: OpenJDK 64-Bit Server VM (26.0.2+10-55, mixed mode, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, linux-amd64)
# Problematic frame:
# C 0x00007153645df000
#
# Core dump will be written. Default location: Determined by the following: "/usr/share/apport/apport -p%p -s%s -c%c -d%d -P%P -u%u -g%g -F%F -- %E" (alternatively, falling back to core.543931)
#
# An error report file with more information is saved as:
# hs_err_pid543931.log
[0.436s][warning][os] Loading hsdis library failed
#
# If you would like to submit a bug report, please visit:
# https://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
This isn’t an exception we can catch: the whole JVM has crashed. The CPU refused to run our bytes because the page isn’t executable, and the “problematic frame” address is the start of our page.
Making the page executable
We could ask mmap for executable memory straight away, but then the page would be writable at the same time as our code can run. If a bug, or an attacker, wrote to that memory, our code could be replaced at any point during its lifetime. Instead, we’ll only make the page executable once we’ve finished writing our bytes, so the page is only writable for that short time. Keeping memory writable or executable, but never both at once, is a common security rule known as W^X (write xor execute).
We’ll use mprotect to change the page to readable and executable once our bytes are in, calling it through a downcall handle just like mmap.
import java.lang.foreign.*;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = {
(byte) 0xB8, 42, 0, 0, 0, // mov eax, 42
(byte) 0xC3, // ret
};
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
// A new page of memory, readable and writable, holding our bytes.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size);
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable: never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(JAVA_INT));
int result = (int) function.invokeExact();
System.out.println(result);
}
}
Now we can finally execute some real x86-64 instructions from Java via the FFM API:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
42
Cleaning up
Since we’re allocating memory, we should also clean up after ourselves by unmapping the page with munmap when we’re done with it. With the FFM API, we can tie the memory page’s lifetime to an Arena: when the arena is closed, it runs a given cleanup action, and we can have that action call munmap.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = {
(byte) 0xB8, 42, 0, 0, 0, // mov eax, 42
(byte) 0xC3, // ret
};
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(JAVA_INT));
int result = (int) function.invokeExact();
System.out.println(result);
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
}
If you run the program again, you’ll see the same output as before:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
42
A tiny assembler
Before we move on to “Hello, World!”, let’s make building sequences of machine instructions easier with a small assembler, so that we can write mov(EAX, 42) instead of working out the bytes B8 2A 00 00 00 ourselves. Instructions refer to registers by number: B8 is mov into register 0, which is eax. We’ll model registers with a simple Register record that holds both the register number and the size in bits, and declare constants for the ones we’ll need.
import java.io.ByteArrayOutputStream;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = new Code()
.mov(EAX, 42)
.ret()
.bytes();
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(JAVA_INT));
int result = (int) function.invokeExact();
System.out.println(result);
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
// Instructions refer to registers by number, each with a 32-bit and a
// 64-bit name: for example, EAX is the low 32 bits of register 0, RAX
// all 64. A prefix byte selects 64 bits.
record Register(int id, int bits) {}
static final Register EAX = new Register(0, 32), RAX = new Register(0, 64);
static final Register EDX = new Register(2, 32), RSI = new Register(6, 64);
static final Register EDI = new Register(7, 32);
// A tiny x86-64 assembler: one method per instruction,
// each appending the instruction's bytes.
static class Code {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
void emit(int... bytes) {
for (int b : bytes) out.write(b);
}
void emitInt(int value) { // 4 bytes, least significant first
emit(value, value >> 8, value >> 16, value >> 24);
}
Code mov(Register dst, int value) { // mov r32, imm32
if (dst.bits() != 32) {
throw new UnsupportedOperationException(
"mov only supports 32-bit registers");
}
emit(0xB8 + dst.id()); // opcode: mov, plus the register number
emitInt(value); // the value, 4 bytes
return this;
}
Code ret() {
emit(0xC3); // opcode: ret
return this;
}
byte[] bytes() {
return out.toByteArray();
}
}
}
Double-check that everything still works:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
42
We’re now ready to move on to the main goal: printing “Hello, World!”.
Hello World from Java
To print “Hello, World!” we need to:
- Store the constant string “Hello, World!” somewhere
- Call the
writesystem call with the correct parameters
To do this, we’ll use two further x86-64 instructions on top of the mov and ret that we’ve already seen:
lea(load effective address): puts the address of the message into a register, sowriteknows where to find itsyscall: hands control to the Linux kernel, which runs the system call whose number is inrax
And we’ll also place the raw bytes of the string “Hello, World!\n” just after the code, where lea can find it by its distance from the lea instruction.
Executing system calls
To write “Hello, World!” we’ll need to execute a system call but before we do that, let’s look at a simpler system call: getpid, which returns the current process ID.
Whether we call a function or make a system call, its inputs and its result have to go somewhere: a calling convention is a set of rules for where a call’s inputs go and where its result comes back. System calls on Linux have their own, which you can find in the syscall man page:
- the system call number goes in
rax - the arguments go in
rdi,rsi,rdx,r10,r8andr9, in that order - the result comes back in
rax
So to call getpid, we put system call number 39 in rax, and the kernel puts the process ID back in rax, where the FFM API picks it up as our function’s int return value.
import java.io.ByteArrayOutputStream;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
byte[] bytes = new Code()
.mov(EAX, 39) // system call 39: getpid
.syscall()
.ret() // back to Java, with the result in rax
.bytes();
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(JAVA_INT));
int result = (int) function.invokeExact();
System.out.println(result);
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
// Instructions refer to registers by number, each with a 32-bit and a
// 64-bit name: for example, EAX is the low 32 bits of register 0, RAX
// all 64. A prefix byte selects 64 bits.
record Register(int id, int bits) {}
static final Register EAX = new Register(0, 32), RAX = new Register(0, 64);
static final Register EDX = new Register(2, 32), RSI = new Register(6, 64);
static final Register EDI = new Register(7, 32);
// A tiny x86-64 assembler: one method per instruction,
// each appending the instruction's bytes.
static class Code {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
void emit(int... bytes) {
for (int b : bytes) out.write(b);
}
void emitInt(int value) { // 4 bytes, least significant first
emit(value, value >> 8, value >> 16, value >> 24);
}
Code mov(Register dst, int value) { // mov r32, imm32
if (dst.bits() != 32) {
throw new UnsupportedOperationException(
"mov only supports 32-bit registers");
}
emit(0xB8 + dst.id()); // opcode: mov, plus the register number
emitInt(value); // the value, 4 bytes
return this;
}
Code syscall() {
emit(0x0F, 0x05); // opcode: syscall (2 bytes)
return this;
}
Code ret() {
emit(0xC3); // opcode: ret
return this;
}
byte[] bytes() {
return out.toByteArray();
}
}
}
If you run this in the background with &, the shell prints the process ID of the program it started, and you’ll see our syscall returns the same number:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java &
[1] 963329
963329
Finding the message with lea
Now that we’ve seen how we’ll execute a system call, let’s see how we can store a string and refer to it with a relative address using lea. We don’t know where mmap will put our page, so we can’t use the message’s address directly; instead, lea works it out from how far the message is from the lea instruction itself. So before we get around to printing the string, let’s just return that address to Java, in rax, and see what it is.
We load the address relative to rip, the instruction pointer: a register where the CPU keeps the address of the next instruction to run. Here’s what our page will look like, with the offset of each instruction from the start of the page, its bytes, and the instruction they encode:
offset bytes instruction
0 48 8D 05 01 00 00 00 lea rax, [rip + 1]
^ ^ ^ ^^^^^^^^^^^
| | | distance: 1, least significant byte first
| | ModR/M: mod 00, reg 000 (rax), rm 101 (rip + distance)
| opcode: lea
REX_W prefix: use all 64 bits of the register
7 C3 ret <- rip points here
while lea runs
8 48 65 6C 6C 6F 2C ... "Hello, World!\n" <- rip + 1: the message
The lea instruction takes up the first 7 bytes, so when it is the currently executing instruction, rip holds the address of offset 7, the ret. Adding 1 gives offset 8, where our message starts.
The 48 prefix (REX_W) tells the CPU to use all 64 bits of rax: an address doesn’t fit in 32 bits, and without it this would be lea eax.
The ModR/M byte packs three fields into 8 bits: 05 is 00 000 101 in binary. The middle 3 bits (reg) hold the register we’re loading into (000, rax), and the outer bits, 00 and 101, are a special combination meaning “rip plus the distance that follows” (the distance is commonly referred to as the displacement).
The code now returns an address, so the Java side gets a zero-length MemorySegment which we can reinterpret with the correct length to read the string and print it from Java.
import java.io.ByteArrayOutputStream;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
var message = "Hello, World!\n";
int length = message.getBytes(StandardCharsets.UTF_8).length;
byte[] bytes = new Code()
.lea(RAX, 1) // the message, 1 byte after this instruction
.ret() // back to Java, with the address in rax
.string(message)
.bytes();
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(ADDRESS));
var address = (MemorySegment) function.invokeExact();
byte[] text = address.reinterpret(length).toArray(JAVA_BYTE);
System.out.print(new String(text, StandardCharsets.UTF_8));
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
// Instructions refer to registers by number, each with a 32-bit and a
// 64-bit name: for example, EAX is the low 32 bits of register 0, RAX
// all 64. A prefix byte selects 64 bits.
record Register(int id, int bits) {}
static final Register EAX = new Register(0, 32), RAX = new Register(0, 64);
static final Register EDX = new Register(2, 32), RSI = new Register(6, 64);
static final Register EDI = new Register(7, 32);
// A tiny x86-64 assembler: one method per instruction,
// each appending the instruction's bytes.
static class Code {
// prefix: the instruction uses 64-bit registers
static final int REX_W = 0x48;
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
void emit(int... bytes) {
for (int b : bytes) out.write(b);
}
void emitInt(int value) { // 4 bytes, least significant first
emit(value, value >> 8, value >> 16, value >> 24);
}
Code mov(Register dst, int value) { // mov r32, imm32
if (dst.bits() != 32) {
throw new UnsupportedOperationException(
"mov only supports 32-bit registers");
}
emit(0xB8 + dst.id()); // opcode: mov, plus the register number
emitInt(value); // the value, 4 bytes
return this;
}
Code lea(Register dst, int distance) { // lea dst, [rip + distance]
if (dst.bits() == 64) emit(REX_W); // prefix: use all 64 bits of dst
emit(0x8D); // opcode: lea
// ModR/M: mod 00, reg = dst, rm 101 (with mod 00: rip + distance)
emit(0b00_000_101 | dst.id() << 3);
emitInt(distance); // the distance, 4 bytes
return this;
}
Code syscall() {
emit(0x0F, 0x05); // opcode: syscall (2 bytes)
return this;
}
Code string(String text) {
out.writeBytes(text.getBytes(StandardCharsets.UTF_8));
return this;
}
Code ret() {
emit(0xC3); // opcode: ret
return this;
}
byte[] bytes() {
return out.toByteArray();
}
}
}
If you run this, you’ll see the string from native memory printed by Java.
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
Hello, World!
Counting the distance by hand works in a small example like this but any change to the instructions between the lea and the message means counting again. Instead, we can give the message a label and let the assembler work out the distance for us.
We’ll add a label pseudo-instruction, which emits nothing but records the current position under that label. Since lea might refer to a label that comes later, the assembler doesn’t always know the distance yet, so it always writes placeholder bytes and records a fixup: where the placeholder is, how big it is, and where the instruction ends. Then, when we create the final byte array in bytes(), every label’s position is known, so we can fill in each placeholder with the distance from the end of the instruction to its label.
import java.io.ByteArrayOutputStream;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
var message = "Hello, World!\n";
int length = message.getBytes(StandardCharsets.UTF_8).length;
byte[] bytes = new Code()
.lea(RAX, "message") // the message
.ret() // back to Java, with the address in rax
.label("message")
.string(message)
.bytes();
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.of(ADDRESS));
var address = (MemorySegment) function.invokeExact();
byte[] text = address.reinterpret(length).toArray(JAVA_BYTE);
System.out.print(new String(text, StandardCharsets.UTF_8));
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
// Instructions refer to registers by number, each with a 32-bit and a
// 64-bit name: for example, EAX is the low 32 bits of register 0, RAX
// all 64. A prefix byte selects 64 bits.
record Register(int id, int bits) {}
static final Register EAX = new Register(0, 32), RAX = new Register(0, 64);
static final Register EDX = new Register(2, 32), RSI = new Register(6, 64);
static final Register EDI = new Register(7, 32);
// A tiny x86-64 assembler: one method per instruction,
// each appending the instruction's bytes.
static class Code {
// prefix: the instruction uses 64-bit registers
static final int REX_W = 0x48;
// at: where the placeholder is; size: its length in bytes;
// end: where the instruction ends (rip points there)
record Fixup(String label, int at, int size, int end) {}
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
// label -> its offset
private final Map<String, Integer> labels = new HashMap<>();
// distances to fill in once all labels are known
private final List<Fixup> fixups = new ArrayList<>();
void emit(int... bytes) {
for (int b : bytes) out.write(b);
}
void emitInt(int value) { // 4 bytes, least significant first
emit(value, value >> 8, value >> 16, value >> 24);
}
Code mov(Register dst, int value) { // mov r32, imm32
if (dst.bits() != 32) {
throw new UnsupportedOperationException(
"mov only supports 32-bit registers");
}
emit(0xB8 + dst.id()); // opcode: mov, plus the register number
emitInt(value); // the value, 4 bytes
return this;
}
Code lea(Register dst, String label) { // lea dst, [rip + label]
if (dst.bits() == 64) emit(REX_W); // prefix: use all 64 bits of dst
emit(0x8D); // opcode: lea
// ModR/M: mod 00, reg = dst, rm 101 (with mod 00: rip + distance)
emit(0b00_000_101 | dst.id() << 3);
int at = out.size(), size = Integer.BYTES;
// placeholder for the distance, filled in by bytes()
out.writeBytes(new byte[size]);
fixups.add(new Fixup(label, at, size, out.size()));
return this;
}
Code syscall() {
emit(0x0F, 0x05); // opcode: syscall (2 bytes)
return this;
}
Code label(String name) {
labels.put(name, out.size());
return this;
}
Code string(String text) {
out.writeBytes(text.getBytes(StandardCharsets.UTF_8));
return this;
}
Code ret() {
emit(0xC3); // opcode: ret
return this;
}
byte[] bytes() {
byte[] code = out.toByteArray();
for (var f : fixups) {
// rip points at the end of the instruction
int distance = labels.get(f.label()) - f.end();
for (int i = 0; i < f.size(); i++) {
code[f.at() + i] = (byte) (distance >> (8 * i));
}
}
return code;
}
}
}
If you run the program now, you’ll already see “Hello, World!”:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
Hello, World!
But we’re not done yet! The goal was to print directly from the native code using a system call rather than print using Java’s System.out.println.
Let’s see how we can put all that together next…
Hello, World!
So we’ve seen how to call system calls, using the system calling convention. We’ve also seen how to embed the message as data in the native code and refer to it using relative addressing. And we’ve built an assembler that makes it easy to do.
So the only thing we need to do now is build the correct instruction sequence to call write with the destination (stdout, which Linux numbers as file descriptor 1, the same place System.out prints to), the message’s address and its length.
import java.io.ByteArrayOutputStream;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.foreign.ValueLayout.*;
public class HelloWorld {
static final int PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4;
static final int MAP_PRIVATE = 0x02, MAP_ANONYMOUS = 0x20;
public static void main(String[] args) throws Throwable {
var message = "Hello, World!\n";
int length = message.getBytes(StandardCharsets.UTF_8).length;
byte[] bytes = new Code()
.mov(EAX, 1) // system call 1: write
.mov(EDI, 1) // to stdout
.lea(RSI, "message") // the message
.mov(EDX, length) // its length in bytes
.syscall()
.ret() // back to Java
.label("message")
.string(message)
.bytes();
var linker = Linker.nativeLinker();
var libc = linker.defaultLookup();
var mmap = linker.downcallHandle(
libc.find("mmap").orElseThrow(),
FunctionDescriptor.of(ADDRESS,
ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_LONG));
var mprotect = linker.downcallHandle(
libc.find("mprotect").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT));
var munmap = linker.downcallHandle(
libc.find("munmap").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG));
try (var arena = Arena.ofConfined()) {
// A new page of memory, readable and writable, holding our bytes.
// The page is unmapped when the arena is closed.
long size = bytes.length;
var page = ((MemorySegment) mmap.invokeExact(
MemorySegment.NULL, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L))
.reinterpret(size, arena,
segment -> unmap(munmap, segment, size));
page.copyFrom(MemorySegment.ofArray(bytes));
// Then readable and executable:
// never writable and executable at once.
if ((int) mprotect.invokeExact(page, size,
PROT_READ | PROT_EXEC) != 0) {
throw new RuntimeException("mprotect failed");
}
var function = linker.downcallHandle(page,
FunctionDescriptor.ofVoid());
function.invokeExact();
}
}
static void unmap(MethodHandle munmap, MemorySegment page, long size) {
int result;
try {
result = (int) munmap.invokeExact(page, size);
} catch (Throwable t) {
throw new RuntimeException(t);
}
if (result != 0) {
throw new RuntimeException("munmap failed");
}
}
// Instructions refer to registers by number, each with a 32-bit and a
// 64-bit name: for example, EAX is the low 32 bits of register 0, RAX
// all 64. A prefix byte selects 64 bits.
record Register(int id, int bits) {}
static final Register EAX = new Register(0, 32), RAX = new Register(0, 64);
static final Register EDX = new Register(2, 32), RSI = new Register(6, 64);
static final Register EDI = new Register(7, 32);
// A tiny x86-64 assembler: one method per instruction,
// each appending the instruction's bytes.
static class Code {
// prefix: the instruction uses 64-bit registers
static final int REX_W = 0x48;
// at: where the placeholder is; size: its length in bytes;
// end: where the instruction ends (rip points there)
record Fixup(String label, int at, int size, int end) {}
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
// label -> its offset
private final Map<String, Integer> labels = new HashMap<>();
// distances to fill in once all labels are known
private final List<Fixup> fixups = new ArrayList<>();
void emit(int... bytes) {
for (int b : bytes) out.write(b);
}
void emitInt(int value) { // 4 bytes, least significant first
emit(value, value >> 8, value >> 16, value >> 24);
}
Code mov(Register dst, int value) { // mov r32, imm32
if (dst.bits() != 32) {
throw new UnsupportedOperationException(
"mov only supports 32-bit registers");
}
emit(0xB8 + dst.id()); // opcode: mov, plus the register number
emitInt(value); // the value, 4 bytes
return this;
}
Code lea(Register dst, String label) { // lea dst, [rip + label]
if (dst.bits() == 64) emit(REX_W); // prefix: use all 64 bits of dst
emit(0x8D); // opcode: lea
// ModR/M: mod 00, reg = dst, rm 101 (with mod 00: rip + distance)
emit(0b00_000_101 | dst.id() << 3);
int at = out.size(), size = Integer.BYTES;
// placeholder for the distance, filled in by bytes()
out.writeBytes(new byte[size]);
fixups.add(new Fixup(label, at, size, out.size()));
return this;
}
Code syscall() {
emit(0x0F, 0x05); // opcode: syscall (2 bytes)
return this;
}
Code label(String name) {
labels.put(name, out.size());
return this;
}
Code string(String text) {
out.writeBytes(text.getBytes(StandardCharsets.UTF_8));
return this;
}
Code ret() {
emit(0xC3); // opcode: ret
return this;
}
byte[] bytes() {
byte[] code = out.toByteArray();
for (var f : fixups) {
// rip points at the end of the instruction
int distance = labels.get(f.label()) - f.end();
for (int i = 0; i < f.size(); i++) {
code[f.at() + i] = (byte) (distance >> (8 * i));
}
}
return code;
}
}
}
If everything is correct, then you should be able to run the program and see “Hello, World!”:
$ java --enable-native-access=ALL-UNNAMED HelloWorld.java
Hello, World!
Next steps
In this post, we ran our own x86-64 machine code from Java: no JNI, no C code and, unlike last year’s Java Advent post, no LLVM. We wrote the bytes for Hello World ourselves, copied them into memory from mmap, made it executable with mprotect, and called them with a downcall handle. Along the way, we built a tiny assembler that turns instructions into bytes.
We’ve only just scratched the surface of x86-64. Hello World used four instructions, four of the 16 general-purpose registers and one way of addressing memory, out of an instruction set whose Intel manual runs to thousands of pages. Try adding a few more instructions to Code, such as add or jmp, and see how the encodings grow from there.
To check your encodings against a real assembler, write the same instructions in a .s file, assemble it with as and look at the bytes with objdump. To see how a compiler uses x86-64 instructions, compile some C with gcc -S -masm=intel to get its assembly, or try it online in Compiler Explorer.
For a follow-up project, take a look at the small compiler from My First Compiler (also updated for the Class-File API) and see if you can replace its Java bytecode backend with an x86-64 one, using the assembler from this post.
The full code for this post can be found on GitHub here.
