heap_alloc.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * libc/stdlib/malloc-zarg/heap_alloc.c -- allocate from a heap
  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 "heap.h"
  15. /* Allocate and return a block at least *SIZE bytes long from HEAP.
  16. *SIZE is adjusted to reflect the actual amount allocated (which may be
  17. greater than requested). */
  18. void *
  19. __heap_alloc (struct heap *heap, size_t *size)
  20. {
  21. struct heap_free_area *fa;
  22. size_t _size = *size;
  23. void *mem = 0;
  24. _size = HEAP_ADJUST_SIZE (_size);
  25. if (_size < sizeof (struct heap_free_area))
  26. /* Because we sometimes must use a freed block to hold a free-area node,
  27. we must make sure that every allocated block can hold one. */
  28. _size = HEAP_ADJUST_SIZE (sizeof (struct heap_free_area));
  29. mutex_lock (heap->lock);
  30. HEAP_DEBUG (heap, "before __heap_alloc");
  31. /* Look for a free area that can contain _SIZE bytes. */
  32. for (fa = heap->free_areas; fa; fa = fa->next)
  33. if (fa->size >= _size)
  34. {
  35. /* Found one! */
  36. mem = HEAP_FREE_AREA_START (fa);
  37. *size = __heap_free_area_alloc (heap, fa, _size);
  38. break;
  39. }
  40. HEAP_DEBUG (heap, "after __heap_alloc");
  41. mutex_unlock (heap->lock);
  42. return mem;
  43. }