libtom / libtommath

LibTomMath is a free open source portable number theoretic multiple-precision integer library written entirely in C.
https://www.libtom.net
Other
650 stars 194 forks source link

Unworked condition in mp_div #137

Closed dmitry-lipetsk closed 5 years ago

dmitry-lipetsk commented 5 years ago

Hello.

https://github.com/libtom/libtommath/blob/9ff526fa2218f8697dcd0c9821330fa04682eb75/bn_mp_div.c#L223

PVS-Studio says "(i <1)" always false.

I made research in my copy libtommath and agree with PVS-Studio.

czurnieden commented 5 years ago

Yes, that's correct: Because zero is a special value and the only place where BIGINT.used == 0, so t must be at least zero after the assignment t = y.used -1 in line 165 with y != 0. Than t + 1 in the condition of the main loop of step 3 at line 183 must be at least one, hence i - 1 is at least zero and the check in line 223 is superfluous.

We are working frantically at a new official version and we hope to get it out before the Debian freeze in January, so any bugs that do not cause a malfunction have to go to the back of the line until then, so be patient, please, it won't be long.

It would be interesting to know how PVS-Studio found it because the fact y.used > 0 would be quite hard to find with software alone.

minad commented 5 years ago

It would be interesting to know how PVS-Studio found it because the fact y.used > 0 would be quite hard to find with software alone.

@czurnieden Since b==0 is handled in the beginning, y.used > 0 always holds. Such things are usually easy to find for static analysis if the analyzer tracks constraints for each variable over the control flow across functions.

minad commented 5 years ago

closed via #276

dmitry-lipetsk commented 5 years ago

My code, which was used and tested within past 5 months:

   assert(t2.alloc >= 3);

   assert(t2.used <= 3); //[2016-05-30]

   assert(i < x.alloc); // [2017-03-14] Research assert. Can be removed. See get_safe

   //assert(x.dp[i] != 0); //[2016-12-05]

   //[2018-12-24] Research
   assert_hint(i > t); //Again
   assert_hint(i > 0); //So

   t2.dp[0] = (i < 2) ? 0 : x.dp[i - 2];
   t2.dp[1] = (i < 1) ? 0 : x.dp[i - 1]; // [2018-12-24] Always = x.dp[i - 1];
   t2.dp[2] = x.get_safe(i);
   t2.used  = 3;

   //[2018-12-24] Research
   assert(t2.dp[1]==x.dp[i - 1]);