-
-
Save cjwelborn/280f12b17db436516cd104de3feb55ea to your computer and use it in GitHub Desktop.
dlopen from command-line arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! \file dlopentest.c | |
Testing dlopen with user args from the command line. | |
** Remember to use libdl, -ldl when compiling. ** | |
\author Christopher Welborn | |
\date 09-14-2019 | |
*/ | |
#include <dlfcn.h> | |
#include <stdbool.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
char *concat_strings(const char *s1, const char *s2) { | |
char *ret = malloc(strlen(s1) + strlen(s2) + 1); | |
ret[0] = '\0'; | |
strcat(ret, s1); | |
strcat(ret, s2); | |
return ret; | |
} | |
static int open_library(char *libname) { | |
char *tmp, *full_library_name; | |
int ret; | |
/* First, attempt to open just the library, if it has been fully | |
* specified. */ | |
if (dlopen(libname, RTLD_NOW | RTLD_GLOBAL)) { | |
printf("Loaded libary: %s\n", libname); | |
return 1; | |
} | |
/* Append ".so" and prepend "lib" onto `libname' so that we accept | |
* library names as GCC does. */ | |
tmp = concat_strings("lib", libname); | |
full_library_name = concat_strings(tmp, ".so"); | |
printf("Couldn't load '%s', trying '%s'...\n", libname, full_library_name); | |
if(dlopen(full_library_name, RTLD_NOW | RTLD_GLOBAL)) { | |
printf("Library was loaded: '%s'\n", full_library_name); | |
ret = 1; | |
} else { | |
printf("Library load failed: '%s'\n", full_library_name); | |
ret = 0; | |
} | |
free(tmp); | |
free(full_library_name); | |
return ret; | |
} | |
int main(int argc, char** argv) { | |
if (argc < 2) { | |
fprintf(stderr, "No arguments. Usage: dlopentest FILE...\n"); | |
return EXIT_FAILURE; | |
} | |
for (int i = 1; i < argc; i++) { | |
if (!open_library(argv[i])) continue; | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment