Hi,
I have some code that normally uses nrf_crypto with the cc310 or cc310_bl backend. I was writing a unit test for this code which compiles and runs in Linux/WSL. Since the cc310 is a hardware component in the nRF chip I decided to use the software backend for nrf_crypto for the unit test.
But I got a couple of compilation warnings and errors in the sha256 library that is used by the software backend to nrf_crypto.
With -fsanitize=undefined in CFLAGS:
nrf5_sdk/components/libraries/sha256/sha256.c:79:25: runtime error: left shift of 255 by 24 places cannot be represented in type 'int'
If I add casts to uint32_t on line 79 it compiles and runs without error:
// Not safe / undefined. data[j] is promoted to int, but 255 << 24 can not be represented by a signed int m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); // Safe - no errors m[i] = ((uint32_t)data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]);
Presumably because data[j] is promoted to a normal signed int since an int can represent all values of uint8_t. But UINT8_MAX << 24 can not be represented by a signed int.
https://stackoverflow.com/a/7954861
I had also used the sha256 library and included sha256.h directly in some of my code, and got this compile error:
nrf5_sdk/components/libraries/sha256/sha256.h:102:77: error: unknown type name ‘size_t’ 102 | ret_code_t sha256_update(sha256_context_t *ctx, const uint8_t * data, const size_t len); | ^~~~~~
The sha256_update function takes a size_t as one of its parameters. But sha256.h does not include any header from the standard library that defines size_t. Including stdio.h or stdlib.h fixes it.
I was using gcc version 9.3.0 and nRF SDK 15.3. I checked SDK 17.0.2 and the sha256 library has not changed since 15.3. I also had other flags in CFLAGS, but I don't think they should matter.