Song of The Day: Inside Out - Artist: Eve 6

Sree Kotay recently wrote an interesting blog entry about finding a faster and better mechanism to detect integer overflow. The entry for those interested is here.

In response to it and to a couple of comments (e.g., from Michael Herf), I wrote a simple program, that uses the SETO opcode/instruction, to detect the overflow condition. It was pretty fast by my benchmarks, but didn’t pass Sree’s correctness test and didn’t perform well with the “exception-toss-on-overflow-flag-set.”

I thought the code was an interesting and important exercise, given the plethora of security issues in code today, so I include it below. The code should only be used for research and review purposes (i.e., “as-is” and at your own risk).

When I get some more time (i.e., maybe this weekend if my family doesn’t “kill” me first for being computer-bound :) ), I’ll take a look at Sree’s tests and MS’s SafeInt class more.

Here is the output of the program:

asm OF test…
Error: over flow [-2147483648]
Total: 825.803 usecs
Press key to continue…

asm non-OF test…
Success: sum = [2147483647]
Total: 552.305 usecs
Press key to continue…

Simple add OF test…
Error: over flow [-2147483648]
Total: 784.178 usecs
Press key to continue…

Simple add non-OF test…
Success: sum = [2147483647]
Total: 552.025 usecs
Press key to continue…

add64 OF test…
Error: over flow [-2147483648]
Total: 925.537 usecs
Press key to continue…

add64 non-OF test…
Success: sum = [2147483647]
Total: 550.349 usecs
Press key to exit…

Here is the program safeadd.cpp (Updated: 9/23/06, 1:30pm ET).

This brief program and benchmark produced up to ~50% performance degradation with SETO compared to the simple add (i.e., different upon inspection from the 15% originally reported). Also, I added a 64-bit C version for comparison that is posted at various spots on the Internet.

Of course, there appears to be even more to consider after the follow-up post. As mentioned, hope to revisit a little later, but good blog fodder for the moment.

Tags: , Integer Overflow