andrewrk / libsoundio

C library for cross-platform real-time audio input and output
http://libsound.io/
MIT License
1.93k stars 228 forks source link

Race condition in soundio_ring_buffer_fill_count #276

Open krumelmonster opened 1 year ago

krumelmonster commented 1 year ago

The soundio_ring_buffer_fill_count function is not thread safe. The read and write pointers may change inbetween the calls to SOUNDIO_ATOMIC_LOAD. In my case this leads to assertion failures at assert(count <= rb->capacity); randomly.

https://github.com/andrewrk/libsoundio/blob/master/src/ring_buffer.c#L72

Attached is a screenshot that shows how the assertion fires because an outdated read_offset value is used to calulate count, resulting in count=26521600-25850880=670720 which wrongfully indicates count exceeded the buffers capacity of 667648. If a synchronization primitive had prevented the pointers from being read while modified, count would have correctly been calculated as count=26521600-25861120=660480.

image