https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86885

            Bug ID: 86885
           Summary: gcc erroneously allows constructor/destructor
                    attributes on nested functions
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: bugdal at aerifal dot cx
  Target Milestone: ---

Nested functions cannot meaningfully be called outside of the lifetime of a
particular instance of the block in which they are nested. However, gcc allows
them to be given the constructor or destructor attribute, causing them to be
called at init/fini time without a meaningful value for the hidden context
pointer, potentially leading to runaway wrong behavior.

The GCC documentation on nested functions related to this issue is also
outdated and imprecise:

"If you try to call the nested function through its address after the
containing function exits, all hell breaks loose. If you try to call it after a
containing scope level exits, and if it refers to some of the variables that
are no longer in scope, you may be lucky, but it’s not wise to take the risk.
If, however, the nested function does not refer to anything that has gone out
of scope, you should be safe."

Due to various transformations that may be performed, it seems impossible to
guarantee that a nested function called after the containing function exits, or
without any containing function ever existing (the ctor/dtor case), does not
attempt to access the containing function's stack frame, even if the code path
taken does not access local variables at the abstract machine level. For
instance hoisting could cause accesses that would reasonably be assumed to be
valid. I don't see any indication that GCC has the necessary machinery to
prevent such transformations.

Applying the ctor/dtor attributes to a nested function should be an error, and
the documentation should be updated to reflect that it's invalid to call a
nested function outside the lifetime of the containing block.

Source of this issue was a question on Stack Overflow:

https://stackoverflow.com/questions/51736547/how-to-specify-priority-in-attribute-constructor-for-nested-functions

Reply via email to