开发者

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

开发者 https://www.devze.com 2022-12-20 09:52 出处:网络
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.

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.


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.


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.


GCC mudflap (-fmudflap) can do bounds checking for C, but can't handle all C++ code as of mid-2012 (e.g. std::vector). It was removed in GCC 4.9 in mid-2015, superseded by Address Sanitizer. The mudflap options remain, but do nothing.

There is the MIRO patch – Mudflap Improved with Referent Objects. See its homepage for more information. Also, there is a paper about it.

I have tried MIRO briefly. It seems to be very good, but perhaps will not work with 100% of C++ code. I intend to use MIRO during development, then turn it off (and use the regular compiler) for release. If you are writing your own code, it should be fairly easy to make it work with MIRO.

0

精彩评论

暂无评论...
验证码 换一张
取 消