Xv6 with picoc & Linkage editor
v1.0
The project delineate mutual cohesion between c library, linkage editor ( linker), interpreter and operating system by porting the same on xv6 kernel
|
00001 #include "types.h" 00002 #include "stat.h" 00003 #include "user.h" 00004 #include "param.h" 00005 00006 // Memory allocator by Kernighan and Ritchie, 00007 // The C programming Language, 2nd ed. Section 8.7. 00008 00009 typedef long Align; 00010 00011 union header { 00012 struct { 00013 union header *ptr; 00014 uint size; 00015 } s; 00016 Align x; 00017 }; 00018 00019 typedef union header Header; 00020 00021 static Header base; 00022 static Header *freep; 00023 00024 void 00025 free(void *ap) 00026 { 00027 Header *bp, *p; 00028 00029 bp = (Header*)ap - 1; 00030 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 00031 if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 00032 break; 00033 if(bp + bp->s.size == p->s.ptr){ 00034 bp->s.size += p->s.ptr->s.size; 00035 bp->s.ptr = p->s.ptr->s.ptr; 00036 } else 00037 bp->s.ptr = p->s.ptr; 00038 if(p + p->s.size == bp){ 00039 p->s.size += bp->s.size; 00040 p->s.ptr = bp->s.ptr; 00041 } else 00042 p->s.ptr = bp; 00043 freep = p; 00044 } 00045 00046 static Header* 00047 morecore(uint nu) 00048 { 00049 char *p; 00050 Header *hp; 00051 00052 if(nu < 4096) 00053 nu = 4096; 00054 p = sbrk(nu * sizeof(Header)); 00055 if(p == (char*)-1) 00056 return 0; 00057 hp = (Header*)p; 00058 hp->s.size = nu; 00059 free((void*)(hp + 1)); 00060 return freep; 00061 } 00062 00063 void* 00064 malloc(uint nbytes) 00065 { 00066 Header *p, *prevp; 00067 uint nunits; 00068 00069 nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 00070 if((prevp = freep) == 0){ 00071 base.s.ptr = freep = prevp = &base; 00072 base.s.size = 0; 00073 } 00074 for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 00075 if(p->s.size >= nunits){ 00076 if(p->s.size == nunits) 00077 prevp->s.ptr = p->s.ptr; 00078 else { 00079 p->s.size -= nunits; 00080 p += p->s.size; 00081 p->s.size = nunits; 00082 } 00083 freep = prevp; 00084 return (void*)(p + 1); 00085 } 00086 if(p == freep) 00087 if((p = morecore(nunits)) == 0) 00088 return 0; 00089 } 00090 }