Friday, July 6, 2007

My OMGWTF Calculator

A while back, I submitted an entry to the Worse than Failure Olympiad of Misguided Geeks contest. I didn't win, but I thought my entry was somewhat clever.

The contest was to implement a 4-function calculator in the most "WTF" way possible. My entry took advantage of the fact that floating point representation of the correct result of each test case was also an invalid memory address. I performed the calculations in the expected way, but instead of returning the result, I attempted to write to that memory location.
sprintf( (char *) *(int *) &r, "paula = brillant");
There was some amount of type punning that needed to happen in order to maintain the float representation of the result, as you can see.

I set up a signal handler to handle SIGSEGV (segmentation fault), and used setjmp/longjmp to return the invalid address/correct result at a known-good location in the program. I set up a similar handler for SIGFPE (floating point exception) to correctly report an error when attempting to divide by zero. The meat of it occurs in this conditional:
if(sigsetjmp(err_env, 1)) {
SetDisplayText("Err");
} else if(int result = sigsetjmp(ans_env, 1)) {
siginfo_t *sigInfo = (siginfo_t *)result;
sprintf(newText, "%g", *(float *)&sigInfo->si_addr);
SetDisplayText(newText);
} else {
DoOperation(g_Operator, op1, op2);
}
As you can see, the result is contained in the si_addr field of the appropriate siginfo_t struct.

Some of the winners obviously put a lot of thought and time into their entries, and I was very impressed at the creativity they showed. I'm also proud of my little idea, and I had a lot of fun writing it!

No comments: