Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: memory leak in tcp client writing holding register #302

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/codec/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,8 @@ impl<'a> Encoder<RequestAdu<'a>> for ClientCodec {
hdr,
pdu: RequestPdu(request),
} = adu;
let buf_offset = buf.len();
let request_pdu_size = request_pdu_size(&request)?;
buf.reserve((buf.capacity() - buf_offset) + request_pdu_size + 7);
buf.reserve(request_pdu_size + 7);
buf.put_u16(hdr.transaction_id);
buf.put_u16(PROTOCOL_ID);
buf.put_u16(u16_len(request_pdu_size + 1));
Expand Down
74 changes: 74 additions & 0 deletions tests/tcp_repeated_register_write.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: Copyright (c) 2017-2024 slowtec GmbH <[email protected]>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Test repeated writes to holding registers with the TCP client and TCP server.
//! Test for [#301 memory leak in TCP client](https://github.com/slowtec/tokio-modbus/issues/301).

#![cfg(feature = "tcp-server")]

#[allow(unused)]
mod exception;

use std::net::SocketAddrV4;
use std::{net::SocketAddr, time::Duration};

use tokio::net::TcpListener;
use tokio_modbus::prelude::*;
use tokio_modbus::{
client,
server::tcp::{accept_tcp_connection, Server},
};

use crate::exception::TestService;

#[tokio::test]
async fn tcp_issue301_write_test() -> Result<(), Box<dyn std::error::Error>> {
let bind_addr: SocketAddrV4 = "127.0.0.1:0".parse().unwrap();
let listener = TcpListener::bind(bind_addr).await?;
let server_addr = listener.local_addr()?;

tokio::select! {
_ = tokio::time::sleep(Duration::from_millis(10000)) => panic!("timeout - perhaps we have a lockup or a thread was killed"),
r = server_context(listener) => r?,
r = client_context(server_addr) => r?,
}

Ok(())
}

async fn server_context(listener: TcpListener) -> anyhow::Result<()> {
println!("Starting up server on {:? }", listener.local_addr()?);
let server = Server::new(listener);
let new_service = |_socket_addr| Ok(Some(TestService {}));
let on_connected = |stream, socket_addr| async move {
accept_tcp_connection(stream, socket_addr, new_service)
};
let on_process_error = |err| {
eprintln!("{err}");
};
server.serve(&on_connected, on_process_error).await?;
Ok(())
}

async fn client_context(socket_addr: SocketAddr) -> anyhow::Result<()> {
// Give the server some time for starting up
tokio::time::sleep(Duration::from_millis(200)).await;

let mut ctx = client::tcp::connect(socket_addr).await?;

let max_iterations = 1000;
let mut iterations = 1;
loop {
println!("iteration {}", iterations);
// In this case, the TestService always returns an exception, we'll ignore that.
// We are only interested here in the TCP client side constructing the request.
_ = ctx.write_multiple_registers(0x1000, &[1]).await?;
_ = ctx.write_multiple_registers(0x1000, &[1, 2]).await?;

if iterations == max_iterations {
return Ok(());
}

iterations += 1;
}
}