mprotect_example_exclusive_region.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 thread1_private_data[MPU_MIN_REGION_SIZE];
  16. static void thread1_entry(void *parameter)
  17. {
  18. (void)parameter;
  19. /* Thread 1 configures thread1_private_data for exclusive access */
  20. rt_kprintf("Thread 1 configures private data\n");
  21. rt_mprotect_add_exclusive_region((void *)thread1_private_data, MPU_MIN_REGION_SIZE);
  22. rt_kprintf("Thread 1 private data address: %p - %p\n", &thread1_private_data[0], &thread1_private_data[MPU_MIN_REGION_SIZE]);
  23. rt_kprintf("Thread 1 reads and writes to its private data\n");
  24. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  25. {
  26. /* Thread 1 has access to its private data */
  27. thread1_private_data[i] = i;
  28. rt_kprintf("thread1_private_data[%d] = %d\n", i, thread1_private_data[i]);
  29. }
  30. }
  31. static void thread2_entry(void *parameter)
  32. {
  33. (void)parameter;
  34. rt_kprintf("Thread 2 writes to thread 1's private data\n");
  35. for (int i = 0; i < MPU_MIN_REGION_SIZE; i++)
  36. {
  37. /*
  38. * Thread 2 does not have access to thread 1's private data.
  39. * Access generates an exception.
  40. */
  41. thread1_private_data[i] = i;
  42. }
  43. }
  44. int mprotect_example_exclusive_region()
  45. {
  46. extern void mprotect_example_exception_hook(rt_mem_exception_info_t *info);
  47. rt_hw_mpu_exception_set_hook(mprotect_example_exception_hook);
  48. rt_thread_t tid1 = RT_NULL;
  49. tid1 = rt_thread_create("thread1",
  50. thread1_entry, RT_NULL,
  51. THREAD_STACK_SIZE,
  52. THREAD_PRIORITY - 1,
  53. THREAD_TIMESLICE);
  54. if (tid1 != RT_NULL)
  55. rt_thread_startup(tid1);
  56. rt_thread_t tid2 = RT_NULL;
  57. tid2 = rt_thread_create("thread2",
  58. thread2_entry, RT_NULL,
  59. THREAD_STACK_SIZE,
  60. THREAD_PRIORITY,
  61. THREAD_TIMESLICE);
  62. if (tid2 != RT_NULL)
  63. rt_thread_startup(tid2);
  64. return 0;
  65. }
  66. MSH_CMD_EXPORT(mprotect_example_exclusive_region, Memory protection example (exclusive_region));