cpprestsdk icon indicating copy to clipboard operation
cpprestsdk copied to clipboard

Not caught exception in wspp_callback_client::shutdown_wspp_impl.

Open bartek256 opened this issue 10 years ago • 2 comments

I recently got report from my client about application crash. From the core dump and stack trace I can see that the exception is thrown form wspp_callback_client::shutdown_wspp_impl. I was able to reproduce the same behavior (I received the exact same stack trace) when for testing purposes I threw an exception from close handler callback. The close handler callback catches every exception in my production code so there is no way it got thrown form there.

When I analyzed the code of wspp_callback_client::shutdown_wspp_impl I saw that you're creating an async pplx task that is not being waited for. This task (among other things) calls close handler callback from client code. I think that if something is thrown from that task it is not caught but rather propagated to runtime and in turn causes client application to crash. This is what happens in that pplx task:

        // Can't join thread directly since it is the current thread.
        pplx::create_task([this, connecting, ec, closeCode, reason]
        {
                if (m_thread.joinable()) {
                    m_thread.join();
                }

                // Delete client to make sure Websocketpp cleans up all Boost.Asio portions.
                m_client.reset();

                if (connecting) {
                    websocket_exception exc(ec, build_error_msg(ec, "set_fail_handler"));
                    m_connect_tce.set_exception(exc);
                }
                if (m_external_close_handler) {
                    m_external_close_handler(static_cast<websocket_close_status>(closeCode), utility::conversions::to_string_t(reason), ec);
                }
                // Making a local copy of the TCE prevents it from being destroyed along with "this"
                auto tceref = m_close_tce;
                tceref.set();
            }
        });

Here is the stack trace from my application:

    !Concurrency::details::_ExceptionHolder::~_ExceptionHolder() Line 914   C++
    !Concurrency::details::_Task_impl_base::~_Task_impl_base() Line 1677    C++
    !Concurrency::details::_Task_impl<unsigned char>::`scalar deleting destructor'(unsigned int)    C++
    !std::_Ref_count_obj<EgnyteDrive::CBFS::MetadataRefresher>::_Destroy() Line 945 C++
    !Concurrency::details::_UnrealizedChore::_InternalFree(Concurrency::details::_UnrealizedChore * _PChore) Line 35    C++
    !Concurrency::details::_TaskCollection::_NotifyCompletedChoreAndFree(Concurrency::details::_UnrealizedChore * pChore) Line 1192 C++
    !Concurrency::details::_UnrealizedChore::_UnstructuredChoreWrapper(Concurrency::details::_UnrealizedChore * pChore) Line 373    C++
    !Concurrency::details::WorkItem::Invoke() Line 171  C++
    !Concurrency::details::InternalContextBase::ExecuteChoreInline(Concurrency::details::WorkItem * pWork) Line 1605    C++
    !Concurrency::details::InternalContextBase::Dispatch(Concurrency::DispatchState * pDispatchState) Line 1720 C++
    !Concurrency::details::FreeThreadProxy::Dispatch() Line 197 C++
    !Concurrency::details::ThreadProxy::ThreadProxyMain(void * lpParameter) Line 174    C++
    kernel32.dll!75e4338a() Unknown
    [Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]  
    [External Code] 

The _M_stackTrace in _ExceptionHolder points to: _M_stackTrace = {[0]=0x015bb080 {Inside EgnyteDrive.exe!web::websockets::client::details::wspp_callback_client::shutdown_wspp_impl<struct websocketpp::config::asio_tls_client>(class std::weak_ptr<void> const &,bool)} }

This is how I call close method on the websocket_callback_client:

    try {

        auto websocketCloseGuard = std::make_shared<std::mutex>();
        auto websocketCloseNotify = std::make_shared<std::condition_variable>();

        m_websocketClient.close().then([=]() {

                ...
            }
        }).wait();
    }
    catch (const std::exception & e) {

        EDLOG(logERROR) << "REDWorker::disconnect()."
            << " Cannot connect. Error message: " << e.what();
    }
    catch (...) {

        EDLOG(logERROR) << "REDWorker::disconnect()."
            << " Cannot connect. Unknown error.";
    }

The exception is not caught even though I wait for the task to finish.

Additionally I'd like to ask about the timeout when websocket_callback_client::close(). Sometimes when I wait for the task to finish it never returns (e.g. when internet connection is lost).

  • Is there any timeout implemented there?
  • I see that close handler callback is also called when websocket_callback_client is destructed so is calling close even necessary?

Thanks, Bartek

bartek256 avatar May 30 '16 17:05 bartek256

First, thank you for doing your homework here and filing an excellent issue.

It does look like a bug that any exceptions thrown by the close handler are not propagated to the .close() task. Ideally, we should use the TCE to marshall any exceptions (and if not exceptions then the error_code value itself) out to any calls to .close().

We should be using the default websocket++ timeouts (which for our version should be 5 seconds for most operations). To configure them it looks like we would need to expose a way to call .set_open_handshake_timeout() on the client or connection object. However, the defaults should not result in the task not finishing; that sounds like either a race condition or we aren't hooking up every callback -- in either case a bug. How easy is this issue to reproduce?

We call close in the destructor to prevent use-after-free. However, it means that 1) any errors that have occurred will be silently swallowed (contrary to the general behavior of the rest of the library) and 2) users might experience a sudden and unexpected block during the destructor. We therefore recommend calling close() yourself before the destructor in order to handle errors and to remain in control of any blocking operations.

ras0219-msft avatar May 31 '16 20:05 ras0219-msft

I've checked the hangs on close() today. It seems that indeed there is a timeout implemented. Sometimes it hits it after 5 seconds sometimes after longer period 10 - 15 seconds. But it seems that it never hangs. I might have been too inpatient and was killing the app before the timeout was hit. If I see something similar, I'll make sure that it really is the issue and I will report back it in separate ticket.

Thanks, Bartek

bartek256 avatar Jun 01 '16 16:06 bartek256