How memory allocation works in Kenaz

Memory allocation is a vital feature for any programming language. Kenaz allows memory allocation to be performed using the "new" operator, like C++/Java/C#/.....
MyObject obj = new MyObject();
Nothing really fancy here. But how is the memory allocation performed ? As previously stated, Kenaz code needs a loader in order to load and execute the code. This loader is written in C++, and so this is the loader which is going to do the memory allocation using the C++ new operator. The only things that is left to do, is to find out how many memory space should be allocated for a given object.
Building a skeleton object
For each kenaz class/interface, there is an associated descriptor. This descriptor stores how many member variables there are (and their type), what and how many functions does the class/interface have, and so forth. Using those informations, the loader is able to build a skeleton object. The skeleton object will contains one or more V-table (cf inside Kenaz : kenaz loader) as well as memory space for the member variable, initially set to null, 0 or false, according to their type. When allocating a Kenaz object, the loader will make a copy of this skeleton object and return it.
Binding between Kenaz code and C++ :
tells the loader what kind of object we wants to allocate
Now we are going to dig into the Kenaz compiler. Suppose we have the following Kenaz code :
MyObject obj = new MyObject();
The Kenaz compiler will turn this code into something like this :
push 0xcdcdcdcd 	[type(MyObject)] ;
mov  eax, 0xcdcdcdcd    [function(System.alloc)];
call eax;
And this is the code that is going to be stored. What you see into brackets are code annotations, or references. Code stored is eventually later loaded, and during the loading a reference solving step is performed, using the given annotation. The first annotation (type) tells the code loader to repace the 0xcdcdcdcd with a pointer to the object descriptor for the "MyObject" class, while the second indicates that the 0xcdcdcdcd should be replaced with the address of the "System.alloc" function. 0xcdcdcdcd is used instead of 0, because code like
mov  eax, 0
will maybe be turned into the following code by the peephole optimizer :
xor eax, eax;
Preventing us to perform any code modifications without producing illegal code ('mov eax,0' needs 5 opcodes, leaving us room to apply our modification, while 'xor eax,eax' only needs 2 opcodes. Besides, we wants to 'mov' and not to 'xor').
After the references are replaced and the code executed, we will jump into a C++ function :
void * alloc(ZGCClassType *type)
{
    //copy the skeleton object and return it
}
ZGCClassType is the wanted object descriptor, allowing us to perform the memory allocation. Same principes is applied to memory allocation of array, the only difference reside in the addition of a new parameter, the size of the array.

top of page