Test aliasing in |BN_add| and |BN_sub|. Also update the documentation for |BN_sub|. Change-Id: I544dbfc56f22844f6ca08e9e472ec13e76baf8c4 Reviewed-on: https://boringssl-review.googlesource.com/8592 Reviewed-by: David Benjamin <davidben@google.com>
diff --git a/crypto/bn/bn_test.cc b/crypto/bn/bn_test.cc index 0c9d74e..6248aaa 100644 --- a/crypto/bn/bn_test.cc +++ b/crypto/bn/bn_test.cc
@@ -312,6 +312,30 @@ return false; } + // Test that the functions work when |r| and |a| point to the same |BIGNUM|, + // or when |r| and |b| point to the same |BIGNUM|. TODO: Test the case where + // all of |r|, |a|, and |b| point to the same |BIGNUM|. + if (!BN_copy(ret.get(), a.get()) || + !BN_add(ret.get(), ret.get(), b.get()) || + !ExpectBIGNUMsEqual(t, "A + B (r is a)", sum.get(), ret.get()) || + !BN_copy(ret.get(), b.get()) || + !BN_add(ret.get(), a.get(), ret.get()) || + !ExpectBIGNUMsEqual(t, "A + B (r is b)", sum.get(), ret.get()) || + !BN_copy(ret.get(), sum.get()) || + !BN_sub(ret.get(), ret.get(), a.get()) || + !ExpectBIGNUMsEqual(t, "Sum - A (r is a)", b.get(), ret.get()) || + !BN_copy(ret.get(), a.get()) || + !BN_sub(ret.get(), sum.get(), ret.get()) || + !ExpectBIGNUMsEqual(t, "Sum - A (r is b)", b.get(), ret.get()) || + !BN_copy(ret.get(), sum.get()) || + !BN_sub(ret.get(), ret.get(), b.get()) || + !ExpectBIGNUMsEqual(t, "Sum - B (r is a)", a.get(), ret.get()) || + !BN_copy(ret.get(), b.get()) || + !BN_sub(ret.get(), sum.get(), ret.get()) || + !ExpectBIGNUMsEqual(t, "Sum - B (r is b)", a.get(), ret.get())) { + return false; + } + // Test with |BN_add_word| and |BN_sub_word| if |b| is small enough. BN_ULONG b_word = BN_get_word(b.get()); if (!BN_is_negative(b.get()) && b_word != (BN_ULONG)-1) {
diff --git a/include/openssl/bn.h b/include/openssl/bn.h index 9ee2237..bc715b0 100644 --- a/include/openssl/bn.h +++ b/include/openssl/bn.h
@@ -383,8 +383,8 @@ /* BN_add_word adds |w| to |a|. It returns one on success and zero otherwise. */ OPENSSL_EXPORT int BN_add_word(BIGNUM *a, BN_ULONG w); -/* BN_sub sets |r| = |a| - |b|, where |r| must be a distinct pointer from |a| - * and |b|. It returns one on success and zero on allocation failure. */ +/* BN_sub sets |r| = |a| - |b|, where |r| may be the same pointer as either |a| + * or |b|. It returns one on success and zero on allocation failure. */ OPENSSL_EXPORT int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b); /* BN_usub sets |r| = |a| - |b|, where |a| and |b| are non-negative integers,