Skip to content

Commit

Permalink
drivers: sensor: mx5837: address integer overflow.
Browse files Browse the repository at this point in the history
Avoid integer overflow in temp_sq calculation.
For an analysis of the value ranges for the temp_sq calculation
of mx5837-02 see below:

calculation:
dT = adc_temperature - ((int32_t)(data->t_ref) << 8);
data->temperature = 2000 + (dT * data->tempsens) / (1ll << 23);
temp_sq = (data->temperature - 2000) * (data->temperature - 2000);

given needed storage sizes:
t_ref is uint16_t,
adc_temperature is uint24_t,
data->tempsens is uint16_t,

ranges
=> dT:                -16776960 <= dT <= 16777215         (25 bit)

=> data->temperature (TEMP):
  intermed.(mult): -1099478073600 <=  x   <= 1099494785025 (41 bit)
  TEMP:         2.000 - 131068 <= TEMP <= 2.000 + 131.069
  TEMP:                -129068 <= TEMP <= 133069     (17 bit)

So worst case we need 17 bit for TEMP, so the square of it would
overflow an int32_t. The nominal measurement range is
only -40 to 85°C, meaning a range of -4000 to 8500.
So normally the result for temp_seq would fit into a int32_t,
but we cast to be better safe than sorry. Also the 64-bit
multiplication won't be the dominating operation of the
whole calculation.

Fixes zephyrproject-rtos#58585
Coverity-CID: 316294
Fixes zephyrproject-rtos#58594
Coverity-CID: 316521

Signed-off-by: Thomas Stranger <[email protected]>
  • Loading branch information
str4t0m authored and carlescufi committed Jul 11, 2023
1 parent f5e4621 commit cf29b8c
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions drivers/sensor/ms5837/ms5837.c
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ static void ms5837_compensate_30(const struct device *dev,
* SECOND ORDER TEMPERATURE COMPENSATION
*/

temp_sq = (data->temperature - 2000) * (data->temperature - 2000);
temp_sq = (int64_t)(data->temperature - 2000) * (data->temperature - 2000);
if (data->temperature < 2000) {
Ti = (3ll * dT * dT) / (1ll << 23);
OFFi = (3ll * temp_sq) / 1ll;
Expand Down Expand Up @@ -120,7 +120,7 @@ static void ms5837_compensate_02(const struct device *dev,
OFF = ((int64_t)(data->off_t1) << 17) + (dT * data->tco) / (1ll << 6);
SENS = ((int64_t)(data->sens_t1) << 16) + (dT * data->tcs) / (1ll << 7);

temp_sq = (data->temperature - 2000) * (data->temperature - 2000);
temp_sq = (int64_t)(data->temperature - 2000) * (data->temperature - 2000);
if (data->temperature < 2000) {
Ti = (11ll * dT * dT) / (1ll << 35);
OFFi = (31ll * temp_sq) / (1ll << 3);
Expand Down

0 comments on commit cf29b8c

Please sign in to comment.