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. for (i = 0; i < length; i += 16) {
  40. int j;
  41. all_zero++;
  42. for (j = 0; (j < 16) && (i + j < length); j++) {
  43. if (m[i + j] != 0) {
  44. all_zero = 0;
  45. break;
  46. }
  47. }
  48. if (all_zero < 2) {
  49. iprint("%p:", (void *)(memory + i));
  50. for (j = 0; j < 16; j++)
  51. iprint(" %02x", m[i + j]);
  52. iprint(" ");
  53. for (j = 0; j < 16; j++)
  54. iprint("%c", isprint(m[i + j]) ? m[i + j] : '.');
  55. iprint("\n");
  56. } else if (all_zero == 2) {
  57. iprint("...\n");
  58. }
  59. }
  60. }
  61. void pahexdump(uintptr_t pa, int len)
  62. {
  63. void *v = KADDR(pa);
  64. hexdump(v, len);
  65. }
  66. /* Print a string, with printables preserved, and \xxx where not possible. */
  67. int printdump(char *buf, int buflen, uint8_t *data)
  68. {
  69. int ret = 0;
  70. int ix = 0;
  71. while (ret < buflen) {
  72. if (isprint(data[ix])) {
  73. buf[ret++] = data[ix];
  74. } else if (ret < buflen - 4) {
  75. /* guarantee there is room for a \xxx sequence */
  76. ret += snprint(&buf[ret], buflen-ret, "\\%03o", data[ix]);
  77. } else {
  78. break;
  79. }
  80. ix++;
  81. }
  82. return ret;
  83. }