From bf9da1dfb1fca79b2df17b30d40d99d6019d9df1 Mon Sep 17 00:00:00 2001
From: Gabor Mezei <gabor.mezei@arm.com>
Date: Fri, 12 Aug 2022 14:11:56 +0200
Subject: [PATCH] Do not read if output pointer is NULL

Skip reading if output pointer is NULL even if the length of the input buffer is 0.
The memory sanitizer will mark this as an error.

Signed-off-by: Gabor Mezei <gabor.mezei@arm.com>
---
 library/bignum_core.c | 24 ++++++++++++++----------
 1 file changed, 14 insertions(+), 10 deletions(-)

diff --git a/library/bignum_core.c b/library/bignum_core.c
index f250009bb..d5db4b0b0 100644
--- a/library/bignum_core.c
+++ b/library/bignum_core.c
@@ -171,10 +171,12 @@ int mbedtls_mpi_core_read_le( mbedtls_mpi_uint *X,
         return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
 
     if( X != NULL )
+    {
         memset( X, 0, nx * ciL );
 
-    for( i = 0; i < buflen; i++ )
-        X[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
+        for( i = 0; i < buflen; i++ )
+            X[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
+    }
 
     return( 0 );
 }
@@ -192,18 +194,20 @@ int mbedtls_mpi_core_read_be( mbedtls_mpi_uint *X,
         return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
 
     if( X != NULL )
+    {
         memset( X, 0, nx * ciL );
 
-    overhead = ( nx * ciL ) - buflen;
+        overhead = ( nx * ciL ) - buflen;
 
-    /* Avoid calling `memcpy` with NULL source or destination argument,
-     * even if buflen is 0. */
-    if( buf != NULL )
-    {
-        Xp = (unsigned char*) X;
-        memcpy( Xp + overhead, buf, buflen );
+        /* Avoid calling `memcpy` with NULL source or destination argument,
+         * even if buflen is 0. */
+        if( buf != NULL && X != NULL )
+        {
+            Xp = (unsigned char*) X;
+            memcpy( Xp + overhead, buf, buflen );
 
-        mbedtls_mpi_core_bigendian_to_host( X, nx );
+            mbedtls_mpi_core_bigendian_to_host( X, nx );
+        }
     }
 
     return( 0 );