hugeshmget05.c revision a5489f1bc843b7bda74fca10fad2f8714b5fb090
1/*
2 * Copyright (c) International Business Machines  Corp., 2004
3 * Copyright (c) Linux Test Project, 2004-2017
4 *
5 * This program is free software;  you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY;  without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
13 * the GNU General Public License for more details.
14 */
15
16/*
17 * DESCRIPTION
18 *	hugeshmget05 - test for EACCES error
19 *
20 * HISTORY
21 *	03/2001 - Written by Wayne Boyer
22 *	04/2004 - Updated by Robbie Williamson
23 */
24
25#include <sys/types.h>
26#include <sys/wait.h>
27#include <limits.h>
28#include "hugetlb.h"
29#include "hugetlb.h"
30
31static size_t shm_size;
32static int shm_id_1 = -1;
33static uid_t ltp_uid;
34static char *ltp_user = "nobody";
35
36static long hugepages = 128;
37static struct tst_option options[] = {
38	{"s:", &nr_opt, "-s   num  Set the number of the been allocated hugepages"},
39	{NULL, NULL, NULL}
40};
41
42static void do_child(void);
43
44static void test_hugeshmget(void)
45{
46	pid_t pid;
47	int status;
48
49	switch (pid = fork()) {
50	case -1:
51		tst_brk(TBROK | TERRNO, "fork");
52	case 0:
53		/* set the user ID of the child to the non root user */
54		SAFE_SETUID(ltp_uid);
55		do_child();
56		exit(0);
57	default:
58		/* wait for the child to return */
59		SAFE_WAITPID(pid, &status, 0);
60	}
61}
62
63static void do_child(void)
64{
65	TEST(shmget(shmkey, shm_size, SHM_HUGETLB | SHM_RW));
66	if (TEST_RETURN != -1) {
67		tst_res(TFAIL, "shmget succeeded unexpectedly");
68		return;
69	}
70	if (TEST_ERRNO == EACCES)
71		tst_res(TPASS | TTERRNO, "shmget failed as expected");
72	else
73		tst_res(TFAIL | TTERRNO, "shmget failed unexpectedly "
74				"- expect errno=EACCES, got");
75}
76
77void setup(void)
78{
79	long hpage_size;
80
81	save_nr_hugepages();
82	if (nr_opt)
83		hugepages = SAFE_STRTOL(nr_opt, 0, LONG_MAX);
84
85	set_sys_tune("nr_hugepages", hugepages, 1);
86	hpage_size = SAFE_READ_MEMINFO("Hugepagesize:") * 1024;
87
88	shm_size = hpage_size * hugepages / 2;
89	update_shm_size(&shm_size);
90	shmkey = getipckey();
91	shm_id_1 = shmget(shmkey, shm_size,
92			  SHM_HUGETLB | SHM_RW | IPC_CREAT | IPC_EXCL);
93	if (shm_id_1 == -1)
94		tst_brk(TBROK | TERRNO, "shmget #setup");
95
96	/* get the userid for a non-root user */
97	ltp_uid = getuserid(ltp_user);
98}
99
100void cleanup(void)
101{
102	rm_shm(shm_id_1);
103	restore_nr_hugepages();
104}
105
106static struct tst_test test = {
107	.needs_root = 1,
108	.options = options,
109	.setup = setup,
110	.cleanup = cleanup,
111	.test_all = test_hugeshmget,
112};
113