shared_library.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/io/shared_library.h>
  6. #include <aws/io/logging.h>
  7. #include <dlfcn.h>
  8. static const char *s_null = "<NULL>";
  9. static const char *s_unknown_error = "<Unknown>";
  10. int aws_shared_library_init(struct aws_shared_library *library, const char *library_path) {
  11. AWS_ZERO_STRUCT(*library);
  12. library->library_handle = dlopen(library_path, RTLD_LAZY);
  13. if (library->library_handle == NULL) {
  14. const char *error = dlerror();
  15. AWS_LOGF_ERROR(
  16. AWS_LS_IO_SHARED_LIBRARY,
  17. "id=%p: Failed to load shared library at path \"%s\" with error: %s",
  18. (void *)library,
  19. library_path ? library_path : s_null,
  20. error ? error : s_unknown_error);
  21. return aws_raise_error(AWS_IO_SHARED_LIBRARY_LOAD_FAILURE);
  22. }
  23. return AWS_OP_SUCCESS;
  24. }
  25. void aws_shared_library_clean_up(struct aws_shared_library *library) {
  26. if (library && library->library_handle) {
  27. dlclose(library->library_handle);
  28. library->library_handle = NULL;
  29. }
  30. }
  31. int aws_shared_library_find_function(
  32. struct aws_shared_library *library,
  33. const char *symbol_name,
  34. aws_generic_function *function_address) {
  35. if (library == NULL || library->library_handle == NULL) {
  36. return aws_raise_error(AWS_IO_SHARED_LIBRARY_FIND_SYMBOL_FAILURE);
  37. }
  38. /*
  39. * Suggested work around for (undefined behavior) cast from void * to function pointer
  40. * in POSIX.1-2003 standard, at least according to dlsym man page code sample.
  41. */
  42. *(void **)(function_address) = dlsym(library->library_handle, symbol_name);
  43. if (*function_address == NULL) {
  44. const char *error = dlerror();
  45. AWS_LOGF_ERROR(
  46. AWS_LS_IO_SHARED_LIBRARY,
  47. "id=%p: Failed to find shared library symbol \"%s\" with error: %s",
  48. (void *)library,
  49. symbol_name ? symbol_name : s_null,
  50. error ? error : s_unknown_error);
  51. return aws_raise_error(AWS_IO_SHARED_LIBRARY_FIND_SYMBOL_FAILURE);
  52. }
  53. return AWS_OP_SUCCESS;
  54. }