AnsweredAssumed Answered

Buffer overflow in CubeMX SDMMC-Driver

Question asked by Nils Zottmann on May 30, 2017
Latest reply on Apr 2, 2018 by Simon Pearson

I'm trying to get a SD-Card working with FATFS on a NUCLEO-L476RG. Code was generated with recent STM32CubeMX 4.21.0 and Firmware Package 1.8.0 for L4. SD-access in polling mode, no DMA.

 

My application was crashing (Default_Handler, Infinite_Loop) while writing to the card. The crash was happening in stm32l4xx_hal_sd.c in HAL_SD_WriteBlocks(), here:

    /* Write block(s) in polling mode */
    while(!__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXUNDERR | SDMMC_FLAG_DCRCFAIL | SDMMC_FLAG_DTIMEOUT | SDMMC_FLAG_DATAEND))
    {
      if(__HAL_SD_GET_FLAG(hsd, SDMMC_FLAG_TXFIFOHE))
      {
        /* Write data to SDMMC Tx FIFO */
        for(count = 0U; count < 8U; count++)
        {
          SDMMC_WriteFIFO(hsd->Instance, (tempbuff + count));
        }
        tempbuff += 8U;
      }
     
      [...]
    }

After a crash, (tempbuff + count) has the value 0x20018000 (see attachment). This seems to be a invalid address which is not in RAM, access causes the system fault.

 

As far as I understand the problem, if the DATAEND flag has not been set yet but the buffer was completely written to the SDMMC fifo, tempbuff will get incremented further out of the bounds of the buffer. If the buffer is located at the end of the memory, a system fault occurs when trying to read. Accessing parts of the memory beyond the buffer should never happen in general but if the memory following the buffer is readable, this will probably not be noticed.

 

My fix is to stop incrementing tempbuff when the buffersize is reached, replace

tempbuff += 8U;

with

if( (tempbuff - (uint32_t *)pData) < (NumberOfBlocks * BLOCKSIZE / sizeof(uint32_t)) ) tempbuff += 8U;

This seems to work, but I'm not sure if this is best solution without any side effects. At first glance it seems to work but I haven't done detailed tests yet.

 

Can anyone confirm this problem? Is my assumption right that this is a bug in the HAL driver?

Attachments

Outcomes