jrowberg / i2cdevlib

I2C device library collection for AVR/Arduino or other C++-based MCUs

Home Page:http://www.i2cdevlib.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Count overflow in Arduino/I2Cdev::readBytes and I2Cdev::readWords

nekomona opened this issue · comments

The data type of count in these two functions are incorrectly being int8_t, while length is uint8_t. This will cause an overflow when transmitting data with length > 128 and corrupt the data before buffer.

*/
int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout, void *wireObj) {
#ifdef I2CDEV_SERIAL_DEBUG
Serial.print("I2C (0x");
Serial.print(devAddr, HEX);
Serial.print(") reading ");
Serial.print(length, DEC);
Serial.print(" bytes from 0x");
Serial.print(regAddr, HEX);
Serial.print("...");
#endif
int8_t count = 0;
uint32_t t1 = millis();

More occurrences have been found in #750 .

Below is an overflow captured when reading 168 bytes from a MPU6050 FIFO, which caused function frame corruption and crashed the program.
image

It seems that the sign of count is used to report failure, which need to be taken into consideration:
Whether should it limit length within 127 bytes, using 0~254 as normal count and 255 as failure, or extend the data width.

Currently it's the second one with implicit type conversion. Code detecting failure by comparing with -1 still works, yet if it only compares with 0, reads with length > 127 will be misinterpreted as failed even if the result is correct.