heap_debug.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * libc/stdlib/malloc/heap_debug.c -- optional heap debugging routines
  3. *
  4. * Copyright (C) 2002 NEC Corporation
  5. * Copyright (C) 2002 Miles Bader <miles@gnu.org>
  6. *
  7. * This file is subject to the terms and conditions of the GNU Lesser
  8. * General Public License. See the file COPYING.LIB in the main
  9. * directory of this archive for more details.
  10. *
  11. * Written by Miles Bader <miles@gnu.org>
  12. */
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include "heap.h"
  18. #ifdef HEAP_DEBUGGING
  19. int __heap_debug = 0;
  20. #endif
  21. static void
  22. __heap_dump_freelist (struct heap *heap)
  23. {
  24. struct heap_free_area *fa;
  25. for (fa = heap->free_areas; fa; fa = fa->next)
  26. fprintf (stderr,
  27. " 0x%lx: 0x%lx - 0x%lx (%d)\tP=0x%lx, N=0x%lx\n",
  28. (long)fa,
  29. (long)HEAP_FREE_AREA_START (fa),
  30. (long)HEAP_FREE_AREA_END (fa),
  31. fa->size,
  32. (long)fa->prev,
  33. (long)fa->next);
  34. }
  35. /* Output a text representation of HEAP to stderr, labelling it with STR. */
  36. void
  37. __heap_dump (struct heap *heap, const char *str)
  38. {
  39. static int recursed = 0;
  40. if (! recursed)
  41. {
  42. __heap_check (heap, str);
  43. recursed = 1;
  44. fprintf (stderr, " %s: heap @0x%lx:\n", str, (long)heap);
  45. __heap_dump_freelist (heap);
  46. recursed = 0;
  47. }
  48. }
  49. /* Do some consistency checks on HEAP. If they fail, output an error
  50. message to stderr, and exit. STR is printed with the failure message. */
  51. void
  52. __heap_check (struct heap *heap, const char *str)
  53. {
  54. struct heap_free_area *fa, *prev;
  55. for (prev = 0, fa = heap->free_areas; fa; prev = fa, fa = fa->next)
  56. if (fa->prev != prev)
  57. {
  58. if (str)
  59. fprintf (stderr, "\nHEAP CHECK FAILURE %s: ", str);
  60. else
  61. fprintf (stderr, "\nHEAP CHECK FAILURE: ");
  62. fprintf (stderr,
  63. " prev pointer corrupted: P=0x%lx should be 0x%lx\n",
  64. (long)fa->prev, (long)prev);
  65. fprintf (stderr, "\nheap:\n");
  66. __heap_dump_freelist (heap);
  67. exit (22);
  68. }
  69. }