Stack Smashing Protector: Difference between revisions

m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
m (→‎Usage: clarify the the optimization level is meant)
m (Bot: Replace deprecated source tag with syntaxhighlight)
Line 4:
 
Compilers implement this feature by selecting appropriate functions, storing the stack canary during the function prologue, checking the value in the epilogue, and invoking a failure handler if it was changed. For instance, consider the code:
<sourcesyntaxhighlight lang="c">
void foo(const char* str)
{
Line 10:
strcpy(buffer, str);
}
</syntaxhighlight>
</source>
SSP automatically illustratively transforms that code into this:
<sourcesyntaxhighlight lang="c">
/* Note how buffer overruns are undefined behavior and the compilers tend to
optimize these checks away if you wrote them yourself, this only works
Line 26:
__stack_chk_fail();
}
</syntaxhighlight>
</source>
Note how the secret value is stored in a global variable (initialized at program
load time) and is copied into the stack frame, and how it is safely erased from
Line 90:
 
It should also be noted that with the optimisations enabled via <tt>-O<n></tt> in GCC, the compiler may or may not "inline" a function. If a function has been inlined, then '''stack smash protection will not work for that function.''' To prevent this, one must use the <tt>noinline</tt> attribute like so:
<sourcesyntaxhighlight lang="c">
void __attribute__ ((noinline)) foo( /* args */ )
{
// Code goes here
}
</syntaxhighlight>
</source>
 
Disabling inlining in GCC can be done with the <tt>-fno-inline</tt> compile flag, however, that will not inline functions with the <tt>inline</tt> attribute. The <tt>-fno-inline-functions</tt> will not inline functions optimised with <tt>-O<n></tt>; but that has been proven ineffective for GCC versions 3.4.5 and over ([https://gcc.gnu.org/bugzilla/show_bug.cgi?id=28120 see bug report]).