Gracefully handle A_limbs > N_limbs and test it
Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
diff --git a/library/bignum_core.c b/library/bignum_core.c
index 49a966f..8ac65e2 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -1123,12 +1123,15 @@
* We only write to G (aka v) after reading from inputs (A and N), which
* allows aliasing, except with N when I != NULL, as then we'll be operating
* mod N on q and r later - see the public documentation.
- *
- * Also avoid possible UB with memcpy when src == dst.
*/
+ if (A_limbs > N_limbs) {
+ /* Violating this precondition should not result in memory errors. */
+ A_limbs = N_limbs;
+ }
memcpy(u, A, A_limbs * ciL);
memset((char *) u + A_limbs * ciL, 0, (N_limbs - A_limbs) * ciL);
+ /* Avoid possible UB with memcpy when src == dst. */
if (v != N) {
memcpy(v, N, N_limbs * ciL);
}
diff --git a/library/bignum_core.h b/library/bignum_core.h
index cd78e72..f044b33 100644
--- a/library/bignum_core.h
+++ b/library/bignum_core.h
@@ -832,7 +832,7 @@
* When I != NULL (computing the modular inverse), G or I may alias A
* but none of them may alias N (the modulus).
*
- * If any precondition is not met, output values are unspecified.
+ * If any of the above preconditions is not met, output values are unspecified.
*
* \param[out] G The GCD of \p A and \p N.
* Must have the same number of limbs as \p N.