dbg.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2011-2017 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <inttypes.h>
  8. #include <ctype.h> // isprint
  9. #include "dbg.h"
  10. #include <bx/string.h>
  11. #include <bx/debug.h>
  12. void dbgPrintfVargs(const char* _format, va_list _argList)
  13. {
  14. char temp[8192];
  15. char* out = temp;
  16. int32_t len = bx::vsnprintf(out, sizeof(temp), _format, _argList);
  17. if ( (int32_t)sizeof(temp) < len)
  18. {
  19. out = (char*)alloca(len+1);
  20. len = bx::vsnprintf(out, len, _format, _argList);
  21. }
  22. out[len] = '\0';
  23. bx::debugOutput(out);
  24. }
  25. void dbgPrintf(const char* _format, ...)
  26. {
  27. va_list argList;
  28. va_start(argList, _format);
  29. dbgPrintfVargs(_format, argList);
  30. va_end(argList);
  31. }
  32. #define DBG_ADDRESS "%" PRIxPTR
  33. void dbgPrintfData(const void* _data, uint32_t _size, const char* _format, ...)
  34. {
  35. #define HEX_DUMP_WIDTH 16
  36. #define HEX_DUMP_SPACE_WIDTH 48
  37. #define HEX_DUMP_FORMAT "%-" DBG_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "." DBG_STRINGIZE(HEX_DUMP_SPACE_WIDTH) "s"
  38. va_list argList;
  39. va_start(argList, _format);
  40. dbgPrintfVargs(_format, argList);
  41. va_end(argList);
  42. dbgPrintf("\ndata: " DBG_ADDRESS ", size: %d\n", _data, _size);
  43. if (NULL != _data)
  44. {
  45. const uint8_t* data = reinterpret_cast<const uint8_t*>(_data);
  46. char hex[HEX_DUMP_WIDTH*3+1];
  47. char ascii[HEX_DUMP_WIDTH+1];
  48. uint32_t hexPos = 0;
  49. uint32_t asciiPos = 0;
  50. for (uint32_t ii = 0; ii < _size; ++ii)
  51. {
  52. bx::snprintf(&hex[hexPos], sizeof(hex)-hexPos, "%02x ", data[asciiPos]);
  53. hexPos += 3;
  54. ascii[asciiPos] = isprint(data[asciiPos]) ? data[asciiPos] : '.';
  55. asciiPos++;
  56. if (HEX_DUMP_WIDTH == asciiPos)
  57. {
  58. ascii[asciiPos] = '\0';
  59. dbgPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii);
  60. data += asciiPos;
  61. hexPos = 0;
  62. asciiPos = 0;
  63. }
  64. }
  65. if (0 != asciiPos)
  66. {
  67. ascii[asciiPos] = '\0';
  68. dbgPrintf("\t" DBG_ADDRESS "\t" HEX_DUMP_FORMAT "\t%s\n", data, hex, ascii);
  69. }
  70. }
  71. #undef HEX_DUMP_WIDTH
  72. #undef HEX_DUMP_SPACE_WIDTH
  73. #undef HEX_DUMP_FORMAT
  74. }