#include #include #include "dmm_config.h" #ifdef HAVE_LOCKS #include "posix_lock.h" #endif /* HAVE_LOCKS */ #include "dmm_init.h" #include "other.h" #include "sys_alloc.h" #include "block_header.h" #include "dmm_adaptor.h" void * custom_ahmalloc(allocator_t* allocator, heap_t* heap, size_t size) { void *ptr; int heap_id, fixed_list_id, i; maptable_node_t *current_maptable_node; void *current_block, *previous_block; // Go to the system allocator if none was given if(allocator == NULL) { allocator = &systemallocator; if(allocator->initialized != true) { dmm_init(allocator); } } if(heap == NULL) { heap_id = map_thread_heap(); heap = &allocator->heaps[heap_id]; } ptr = NULL; previous_block = NULL; #ifdef HAVE_LOCKS posix_lock(heap); #endif /* HAVE_LOCKS */ fixed_list_id = map_size_to_list(heap, req_padding(size)); // If a fixed list is found, do a first fit if(fixed_list_id != -1) { current_maptable_node = heap->maptable_head; // traverse through the maptable node list if(fixed_list_id != 0) { for(i = 1; i < fixed_list_id; i++) { current_maptable_node = current_maptable_node->next; } } if(current_maptable_node->fixed_list_head != NULL) { ptr = current_maptable_node->fixed_list_head; current_maptable_node->fixed_list_head = get_next(ptr); } } if(ptr == NULL) { // first fit from free list for(current_block = heap->free_list_head; current_block != NULL; current_block = get_next(current_block)) { if(get_size(current_block) >= size) { if(current_block == heap->free_list_head) { heap->free_list_head = get_next(ptr); } else { set_next(previous_block, get_next(current_block)); } ptr = current_block; break; } previous_block = current_block; } } if(ptr == NULL) { ptr = sys_alloc(heap, size); } set_requested_size(ptr, size); set_next(ptr, heap->used_blocks_head); heap->used_blocks_head = ptr; // Begin of Stats heap->dmm_stats.live_objects += 1; heap->dmm_stats.num_malloc += 1; // End of Stats // Refresh the state of the heap allocator if a certain number of // malloc's has been served already // TODO Define 50 as a constant if(heap->dmm_stats.num_malloc % 50) { state_refresh(heap); } #ifdef HAVE_LOCKS posix_unlock(heap); #endif /* HAVE_LOCKS */ return ptr; } void * custom_malloc(size_t size) { return custom_ahmalloc(NULL, NULL, size); }