custom_malloc.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include "custom_malloc.h"
  2. #ifdef HAVE_LOCKS
  3. #include "posix_lock.h"
  4. #endif /* HAVE_LOCKS */
  5. #include "other.h"
  6. #include "sys_alloc.h"
  7. #include "block_header.h"
  8. #include "dmm_adaptor.h"
  9. void * custom_malloc(heap_t* heap, size_t size) {
  10. void *ptr;
  11. int fixed_list_id, i;
  12. maptable_node_t *current_maptable_node;
  13. void *current_block, *previous_block;
  14. ptr = NULL;
  15. previous_block = NULL;
  16. #ifdef HAVE_LOCKS
  17. posix_lock(heap);
  18. #endif /* HAVE_LOCKS */
  19. fixed_list_id = map_size_to_list(heap, req_padding(size));
  20. // If a fixed list is found, do a first fit
  21. if(fixed_list_id != -1) {
  22. current_maptable_node = heap->maptable_head;
  23. // traverse through the maptable node list
  24. if(fixed_list_id != 0) {
  25. for(i = 1; i < fixed_list_id; i++) {
  26. current_maptable_node = current_maptable_node->next;
  27. }
  28. }
  29. if(current_maptable_node->fixed_list_head != NULL) {
  30. ptr = current_maptable_node->fixed_list_head;
  31. current_maptable_node->fixed_list_head = get_next(ptr);
  32. }
  33. }
  34. if(ptr == NULL) {
  35. // first fit from free list
  36. for(current_block = heap->free_list_head; current_block != NULL;
  37. current_block = get_next(current_block)) {
  38. if(get_size(current_block) >= size) {
  39. if(current_block == heap->free_list_head) {
  40. heap->free_list_head = get_next(ptr);
  41. } else {
  42. set_next(previous_block, get_next(current_block));
  43. }
  44. ptr = current_block;
  45. break;
  46. }
  47. previous_block = current_block;
  48. }
  49. }
  50. if(ptr == NULL) {
  51. ptr = sys_alloc(heap, size);
  52. }
  53. set_requested_size(ptr, size);
  54. set_next(ptr, heap->used_blocks_head);
  55. heap->used_blocks_head = ptr;
  56. // Begin of Stats
  57. heap->dmm_stats.live_objects += 1;
  58. heap->dmm_stats.num_malloc += 1;
  59. // End of Stats
  60. // Refresh the state of the heap allocator if a certain number of
  61. // malloc's has been served already
  62. // TODO Define 50 as a constant
  63. if(heap->dmm_stats.num_malloc % 50) {
  64. state_refresh(heap);
  65. }
  66. #ifdef HAVE_LOCKS
  67. posix_unlock(heap);
  68. #endif /* HAVE_LOCKS */
  69. return ptr;
  70. }