Watch out for overflows
I've been wanting to write this entry for about one year now. Not quite sure why it didn't occur before (but lazyness would be my prime suspect ;-).
Using .NET makes it hard, but not impossible, for buffer overflows to occurs. However other overflows, like integer overflows, exists and are still very real in a managed environment (and can even lead to buffer overflows).
Now it's easy to imagine a lot of nasty problem with this code as none of the parameters are validated before being used. It's even worst as we have declared this method as public - so we can't assume the caller knows "how to call it". Anyway we should never assume that so let's check them...
This second version is better because it adds validation of all parameters. However
it doesn't validate all of them correctly. For example what if
count is big, very big like
In this case we have:
bufferis non null, first check is ok;
startIndex == 15, which is greater than 0, second check is ok;
count == Int32.MaxValue, which is also greater than 0, third check is ok;
startIndex + count = 15 + Int32.MaxValue == -2147483634which is smaller than 16, fourth check is ok :(
All checks are positive so the unsafe code can execute, problem is
(i++ < count)
won't happen anytime soon - at least not before a lot of data gets zeroized. It this common ?
You bet! The .NET documentation often (or maybe always ?) documents the check as an addition (or doesn't even document the check) but the framework itself isn't coded like that. I have yet to found one integer overflow in MS implementation of the framework but I did found other interesting stuff, which were all reported, so I guess they have some automated tool to check for this (it's too good to be true ;-).
Integer overflow are usually much easier to fix than to find (even with a common pattern). In this case the problem can be fixed by reversing the operation, i.e. doing a substraction instead of an addition.
We could have an integer underflow if we were only using this check (e.g. if
count were equals to
Int32.MinValue). This is why there are
(or there should be) checks for both the
parameters to ensure they can't be negative.
This isn't the only case where integer [over|under]flow can bite you. In many case the VM will protect you against this problem (e.g. if we haven't used unsafe code). However this can be very dangerous if your code, like it's often the case inside mscorlib.dll, System.dll and in all interop assemblies, use those values to deal with unmanaged ressources (e.g. memory).
6/10/2005 15:19:27 | Comments
The views expressed on this website/weblog are mine alone and do not necessarily reflect the views of my employer.