mcci-catena / Modbus-for-Arduino

Modbus library for Arduino
GNU Lesser General Public License v2.1
7 stars 6 forks source link

Time calculations are prone to error at wraparound #14

Closed terrillmoore closed 6 years ago

terrillmoore commented 6 years ago

In several places, we find code like the following:

https://github.com/mcci-catena/Modbus-for-Arduino/blob/30daf897feb04c3e2f6a492519d5a8cf8beb4c1f/ModbusRtu.h#L560-L567

The problem here is that the value computed for u32time at line 565 might be much less than millis() in the case where millis() is close to wrapping around; and so the timeout will happen immediately.

The solution is to check using if ((int32_t)(millis() - u32time) < 0) return 0;. The difference may well overflow, but by casting it to int32_t we are assured that we'll get a reasonable result as long as we check reasonably often.