Last active
June 20, 2023 13:56
-
-
Save pcotret/11f36e51851cdf1d3c854936a10f7c89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
// Function to enable PMP and set permissions for region 0 | |
void enable_pmp(uintptr_t start, uintptr_t end, uint8_t permissions) { | |
uint8_t pmpcfg = (permissions << 3) | 0x01; | |
uintptr_t pmpaddr = ((start >> 2) << 2) | 0x08; | |
// Calculate the PMP address mask | |
uintptr_t pmpmask = ((end - start) >> 2) - 1; | |
// Write the configuration and address values to PMP registers | |
asm volatile ("csrw pmpcfg0, %0" : : "r" (pmpcfg)); | |
asm volatile ("csrw pmpaddr0, %0" : : "r" (pmpaddr | pmpmask)); | |
} | |
int main() { | |
// Enable PMP for region 0 with start and end addresses | |
enable_pmp(0x1000, 0x2000, 0x03); // Permission: Read-Write (0x03) | |
// Access a memory location within the protected region (success case) | |
uint32_t *ptr = (uint32_t *)0x1500; | |
*ptr = 0xDEADBEEF; | |
printf("Success: Accessed protected memory region. Value: 0x%x\n", *ptr); | |
// Access a memory location outside the protected region (failure case) | |
uint32_t *ptr2 = (uint32_t *)0x3000; | |
*ptr2 = 0x12345678; | |
printf("Failure: Accessed unprotected memory region. Value: 0x%x\n", *ptr2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment