How does STM32 demo USB-DFU boot loader check if user code is loaded?

480 Views Asked by At

STM32 HAL demo USB-DFU boot loader contains this code:

/* Test if user code is programmed starting from address 0x0800C000 */
if (((*(__IO uint32_t *) USBD_DFU_APP_DEFAULT_ADD) & 0x2FFC0000) == 0x20000000)
{
  /* Jump to user application */
  JumpAddress = *(__IO uint32_t *) (USBD_DFU_APP_DEFAULT_ADD + 4);
  JumpToApplication = (pFunction) JumpAddress;

  /* Initialize user application's Stack Pointer */
  __set_MSP(*(__IO uint32_t *) USBD_DFU_APP_DEFAULT_ADD);
  JumpToApplication();
}

How does this predicate ((*(__IO uint32_t *) USBD_DFU_APP_DEFAULT_ADD) & 0x2FFC0000) == 0x20000000 determine whether or not user code is loaded on STM32H7A3 MPU?
What is this magic 0x2FFC0000 mask?

2

There are 2 best solutions below

2
On

It is very simple and a very bad way. It simply checks if at USBD_DFU_APP_DEFAULT_ADD address (where initial stack pointer value should be) the value AND-et with mask is equal to some value.

I personally always add the CRC32 at the end of the app to check if the app is there and if the app is valid.

... determine whether or not user code is loaded on STM32H7A3 MPU?

It does not have anything in common with MPU

0
On

This sample code distributed with CubeMX STM32Cube_FW_H7_V1.9.0 package initially verifies if the app start address (stack top) lies in RAM address space - between 0x20000000 and 0x2003FFFF (256k).
For STM32H7A3ZI MPU (e.g. Nucleo-H7A3ZI-Q) this is incorrect because "regular" RAM (not DTCRAM) starts at address 0x24000000 and is 1024k large. It seems that the correct check for this MPU should be: if((stackAddr & 0x24E00000) == 0x24000000) ...
Although I do not quite understand why for this MPU default stack address configured by CubeMX is 0x24100000 which is top RAM address + 1.