Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does clang support bounds checking?

Tags:

clang

clang++

if so, how do I turn on? I can't find this in the documentation myself and google didn't provide useful results

e.g,

int arr[2];
arr[5] = n;  // runtime error
like image 776
The Mask Avatar asked Apr 03 '14 03:04

The Mask


2 Answers

Yes. The command-line to enable this is -fsanitize=address.

For more information on this, including expected slowdown and why you might be getting link errors, see Clang's AddressSanitizer Documentation.

Keep in mind the address sanitizer does more than bounds check on stack objects; if that's the only capability you want, I think you can limit it to doing only that by additionally passing -mllvm -asan-stack. See this page on address sanitizer flags for details.

like image 175
Oak Avatar answered Oct 24 '22 04:10

Oak


No. Unfortunately, even with the -fsanitize=address switch, clang does not prevent abusing a pointer to one object to access data of another object. Consider the following code:

#include <stdio.h>
int main(int argc, char **argv)
{
   char a[4] = "123";
   char b[4] = "ABC";
   int i, k;
   sscanf(argv[1], "%d", &i);
   k = i + (&b[i] - &a[i]);
   printf("a[%d] = '%c'\n", k, a[k]);
   return 0;
}

Save this as badcode.c and compile like this:

clang -fsanitize=address badcode.c -o badcode

Output of a sample run:

$ ./badcode 1
a[17] = 'B'

With real bounds checking, a[17] should be detected as an error.

like image 30
Jo Schueth Avatar answered Oct 24 '22 04:10

Jo Schueth