From b4a5230932ff84855e1e5dfe2374d47f570925ff Mon Sep 17 00:00:00 2001 From: StalderT Date: Thu, 5 Nov 2026 12:15:24 +0100 Subject: [PATCH] _modbus_receive_msg: don't require a socket for the Windows RTU backend On Windows the RTU backend waits on a serial HANDLE held in its own backend data and never sets ctx->s, which stays at -1. It also ignores the fd_set it is given: _modbus_rtu_select() only uses rset in its POSIX branch, and a mingw build reports the parameter as unused. Since 7b13341 _modbus_receive_msg() validates ctx->s before every FD_SET, so every receive on a Windows RTU context now fails at once with EINVAL instead of waiting for the timeout. v3.1.11 is not affected, v3.1.12 and v3.2.0 are. Skip the check and the FD_SET for a backend that does not use the set, which on Windows means the RTU one. Nothing changes anywhere else: on POSIX the condition is the constant 1. Fixes #890 --- src/modbus.c | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/modbus.c b/src/modbus.c index abdd718c4..b20218358 100644 --- a/src/modbus.c +++ b/src/modbus.c @@ -373,6 +373,10 @@ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) _step_t step; #ifdef _WIN32 int wsa_err; + /* The RTU backend waits on a serial HANDLE, not on a socket */ + const int uses_fd_set = ctx->backend->backend_type != _MODBUS_BACKEND_TYPE_RTU; +#else + const int uses_fd_set = 1; #endif if (ctx->debug) { @@ -390,16 +394,20 @@ int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) return -1; } - /* Add a file descriptor to the set */ + /* Add a file descriptor to the set. On Windows the RTU backend leaves ctx->s + * at -1 and ignores the set (see _modbus_rtu_select), so there is no + * descriptor to check nor to register. */ FD_ZERO(&rset); - if (ctx->s < 0 || ctx->s >= FD_SETSIZE) { - if (ctx->debug) { - fprintf(stderr, "ERROR Invalid socket descriptor %d\n", ctx->s); + if (uses_fd_set) { + if (ctx->s < 0 || ctx->s >= FD_SETSIZE) { + if (ctx->debug) { + fprintf(stderr, "ERROR Invalid socket descriptor %d\n", ctx->s); + } + errno = EINVAL; + return -1; } - errno = EINVAL; - return -1; + FD_SET(ctx->s, &rset); } - FD_SET(ctx->s, &rset); /* We need to analyse the message step by step. At the first step, we want * to reach the function code because all packets contain this