Advertisement
konalisp

memory.cxx

Jan 21st, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <kernel/memory.hxx>
  2. using namespace memory;
  3.  
  4. heap::heap(uint32_t bsize) {
  5.     this->fblock = 0;
  6.     this->bsize = bsize;
  7. }
  8.  
  9. void heap::add(uintptr_t address, uint32_t size) {
  10.     block *b;
  11.     uint32_t *stack;
  12.     uint32_t stacksize, slotres;
  13.    
  14.     b = (block*)address;
  15.     /* Interpret the pointer
  16.        as an address to a block. */
  17.    
  18.     b->next = this->fblock;
  19.     /* Next block should point
  20.        to the heap's own. */
  21.    
  22.     this->fblock = b;
  23.     /* The heap's block should point to
  24.        the block defined here. */
  25.    
  26.     b->size = size;
  27.    
  28.     size = size - sizeof(block);
  29.    
  30.     b->max = size / (this->bsize);
  31.    
  32.     stacksize = b->max * 4;
  33.    
  34.     slotres = (stacksize / this->bsize) *
  35.         this->bsize < stacksize ?
  36.                   (stacksize / this->bsize) + 1 : stacksize / this->bsize;
  37.    
  38.     b->top = slotres;
  39.    
  40.     stack = (uint32_t*)&b[1];
  41.    
  42.     for(uint32_t x = slotres; x < b->max; ++x){
  43.         stack[x] = x * this->bsize;
  44.     }
  45. }
  46.  
  47. int* heap::alloc(uint32_t size) {
  48.     uintptr_t ptr;
  49.     uint32_t *stack;
  50.    
  51.     if(size > this->bsize){
  52.         return 0;
  53.     }
  54.    
  55.     for(block *b = this->fblock; b; b = b->next) {
  56.         if(b->top != b->max){
  57.             stack = (uint32_t*)&b[1];
  58.             ptr = stack[b->top++];
  59.             ptr = (uintptr_t)&b[1] + ptr;
  60.             return (int*)ptr;
  61.         }
  62.     }
  63.    
  64.     return 0;
  65. }
  66.  
  67. void heap::free(int* ptr) {
  68.     block *b;
  69.     uintptr_t rptr;
  70.     uint32_t *stack;
  71.    
  72.     while (*ptr != (int)NULL) {
  73.         *ptr = (int)NULL;
  74.         ptr++;
  75.     }
  76.    
  77.     //find block
  78.     rptr = (uintptr_t)ptr;
  79.     for(b = this->fblock; b; b = b->next) {
  80.         if(rptr > (uintptr_t)b && rptr < ((uintptr_t)b + b->size)) {
  81.             break;
  82.         }
  83.     }
  84.    
  85.     //make sure we don't corrupt memory
  86.     if (!b) {
  87.         return;
  88.     }
  89.    
  90.     //get stack
  91.     stack = (uint32_t*)&b[1];
  92.    
  93.     stack[--b->top] = rptr - (uintptr_t)&b[1];
  94.    
  95.     return;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement