On Sun, 2013-10-27 at 07:48 +0100, Ondřej Bílka wrote: > On Sun, Oct 27, 2013 at 01:50:14AM +0200, Hannes Frederic Sowa wrote: > > On Sat, Oct 26, 2013 at 09:29:12PM +0200, Ondřej Bílka wrote: > > > Hi, as I brainstormed how prevent possible overflows in memory allocation > > > I > > > came with heretic idea: > > > > > > For gcc -D_FORTIFY_SOURCE=2 we expand all multiplication with size_t > > > type by one that checks for integer overflow and aborts on it. This > > > would prevent most overflow at cost of breaking some legitimate > > > applications that use multiplication in clever way. > > > > > > A less heretic way that is applicable for C++ would be write a class > > > size_t overflow that would do arithmetic in saturating way and issue > > > warnings when there is a size_t multiplication. > > > > I am afraid of the false-positive aborts which could result in DoS against > > applications. I like the checked arithmetic builtins LLVM introduced in > > How likely is code that uses size_t for something other than size > calculation? > > I did not realized that this has opposite problem as lot of programs > still use int for size calculations. > > > 3.4 (not yet released) where one can test for overflow manually and handle > > the overflows appropriately. They also generate better code (e.g. they > > use the overflow flag and get inlined on x86 compared to the ftrapv insn). > > > As a workaround you can on x64 implement them by macros with inline assembly. > > > So I would vote for fast checked arithmetic builtins first.
I think both, checked arithmetic builtins and ftrapv can be useful. Builtins can be used to selectively do fine grained checked arithmetic, ftrapv can be used to enable checked arithmetic on a per-function base, for example: int __attribute__ ((optimize ("trapv", "non-call-exceptions"))) mission_critical_stuff (int x, int y) { try { // do all checked arithmetic here... return x + y; } catch (const std::overflow_error& e) { // runtime has to turn the trap into a c++ exception for this // to work. return 0; } } Of course the function doesn't need to do the try-catch by itself. The exception could also be handled outside the function if fine grained checking is not required. Internally (although not documented as standard name patterns), GCC already has support for the following trapping integer arithmetic insns: addv, subv, smulv, negv, absv. The individual target support for those insns varies and the existing insns are for signed arithmetic only, but it could be a starting point. Cheers, Oleg