Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <kernel/memory.hxx>
- using namespace memory;
- heap::heap(uint32_t bsize) {
- this->fblock = 0;
- this->bsize = bsize;
- }
- void heap::add(uintptr_t address, uint32_t size) {
- block *b;
- uint32_t *stack;
- uint32_t stacksize, slotres;
- b = (block*)address;
- /* Interpret the pointer
- as an address to a block. */
- b->next = this->fblock;
- /* Next block should point
- to the heap's own. */
- this->fblock = b;
- /* The heap's block should point to
- the block defined here. */
- b->size = size;
- size = size - sizeof(block);
- b->max = size / (this->bsize);
- stacksize = b->max * 4;
- slotres = (stacksize / this->bsize) *
- this->bsize < stacksize ?
- (stacksize / this->bsize) + 1 : stacksize / this->bsize;
- b->top = slotres;
- stack = (uint32_t*)&b[1];
- for(uint32_t x = slotres; x < b->max; ++x){
- stack[x] = x * this->bsize;
- }
- }
- int* heap::alloc(uint32_t size) {
- uintptr_t ptr;
- uint32_t *stack;
- if(size > this->bsize){
- return 0;
- }
- for(block *b = this->fblock; b; b = b->next) {
- if(b->top != b->max){
- stack = (uint32_t*)&b[1];
- ptr = stack[b->top++];
- ptr = (uintptr_t)&b[1] + ptr;
- return (int*)ptr;
- }
- }
- return 0;
- }
- void heap::free(int* ptr) {
- block *b;
- uintptr_t rptr;
- uint32_t *stack;
- while (*ptr != (int)NULL) {
- *ptr = (int)NULL;
- ptr++;
- }
- //find block
- rptr = (uintptr_t)ptr;
- for(b = this->fblock; b; b = b->next) {
- if(rptr > (uintptr_t)b && rptr < ((uintptr_t)b + b->size)) {
- break;
- }
- }
- //make sure we don't corrupt memory
- if (!b) {
- return;
- }
- //get stack
- stack = (uint32_t*)&b[1];
- stack[--b->top] = rptr - (uintptr_t)&b[1];
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement