dbg.cpp 2.0 KB

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