【STM32】 Memory Protection Unit,HAL庫MPU

內存保護單元 Memory Protection Unit(MPU),

找一個HAL庫包,例如我是G4系列開發板:在STM32Cube_FW_G4_V1.2.0\Projects\NUCLEO-G474RE\Examples\Cortex下打開一個工程測試。

stm32xx_hal_cortex.h文件中 。

void MPU_AccessPermConfig(void)
{
  MPU_Region_InitTypeDef MPU_InitStruct;

  /* Configure region for PrivilegedReadOnlyArray as REGION N°3, 32byte and R
     only in privileged mode */
  /* Disable MPU */

 //有省略。。。。

  /* Enable MPU (any access not covered by any enabled region will cause a fault) */
  HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);

  /* Read from PrivilegedReadOnlyArray. This will not generate error */
  (void)PrivilegedReadOnlyArray[0];

  /* Uncomment the following line to write to PrivilegedReadOnlyArray. This will
     generate error */
   //PrivilegedReadOnlyArray[0] = 'e'; 
}

配置區域僅允許讀,不允許寫。取消  //PrivilegedReadOnlyArray[0] = 'e'; 註釋將會出錯

#define  MPU_REGION_NUMBER0          ((uint8_t)0x00)
#define  MPU_REGION_NUMBER1          ((uint8_t)0x01)
#define  MPU_REGION_NUMBER2          ((uint8_t)0x02)
#define  MPU_REGION_NUMBER3          ((uint8_t)0x03)
#define  MPU_REGION_NUMBER4          ((uint8_t)0x04)
#define  MPU_REGION_NUMBER5          ((uint8_t)0x05)
#define  MPU_REGION_NUMBER6          ((uint8_t)0x06)
#define  MPU_REGION_NUMBER7          ((uint8_t)0x07)

以上定義: 獨立存儲區域配置如下。 

 

 MPU區域大小配置:更多可以參考源碼和programming manual程序設計手冊PM0253

/** @defgroup CORTEX_MPU_Region_Size CORTEX MPU Region Size
  * @{
  */
#define   MPU_REGION_SIZE_32B        ((uint8_t)0x04)
#define   MPU_REGION_SIZE_64B        ((uint8_t)0x05)
#define   MPU_REGION_SIZE_128B       ((uint8_t)0x06)
#define   MPU_REGION_SIZE_256B       ((uint8_t)0x07)
/* Configure Peripheral region as REGION N°2, 512MB of size, R/W and Execute
  Never region */
  MPU_InitStruct.BaseAddress = EXAMPLE_PERIPH_ADDRESS_START;
  MPU_InitStruct.Size = EXAMPLE_PERIPH_SIZE;
  MPU_InitStruct.Number = EXAMPLE_PERIPH_REGION_NUMBER;
  MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;

MPU作用:

阻止用戶應用程序破壞操作系統使用的數據。

阻止一個任務訪問其它任務的數據區,從而把任務隔開。(類似臨界區)

臨界區參考【FreeRTOS】FreeRTOS結構

可以把關鍵數據區設置爲只讀,從根本上消除了被破壞的可能。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章