Sub topic 12
Reading errno safely after a call
This chapter assumes you can write a downcall handle with Linker, SymbolLookup and FunctionDescriptor, and that you know what a C errno value is. The code targets Java 22, where allocateUtf8String and getUtf8String are the method names. Java 23 and later call them allocateFrom and getString.
Why errno is a problem
Many C functions report failure in two parts. The return value says that something went wrong, for example -1 or a null pointer. A thread-local integer named errno says why, for example ENOENT for "no such file or directory".
The obvious approach is to call the C function and then read errno from Java. That approach is unreliable. Between the native call returning and your next Java statement, the JVM may run code that makes its own native calls. Examples are a garbage collection, a thread state transition, class loading, or a safepoint. Any of these can overwrite errno. You would then read a value that has nothing to do with your call.
On some platforms errno is also not a variable you can look up. With glibc, errno is a macro that expands to a call of __errno_location(). A SymbolLookup for the name errno finds nothing.
The FFM API fixes this at the source. You ask the linker to save the error state inside the native call stub, before control returns to ordinary Java code. You then read the saved copy at your own pace.
The capture-call-state option
You request the saving with Linker.Option.captureCallState(String...). You pass it the names of the values to capture. The name set depends on the platform.
| Platform | Capturable names |
|---|---|
| Linux, macOS | `errno` |
| Windows | `GetLastError`, `WSAGetLastError`, `errno` |
Passing a name the platform does not support throws an IllegalArgumentException when you create the handle. On Windows, GetLastError is the value you normally want for Win32 API calls. errno there applies to the C runtime functions.
Three pieces work together:
Linker.Option.captureCallState("errno")is passed todowncallHandle. It tells the linker to save the value.Linker.Option.captureStateLayout()returns aStructLayoutthat describes the memory area where the saved values are stored. You allocate a segment of this layout.- The downcall handle takes that segment as an extra parameter. The stub writes the captured values into it right after the native function returns.
The layout describes the platform's capture area, with one member for each capturable name. You allocate the whole layout even if you requested only one name. You find a member's offset by name with byteOffset.
The extra parameter
Adding the option changes the shape of the MethodHandle. The new handle takes a leading MemorySegment parameter that receives the captured state. The rest of the parameters follow in the usual order.
For a function with the C signature int chdir(const char *path), the handle types look like this:
| Handle type | Parameters |
|---|---|
| Without the option | `(MemorySegment path) -> int` |
| With `captureCallState` | `(MemorySegment state, MemorySegment path) -> int` |
If you create the handle without a bound symbol, using downcallHandle(FunctionDescriptor, Option...), the target address parameter comes first. The capture segment is the second parameter in that case.
The FunctionDescriptor does not change. It describes the C signature, and the capture segment is not part of it.
A complete example
The program below calls chdir with a directory that does not exist. It captures errno, then calls strerror to turn the number into text. It runs on Linux and macOS. It needs --enable-native-access=ALL-UNNAMED to avoid the restricted-method warning.
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class ErrnoDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
StructLayout stateLayout = Linker.Option.captureStateLayout();
long errnoOffset = stateLayout.byteOffset(PathElement.groupElement("errno"));
// int chdir(const char *path);
MethodHandle chdir = linker.downcallHandle(
linker.defaultLookup().find("chdir").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS),
Linker.Option.captureCallState("errno"));
// char *strerror(int errnum);
MethodHandle strerror = linker.downcallHandle(
linker.defaultLookup().find("strerror").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.JAVA_INT));
try (Arena arena = Arena.ofConfined()) {
MemorySegment state = arena.allocate(stateLayout);
MemorySegment path = arena.allocateUtf8String("/no/such/directory");
int rc = (int) chdir.invokeExact(state, path);
if (rc != 0) {
int err = state.get(ValueLayout.JAVA_INT, errnoOffset);
MemorySegment msg = (MemorySegment) strerror.invokeExact(err);
String text = msg.reinterpret(Long.MAX_VALUE).getUtf8String(0);
System.out.println("chdir failed: errno=" + err + " (" + text + ")");
}
}
}
}On Linux the output is:
chdir failed: errno=2 (No such file or directory)Read the code in the order it runs.
captureStateLayout()andbyteOffset(...)give you the position of theerrnomember. You compute the offset once and reuse it, as with struct fields.- The
chdirhandle is created with the capture option. Its first parameter is thereforestate. invokeExactrequires the static types to match the handle exactly. That is why the code writes(int)for the result and passesMemorySegmentarguments.- The code checks
rc != 0before readingerrno. This ordering is deliberate. See the next section. strerrorreturns achar *. The returned segment has size zero, because the linker cannot know how long the string is.reinterpret(Long.MAX_VALUE)gives it a usable size so thatgetUtf8String(0)can scan for the terminating zero byte.reinterpretis itself a restricted method. Chapter material on native strings covers this in more detail.
Reusing the capture segment
You do not need a new capture segment for every call. The stub overwrites the captured values on each invocation. In a loop or a long-running service, allocate one segment and reuse it.
Two rules keep this safe:
- Read the value before the next call that uses the same segment. A second call overwrites the first call's value.
- Do not share one capture segment between threads. Each thread has its own
errno, and each thread needs its own capture segment. A confined arena enforces this, because only the owner thread may access segments allocated from it.
A common structure is a small helper that owns the segment and wraps the check. This example turns a failed call into an exception:
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.io.IOException;
final class ErrnoSupport {
private ErrnoSupport() {}
static void check(int returnValue, MemorySegment state, long errnoOffset, String what)
throws IOException {
if (returnValue != 0) {
int err = state.get(ValueLayout.JAVA_INT, errnoOffset);
throw new IOException(what + " failed, errno=" + err);
}
}
}You would call ErrnoSupport.check(rc, state, errnoOffset, "chdir") right after invokeExact. Keeping the check next to the call means no unrelated native call can intervene.
Common errors
- Passing the wrong arguments. After you add the option, the handle has one more parameter. Calling it with the old argument list gives a
WrongMethodTypeExceptionfrominvokeExact. Add the capture segment as the first argument. - A segment that is too small. Allocating, say, 4 bytes by hand fails when the layout is larger. Allocate from
captureStateLayout()so the size is correct on every platform. - Hard-coded names.
"errno"works on Linux and macOS and on Windows for C runtime functions. Win32 calls need"GetLastError". Choose the name by the function you call. - Reading errno through a second handle. Looking up a function that returns
errno, such as__errno_location, and calling it later has the original problem. The value may have changed by then. Use the capture option. - Using the segment after closing its arena. The capture segment follows the usual lifetime rules. Access after the arena closes throws
IllegalStateException.
Exercise
You wrap the C function int unlink(const char *path) in a downcall handle created with Linker.Option.captureCallState("errno"). The descriptor is FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS). (a) What are the parameter types of the resulting MethodHandle? (b) After the call returns 0, should you read errno? (c) Why is it wrong to call a separate lookup of __errno_location after the call instead of using the option?
Show answer
(a) The handle takes (MemorySegment state, MemorySegment path) and returns int. The capture segment is added as the first parameter, and the FunctionDescriptor stays unchanged. (b) No. A return value of 0 means success, and errno may contain a stale value from an earlier failure, so you read it only after a failure result such as -1. (c) Between the native call and a later lookup call, the JVM may run other native code that overwrites errno. The capture option copies errno inside the call stub, before any other Java or JVM code runs, so the value belongs to your call.
Exercise
Modify the ErrnoDemo program so that it calls chdir in a loop over three paths, one valid ("/tmp") and two invalid, reusing a single capture segment. Which two things must you do for each iteration to avoid reporting wrong errors?
Show answer
Check the return value of each call and read errno only when it indicates failure, so that a successful call does not report a stale value. Read errno from the segment before the next iteration's call overwrites it. Keep the segment in one confined arena owned by the calling thread. Reusing it is safe because each invocation overwrites the captured value.