#include #include #include #include #define _VALLOC_PAGE_BOUNDRY 0 void* calloc(size_t num, size_t size) { unsigned char* tempOut = (unsigned char*)malloc(num * size); if(tempOut == NULL) return NULL; memset(tempOut, 0x00, (num * size)); return (void*)tempOut; } void* memalign(size_t align, size_t size) { if((align == 0) || ((align & (align -1)) != 0)) { errno = EINVAL; return NULL; } void* tempOut = malloc(size); if(tempOut == NULL) return NULL; if(((uintptr_t)tempOut & (align - 1)) == 0) return tempOut; free(tempOut); // TODO - Work out a way to allocate and free aligned values safely. return NULL; } void* valloc(size_t size) { // TODO - Work out actual page boundary. return memalign(_VALLOC_PAGE_BOUNDRY, size); } // wrapper implementation from here on static _malloc_list_node* _malloc_list_root = NULL; // don't call the wrappers from the wrappers #undef malloc #undef realloc #undef free void* _malloc_list_add(void* region) { _malloc_list_node* first = _malloc_list_root; _malloc_list_node* new_node = malloc(sizeof(_malloc_list_node)); if (new_node == NULL) { free(region); return NULL; } new_node->region = region; new_node->next = first; _malloc_list_root = new_node; return region; } void* _malloc(size_t numbytes) { void* region; // allocate region region = malloc(numbytes); if (region == NULL) return NULL; // return region return _malloc_list_add(region); } void* _realloc(void* region, size_t numbytes) { // should we behave as malloc? if (region == NULL) { return _malloc(numbytes); } // should we behave as free? if (numbytes == 0) { _free(region); return NULL; } // reallocate region, find region in list _malloc_list_node* cur = _malloc_list_root; while (cur != NULL) { if (cur->region == region) { void* temp = realloc(region, numbytes); if (temp != NULL) { cur->region = temp; } return temp; } cur = cur->next; } // this is not supposed to happen return NULL; } void _free(void* region) { if (region == NULL) return; free(region); if (_malloc_list_root == NULL) return; if (_malloc_list_root->region == region) { _malloc_list_node* temp = _malloc_list_root->next; free(_malloc_list_root); _malloc_list_root = temp; return; } _malloc_list_node* cur = _malloc_list_root; _malloc_list_node* next; while (1) { next = cur->next; if (next == NULL) return; if (next->region == region) { cur->next = next->next; free(next); return; } cur = next; } } void _malloc_reclaim() { _malloc_list_node* cur = _malloc_list_root; _malloc_list_root = NULL; while (cur != NULL) { _malloc_list_node* temp = cur; cur = cur->next; free(temp->region); free(temp); } return; }