rocksdb icon indicating copy to clipboard operation
rocksdb copied to clipboard

Fix memtable_list Unsigned difference expression compared to zero

Open odaysec opened this issue 7 months ago • 0 comments

https://github.com/facebook/rocksdb/blob/2ea356d0bea2e9a847792559498c02571dbf1e53/db/memtable_list.cc#L402-L402

Fix the issue need to ensure that the subtraction does not result in unsigned underflow. The best approach is to cast the result of the subtraction to a signed type (e.g., int64_t) before performing the comparison. This ensures that the subtraction behaves as expected, even if num_flush_not_started_ is greater than current_->memlist_.size(). The fix involves modifying line 402 to cast the result of the subtraction to int64_t before comparing it to 0.

uint32_t limit = get_limit();
uint32_t total = 0;

while (limit - total > 0) { // BAD: if `total` is greater than `limit` this will underflow and continue executing the loop.
  total += get_data();
}

while (total < limit) { // GOOD: never underflows here because there is no arithmetic.
  total += get_data();
}

while ((int64_t)limit - total > 0) { // GOOD: never underflows here because the result always fits in an `int64_t`.
  total += get_data();
}

References

INT02-C. Understand integer conversion rules CWE-191

odaysec avatar May 18 '25 11:05 odaysec