• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2004
4  * Copyright (c) Linux Test Project, 2004-2017
5  *
6  * DESCRIPTION
7  *	hugeshmat03 - test for EACCES error
8  *
9  * ALGORITHM
10  *	create a shared memory segment with root only read & write permissions
11  *	fork a child process
12  *	if child
13  *	  set the ID of the child process to that of "nobody"
14  *	  loop if that option was specified
15  *	    call shmat() using the TEST() macro
16  *	    check the errno value
17  *	      issue a PASS message if we get EACCES
18  *	    otherwise, the tests fails
19  *	      issue a FAIL message
20  *	  call cleanup
21  *	if parent
22  *	  wait for child to exit
23  *	  remove the shared memory segment
24  *
25  * HISTORY
26  *	03/2001 - Written by Wayne Boyer
27  *	04/2004 - Updated by Robbie Williamson
28  *
29  * RESTRICTIONS
30  *	test must be run at root
31  */
32 
33 #include <limits.h>
34 #include "hugetlb.h"
35 
36 static size_t shm_size;
37 static int shm_id_1 = -1;
38 static void *addr;
39 static uid_t ltp_uid;
40 static char *ltp_user = "nobody";
41 
verify_hugeshmat(void)42 static void verify_hugeshmat(void)
43 {
44 	int status;
45 	pid_t pid;
46 
47 	switch (pid = SAFE_FORK()) {
48 	case 0:
49 		SAFE_SETUID(ltp_uid);
50 
51 		addr = shmat(shm_id_1, NULL, 0);
52 		if (addr != (void *)-1) {
53 			tst_res(TFAIL, "shmat succeeded unexpectedly");
54 			return;
55 		}
56 		if (errno == EACCES) {
57 			tst_res(TPASS | TERRNO, "shmat failed as expected");
58 		} else {
59 			tst_res(TFAIL | TERRNO, "shmat failed unexpectedly "
60 					"- expect errno=EACCES, got");
61 		}
62 		break;
63 	default:
64 		SAFE_WAITPID(pid, &status, 0);
65 	}
66 }
67 
setup(void)68 static void setup(void)
69 {
70 	long hpage_size;
71 
72 	if (tst_hugepages == 0)
73 		tst_brk(TCONF, "No enough hugepages for testing.");
74 
75 	hpage_size = SAFE_READ_MEMINFO("Hugepagesize:") * 1024;
76 
77 	shm_size = hpage_size * tst_hugepages / 2;
78 	update_shm_size(&shm_size);
79 	shmkey = getipckey();
80 	shm_id_1 = shmget(shmkey, shm_size,
81 			  SHM_HUGETLB | SHM_RW | IPC_CREAT | IPC_EXCL);
82 	if (shm_id_1 == -1)
83 		tst_brk(TBROK | TERRNO, "shmget");
84 
85 	ltp_uid = getuserid(ltp_user);
86 }
87 
cleanup(void)88 static void cleanup(void)
89 {
90 	rm_shm(shm_id_1);
91 }
92 
93 static struct tst_test test = {
94 	.needs_root = 1,
95 	.forks_child = 1,
96 	.needs_tmpdir = 1,
97 	.options = (struct tst_option[]) {
98 		{"s:", &nr_opt, "Set the number of the been allocated hugepages"},
99 		{}
100 	},
101 	.test_all = verify_hugeshmat,
102 	.setup = setup,
103 	.cleanup = cleanup,
104 	.hugepages = {128, TST_REQUEST},
105 };
106