3 ms·
I'm not conviced that GCC defines the behavior of this, because the trick relies on defining a local function in a block scope, and then allowing it to escape f
by kazinator 7y ago
I'm not conviced that GCC defines the behavior of this, because the trick relies on defining a local function in a block scope, and then allowing it to escape from that block scope:
{
rettype foo(args ...) { ... }
foo;
}
GCC local functions are "downward funarg only", as far as I know. This would definitely be wrong:
{
int local = 42;
rettype foo(args ...) { ... reference local ... }
foo;
}
then, when foo is called, local no longer exists, which is bad news. The lambda macro doesn't do this (the block doesn't extend the enviornment; nothing is captured from there), and so maybe works by fluke.
Another thing to is that pointers to GCC local functions work via trampolines: pieces of executable machine code installed into the stack. When you use GCC functions, the linker has to mark the executable with a bit which says "allow stacks to be executable". The default in most distros is non-executable stacks, which guards against stack overflow exploits.
(Speaking of trampolines, I'm not sure about the effective scope of those. If we lift a pointer to a local function inside a block, requiring a trampoline, and then that block terminates, is that trampoline scoped to the block or the function? If it's scoped to the function, won't it be overwritten if we execute that logic multiple times? If the trampoline is scoped to the block, then the invocation of foo is using an out-of-scope trampoline.
- ndesaulniers 7y agoThere are quite a few GNU C extensions with unspecified behavior for edge cases. Source: have implemented and debugged/fixed some in Clang.
- kazinator 7y agoBy the way I compiled and ran the program (Ubuntu 18.04, x86_64 with various optimization options and whatnot, such as -fstack-protector. It runs cleanly under Valgrind.
- iforgotpassword 7y agoValgrind is pretty bad at detecting stack corruption, or at least was a couple years ago. Did you try -fsanitize=address too?
- deleted 7y ago[deleted]