C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Ensuring safety of longjmp with [[trivial_dtors]]

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Fri, 14 Apr 2023 09:37:24 +0100
On Fri, 14 Apr 2023, 09:07 Frederick Virchanza Gotham via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> In the latest Standard we have:
>
> "The function signature longjmp(jmp_buf jbuf, int val) has more
> restricted behavior in this document. A setjmp/longjmp call pair has
> undefined behavior if replacing the setjmp and longjmp by catch and
> throw would invoke any non-trivial destructors for any objects with
> automatic storage duration. A call to setjmp or longjmp has undefined
> behavior if invoked in a suspension context of a coroutine."
>
> So let's say we have:
>
> extern void Some_Library_Func( void (*)(void) );
>
> jmp_buf jb;
>
> void JumpBack(void)
> {
> longjmp(jb,1);
> }
>
> int main(void)
> {
> setjmp(jb);
>
> Some_Library_Func( JumpBack );
> }
>
> We would really want an assurance that the function,
> Some_Library_Func, won't put an object on the stack that has a
> non-trivial destructor. Maybe a function attribute could ensure this?
>
> extern void SomeOtherFunc(void);
>
> [[trivial_dtors]] void Some_Library_Func( void (*)(void) )
> {
> std::string s; // COMPILER ERROR: cannot
> // put an object with an non-trivial
> // constructor on the stack
>
> SomeOtherFunc(); // COMPILER ERROR: cannot
> // call another function that has
> // not been marked as trivial_dtors
> }
>

Why is this useful? Who is using longjmp in modern C++ code? Who is using
longjmp in callbacks invoked by code they can't trust/control to be
correct? This seems like a terrible idea - why should anybody care?

Why should it be the responsibility of Some_Library_Func to deal with
longjmp being called in its callback?

This seems like an incredibly niche problem and really not worth anybody
caring about.

Write a compiler plugin or clang-tidy check and then use your own
non-standard attribute, don't complicate the C++ standard with this.

Received on 2023-04-14 08:37:40