Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "module_loader.h"
- /*
- * Loads all of the modules in the provided directory.
- * Returns 1 on success or zero on failure.
- */
- int
- load_modules(char *module_dir)
- {
- DIR *dir;
- struct dirent *ent;
- void *handle;
- int (*fn)();
- char *error;
- int len;
- int load_result;
- char *mod_loc;
- dir = opendir(module_dir);
- if (dir == NULL) {
- perror("load_modules() failed to open directory");
- exit(EXIT_FAILURE);
- }
- /*
- * If the filename contains .so then we attempt
- * to load it as a plugin.
- */
- while ((ent = readdir(dir)) != NULL) {
- char *c = strstr(ent->d_name, ".so");
- if (c != NULL) {
- len = strlen(module_dir) + strlen(ent->d_name) + 1;
- mod_loc = (char *) malloc(len);
- strcat(mod_loc, module_dir);
- strcat(mod_loc, ent->d_name);
- handle = dlopen(mod_loc, RTLD_NOW);
- free(mod_loc);
- if (!handle) {
- fprintf(stderr, "Failed open: %s. Could not load module %s\n",
- dlerror(), ent->d_name);
- return 0;
- }
- fn = dlsym(handle, "module_init");
- if ((error = dlerror()) != NULL) {
- fprintf(stderr, "Failed symbol search: %s. Could not load module %s\n",
- error, ent->d_name);
- return 0;
- }
- load_result = (*fn)();
- if (!load_result) {
- printf("Failed to load module %s\n", ent->d_name);
- return 0;
- }
- printf("Loaded module: %s\n", ent->d_name);
- dlclose(handle); /* Cleanup, temporary only */
- }
- }
- closedir(dir);
- return 1;
- }
- int
- unload_modules()
- {
- return 1;
- }
- int
- load_module(char *module_dir, char *module_name)
- {
- void *handle;
- int (*fn)();
- int load_result;
- char *error;
- char full_module_name[100];
- memset(full_module_name, '\0', 100);
- strcat(full_module_name, module_dir);
- strcat(full_module_name, module_name);
- strcat(full_module_name, ".so");
- handle = dlopen(full_module_name, RTLD_NOW);
- if (!handle) {
- fprintf(stderr, "1. %s\n", dlerror());
- return 0;
- }
- fn = dlsym(handle, "module_init");
- if ((error = dlerror()) != NULL) {
- fprintf(stderr, "2. %s\n", error);
- return 0;
- }
- load_result = (*fn)();
- if (!load_result) {
- fprintf(stderr, "Failed to load module %s\n", module_name);
- return 0;
- }
- dlclose(handle); /* Cleanup, temporary only */
- return 1;
- }
- int
- unload_module(char *module_name)
- {
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement