内存检查:缓冲区溢出是一种非常危险的c语言错误,大部分安全漏洞都与它有关,splint可以对缓冲区的使用进行检查,报告溢出或越界错误。

  实例:overflow.c

/*Program: overflow -- splint check overflow error */
int main(){
 int buf[10];
 buf[10] = 3;
 return 0;
}

  splint命令:splint overflow.c +bounds +showconstraintlocation

  splint执行的结果:-

  Splint 3.1.2--- 03 May 2009
  CommandLine: Setting +showconstraintlocation redundant with current value
  overflow.c:(in function main)
  overflow.c:4:2:Likely out-of-bounds store: buf[10]
  Unableto resolve constraint:
  requires9 >= 10
  neededto satisfy precondition:
  requiresmaxSet(buf @ overflow.c:4:2) >= 10
  A memorywrite may write to an address beyond the allocated buffer. (Use
  -likelyboundswriteto inhibit warning)
  Finishedchecking --- 1 code warning

  错误类型:数组buf的大小是10字节,大也可使用的buf[9],但是程序中使用了buf[10],数组越界了,所以报错了。

  实例程序2.bound.c

/*Program: bound.c -- use splint checking bound overflow error */
void updateEnv(char * str){
 char *tmp;
 tmp = getenv("MYENV");
 if(tmp != NULL) strcpy(str,tmp);
}

void updateEnvSafe(char * str, size_t strSize){
 char *tmp;
 tmp = getenv("MYENV");
 if(tmp != NULL){
  strncpy(str,tmp,strSize -1);
  str[strSize-1]='';
 }
}

  splint命令:splint bound.c +bounds +showconstraintlocation

  splint执行的结果:

  Splint3.1.2 --- 03 May 2009
  CommandLine: Unrecognized option: +
  A flag isnot recognized or used in an incorrect way (Use -badflag to inhibit
  warning)
  Spec filenot found: showconstraintlocation.lcl
  Cannot openfile: showconstraintlocation.c
  bound.c: (infunction updateEnv)
  bound.c:5:18:Possible out-of-bounds store: strcpy(str, tmp)
  Unableto resolve constraint:
  requiresmaxSet(str @ bound.c:5:25) >= maxRead(getenv("MYENV") @
  bound.c:4:8)
  neededto satisfy precondition:
  requiresmaxSet(str @ bound.c:5:25) >= maxRead(tmp @ bound.c:5:29)
  derivedfrom strcpy precondition: requires maxSet(<parameter 1>) >=
  maxRead(<parameter2>)
  A memorywrite may write to an address beyond the allocated buffer. (Use
  -boundswriteto inhibit warning)
  bound.c: (infunction updateEnvSafe)
  bound.c:13:3:Possible out-of-bounds store: str[strSize - 1]
  Unableto resolve constraint:
  requiresmaxSet(str @ bound.c:13:3) >= strSize @ bound.c:13:7 + -1
  neededto satisfy precondition:
  requiresmaxSet(str @ bound.c:13:3) >= strSize @ bound.c:13:7 - 1
  Finishedchecking --- 2 code warnings

  错误类型:由于使用strcpy函数,没有指定复制字符串的长度,所以,可能导致缓冲区溢出。UpdateEnvSafe中使用strncpy进行字符串复制,从而避免了缓冲区溢出的错误。

  4.小结

  在命令行下使用的splint非常的强大,splint同样可以可以集成到IDE 中.具体的要IDE的其他工具的设置。splint同样也可以写到在makefile文件中,然后使用make命令来预先检查代码中常见的静态错误。

  有了上面的这些简单的实例的演示,我们可以感受到splint的强大之处,当然,这里的介绍仅仅是一个简单抛砖引玉。更多的有关splint的内容可以参考参考文献[4],更多关于splint的使用可以参考splint 的官方手册[4].

  除了C有静态的代码工具以外,java中也有一款开源的功能强大的静态代码检查工具FindBugs。