Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime array bounds checking in C++ built with g++

Tags:

Is there any way to do array bounds checking in C++ compiled using g++?

  • Valgrind's Memcheck can't detect overflows on arrays allocated on the stack.

  • The GCC extension enabled by -fbounds-checking is only implemented for the C front end.

Ideally, the source code shouldn't be modified in any way. Using std::vector, std::tr1::array or boost::array is not an option because the codebase is large and such shift would be infeasible.

like image 881
aramadia Avatar asked Feb 18 '10 18:02

aramadia


2 Answers

Google's AddressSanitizer is a compiler instrumentation module and runtime library that can check out-of-bound access to heap, stack and globals, among other things. It is available in Clang 3.1+ and in GCC 4.8+.

To use it, pass -fsanitize=address (or -faddress-sanitizer in old Clang 3.1) among the arguments to the compiler and to the linker (links asan; no need for explicit -lasan). To get nicer stack traces in error messages, pass -fno-omit-frame-pointer to the compiler.

It was initially used for Chromium testing, and since 2012, it is used by Firefox devs, too. There is a good blog post on how to get it running with Qt. You may also want to read some more context on Wikipedia.

like image 102
Dimiter Georgiev Avatar answered Sep 23 '22 15:09

Dimiter Georgiev


There is a Valgrind tool called SGCheck (formerly known as Ptrcheck) that does check stack array bounds overrun.

valgrind --tool=exp-sgcheck <program> <arguments>

The tool is still labeled experimental and it comes with several limitations. One of them is:

Platforms: the stack/global checks won't work properly on PowerPC, ARM or S390X platforms, only on X86 and AMD64 targets. That's because the stack and global checking requires tracking function calls and exits reliably, and there's no obvious way to do it on ABIs that use a link register for function returns.

like image 27
Demi Avatar answered Sep 19 '22 15:09

Demi