peek.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* peek command: hex dump of memory (identity-mapped, so this also covers
  2. * MMIO registers, e.g. a driver's BAR once mapped).
  3. *
  4. * peek <addr> [len] default len 64, max 256
  5. *
  6. * Reading an unmapped address faults; the exception handler shows EIP/CR2.
  7. */
  8. #include "io.h"
  9. static void put_hex2(unsigned int v)
  10. {
  11. static const char hex[] = "0123456789ABCDEF";
  12. io_putchar(hex[(v >> 4) & 0xF]);
  13. io_putchar(hex[v & 0xF]);
  14. }
  15. static void put_hex8(unsigned int v)
  16. {
  17. put_hex2((v >> 24) & 0xFF);
  18. put_hex2((v >> 16) & 0xFF);
  19. put_hex2((v >> 8) & 0xFF);
  20. put_hex2(v & 0xFF);
  21. }
  22. static int hexval(char c)
  23. {
  24. if (c >= '0' && c <= '9')
  25. return c - '0';
  26. if (c >= 'a' && c <= 'f')
  27. return c - 'a' + 10;
  28. if (c >= 'A' && c <= 'F')
  29. return c - 'A' + 10;
  30. return -1;
  31. }
  32. static int parse_hex(const char *s, unsigned int *out, const char **endp)
  33. {
  34. unsigned int v = 0;
  35. int digits = 0, d;
  36. if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
  37. s += 2;
  38. while ((d = hexval(*s)) >= 0) {
  39. v = (v << 4) | (unsigned int)d;
  40. digits++;
  41. s++;
  42. }
  43. if (!digits)
  44. return -1;
  45. *out = v;
  46. *endp = s;
  47. return 0;
  48. }
  49. void program_peek_main(const char *arg)
  50. {
  51. const char *p = arg;
  52. const volatile unsigned char *mem;
  53. unsigned int addr, len = 64, i, j;
  54. if (parse_hex(p, &addr, &p) != 0) {
  55. io_putstr("peek: usage peek <hexaddr> [len<=256]\n");
  56. return;
  57. }
  58. while (*p == ' ')
  59. p++;
  60. if (*p) {
  61. if (parse_hex(p, &len, &p) != 0 || len == 0 || len > 256) {
  62. io_putstr("peek: usage peek <hexaddr> [len<=256]\n");
  63. return;
  64. }
  65. }
  66. while (*p == ' ')
  67. p++;
  68. if (*p) {
  69. io_putstr("peek: usage peek <hexaddr> [len<=256]\n");
  70. return;
  71. }
  72. mem = (const volatile unsigned char *)addr;
  73. for (i = 0; i < len; i += 16) {
  74. put_hex8(addr + i);
  75. io_putstr(": ");
  76. for (j = 0; j < 16 && i + j < len; j++) {
  77. put_hex2(mem[i + j]);
  78. io_putchar(' ');
  79. }
  80. io_putchar('\n');
  81. }
  82. }