njvm/GC.c
nilspolek 35f051b5da gc
2024-01-28 16:45:50 +01:00

106 lines
2.7 KiB
C

#ifndef GC
#define GC
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "objref.c"
#include "instruktion.c"
bool halbspeicher1IsActiv = true;
unsigned char* halbspeicher1;
unsigned char* halbspeicher2;
unsigned char* freizeiger;
unsigned int groesse;
void initHeap(unsigned int size){
groesse = size*1024/2;
if((halbspeicher1 = malloc(groesse)) == NULL) perror("malloc");
if((halbspeicher2 = malloc(groesse)) == NULL) perror("malloc");
freizeiger = halbspeicher1;
}
ObjRef copyObjToFreeMem(ObjRef obj){
ObjRef copy = (ObjRef) halbspeicher2[freizeiger];
unsigned int size = (IS_PRIMITIVE(obj))? obj->size : GET_ELEMENT_COUNT(obj)* sizeof(void *);
memcpy((void *) halbspeicher2[freizeiger], obj, size);
freizeiger += size;
return copy;
}
void setBrokenHeart(ObjRef obj, bool val){
//TODO
}
bool getBrokenHeart(ObjRef obj){
//TODO
return true;
}
void setForwardPointer(ObjRef obj, void* ref){
//TODO
}
void *getForwardPointer(ObjRef obj){
//TODO
return malloc(0);
}
ObjRef reallocate(ObjRef orig){
ObjRef copy;
if(orig == NULL){
copy == NULL;
}else{
if(getBrokenHeart(orig)){
setForwardPointer(copy,orig);
}else{
copy = copyObjToFreeMem(orig);
setBrokenHeart(orig,true);
setForwardPointer(orig,copy);
}
}
return copy;
}
unsigned int getSize(ObjRef obj){
return (IS_PRIMITIVE(obj))? obj->size : GET_ELEMENT_COUNT(obj)* sizeof(void *);
}
void scan(void){
void *scan = halbspeicher1;
while (scan < freizeiger){
if(!IS_PRIMITIVE((ObjRef)scan)){
for (unsigned int i = 0; i < GET_ELEMENT_COUNT((ObjRef)scan); i += getSize(GET_REFS_PTR((ObjRef)scan)[i])) {
GET_REFS_PTR((ObjRef)scan)[i] = reallocate(GET_REFS_PTR((ObjRef)scan)[i]);
}
}
scan += getSize((ObjRef)scan);
}
}
void *alloc(unsigned int size){
if((&freizeiger - &halbspeicher1)/8 + size > groesse) {
printf("Heap Overflow\n");
exit(EXIT_FAILURE);
}
// Set broken heart to false
setBrokenHeart((ObjRef)freizeiger,false);
freizeiger += sizeof(bool) + sizeof(void *);
void *ptr = &freizeiger;
freizeiger += size;
return ptr;
}
void swap(void){
unsigned char *tmp = halbspeicher1;
halbspeicher1 = halbspeicher2;
halbspeicher2 = tmp;
freizeiger = halbspeicher1;
halbspeicher1IsActiv = !halbspeicher1IsActiv;
}
void triggerGC(void){
printf("GC triggered\n");
//TODO
}
void copy(){
ObjRef *test;
unsigned int objResSize = 2;
if((test = malloc(2*sizeof(test)))==NULL) perror("malloc");
for (int i = 0; i < objResSize; ++i) {
}
}
#endif