• 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 
42 static struct tst_option options[] = {
43 	{"s:", &nr_opt, "-s num   Set the number of the been allocated hugepages"},
44 	{NULL, NULL, NULL}
45 };
46 
verify_hugeshmat(void)47 static void verify_hugeshmat(void)
48 {
49 	int status;
50 	pid_t pid;
51 
52 	switch (pid = SAFE_FORK()) {
53 	case 0:
54 		SAFE_SETUID(ltp_uid);
55 
56 		addr = shmat(shm_id_1, NULL, 0);
57 		if (addr != (void *)-1) {
58 			tst_res(TFAIL, "shmat succeeded unexpectedly");
59 			return;
60 		}
61 		if (errno == EACCES) {
62 			tst_res(TPASS | TERRNO, "shmat failed as expected");
63 		} else {
64 			tst_res(TFAIL | TERRNO, "shmat failed unexpectedly "
65 					"- expect errno=EACCES, got");
66 		}
67 		break;
68 	default:
69 		SAFE_WAITPID(pid, &status, 0);
70 	}
71 }
72 
setup(void)73 static void setup(void)
74 {
75 	long hpage_size;
76 
77 	if (tst_hugepages == 0)
78 		tst_brk(TCONF, "No enough hugepages for testing.");
79 
80 	hpage_size = SAFE_READ_MEMINFO("Hugepagesize:") * 1024;
81 
82 	shm_size = hpage_size * tst_hugepages / 2;
83 	update_shm_size(&shm_size);
84 	shmkey = getipckey();
85 	shm_id_1 = shmget(shmkey, shm_size,
86 			  SHM_HUGETLB | SHM_RW | IPC_CREAT | IPC_EXCL);
87 	if (shm_id_1 == -1)
88 		tst_brk(TBROK | TERRNO, "shmget");
89 
90 	ltp_uid = getuserid(ltp_user);
91 }
92 
cleanup(void)93 static void cleanup(void)
94 {
95 	rm_shm(shm_id_1);
96 }
97 
98 static struct tst_test test = {
99 	.needs_root = 1,
100 	.forks_child = 1,
101 	.needs_tmpdir = 1,
102 	.options = options,
103 	.test_all = verify_hugeshmat,
104 	.setup = setup,
105 	.cleanup = cleanup,
106 	.request_hugepages = 128,
107 };
108