dlfcn.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <dlfcn.h>
  4. int add(int a, int b)
  5. {
  6. return a + b;
  7. }
  8. void test_dlopen_null()
  9. {
  10. void* handle = dlopen(NULL, RTLD_LAZY);
  11. if (!handle) {
  12. printf("dlopen(NULL) failed\n");
  13. exit(1);
  14. }
  15. int (*f)(int, int) = dlsym(handle, "add");
  16. if (!f) {
  17. printf("dlsym(handle, add) failed\n");
  18. exit(2);
  19. }
  20. int a = 22;
  21. int b = 33;
  22. printf("add(%d, %d) = %d\n", a, b, f(a, b));
  23. dlclose(handle);
  24. }
  25. void test_dlopen_libc()
  26. {
  27. void* handle = dlopen("libc.so.6", RTLD_LAZY);
  28. if (!handle) {
  29. printf("dlopen(libc.so.6) failed\n");
  30. exit(1);
  31. }
  32. int (*f)(const char*) = dlsym(handle, "puts");
  33. if (!f) {
  34. printf("dlsym(handle, puts) failed\n");
  35. exit(2);
  36. }
  37. f("puts from dlopened libc");
  38. dlclose(handle);
  39. }
  40. void test_dlsym_function()
  41. {
  42. void* handle = dlopen("sharedlib.so", RTLD_LAZY);
  43. if (!handle) {
  44. printf("dlopen(sharedlib.so) failed\n");
  45. exit(1);
  46. }
  47. void (*f)() = dlsym(handle, "print");
  48. if (!f) {
  49. printf("dlsym(handle, print) failed\n");
  50. exit(2);
  51. }
  52. f();
  53. dlclose(handle);
  54. }
  55. void test_dlsym_global_var()
  56. {
  57. void* handle = dlopen("sharedlib.so", RTLD_LAZY);
  58. if (!handle) {
  59. printf("dlopen(sharedlib.so) failed\n");
  60. exit(1);
  61. }
  62. int* global_var = dlsym(handle, "global_var");
  63. if (!global_var) {
  64. printf("dlsym(handle, global_var) failed\n");
  65. exit(2);
  66. }
  67. printf("main: global_var == %d\n", *global_var);
  68. dlclose(handle);
  69. }
  70. void test_dlsym_tls_var()
  71. {
  72. void* handle = dlopen("sharedlib.so", RTLD_LAZY);
  73. if (!handle) {
  74. printf("dlopen(sharedlib.so) failed\n");
  75. exit(1);
  76. }
  77. int* tls_var = dlsym(handle, "tls_var");
  78. if (!tls_var) {
  79. printf("dlsym(handle, tls_var) failed\n");
  80. exit(2);
  81. }
  82. printf("main: tls_var == %d\n", *tls_var);
  83. dlclose(handle);
  84. }
  85. int main()
  86. {
  87. test_dlopen_null();
  88. test_dlopen_libc();
  89. test_dlsym_function();
  90. test_dlsym_global_var();
  91. test_dlsym_tls_var();
  92. }