2017年4月17日 星期一

dlopen and dlsym


Prepare a SO file writtern in C:
vi libso.c
#include <stdio.h>
int bejo_lib(char *name, int i) {
    printf("I am %s, do i=%d\n", name, i);
    return 0;
}
gcc -fPIC -c libso.c
gcc -shared -o libso.so libso.o

Notice the function name is not mangled because it is not C++:
nm libso.so  | grep bejo
00000000000006c8 T bejo_lib

Prepare the C user code:
vi use.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
    void* so = dlopen("./libso.so",RTLD_LAZY);
    printf("so: %p\n", so);
    if (!so) {
        fprintf(stderr, "%s\n", dlerror());
        exit(1);
    }
    dlerror();
    void (*fn)();
    fn = (void(*)())dlsym(so, "bejo_lib");
    printf("fn: %p\n", fn);
    if (fn) {
        fn("BEJO", 999);
    }
    dlclose(so);
    return 0;
}
// nm libso.so  | grep bejo
// 00000000000006c8 T bejo_lib
// gcc use.c -ldl -o use && ./use

The functions are mangled in the SO file libEsunnyQuot.so written in C++:
nm libEsunnyQuot.so | grep CreateEsunnyQuotClient
0000000000007c60 T _Z22CreateEsunnyQuotClientP17IEsunnyQuotNotify
nm libEsunnyQuot.so | grep DelEsunnyQuotClient
0000000000007c30 T _Z19DelEsunnyQuotClientP17IEsunnyQuotClient

Prepare the C++ user code:
vi sun.cpp
#include "EsunnyQuot.h"
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
    void* so = dlopen("./libEsunnyQuot.so",RTLD_LAZY);
    printf("so: %p\n", so);
    if (!so) {
        fprintf(stderr, "%s\n", dlerror());
        exit(1);
    }
    dlerror();
    void (*fn)(IEsunnyQuotClient*);
    fn = (void(*)(IEsunnyQuotClient*))dlsym(so, "_Z19DelEsunnyQuotClientP17IEsunnyQuotClient");
    printf("fn: %p\n", fn);
    if (fn) {
        fn(NULL);
    }
    dlclose(so);
    return 0;
}
// nm libEsunnyQuot.so | grep CreateEsunnyQuotClient
// 0000000000007c60 T _Z22CreateEsunnyQuotClientP17IEsunnyQuotNotify
// nm libEsunnyQuot.so | grep DelEsunnyQuotClient
// 0000000000007c30 T _Z19DelEsunnyQuotClientP17IEsunnyQuotClient
// gcc sun.cpp -ldl -o sun && ./sun

沒有留言:

張貼留言

202501 Debian USB LAN Card Bridge

 202501 Debian USB LAN Card Bridge ChatGPT Question I have a machine running debian 12 with a LAN port using a cable to connect to my office...