drivers: sensor: mx5837: address integer overflow.
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 #58585 Coverity-CID: 316294 Fixes #58594 Coverity-CID: 316521 Signed-off-by: Thomas Stranger <thomas.stranger@outlook.com>
This commit is contained in:
parent
f5e462137f
commit
cf29b8caad
1 changed files with 2 additions and 2 deletions
|
@ -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;
|
||||
|
@ -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);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue