r/cprogramming • • Oct 09 '26

Calling a function in C without naming it

https://wiro.world/posts/calling-c-func-without-naming-it/
50 Upvotes

6 comments sorted by

8

u/jsh1138 Oct 09 '26

"Get over here, you!"

7

u/aalmkainzi Oct 09 '26

dlsym(NULL, "func")

And you can construct the string literal without naming it directly

8

u/Zirias_FreeBSD Oct 09 '26

Only reading the title may be misleading. This is about some kind of environment that tries to enforce a certain "whitelist" of functions that can be called, and dlsym is very likely also not on that list.

2

u/johnchen902 Oct 13 '26

The following snippets (x86-64, -O) execve without a magic offset:

#include <stdio.h>
static char *argv[] = { "/bin/false", NULL };
static long f(const char *p, char *const a[], char *const e[]) {
    return 0xc3050f;
}
int main(void) {
    union {
        long (*f)(const char *p, char *const a[], char *const e[]);
        long x;
    } u = {f};
    u.x += 1;
    printf("%58p\n", &u);
    printf("%ld\n", u.f(argv[0], argv, NULL));
    return 0;
}

Explanation:

  • Under optimization, f starts with movl $12780815, %eax (b8 0f 05 c3 00); f+1 starts with syscall + ret (0f 05 c3).
  • The first printf returns 59, putting 59 into rax per System V ABI.
  • The second printf prints -errno in case execve failed.

3

u/LeeHide Oct 09 '26

Nice, good writeup!

1

u/srhubb Oct 12 '26

Excellent travels down a rabbit hole, excellent write-up, and clever solution.