Sub topic 6
Finding native functions with SymbolLookup
This chapter assumes you can read basic MethodHandle code, know what a shared library is, and have a JDK 22 or later. Earlier chapters showed Arena and memory segments. Here you learn how to turn a C function name into something the Linker can call.
What a symbol lookup does
A shared library (.so on Linux, .dylib on macOS, .dll on Windows) exports named entry points called symbols. A SymbolLookup maps a symbol name to the address of that symbol in memory. It has one abstract method:
Optional<MemorySegment> find(String name)If the symbol exists, you get an Optional holding a MemorySegment whose address is the symbol's location. If it does not exist, you get an empty Optional. A missing symbol never throws by itself. Calling orElseThrow() is your decision.
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
public class FindDemo {
public static void main(String[] args) {
SymbolLookup stdlib = Linker.nativeLinker().defaultLookup();
MemorySegment strlen = stdlib.find("strlen").orElseThrow();
System.out.println(strlen.byteSize()); // 0
System.out.println(stdlib.find("no_such_function").isPresent()); // false
}
}The segment for strlen has size 0. The API knows where the function starts but not how many bytes of code it has, so it gives you a zero-length segment. You cannot read or write through it. Its only job is to carry an address into Linker.downcallHandle.
The three built-in lookups
The API gives you three ready-made ways to get a SymbolLookup.
| Lookup | How you get it | What it searches |
|---|---|---|
| Default lookup | `Linker.nativeLinker().defaultLookup()` | Commonly used libraries for the platform, such as the C standard library |
| Loader lookup | `SymbolLookup.loaderLookup()` | Libraries loaded by the caller's class loader with `System.load` or `System.loadLibrary` |
| Library lookup | `SymbolLookup.libraryLookup(name or path, arena)` | One specific library that you open yourself |
The default lookup
defaultLookup() is the right choice for the C standard library. On Linux it covers libc functions such as strlen, qsort and getpid. The exact set of libraries and symbols is platform-specific and not a complete promise. On Windows, for example, it exposes the C runtime but not everything you might expect. If a symbol you need is missing, fall back to libraryLookup.
The loader lookup
loaderLookup() finds symbols in libraries that Java code already loaded. It is the natural fit when you ship a native library next to your application and load it with System.loadLibrary. It has two properties to keep in mind:
- It is tied to the class loader of the class that calls
loaderLookup(). Two different class loaders see two different sets of libraries. - It is dynamic. A symbol that is not found now may be found after a later
System.loadLibrarycall.
The following program assumes a library named greeter that exports a C function greet, and that java.library.path contains it.
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.util.Optional;
public class LoaderDemo {
public static void main(String[] args) {
SymbolLookup loader = SymbolLookup.loaderLookup();
Optional<MemorySegment> before = loader.find("greet");
System.out.println(before.isPresent()); // false, library not loaded yet
System.loadLibrary("greeter");
Optional<MemorySegment> after = loader.find("greet");
System.out.println(after.isPresent()); // true
}
}Run it with -Djava.library.path=/path/to/dir. The same loader object sees the new library because it searches the loaded libraries each time you call find.
The library lookup
SymbolLookup.libraryLookup opens a library for you, without System.loadLibrary. It has two forms:
SymbolLookup.libraryLookup(String name, Arena arena)
SymbolLookup.libraryLookup(Path path, Arena arena)With a String, the platform loader resolves the name using its normal search rules (dlopen on Linux and macOS, LoadLibrary on Windows). With a Path, you name the file explicitly. If the library cannot be opened, the call throws IllegalArgumentException.
The Arena controls how long the library stays loaded. When the arena closes, the library is unloaded. The segments that find returns are tied to that arena, so touching one after the close throws IllegalStateException.
This example calls cos from the math library on Linux, where the file is libm.so.6:
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class LibmDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
try (Arena arena = Arena.ofConfined()) {
SymbolLookup libm = SymbolLookup.libraryLookup("libm.so.6", arena);
MemorySegment cos = libm.find("cos").orElseThrow();
MethodHandle handle = linker.downcallHandle(cos,
FunctionDescriptor.of(ValueLayout.JAVA_DOUBLE, ValueLayout.JAVA_DOUBLE));
double result = (double) handle.invokeExact(0.0);
System.out.println(result); // 1.0
}
}
}The library name is not portable. macOS and Windows use different file names, and on those systems cos is already reachable through the default lookup. Pick the name per platform, or prefer the default lookup when it has what you need.
Combining lookups with or
SymbolLookup is a functional interface, and its or method chains two lookups. a.or(b) asks a first and asks b only if a returned empty. The first hit wins.
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
public class ChainDemo {
static SymbolLookup lookup() {
return SymbolLookup.loaderLookup()
.or(Linker.nativeLinker().defaultLookup());
}
public static void main(String[] args) {
MemorySegment getpid = lookup().find("getpid")
.orElseThrow(() -> new IllegalStateException("getpid not found"));
System.out.println(getpid.address() != 0); // true on Linux and macOS
}
}The order matters. Putting loaderLookup() first means a library you ship can override a symbol with the same name from libc. Reversing the order gives libc priority. Choose the order on purpose, because a name clash silently picks one and hides the other.
The lookup pipeline looks like this:
Writing your own lookup
Because SymbolLookup has a single abstract method, a lambda is enough. This is useful for tests, for wrapping a lookup with logging, or for adding a fallback with a clear error message.
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.util.Optional;
public class LoggingLookupDemo {
public static void main(String[] args) {
SymbolLookup base = Linker.nativeLinker().defaultLookup();
SymbolLookup logging = name -> {
Optional<MemorySegment> result = base.find(name);
System.out.println("lookup " + name + " -> " + (result.isPresent() ? "found" : "missing"));
return result;
};
logging.find("strlen");
logging.find("not_a_function");
}
}It prints lookup strlen -> found and then lookup not_a_function -> missing. A wrapper like this is a cheap way to see which names your bindings request.
Edge cases and common errors
- Empty result from a name that looks right. Names are case-sensitive and must match the exported symbol exactly. C++ functions are name-mangled unless declared
extern "C", sofind("add")will not find a C++add(int, int). Inspect the library withnm -D libfoo.soon Linux, ordumpbin /exportson Windows. - Wrong library, right name. On Windows, the same function name can live in different DLLs. Check which library you opened.
- Library not found.
libraryLookup("foo", arena)throwsIllegalArgumentExceptionif the platform loader cannot resolvefoo. Pass an absolutePathto remove the search-path question. - Using a segment after the arena closes. The segment from
libraryLookupis bound to the arena. Reading its address afterwards throwsIllegalStateException. Keep the arena open for as long as you use any handle built from it. - Closing the arena while a handle is still in use. Closing unloads the library. A downcall handle that you built earlier does not re-check the arena on every call, so invoking it after the close can crash the JVM. Treat the arena as the owner of both the symbols and every handle derived from them.
- Long-lived libraries. For a library that must stay loaded for the whole process, use
Arena.global()withlibraryLookup, orSystem.loadLibrarywithloaderLookup. Do not use a short-lived arena for something you cache in a static field. - Cache the result. Looking up a symbol and creating a downcall handle are both comparatively slow. Do them once, store the
MethodHandlein astatic finalfield, and reuse it.
Choosing a lookup
- Start with
defaultLookup()for standard C functions. It needs no setup. - Use
loaderLookup()when your application packages its own native library and loads it withSystem.loadLibrary. Class-loader scoping then matches how the rest of your Java code is organized. - Use
libraryLookup(...)when you want the library's lifetime tied to an arena, or when you need to open a system library that the default lookup does not cover. - Combine them with
orand decide the priority explicitly.
Exercise
You build a lookup as SymbolLookup.libraryLookup("libm.so.6", arena).find("cos").orElseThrow() inside a try-with-resources block on Arena.ofConfined(), and store the resulting MethodHandle in a static field. A later call to that handle from another part of the program crashes or fails. What is wrong, and how do you fix it?
Show answer
The arena closed at the end of the try block, which unloaded libm. The segment for cos is no longer valid, and the cached handle points at code that is no longer loaded. Fix it by tying the library to a lifetime that matches the handle's use. Open the library with Arena.global(), or with an arena you close only at application shutdown. Alternatively, use Linker.nativeLinker().defaultLookup() for cos where the platform provides it, because that lookup does not depend on a closing arena.
Exercise
You write SymbolLookup.loaderLookup().or(Linker.nativeLinker().defaultLookup()) and your own library also exports a function named strlen. Which implementation does find("strlen") return, and how do you make libc win instead?
Show answer
It returns the one from your own library, because or asks the first lookup first and returns its result when present. To make libc win, reverse the order: Linker.nativeLinker().defaultLookup().or(SymbolLookup.loaderLookup()).