CERT recently issued an unfortunate advisory about gcc.
The advisory is about an optimization which gcc introduced in gcc 4.2: given a pointer p
, then a comparison of the form p + C1 < p + C2
can be reduced to C1 < C2
. This is always valid in standard C and C++, because those languages say that if you have a pointer to an object, and you add an integer to that pointer, then the result must be a pointer to that same object, or must point just past the end of the object. Any other result is undefined. This means in particular that p + C
can not wrap around the end of memory, so the compiler can ignore wrapping issues.
Now, I don’t know who would have thought otherwise. Checking for overflow is always a good idea when validating user input. But checking for pointer overflow using wrapping arithmetic does not make sense. What matters is whether the offset is within the bounds of the object the pointer points at. A test which relies on wrapping overflow for pointer bounds seems rather strange.
However, if you do write such a test, you are indeed in trouble. It is perfectly reasonable for CERT to warn against doing so. gcc implements this optimization because it is very useful for determining how often a loop will iterate when the loop is written using a pointer. So people should be aware of it.
Where CERT went wrong is in only mentioning gcc in their advisory. In fact all popular optimizing compilers implement the same optimization. The CERT advisory suggests that you can avoid this problem by avoiding new versions of gcc. That is just plain incorrect. If you switch to a different compiler, you will have the same problem.
As the CERT advisory is written today, they warn that gcc 4.2 and later are a potential hazard, without warning about any other compiler. That seems very unfair and wrong. I certainly hope that CERT will correct or withdraw the advisory.
Also, CERT describes the problem in a rather vague manner, which has led several people to misunderstand it and think that the potential problem is even worse than it seems–i.e., that it might apply to code that people might actually write.
All that said, I am working on adding a warning to gcc for this case. I doubt it will ever be useful to any real programmer, but I hope that it will pacify CERT.
Leave a Reply
You must be logged in to post a comment.