Friday, September 28, 2007

Never say never

Well, it's been a while since my last post. Actually, I moved sometime in July, so it's been a while since I had internet at home, let alone posted anything. And I went to Usenix in Boston last month, and visited a friend in Colorado last week. Soo... anyways, I did manage to sneak in one upload of code a week or so ago, and ended up doing exactly what I said wouldn't happen in the last blog post, namely:

"Sooo, yah, dynamically creating functions - ain't gonna happen."

Now, granted I gave myself one little loophole:

"Unless you want to drop into asm and self-modifying code."

So, basically, I decided I really did want to get something like reflection in C++, to avoid the inevitable:

switch( request )
{
case 1:
function 1
case 2:
funciton 2
....
}

So, what the heck, I thought, I'll try writing some assembly to generate my function calls at runtime. To make a long story short, you create a buffer of machine code, basically your standard "trampoline" code, but on the heap, and call the buffer. The downside is the code needs to be ported if you want to run it on, say, a Mac. The upside is the code is relatively short (should be easy to port). Also, C is flexible enough that the transition from 32 bit -> 64 bit should be a matter of fixing bugs, not rewriting code. Which is good, because I'm writing this blog on my new 64 bit laptop :).

The real downside to this code is it can be a pain to debug. Luckily, I've worked with enough asm at this point, so when the debugger just gives up and spits out an address, it actually is giving me useful information. And I thought those asm/computer architecture classes I took so long ago would have no practical applications. Now I use them at work and for play. C'est la vie.

My first rough draft of dynamically generated function calls is up now. Still needs work to round it out, and I still need a way to generate metadata about my classes, so clients can generate requests appropriately (c++2xml?). Anywho, that's it for now.

cheers!

No comments: