I have a legacy c project with many type conversions and castings. Normally to check the overflow dynamic behavior, gcc (and C lang) defines a builtin function for that:
Built-in Function: bool __builtin_add_overflow (type1 a, type2 b, type3 *res)
If the result overflows the function returns true. Then my program may catch this condition and act accordingly.
For the sake of having the same functionality without changing any legacy code, is it possible to instruct gcc to use such builtins and invoke a provided function as a catcher if the builtins return true? I wish I can find something like:
void _cyg_add_overflow_catcher(A, B, __FILE, LINE);
GCC already can instrument functions, for traceability and profiling, so the concept is not weird. Any ideas?
These functions are lowered by GCC to efficient asm sequences so they are not present in final object code. On the other hand when compiled in UBSan mode GCC will call dedicated callbacks from libubsan.so on overflow. You could override these callbacks in your executable and do the necessary processing (this is of course quite hacky).
Note that GCC only tracks overflows for signed numbers as unsigned overflows are defined by the Standard.