15.3.1 Stack Protector Function Attribute
The __attribute__((stack_protector)) attribute adds stack protection code to the
function if flags -fstack-protector,
-fstack-protector-strong or
-fstack-protector-explicit are set.
- Function inlining can affect whether a function is protected.
- Removal of an unused variable can prevent a function from being protected.
Usage (test_stack_protect.c)
#include <stdint.h>
int32_t __attribute__((stack_protector)) func1(void) {
char ana[]="Test canary use";
int32_t i;
if (ana[1] == ana[14])
return 1;
return 0;
}
int main(void) {
return func1();
}
xc32-gcc -mprocessor=ATSAME54P20A
-mdfp="Microchip/SAME54_DFP/3.9.244" -fstack-protector -O2 test_stack_protect.c -o test_p.elfIn this example, function func1() would be instrumented with the stack
protection code. The stack protector feature adds one stack-canary variable on the
call stack of func1() and, at the end of the function, it checks
the variable value. If the value is modified, the stack was corrupted, and the
generated code calls the __stack_chk_fail() function.
The __attribute__((no_stack_protector)) form of this attribute can
be used to disable the stack protector for the nominated function, even when a stack
protection option has been issued.
