How the Nasal GC works
Objective
Document how the existing Nasal GC works, so that it can be fully understood, before alternatives or additional implementations are added (feedback appreciated).
Memory allocation
All memory allocation takes place via wrappers in misc.c:
void naFree(void* m) { free(m); }
void* naAlloc(int n) { return malloc(n); }
void* naRealloc(void* b, int n) { return realloc(b, n); }
void naBZero(void* m, int n) { memset(m, 0, n); }
Allocating Nasal types
Nasal types (scalars, vectors, hashes, funcs, ghosts) are allocated via wrappers in misc.c.
These wrappers are:
- naNewString(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line77
- naNewVector(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line87
- naNewHash(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line94
- naNewCode(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line101
- naNewCCode(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line106
- naNewFunc(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line113
- naNewGhost(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line122
- naNewGhost2(): https://gitorious.org/fg/simgear/blobs/next/simgear/nasal/misc.c#line135
As can be seen, the key allocator function is naNew(). naNew() is really just a fancy malloc() replacement, i.e. it's just getting passed the size of the requested memory region.
The naNew() function is also implemented in misc.c, see line 66:
naRef naNew(struct Context* c, int type)
{
naRef result;
if(c->nfree[type] == 0)
c->free[type] = naGC_get(&globals->pools[type],
OBJ_CACHE_SZ, &c->nfree[type]);
result = naObj(type, c->free[type][--c->nfree[type]]);
naTempSave(c, result);
return result;
}
Pool storage
The interesting part is the naGC_get() function which isn't directly mapped to naAlloc() or malloc(), but instead manages the Nasal memory pools. For each native Nasal data type, there are separate memory pools in globals->[n]. The index (n) is one of T_VEC, T_HASH, T_FUNC etc.