test_dlopen_null.c revision 6f09971503f9bea177168d1599e925a5b22d18dd
1#include <dlfcn.h>
2#include <stddef.h>
3#include <stdio.h>
4
5extern int foo(void)
6{
7    return 42;
8}
9
10int (*func_ptr)(void) = foo;
11
12int main(void)
13{
14    void*  lib = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
15    void*  symbol;
16
17#if 0
18    /* The Gold linker will garbage-collect unused global functions
19     * even if --Wl,--export-dynamic is used. So use a dummy global
20     * variable reference here to prevent this.
21     */
22    if (foo() != 42)
23        return 3;
24#endif
25
26    if (lib == NULL) {
27        fprintf(stderr, "Could not open self-executable with dlopen(NULL) !!: %s\n", dlerror());
28        return 1;
29    }
30    symbol = dlsym(lib, "foo");
31    if (symbol == NULL) {
32        fprintf(stderr, "Could not lookup symbol inside executable !!: %s\n", dlerror());
33        return 2;
34    }
35    dlclose(lib);
36    return 0;
37}
38