tss2-dlopen-rc.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* SPDX-License-Identifier: BSD-2-Clause */
  2. /*******************************************************************************
  3. * Copyright 2021, Fraunhofer SIT
  4. * All rights reserved.
  5. *******************************************************************************/
  6. /**
  7. * The purpose of this file is to copy it into your project and
  8. * include it during compilation if you don't want to link against
  9. * libtss2-rc at compile time.
  10. * It will attempt to load libtss2-rc.so during runtime.
  11. * It will either work similarly to directly linking to libtss2-rc.so
  12. * at compile-time or return an error string or NULL.
  13. *
  14. * For new versions of this file, please check:
  15. * http://github.com/tpm2-software/tpm2-tss/tss2-dlopen
  16. */
  17. #include <dlfcn.h>
  18. #include <stdio.h>
  19. #include <tss2/tss2_rc.h>
  20. #define str(s) xstr(s)
  21. #define xstr(s) #s
  22. #ifdef ENABLE_WARN
  23. #define WARN(str, ...) do { fprintf(stderr, "WARNING: " str "\n", ## __VA_ARGS__); } while (0)
  24. #else /* ENABLE_WARN */
  25. #define WARN(...) do { } while (0)
  26. #endif /* ENABLE_WARN */
  27. #define LIB "libtss2-rc.so.0"
  28. static void *dlhandle = NULL;
  29. static TSS2_RC
  30. init_dlhandle(void)
  31. {
  32. if (dlhandle)
  33. return TSS2_RC_SUCCESS;
  34. dlhandle = dlopen(LIB, RTLD_NOW | RTLD_LOCAL);
  35. if (!dlhandle) {
  36. WARN("Library " LIB " not found: %s.", dlerror());
  37. return TSS2_BASE_RC_NOT_IMPLEMENTED;
  38. }
  39. return TSS2_RC_SUCCESS;
  40. }
  41. static const char *error = LIB " not found.";
  42. const char *
  43. Tss2_RC_Decode(TSS2_RC rc)
  44. {
  45. if (init_dlhandle() != TSS2_RC_SUCCESS)
  46. return error;
  47. static const char * (*sym) (TSS2_RC rc) = NULL;
  48. if (!sym)
  49. sym = dlsym(dlhandle, "Tss2_RC_Decode");
  50. if (!sym) {
  51. WARN("Function Tss2_RC_Decode not found.");
  52. return error;
  53. }
  54. return sym(rc);
  55. }
  56. TSS2_RC_HANDLER
  57. Tss2_RC_SetHandler(uint8_t layer, const char *name, TSS2_RC_HANDLER handler)
  58. {
  59. if (init_dlhandle() != TSS2_RC_SUCCESS)
  60. return NULL;
  61. TSS2_RC_HANDLER (*sym) (uint8_t layer, const char *name, TSS2_RC_HANDLER handler) = NULL;
  62. if (!sym)
  63. sym = dlsym(dlhandle, "Tss2_RC_SetHandler");
  64. if (!sym) {
  65. WARN("Function Tss2_RC_SetHandler not found.");
  66. return NULL;
  67. }
  68. return sym(layer, name, handler);
  69. }