且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++可疑堆栈溢出更改函数参数

更新时间:2023-11-10 15:45:34

您也可以尝试 AddressSanitizer 进行调试。它可以检测堆栈缓冲区溢出。下面是如何在Linux上使用它:



AddressSanitizer至少需要gcc 4.8,并且必须安装libasan(例如Fedora上的 yum install libasan 为root)。编译并链接到 -g -fsanitize = address 并运行生成的可执行文件。 AddressSanitizer停止并发出信息,如果它检测到第一个错误,没有长日志文件需要分析。解决报告的问题,编译并再次运行,直到AddressSanitizer不再停止程序。不幸的是,可能会有误报,因为您在程序中使用swapcontext,但值得一试。通过添加属性no_sanitize_address可以关闭特定函数的工具: extern int func(void)__attribute __((no_sanitize_address));


I am working on implementing a user level thread library in C++ using setcontext(), makecontext(), getcontext(), and swapcontext() on a Linux system.

I am using a wrapper function to wrap the function the user wants to run as a thread. For example, the user calls newthread(funcPtr), and within the thread library funcPtr is passed to a wrapper function that runs it.

The error occurs differently depending on whether or not I initiate an unused string within the function. If I include the line string s = "a"; the program will run to completion, but gdb reveals that context is switching to somewhere within the string library. Without this line, the program segfaults after leaving the function wrapper.

The gdb output shows the corruption of the parameters to function().

I ran valgrind but did not see anything particularly out of the ordinary in the output, just many "Invalid read of size 4" and "Invalid write of size 4" warnings, usually within the C++ standard map.

You could try also AddressSanitizer for debugging. It can detect stack buffer overflows. Here's how to use it on Linux:

At least gcc 4.8 is needed for AddressSanitizer and libasan must be installed (e.g. on Fedora yum install libasan as root). Compile and link with -g -fsanitize=address and run the generated executable. AddressSanitizer stops and emits information if it detects the first error, no long log files have to be analyzed. Solve the reported problem, compile and run again until AddressSanitizer doesn't stop the program anymore. Unfortunately there might be false positives because you use swapcontext in your program, but it's worth a try. Instrumentation can be turned off for a specific function by adding the attribute no_sanitize_address: extern int func(void) __attribute__((no_sanitize_address));