• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  *  07/2001 Ported by Wayne Boyer
5  * Copyright (c) 2023 SUSE LLC Avinesh Kumar <avinesh.kumar@suse.com>
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Verify that, mmap() call fails with errno:
12  *
13  * - EACCES, when a file mapping is requested but the file descriptor is not open for reading.
14  * - EINVAL, when length argument is 0.
15  * - EINVAL, when flags contains none of MAP_PRIVATE, MAP_SHARED, or MAP_SHARED_VALIDATE.
16  */
17 
18 #include <stdlib.h>
19 #include "tst_test.h"
20 
21 #define MMAPSIZE 1024
22 #define TEMPFILE "mmapfile"
23 static size_t page_sz;
24 static int fd;
25 
26 static struct tcase {
27 	size_t length;
28 	int prot;
29 	int flags;
30 	int exp_errno;
31 } tcases[] = {
32 	{MMAPSIZE, PROT_WRITE, MAP_FILE | MAP_PRIVATE, EACCES},
33 	{MMAPSIZE, PROT_WRITE, MAP_FILE | MAP_SHARED, EACCES},
34 	{MMAPSIZE, PROT_READ, MAP_FILE | MAP_PRIVATE, EACCES},
35 	{MMAPSIZE, PROT_READ, MAP_FILE | MAP_SHARED, EACCES},
36 	{MMAPSIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, EACCES},
37 	{MMAPSIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, EACCES},
38 	{0, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, EINVAL},
39 	{MMAPSIZE, PROT_READ | PROT_WRITE, MAP_FILE, EINVAL}
40 };
41 
setup(void)42 static void setup(void)
43 {
44 	char *buf;
45 
46 	page_sz = getpagesize();
47 	buf = SAFE_MALLOC(page_sz);
48 	memset(buf, 'A', page_sz);
49 
50 	fd = SAFE_OPEN(TEMPFILE, O_WRONLY | O_CREAT, 0666);
51 	SAFE_WRITE(SAFE_WRITE_ALL, fd, buf, page_sz);
52 	free(buf);
53 }
54 
run(unsigned int i)55 static void run(unsigned int i)
56 {
57 	struct tcase *tc = &tcases[i];
58 
59 	TESTPTR(mmap(NULL, tc->length, tc->prot, tc->flags, fd, 0));
60 
61 	if (TST_RET_PTR != MAP_FAILED) {
62 		tst_res(TFAIL, "mmap() was successful unexpectedly");
63 		SAFE_MUNMAP(TST_RET_PTR, MMAPSIZE);
64 	} else if (TST_ERR == tc->exp_errno) {
65 		tst_res(TPASS | TERRNO, "mmap() failed with");
66 	} else {
67 		tst_res(TFAIL | TERRNO, "mmap() failed unexpectedly");
68 	}
69 }
70 
cleanup(void)71 static void cleanup(void)
72 {
73 	if (fd > 0)
74 		SAFE_CLOSE(fd);
75 }
76 
77 static struct tst_test test = {
78 	.setup = setup,
79 	.cleanup = cleanup,
80 	.test = run,
81 	.tcnt = ARRAY_SIZE(tcases),
82 	.needs_tmpdir = 1
83 };
84