Sub topic 12
Reading errno safely after a call
This chapter assumes you can already build a downcall handle from a Linker, a symbol and a FunctionDescriptor.
Why errno needs special handling
Many C functions report failure by returning a sentinel value such as -1 and storing the reason in errno. errno is a thread-local variable, and any code that runs on the same thread can overwrite it. Between your native call returning and your Java code reading errno, the JVM can run its own native code, such as garbage collection work, class loading or a safepoint. That code can change errno.
Reading errno through a second downcall is therefore unreliable. The FFM API solves this by saving the value inside the native call sequence, before the JVM can interfere.
Capturing call state
You request the capture when you create the downcall handle. Pass Linker.Option.captureCallState("errno") as a linker option. The linker then adds a leading MemorySegment parameter to the method handle. After the call, the linker writes the captured errno into that segment.
The segment must match the layout returned by Linker.Option.captureStateLayout(). This is a struct that contains one field for each value the platform can capture. The errno field is available on every platform. Windows also offers GetLastError and WSAGetLastError.
Example: a failing close
The POSIX function close(int fd) returns -1 and sets errno to EBADF when the descriptor is invalid. Passing -1 as the descriptor makes it fail. On Linux and macOS, EBADF is 9.
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 captureLayout = Linker.Option.captureStateLayout();
long errnoOffset = captureLayout.byteOffset(PathElement.groupElement("errno"));
MethodHandle close = linker.downcallHandle(
linker.defaultLookup().find("close").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT),
Linker.Option.captureCallState("errno"));
try (Arena arena = Arena.ofConfined()) {
MemorySegment state = arena.allocate(captureLayout);
int result = (int) close.invokeExact(state, -1);
if (result == -1) {
int errno = state.get(ValueLayout.JAVA_INT, errnoOffset);
System.out.println("close failed, errno = " + errno); // 9 (EBADF)
}
}
}
}Run it with --enable-native-access=ALL-UNNAMED. Three details matter here:
- The
FunctionDescriptordescribes only the C signature. It does not mention the capture segment. The extra parameter exists only on theMethodHandle. - The capture segment comes first in the argument list, so the call is
close.invokeExact(state, -1). - The result is
-1, so the code readserrno. A successful call can also leave a stale or meaninglesserrno.
Common errors
- Reading errno without checking the result. Only read the captured value when the function's own return value signals failure. C functions may set
errnoon success. - Allocating the wrong size. Use
captureStateLayout()for the allocation. A hand-written 4-byte segment is too small on platforms that capture more fields. - Forgetting the extra parameter. A handle created with
captureCallStatehas a differentMethodType. Calling it with the C arguments alone throwsWrongMethodTypeException. - Reusing a segment from another thread. A confined arena's segment is only accessible from its owner thread. Allocate the capture segment in the thread that makes the call.
- Assuming one
errnovalue across platforms. The numeric codes differ between operating systems. Compare against constants for the target platform, or translate them with a lookup such asstrerror.
Exercise
You create a downcall handle for int unlink(const char *path) with Linker.Option.captureCallState("errno"). The descriptor is FunctionDescriptor.of(JAVA_INT, ADDRESS). What parameter types does the resulting method handle take, and when should you read the captured errno?
Show answer
The handle takes two parameters, in this order: a MemorySegment for the capture state, then a MemorySegment for the path. Read the captured errno immediately after the call, and only if unlink returned -1.