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

            Bug ID: 110635
           Summary: Segmentation fault when the awaiter's await_resume in
                    initial-suspend returns a class type.
           Product: gcc
           Version: 13.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: eustrain at outlook dot com
  Target Milestone: ---

The simplest code here:

#include <coroutine>

struct Coroutine {
    struct promise_type;
    using handler_type = std::coroutine_handle<promise_type>;
    struct initial_suspend_awaiter {
        bool await_ready() noexcept { return false; }
        void await_suspend(handler_type h) noexcept { }
        using await_resume_return_object = struct{}; // bad
        // using await_resume_return_object = int; // ok
        await_resume_return_object await_resume() noexcept { return {}; }
        initial_suspend_awaiter() noexcept { }
        ~initial_suspend_awaiter() noexcept { }
    };
    struct promise_type {
        void return_void() noexcept {}
        void unhandled_exception() noexcept { }
        initial_suspend_awaiter initial_suspend() noexcept { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        Coroutine get_return_object() { return
Coroutine{handler_type::from_promise(*this)}; }
    };
    handler_type handler;
};

int main() {
    auto coro = []()->Coroutine { co_return; }();
    coro.handler.resume();
}

The C++ standard said, a coroutine behaves as if its function-body were
replaced by:

{
   promise-type promise promise-constructor-arguments ;
   try {
      co_await promise.initial_suspend() ;
      <function-body>
   } catch ( ... ) {
      if (!initial-await-resume-called)
         throw ;
      promise.unhandled_exception() ;
   }
final-suspend :
   co_await promise.final_suspend() ;
}

So, the result of "promise-type promise promise-constructor-arguments" will be
discarded. However, when it returns the class type, gcc will get a segmentation
fault.

The complete test code: https://godbolt.org/z/dG8q9GGj8

You can modify the CASE macro to adjust the return type in that code.

The bug is also occur in clang in a somewhat different situation.

https://github.com/llvm/llvm-project/issues/63803

Reply via email to