Customizable `__stack_chk_fail` implementation

Łukasz Żak
Tue Oct 15 10:25:00 GMT 2019

Dear list,

I am using new lib for C/C++ development on arm devices (cortex-m3 and such) using gnu arm embedded toolchain ( which does include recent new lib version at the time of its release. Just recently I have tried to enable gcc built-in stack protection mechanism (-fstack-protector flag). The new lib implementation of `__stack_chk_fail` does work great in an environment where semihosting is available - i.e. under the Qemu. I get nice message saying the stack corruption has been detected and execution terminates. When however I build and run the same sources for real hardware the problems are detected - I can observe the calls to `__stack_chk_fail` with the gdb but as there is no semihosting available the write/_exit procedures used by the `__stack_chk_fail` handler are basically noops as they should be as on real hardware there is no standard output (at least in my case) and there is nothing to exit to. So what happens is problem is detected but not reported anywhere and program execution continues as if there were never a problem at all.

I tried replacing this handler with my own custom handler but as it is not marked as weak the only thing that I can do is to try and use ld's `--wrap` argument to replace this handler at the link time. This does work as long as link time optimization (-flto) is not enabled ( which is unfortunately requirement for me in release builds.  

Would you consider making stack protection handler overridable by i.e. making it weak function and/or proving a hook that someone can intercept?

Łukasz Żak

More information about the Newlib mailing list