hexdump.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2013 Google Inc.
  3. *
  4. * See file CREDITS for list of people who contributed to this
  5. * project.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2 of
  10. * the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but without any warranty; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  20. * MA 02111-1307 USA
  21. */
  22. #include "u.h"
  23. #include "tos.h"
  24. #include "../port/lib.h"
  25. #include "mem.h"
  26. #include "dat.h"
  27. #include "fns.h"
  28. #include "../port/error.h"
  29. static int isprint(int c)
  30. {
  31. return (c >= 32 && c <= 126);
  32. }
  33. void hexdump(void *v, int length)
  34. {
  35. int i;
  36. uint8_t *m = v;
  37. uintptr_t memory = (uintptr_t) v;
  38. int all_zero = 0;
  39. print("hexdump: %p, %u\n", v, length);
  40. for (i = 0; i < length; i += 16) {
  41. int j;
  42. all_zero++;
  43. for (j = 0; (j < 16) && (i + j < length); j++) {
  44. if (m[i + j] != 0) {
  45. all_zero = 0;
  46. break;
  47. }
  48. }
  49. if (all_zero < 2) {
  50. print("%p:", (void *)(memory + i));
  51. for (j = 0; j < 16; j++)
  52. print(" %02x", m[i + j]);
  53. print(" ");
  54. for (j = 0; j < 16; j++)
  55. print("%c", isprint(m[i + j]) ? m[i + j] : '.');
  56. print("\n");
  57. } else if (all_zero == 2) {
  58. print("...\n");
  59. }
  60. }
  61. }
  62. void pahexdump(uintptr_t pa, int len)
  63. {
  64. void *v = KADDR(pa);
  65. hexdump(v, len);
  66. }
  67. /* Print a string, with printables preserved, and \xxx where not possible. */
  68. int printdump(char *buf, int buflen, uint8_t *data)
  69. {
  70. int ret = 0;
  71. int ix = 0;
  72. while (ret < buflen) {
  73. if (isprint(data[ix])) {
  74. buf[ret++] = data[ix];
  75. } else if (ret < buflen - 4) {
  76. /* guarantee there is room for a \xxx sequence */
  77. ret += snprint(&buf[ret], buflen-ret, "\\%03o", data[ix]);
  78. } else {
  79. break;
  80. }
  81. ix++;
  82. }
  83. return ret;
  84. }