嵌套asio调用在__throw_bad_function_call()中结束

Nesting asio call ends in __throw_bad_function_call()

本文关键字:call 结束 function bad asio 调用 throw 嵌套      更新时间:2023-10-16

我围绕无Boostless asio编写了一个包装器来处理所有网络通信。大多数交换涉及在客户端和服务器之间来回发送几个数据包。我现在有一个问题,如果我嵌套对asio方法的调用,我最终会出现在方法__throw_bad_function_call();

这是我的听众:

.hpp

/// brief Socket object used to manage connections to the remote server.
struct listener : public std::enable_shared_from_this<listener> {
/// brief Creates an instance of the object and opens a connection to the remote host.
/// param[in] params Connection parameters.
/// param[out] ec Errors returned by the OS.
explicit listener(const parameters &params, std::error_code &ec) noexcept;
/// brief Executes all queued handlers and resets the io_context for another run.
auto execute_handlers() noexcept -> void;
/// brief Writes data to the socket.
/// details Writes data to the socket and passes any errors to the callback.
/// param[in] barray Byte array to send to the server.
/// param[in] callback Method called when data has been written to the server.
auto write(packet barray, std::function<void(std::error_code ec, std::size_t length)> callback) noexcept -> void;
/// brief Reads data from the socket.
/// details Reads that present in the socket and passes the data as a single byte array to the callback.
/// param[in] callback Method called when data has been written to the server.
auto read(std::function<void(std::error_code ec, packet barray)> callback) noexcept -> void;
private:
/// brief Underlying OS socket.
std::unique_ptr<asio::generic::stream_protocol::socket> m_socket;
asio::io_context m_context;
asio::local::stream_protocol::endpoint m_endpoint;
/// brief Connection parameters
parameters m_params;
/// brief DNS resolver
asio::ip::tcp::resolver m_resolver;
/// brief Buffer that holds data to be received from the socket. Reset and resized before each call to read().
packet m_buffer;
};

.cpp

listener::listener(const parameters &params, std::error_code &ec) noexcept
: m_endpoint{params.domain_socket}, m_params{params}, m_resolver{m_context} {
#if !defined(_WIN32) && !defined(_WIN64)
if (!m_params.domain_socket.empty()) {
m_socket.reset(new asio::generic::stream_protocol::socket(m_context));
m_socket->connect(m_endpoint, ec);
if (ec) {
return;
}
m_socket->non_blocking(true);
return;
}
#endif
m_resolver.async_resolve(m_params.host, std::to_string(m_params.port),
[&](const std::error_code &error, asio::ip::tcp::resolver::results_type results) {
if (error) {
ec = error;
return;
}
//! todo Add timeout to async_connect
for (const auto &endpoint : results) {
m_socket.reset(new asio::generic::stream_protocol::socket(m_context));
m_socket->async_connect(endpoint.endpoint(), [&](const std::error_code &err_c) {
if (err_c) {
ec = err_c;
return;
}
});
}
});
}
auto listener::execute_handlers() noexcept -> void {
const auto handlers = m_context.run();
m_context.restart();
}
auto listener::write(packet barray, std::function<void(std::error_code ec, std::size_t length)> callback) noexcept
-> void {
asio::async_write(*m_socket, asio::buffer(barray), callback);
}
auto listener::read(std::function<void(std::error_code ec, packet barray)> callback) noexcept -> void {
packet tmp;
tmp.resize(1);
asio::async_read(*m_socket, asio::buffer(tmp), asio::transfer_exactly(1),
[&](std::error_code ec, std::size_t size) {
if (!ec) {
const auto available = m_socket->available();
m_buffer.resize(available);
m_buffer.shrink_to_fit();
asio::async_read(*m_socket, asio::buffer(m_buffer), asio::transfer_all());
}
callback(ec, std::move(m_buffer));
});
}

然后我开始与远程服务器交换,但lldb告诉我们失败了:

auto connection::do_connect(std::function<void(std::error_code ec, sql_state state)> callback) noexcept -> void {
m_listener = std::make_shared<listener>(m_params, ec);
m_listener->execute_handlers();
if (ec) {
callback(ec, state);
}
sql_state state;
const auto startup = write::startup(m_params);
m_listener->write(startup, [&](std::error_code ec, std::size_t length) {
if (ec) {
callback(ec, state);
}
m_listener->read([&](std::error_code ec, packet packet){});
});
m_listener->execute_handlers();
}

