Skip to content

hal_rng_get_random_in_range example implementation can lead to division by zero #127

@djObsidian

Description

@djObsidian

A fairly basic problem, but a bit tricky nonetheless. So, in Random Number Generator Hardware Abstraction Layer implementation there is:

return ( uint32_t )( ( hal_rng_get_random( ) % ( val_2 - val_1 + 1 ) ) + val_1 );

In porting tests random is tested with following values:
uint32_t rdom1 = smtc_modem_hal_get_random_nb_in_range( 0, 0xFFFFFFFF );

0xffffffff-0+1 = 0x100000000 but because Cortex-M registers are 32 bit wide it is truncated, which causes division by zero. Disassembly on STM32L4 looks like this:

08010260:   subs    r4, r4, r6
08010262:   adds    r4, #1
08010264:   ldr     r3, [sp, #4]
08010266:   udiv    r2, r3, r4

The problem is that somehow hardfault does not occur when running the code without SWD or JTAG debugger attached, but it appears when debugging.

I suggest to fix it like this:

    uint32_t min_val, max_val, range;
    if (val_1 <= val_2) {
        min_val = val_1;
        max_val = val_2;
    } else {
        min_val = val_2;
        max_val = val_1;
    }
 
    if (min_val == max_val) {
        return min_val; 
    }
    if (max_val == UINT32_MAX && min_val == 0) {
        return rand_nb;
    }
    range = max_val - min_val + 1;

    return min_val + (rand_nb % range);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions