Ptrs. And Memoryblocks. Oh My !

Sure I badly paraphrased the line from Wizard of Oz but this isn’t a word junkies blog. Or a Word© junkies blog either 🙂

Stupid tech jokes aside this one is about Ptr and Memoryblock and their interesting relationship.

In Xojo a memory block is just that – a chunk of memory acquired in one of many ways, that usually can be manipulated in lots of ways. They can be really useful for all kinds of tasks like dealing with byte oriented data (files, binary streams) as well as more high level things like manipulating UTF-8 data since at the very lowest level UTF-8 is just special runs of bytes that we interpret as “characters” or “text”.

But then, everything in a program is JUST runs of bytes that are interpreted in special ways depending on what the bytes are, whether they happen to be “data” or “code”.

And this is where things get interesting.

A recent post on the forums did

dim p as ptr = d //d is a delegate like "AddressOf methodName"
dim mb as MemoryBlock = p
dim id as string = Crypto.SHA256(mb)

So exactly whats going on here and why might this be a problem and why might it cause a crash ?

AddressOf returns, as it states, the in memory address of whatever method you ask for. And this address is a ptr – a specific place in the running instance as loaded at this time which _could_ be different next time you run the application. This tends to be an OS level security measure.

Memory blocks CAN be created from a Ptr. Usually this is so you can use it with a declare that creates and allocates some memory and returns a pointer to that allocated chunk of memory. But, a pointer is a pointer is a pointer. So it really doesn’t matter where that pointer came from. And with this particular pointer

dim mb as MemoryBlock = p

being the address of some method, or executable code, it just happens to be in our program and its memory space. But it is relevant that is its executable code.

And then when this code tries to access that ptr it tries to READ the code, not just the ptr, since the base address of the memory block is just where “the bytes that make up thi memoryblock” are.

Crypto may die for one of two reasons. First – the OS may bock you from reading the executable code this way. Secondly Crypto would need to know how much data to encrypt. And a memoryblock created from a Ptr doesn’t have a known size. So SHA256 may just try and read -1 byes (which is a HUGE unsigned number) and crash because of that.

If you’re going to mess with Ptr’s & memoryblocks make sure you know what toes you’re prepared to lose 🙂