Hardening flag causes crash on 32-bit RISC-V systems

When Mbed TLS is compiled for 32-bit RISC-V Linux, the mbedtls_entropy_gather() function can cause an abort when using the GCC -ftrapv hardening flag.

The mbedtls_entropy_gather() function falls through to the mbedtls_timing_hardclock() function (when enabled). For the RISC-V architecture, the fallback C function that uses gettimeofday() system call is used.

In line 236 of timing.c, the time is converted to microseconds:
gettimeofday( &tv_cur, NULL );
return( ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000
+ ( tv_cur.tv_usec - tv_init.tv_usec ) );

When compiled for 32-bit RISC-V Linux, the time_t type is a 32-bit signed integer. The multiplication of ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000 will cause a signed integer overflow and hence an abort.
When making the constant unsigned (e.g. 1000000U), GCC will see the multiplication as unsigned multiplication and hence not trap. The overflow itself is by design according to the API Documentation.

Thank you @tnltom for raising this issue!

I have created this ticket on your behalf for better tracking this.

I believe this crash would happen in other calls that use gettimeofday() as well, not only the weak timing entropy source

Regards,
Mbed TLS Support
Ron