1
0

mprotect_example_ro_data.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-09-25 tangzz98 the first version
  9. */
  10. #include <rtthread.h>
  11. #include <mprotect.h>
  12. #define THREAD_PRIORITY 25
  13. #define THREAD_STACK_SIZE 512
  14. #define THREAD_TIMESLICE 5
  15. rt_align(MPU_MIN_REGION_SIZE) rt_uint8_t ro_data[MPU_MIN_REGION_SIZE];
  16. static void thread1_entry(void *parameter)
  17. {
  18. (void)parameter;
  19. rt_kprintf("ro_data address: %p - %p\n", &ro_data[0], &ro_data[MPU_MIN_REGION_SIZE]);
  20. /* Thread 1 can write ro_data before configuring memory protection. */
  21. rt_kprintf("Thread 1 writes to ro_data before configuring memory protection\n");
  22. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  23. {
  24. ro_data[i] = i;
  25. rt_kprintf("ro_data[%d] = %d\n", i, ro_data[i]);
  26. }
  27. rt_mem_region_t ro_region =
  28. {
  29. .start = (void *)ro_data,
  30. .size = MPU_MIN_REGION_SIZE,
  31. .attr = RT_MEM_REGION_P_RO_U_RO,
  32. };
  33. /* Thread 1 configures ro_data as read only. */
  34. rt_kprintf("Thread 1 configures ro_data for read-only access for thread 1\n");
  35. rt_mprotect_add_region(RT_NULL, &ro_region);
  36. rt_kprintf("Thread 1 reads ro_data\n");
  37. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  38. {
  39. rt_kprintf("ro_data[%d] = %d\n", i, ro_data[i]);
  40. }
  41. rt_thread_delay(RT_TICK_PER_SECOND * 1);
  42. /* Thread 1 cannot write ro_data. */
  43. rt_kprintf("Thread 1 writes to ro_data\n");
  44. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  45. {
  46. ro_data[i] = i;
  47. }
  48. }
  49. static void thread2_entry(void *parameter)
  50. {
  51. (void)parameter;
  52. rt_kprintf("Thread 2 writes to ro_data\n");
  53. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  54. {
  55. /* Thread 2 can write ro_data. */
  56. ro_data[i] = i;
  57. rt_kprintf("ro_data[%d] = %d\n", i, ro_data[i]);
  58. }
  59. }
  60. int mprotect_example_ro_data()
  61. {
  62. extern void mprotect_example_exception_hook(rt_mem_exception_info_t *info);
  63. rt_hw_mpu_exception_set_hook(mprotect_example_exception_hook);
  64. rt_thread_t tid1 = RT_NULL;
  65. tid1 = rt_thread_create("thread1",
  66. thread1_entry, RT_NULL,
  67. THREAD_STACK_SIZE,
  68. THREAD_PRIORITY - 1,
  69. THREAD_TIMESLICE);
  70. rt_thread_startup(tid1);
  71. rt_thread_t tid2 = RT_NULL;
  72. tid2 = rt_thread_create("thread2",
  73. thread2_entry, RT_NULL,
  74. THREAD_STACK_SIZE,
  75. THREAD_PRIORITY,
  76. THREAD_TIMESLICE);
  77. rt_thread_startup(tid2);
  78. return 0;
  79. }
  80. MSH_CMD_EXPORT(mprotect_example_ro_data, Memory protection example (read-only data));