简体   繁体   English

如何在C程序中找到(全部)整数溢出?

[英]How to find (all) integer overflows in a C program?

I am working on a large project that generally works just fine, but shows serious issues once the input data size exceeds some limitations. 我正在开发一个通常工作得很好的大型项目,但是一旦输入数据大小超出某些限制就会出现严重问题。

These issues are (suspected) only due to signed integer overflows like these: 这些问题(怀疑)只是由于有符号的整数溢出,如下所示:

int a, o;
// Initialize a and o
int x = (a+o) >> 1);

Obviously, once the sum of a and o overflows (gets larger than 2^31-1), x is no longer the mean of a and o. 显然,一旦a和o的总和溢出(大于2 ^ 31-1),x就不再是a和o的平均值。

Is there a generic way to find all of these integer overflows in a running program? 是否有一种通用的方法来查找正在运行的程序中的所有这些整数溢出?

I am thinking of a tool like Valgrind or a GDB extension that breaks at every integer arithmetic instruction, takes the parameters and compares the correct result (calculated with a larger-sized datatype or arbitrary-precision arithmetic) with the actual result. 我正在考虑像Valgrind或GDB扩展的工具,它在每个整数算术指令处中断,获取参数并将正确的结果(使用较大的数据类型或任意精度算术计算)与实际结果进行比较。 If the results differ, it should output a warning, trigger a debug break or something like this. 如果结果不同,它应该输出警告,触发调试中断或类似的事情。

I know, how to check a single arithmetic instruction for overflows (eg checking the sign for additions), however due to the vast amount of code, it is not viable solution for me to go through the whole project and insert checking code everywhere by hand. 我知道,如何检查单个算术指令是否有溢出(例如检查添加的符号),但是由于代码量很大,对于我来说,通过整个项目并手动插入检查代码并不是一个可行的解决方案。 。

You have to work through all the code and work out what the limit on the user-input is and validate the input. 您必须完成所有代码并计算出用户输入的限制并验证输入。 You may also need to re-write some algorithms to reduce overflow issues. 您可能还需要重写一些算法以减少溢出问题。

As the example you give doesn't work for negative values, you should be using an unsigned int anyway, giving you an extra order of magnitude already. 由于您提供的示例不适用于负值,因此您应该使用unsigned int ,这样您就可以获得额外的数量级。

Edit: gcc has the -ftrapv option, but this usually doesn't actually do anything only works with -O0 . 编辑: gcc有-ftrapv选项,但这通常不会做任何事只适用于-O0 If you are taking the approach of trapping overflows when they happen, you still need good knowledge of the code in order to test it fully. 如果你正在采取捕获溢出的方法,你仍然需要很好的代码知识才能完全测试它。

For large code base, Coverity is a good tool. 对于大型代码库, Coverity是一个很好的工具。 I am not sure it will detect all integer overflows or not, but its worth giving a try. 我不确定它是否会检测到all整数溢出,但值得一试。

How about a script which goes through the code and replaces all "a+b" with DEBUGADD(a,b) - where you can do: 如何通过代码并用DEBUGADD(a,b)替换所有“a + b”的脚本 - 你可以做的事情:

#ifdef DEBUG
int addFn(int a, int b) {
  long long m;
  int n;
  m = (long long)a + (long long)b;
  n = a + b;
  if (m != (long long)n)
    printf("PANIC!\n");
  return n;
}
#define DEBUGADD(a,b) addFn(a,b)
#else
#define DEBUGADD(a,b) ((a)+(b))
#endif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM