#include #include "dmm_config.h" #ifdef HAVE_LOCKS #include "posix_lock.h" #endif /* HAVE_LOCKS */ #include #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; #ifndef WITH_MEMORY_SPACE_AWARENESS /* Go to the system allocator if none was given */ if(allocator == NULL) { allocator = &systemallocator; if(allocator->initialized != true) { initialize_allocator(allocator); } } if(heap == NULL) { heap_id = map_thread_heap(); heap = &allocator->heaps[heap_id]; } #endif /* WITH_MEMORY_SPACE_AWARENESS */ ptr = NULL; previous_block = NULL; #ifdef HAVE_LOCKS posix_lock(heap); #endif /* HAVE_LOCKS */ /* Perform exact fit to fixed lists */ 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(current_block); } else { set_next(previous_block, get_next(current_block)); } ptr = current_block; break; } previous_block = current_block; } } if(ptr != NULL) { /* FIXME To be refactored - START */ set_requested_size(ptr, size); mark_used(ptr); /* FIXME split to be put here */ /* Update the used blocks list */ 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 */ /* FIXME To be refactored - END */ } if(ptr == NULL) { ptr = sys_alloc(allocator, heap, size); } /* 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) { malloc_state_refresh(heap); } #ifdef HAVE_LOCKS posix_unlock(heap); #endif /* HAVE_LOCKS */ return ptr; } /* Currently all the memory space aware allocators are pre-initialized, so * we do not expect any custom_ahmalloc call without knowing which allocator * and heap are to be used. */ #ifndef WITH_MEMORY_SPACE_AWARENESS void * custom_malloc(size_t size) { return custom_ahmalloc(NULL, NULL, size); } #endif /* WITH_MEMORY_SPACE_AWARENESS */