Would Rust prevent this bug?

I've written code to write data out from uart via the DMA controller on an STM32L476RGT6 microcontroller this week, and I wrote my code like this:

==pseudocode==
function handle_timer_interrupt {
    byte_buffer[30]
    write "Time spent handling interrupt: " + read_timer().as_string() + "\r\n" to byte_buffer
    transmit_uart_dma(byte_buffer)
}

The interesting thing was that I got something like this out:

Time spq23pas;f
Time spen3490aioafjj
Time spent handling interrupt: 200
Time s;;q234udkf

Basically, my output was garbage most of the time, but it started with the correct characters each time. After a little thought, I realized that I'm building a string to transmit in a local variable, then transmitting it asynchronously via dma. What happened, is the local goes out of scope before the dma transaction is complete because the interrupt handler returns. Then the source memory gets clobbered or the compiler is optimizing the UB or something, I don't know what. Swapping the local variable buffer out for a global memory block solved the problem. (Also, it is worth mentioning that the code was written in C with the STM32 HAL libraries and their Cube IDE and code generation tool.)

Now my question is: would Rust have complained about use of moved value or something like that in this case, or will this bite you in Rust as well?

Since Rust doesn't have a built-in concept of DMA, handling this correctly is still up to the libraries you use to work with the chip. If you build this program on top of a HAL crate that handles this correctly, then yes, the Rust compiler would have complained about this. If you're not using a HAL, or the HAL you use doesn't support DMA for writing to the UART, then it's up to you to build a safe abstraction for it. Once that is written though, it can be easily reused thanks to Cargo.

Thanks for the explanation.

It would seem that I also didn't have a built-in concept of DMA... :wink:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.