Skip to content
systemcoding.dev
Kernels

Probe for Optional Syscalls at Runtime and Fall Back Gracefully

Detect a missing system call by trying it once, treating ENOSYS and seccomp EPERM as absent, caching the answer and falling back, shown with close_range.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and Rust logos.

A program compiled today may run next year on a kernel from five years ago, or inside a container whose security profile blocks calls the host kernel supports. If it needs a system call that is newer than the oldest kernel you support, you have two choices: refuse to start, or notice the call is missing and do the job another way. The second is almost always better for system tools, and the technique is the same for every optional call. This post builds it for close_range, added in Linux 5.9, with a working fallback, on a 6.12 kernel and glibc 2.40.

Why checking the kernel version is the wrong test

The obvious idea is to read uname and compare the version to "5.9". It fails in three ways.

First, distribution kernels backport features. A vendor kernel labeled 4.18 may contain close_range, and a check against the number would wrongly refuse it. Second, a container runtime or a sandbox can filter system calls with seccomp, and then the host kernel may support a call that your process may not make. Third, the version string is a free-form text field that some environments modify.

What you want to know is whether this call works for this process right now, and the only reliable way to learn that is to make the call.

What a missing call returns

When a program invokes a system call number the kernel does not implement, the kernel returns -ENOSYS, "Function not implemented". That is the clean signal. Two other results matter in practice:

ResultMeaning
ENOSYSThe kernel does not have this call
EPERMA seccomp filter denied the call, common in older container profiles
EINVALThe call exists but a flag or argument is not understood

Seccomp filters decide their own default. A filter can answer a blocked call with EPERM, with ENOSYS or by killing the process. Runtimes that care about compatibility return ENOSYS for unknown calls so that programs fall back, but older profiles return EPERM. A program that treats only ENOSYS as "unavailable" fails in the second case. The safe rule is to accept both as "not usable here" for a call whose absence you can work around.

The wrapper may not exist either

There is a second kind of absence: the C library. close_range has a glibc wrapper since glibc 2.34, declared in <unistd.h> when _GNU_SOURCE is defined. On an older library, calling it fails at link time. The portable approach is to use syscall() with the constant from <sys/syscall.h>, which exists whenever the kernel headers the program was built against know the call, and to guard it with #ifdef:

c
#ifdef SYS_close_range
	/* the headers know the number: try the call */
#else
	/* headers too old: go straight to the fallback */
#endif

This handles three situations: old headers, old kernel and filtered call, with the same fallback code serving all of them.

The task: close every descriptor from N upward

A daemon about to execute another program wants to close every inherited file descriptor from 3 up, so the child does not leak them. close_range(first, last, flags) does it in one system call. Without it, the usual fallback lists /proc/self/fd and closes each one. Here is a complete implementation with a cached probe:

closefrom.cc
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>

enum { CR_UNKNOWN = -1, CR_ABSENT = 0, CR_PRESENT = 1 };
static int close_range_state = CR_UNKNOWN;

static int close_from_fallback(int first)
{
	DIR *d = opendir("/proc/self/fd");
	int *fds = NULL;
	size_t n = 0, cap = 0;
	struct dirent *e;
	int self, rc = 0;

	if (!d)
		return -1;
	self = dirfd(d);

	while ((e = readdir(d)) != NULL) {
		char *end;
		long v = strtol(e->d_name, &end, 10);

		if (*end != '\0' || v < first || v == self)
			continue;
		if (n == cap) {
			size_t ncap = cap ? cap * 2 : 32;
			int *tmp = realloc(fds, ncap * sizeof(*fds));

			if (!tmp) {
				rc = -1;
				break;
			}
			fds = tmp;
			cap = ncap;
		}
		fds[n++] = (int)v;
	}
	closedir(d);

	for (size_t i = 0; i < n; i++)
		close(fds[i]);
	free(fds);
	return rc;
}

