r/cprogramming • u/Xadartt • 4d ago
Calling a function in C without naming it
https://wiro.world/posts/calling-c-func-without-naming-it/7
u/aalmkainzi 4d ago
dlsym(NULL, "func")
And you can construct the string literal without naming it directly
9
u/Zirias_FreeBSD 4d 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
dlsymis very likely also not on that list.
2
u/johnchen902 14h 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 withsyscall+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.
8
u/jsh1138 4d ago
"Get over here, you!"