debug.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #define _ISOC99_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdarg.h>
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include "config.h"
  8. #include "error.h"
  9. #include "debug.h"
  10. #define PCILIB_MAX_DEBUG_FILENAME_LENGTH 1023
  11. void pcilib_debug_message(const char *function, const char *file, int line, pcilib_log_flags_t flags, const char *format, ...) {
  12. va_list va;
  13. // if (!getenv(function)) return;
  14. va_start(va, format);
  15. pcilib_log_vmessage(file, line, PCILIB_LOG_DEBUG, flags, format, va);
  16. va_end(va);
  17. }
  18. void pcilib_debug_data_buffer(const char *function, size_t size, void *buffer, pcilib_debug_buffer_flags_t flags, const char *file, ...) {
  19. va_list va;
  20. FILE *f;
  21. size_t prefix_len;
  22. const char *prefix;
  23. char fname[PCILIB_MAX_DEBUG_FILENAME_LENGTH + 1];
  24. prefix = getenv(function);
  25. if (!prefix) return;
  26. if ((!prefix[0])||(prefix[0] == '1'))
  27. prefix = PCILIB_DEBUG_DIR;
  28. prefix_len = strlen(prefix);
  29. if (prefix_len >= PCILIB_MAX_DEBUG_FILENAME_LENGTH)
  30. return;
  31. if (prefix_len) {
  32. strncpy(fname, prefix, PCILIB_MAX_DEBUG_FILENAME_LENGTH + 1);
  33. fname[prefix_len++] = '/';
  34. }
  35. fname[PCILIB_MAX_DEBUG_FILENAME_LENGTH] = -1;
  36. va_start(va, file);
  37. vsnprintf(fname + prefix_len, PCILIB_MAX_DEBUG_FILENAME_LENGTH + 1 - prefix_len, file, va);
  38. va_end(va);
  39. // file name is too long, skipping...
  40. if (!fname[PCILIB_MAX_DEBUG_FILENAME_LENGTH])
  41. return;
  42. if (flags&PCILIB_DEBUG_BUFFER_MKDIR) {
  43. char *slash;
  44. if (prefix_len) slash = fname + prefix_len - 1;
  45. else slash = strchr(fname, '/');
  46. while (slash) {
  47. size_t len;
  48. *slash = 0;
  49. mkdir(fname, 0755);
  50. len = strlen(fname);
  51. *slash = '/';
  52. slash = strchr(fname + len + 1, '/');
  53. }
  54. }
  55. if (flags&PCILIB_DEBUG_BUFFER_APPEND)
  56. f = fopen(fname, "a+");
  57. else
  58. f = fopen(fname, "w");
  59. if (!f)
  60. return;
  61. if (size&&buffer)
  62. fwrite(buffer, 1, size, f);
  63. fclose(f);
  64. }