/* Returns 1 if the kernel call did the work, 2 if the fallback did, -1 on error. */
static int close_from(int first)
{
#ifdef SYS_close_range
	if (close_range_state != CR_ABSENT) {
		if (syscall(SYS_close_range, (unsigned int)first, ~0U, 0) == 0) {
			close_range_state = CR_PRESENT;
			return 1;
		}
		if (errno == ENOSYS || errno == EPERM) {
			close_range_state = CR_ABSENT;
		} else {
			return -1;
		}
	}
#endif
	return close_from_fallback(first) == 0 ? 2 : -1;
}

int main(void)
{
	for (int i = 0; i < 3; i++)
		open("/dev/null", O_RDONLY);

	int how = close_from(3);
	int still_open = fcntl(3, F_GETFD) != -1;

	printf("path %d, fd 3 still open: %s\n", how, still_open ? "yes" : "no");
	return 0;
}

On a kernel with the call the program prints:

Text
path 1, fd 3 still open: no

How the probe works

The first call to close_from sets close_range_state only after it learns something. A success means the call exists, so later calls skip any checking. ENOSYS or EPERM means it does not work here, so the state becomes absent and every later call goes straight to the fallback without paying for another failing system call. Any other error is a real failure, returned to the caller, not mistaken for absence. That separation matters: swallowing every error as "not available" would hide a genuine bug such as passing a bad range.

The state variable is a plain static int. If several threads may call close_from at the same time, the race is benign here because every writer stores the same value, but you should use atomic_int if the state could ever flip in both directions. A program that sets up seccomp in the middle of its life is a rare example, and for that case you re-probe after the filter changes.

Testing the fallback without an old kernel

You do not need an old kernel to exercise the fallback. strace can make a call fail on demand with its inject option:

Shell
strace -e inject=close_range:error=ENOSYS -o /dev/null ./closefrom
Text
path 2, fd 3 still open: no

The trace output is discarded, and the program's own output shows that it took path 2, the fallback. Run the program once with the injection and once without in your test suite, so both code paths stay correct. The same trick with error=EPERM checks the seccomp case. You can also compile with -USYS_close_range on the command line, or wrap the #ifdef in a project macro, to test the "old headers" branch.

Flags are a second kind of probing

New flags on an existing call need the same care. close_range gained the CLOSE_RANGE_CLOEXEC flag in Linux 5.11, which marks descriptors close-on-exec instead of closing them. An older kernel that knows the call but not the flag returns EINVAL. The pattern is identical: try the flag, and on EINVAL try again without it, or fall back to the older approach. Keep this in mind when you read the documentation: the version in the NOTES section of each manual page tells you when a call, and often each flag, appeared.

Choosing between fallback and failure

Not every missing call deserves a fallback. Use the question: does the fallback give the same guarantee? The /proc fallback above gives the same end result, but it can fail where /proc is not mounted, and it is not atomic with respect to other threads opening descriptors. For close_range that is acceptable. For a call that provides a security property, such as openat2 with RESOLVE_BENEATH to stop path traversal, an emulation built from openat and manual checks is easy to get subtly wrong, and refusing to run may be the safer choice. Decide per call, write the decision down in a comment, and fail loudly when no safe path exists.

Where the probe belongs in a program

Decide when the first call happens. Probing at startup, in an initialization function, keeps the cost and the decision in one place and lets the program log which path it chose, which helps support engineers diagnose a report from an unusual environment. Probing lazily, on the first use, avoids work for programs that never need the call. Either way, keep the result in one variable inside one module, and expose a function such as close_from() to the rest of the program, so no other file needs to know that a fallback exists.

In a library, be careful about process-wide state. A program may install a seccomp filter after your library's first call, changing the answer, and a forked child may run under a stricter filter than its parent. If that matters, re-probe after fork, or treat the cached state as a hint and still handle ENOSYS and EPERM on every call. Log the chosen path once, at debug level, with the reason, such as the error name returned by the probe. And add a test that forces each path in continuous integration, with strace -e inject= or a build flag, so that the fallback, which almost never runs in production, does not rot.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.