stephane / libmodbus

A Modbus library for Linux, Mac OS, FreeBSD and Windows
http://libmodbus.org
GNU Lesser General Public License v2.1
3.29k stars 1.71k forks source link

facing crash in libmodbus library #738

Open dixitsatyam opened 5 months ago

dixitsatyam commented 5 months ago

libmodbus version

libmodbus-3.1.10

OS and/or distribution

CentOS Linux - 7

Environment

x86 , 64bit

Description

int numOfReadRegisters = modbus_read_input_registers(ctx, 0, 7, reg); above function i called to read register values from the device , my reg value is valid (i checked with gdb reg array has valid address) , But still it is breaking in libmodbus library, below is the pointed stacktrace

0 0x00007fef6921abf8 in read_registers (ctx=0x2481450, function=, addr=, nb=, dest=0x1)

at modbus.c:1313

when i tried to check dest buffer it is showing inaccessable address

below is the pointing code in modbus.c

static int read_registers(modbus_t ctx, int function, int addr, int nb, uint16_t dest) { int rc; int req_length; uint8_t req[_MIN_REQ_LENGTH]; uint8_t rsp[MAX_MESSAGE_LENGTH];

if (nb > MODBUS_MAX_READ_REGISTERS) {
    if (ctx->debug) {
        fprintf(stderr,
                "ERROR Too many registers requested (%d > %d)\n",
                nb,
                MODBUS_MAX_READ_REGISTERS);
    }
    errno = EMBMDATA;
    return -1;
}

req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);

rc = send_msg(ctx, req, req_length);
if (rc > 0) {
    unsigned int offset;
    int i;

    rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
    if (rc == -1)
        return -1;

    rc = check_confirmation(ctx, req, rsp, rc);
    if (rc == -1)
        return -1;

    offset = ctx->backend->header_length;

    for (i = 0; i < rc; i++) {
        /* shift reg hi_byte to temp OR with lo_byte */
        dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)];     >> here it is pointing 
    }
}

return rc; }

Actual behavior if applicable

it should not crash if passed dest array address is valid

Expected behavior or suggestion

it should not crash if passed dest array address is valid

Steps to reproduce the behavior (commands or source code)

not reproduceble everytime , it is crashing sometimes

libmodbus output with debug mode enabled

(gdb) bt

0 0x00007fef6921abf8 in read_registers (ctx=0x2481450, function=, addr=, nb=, dest=0x1)

at modbus.c:1313

1 0x0000000000498207 in main () at pollExternalDevice.cpp:366

(gdb)

at 366 line i called modbus_read_input_registers(ctx, 0, 7, reg); function