mackron / miniaudio

Audio playback and capture library written in C, in a single source file.
https://miniaud.io
Other
3.96k stars 348 forks source link

UBSAN error in ma_lcg_rand_s32 #853

Closed kavika13 closed 1 month ago

kavika13 commented 4 months ago

I am making a zig wrapper, and ported over a random unit test to see if things are working. The unit test is hitting a UBSAN trap.

The test is: https://github.com/mackron/miniaudio/tree/master/tests/test_generation/ma_test_generation_noise.c

The error is:

miniaudio.h:13906:29: runtime error: signed integer overflow: 48271 * 208578991 cannot be represented in type 'int'
    #0 0x1273375 in ma_lcg_rand_s32 miniaudio.h:13906
    #1 0x1273375 in ma_lcg_rand_f64 miniaudio.h:13922
    #2 0x1273375 in ma_noise_f32_white miniaudio.h:66681
    #3 0x1273375 in ma_noise_read_pcm_frames__white miniaudio.h:66742
    #4 0x1273375 in ma_noise_read_pcm_frames miniaudio.h:66974
mackron commented 4 months ago

Thanks. If you change ma_lcg_rand_s32() to cast pLCG->state to ma_uint32, does it work? Like this (untested):

static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG)
{
    pLCG->state = (ma_int32)(MA_LCG_A * (ma_uint32)pLCG->state + MA_LCG_C) % MA_LCG_M;
    return pLCG->state;
}