123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- #include "custom_malloc.h"
- #ifdef HAVE_LOCKS
- #include "posix_lock.h"
- #endif /* HAVE_LOCKS */
- #include "other.h"
- #include "sys_alloc.h"
- #include "block_header.h"
- #include "dmm_adaptor.h"
- void * custom_malloc(heap_t* heap, size_t size) {
- void *ptr;
- int fixed_list_id, i, found;
- maptable_node_t *current_maptable_node;
- void *current_block, *previous_block;
- ptr = NULL;
- previous_block = NULL;
- #ifdef HAVE_LOCKS
- posix_lock(heap);
- #endif /* HAVE_LOCKS */
- fixed_list_id = map_size_to_list(heap, 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);
- set_requested_size(ptr, size);
- set_next(ptr, heap->used_blocks_head);
- heap->used_blocks_head = ptr;
- }
- }
- if(ptr == NULL) {
- found = 0;
- // 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) {
- ptr = current_block;
- heap->used_blocks_head = ptr;
- if(current_block != heap->free_list_head) {
- set_next(previous_block, get_next(ptr));
- } else {
- heap->free_list_head = get_next(ptr);
- }
- set_requested_size(ptr, size);
- set_next(ptr, heap->used_blocks_head);
- // Begin of Stats
- heap->dmm_stats.live_objects += 1;
- heap->dmm_stats.num_malloc += 1;
- // End of Stats
- #ifdef HAVE_LOCKS
- posix_unlock(heap);
- #endif /* HAVE_LOCKS */
- return ptr;
- }
- previous_block = current_block;
- }
- if(!found) {
- ptr = sys_alloc(heap, size);
- heap->dmm_stats.mem_allocated += req_padding(size);
- heap->dmm_stats.mem_requested += size;
- }
- }
- // 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;
- }
|