realloc.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * libc/stdlib/malloc-zarg/realloc.c -- realloc function
  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 <string.h>
  15. #include <sys/mman.h>
  16. #include "malloc.h"
  17. #include "heap.h"
  18. void *realloc (void *mem, size_t new_size)
  19. {
  20. if (! mem)
  21. return malloc (new_size);
  22. else
  23. {
  24. void *base_mem = (size_t *)mem - 1;
  25. size_t size = *(size_t *)base_mem;
  26. MALLOC_DEBUG ("realloc: 0x%lx, %d (base = 0x%lx, total_size = %d)\n",
  27. (long)mem, new_size, (long)base_mem, size);
  28. if (new_size <= size)
  29. return mem;
  30. else
  31. {
  32. void *new_mem = 0;
  33. size_t ext_size = new_size - size;
  34. void *ext_addr = (char *)base_mem + ext_size;
  35. if (size >= MALLOC_MMAP_THRESHOLD)
  36. /* Try to extend this block in place using mmap. */
  37. {
  38. ext_size += MALLOC_ROUND_UP_TO_PAGE_SIZE (ext_size);
  39. new_mem = mmap (ext_addr, ext_size, PROT_READ | PROT_WRITE,
  40. MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS, 0, 0);
  41. if (new_mem == MAP_FAILED)
  42. /* Can't do it. */
  43. ext_size = 0;
  44. }
  45. else
  46. ext_size = __heap_alloc_at (&__malloc_heap, ext_addr, ext_size);
  47. if (! ext_size)
  48. /* Our attempts to extend MEM in place failed, just
  49. allocate-and-copy. */
  50. {
  51. new_mem = malloc (new_size);
  52. if (new_mem)
  53. {
  54. memcpy (new_mem, mem, size);
  55. free (mem);
  56. }
  57. }
  58. if (new_mem)
  59. MALLOC_DEBUG (" realloc: returning 0x%lx"
  60. " (base:0x%lx, total_size:%d)\n",
  61. (long)new_mem, (long)new_mem - sizeof(size_t), size);
  62. return new_mem;
  63. }
  64. }
  65. }