custom_malloc.c 2.3 KB

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