Custom memory allocation in C# Part 4 — Invoking constructor for uninitialized object

This is the fourth part of the Custom memory allocation series. For your convenience you can find other parts in the table of contents in Part 1 — Allocating object on a stack

We already know how to allocate objects on a stack, how to hijack new operator, how to put objects in any place in memory. Today we are going to write simple trivial implementation of memory allocator. Let’s begin.

Introduction

In theory, we already know how to do that. We know how to allocate a piece of memory and how to put object there. However, for now we were working only with simple objects with no constructors (or with empty constructors). We know how to create object somewhere, but we don’t know how to invoke constructor for it without hijacking new operator.

We will write a simple library capable of doing exactly that. We want the following syntax:

So we want to have two things here: first, we want to have a compile time support whether we create object in a correct way (with all parameters correct). Second, we do not want to have any casting. Third, we want to allocate exactly one object — since object creation might be expensive, we do not want to create it on side and copy it somewhere else.

What’s more, our objects need to be casual objects — with constructors, base classes, finalizers, disposable etc. There is no use in memory allocator which is not able to allocate common objects.

Plan

As we can see, we are passing a lambda to allocator method. This takes first requirement: compile time support. Since this lambda is checked by the compiler, we are not able to pass incorrect arguments. What’s more, since this is a lambda, it is not invoked. It only contains all necessary information to be able to execute correctly. We will parse this lambda and extract all informations to create an object.

So our allocator should work as follows:

  • We obtain type of object to create
  • We calculate its size and allocate memory
  • We create an object (by storing its metadata in place)
  • We parse lambda and execute object’s constructor with correct arguments

Everything looks good and we already know how to finish thirst three bullets. Let’s get to the code.

Easier part

We start with the following interface:

We have three methods: first one is the one which we will use. Second one is there so we will be able to free our object.

Let’s see actual implementation:

Lots of code here. Let’s go line by line.

First, we define variables. We store lists of free and occupied chunks as a tuples of integers: first element of a tuple stores the address of the chunk, second element stores the size of the chunk. Next, we store size of a page, a smallest size of allocated chunk we handle. Next, we stores handles to the chunks — we will need to pin them in memory so they are not moved by GC. Finally, flag for IDisposable pattern.

Next goes two important methods. First one dispatches object allocation and invokes constructor using helper class, second one performs actual allocation and performs some accounting — we do not want GC to run destructor of newly created object, we also do not want it to be moved. Rest of the code should be pretty straightforward.

OK, let’s see helper classes:

Most of this code is already covered in this series so should be pretty easy. One important thing to notice here is: we do not zero memory for object (we only zero its syncblock). In production code you probably would want to clear the memory before invoking constructor.

OK, easy part is done. Now we need to parse lambda and invoke constructor.

Harder part

We start with the following:

First, we check whether passed lambda is in form of new something() If it is not then we abort. Next, we create method for invoking constructor and invoke it.

Before we dive into lambda stuff, we need to consider arguments passing. Since lambda might be very complex (instead of just new MyType(1, 2, reference) we might get something like new MyType(1 * 123 + 15, AbstractProviderFactory.GetObject(ref variable), (() => DateTime.Now)())), we do not want to parse every bit of it. Instead, we are going to invoke the lambda. But since we cannot invoke it as a whole (because it would create an object), we will create a lambda for every single parameter passed to new type() and invoke all of them to get the arguments. Simple as that.

OK, so first let’s see LambdaHelper.GetLambda:

We get a piece of lambda responsible for a single parameter. It might be something simple (like constant) or something really complex (with asyncs, factories, reflection, etc). We then wrap this lambda in a function returning object. This function contains exactly one additional instruction: casting retrieved parameter to object. Yes — we might be boxing here. But it is actually good to do that.

Let’s see an example. Imagine that we create an object in this way:

In order to obtain the parameter, we first extract part of lambda working on that parameter (namely AbstractFactory.GetParameter()). Next, we create on the fly the following function:

So we have a function which is capable of extracting the argument. Notice that arguments will be evaluated from left to right and they will be evaluated as usual.

Let’s get back to constructor invocation:

We take all parameters, convert them to functions, compile all of them, and invoke them. Next, we store them in one array of objects and pass to another lambda. So the function we are we want to call should look like this:

So we accept target object to invoke constructor and object array with arguments. Next, we need to flatten this array and pass arguments one by one.

The code is as follows:

First, we create dynamic method accepting two parameters, as described before. Next, we get IL generator and start generating code. We could do the same using reflection as well.

First, we push object reference on the stack. Next, we iterate over all arguments, push on the stack the number of argument (basically, the index in the array), we then load the element from the array and push it on the stack. Finally, we check whether the argument is value type — in that case we unbox the argument.

Next, emit call to constructor and instruction to exit from the function. Finally, we create delegate to the method.

Destructor

We already know how to create an object with lambda, now we need to clean up. Here goes destructor call:

We first try to call Dispose from IDisposable interface. Next, we get handler to Finalize method using reflection and invoke it. This method is the destructor.

Summary

Being able to generate code in runtime is really useful. It is not as useful now when we have lambdas and we can generate them on the fly, however, with raw IL code we can do some really nice tricks. In the next part we are going to revisit once again stack allocation.