Assert that BN_CTX_end is actually called.

If a function forgets to BN_CTX_end, everything will work but we'll use
more memory than intended. Catch such errors by asserting in
BN_CTX_free.

Update-Note: BN_CTX is exposed publicly. Some callers may have been
using it wrong and trip this assert. If so, add the missing BN_CTX_end
calls.

Change-Id: I9c38431376a256e5176fd295c0114a10a7f588bd
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/37787
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/fipsmodule/bn/ctx.c b/crypto/fipsmodule/bn/ctx.c
index 1926e80..f8c7ebf 100644
--- a/crypto/fipsmodule/bn/ctx.c
+++ b/crypto/fipsmodule/bn/ctx.c
@@ -126,6 +126,10 @@
     return;
   }
 
+  // All |BN_CTX_start| calls must be matched with |BN_CTX_end|, otherwise the
+  // function may use more memory than expected, potentially without bound if
+  // done in a loop. Assert that all |BIGNUM|s have been released.
+  assert(ctx->used == 0 || ctx->error);
   sk_BIGNUM_pop_free(ctx->bignums, BN_free);
   BN_STACK_cleanup(&ctx->stack);
   OPENSSL_free(ctx);