浏览代码

modbus_mask_write_register: better fix with unit test (closes #265)

Stéphane Raimbault 9 年之前
父节点
当前提交
9b4212c892
共有 3 个文件被更改,包括 20 次插入1 次删除
  1. 6 0
      NEWS
  2. 4 1
      src/modbus.c
  3. 10 0
      tests/unit-test-client.c

+ 6 - 0
NEWS

@@ -1,3 +1,9 @@
+libmodbus 3.2.0 (XXXX-XX-XX)
+============================
+
+- Fix buffer overflow in modbus_mask_write_register #265)
+
+
 libmodbus 3.1.2 (2015-02-13)
 ============================
 

+ 4 - 1
src/modbus.c

@@ -1458,7 +1458,10 @@ int modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint1
 {
     int rc;
     int req_length;
-    uint8_t req[MAX_MESSAGE_LENGTH];
+    /* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to
+     * store the masks. The ugly substraction is there to remove the 'nb' value
+     * (2 bytes) which is not used. */
+    uint8_t req[_MIN_REQ_LENGTH + 2];
 
     req_length = ctx->backend->build_request_basis(ctx,
                                                    MODBUS_FC_MASK_WRITE_REGISTER,

+ 10 - 0
tests/unit-test-client.c

@@ -299,6 +299,16 @@ int main(int argc, char *argv[])
     real = modbus_get_float_dcba(tab_rp_registers);
     ASSERT_TRUE(real == UT_REAL, "FAILED (%f != %f)\n", real, UT_REAL);
 
+    /* MASKS */
+    printf("1/1 Write mask: ");
+    rc = modbus_write_register(ctx, UT_REGISTERS_ADDRESS, 0x12);
+    rc = modbus_mask_write_register(ctx, UT_REGISTERS_ADDRESS, 0xF2, 0x25);
+    ASSERT_TRUE(rc != -1, "FAILED (%x == -1)\n", rc);
+    rc = modbus_read_registers(ctx, UT_REGISTERS_ADDRESS, 1, tab_rp_registers);
+    ASSERT_TRUE(tab_rp_registers[0] == 0x17,
+                "FAILED (%0X != %0X)\n",
+                tab_rp_registers[0], 0x17);
+
     printf("\nAt this point, error messages doesn't mean the test has failed\n");
 
     /** ILLEGAL DATA ADDRESS **/