在lldb中运行此操作失败,并出现以下跟踪:

Process 82736 launched: '/Users/ruihpacheco/Desktop/databaseclient/build_ninja/tests/integration/integration' (x86_64)
Process 82736 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
frame #0: 0x0000000100178118 integration`std::__1::function<void (std::__1::error_code, std::__1::vector<nonstd::byte, std::__1::allocator<nonstd::byte> >)>::operator(this=0x00007ffeefbfd780, __arg=(__val_ = 0, __cat_ = 0x00007fffa6cd6cd8), __arg=size=329)(std::__1::error_code, std::__1::vector<nonstd::byte, std::__1::allocator<nonstd::byte> >) const at functional:1913
1910 {
1911     if (__f_ == 0)
1912         __throw_bad_function_call();
-> 1913     return (*__f_)(_VSTD::forward<_ArgTypes>(__arg)...);
1914 }
1915 
1916 #ifndef _LIBCPP_NO_RTTI
Target 0: (integration) stopped.

这感觉应该有效。。。

您的问题似乎是启动异步操作,该操作将缓冲区带到局部变量。

auto listener::write(packet barray, std::function<void(std::error_code ec, std::size_t length)> callback) noexcept
-> void {
asio::async_write(*m_socket, asio::buffer(barray), callback);
}

barraywrite内部的局部变量,async_write立即返回,但asio::buffer()只返回传递数据的包装器(指向数据及其大小的指针),不复制数据。write结束,barray被破坏,async_write获得了删除数据的缓冲区。。

与相同

auto listener::read(std::function<void(std::error_code ec, packet barray)> callback) noexcept -> void {
packet tmp;
tmp.resize(1);
asio::async_read(*m_socket, asio::buffer(tmp), asio::transfer_exactly(1),
[&](std::error_code ec, std::size_t size) {
if (!ec) {
const auto available = m_socket->available();
m_buffer.resize(available);
m_buffer.shrink_to_fit();
asio::async_read(*m_socket, asio::buffer(m_buffer), asio::transfer_all());
}
callback(ec, std::move(m_buffer));
});

async_readbuffer(tmp),其中tmp是局部的。async_read也会立即返回,所以当调用处理程序时,tmp不存在。

编辑

关于listener::read方法的几句话:

auto listener::read(
std::function<void(std::error_code ec, packet barray)> callback) noexcept -> void  // [1]
{
packet tmp;
tmp.resize(1);
asio::async_read(*m_socket, asio::buffer(tmp), asio::transfer_exactly(1),
[&](std::error_code ec, std::size_t size) { // [2]
if (!ec) {
const auto available = m_socket->available();
m_buffer.resize(available);
m_buffer.shrink_to_fit();
asio::async_read(*m_socket, asio::buffer(m_buffer), asio::transfer_all()); // [3]
}
callback(ec, std::move(m_buffer)); // [4]
});
}

[1] 回调通过值传递

[2] lambda通过引用捕获,因此没有callback的副本,闭包保持对局部变量的引用,在[4]中,您调用的闭包callback(ec,std::move(m_buffer))是悬空的,因为async_read立即返回,listener::read结束

[3] 有了[4],奇怪的是,async_read立即返回,您在调用ayns_read时将buffer传递给了m_bufferasync_read返回(正在执行读取异步操作),并调用了移动m_buffer的回调(它更改了异步操作使用的对象!),您应该等到async_read的处理程序被调用后,才能将m_buffer移动到回调中

主要问题:在我看来,问题在于参考listener::read方法中的通过callback。当调用处理程序时,它会对悬挂引用调用callback(..)。尝试通过值传递callback

[&,callback /*pass by value*/](std::error_code ec, std::size_t size) 
{
if (!ec) 
{
const auto available = m_socket->available();
m_buffer.resize(available);
m_buffer.shrink_to_fit();
asio::async_read(*m_socket, asio::buffer(m_buffer), asio::transfer_all());
}
callback(ec, std::move(m_buffer));
});