附上malloc/free代码,不完整,只能大概了解它的机制:void free(void* p)
{
if(!p) return 0;
r3 = __microlib_freelist;
void* r2 = 0;
p -= 4;
void* r1 = *r3; // r1 = r3->node
while(r1)
{
if(r1 > p) break;
r2 = r1;
r1 = *(r1 + 4); // r1 = r1->next
}
if(!r2)
r3->node = p;
else
{
r3 = *r2;
r4 = p - r2;
if(r4 != r3)
*(r2 + 4) = p;
else
{
p = *p;
p += r3;
}
}
}
typedef struct
{
uint size;
void* next;
} Node;
__microlib_freelist:
Node* _freelist;
__microlib_freelist_initialised:
int _freelist_initialised = 0;
void* malloc(int size)
{
/*r0 += 0x0b;
r0 >>= 3;
r0 <<= 3;*/
r1 = (size + 11) & 0xFFFFFFF8;
r7 = __microlib_freelist_initialised;
r6 = 0;
/*r2 = __microlib_freelist;
if(!*r2 && !*r7)*/
if(!_freelist && !_freelist_initialised)
{
/*r2 = __microlib_freelist;
r0 = __heap_base + 4;
*r2 = r0;
r2 = __heap_limit;
r2 -= r0;
r2 &= 0xFFFFFFF0;
*r0 = r2;
*(r0 + 4) = 0;
*r7 = 1;*/
_freelist = (Node*)(__heap_base + 4);
_freelist->size = (__heap_limit - __heap_base - 4) & 0xFFFFFFF8;
_freelist->next = 0;
_freelist_initialised = 1;
}
//r2 = __microlib_freelist;
r0 = _freelist;
while(true)
{
/*r0 = *r2;
if(!r0)
{
r0 = r6;
break;
}*/
//r0 = *r2;
if(!r0) return 0;
//r3 = *r0;
r3 = r0->size;
if(r3 <= r1) break;
//r2 = r0 + 4;
//r2 = r0->next;
r0 = *(r0->next);
}
if(r3 <= r1)
{
//r3 = *(r0 + 4);
/*r3 = _freelist->next;
*r2 = r3;*/
_freelist->size = r1;
_freelist = _freelist->next;
return &;
}
else
{
/*r4 = r3 - r1;
r3 = r0 + r1;
r5 = *(r0 + 4);
*r3 = r4;
r3 +=4 ;
*(r3 + 4) = r5;
r3 +=4 ;
r3 -= 8;// 减8为了回到r3开始*/
Node* lst = (void*)_freelist + r1;
lst->size = _freelist->size - r1;
lst->next = _freelist->next;
_freelist->size = r1;
_freelist = lst;
return &lst->next;
}
return r0;
}
|