@@ -408,6 +408,82 @@ void test_k_mem_map_exhaustion(void)
408408#endif /* !CONFIG_DEMAND_PAGING */
409409}
410410
411+ #ifdef CONFIG_USERSPACE
412+ #define USER_STACKSIZE (128)
413+
414+ struct k_thread user_thread ;
415+ K_THREAD_STACK_DEFINE (user_stack , USER_STACKSIZE );
416+
417+ K_APPMEM_PARTITION_DEFINE (default_part );
418+ K_APP_DMEM (default_part ) uint8_t * mapped ;
419+
420+ static void user_function (void * p1 , void * p2 , void * p3 )
421+ {
422+ mapped [0 ] = 42 ;
423+ }
424+ #endif /* CONFIG_USERSPACE */
425+
426+ /**
427+ * Test that the allocated region will be only accessible to userspace when
428+ * K_MEM_PERM_USER is used.
429+ */
430+ void test_k_mem_map_user (void )
431+ {
432+ #ifdef CONFIG_USERSPACE
433+ int ret ;
434+
435+ ret = k_mem_domain_add_partition (& k_mem_domain_default , & default_part );
436+ if (ret != 0 ) {
437+ printk ("Failed to add default memory partition (%d)\n" , ret );
438+ k_oops ();
439+ }
440+
441+ /*
442+ * Map the region using K_MEM_PERM_USER and try to access it from
443+ * userspace
444+ */
445+ expect_fault = false;
446+
447+ z_phys_map (& mapped , z_mem_phys_addr (test_page ), sizeof (test_page ),
448+ BASE_FLAGS | K_MEM_PERM_RW | K_MEM_PERM_USER );
449+
450+ printk ("mapped a page: %p - %p (with K_MEM_PERM_USER)\n" , mapped ,
451+ mapped + CONFIG_MMU_PAGE_SIZE );
452+ printk ("trying to access %p from userspace\n" , mapped );
453+
454+ k_thread_create (& user_thread , user_stack , USER_STACKSIZE ,
455+ user_function , NULL , NULL , NULL ,
456+ -1 , K_USER , K_NO_WAIT );
457+ k_thread_join (& user_thread , K_FOREVER );
458+
459+ /* Unmap the memory */
460+ z_phys_unmap (mapped , sizeof (test_page ));
461+
462+ /*
463+ * Map the region without using K_MEM_PERM_USER and try to access it
464+ * from userspace. This should fault and fail.
465+ */
466+ expect_fault = true;
467+
468+ z_phys_map (& mapped , z_mem_phys_addr (test_page ), sizeof (test_page ),
469+ BASE_FLAGS | K_MEM_PERM_RW );
470+
471+ printk ("mapped a page: %p - %p (without K_MEM_PERM_USER)\n" , mapped ,
472+ mapped + CONFIG_MMU_PAGE_SIZE );
473+ printk ("trying to access %p from userspace\n" , mapped );
474+
475+ k_thread_create (& user_thread , user_stack , USER_STACKSIZE ,
476+ user_function , NULL , NULL , NULL ,
477+ -1 , K_USER , K_NO_WAIT );
478+ k_thread_join (& user_thread , K_FOREVER );
479+
480+ printk ("shouldn't get here\n" );
481+ ztest_test_fail ();
482+ #else
483+ ztest_test_skip ();
484+ #endif /* CONFIG_USERSPACE */
485+ }
486+
411487/* ztest main entry*/
412488void test_main (void )
413489{
@@ -425,7 +501,8 @@ void test_main(void)
425501 ztest_unit_test (test_k_mem_map_unmap ),
426502 ztest_unit_test (test_k_mem_map_guard_before ),
427503 ztest_unit_test (test_k_mem_map_guard_after ),
428- ztest_unit_test (test_k_mem_map_exhaustion )
504+ ztest_unit_test (test_k_mem_map_exhaustion ),
505+ ztest_unit_test (test_k_mem_map_user )
429506 );
430507 ztest_run_test_suite (test_mem_map );
431508}
0 commit comments