How to isolate the runtime of a dynamic loaded library (dlopen)

132 Views Asked by At

Take for instance an application that needs to load several other shared libraries. Each with the same interface. How can I prevent that a crash in any of the loaded shared libraries to not crash the main application? Keep in mind that they are only loaded one at a time.

Essentially making so that a crash in a call of a symbol from dlsym would not crash the main application.

One of the solutions, like the one bellow, would be to just fork() the main program, load and call the library in the child.

lib.so:

int foo() {
    int a = ((int*)0)[1]; // die

    return a;
};

main.c:

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
    pid_t pid;

    if ((pid = fork()) < 0) {
        perror("fork() error");
    } else if (pid == 0) {
        void* handle = dlopen("./lib.so", RTLD_NOW);

        if (!handle) {
            fprintf(stderr, "%s\n", dlerror());
        }

        dlerror();

        int (*foo)(void) = dlsym(handle, "foo");

        char* error = dlerror();
        if (error != NULL) {
            fprintf(stderr, "%s\n", error);
            exit(1);
        }

        foo(); // only the child will die

        exit(0);
    } else {
        int status;
        waitpid(pid, &status, 0);
        printf("child status %d\n", status);
    }

    puts("exit parent");

    return 0;
}

Is there a better way of doing this? Since fork without exec can lead to other problems.

1

There are 1 best solutions below

0
Employed Russian On

Is there a better way of doing this?

No.