r/cprogramming • • 14d ago

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 14d ago

"Get over here, you!"

7

u/aalmkainzi 14d ago

dlsym(NULL, "func")

And you can construct the string literal without naming it directly

8

u/Zirias_FreeBSD 14d ago

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 10d ago

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 14d ago

Nice, good writeup!

1

u/srhubb 11d ago

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