15.3.1 Stack Protector Function Attribute

__attribute__((stack_protect))

This attribute adds stack protection code to the function if flags -fstack-protector, -fstack-protector-strong or -fstack-protector-explicit are set.

Optimizations can affect stack protection:

  • 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_protect)) func1()
{
    char ana[]="Test canary use";
    int32_t i;

    if (ana[1] == ana[14])
      return 1;

    return 0;
}

int main()
{
    return func1();
}

Compiled with this command line:

xc32-gcc -fstack-protector -O2 test_stack_protect.c -o test_p.elf -mprocessor=ATSAME70J19

In 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.