malloc-find.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Find the starting address of a malloc'd block, from anywhere inside it.
  2. Copyright (C) 1995 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library. Its master source is NOT part of
  4. the C library, however. The master source lives in /gd/gnu/lib.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Library General Public License as
  7. published by the Free Software Foundation; either version 2 of the
  8. License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Library General Public License for more details.
  13. You should have received a copy of the GNU Library General Public
  14. License along with the GNU C Library; see the file COPYING.LIB. If
  15. not, write to the Free Software Foundation, Inc., 675 Mass Ave,
  16. Cambridge, MA 02139, USA. */
  17. #ifndef _MALLOC_INTERNAL
  18. #define _MALLOC_INTERNAL
  19. #include <malloc.h>
  20. #endif
  21. /* Given an address in the middle of a malloc'd object,
  22. return the address of the beginning of the object. */
  23. __ptr_t
  24. malloc_find_object_address (ptr)
  25. __ptr_t ptr;
  26. {
  27. __malloc_size_t block = BLOCK (ptr);
  28. int type = _heapinfo[block].busy.type;
  29. if (type == 0)
  30. {
  31. /* The object is one or more entire blocks. */
  32. __malloc_ptrdiff_t sizevalue = _heapinfo[block].busy.info.size;
  33. if (sizevalue < 0)
  34. /* This is one of the blocks after the first. SIZEVALUE
  35. says how many blocks to go back to find the first. */
  36. block += sizevalue;
  37. /* BLOCK is now the first block of the object.
  38. Its start is the start of the object. */
  39. return ADDRESS (block);
  40. }
  41. else
  42. {
  43. /* Get the size of fragments in this block. */
  44. __malloc_size_t size = 1 << type;
  45. /* Turn off the low bits to find the start address of the fragment. */
  46. return _heapbase + (((char *) ptr - _heapbase) & ~(size - 1));
  47. }
  48. }