Sub topic 13
Calling variadic functions such as printf
This chapter covers C functions that take a variable number of arguments, such as printf and snprintf. It assumes you can already build a downcall handle with Linker, SymbolLookup and FunctionDescriptor, and that you know how to allocate native strings in an Arena. The examples are written for Java 22. Java 23 and later rename allocateUtf8String to allocateFrom and getUtf8String to getString.
What makes a function variadic
A variadic function declares a fixed list of leading parameters, followed by ...:
int printf(const char *format, ...);
int snprintf(char *buf, size_t n, const char *format, ...);The C compiler sees the call site and knows the actual argument types. The function itself does not. It learns the types only by reading the format string. This has two consequences for Java:
- A single native symbol can be called with many different argument shapes.
- The calling convention for the extra arguments can differ from that of an ordinary call.
The second point is the important one. On x86-64 System V, the caller sets a register to the number of vector registers used. On Windows x64, floating-point arguments are also copied into integer registers. On macOS AArch64, variadic arguments go on the stack, while ordinary arguments go in registers. The linker must know where the variadic part begins so it can follow the right convention for your platform.
Marking the first variadic argument
You tell the linker with Linker.Option.firstVariadicArg(int index). The index is a position in the FunctionDescriptor, counting from zero. For printf, the format string is at index 0, so the first variadic argument is at index 1.
The descriptor lists the types you will pass in one specific call. Because a MethodHandle has a fixed type, each distinct argument shape needs its own downcall handle, even though the native symbol is the same.
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.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.ADDRESS;
import static java.lang.foreign.ValueLayout.JAVA_DOUBLE;
import static java.lang.foreign.ValueLayout.JAVA_INT;
public class PrintfDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
SymbolLookup libc = linker.defaultLookup();
// int printf(const char *format, int, double)
MethodHandle printf = linker.downcallHandle(
libc.find("printf").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_INT, JAVA_DOUBLE),
Linker.Option.firstVariadicArg(1));
// int fflush(FILE *stream); NULL flushes all open output streams
MethodHandle fflush = linker.downcallHandle(
libc.find("fflush").orElseThrow(),
FunctionDescriptor.of(JAVA_INT, ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment fmt = arena.allocateUtf8String("count=%d ratio=%.2f\n");
int written = (int) printf.invokeExact(fmt, 42, 3.5);
int rc = (int) fflush.invokeExact(MemorySegment.NULL);
System.out.println("printf wrote " + written + " bytes");
}
}
}Run it with --enable-native-access=ALL-UNNAMED. It prints count=42 ratio=3.50 and then printf wrote 20 bytes.
The handle type is (MemorySegment, int, double) int. Because the code uses invokeExact, the call site must match that type exactly, including the cast on the result.
The fflush call is there for a practical reason. C's stdout has its own buffer, separate from Java's System.out. When output is piped or redirected, C fully buffers it, and the text may appear after later Java output. Flushing makes the order deterministic.
Which layouts you may use
C applies default argument promotions to variadic arguments. A char, short or _Bool is promoted to int. A float is promoted to double. The variadic part of a C function therefore never receives anything narrower than an int or double.
The linker enforces this. If a layout after the first variadic index is JAVA_BOOLEAN, JAVA_BYTE, JAVA_CHAR, JAVA_SHORT or JAVA_FLOAT, creating the handle throws IllegalArgumentException. Use these instead:
| C argument type | Layout to use in the variadic part | Matching printf conversion |
|---|---|---|
| `char`, `short`, `int` | `JAVA_INT` | `%d`, `%c` |
| `float`, `double` | `JAVA_DOUBLE` | `%f`, `%g` |
| `long long` | `JAVA_LONG` | `%lld` |
| `const char *`, any pointer | `ADDRESS` | `%s`, `%p` |
Fixed parameters before the variadic index are not restricted. You can use JAVA_FLOAT or JAVA_SHORT there if the C declaration has such a parameter.
A useful example: snprintf
printf writes to the process's stdout, which makes it awkward to check from Java. snprintf writes into a buffer that you own, so it is easier to test. It also shows a descriptor with several fixed parameters before the variadic part.
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.ADDRESS;
import static java.lang.foreign.ValueLayout.JAVA_DOUBLE;
import static java.lang.foreign.ValueLayout.JAVA_INT;
import static java.lang.foreign.ValueLayout.JAVA_LONG;
public class SnprintfDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
// int snprintf(char *buf, size_t n, const char *fmt, int, double, const char *)
// size_t is modeled as JAVA_LONG, which is correct on 64-bit platforms.
MethodHandle snprintf = linker.downcallHandle(
linker.defaultLookup().find("snprintf").orElseThrow(),
FunctionDescriptor.of(JAVA_INT,
ADDRESS, JAVA_LONG, ADDRESS,
JAVA_INT, JAVA_DOUBLE, ADDRESS),
Linker.Option.firstVariadicArg(3));
try (Arena arena = Arena.ofConfined()) {
MemorySegment buf = arena.allocate(64);
MemorySegment fmt = arena.allocateUtf8String("id=%d ratio=%.2f name=%s");
MemorySegment name = arena.allocateUtf8String("Duke");
int needed = (int) snprintf.invokeExact(buf, buf.byteSize(), fmt, 7, 2.5, name);
System.out.println(buf.getUtf8String(0)); // id=7 ratio=2.50 name=Duke
System.out.println(needed); // 25
}
}
}The first variadic argument is the int at index 3, after the buffer, the size and the format string. The %s conversion receives a pointer, so the descriptor uses ADDRESS for it.
snprintf returns the number of characters it would have written if the buffer were large enough, not the number it actually wrote. If needed is greater than or equal to the buffer size, the output was truncated. A robust wrapper compares the two and retries with a larger buffer.
Errors the linker cannot catch
The linker checks the shape of the descriptor against the platform ABI. It cannot check that your arguments agree with the format string. These mistakes compile and run, and they have undefined behavior in C:
- Too few arguments.
%swith nothing left to consume reads a pointer from whatever register or stack slot comes next. This can crash the JVM. - Wrong width. Passing
JAVA_INTfor%lld, orJAVA_LONGfor%d, makes the function read the wrong number of bytes. - Wrong class. Passing an integer where
%fexpects a double reads a floating-point register that your call never set. - Unterminated strings. A
%sargument must point to a null-terminated string. A segment fromallocateUtf8Stringalways is. A raw byte buffer may not be.
Platform differences in type sizes
The width of C's long differs between platforms. It is 64 bits on 64-bit Linux and macOS, but 32 bits on Windows. A call that uses %ld with JAVA_LONG works on Linux and fails on Windows. %lld always takes a 64-bit long long, so JAVA_LONG with %lld is portable. For size_t, %zu matches JAVA_LONG on 64-bit platforms.
Availability also varies. On Windows, the printf family is defined inline in the C runtime headers, and the default lookup is not guaranteed to expose it. Check the result of find before calling orElseThrow, and be ready to load the C runtime library explicitly.
Choosing between a variadic handle and a wrapper
If the C library offers a va_list variant such as vsnprintf, it is not easier to call, because you would have to build a va_list yourself. If you control the native side, a small C wrapper with a fixed signature, for example format_record(char *buf, size_t n, int id, double ratio, const char *name), is often the better choice. It removes the format-string hazard from the Java side entirely. Use a variadic handle when you must call an existing library function as it is.
Exercise
You build a handle for snprintf with the descriptor FunctionDescriptor.of(JAVA_INT, ADDRESS, JAVA_LONG, ADDRESS, JAVA_FLOAT) and firstVariadicArg(3). You intend to format a Java float with %f. What happens, and how do you fix it?
Show answer
Creating the handle throws IllegalArgumentException, because JAVA_FLOAT is not allowed in the variadic part of a descriptor. C promotes a float to double when it is passed to a variadic function. Change the layout to JAVA_DOUBLE, and pass the value as a double (for example by widening the float with a cast) when you invoke the handle.
Exercise
Why does a program that calls printf through a downcall handle sometimes print its C output after later System.out lines when stdout is redirected to a file, and what is a way to make the order predictable?
Show answer
The C library keeps its own stdout buffer, separate from Java's System.out. When stdout is redirected, C buffers it fully and writes it only when the buffer fills, when the stream is flushed, or at process exit. Calling fflush(NULL) through another downcall handle after printf forces the C buffer out. Alternatively, call snprintf and print the result from Java.
Exercise
A downcall handle for printf has the descriptor of(JAVA_INT, ADDRESS, JAVA_INT) with firstVariadicArg(1). Can you use the same handle to call printf("%s\n", name)? Explain.
Show answer
No. The handle's type is (MemorySegment, int) int, so the second argument must be an int. To pass a pointer for %s, create a second handle from the same symbol with the descriptor of(JAVA_INT, ADDRESS, ADDRESS) and firstVariadicArg(1). Each argument shape needs its own handle.